$(document).ready(function() {
	// show date
	WEATHER.RunGLNL();
	// menu
	new cehomepage_menu().initialize(el('toggle_options'), el('tips'));
	// z.g-fox.cn
	if (typeof render_header == 'function') render_header();
	// news tab auto change
	new tab_auto_change().initialize(el('focus').getElementsByTagName('li')[0], "auto_");
	// hotel tickets
	var date = new Date();
	var temp_month = date.getMonth() + 1;
	var temp_day = date.getDate();
	if (temp_month < 10) {
		temp_month = "0" + temp_month;
	}
	if (temp_day < 10) {
		temp_day = "0" + temp_day;
	}
	f_d = date.getFullYear() + '-' + temp_month + '-' + temp_day;
	dates = document.getElementById('links').getElementsByTagName('INPUT');
	for (var i = 0; i < dates.length; i++) {
		if (dates[i].className == 'date') {
			dates[i].value = f_d;
		}
	}
	// init panels
	PANEL.init();
	//search box
	(function() {
		MONAV.Search.init({
			tab_box: 'search_tab_box',
			logo: 'search_engine_logo',
			href: 'search_engine_href',
			submit_btn: 'search_engine_button',
			search_input: 'search_input',
			iframetabs: {
			},
			form: document.form1
		});
		
		MONAV.Tab.init_tabs({
			tab_box: 'bussiness_query_box'
		});
		
		SUGGEST.init();
	})();
	
	/*新闻滚动*/
	$(function(){
			var $this =$(".scrollNews");
			var scrollTimer;
			$this.hover(function(){
				  clearInterval(scrollTimer);
			 },function(){
			   scrollTimer = setInterval(function(){
							 scrollNews( $this );
						}, 6000 );
			}).trigger("mouseleave");
	});
	$(function(){
			var $this =$(".horScroll");
			var horTimer;
			$this.hover(function(){
				  clearInterval(horTimer);
			 },function(){
			   horTimer = setInterval(function(){
							 horScroll( $this );
						}, 10000 );
			}).trigger("mouseleave");
	});
	function scrollNews(obj){
	   var $self = obj.find("ul:first"); 
	   var lineHeight = $self.find("li:first").height(); //获取行高
	   $self.animate({ "marginTop" : -lineHeight +"px" }, 600 , function(){
			 $self.css({marginTop:0}).find("li:first").appendTo($self); //appendTo能直接移动元素
	   })
	}
	function horScroll(obj) {
		var $self = obj.find("ul:first");
		var width = $self.find("li:first").width();
		$self.animate({ "marginLeft" : -width +"px" }, 500 , function(){
			 $self.css({marginLeft:0}).find("li:first").appendTo($self);
	   })
	}
	TAB.random_show_one("ff_garden_store");
	document.getElementById("search_input").setAttribute("autocomplete", "off");
	var iframe_src = el("banner_show1").getElementsByTagName("iframe")[0].src;
	el("banner_show1").getElementsByTagName("iframe")[0].src = iframe_src;
});



var __ie__ = el('__ie__');
if (!__ie__) {
    window['__event__'] = function(evt) { return evt; };
}

function observe_event(element, eventName, handler) {
    if (element.addEventListener) {
      element.addEventListener(eventName, handler, false);
    } else {
      element.attachEvent("on" + eventName, handler);
    }
}     

function stop_event(evt) {
    evt = window.event ? window.event : evt;
       if (evt) {
           if(__ie__) {
            evt.cancelBubble = true;
            evt.returnValue = false;
           } else {
            evt.stopPropagation();
            evt.preventDefault();
            evt.target.blur();
           }
    }
}

var UTIL = {
    map: function(f, xs) {
        var ret = [];
        var len = xs.length;
		var i;
        for (i = 0; i < len; i++) {
            ret.push(f(xs[i]));
        }
        return ret;
    },
    
    get_height: function() {
        return document.body.scrollHeight;
    },
      
    getRel: function(elem) {
        if (!!elem.getAttribute('rel')) {
            return elem.getAttribute('rel');
		}
        var rel = /rel-([^ ]+)/i.exec(elem.className);
        if (!!rel && rel.length === 2) {
            return rel[1];
		}
    },
	set_hversion: function() {
		PREF.set('homepage_version', 'new');
		location.href = "http://i.g-fox.cn/";
	}
};

var CSS = {
    is: function(node, cls) {
        var re = new RegExp('(^|\\s)' + cls + '(\\s|$)');
        if (re.test(node.className)) {
            return true;
        } else {
            return false;
        }
    },
    add: function(node, cls) {
        if (this.is(node, cls)) {
            return;
		}
        var clss = node.className.split(' ');
        clss.push(cls);
        node.className = clss.join(' ');
    },
    del: function(node, cls) {
        var clss = node.className.split(' ');
		var i;
        for ( i in clss) {
            if (clss[i] === cls) {
                clss.splice(i, 1);
                node.className = clss.join(' ');
                return;
            }
        }
    },
    find: function(cls, node) {
        if (!node) {
            node = document;
        }
        if (node.getElementsByClassName) {
            return node.getElementsByClassName(cls);
        } else if (node.querySelectorAll) {
            return node.querySelectorAll('.' + cls);
        } else if (document.getElementsByClassName) {
            return document.getElementsByClassName.call(node, cls);
        }
    }
};

function setTab(name,cursel,n){
 for(i=1;i<=n;i++){
  var menu=document.getElementById(name+i);
  var con=document.getElementById("con_"+name+"_"+i);
  if(i==cursel){
	  CSS.add(menu,"hover");
	  con.style.display="block"; 
  }
  else{
	  CSS.del(menu,"hover");
	  con.style.display="none";	
  }
 }
}

