/* --------------------------------------------------------------
	GLOBAL VARIABLES
-------------------------------------------------------------- */
var dropTimer = null;

/* --------------------------------------------------------------
	GLOBAL EVENT REGISTRATION
-------------------------------------------------------------- */


/* --------------------------------------------------------------
	PRELOAD TABS
-------------------------------------------------------------- */


//chain more than one function to the onload/onunload handler
function chainOnload(f) {
	var prev = window.onload;
	window.onload = function() {
		if (prev) {
			prev();
		}
		f();
	}
}

function chainOnunload(f) {
	var prev = window.onunload;
	window.onunload = function() {
		if (prev) {
			prev();
		}
		f();
	}
}

/* --------------------------------------------------------------
	GLOBAL VARIABLES
-------------------------------------------------------------- */
var dropTimer = null;

/* --------------------------------------------------------------
	GLOBAL EVENT REGISTRATION
-------------------------------------------------------------- */


/* --------------------------------------------------------------
	PRELOAD TABS
-------------------------------------------------------------- */


function imageUrl(){
var iUrlStr = imagesHostUrl + imagesSerial +'/i/';
return iUrlStr;
}

/* --------------------------------------------------------------
	Generic image swapping function
	img_id - the id attribute of the image to be swapped
	img_src - the path to the new image to be swapped in
-------------------------------------------------------------- */
function swap(imgId, imgSrc) {
	var imgObj = document.getElementById(imgId);
	imgObj.src = imgSrc;
}


/* --------------------------------------------------------------
	Character counting for textareas which cannot take maxlength
-------------------------------------------------------------- */
function countChars(fieldname,limit) {
	var num = fieldname.value.length;
	if (num > limit) {
		alert('很抱歉,在这里您最多只能输入'+limit+'个字符。');
		fieldname.value = fieldname.value.substring(0, limit-1);
	} else {
		//be idle
	}
	return;
}

/* --------------------------------------------------------------
	Sets the browser's location
-------------------------------------------------------------- */
function set_location(url)
{
	document.location.href = url;
}

/* --------------------------------------------------------------
	Functions for the location drop down
	moveDropper() - positions the dropper beneath the text field
		with which it is currently associated
	showDropper() - turns the rendering on the dropper on
		buttonTarget - the div containing the button image
		textTarget - the text box to fill with an address
	hideDropper() - turns the rendering of the dropper off
	dropperFill() - fills the text box from the global var
		dropTxtBox with the string str
-------------------------------------------------------------- */

function loadPrototype(){
	if (typeof Prototype=='undefined') {			
			var script = document.createElement('script');
			script.src = '../'+imagesSerial+'/js/st_lib/prototype.js';
			script.type = 'text/javascript';			
			var head = document.getElementsByTagName('head').item(0);
			head.appendChild(script);
	}
}

