///////////////////////////////////////////////////////////////////////////////////////////////////
//对javascript的封装部分(没有使用jquery)
///////////////////////////////////////////////////////////////////////////////////////////////////
//URL编码、解码函数
function $EN(s)	{return encodeURIComponent(s);}
function $DE(s)	{return decodeURIComponent(s);}

//浏览器特性(宽度等)
var ABBrowser = {
	navi: navigator.userAgent.toLowerCase(),
	isIE: function(){
		return (this.navi.indexOf("msie") != -1) && (this.navi.indexOf("opera") == -1) && (this.navi.indexOf("omniweb") == -1);
	},
	getBody: function(){
		return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
	},
	getScrollTop: function(){
		return this.isIE()?this.getBody().scrollTop:window.pageYOffset;
	},
	getScrollLeft: function(){
		return this.isIE()?this.getBody().scrollLeft:window.pageXOffset;
	},
	getAvailableHeight:function(){
		return this.getBody().offsetHeight>this.getBody().scrollHeight?this.getBody().offsetHeight:this.getBody().scrollHeight;
	},
	getAvailableWidth: function(){
		return this.getBody().offsetWidth>this.getBody().scrollWidth?this.getBody().offsetWidth:this.getBody().scrollWidth;        
	},
	getViewWidth: function(){
		return self.innerWidth || (document.documentElement.clientWidth || document.body.clientWidth);
	},
	getViewHeight: function(){
		return self.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight);
	},
	getPointerPositionInDocument:function(evt){
		var eventObject = evt;
		var x = eventObject.pageX || (eventObject.clientX+ABBrowser.getBody().scrollLeft);
		var y = eventObject.pageY || (eventObject.clientY+ABBrowser.getBody().scrollTop);
		return {'x':x,'y':y};
	},
	getElementPosition: function(ebj){
		if(typeof ebj.offsetParent != "undefined"){
			for(var _x = 0, _y = 0; ebj; ebj = ebj.offsetParent) {
				_x += ebj.offsetLeft;
				_y += ebj.offsetTop;
			}
			return {"x":_x,"y":_y};
		}
		else{
			return {"x":_x,"y":_y};
		}
	}
};