var WEATHER = {
	RunGLNL: function(){
		var today=new Date();
		var dd = today.getDate(), mt = today.getMonth()+1, yy=today.getFullYear();
		var d = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
		var weekday = d[today.getDay()];
		var D1 = yy + "年" + mt + "月" + dd + "日" + " " + weekday;
		var DDDD = this.CnDateofDateStr(today); //显示农历
		el("chinese_date").innerHTML = DDDD;
		el("western_date").innerHTML = D1;
	},
	
	DaysNumberofDate: function(DateGL){
		return parseInt((Date.parse(DateGL)-Date.parse(DateGL.getFullYear()+"/1/1"))/86400000, 10)+1;
	},
	
	CnDateofDate: function(DateGL){
		var CnData=[
		0x16,0x2a,0xda,0x00,0x83,0x49,0xb6,0x05,0x0e,0x64,0xbb,0x00,0x19,0xb2,0x5b,0x00,
		0x87,0x6a,0x57,0x04,0x12,0x75,0x2b,0x00,0x1d,0xb6,0x95,0x00,0x8a,0xad,0x55,0x02,
		0x15,0x55,0xaa,0x00,0x82,0x55,0x6c,0x07,0x0d,0xc9,0x76,0x00,0x17,0x64,0xb7,0x00,
		0x86,0xe4,0xae,0x05,0x11,0xea,0x56,0x00,0x1b,0x6d,0x2a,0x00,0x88,0x5a,0xaa,0x04,
		0x14,0xad,0x55,0x00,0x81,0xaa,0xd5,0x09,0x0b,0x52,0xea,0x00,0x16,0xa9,0x6d,0x00,
		0x84,0xa9,0x5d,0x06,0x0f,0xd4,0xae,0x00,0x1a,0xea,0x4d,0x00,0x87,0xba,0x55,0x04
		];
		var CnMonth = [];
		var CnMonthDays = [];
		var CnBeginDay;
		var LeapMonth;
		var Bytes = [];
		var I;
		var CnMonthData;
		var DaysCount;
		var CnDaysCount;
		var ResultMonth;
		var ResultDay;
		var yyyy=DateGL.getFullYear();
		var mm=DateGL.getMonth()+1;
		var dd=DateGL.getDate();

		if (yyyy<100) {
			yyyy+=1900;
		}
		if ((yyyy < 1997) || (yyyy > 2020)){
			return 0;
		}
		  Bytes[0] = CnData[(yyyy - 1997) * 4];
		  Bytes[1] = CnData[(yyyy - 1997) * 4 + 1];
		  Bytes[2] = CnData[(yyyy - 1997) * 4 + 2];
		  Bytes[3] = CnData[(yyyy - 1997) * 4 + 3];
		  if ((Bytes[0] & 0x80) !== 0) {CnMonth[0] = 12;}
		  else {CnMonth[0] = 11;}
		  CnBeginDay = (Bytes[0] & 0x7f);
		  CnMonthData = Bytes[1];
		  CnMonthData = CnMonthData << 8;
		  CnMonthData = CnMonthData | Bytes[2];
		  LeapMonth = Bytes[3];
		for (I=15;I>=0;I--){
			CnMonthDays[15 - I] = 29;
			if (((1 << I) & CnMonthData) !== 0 ){
			  CnMonthDays[15 - I]++;}
			if (CnMonth[15 - I] === LeapMonth ){
			  CnMonth[15 - I + 1] = - LeapMonth;}
			else{
			  if (CnMonth[15 - I] < 0 ){CnMonth[15 - I + 1] = - CnMonth[15 - I] + 1;}
			  else {CnMonth[15 - I + 1] = CnMonth[15 - I] + 1;}
			  if (CnMonth[15 - I + 1] > 12 ){ CnMonth[15 - I + 1] = 1;}
			}
		  }
		  DaysCount = this.DaysNumberofDate(DateGL) - 1;
		  if (DaysCount <= (CnMonthDays[0] - CnBeginDay)){
			if ((yyyy > 1901)  &&  (this.CnDateofDate(new Date((yyyy - 1)+"/12/31")) < 0)){
			  ResultMonth = - CnMonth[0];}
			else {ResultMonth = CnMonth[0];}
			ResultDay = CnBeginDay + DaysCount;
		  }
		  else{
			CnDaysCount = CnMonthDays[0] - CnBeginDay;
			I = 1;
			while ((CnDaysCount < DaysCount)  &&  (CnDaysCount + CnMonthDays[I] < DaysCount)){
			  CnDaysCount+= CnMonthDays[I];
			  I++;
			}
			ResultMonth = CnMonth[I];
			ResultDay = DaysCount - CnDaysCount;
		  }
		  if (ResultMonth > 0){
			return ResultMonth * 100 + ResultDay;}
		  else{return ResultMonth * 100 - ResultDay;}
	},
	
	CnYearofDate: function(DateGL){
		var YYYY=DateGL.getFullYear();
		var MM=DateGL.getMonth()+1;
		var CnMM=parseInt(Math.abs(this.CnDateofDate(DateGL))/100, 10);
		if(YYYY<100) { YYYY+=1900; }
		if(CnMM>MM) { YYYY--; }
		YYYY-=1864;
		return this.CnEra(YYYY)+"年";
	},
	
	CnMonthofDate: function(DateGL){
		var  CnMonthStr = ["零","正","二","三","四","五","六","七","八","九","十","冬","腊"];
		var  Month;
		  Month = parseInt(this.CnDateofDate(DateGL)/100, 10);
		  if (Month < 0){return "闰" + CnMonthStr[-Month] + "月";}
		  else{return CnMonthStr[Month] + "月";}
	},
	
	CnDayofDate: function(DateGL){
		var CnDayStr= ["零",
			"初一", "初二", "初三", "初四", "初五",
			"初六", "初七", "初八", "初九", "初十",
			"十一", "十二", "十三", "十四", "十五",
			"十六", "十七", "十八", "十九", "二十",
			"廿一", "廿二", "廿三", "廿四", "廿五",
			"廿六", "廿七", "廿八", "廿九", "三十"];
		var Day;
		  Day = (Math.abs(this.CnDateofDate(DateGL)))%100;
		  return CnDayStr[Day];
	},
	
	CnEra: function(YYYY){
		var Tiangan = ["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"];
		//var Dizhi=new Array("子(鼠)","丑(牛)","寅(虎)","卯(兔)","辰(龙)","巳(蛇)",
							//"午(马)","未(羊)","申(猴)","酉(鸡)","戌(狗)","亥(猪)");
		var Dizhi = ["子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"];
		return Tiangan[YYYY%10]+Dizhi[YYYY%12];
	},
	
	CnDateofDateStr: function(DateGL){
		if(this.CnMonthofDate(DateGL) === "零月") {
			return "　请调整您的计算机日期!";
		}
		 else {
			return "农历"+this.CnYearofDate(DateGL)+ " " + this.CnMonthofDate(DateGL) + this.CnDayofDate(DateGL);
		}
	}
};

var SUGGEST = {
	list: null,
	box: null,
	inbox: null,
	save: null,
	sign: null,
	init: function() {
		on = true;
		list = document.getElementById("suggestlist");
		box = document.getElementById("suggestbox");
		inbox = document.getElementById("search_input");
		save = document.getElementById("search_input").value;
		inbox.onfocus = function(){
			if (this.check !== null) {
				clearInterval(this.check);
			}
			this.check = setInterval(SUGGEST.get_suggest, 300);
		};
		inbox.onblur = function(){
			clearInterval(SUGGEST.check);
		};
		inbox.onclick = function() {
			box.style.display = "none";
		};
		document.body.onclick = function(evt) {
			el("suggestbox").style.display = "none";
		};
		inbox.onkeydown = function(evt) {
			if (box.style.display === "none") {
				return;
			}
			var target = window.event ? window.event : evt;
			var code = target.keyCode;
			if (code === 38) {
				SUGGEST.movekey("up");
			} else {
				if (code === 40) {
					SUGGEST.movekey("down");
				}
			}
		};
		
		window.baidu = {};
		window.baidu.sug = function(sug) {
			list.innerHTML="";
			save = sug.q;
			var i, j;
			if (sug.s.length === 0) {
				box.style.display = "none";
			} else {
				var ul = [];
				for (i = 0; i < sug.s.length; i++) {
					var li = "<li><p>" + sug.s[i] + "</p></li>";
					ul.push(li);
				}
				list.innerHTML = ul.join("");
				box.style.display = "block";
				for (i = 0; i < list.childNodes.length; i++) {
					var list_li = list.childNodes[i];
					list_li.onclick = function(evt) {
						inbox.value = this.childNodes[0].innerHTML;
						save = inbox.value;
						el("search_engine_button").click();
					};
					list_li.onmouseover = function(evt) {
						SUGGEST.set_curr(this);
					};
				}
				box.onmouseout = function() {
					for (j = 0; j < list.childNodes.length; j++) {
							CSS.del(list.childNodes[j], "currkey");
					}
				};
			}
		};
	},
	isvalid: function(a) {
		if (a === '') {
			box.style.display = "none";
			return false;
		} else if (a === save) {
			return false;
		}
		return true;
	},
	get_suggest: function() {
		var curr = inbox.value;
		if (SUGGEST.isvalid(curr)) {
			if ((sign === 'map')||(sign === 'shopping')) {
				return;
			} else {
				var s = document.createElement("script");
				document.body.appendChild(s);
				s.charset = "gb2312";
				switch (sign) {
					case 'web':
						s.src = "http://suggestion.baidu.com/su?wd=" + encodeURIComponent(curr);
						break;
					case 'music':
						s.src = "http://nssug.baidu.com/su?wd=" + encodeURIComponent(curr) + "&prod=mp3";
						break;
					case 'image':
						s.src = "http://nssug.baidu.com/su?wd=" + encodeURIComponent(curr) + "&prod=image";
						break;
					case 'news':
						s.src = "http://nssug.baidu.com/su?wd=" + encodeURIComponent(curr) + "&prod=news";
						break;
					case 'video':
						s.src = "http://nssug.baidu.com/su?wd=" + encodeURIComponent(curr) + "&prod=video";
						break;
					case 'zhidao':
						s.src = "http://nssug.baidu.com/su?wd=" + encodeURIComponent(curr) + "&prod=zhidao";
						break;
				}
			}
		}
	},
	movekey: function(e) {
		var curr = '';
		var tar = '';
		curr = SUGGEST.get_curr();
		if (curr) {
			if (e === "up") {
				tar = curr.previousSibling;
			} else if (e === "down"){
				tar = curr.nextSibling;
			}	
			// the first one or last one
			if (tar === null) {
				SUGGEST.del_curr();
			}
		} else {
			if (e === "up") {
				tar = list.lastChild;
			} else if (e === "down"){
				tar = list.firstChild;
			}
		}
		if (tar !== null) {
			SUGGEST.set_curr(tar);
			save = inbox.value = tar.childNodes[0].innerHTML;
		}
	},
	get_curr: function() {
		var curr = CSS.find("currkey", this.list)[0];
		return curr;
	},
	set_curr: function(tar) {
		this.del_curr();
		CSS.add(tar, "currkey");
	},
	del_curr: function() {
		var j;
		for (j = 0; j < list.childNodes.length; j++) {
			CSS.del(list.childNodes[j], "currkey");
		}
	},
	turn :function(a) {
		sign = a;
	}
};
var MAIL = {
	popmail: function() {
		var mailbox = el("mailbox");
		var matchp = /^p(\d+)/;
		if (matchp.test(mailbox.value)) {
			var num = mailbox.value.replace(matchp, '$1');
			LINKTRACE.xhr_trace('hp', 'popmail', mailbox.children[mailbox.selectedIndex].innerHTML);
			switch (num) {
				case "1":
					window.open("http://mail.google.com/");
					break;
				case "2":
					window.open("http://mail.live.com/");
					break;
				case "3":
					window.open("http://email.163.com/");
					break;
				case "4":
					window.open("http://email.126.com/");
					break;
				case "5":
					window.open("http://mail.yeah.net/");
					break;
				case "6":
					window.open("http://mail.qq.com/");
					break;
				case "7":
					window.open("http://mail.263.net/");
					break;
				case "8":
					window.open("http://www.kaixin001.com/");
					break;
				default:
					break;
			}
			mailbox.selectedIndex = 0;
		} 
	},
	checkmail: function() {
		var mailbox = el("mailbox");
		var mailform = el("mail_form");
		var un = el("username").value;
		var pw = el("password").value;
		var insert_array = [];
		var insert_value = [];
		MAIL.remove_inputs("mail_form");
		var matchm = /^m(\d+)/;
		if (matchm.test(mailbox.value)) {
			var num = mailbox.value.replace(matchm, '$1');	
			LINKTRACE.xhr_trace('hp', 'checkmail',mailbox.children[mailbox.selectedIndex].innerHTML);			
			switch (num) {
				case "1":
					mailform.action = "http://mail.sina.com.cn/cgi-bin/cnlogin.php";
					insert_array = ["u", "psw"];
					insert_value = [un, pw];
					MAIL.insert_inputs(insert_array, insert_value);
					break;
				case "2":
					mailform.action = "http://mail.sina.com.cn/cgi-bin/login.cgi";
					insert_array = ["u", "psw"];
					insert_value = [un, pw];
					MAIL.insert_inputs(insert_array, insert_value);
					break;
				case "3":
					mailform.action = "http://passport.sohu.com/login.jsp";
					var username = un + "@sohu.com";
					insert_array = ["loginid", "passwd", "fl", "vr", "appid", "ct", "sg", "ru"];
					insert_value = [username, pw, "1", "1|1", "1000", "1173080990", "5082635c77272088ae7241ccdf7cf062", "http://login.mail.sohu.com/servlet/LoginServlet"];
					MAIL.insert_inputs(insert_array, insert_value);
					break;
				case "4":
					username = un + "@yahoo.cn";
					mailform.action = "https://edit.bjs.yahoo.com/config/login";
					insert_array = ["login", "passwd", ".intl", "domainss", ".done"];
					insert_value = [username, pw, "cn", "yahoo", "http://mail.cn.yahoo.com/inset.html"];
					MAIL.insert_inputs(insert_array, insert_value);
					break;
				case "5":
					username = un + "@yahoo.com.cn";
					mailform.action = "https://edit.bjs.yahoo.com/config/login";
					insert_array = ["login", "passwd", ".intl", "domainss", "src", ".done"];
					insert_value = [username, pw, "cn", "yahoo", "ym", "http://mail.cn.yahoo.com/inset.html"];
					MAIL.insert_inputs(insert_array, insert_value);
					break;
				case "6":
					mailform.action = "http://login.mail.tom.com/cgi/login";
					insert_array = ["user", "pass"];
					insert_value = [un, pw];
					MAIL.insert_inputs(insert_array, insert_value);
					break;
				case "7":
					mailform.action = "http://passport.21cn.com/maillogin.jsp";
					insert_array = ["UserName", "passwd"];
					insert_value = [un, pw];
					MAIL.insert_inputs(insert_array, insert_value);
					break;
				case "8":
					mailform.action = "https://mail.10086.cn/Login/Login.ashx";
					insert_array = ["UserName", "Password"];
					insert_value = [un, pw];
					MAIL.insert_inputs(insert_array, insert_value);
					break;
				case "9":
					mailform.action = "https://passport.baidu.com/?login";
					insert_array = ["username", "password"];
					insert_value = [un, pw];
					MAIL.insert_inputs(insert_array, insert_value);
					break;
				case "10":
					mailform.action = "http://passport.renren.com/PLogin.do";
					insert_array = ["email", "password"];
					insert_value = [un, pw];
					MAIL.insert_inputs(insert_array, insert_value);
					break;
				case "11":
					mailform.action = "http://passport.51.com/login.5p";
					insert_array = ["passport_51_user", "passport_51_password", "gourl"];
					insert_value = [un, pw, "http%3A%2F%2Fmy.51.com%2Fwebim%2Findex.php"];
					MAIL.insert_inputs(insert_array, insert_value);
					break;
				case "12":
					mailform.action = "http://passport.sohu.com/login.jsp";
					insert_array = ["loginid", "passwd", "fl", "vr", "appid", "ct", "sg", "ru"];
					insert_value = [un, pw, "1", "1|1", "1005", "1282560903", "5365e2f819144cbb0d83b07a2976a01d", "http://profile.chinaren.com/urs/setcookie.jsp?burl=http://alumni.chinaren.com/"];
					MAIL.insert_inputs(insert_array, insert_value);
					break;
				default:
					break;
			}
			mailform.submit();
		}
	},	
	remove_inputs: function(pname) {
		var mailform = el(pname);
		var rmlist = [];
		var mail_input = mailform.getElementsByTagName("input");
		if (mail_input.length > 0) {
			var i;
			for (i = 0; i < mail_input.length; i++) {
				if (mail_input[i].type === "hidden") {
					rmlist.push(mail_input[i]);
				}
			}
			for (i = 0; i < rmlist.length; i++) {
				mailform.removeChild(rmlist[i]);
			}
		}
	},
	insert_inputs: function(insert_array, insert_value) {
		var i;
		for (i = 0; i < insert_array.length; i++) {
				MAIL.insert_child("mail_form", insert_array[i], insert_value[i]);
			}
	},
	insert_child: function(pname, nodename, nodevalue) {
		pname = el(pname);
		var temp = document.createElement("input");
		temp.name = nodename;
		temp.value = nodevalue;
		temp.type = "hidden";
		pname.appendChild(temp);
	}
};