var locationPicker = {

dropper_contents:null,
xmlHttpReq : Ajax.getTransport(),

//城市列表
fillDropper:function(aLink){

	if(this.xmlHttpReq){
		
			var myAjax = new Ajax.Request(
			'/home/citylist.html?nocache=' + (new Date()).getTime(), 
			{
				method: 'get',
				onComplete: function(req){
					locationPicker.dropper_contents = JSON.parse(req.responseText);
					if(locationPicker.dropper_contents.success){
						locationPicker.showDropper();
					}else{
						alert('获取城市列表失败.');
					}
				},
				onFailure:function(){
					alert('错误的列表.');
				}
			});
		
	}
	//else{window.location.href=aLink.href;}
},
attachEvents:function(){
	Event.observe($('dropper'),'mouseout',setDropperTimer);
	Event.observe($('dropper'),'mouseover',clearDropperTimer);
	
	var thePs = document.getElementsByTagName('td');	
	for(var i=0;i<thePs.length;i++){
		if(thePs[i].mouse=='dropper'){
			Event.observe(thePs[i],"mouseover",function(evt){
				var target = Event.element(evt);
				target.style.backgroundColor = '#FFFED7';
				target.style["color"] = 'red';
				target.style["cursor"] = "hand";
			});
			Event.observe(thePs[i],"mouseout",function(evt){
				var target = Event.element(evt);
				target.style.backgroundColor = '#FFFFFF';
				target.style["color"] = '#6365CE';
				target.style["cursor"] = "default";
			});		
			if(thePs[i].parentNode.id!='dropperFooter'){
				Event.observe(thePs[i],"click",function(evt){
					var target = Event.element(evt);
					//locationPicker.setLocation(target.lastChild.nodeValue + "站");
					locationPicker.setLocation("正在切换中...");
					locationPicker.hideDropper();
				});	
			}
		}
		
	}
},
hideDropper:function(){
	if($('dropper')){
		document.body.removeChild($('dropper'));
		this.clickTrg.src=imageUrl()+'new/gfx/dropper_down.gif';
	}
},
showDropper:function(){
	this.dropper = document.createElement('div');
	this.dropper.id = 'dropper';
	var html = "";
	if(locationPicker.dropper_contents.citylist){
		var dl = document.createElement('div');
	
		
		//dl.innerHTML = '<h4 class="dropperHeader">选择城市</h4>';
		html = '<table border=0 width=100%><tr>';
		var i = 0;
		for(;i<locationPicker.dropper_contents.citylist.length;i++){
			if(i !=0 && i % 6 == 0) html += "</tr><tr>"
			html+='<td width=\"100px\" mouse=\"dropper\" style="color:#6365CE" onclick=\"location.href=\'/home/location.html?city='+locationPicker.dropper_contents.citylist[i].id+'\'\">'+locationPicker.dropper_contents.citylist[i].name+'</td>';
		}
		
		for(var j=0; i > 0 && j < (6 - i % 6); j++)
		{
			html+='<td>&nbsp;</td>'
		}
		html += '</tr></table>';
		
		dl.innerHTML = html;
		this.dropper.appendChild(dl);
	}

	
	this.dropper.style.top = (this.coords[1]+22)+'px';
	this.dropper.style.left = (this.coords[0]-83)+'px';
	document.body.appendChild(this.dropper);	
	this.attachEvents();
	
},
setLocation:function(lStr){
	switch(this.clickTrg.id){
		case 'dropperBtn_Mast':
			document.header_find_form.find_loc.value=lStr;
			break;
		case 'dropperBtn_Talk':
			document.talk_form.message_board_loc.value=lStr;
			break;
		case 'dropperBtn_Review':
			document.search_form.search_loc.value=lStr;
			break;
		case 'dropperBtn_SB':
			document.search_form.search_loc.value=lStr;
			break;
		case 'dropperBtn_ABS':
			document.new_talk_topic.location.value=lStr;
			break;
		default:
			document.header_find_form.find_loc.value=lStr;
	}
},
initDropper:function(aLink){
	this.clickTrg = aLink;
	
	
	
	this.coords = findPosition(aLink);
	if(this.clickTrg.id=="dropperBtn_Talk"){
		this.coords[1] = this.coords[1]+13;
	}
	if (!this.dropper_contents){
		this.fillDropper(aLink);
		aLink.src=imageUrl()+'new/gfx/dropper_up_on.gif';
		
		//alert(imageUrl()+'new/gfx/dropper_up_on.gif');
		//document.write (imageUrl()+'new/gfx/dropper_up_on.gif');
	}else if($('dropper')){
		document.body.removeChild($('dropper'));
		aLink.src=imageUrl()+'new/gfx/dropper_down_on.gif';
	}else{
		this.showDropper();
		aLink.src=imageUrl()+'new/gfx/dropper_up_on.gif';
	}
	
	//
	
}
}


function swapDropperIn(btn) {	
	
	var btnStr = btn.src;
	
	if (btnStr.indexOf('dropper_down.gif') > 0) {
		btn.src=imageUrl()+'new/gfx/dropper_down_on.gif';
	} else if (btnStr.indexOf('dropper_up.gif') > 0) {
		btn.src=imageUrl()+'new/gfx/dropper_up_on.gif';
	}
}

function swapDropperOut(btn) {	
	var btnStr = btn.src;
	if (btnStr.indexOf('dropper_down_on.gif') > 0) {
        btn.src=imageUrl()+'new/gfx/dropper_down.gif';
	} else if (btnStr.indexOf('dropper_up_on.gif') > 0) {
        btn.src=imageUrl()+'new/gfx/dropper_up.gif';
	}
}

function setDropperTimer() {
	
		dropTimer = setTimeout("locationPicker.hideDropper()", 1500);
}

function clearDropperTimer() {
	clearTimeout(dropTimer);
	dropTimer = null;
}

/////////////////////////////////////////////////////////
// Functions to find various cross-browser properties //
////////////////////////////////////////////////////////

// Find element x,y location
function findPosition( oLink ) {
  var posX = null;
  var posY = null;
  if( oLink.offsetParent ) {
    for( posX = 0, posY = 0; oLink.offsetParent; oLink = oLink.offsetParent ) {
      posX += oLink.offsetLeft;
      posY += oLink.offsetTop;
    }
    return [ posX, posY ];
  } else {
    posX = oLink.x;
	posY = oLink.y;
	return [ posX, posY ];
  }
}

