/*
 * City list for Js 
 * Update 20090520
 * 
 */
function ht_getcookie(name) {
	var cookie_start = document.cookie.indexOf(name);
	var cookie_end = document.cookie.indexOf(";", cookie_start);
	return cookie_start == -1 ? '' : unescape(document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end : document.cookie.length)));
}
function ht_setcookie(cookieName, cookieValue, seconds, path, domain, secure) {
	var expires = new Date();
	expires.setTime(expires.getTime() + seconds*1000);
	document.cookie = escape(cookieName) + '=' + escape(cookieValue)
		+ (expires ? '; expires=' + expires.toGMTString() : '')
		+ (path ? '; path=' + path : '/')
		+ (domain ? '; domain=' + domain : '')
		+ (secure ? '; secure' : '');
}
	

//var cities='@Beijing|北京|1100@Shanghai|上海|3100@Hangzhou|杭州|3301@Suzhou|苏州|3205@Nanjing|南京|3201@Wuxi|无锡|3202@Tianjin|天津|1200@Chengdu|成都|5101@Chongqing|重庆|5000@Xian|西安|6101@Wuhan|武汉|4201@Zibo|淄博|3703@Hefei|合肥|3401@Jinan|济南|3701@Fuzhou|福州|3501@Dalian|大连|2102@Nanning|南宁|4501@Guilin|桂林|4503@Shenyang|沈阳|2101@Taiyuan|太原|1401@Wuhu|芜湖|3402@Yiwu|义乌|3307@Zhengzhou|郑州|4101@Changchun|长春|2201@Changsha|长沙|4301@Guangzhou|广州|4401@kunshan|昆山|3214@Ningbo|宁波|3302@Xiamen|厦门|3502@Nantong|南通|3206@Taizhou|泰州|3212@Changzhou|常州|3204@Haerbin|哈尔滨|2301@Qingdao|青岛|3702@Shenzhen|深圳|4403@Yangzhou|扬州|3210@Zhenjiang|镇江|3211@Shijiazhuang|石家庄|1301@Putian|莆田|3503@';

var array_cities = [];//完整城市列表
var array_cities_filter=[];//当前搜索结果
var array_cities_showing=[];//显示中的城市
var sugSelectItem= 0 ;//选中项目
var sugSelectTurn= 0 ;//显示中选中项的序号
var citySelected =0;//选中城市[SHIJIAZHUANG, 石家庄, 1301]
var cityfield_focused=false;//输入框是否获得焦点
var mousedownOnPanel=false;//鼠标按在菜单上
var curPageIndex=0;//当前分页序号
var curObj=null; //当前作用对象