var PREF = {
    backend: null,
    init: function() {
        if (window.localStorage) {
            this.backend = localStorage;
            this.backend['__type__'] = 'ls';
        } else if (window.globalStorage) {
            this.backend = globalStorage[document.domain];
            this.backend['__type__'] = 'gs';
        } else if (document.cookie) {
            this.backend = {
                getItem: function(k) {
                    var seq = document.cookie.split(';');
                    var re = new RegExp('^ ?' + k + '=');
					var i;
                    for (i in seq) {
                        if (re.test(seq[i])) {
                            var str = seq[i];
                            return unescape(str.substr(str.indexOf('=') + 1));
                        }
                    }
                },
                setItem: function(k, v) {
                    document.cookie = k + '=' + escape(v) + '; domain=' + document.domain + '; expires=' + ((new Date('December 31, 2100')).toGMTString());
                },
                __type__: 'cookie'
            };
        } else {
            this.backend = {
                getItem: function() { return null; },
                setItem: function() {},
                __type__: 'dummy'
            };
        }
    },
    get: function(k, d) {
        var v = null;
        try {
            v = this.backend.getItem(k);
            if (v !== null) {
                v = JSON.parse(v + '') || d;
            } else {
                v = d;
            }
        } catch (ex) {
            v = d;
        }
        return v;
    },
    set: function(k, v) {
        try {
            this.backend.setItem(k, JSON.stringify(v));
        } catch (ex) {
        }
    }
};
PREF.init();

var TAB = {
	cbs: [],
    hook: function(tab) {
        var me = this;
        tab.onmouseover = function(evt) {
            tab['__cehp_tab_moving'] = true;
            if (!__ie__) {
            	window.setTimeout(function() {me.change(evt);}, 100);
			} else {
            	window.setTimeout(function() {me.change(tab);}, 100);
			}
			me.on_tab_switch(tab);
        };
        tab.onmouseout = function() {
            tab['__cehp_tab_moving'] = false;
        };
    },
    
    add_cb_on_tab_switch: function(cb) {
    	this.cbs.push(cb);
    },
    
    on_tab_switch: function(tab) {
		var i;
    	for(i in this.cbs) {
    		this.cbs[i](tab);
    	}
    },
    
    change: function(evt) {
        try{
            if (!__ie__){
                evt = __event__(evt);
				var tab = evt.target;
            }else{
                var tab = evt;
            }
			if (!tab['__cehp_tab_moving']) {
				return;
			}
			var ul = tab;    
			while (ul.nodeName.toLowerCase() != 'ul') {
				ul = ul.parentNode;
			}
			var currents = CSS.find('tab-title-current', ul);
			var i;
			for (i in currents) {
				if (currents[i].nodeType != 1)
					continue;
				document.getElementById(UTIL.getRel(currents[i])).style['display'] = 'none';
				CSS.del(currents[i], 'tab-title-current');
			}
			CSS.add(tab, 'tab-title-current');
			var id = UTIL.getRel(tab);
			var node = document.getElementById(id);
			node.style['display'] = 'block';
			//if(id == "focus_news_1") {
			//	el("jrj_ff_iframe").src = "http://stock.jrj.com.cn/hezuo/ff/jrj_ff.html";				
			//}
        }catch(e){}
    },
	random_show: function(prefix, num) {
		var ran = Math.floor(Math.random()*num) + 1;
		if (ran > num) {
			ran = num;
		}
		var temp = prefix + ran;
		var target = el(temp);
		TAB.auto_change(target);
	},
	random_show_one: function(id) {
		var ran = Math.random();
		if (ran > 0.5) {
			var target = el(id);
			TAB.auto_change(target);
		}
	},
	auto_change: function(tar_tab) {
        var ul = tar_tab;
        while (ul.nodeName.toLowerCase() != 'ul') {
            ul = ul.parentNode;
        }
        var currents = CSS.find('tab-title-current', ul);
        for (var i in currents) {
            if (currents[i].nodeType != 1)
                continue;
            document.getElementById(UTIL.getRel(currents[i])).style['display'] = 'none';
            CSS.del(currents[i], 'tab-title-current');
        }
        CSS.add(tar_tab, 'tab-title-current');
        var id = UTIL.getRel(tar_tab);
        var node = document.getElementById(id);
        node.style['display'] = 'block';
    }
};