///////////////////////////////////////////////////////////////////////////////////////////////////
//Jquery插件部分
///////////////////////////////////////////////////////////////////////////////////////////////////
/*
来源：	http://plugins.jquery.com/files/jquery.cookie.js.txt
功能：	cooke的读、写、删
写：		$.cookie('key', 'value');	默认保存30天
		$.cookie('key', 'value', {expires:5});	保存5天
		$.cookie('key', 'value', {expires:0});	关闭浏览器则删除
读：		$.cookie('key');
删：		$.cookie('key', null);
*/
jQuery.cookie = function(name, value, options) {
	var defaultExpires = 30;		//***默认过期时间为30天
	var defaultPath = '; path=/';	//***默认设为根目录
	var defaultDomain = '; domain=' + GConfig.domainCookie();//***默认设为abang.com
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if(String(options.expires) == 'undefined') options.expires = defaultExpires;//***
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : defaultPath;//****修改
        var domain = options.domain ? '; domain=' + (options.domain) : defaultDomain;//****修改
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', $EN(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = $DE(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

///////////////////////////////////////////////////////////////////////////////////////////////////
//OOP 支持部分
///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////
//与我们业务相关的部分
///////////////////////////////////////////////////////////////////////////////////////////////////
/*
功能：全局的变量部分
*/
var GConfig = {
	domainAibang:'',		//爱帮的域名，用途：在公交域下跳转到爱帮域下使用，所以在公交域下的页面要对该变量赋值
	domainBus:'',			//公交的域名，用途：在爱帮域下跳转到公交域下使用，所以在爱帮域下的页面要对该变量赋值
	domainCookie:function(){//记录cookie的域名
		//两种情况：1、线上，都是用aibang.com域；2、测试环境使用当前域
		var domainInner = '';
		if((document.domain).indexOf('aibang.com') == -1) domainInner = "";
		else domainInner =  "aibang.com";
		//一次性计算函数
		this.domainCookie = function(){
			return domainInner;
		}
		return domainInner;
	},
	isCityDomain: function(){
		var arr = ["beijing","shanghai","tianjin","chongqing",
		"hefei","fuzhou","guangzhou","nanning",
		"guiyang","lanzhou","haikou","shijiazhuang",
		"zhengzhou","wuhan","changsha","haerbin",
		"changchun","nanjing","nanchang","shenyang",
		"huhehaote","taiyuan","xian","jinan",
		"chengdu","wulumuqi","kunming","hangzhou",
		"shenzhen","xiamen","ningbo","qingdao",
		"dalian","suzhou"];
		for(var i =0; i<arr.length; i++){
			if(location.hostname.indexOf(arr[i]) == 0)
				return true;
		}
		return false;
	},
	channel: '',		//当前所在的频道：act，mov，traffic，discount，bizsearch，exp，face
	//获取/设置(城市、Addr、What)
	getCity: function(){
		if(PConfig && PConfig.city) return PConfig.city;
		return $.cookie('city');
	},
	setCity: function(){
		
	},
	getAddr: function(){
		
	},
	setAddr: function(){
		
	},
	getWhat: function(){
		
	},
	setWhat: function(){
		
	}
};

/*
功能：发送统计请求
格式：/files/StatUrl.html?randcode=&sid=&frm=&turl=&ln=&pn=
*/
var Log = {
	run: function(frm, objLink, lineNum, pageNum){
		var randCode = (new Date()).getTime() + (Math.random()*9 + 1);
		var cookie = $.cookie('PHPSESSID');
		var objImage = new Image();
		
		var srcImage = "/files/StatUrl.html?randcode="+randCode+"&sid="+cookie+"&frm="+frm;
		if(objLink){
			var hrefLink = $(objLink).attr("href");
			if(hrefLink) srcImage += "&turl=" + $EN(hrefLink);
		}
		if(lineNum && pageNum){
			srcImage += "&ln="+lineNum+"&pn="+pageNum;
		}
		
		objImage.src = srcImage;
		return true;
	}
};

/*
功能：全局锁
*/
var Lock = {
	lock: function(){
		
	},
	unlock: function(){
		
	}
};

/*
爱帮通用头部分
*/
var Head = {
	_homeUrl: 'http://www.aibang.com',
	homepage: function(objIn){//设为首页
		try{
			objIn.style.behavior='url(#default#homepage)';
			objIn.setHomePage(this._homeUrl);
		}
		catch(e){alert("您现在使用的浏览器无法自动设为首页，请手动设置！");}
	},
	addFavorite: function(){//添加为收藏
		var url = this._homeUrl;
		var title = "爱帮 - 中国最大的生活搜索引擎 - 生活黄页 - 本地搜索 - 打折优惠 - 公交查询 - 城市指南";
		if (window.sidebar) window.sidebar.addPanel(title, url, "");
		else if( document.all ) window.external.AddFavorite(url, title);
		else if( window.opera && window.print ) return true;
	},
	loginOrOut: function(type, fromURL){//登陆或者退出，通过formURL可以设置登陆后到达一个新的页面
		fromURL = fromURL?$EN(fromURL):$EN(location.href);
		if("login" == type) location.href = GConfig.domainAibang+"/?area=user&cmd=showlogin&backurl="+fromURL;
		else if("logout" == type) location.href = GConfig.domainAibang+"/?area=user&cmd=logout&backurl="+fromURL;
		else if("getpwd" == type) window.open(GConfig.domainAibang+"/?area=user&cmd=showlogin&gpwd=1&backurl="+fromURL,"_blank");
	}
};

var Channel={
	init:function(){
		var _nav = document.getElementById("Nav");
		if(!_nav) return;
		var _navLi = _nav.getElementsByTagName("LI");
		if(!_navLi) return;
		
		var _navLiLen = _navLi.length;
		for(var i = 0; i < _navLiLen; i++){
			if(_navLi[i].className == "sel") continue;
			if(_navLi[i].id == "nav_wap") continue;
			var tmp = _navLi[i];
			if($(tmp).attr('id') == 'morechannel'){//临时解决
				continue;
			}
			$(tmp).bind('mouseover', function(event){
				event.target.className = "over";
			});
			$(tmp).bind('mouseout', function(event){
				event.target.className = "";
			});
			//
			$(tmp).children("a:first-child").bind('mouseover', function(event){
				event.target.parentNode.className = "over";
			});
			$(tmp).children("a:first-child").bind('mouseout', function(event){
				event.target.parentNode.className = "";
			});
		}
	}
};
$(function(){Channel.init()});

/*
切换城市
*/
var ChangeCity={
	_init: function(){//绑定事件
		$(document).bind('mouseup', this._hide);//鼠标click/mouseup时隐藏切换城市
		$(".hotcitylist a:lt(20)").bind('click', this._run);//点击各个城市
		$("#msgBak .hotcitylist a:lt(20)").bind('click', this._run);//点击各个城市
		delete this._init;
	},
	show: function(msgId){
		if(this._init) this._init();
		if($("#"+msgId).css('display') != 'none') $("#"+msgId).hide();
		else $("#"+msgId).show();
	},
	_hide: function(event){
		if(event.target==document.getElementById('changecitysearch') || event.target==document.getElementById('changecityhead')) return;
		$("#msg").hide();
		$("#msgBak").hide();
	},
	registerChangeCityFun: function(channel, fun){//注册各个频道的切换城市的url
		if(!this._arrChannelUrl) this._arrChannelUrl = [];
		this._arrChannelUrl[channel] = fun;
	},
	_run: function(event){//执行切换城市
		var city = $(event.target).html();
		if($('#city3')) $('#city3').html(city);
		$.cookie('addr', null);
		$.cookie('city', city);
		
		//获得切换城市后的url
		var urlNew = '/';
		if(	GConfig.channel &&
			this._arrChannelUrl &&
			this._arrChannelUrl[GConfig.channel])
			urlNew = this._arrChannelUrl[GConfig.channel](city);
		open(urlNew, "_self");
		return false;
	},
	moreCity: function(){//这个函数需要改
		open("/files/MoreCity1.html?tag=index", "_blank");
	}
};

/*
功能：页面跳转，实现爱帮内部页面的跳转
*/
var JumpUrl={
	run:function(objParas){
		if(!objParas || !objParas['area']) return;
		switch(objParas['area']){
			case 'search': this._search(objParas); break;
		}
	},
	_search: function(objParas){
		var city = $EN(objParas['city']);
		var addr = $EN(objParas['addr']);
		var what = $EN(objParas['what']);
		var target = '_self';
		if(objParas['isBlank']) target = '_blank';
		var url =  "/?area=bizsearch&cmd=bigmap&city="+city+"&a="+addr+"&q="+what;
		/*if(ABBrowser.isIE()) setTimeout(function(){open(url, target)}, 0);
		else */
		
		open(url, target);
		//if(event) cancelEvent(event);
	}
};

/*
功能：地址提示、关键字提示、城市提示
注明：	1、为了兼容老的代码，增加了几个全局函数，兼容老的
		2、内部代码比较混乱，需要整理
		3、ajax在IE上abort异常！
*/
function mouseOutDiv(obj){
	obj.className = '';
}

function mouseOverAddr(obj){
	var oA = document.getElementById("address_drop").getElementsByTagName("a");
	var totalResultNum = oA.length;
	for(var i=0; i<totalResultNum-1; i++){
		if(oA[i] == obj){
			Suggest.curPosition = i;
			oA[i].className = 'drop_item';
		}
		else{
			oA[i].className = '';
		}
	}
}

function locate(type,addr,grid,mapxy,radius){
	Suggest.curInput.value = addr;
	Suggest.cancel();
}

function selectKeyword(what){
	Suggest.curInput.value = what;
	var jumpParas = {};
	jumpParas['area'] = 'search';
	jumpParas['city'] = PConfig.city;
	jumpParas['addr'] = $('#addr').attr('value');
	if(jumpParas['addr'] == '输入地点,默认全市') jumpParas['addr'] = '全市';
	jumpParas['what'] = what;
	JumpUrl.run(jumpParas);
}

var Suggest={
	curPosition: -1, //initial is -1
	totalResultNum: 0, //initial is 0
	add:function(addId, urlPath, mode, s){
		if(!$('#'+addId) || !urlPath || !mode) return false;
		if(this.init) this.init();
		//对需要提示的对象绑定事件
		$('#'+addId).bind('keyup', this.showSuggest);
		$('#'+addId).bind('keydown', this.selectSuggest);
		//记录obj=>(urlPath, mode)三元组
		if(!this.objInfo) this.objInfo = new Object();
		this.objInfo[addId] = {
			'path': urlPath,
			'mode': mode,
			's': s
		};
		return true;
	},
	selectSuggest: function(event){
		//对输入条件进行验证：只响应up、down两个键
		if(event.keyCode!=38 && event.keyCode!=40) return;
		Suggest.totalResultNum = $('#address_drop a').length;
		if(!Suggest.totalResultNum) return;
		if(document.getElementById('address_drop').style.display=='none') return;
		
		//真正响应
		Suggest.curInput = event.target;
		var target = event.target;
		var oA = document.getElementById('address_drop').getElementsByTagName("a");
		var oS = document.getElementById('address_drop').getElementsByTagName("input");
		var e = event;
		if(e.keyCode == 38){//up
			Suggest.curPosition -= 1;
			if(Suggest.curPosition <= -1){//is top
				Suggest.curPosition = Suggest.totalResultNum-2;//except close tip
				oA[0].className = ''; //release top style
			}
			else{
				oA[Suggest.curPosition+1].className = '';//release pre style
			}
			//reset now
			//oS is address suggestion
			//oA is keyword suggestion
			target.value = oS[Suggest.curPosition] ? oS[Suggest.curPosition].name : oA[Suggest.curPosition].innerHTML;           
			oA[Suggest.curPosition].className = 'drop_item'; 
		}
		else if(e.keyCode == 40){//down
			Suggest.curPosition += 1;
			if(Suggest.curPosition >= Suggest.totalResultNum-1){            
				oA[Suggest.curPosition-1].className = '';
				Suggest.curPosition = 0;
			}
			else if(Suggest.curPosition > 0){
				oA[Suggest.curPosition-1].className = '';//release pre style
			}
			//reset now
			target.value = oS[Suggest.curPosition] ? oS[Suggest.curPosition].name : oA[Suggest.curPosition].innerHTML;           
			oA[Suggest.curPosition].className = 'drop_item';
		}
	},
	showSuggest: function(event){
		//获得输入
		Suggest.curInput = event.target;
		var target = $(event.target);
		var targetId = target.attr('id');
		var path = Suggest.objInfo[targetId]['path'];
		var mode = Suggest.objInfo[targetId]['mode'];
		var s = Suggest.objInfo[targetId]['s'];
		var city = (PConfig&&PConfig.city)?(PConfig.city):(Config.city());
		var query = target.attr('value');
		if(!path || !mode || !city || !query){
			Suggest.cancel();
			return;
		}
		
		//对keydown的键进行检查
		if(event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 ){//Tab Tab、Left、Right
			return;
		}
		else if(event.keyCode == 13){//回车
			Suggest.cancel();
			return;
		}
		else if(event.keyCode == 38 || event.keyCode == 40){//Up、Down
			return;
		}
		
		//拼接url，发送Ajax请求
		var url = "/"+path+"?mode="+mode+"&s="+s+"&n=10&rc=1&city="+$EN(city)+"&key="+$EN(query);
		try{
			if(Suggest.hAjax && Suggest.hAjax.abort){
				Suggest.hAjax.abort();
				Suggest.hAjax = null;
			}
		}
		catch(gError){}
		
		Suggest.hAjax = $.get(url, Suggest.ajaxSuccess);

		//保存本次出发该事件的对象
		Suggest.targetId = targetId;
	},
	ajaxSuccess: function(retHtml){
		var target = document.getElementById(Suggest.targetId);
		if(retHtml && $(retHtml).length>1 ){
			Suggest.objContainer.html("<div id='ssss'>"+retHtml+"</div>");
		}
		else{
			Suggest.objContainer.html('');
		}
		var objInput = ('#address_drop input');
		var objSSSS = document.getElementById('ssss');
		if(objSSSS){
			var __height = objSSSS.clientHeight;
			__height = __height?__height:18*(objInput.length);
			//document.getElementById('adir').style.height = __height+'px';
		}
		if(retHtml){
			var objContainer = document.getElementById('address_drop');
			var oStyle = objContainer.style;
			if( objContainer.style.display == "none"){
				oStyle.left = "-1000px";
			}
			$(objContainer).show();

			var input = target;
			var t = target.offsetTop,  h = target.clientHeight, l = target.offsetLeft, p = target.type;
			var hasAbsoluteTarget = false;
			while (target = target.offsetParent){
				t += target.offsetTop; 
				l += target.offsetLeft;
				if(ABBrowser.isIE()){
					var _pl = target.style.paddingLeft;
					_pl = _pl ? parseInt(_pl,10) : 0;
					
					var _pt = target.style.paddingTop;
					_pt = _pt ? parseInt(_pt,10) : 0;
					
					var _bl = target.style.borderLeft;
					_bl = _bl ? parseInt(_bl,10): 0;
					
					var _bt = target.style.borderTop;
					_bt = _bt ? parseInt(_bt,10) : 0;
					
					var _ml = target.style.marginLeft;
					_ml = _ml ? parseInt(_ml,10) : 0;
					
					var _mt = target.style.marginTop;
					_mt = _mt ? parseInt(_mt,10) : 0;

					var _tmp_l = _pl + _bl + _ml;
					var _tmp_t = _pt + _bt + _mt;

					if("msg_addr_down" == target.id){
						hasAbsoluteTarget = true;
					}
					t -= _tmp_t;
					if(!hasAbsoluteTarget){
						l -= _tmp_l;
					}
				}
				var cw = input.offsetWidth;
				var ch = objSSSS.offsetHeight;
				var dw = ABBrowser.getViewWidth(), dl = ABBrowser.getScrollLeft(), dt = ABBrowser.getScrollTop();
				if (ABBrowser.getViewHeight() + dt - t - h >= ch){ 
					oStyle.top = ((p=="image")? t + h : t + h + 6)+"px";
				}
				else {
					oStyle.top  = ((t - dt < ch) ? ((p=="image")? t + h : t + h + 6) : t - ch-2)+"px";
				}
				if (dw + dl - l >= cw) {
					oStyle.left = l+"px"; 
				}
				else{
					oStyle.left = ((dw >= cw) ? dw - cw + dl : dl)+"px";
				}
			}
		}
		else{
			Suggest.cancel();
		}                            
		Suggest.curPosition = -1;
		Suggest.totalResultNum = 0;
	},
	init:function(){
		//创建suggest container
		this.objContainer = $('<div id="address_drop"></div>').appendTo($(document.body));
		//以下3种情况要取消提示：1、隐藏提示；2、取消ajax
		$(document).bind('click',	this.cancel);
		$(document).bind('mouseup',	this.cancel);
		$(document).bind('keydown',	function(event){if(event.keyCode == 9) Suggest.cancel();});
		delete this.init;
	},
	cancel: function(){
		//1、隐藏；2、清空；3、取消Ajax
		Suggest.objContainer.hide();
		//Suggest.objContainer.html('');
		try{
			if(Suggest.hAjax && Suggest.hAjax.abort){
			Suggest.hAjax.abort();
			}
		}
		catch(gError){}
	}
};