// Attach events to objects (remains for backwards compatability)
function addEvent(obj, evType, fn){
	try{
		Event.observe(obj,evType,fn);
		return true;
	}catch (e){
		return false;
	}
}

// Cross-browser event target finder
function findEventTarget(evt){
	var e=evt?evt:window.event?window.event:null; 
	var target=e.target?e.target:e.srcElement?e.srcElement:null; 
	if(target.nodeType==3) target=target.parentNode;// handle Safari bug 
	return target;
}

// Find proper vertical scroll distance
function findScrollDist(){
	if(window.pageYOffset){
		var num = window.pageYOffset;
	}else if(document.documentElement && document.documentElement.scrollTop){
		var num = document.documentElement.scrollTop;
	}else{
		var num = document.body.scrollTop;
	}
	return num;
}
////////////////////////////////////////////////

//standards compliant window target script, 'cause target is depricated in 4.01 strict
function externalLinks(theAnchor,windowName) {
var theName = "";
if(windowName){
theName = windowName;
}else{
theName = "_blank";
}
theAnchor.target = theName; 
}

// print page launcher
function printSwitch(pageUrl){
var newWindow = window.open("","printerWindow","width=720,menubar=yes,toolbar=no,location=no,resizable=yes,scrollbars=yes,status=no");
pageUrl = pageUrl+'';
var re = new RegExp("=");

	if(pageUrl.match(re)){
		newWindow.location = pageUrl + '&printLayout=true';
	}else{
		newWindow.location = pageUrl + '?printLayout=true';
	}
}

// makes yer variables into a URL query string
function xmlhttpreq_encode_dict(dict){ 
	var result_string = "";
	var start = true;
	for (var i in dict){ 
		if (!start) {result_string += "&";}
		else start = false;
		result_string += encodeURIComponent(i) + "=" + encodeURIComponent(dict[i]);
	}
	return result_string; 
}

// make a happy little status box
function ajaxStatusMessage(mess,timeout){
	var d = document.createElement('div');
	d.setAttribute('id','ajaxStatusMessage');
	d.innerHTML = '<img src="'+imageUrl()+'new/gfx/stat_mess_lft.gif"><p>'+mess+'</p><img src="'+imageUrl()+'new/gfx/stat_mess_rt.gif">';
	document.body.appendChild(d);
		d.style.left = (posX) + "px";
		d.style.top = (posY - 45) + "px";
	if(timeout){
		window.setTimeout("document.body.removeChild(document.getElementById('ajaxStatusMessage'));",timeout);
	}
}

// make strings with quotes in them js-safe
function somewhatSanitize(xStr){
	var singleQutoRE = /'/g;
	var doubleQutoRE = /"/g;
	var tagRE = /<\/?[^>]+>/gi;
	xStr = xStr.replace(singleQutoRE,"&#39;");
	xStr = xStr.replace(doubleQutoRE,"&#34;");
	xStr = xStr.replace(tagRE,"");
	return xStr;
}


///////////////////////////////
// Review Feedback Handlers //
//////////////////////////////

var feedback_types = new Array('useful', 'funny', 'cool');

function set_element_html(element_id, text) {
	var element = document.getElementById(element_id);	
	element.innerHTML = text;
}

chainOnload(function(){
var preload = new Image();

for (var i = 0; i < feedback_types.length; i++) {
	var button_types = new Array('off', 'on', 'press');
	for (var j = 0; j < button_types.length; j++) {
		preload.src = imageUrl()+'new/btn/rate_' + feedback_types[i] + '_' + button_types[j] + '.gif';
	}
}
});