function CityPicker() {}
CityPicker.prototype = {
	initialize: function(input, placeIn, cities, sign, more) { // input: sign == 0; div: sign == 1;
		this.placeIn = placeIn ? placeIn : document.body;
		this.input = input;
		this.cities = cities;
		this.sign = sign;
		this.more = more;
		this.picker = null;
		this.initPicker();
        this.initEventListeners();
	},
	
	initPicker: function() {
    	this.picker = document.createElement('DIV');
    	this.picker.className = 'city-picker widget round-box trans-box';
    	this.picker.style['display'] = 'none';
    	var ul = document.createElement('UL');
    	this.picker.appendChild(ul);
    	for(var i in this.cities) {
    		var item = document.createElement('LI');
    		item.innerHTML = '<a href="javascript:void(0);" title="' + this.cities[i] + '">' + this.cities[i] + '</a>';
    		var self = this;
    		item.childNodes[0].onclick = function(evt) {
				if (self.sign == 0) {
					self.input.value = this.innerHTML;
				} else if (self.sign == 1) {
					self.input.innerHTML = this.innerHTML;
				}
    			self.picker.style['display'] = 'none';
				evt = __event__(evt);
				var a = evt.target;
				if(a.parentNode.parentNode.parentNode.parentNode.children[1].id == "tuan_city_input") {
					TUAN.change();
				}
    		};
    		ul.appendChild(item);
    	}
		if (this.more) {
			var item = document.createElement('li');
			item.innerHTML = "<a target='_blank' href=" + this.more + ">更多</a>";
			ul.appendChild(item);
		}
    	this.placeIn.appendChild(this.picker);
	},
	
    initEventListeners : function() {
    	var self = this;
		this.input.onclick = function(evt) {
			self.picker.style['display'] = 'block';
		};
		this.input.onkeydown = function(evt) {
			self.picker.style['display'] = 'none';
		};
		this.picker.onmousedown = function(evt) {
			stop_event(evt);
		};
		observe_event(document.body, 'mousedown', function(evt) {
			self.picker.style['display'] = 'none';
		}, false);
		TAB.add_cb_on_tab_switch(function(tab) {
			if ((tab.className == 'tab-title rel-links_hotel')||(tab.className == 'tab-title rel-mblog')) {
				self.picker.style['display'] = 'none';
			}
		});
    }
}

function cehomepage_menu() {}
cehomepage_menu.prototype = {
    initialize : function(btn, menu, items) {
        this.btn = btn;
        this.menu = menu;
        this.items = items;
        this.initEventListeners();
    },
    
    initEventListeners : function() {
        var self = this;
        this.btn.onclick = function(evt) {
            self.btn_onclick(evt);
        }
        this.btn.onmousedown = function(evt) {
            self.btn_onmousedown(evt);
        }
        this.menu.onmousedown = function(evt) {
            self.menu_onmousedown(evt);
        }
        if(this.items) {
            for(var i = 0; i < this.items.length; i++) {
                this.items[i].onclick = function(evt) {
                    self.items_onclick(evt);
                }
            }
        }
        observe_event(document.body, 'mousedown', function(evt) {
            self.body_onmousedown(evt);
        }, false);
    },
    
    body_onmousedown : function(evt) {
        this.menu.style['display'] = 'none';
    },
    
    btn_onmousedown : function(evt) {
        isShowing = this.menu.style['display'] == 'none';
        if (evt && !isShowing) {
            stop_event(evt);
        }
    },
    
    btn_onclick : function(evt) {
        show = this.menu.style['display'] == 'none';
        this.menu.style['display'] = show ? 'block' : 'none';
        stop_event(evt);
    },
    
    items_onclick : function(evt) {
        this.menu.style['display'] = 'none';
    },
    
    menu_onmousedown : function(evt) {
        stop_event(evt);
    }
}

function tab_auto_change(){}
tab_auto_change.prototype = {
    initialize : function(li, tab_pre) {
        this.li = li;
        this.tab_pre = tab_pre;
        this.interval = null;
        this.initEventListeners();
    },
    
    initEventListeners : function() {
        var self = this;
        self.li.onmouseover = function() {
            window.clearInterval(self.interval);
        }    
        var tab_total = self.li.getElementsByTagName('div')[0].getElementsByTagName('ul')[0].getElementsByTagName('li').length;
        self.change_tab(0, tab_total);
    },
    
    auto_change: function(tar_tab) {
        var ul = tar_tab;
        while (ul.nodeName.toLowerCase() != 'ul') {
            ul = ul.parentNode;
        }
        var currents = CSS.find('tab-title-current', ul);
        for (var i in currents) {
            if (currents[i].nodeType != 1)
                continue;
            document.getElementById(UTIL.getRel(currents[i])).style['display'] = 'none';
            CSS.del(currents[i], 'tab-title-current');
        }
        CSS.add(tar_tab, 'tab-title-current');
        var id = UTIL.getRel(tar_tab);
        var node = document.getElementById(id);
        node.style['display'] = 'block';
		if(id == "focus_news_1") {
		//	el("jrj_ff_iframe").src="http://stock.jrj.com.cn/hezuo/ff/jrj_ff.html";
		}
    },
    
    change_tab: function(tab_num, tab_total) {
        var self = this;
        var pre = self.tab_pre;
        self.interval = setInterval(function() {
            tab_num++;
            var index = tab_num % tab_total;
            index += "";
            var tab_class = pre + index;
            var temp = CSS.find(tab_class)[0];
            self.auto_change(temp);
        }, 5000);
    }     
}

var panels_visibility = {};
function panel_toggle(evt) {
    evt = __event__(evt);
    var a = evt.target;
    a.blur();
    if (a.nodeName.toLowerCase() != 'a') return;
    evt.stopPropagation();
    evt.preventDefault();
    var is_show = CSS.is(a, 'check');
    var panel = el(a.getAttribute('rel'));
    if (is_show) {
        CSS.del(a, 'check');
        panel.style['display'] = 'none';
        a.setAttribute('title', '显示 ' + a.firstChild.nodeValue);
        panels_visibility[panel.id] = 'collapse';
    } else {
        CSS.add(a, 'check');
        panel.style['display'] = 'block';
        a.setAttribute('title', '显示 ' + a.firstChild.nodeValue);
        panels_visibility[panel.id] = 'toggle';
    }
    PREF.set('panels_visibility', panels_visibility);
}

var XHR = {
    get: function(url, cb) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                cb(xhr.responseText);
            }
        };
        xhr.open('GET', url, true);
        xhr.send('');
    }
};

var NOTIFY = {
    panel: null,
    mask: null,
    mask_iframe: null,
    timer: null,
    confirm: function(msg, cb) {
        if (this.panel == null) {
            this.panel = el('notify_confirm');
        }
        if (this.mask == null) {
        	this.mask = el('notify_mask');
        }
        if (this.mask_iframe == null) {
        	this.mask_iframe = el('notify_mask_iframe');
        }
        this.panel.getElementsByTagName('p')[0].innerHTML = msg;
        this.panel.style['display'] = 'block';
        this.mask.style['display'] = 'block';
        this.mask_iframe.style['display'] = 'block';
        this.setPos();
        window.clearInterval(this.timer);
        var self = this;
        this.timer = window.setInterval(function() {
        	self.setPos();
        }, 1000);
        this.onconfirm['callback'] = cb;
    },
    onconfirm: function(ret) {
        window.clearInterval(this.timer);
        this.panel.style['display'] = 'none';
        this.mask.style['display'] = 'none';
        this.mask_iframe.style['display'] = 'none';
        CSS.find('cancel-btn', this.panel)[0].style['display'] = 'inline';
        if (this.onconfirm['callback']) {
            this.onconfirm['callback'](ret);
        }
    },
    setPos: function() {
    	this.panel.style.top = this.mask.offsetHeight / 2 - this.panel.offsetHeight / 2+ 'px';
    },
    alert: function(msg, cb) {
        this.confirm(msg, cb);
        CSS.find('cancel-btn', this.panel)[0].style['display'] = 'none';
    }
};