//分拆城市信息
var cities = cities.split('@'); 
var favcityID = ht_getcookie("hj_favcity");
for(var i=0; i<cities.length; i++){
	var titem = cities[i];
	if(titem.length>0){
		titem = titem.split('|'); 
		if(favcityID!="" && titem[2]== favcityID){
			favcity = titem;
			array_cities.unshift(titem);
			//当fav城市位于第一页时，避免重复显示
			if(i>8){
				array_cities.push( titem );
			}
		}else{array_cities.push( titem );}
	}
}
for(var i=0; i<array_cities.length; i++){array_cities[i].push(i);}
//显示给定的城市列表片段
function city_Bind(acitylist){ 
	if(acitylist.length==0)
		return;
	var tHtml = "";
	$.each(
		acitylist,
		function(aIndex){ 
			if(favcityID == acitylist[aIndex][2] )
				tHtml+= "<div class='cityline'  id='citem_"+ aIndex +"' cturn='"+ acitylist[aIndex][3] +"'><span class='lalign'><b>"+ acitylist[aIndex][0] +"</b></span><span class='ralign'><b>"+ acitylist[aIndex][1] +"</b></span></div>\n";
			else
				tHtml+= "<div class='cityline'  id='citem_"+ aIndex +"' cturn='"+ acitylist[aIndex][3] +"'><span class='lalign'>"+ acitylist[aIndex][0] +"</span><span class='ralign'>"+ acitylist[aIndex][1] +"</span></div>\n";
		}
	);
	$('#panel_cities').html(tHtml);
	$('.cityline').mouseover(
		function(){city_shiftSelect(this);}
	).click(
		function(){city_confirmSelect();}
	); 
	city_shiftSelect( $("#citem_0"));
}
//移动当前选中项
function city_changeSelectIndex(aStep){
	var asugSelectTurn = sugSelectTurn + aStep;
	if(asugSelectTurn ==-1){ 
		city_showlist(curPageIndex -1); 
		city_shiftSelect( $("#citem_"+ (array_cities_showing.length-1) ));
	}else if (asugSelectTurn== array_cities_showing.length){ 
		city_showlist(curPageIndex +1);
		city_shiftSelect( $("#citem_0" ));
	}else{
		city_shiftSelect( $("#citem_"+ asugSelectTurn ));
	}
}
//确认选择
function city_confirmSelect(){
	curObj.val( citySelected[1] );
//	ht_setcookie("hj_favcity", citySelected[2], 99999);
//	ht_setcookie("hj_favcityname", citySelected[1], 99999);
	$("#form_cities").css("display","none");
//	if( $("#beginDate").val().length==0 ){
//	    $("#beginDate").focus();
//	}
}
//指定新的选中项，恢复旧项
function city_shiftSelect(atarget){
	if(sugSelectItem!=atarget){
		if(sugSelectItem !=0)
			$(sugSelectItem).removeClass('citylineover').addClass('cityline').css("backgroundColor", "white");
		if(atarget!=0){
			try{
				sugSelectItem = atarget;
				var city_j = $(sugSelectItem).removeClass('cityline').addClass('citylineover').css("backgroundColor", "#f1f1f1"); 
				sugSelectTurn = Number(city_j.attr('id').split("_")[1]);
				citySelected = array_cities[ Number(city_j.attr('cturn'))]; 
				$("#cityid").val( citySelected[2] );
			}catch(e){}
		}
	}
}
//搜索符合关键字的城市
function filterCity(aKeyword){
	if(aKeyword.length==0){ 
		$("#top_cities").html( "输入中文/拼音或↑↓选择.");
		return array_cities;
	}
	var aList = [];
	var isPinyin = /[^A-z]/.test( aKeyword );
	for(var i=0; i<array_cities.length; i++){
		if( isMatchCity(array_cities[i], aKeyword, isPinyin ))
			aList.push( array_cities[i]);
	}
	if(aList.length>0){
		$("#top_cities").html("按“<font color=red>"+ aKeyword +"</font>”字符检索：");
		return aList;
	}else{
		$("#top_cities").html("对不起，找不到：<font color=red>"+ aKeyword +"</font>"); 
		return [];
	}
}
function replaceChar(astring ,aindex, Char){ 
	return astring.substr(0, aindex) + Char+ astring.substr(aindex+1, astring.length-1);
}
//判断某城市是否符合搜索条件,只要拼音或中文顺序包含排列关键词字符元素即可
function isMatchCity(aCityInfo, aKey, aisPinyin){
	var aKey = aKey.toLowerCase();
	var aInfo = [aCityInfo[0].toLowerCase(), aCityInfo[1]];
	//aCityInfo [shanghai, 上海, 1202]
	//是否含有汉字
	var lastIndex = -1;
	if(aisPinyin){
		aKey = aKey.split("");
		for(var m=0; m< aKey.length; m++){
			var newIndex = aInfo[1].indexOf( aKey[m] );
			if(newIndex>lastIndex){ 
				aInfo[1]= replaceChar(aInfo[1], newIndex,"-"); 
				lastIndex= newIndex; 
			}else{
				return false;
			}
		}
	}else{ //处理拼音的
		aKey = aKey.split("");
		for(var m=0; m< aKey.length; m++){
			var newIndex = aInfo[0].indexOf( aKey[m]);
			
			// alert(aInfo[0]);
			if(newIndex>lastIndex && newIndex<=m){
				aInfo[0]= replaceChar(aInfo[0], newIndex, "-"); 
				lastIndex= newIndex; 
			}else{
				return false;
			} 
		}
	}
	return true;
}