function ReviewFeedbackHandler(rid, previous_feedback, stats) {
	STATE_READY = 0;
	STATE_SUBMITTING = 1;
	STATE_ERROR = 2;

	this.rid = rid;

	this.state = STATE_READY;
	this.setting = previous_feedback;
	this.stats = stats;

	this.set_button_image = function(which, img) {
		i = document.getElementById('review_feedback_' + which + '_image.' + this.rid).src = imageUrl()+'new/btn/rate_' + which + '_' + img + '.gif';
	}	

	this.init = function(which) {
		for (var i = 0; i < feedback_types.length; i++) {
			if (this.setting[feedback_types[i]]) {
				this.set_button_image(feedback_types[i], 'press');
			} else {
				this.set_button_image(feedback_types[i], 'off');
			}
		}
	}
	
	function state_change_cb(handler) {
		return (function(req) {
			if (req.readyState == 4) {
				if ((req.status >= 200) && (req.status < 300)) {
					set_element_html('review_feedback_message.' + handler.rid, 'Saved. Thanks!');
					handler.state = STATE_READY;
				} else {
					set_element_html('review_feedback_message.' + handler.rid, 'Error, try again later');
					handler.state = STATE_ERROR;
				}
			}
		});
	}
	
	this.button_click = function(which) {
		if (this.state != STATE_READY) {
			return;
		}

		if (!this.setting[which]) {
			this.set_button_image(which, 'press');
			set_element_html('review_feedback_message.' + this.rid, '<span style="color:gray;">Saving...</span>');
			this.state = STATE_SUBMITTING;
			this.setting[which] = true;
			this.stats[which]++;
			set_element_html('review_feedback_stats.' + this.rid + '.' + which, '(' + this.stats[which] + ')');
			// append the nocache argument to prevent Safari (and other browsers?) from caching request			
			var opt = {
			 method: 'get',			 
			 onComplete:state_change_cb(this)
			};
			(new Ajax.Request('/review_feedback?rid=' + encodeURIComponent(this.rid) + '&amp;fb=' + encodeURIComponent(which) + '&amp;state=on&amp;nocache=' + (new Date()).getTime(), opt));
			
		} else {
			// withdraw feedback
			this.set_button_image(which, 'off');
			set_element_html('review_feedback_message.' + this.rid, '<span style="color:gray;">Saving...</span>');
			this.state = STATE_SUBMITTING;
			this.setting[which] = false;
			this.stats[which]--;
			set_element_html('review_feedback_stats.' + this.rid + '.' + which, this.stats[which] <= 0 ? '' : '(' + this.stats[which] + ')');
			// append the nocache argument to prevent Safari (and other browsers?) from caching request
			var opt = {
			 method: 'get',			 
			 onComplete:state_change_cb(this)
			};
			(new Ajax.Request('/review_feedback?rid=' + encodeURIComponent(this.rid) + '&amp;fb=' + encodeURIComponent(which) + '&amp;state=off&amp;nocache=' + (new Date()).getTime(), opt));
		}
	}

	this.mouseover = function(which) {
		if ((this.state == STATE_READY) && (!this.setting[which])) {
			this.set_button_image(which, 'on');
		}
	}

	this.mouseout = function(which) {
		if ((this.state == STATE_READY) && (!this.setting[which])) {
			this.set_button_image(which, 'off');
		}
	}
}

var review_feedback_handlers = new Array();	



/////////////////////////////////////////////////////////////////
// Fancy title mouseovers                                     //
// Based on http://www.kryogenix.org/code/browser/nicetitle/ //
//////////////////////////////////////////////////////////////



var CURRENT_NICE_TITLE;

function makeNiceTitles() {    
    var dLinks = document.getElementsByTagName("a");    
    for (var ti=0;ti< dLinks.length;ti++) {
        var lnk = dLinks[ti];
		var titleClass = lnk.className;
				
        if (lnk.title && (titleClass.match('bookmark'))) {
            lnk.setAttribute("nicetitle",lnk.title);
            lnk.removeAttribute("title");
            
			lnk.onmouseover = snt;
			lnk.onmouseout = hnt;			
        }
    }
}

function snt(e) {
	
    var lnk = null;
	if (CURRENT_NICE_TITLE) hnt(CURRENT_NICE_TITLE);
    if (window.event && window.event.srcElement) {
        lnk = window.event.srcElement
    } else if (e && e.target) {
        lnk = e.target
    }
	if (lnk.nodeType == 1) {
        lnk = getParent(lnk,"A");
    }
    var nicetitle = lnk.getAttribute("nicetitle");
    
    var d = document.createElement("div");
    d.className = "nicetitle";
    var tempString = '<img src="'+imageUrl()+'new/gfx/top-lf.gif" id="topLf" /><img src="'+imageUrl()+'new/gfx/top-rt.gif" id="topRt" />';
	tempString += '<p class="titletext">'+nicetitle+'</p>';
    tempString+='<img src="'+imageUrl()+'new/gfx/btm-lf.gif" id="btmLf" /><img src="'+imageUrl()+'new/gfx/btm-rt.gif" id="btmRt" />';
	d.innerHTML+=tempString;
	
    var w = 270;
    d.style.width = w + 'px';    

    var coords = findPosition(lnk);
        
    d.style.left = coords[0] + 'px';
    d.style.top = (coords[1]-60) + 'px';
        
    document.getElementsByTagName("body")[0].appendChild(d);
    
    CURRENT_NICE_TITLE = d;
}

function hnt(e) {
    if (!document.getElementsByTagName) return;
    if (CURRENT_NICE_TITLE) {
        document.getElementsByTagName("body")[0].removeChild(CURRENT_NICE_TITLE);
        CURRENT_NICE_TITLE = null;
    }
}