var AD = {
    ads: null,
    algorithm: null,
    iframe: [],
    init: function(ads, algorithm) {
        // FIXME always create an iframe, to fix bug: multiple iframe display wrong content when the page is reloaded.
        for (var i = 0; i < 2; i++) {
            this.iframe[i] = document.createElement('IFRAME');
            this.iframe[i].style.display = 'none';
			// hack for ie6
			this.iframe[i].style.width = '468px';
			this.iframe[i].style.height = '60px';
			this.iframe[i].scrolling = "no";
            el('banner_show1').appendChild(this.iframe[i]);
        }
        
        this.ads = ads;
        this.algorithm = typeof algorithm == 'function' ? algorithm :  this.algr_left_first;
        var left = Math.random() >= 0.5;
        this.showAd(left);
        this.showAd(!left);
		// reload iframes
		var iframe_src = el("banner_show1").getElementsByTagName("iframe")[0].src;
		el("banner_show1").getElementsByTagName("iframe")[0].src = iframe_src;
    },
    
    showAd: function(left) {
        var idx = this.algorithm(this.ads, left);
        this.showItem(this.createItem(this.ads[idx]), left);
	//	if (idx != 0) {
			this.ads.splice(idx, 1);
	//	}
    },
    
    algr_random: function(ads) {
		for (var i = 0; i < 3; i++) {
            var rnd = Math.floor(Math.random() * (ads.length));
            if (rnd >= ads.length) {
                rnd = ads.length - 1;
            }
            if (true != ads[rnd].picked)
                return rnd;
        }
        return 0;
    },
    
    algr_left_first: function(ads, left) {
        if (left) {
            return 0;
        } else {
            ads[0].picked = true;
            return this.algr_half_first(ads);
        }
    },
    
    algr_half_first: function(ads) {
        if (true != ads[0].picked) {
            if (Math.random() >= 0.75) {
				ads[0].picked = true;
                return 0;
			}
        } 
        var max = ads.length - 1;
		var rnd = Math.floor(Math.random() * max);
		if ( rnd >= max) {
			rnd = max - 1;
		}
		return rnd + 1;
    },
    
    createItem: function(ad) {
        var item = null;
        if (ad.type == 1) {
            // iframe
            for (var i = 0; i < this.iframe.length; i++) {
                if(this.iframe[i].src == '')
                    item = this.iframe[i];
            }
            item.name = 'banner_ads_iframe_' + new Date().getTime();
            item.id = item.name;
            item.src = ad.url + '#' + new Date().getTime();
            item.style.display = 'block';
        } else if (ad.type == 2) {
            item = document.createElement('EMBED');
            item.src = ad.url;
        } else {
            // img link
            item = document.createElement('A');
            item.target = '_blank';
            var img = new Image();
            img.alt = ad.title;
            img.src = ad.img;
            item.appendChild(img);
            item.href = ad.url;
            item.title = ad.title;
        }
        return item;
    },
    
    getLeftArea: function() {
        return el('banner_show1').getElementsByTagName('DIV')[0];
    },
    
    getRightArea: function() {
        return el('banner_show1').getElementsByTagName('DIV')[1];
    },
    
    showItem: function(item, left) {
        (true == left ? this.getLeftArea() : this.getRightArea()).appendChild(item);
    },
	
	taobao_goods: function(words) {
		var words_len = words.length;
		var seed = Math.random()*words_len;
		var tnum = 0;
		if(seed < words_len) {
			tnum = Math.floor(seed);
		} else {
			tnum = words_len-1;
		}				
		var url = '"' + words[tnum].url + '"';
		var title = '"' + words[tnum].title + '"';
		var img = '"' + words[tnum].img + '"';
		var price = words[tnum].misc;
		var content = "";
		content += "<a target='_blank' href=" + url + "title=" + title + ">";
		content += "<img alt=" + title + "src=" + img + "/><br/>";
		content += "<span class='price'>" + price + "</span><br/>";
		content += "<span class='name'>" + words[tnum].title + "</span></a>";
		var node = document.createElement('div');
		node.className = "goods";
		node.innerHTML = content;
		el("taobao-imglist").appendChild(node);
	},
	game_big_ad: function(words) {
		var words_len = words.length;
		var seed = Math.random()*words_len;
		var tnum = 0;
		if(seed < words_len) {
			tnum = Math.floor(seed);
		} else {
			tnum = words_len-1;
		}				
		var url = '"' + words[tnum].url + '"';
		var title = words[tnum].title;
		var img = '"' + words[tnum].img + '"';
		var content = "";
		content += "<div><a href=" + url + " target='_blank' title=" + title + "><img src=" + img + "alt=" + title + "/></a></div>";
		content += "<div><a href=" + url + " target='_blank' title=" + title + ">" + title +"</a></div>";
		var nodes = el('ents').getElementsByTagName('li');
		for (var i = 0; i < nodes.length; i++) {
			if(nodes[i].className == 'ents-game-big')
			{
				nodes[i].innerHTML = content;
			}
		}
	}
};

var TBHot = {
    init: function(words) {
        this.words = words;
        var max = this.words.length - 15;
        var rnd = Math.floor(Math.random() * max);
        if (rnd >= max) {
            rnd = max - 1;
        }
        for(var i = 0; i < 15; i++) {
            var li = document.createElement('LI');
            li.innerHTML = '<a href="' + this.words[rnd + i].url +  '" target="_blank">' + this.words[rnd + i].title + '</a>';
            el('taobao_sales_hot').appendChild(li);
        }
    }
};