//显示当前城市列表中的指定分页
function city_showlist(aPageNo){ 
	if(array_cities_filter.length>8){ 
		//取分页数据
		var pagecount = Math.ceil((array_cities_filter.length+1)/8);
		if(aPageNo==-1) 
			aPageNo = (pagecount-1)
		else if(aPageNo==pagecount) 
			aPageNo = 0;  
		array_cities_showing = array_cities_filter.slice(8*(aPageNo),  Math.min(8*(aPageNo+1), array_cities_filter.length) );
		city_Bind( array_cities_showing );
		//翻页控制
		var flipHtml = (aPageNo==0)?"&laquo;上一页":"<a href='' class='cityflip' onclick='city_showlist("+(aPageNo-1)+");return false;'>&laquo;上一页</a>";
		flipHtml += "&nbsp;&nbsp;&nbsp;&nbsp;"+  "&nbsp;&nbsp;&nbsp;&nbsp;"+ "&nbsp;&nbsp;&nbsp;&nbsp;";
		flipHtml += (aPageNo==pagecount-1)?"下一页&raquo;":"<a href='' class='cityflip' onclick='city_showlist("+(aPageNo+1)+");return false;'>下一页&raquo;</a>";
		$("#flip_cities").html(flipHtml);
		$("#flip_cities").css("display", "block");
	}else{  
		aPageNo=0;
		array_cities_showing = array_cities_filter;
		city_Bind( array_cities_showing );
		$("#flip_cities").css("display", "none");
	}
	curPageIndex = aPageNo;
	if( $("#form_cities").css("display")=="block" ) curObj.focus();
}



//页面初始化
$(document).ready(
	function(){
		//空条件过滤出所有城市列表
		array_cities_filter = filterCity("");
		city_showlist(0);
//站站搜索
		$("#txtchufa").keydown(
			function(aevent){
				curObj = $("#txtchufa");
				aevent= aevent||window.event;
				
			//	alert(aevent.keyCode);
				
				if(aevent.keyCode==40){
					city_changeSelectIndex( 1 );
					$("#form_cities").css("display","block");	
					SetISPos($("#txtchufa")); 
				}else if(aevent.keyCode==38){
					city_changeSelectIndex( -1 ); 
					$("#form_cities").css("display","block");	
					SetISPos($("#txtchufa"));  
					
				
				}else if( aevent.keyCode==13){
					
					    city_confirmSelect();
				 
				 				
				        if(document.addEventListener){//如果是Firefox
							document.addEventListener("keypress",myHandlerFg, true);
					
				         }else{
						//document.onkeypress=submitDefault;//如果是IE
					 	evt = window.event;
						 evt.keyCode=9
						
                      //  evt.returnValue=false;//屏蔽IE默认处理

					 }

				
				
				} 
			}
		).focus(
			function(){
				curObj = $("#txtchufa");
				cityfield_focused = true;
				city_shiftSelect( $("#citem_0" ));
				$("#form_cities").css("display","block");
				SetISPos($("#txtchufa"));  
			}
		).blur(
			function(){
				curObj = $("#txtchufa");
				if(!mousedownOnPanel){
					cityfield_focused = false;
					$("#form_cities").css("display","none");
				}	
			}
		).keyup( 
			function(aevent){
				curObj = $("#txtchufa");
				aevent= aevent||window.event; 
				if(aevent.keyCode!=40 && aevent.keyCode!=38 && aevent.keyCode!=37 && aevent.keyCode!=39 && aevent.keyCode!=13 && aevent.keyCode!=9){ 
					array_cities_filter = filterCity( $("#txtchufa").val() ); 
					city_showlist(0);
				}
			}
		)

//站站搜索
		$("#txtdaoda").keydown(
			function(aevent){
				curObj = $("#txtdaoda");
				aevent= aevent||window.event;
				if(aevent.keyCode==40){
					city_changeSelectIndex( 1 );
					$("#form_cities").css("display","block");	
					SetISPos($("#txtdaoda"));  
				}else if(aevent.keyCode==38){
					city_changeSelectIndex( -1 ); 
					$("#form_cities").css("display","block");	
					SetISPos($("#txtdaoda"));  
				}else if( aevent.keyCode==13){city_confirmSelect();
				
						
				        if(document.addEventListener){//如果是Firefox
							document.addEventListener("keypress",myHandler2, true);
					
				        }else{
				            document.onkeypress=submitDefault;//如果是IE
				//		evt = window.event;
                //        evt.returnValue=false;//屏蔽IE默认处理

					 }

				
				} 
			}
		).focus(
			function(){
				curObj = $("#txtdaoda");
				cityfield_focused = true;
				city_shiftSelect( $("#citem_0" ));
				$("#form_cities").css("display","block");
				
				SetISPos($("#txtdaoda"));  
			}
		).blur(
			function(){
				curObj = $("#txtdaoda");
				if(!mousedownOnPanel){
					cityfield_focused = false;
					$("#form_cities").css("display","none");
				}	
			}
		).keyup( 
			function(aevent){
				curObj = $("#txtdaoda");
				aevent= aevent||window.event; 
				if(aevent.keyCode!=40 && aevent.keyCode!=38 && aevent.keyCode!=37 && aevent.keyCode!=39 && aevent.keyCode!=13 && aevent.keyCode!=9){ 
					array_cities_filter = filterCity( $("#txtdaoda").val() ); 
					city_showlist(0);
				}
			}
		)
//车站搜索
		$("#txtchezhan").keydown(
			function(aevent){
				curObj = $("#txtchezhan");
				aevent= aevent||window.event;
				if(aevent.keyCode==40){
					city_changeSelectIndex( 1 );
					$("#form_cities").css("display","block");	
					SetISPos($("#txtchezhan"));  
				}else if(aevent.keyCode==38){
					city_changeSelectIndex( -1 ); 
					$("#form_cities").css("display","block");	
					SetISPos($("#txtchezhan"));  
				}else if( aevent.keyCode==13){city_confirmSelect();} 
			}
		).focus(
			function(){
				curObj = $("#txtchezhan");
				cityfield_focused = true;
				city_shiftSelect( $("#citem_0" ));
				$("#form_cities").css("display","block");
				SetISPos($("#txtchezhan"));  
			}
		).blur(
			function(){
				curObj = $("#txtchezhan");
				if(!mousedownOnPanel){
					cityfield_focused = false;
					$("#form_cities").css("display","none");
				}	
			}
		).keyup( 
			function(aevent){
				curObj = $("#txtchezhan");
				aevent= aevent||window.event; 
				if(aevent.keyCode!=40 && aevent.keyCode!=38 && aevent.keyCode!=37 && aevent.keyCode!=39 && aevent.keyCode!=13 && aevent.keyCode!=9){ 
					array_cities_filter = filterCity( $("#txtchezhan").val() ); 
					city_showlist(0);
				}
			}
		)




		$('#form_cities').mousedown(
			function(){mousedownOnPanel=true;}
		).mouseup(
			function(){mousedownOnPanel=false;}
		)
	}
)