function getParent(el, pTagName) {
	if (el == null) return null;
	else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())	
	//Gecko bug, supposed to be uppercase
		return el;
	else
		return getParent(el.parentNode, pTagName);
}		

var bookLogin = {'loaded':false};
	
function initBookSignUp(aLink,bizId,bizName){
var xmlHttpReq = Ajax.getTransport();
if(xmlHttpReq){
	if(!bookLogin.loaded){		
		var myAjax = new Ajax.Request(
		'../'+imagesSerial+'/js/bookLog.js', 
		{
			method: 'get',
			onComplete: function(req){
			eval(req.responseText);
			bookLogin.loaded = true;			
			bookLogin.createPop(aLink,bizId,bizName);
			},
			on404: function(){alert('404 error, unable to load.')},
			onFailure : function(){alert('Server Error! Please try again later.');}
		});
		}else{
			bookLogin.createPop(aLink,bizId,bizName);
		}
	}else{
		window.location=aLink.href;
	}
}

//-------------------------------更多城市--首页--------------------------
var locScrollDown = {
xmlHttpReq : Ajax.getTransport(),
down:false,
down1:false,
toggleLocBox: function(aLink){
	if(this.xmlHttpReq){
		if (typeof Effect=='undefined') {			
			var script = document.createElement('script');
			script.src = imagesHostUrl+imagesSerial+'/js/st_lib/effects.js';
			script.type = 'text/javascript';			
			var head = document.getElementsByTagName('head').item(0);
			head.appendChild(script);
		}		
		if(!locScrollDown.box_contents){
			var myAjax = new Ajax.Request(
			'/home/MoreCity.html', 
			{
				method: 'get',
				onComplete: function(req){
					locScrollDown.box_contents = JSON.parse(req.responseText);
					locScrollDown.showLocBox(aLink);	
				},
				onFailure:function(){
					alert('获取城市列表时出错.');
				}
			});
		}else{
			locScrollDown.showLocBox(aLink);
		}
	}else{
		//window.location.href=aLink.href;
		alert('获取城市列表时出错.');
	}
},
showLocBox:function(aLink){
		if(!$('locBox')){
			var locBox = document.createElement('div');
			locBox.setAttribute('id','locBox');
			locBox.style.display = 'none';
			locBox.innerHTML = locScrollDown.box_contents.locContent;
			$('locBar').appendChild(locBox);
		}		
		if(locScrollDown.down){
			var myFadeSize = new Effect.BlindUp('locBox',{duration:.8});
			aLink.innerHTML = '更多城市 &raquo;';
			locScrollDown.down=false;			
		}else{
			var myFadeSize = new Effect.BlindDown('locBox',{duration:.8});
			aLink.innerHTML = '隐藏 &raquo;';
			locScrollDown.down=true;
		}
},
toggleLocBox1: function(aLink){
	if(this.xmlHttpReq){
		if (typeof Effect=='undefined') {			
			var script = document.createElement('script');
			script.src = imagesHostUrl+imagesSerial+'/js/st_lib/effects.js';
			script.type = 'text/javascript';			
			var head = document.getElementsByTagName('head').item(0);
			head.appendChild(script);
		}
		if(!locScrollDown.box_contents1){
			var myAjax = new Ajax.Request(
			'/home/OtherCity.html', 
			{
				method: 'get',
				onComplete: function(req){
					locScrollDown.box_contents1 = JSON.parse(req.responseText);
					locScrollDown.showLocBox1(aLink);	
				},
				onFailure:function(){
					alert('获取城市列表时出错.');
				}
			});
		}else{
			locScrollDown.showLocBox1(aLink);
		}
	}else{
		//window.location.href=aLink.href;
		alert('获取城市列表时出错.');
	}
},
showLocBox1:function(aLink){
		if(!$('locBox1')){
			var locBox1 = document.createElement('div');
			locBox1.setAttribute('id','locBox1');
			locBox1.style.display = 'none';
			locBox1.innerHTML = locScrollDown.box_contents1.locContent;
			$('locBox').appendChild(locBox1);
		}		
		if(locScrollDown.down1){
			var myFadeSize = new Effect.BlindUp('locBox1',{duration:.8});
			aLink.innerHTML = '其他城市 &raquo;';
			locScrollDown.down1=false;			
		}else{
			var myFadeSize = new Effect.BlindDown('locBox1',{duration:.8});
			aLink.innerHTML = '隐藏其他城市 &raquo;';
			locScrollDown.down1=true;
		}
}
}