var PANEL = {
    order: null,
	test_order: function (a, b, order) {
		var order1, order2;
		for ( var i = 0; i < order.length; i++) {
			if (order[i].id == a) {
				order1 = i;
			}
			if (order[i].id == b) {
				order2 = i;
			}
		}
		if(order1 < order2) {
			return true;
		} else {
			return false;
		}
	},
    init: function() {
        var pns = CSS.find('panel');
		var panel_array = []
		for ( var j = 0; j < pns.length; j++) {
			panel_array[j] = pns[j];
			var panel = pns[j];
			if (document.querySelector) {
				var a = document.querySelector('#tips a[rel=' + panel.id + ']');
				panel['rev'] = a;
				panel_array[j]['rev'] = a;
			} else {
				var as = el('tips').getElementsByTagName('a');
				for (var i in as) {
					if (as[i].nodeType != 1)
						continue;
					if (as[i].getAttribute('rel') == panel.id) {
						panel['rev'] = as[i];
						panel_array[j]['rev'] = as[i];
						break;
					}
				}
			}
		}
		for ( var j = 0; j < pns.length; j++) {
			var panel = panel_array[j];
			if (this.order == null) {
				this.order = PREF.get('panels_ord', []);
			}
			if (j == 0) {
				panels_visibility = PREF.get('panels_visibility', {});
			}
			var pos = 0;
			if (this.order.indexOf) {
				pos = this.order.indexOf(panel.id);
			} else {
				for (var i = 0; i < this.order.length; i++) {
					if (this.order[i] == panel.id) {
						pos = i;
						break;
					}
				}
			}
			if (pos != -1) {
				pos++;
				while (pos < this.order.length) {
					var np = el(this.order[pos]);
					if (np && PANEL.test_order(np.rev.rel, panel.rev.rel, pns)) {
						np.parentNode.insertBefore(panel, np);
						np.rev.parentNode.insertBefore(panel.rev, np.rev);
						break;
					}
					pos++;
				}
			}
			var visi = panels_visibility[panel.id];
			if (visi == 'toggle' || visi == undefined) {
				panel.style['display'] = 'block';
				var as = el('tips').getElementsByTagName('a');
				for (var i in as) {
					if (as[i].nodeType != 1)
						continue;
					if (as[i].getAttribute('rel') == panel.id) {
						CSS.add(as[i], 'check');
						as[i].setAttribute('title', ['显示', as[i].firstChild.nodeValue].join(' '));
						break;
					}
				}
			} else {
				panel.style['display'] = 'none';
			}
			var movers = CSS.find('panel-mover', panel);
			for (var i in movers) {
				if (movers[i].nodeType == 1) {
					movers[i].onmousedown = this.hook(panel, movers[i]);
				}
			}
			var tabs = CSS.find('tab-title', panel);
			for (var i in tabs) {
				if (tabs[i].nodeType == 1) {
					TAB.hook(tabs[i]);
				}
			}
		}
    },  
	init_fx4: function() {
		var ua = navigator.userAgent.toLowerCase();
		if(ua.match(/firefox\/4.([\d.]+)/)) {
			var enodes = CSS.find('ellipsis', document);
			var temp = new Array();
			if(enodes.length > 0) {
				for(var j = 0; j < enodes.length; j++) {
					temp.push(enodes[j]);
				}
			}
			for(var j = 0; j < temp.length; j++) {
				CSS.del(temp[j], "ellipsis");
				var pnode = temp[j].parentNode;
				CSS.del(pnode, "disc");
				CSS.add(pnode, "disc_fx4");
			}
			var tab = el("news_start_tab");
			TAB.auto_change(tab);
		}
		// init mac
		if (navigator.userAgent.indexOf("Mac",0) != -1) {
			var temp = el("mailbox");
			CSS.add(temp, "mac_style");
			temp = el("mail_button");
			CSS.add(temp, "mac_style");
		}
	},
    collapse: function(id) {
        var panel = el(id);
        do_click(panel.rev);
    },
    moving_panel: null,
    hook: function(panel, mover) {
        var me = this;
        return function(evt) {
            evt = __event__(evt);
            if (evt.button != 0 || me.moving_panel != null || evt.target != mover) {
                me.moving_panel = null;
                return;
            }
            evt.stopPropagation();
            evt.preventDefault();
            me.moving_panel = panel;
        };
    },
    moving: function() {
        var me = this;
        return function(evt) {
            evt = __event__(evt);
            var p = me.moving_panel;
            if (evt.button != 0 || p == null) {
                return;
            }
            evt.stopPropagation();
            evt.preventDefault();
            var ctx = p.move_context;
            if (ctx == null) {
                p.move_context = ctx = {};
                ctx.moved = false;
                var host = ctx.host = el('moving_host');
                var box = ctx.box = me.get_box(p);
                ctx.dx = evt.screenX - ctx.box.left;
                ctx.dy = evt.screenY - ctx.box.top;
                var alter = ctx.alter = document.createElement('div');
                alter.className = 'panel-alter';
                /* hack here, substract 2px from box.height as the border */
                alter.setAttribute('style', 'height:' + (box.height - 2) + 'px;');
                p.parentNode.insertBefore(alter, p);
                with (host) {
                    style['display'] = 'block';
                    appendChild(p);
                    style['left'] = box.left + 'px';
                    style['top'] = box.top + 'px';
                    style['width'] = box.width + 'px';
                    style['height'] = box.height + 'px';
                }
                me.cover(true);
            } else {
                var host = ctx.host;
                var y = parseInt(host.style['top']);
                host.style['left'] = (evt.screenX - ctx.dx) + 'px';
                host.style['top'] = (evt.screenY - ctx.dy) + 'px';
                if (evt.screenY - ctx.dy > y) {
                    me.arrange(ctx, 'nextSibling', me.compare_bottom, me.swap_next);
                } else {
                    me.arrange(ctx, 'previousSibling', me.compare_top, me.swap_previous);
                }
            }
        };
    },
    compare_bottom: function(b, mid) { return b.top + b.height > mid; },
    compare_top: function(b, mid) { return b.top < mid; },
    swap_next: function(current, next) { current.parentNode.insertBefore(next, current); },
    swap_previous: function(current, next) { current.parentNode.insertBefore(current, next); },
    arrange: function(ctx, field, compare, swap) {
        var alter = ctx.alter;
        var b = this.get_box(ctx.host);
        var next = alter[field];
        while (next) {
            if (next.nodeType == 1 && CSS.is(next, 'panel') && next.style['display'] == 'block') {
                var nb = this.get_box(next);
                var mid = nb.top + nb.height / 2;
                if (compare(b, mid)) {
                    log(['arrange', field, b.top, b.top + b.height, mid]);
                    ctx.moved = true;
                    swap(alter, next);
                    swap(this.moving_panel.rev, next.rev);
                    next = alter[field];
                    continue;
                } else {
                    log(['stop', field, b.top, b.top + b.height, mid]);
                    break;
                }
            }
            next = next[field];
        }
    },
    release: function() {
        var me = this;
        return function(evt) {
            evt = __event__(evt);
            var p = me.moving_panel;
            if (evt.button != 0 ||
                p == null) {
                return;
            }
            evt.stopPropagation();
            evt.preventDefault();
            me.cover(false);
            me.moving_panel = null;
            if (p.move_context) {
                var alter = p.move_context.alter;
                if (alter) {
                    alter.parentNode.insertBefore(p, alter);
                    p.parentNode.removeChild(alter);
                }
                if (p.move_context.moved) {
                    var ord = UTIL.map(function(p) { return p.id; }, CSS.find('panel'));
                    PREF.set('panels_ord', ord);
                }
                p.move_context = null;
            }
            el('moving_host').style['display'] = 'none';
        };
    },
    cover: function(show) {
        if (this.moving_panel == null) {
            return;
        }
        var ifs = document.getElementsByTagName('iframe');
        for (var i in ifs) {
            var iframe = ifs[i];
            if (iframe.nodeType != 1)
                continue;
            if (show) {
                var c = document.createElement('div');
                c.className = 'iframe-cover';
                var b = this.get_box(iframe);
                c.style['width'] = b.width + 'px';
                c.style['height'] = b.height + 'px';
                iframe.parentNode.insertBefore(c, iframe);
                iframe['__cover__'] = c;
            } else {
                if (iframe['__cover__'] != null) {
                    iframe.parentNode.removeChild(iframe.__cover__);
                    iframe.__cover__ = null;
                }
            }
        }
    },
    get_box: function(ele) {
        var b = {
            left: ele.offsetLeft,
            top: ele.offsetTop,
            width: ele.offsetWidth,
            height: ele.offsetHeight
        };
        var pp = ele.offsetParent;
        if (pp != ele) {
            while (pp) {
                b.left += pp.offsetLeft;
                b.top += pp.offsetTop;
                pp = pp.offsetParent;
            }
        }
        return b;
    }
};

var LINKTRACE = {
    hooks: {},
    trace: function(evt, link) {
        var href = link.getAttribute('href');
        if (/^#$/.test(href) || /^javascript:/.test(href)) {
            return;
        }
        
        if (this.nolinktrace(link))
            return;
            
        var tracer = link['__linktrace_tracer__'];
        if (tracer == null) {
            tracer = this.setup(link);
        }
        tracer(evt, link);
    },
    identify: function(link) {
        while (link) {
            if (CSS.is(link, 'link-trace')) {
                return UTIL.getRel(link);         //link.getAttribute('rel');
            }
            link = link.parentNode;
        }
        return null;
    },
    nolinktrace : function(link) {
        while (link) {
            if (CSS.is(link, 'no-link-trace')) {
                return true;
            }
            link = link.parentNode;
        }
        return false;
    },
    setup: function(link) {
        var tracer = null;
        var rel = this.identify(link);
        if (rel == null) {
            tracer = function() {};
        }
        var hook = this.hooks;
        if (this.hooks[rel]) {
            tracer = this.hooks[rel];
        } else {
            tracer = this.build(rel);
        }
        link['__linktrace_tracer__'] = tracer;
        return tracer;
    },
    build: function(rel) {
        var me = this;
        return function(evt, link) {
            link['__linktrace_tracer__'] = function() {};
            link.setAttribute('href', me.translate('hp', rel, link));
        };
    },
    translate: function(action, rel, link) {
        var tit = link.getAttribute('title');
        if (tit == null || tit.length == 0) {
            if (link.childNodes.length == 1 && link.firstChild.nodeType == 3) {
                tit = link.firstChild.nodeValue;
            } else if (link.nodeText) {
                tit = link.nodeText;
            } else {
                tit = '';
            }
        }
        return ['/', action, '?u=', encodeURIComponent(link.href), '&c=', rel, '&t=', encodeURIComponent(tit)].join('');
    },
    
    xhr_trace: function(action, rel, href) {
    	XHR.get(['/', action, '?u=', encodeURIComponent(href), '&c=', rel].join(''), function() {});
    }
};