function MapCityID(aCityname){
    //[Beijing, 北京, 1100]
    for(var i=0; i<array_cities.length; i++){
        if(array_cities[i][1]==aCityname){
            return array_cities[i][2];
        }
    }
    return 0;
}

function MapCityName(aCidyID){
    //[Beijing, 北京, 1100]
    for(var i=0; i<array_cities.length; i++){
        if(array_cities[i][2]==aCidyID){
            return array_cities[i][1];
        }
    }
    return "";
} 

function SetISPos(obj)
{
	$("#form_cities").css("left",obj.position().left);
	$("#form_cities").css("top",obj.position().top + obj.height() + 10);
}

//事件处理函数
function myHandlerFg(evt){
//判断浏览器
	if(evt == null){//是IE
	
	    evt.keyCode=9;
	//	evt = window.event;
	//	evt.returnValue=false;//屏蔽IE默认处理
	}
	else{//是Firefox
	
	if(evt.which && evt.which == 13){
		// evt.which=9;
		evt.preventDefault();//屏蔽Firefox默认处理！！！

		}else if(!evt.which && evt.keyCode==13){
			evt.which=9;
		}

		
}
}

//事件处理函数
function myHandler2(evt){
//判断浏览器
	if(evt == null){//是IE
		evt = window.event;
		evt.returnValue=false;//屏蔽IE默认处理
	}
	else{//是Firefox
	
	if(evt.which && evt.which == 13){
	//	evt.which=9;
	 //	evt.preventDefault();//屏蔽Firefox默认处理！！！
		
       //    evt.which==13;
		   
		  //	alert(evt.which);
		  
		  var fireOnThis = document.getElementById("shikechaxun")
                  if (document.createEvent)
                  {
                    var evObj = document.createEvent('MouseEvents')
                    evObj.initEvent( 'click', true, false )
                    fireOnThis.dispatchEvent(evObj)
                  }
                  else if (document.createEventObject)
                  {
                       fireOnThis.fireEvent('onclick')
                  }


		  
		   
		}else if(!evt.which && evt.which==13){
			//evt.which=13;
			evt.preventDefault();//屏蔽Firefox默认处理！！！
			
		}

		
      }
}