var Calender = {
	HS_DateAdd: function(interval, number, date) { 
		number = parseInt(number); 
		if (typeof(date) == "string") {
			var date = new Date(date.split("-")[0], date.split("-")[1], date.split("-")[2]);
		} 
		if (typeof(date)=="object") {
			var date = date;
		} 
		switch (interval) { 
			case "y":return new Date(date.getFullYear()+number,date.getMonth(), date.getDate()); break; 
			case "m":return new Date(date.getFullYear(), date.getMonth()+number, this.checkDate(date.getFullYear(), date.getMonth()+number, date.getDate())); break; 
			case "d":return new Date(date.getFullYear(), date.getMonth(), date.getDate()+number); break; 
			case "w":return new Date(date.getFullYear(),date.getMonth(), 7*number+date.getDate()); break; 
		} 
	}, 
	checkDate: function(year,month,date) { 
		var enddate = ["31","28","31","30","31","30","31","31","30","31","30","31"]; 
		var returnDate = ""; 
		if (year%4 == 0) {
			enddate[1] = "29";
		} 
		if (date>enddate[month]) {
			returnDate = enddate[month];
		} else {
			returnDate = date;
		} 
		return returnDate; 
	}, 
	WeekDay: function(date) { 
		var theDate; 
		if (typeof(date) == "string") {
			theDate = new Date(date.split("-")[0], date.split("-")[1], date.split("-")[2]);
		} 
		if (typeof(date) == "object") {
			theDate = date;
		} 
		return theDate.getDay(); 
	},
	HS_calender: function(){ 
		var lis = ""; 
		var style = ""; 
		var now; 
		if (typeof(arguments[0])=="string") { 
			selectDate = arguments[0].split("-"); 
			var year = selectDate[0]; 
			var month = parseInt(selectDate[1])-1 + ""; 
			var date = selectDate[2]; 
			now = new Date(year,month,date); 
		} else if (typeof(arguments[0]) == "object") { 
			now = arguments[0]; 
		} 
		var lastMonthEndDate = this.HS_DateAdd("d", "-1", now.getFullYear()+"-"+now.getMonth()+"-01").getDate(); 
		var lastMonthDate = this.WeekDay(now.getFullYear() + "-" + now.getMonth() + "-01"); 
		var thisMonthLastDate = this.HS_DateAdd("d","-1", now.getFullYear() + "-" + (parseInt(now.getMonth())+1).toString() + "-01"); 
		var thisMonthEndDate = thisMonthLastDate.getDate(); 
		var thisMonthEndDay = thisMonthLastDate.getDay(); 
		var todayObj = new Date(); 
		today = todayObj.getFullYear() + "-" + todayObj.getMonth() + "-" + todayObj.getDate(); 
		 
		for (i = 0; i < lastMonthDate; i++) {  // Last Month's Date 
			lis = "<li class='lastMonthDate'>" + lastMonthEndDate + "</li>" + lis; 
			lastMonthEndDate--; 
		} 
		for (i = 1; i <= thisMonthEndDate; i++) { // Current Month's Date 
			month_temp = parseInt(now.getMonth()) + 1;
			day_temp = i;
			if (month_temp < 10) {
				month_temp = "0" + month_temp;
			}
			if (day_temp < 10) {
				day_temp = "0" + day_temp;
			}
			if(today == now.getFullYear() + "-" + now.getMonth() + "-" + i) { 
				var todayString = now.getFullYear() + "-" + month_temp + "-" + day_temp; 
				lis += "<li><a href=javascript:void(0) class='today' onclick='Calender.selectThisDay(this)' title='" + now.getFullYear() + "-" + month_temp + "-" + day_temp + "'>" + i + "</a></li>"; 
			} else { 
				lis += "<li><a href=javascript:void(0) onclick='Calender.selectThisDay(this)' title='" + now.getFullYear() + "-" + month_temp + "-" + day_temp + "'>" + i + "</a></li>"; 
			} 
			 
		} 
		var j = 1; 
		for (i = thisMonthEndDay; i < 6; i++) {  // Next Month's Date 
			lis += "<li class='nextMonthDate'>" + j + "</li>"; 
			j++; 
		} 
		lis += style; 

		var CalenderTitle = "<a href='javascript:void(0)' class='NextMonth' onclick=Calender.HS_calender(Calender.HS_DateAdd('m',1,'" + now.getFullYear() + "-" + now.getMonth() + "-" + now.getDate() + "'),this) title='Next Month'>&raquo;</a>"; 
		CalenderTitle += "<a href='javascript:void(0)' class='LastMonth' onclick=Calender.HS_calender(Calender.HS_DateAdd('m',-1,'" + now.getFullYear() + "-" + now.getMonth()+"-" + now.getDate() + "'),this) title='Previous Month'>&laquo;</a>"; 
		CalenderTitle += "<span class='selectThisYear'><a href='javascript:void(0)' onclick='Calender.CalenderselectYear(this)' title='Click here to select other year' >" + now.getFullYear() + "</a></span>年<span class='selectThisMonth'><a href='javascript:void(0)' onclick='Calender.CalenderselectMonth(this)' title='Click here to select other month'>" + (parseInt(now.getMonth())+1).toString() + "</a></span>月";  

		if (arguments.length>1) { 
			arguments[1].parentNode.parentNode.getElementsByTagName("ul")[1].innerHTML = lis; 
			arguments[1].parentNode.innerHTML = CalenderTitle; 

		} else { 
			var CalenderBox = style + "<div class='calender'><div class='calenderTitle'>" + CalenderTitle + "</div><div class='calenderBody'><ul class='day'><li>日</li><li>一</li><li>二</li><li>三</li><li>四</li><li>五</li><li>六</li></ul><ul class='date' id='thisMonthDate'>" + lis + "</ul></div><div class='calenderBottom'><a href='javascript:void(0)' class='closeCalender' onclick='Calender.closeCalender(this)'>&times;</a><span><span><a href=javascript:void(0) onclick='Calender.selectThisDay(this)' title='" + todayString + "'>今天</a></span></span></div></div>"; 
			return CalenderBox; 
		} 
	}, 
	selectThisDay :function(d) { 
		var boxObj = d.parentNode.parentNode.parentNode.parentNode.parentNode; 
			boxObj.targetObj.value = d.title; 
			boxObj.parentNode.removeChild(boxObj); 
	}, 
	closeCalender :function(d) { 
		var boxObj = d.parentNode.parentNode.parentNode; 
			boxObj.parentNode.removeChild(boxObj); 
	}, 
	
	CalenderselectYear :function(obj) { 
			var opt = ""; 
			var thisYear = obj.innerHTML; 
			for (i = 2010; i <= 2011; i++) { 
				if (i == thisYear) { 
					opt += "<option value=" + i + " selected>" + i + "</option>"; 
				} else { 
					opt += "<option value=" + i + ">" + i + "</option>"; 
				} 
			} 
			opt = "<select onblur='selectThisYear(this)' onchange='selectThisYear(this)' style='font-size:11px'>" + opt + "</select>"; 
			obj.parentNode.innerHTML = opt; 
	}, 
	selectThisYear: function(obj) { 
		this.HS_calender(obj.value + "-" + obj.parentNode.parentNode.getElementsByTagName("span")[1].getElementsByTagName("a")[0].innerHTML + "-1",obj.parentNode); 
	},
	CalenderselectMonth :function(obj) { 
			var opt = ""; 
			var thisMonth = obj.innerHTML; 
			for (i = 1; i <= 12; i++) { 
				if (i == thisMonth) { 
					opt += "<option value=" + i + " selected>" + i + "</option>"; 
				}else{ 
					opt += "<option value=" + i + ">" + i + "</option>"; 
				} 
			} 
			opt = "<select onblur='selectThisMonth(this)' onchange='selectThisMonth(this)' style='font-size:11px'>" + opt + "</select>"; 
			obj.parentNode.innerHTML = opt; 
	}, 
	selectThisMonth :function(obj) { 
		HS_calender(obj.parentNode.parentNode.getElementsByTagName("span")[0].getElementsByTagName("a")[0].innerHTML + "-" + obj.value + "-1", obj.parentNode); 
	}, 
	HS_setDate :function(inputObj) { 
		var temp1 = inputObj.parentNode;
		var temp2 = inputObj.parentNode.parentNode;
		if(CSS.find("calender", temp1).length == 0) {
			if(CSS.find("calender", temp2).length > 0) {
				var temp = inputObj.parentNode.parentNode.getElementsByTagName("span")[0];
				temp.parentNode.removeChild(temp);
			}
			var calenderObj = document.createElement("span"); 
			calenderObj.innerHTML = this.HS_calender(new Date()); 
			calenderObj.style.position = "absolute"; 
			calenderObj.targetObj = inputObj; 
			inputObj.parentNode.insertBefore(calenderObj,inputObj.nextSibling); 
		}
	},
	close_pop_window :function(evt, target) {
		var currentNode = target;
		var links1 = el('links_ticket');
		var links2 = el('links_hotel');
		var list1 = CSS.find('calender', links1);
		var list2 = CSS.find('calender', links2);
		var list;
		if((list1.length > 0) || (list2.length > 0))
		{
			if(list1.length > 0) {
				list = list1;
			} else {
				list = list2;
			}
			while(currentNode.nodeName.toLowerCase() != 'body') {
				if((currentNode.getAttribute('class') == 'calender') || (currentNode.getAttribute('class') == 'date')) {
					break;
				}
				currentNode = currentNode.parentNode;
			}
			if(currentNode.nodeName.toLowerCase() == 'body') {
				for(var i = 0; i < list.length; i++) {
					var temp = list[i].parentNode;
					list[i].parentNode.parentNode.removeChild(temp);
				}
			}
		}
	},
	close_on_tab_switch :function(tab) {
		if((tab.getAttribute('class') == 'tab-title rel-links_hotel') || (tab.getAttribute('class') == 'tab-title rel-links_ticket')) {
			var delList = CSS.find('calender');
			if(delList.length > 0) {
				for(var i = 0; i < delList.length; i++) {
					var temp = delList[i].parentNode;
					temp.parentNode.removeChild(temp);
				}
			}
		}
	}
};
TAB.add_cb_on_tab_switch(Calender.close_on_tab_switch);

var TUAN = {
	endtime:[],
	append_goods: function(array1, array2) {
		if(!array1) {
			array1 = [];
		}
		for (var i in array2) {
			array1.push(array2[i]);
		}
		return array1;
	},
	change: function() {
		// clear timers
	//	for (var i = 0; i < this.tuantime.length; i++) {
		//	window.clearInterval(this.tuantime[i]);
		//}
		var i;
		window.clearInterval(this.timer);
		var selected = el("tuan_city_input").value;
		var sarray = new Array();
		for (i in tuan_content) {
			if (i == selected) {
				for (var j in tuan_content[i])
					sarray[j] = tuan_content[i][j];
			}
		}
		//  xituan & snnpnn has '全国' content
		if(tuan_content.全国) {
			if (tuan_content.全国 && selected != '全国') {
				if (tuan_content.全国.kangmei) {
					sarray.kangmei = this.append_goods(sarray.kangmei, tuan_content.全国.kangmei);
				}
			}
		}
		// no data of selected city, check input content
		if (this.len(sarray) == 0) {
			if (selected == "") {
				alert("请选择城市");
			} else {
				if (tuan_content.length > 0) { //hack for empty tuangou data
					alert("您查询的城市尚未开通");
				}
			}
			el("tuan_city_input").value = "北京";
			TUAN.change();
			return;
		}
		var res_array = [];
		// one origin tuan website
		if (this.len(sarray) == 1) {
			for (i in sarray) {
				// if there is only one item, show twice
				if (sarray[i].length == 1) {
					res_array.push(sarray[i][0]);
					res_array.push(sarray[i][0]);
				} else {
				// if there are two items or more, randomly select two
					var temp = TUAN.select_two(sarray[i]);
					res_array.push(temp[0]);
					res_array.push(temp[1]);
				}
			}
		}
		// two or more origin tuan websites, 1 is settled, randomly select another of them
		if (this.len(sarray) >= 2) {
			var sarray = this.select_two_origin(sarray);
			for (var i in sarray) {
				if (this.len(sarray[i]) == 1) {
					res_array.push(sarray[i][0]);
				} else {
				// if there are two items or more, randomly select one
					var temp = this.select_one(sarray[i]);
					res_array.push(temp);
				}
			}
		}
		this.show_items(res_array);
	},
	len: function(ori) {
		var l = 0, i;
		for (i in ori) {
			if(ori[i] != null)
				l++;
		}
		return l;
	},
	select_one: function(ori) {
		var temp = this.random_num(this.len(ori));
		return ori[temp];
	},
	select_two: function(ori) {
		var res = [];
		var temp = this.random_num(ori.length);
		res.push(ori[temp]);
		ori.splice(temp, 1);
		res.push(this.select_one(ori));
		return res;
	},
	select_two_origin: function(ori) {
		var res = [];
		var w = [];
		// init show posibilities 
		var ow1 = { 'meituan':40, 'juqi':15, 'wowotuan':15, 'qunar':15 };
		var ow2 = { 'lashou':40, 'jumei':15, 'manzuo':15, 'gaopeng':15 }
		var aw1 = 0;
		var aw2 = 0;
		//init select_sign
		for (var i in ori) {
			if (ow1[i]) {
				aw1 += ow1[i];
			}
			if (ow2[i]) {
				aw2 += ow2[i];
			}
		}
		var ran = Math.random();
		var temp = 0; //count w[i]
		for (var i in ori) {
			if (ow1[i]) {
				temp += ow1[i]/aw1;
				if (ran <= temp) {
					res.push(ori[i]);
					break;
				}
			}
		}
		ran = Math.random();
		for (var i in ori) {
			if (ow2[i]) {
				temp += ow2[i]/aw2;
				if (ran <= temp) {
					res.push(ori[i]);
					break;
				}
			}
		}
		return res;
	},
	random_num: function(seed) {
		var temp = seed * Math.random();
		temp = Math.floor(temp);
		var res = 0;
		if (temp < seed) {
			res = temp;
		} else {
			res = temp - 1;
		}
		return res;
	},
	show_items: function(items) {
		var tuanChilds = el('tuan').childNodes;
		var rmlist = new Array();
		var i;
		for (i = 0; i < tuanChilds.length; i++) {
			if (tuanChilds[i].nodeType == 1) {
				rmlist.push(tuanChilds[i]);
			}
		}
		for (i = 0; i < rmlist.length; i++) {
			el('tuan').removeChild(rmlist[i]);
		}
		if(this.endtime) {
			var endtime_len = this.endtime.length;
			for (i = 0; i < endtime_len; i++) {
				this.endtime.pop();
			}
		}
		for (i = 0; i < items.length; i++) {
			var content = "";
			var dstring;
			var endtime;
			if (items[i].origin != "火狐") {
				if ((items[i].origin == "上品")||(items[i].origin == "美容团")||(items[i].origin == "去哪儿")) {
					var reg = /(\d+)\-(\d+)\-(\d+)\w(.*)\+\d+:\d+/;
					endtime = items[i].endtime.replace(reg, '$1/$2/$3 $4');
					var temp = new Date(endtime);
					dstring = temp.toString();
				} else {
					endtime = items[i].endtime;
					var temp = new Date();
					temp.setTime(endtime*1000);
					dstring = temp.toString();
				}
			}
			var tuan_img = '"' + items[i].img + '"';
			var tuan_url = '"' + items[i].url + '"';
			content += "<div class='tuan_content'>\n";
			content += "<div class='tuan_pic'>\n";
			content += "<a target='_blank' href=" + tuan_url + ">\n";
			content += "<img alt='' src=" + tuan_img + "/>\n"
			content += "</a>\n";
			if (items[i].origin != "火狐") {
				content += "			<span class='tuan_time'></span>\n";
			} else {
				content += "			<span class='tuan_time_special'></span>\n";
			}
			content += "</div>\n";
			content += "<div class='tuan_right'>\n";
			content += "<div class='price'>\n";
			content += "<strong style='text-decoration:line-through;'>￥" + items[i].value + "</strong>\n";
			content += "<span>￥" + items[i].price + "</span>\n";
			content += "</div>\n";
			content += "<div class='des'>";
			content += "<a target='_blank' href=" + tuan_url + ">" + items[i].description + "</a>\n";
			content += "</div>\n";
			content += "<div class='price_tag'>\n";
			content += "<a target='_blank' href=" + tuan_url + ">\n";
			content += "<strong>￥" + items[i].price + "</strong>\n";
			content += "</a>\n";
			content += "</div>\n";
			content += "</div>\n";			
			content += "</div>\n";			
			
			el('tuan').innerHTML += content;
			//TUAN.tuan_time(dstring, i);
			if (items[i].origin != "火狐") {
				this.endtime.push(dstring);
			}
		}
		if(CSS.find("tuan_time_special").length > 0) {
			var temp = CSS.find("tuan_time_special")[0];
			temp.innerHTML = "火狐商店官方团购，超值优惠！";
		}
		TUAN.tuan_time();
	},
	enterkey: function(e) {
		var keynum;
		if(window.event) { // IE
			keynum = e.keyCode;
		}
		else if(e.which) { // Netscape/Firefox/Opera
			keynum = e.which;
		}
		if(keynum == 13) {
			this.change();
		}
	},
	tuan_time: function() {
		this.timer = setInterval(function() {
			var round;
			for (round = 0; round < TUAN.endtime.length; round++) {
				var ld = new Date(TUAN.endtime[round]);
				var today = new Date();
				var lround = 0;
				var dis = ld.getTime() - today.getTime();
				var day = Math.floor(dis/(24*3600*1000)); 
				var tnum = dis%(24*3600*1000);
				var h = Math.floor(tnum/(3600*1000)); 
				tnum = tnum%(3600*1000);
				var m = Math.floor(tnum/(60*1000)); 
				tnum = tnum%(60*1000);
				var s = Math.floor(tnum/1000);
				var temp = el("tuan").getElementsByTagName("span");
				for (var i = 0; i < temp.length; i++) {
					if (temp[i].className == "tuan_time") {
						if(lround == round) {
							temp[i].innerHTML = "剩余 " + day + "天" + h + "小时" + m + "分" + s + "秒";
							lround++;
						} else {
							lround++;
						}
					}
				}
			}
		}, 500);
	}
};

document.addEventListener('mousemove', PANEL.moving(), true);
document.addEventListener('mouseup', PANEL.release(), true);
function do_click(node) {
    var evt = document.createEvent('MouseEvents');
    evt.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
	// hack for ie6
	if(window.XMLHttpRequest) {
		node.dispatchEvent(evt);
	} else {
		node.click();
	}
}

function body_onclick(evt) {
    trace_link(evt);
}

function trace_link(evt) {
    var target = evt.target || evt.srcElement;
    if (evt.button == 0) {
		Calender.close_pop_window(evt, target);
        if (target.nodeName.toLowerCase() == 'a') {
            LINKTRACE.trace(evt, target);
        } else if (target.parentNode && target.parentNode.nodeName.toLowerCase() == 'a') {
            LINKTRACE.trace(evt, target.parentNode);
        }
    }    
}

function el(id) { return document.getElementById(id); }
function log(msg) {
    var ll = el('log');
    var p = document.createElement('p');
    p.appendChild(document.createTextNode(new Date() + ': ' + msg));
    ll.appendChild(p);
}

/* Reload half an hour, set a cookie to identify it is a refresh */
window.setTimeout(function() {
	var req = new XMLHttpRequest();
	var refresh = 'http://' + window.location.host + '/static/refresh.gif' + '?' + Math.random();
	req.open('GET', refresh, true);
	req.onreadystatechange = function () {  
		if (req.readyState == 4) {  
			if((req.status == 200)) {
				var search = window.location.search;
				if (search.length > 1) {
					search = search.substring(1).split('&');
					search.push('rv=1');
					search = '?' + search.join('&');
				} else {
					search = '?rv=1';
				}
				window.location.href = [window.location.protocal, '//', window.location.host, window.location.pathname, search].join('');
			}
		}   
	};  
	req.send(null);
}, 1000 * 1800 );

