var catagory = ["公司", "产品", "地址","全部"];
var promptArray = ["","搜“产品”描述中包含的关键字 例:茶叶","搜“地址”中包含的关键字 例:长安大厦","搜索公司信息 例：广州 网络"];
var territory = [11,12,31,50];//直辖市
$(function(){
	initGlobal();
	initDefaultCity();
	tab(0);
	$("#lastestDiv1,#lastestDiv2").click(function(){
		 queryRecently(path+'/search','','&day=30&sort=2');
	});
});

//初始化用户设置的默认城市
function initDefaultCity(){
	$.getScript(resourcePath + "/js/city/city.js",function(){
		var cityCode = GetCookie("defaultCity");
		if(cityCode != null && cityCode != "100000"){
			search.setCity(cityCode);
			if(isTerritory(cityCode,territory))
			{
				initMunicipalitiesNavigation(province,municipalities,cityCode,"","false");
			}else{
				initCityNavigation(area,city,province,cityCode,"","false")
			}
			var param = "recall";
    		var title = "取消默认";
    		$("#sa_1 #defaultSpan").remove();
    		var span = "<span id=\"defaultSpan\" ><a href='javascript:instal(\""+param+"\");' class='default'>"+title+"</a></span>";
    		$("#sa_1").append(span);
		}
	});
}


//初始化搜索框
function initSearchBox(){
	var keywordsInput = $("#keywords");
	keywordsInput.keypress(function(event) {
		var code = event.keyCode;
		var val = keywordsInput.val();
		if (code != 13) {
			if (isDefault(promptArray, val) && val != "") {
				keywordColor(true);
			} else {
				keywordColor(false);
			}
		} else {
			if (isDefault(promptArray, val)) {
				keywordColor(true);
			} else {
				if(val==""){
					keywordColor(true);
				}else{
					keywordColor(false);
				}
			}
			query();
		}
	}).focus(function(){
	 	$("#total_number").hide();
	}).click(function(event) {
		var val = keywordsInput.val();
		if (isDefault(promptArray, val)) {
			keywordsInput.val("");
			keywordColor(false);
		}
		keywordsInput.focus();
	}).blur(function(event) {
		var val = keywordsInput.val();
		if("" == val || isDefault(promptArray,val)){
			keywordsInput.val(promptArray[search.getSearchType()]);
			keywordColor(true);
		}
		if(val == "" && search.getSearchType() == 0){
	 		$("#total_number").show();
	 	}
	});
	$("#total_number").click(function(){
	 	$("#keywords").css("color","#333").css("fontSize","16px").focus();
		$(this).hide();
	});
}

function cssAni(osrc, otarget, title, num, duration) {
  var t = null;
  var c = 1;
  var d = 0;
  var n = 0;
  var i = Math.floor((duration || 300) / num);
  var s = otarget.className.replace(/.$/, ''),r = /over/;
  //n=r.test((e||event).type)?1:-1;
  osrc.hover(function() {
    n = 1;
    title.show();
    if (!t) {
      t = setInterval(function() {
        if ((c == 1 || c == num) && ((d == n || c + n < 1) || !(d = n))) {
          return clearInterval(t),
          t = null;
        }
        otarget.className = s + (c += d);
      },i);
    }
  },
  function() {
    n = -1;
    title.hide();
    if (!t) {
      t = setInterval(function() {
        if ((c == 1 || c == num) && ((d == n || c + n < 1) || !(d = n))) {
          return clearInterval(t),
          t = null;
        }
        otarget.className = s + (c += d);
      },
      i);
    }
  });
};

function initNavigation() {
  for (var i = 0; i < 5; i++) {
    var lis = $("#icon_li" + i);
    var divs = document.getElementById("icon_div" + i);
    var points = $("#icon_point" + i);
    cssAni(lis, divs, points, 7);
  }
}

function tab(index) {
  var p = $("#tb");
  var html = "";
  for (var i = 0; i < catagory.length; i++) {
    if (index == i) {
      html = html + "<b>" + catagory[i] + "</b>";
    } else {
      html = html + "<a href=\"javascript:tab(" + i + ");\">" + catagory[i] + "</a>";
    }
  }
  p.html(html);
  initDefault(index);
  search.setSearchType(index);
  if(index == 0 && $("#keywords").val()==""){
  	$("#total_number").show();
  }else{
  	$("#total_number").hide();
  }
}

function initDefault(index) {
  var keywords = $("#keywords");
  var val = keywords.val();
  var result = isDefault(promptArray, val);
  if (result || "" == val) {
    keywords.val(promptArray[index]);
    keywordColor(true);
  } else {
    keywordColor(false);
  }
}


function isDefault(array, value) {
  for (var i = 0; i < array.length; i++) {
    if (array[i] == value) {
      return true;
    }
  }
  return false;
}

function queryRecently(url,word,other) {
	var keywords ;	
	if(word != '' && word != null)
	{
		keywords = word;
	}else
	{
		keywords = $("#keywords").val();
	}
	var searchType = search.getSearchType();
	var cityCode  = search.getCity();
	var result = isDefault(promptArray,keywords);
	if(result || undefined){
		keywords = "";
	}
	savekeyword("keywords",keywords);
	var params = "keywords=" + encodeURIComponent(keywords);
	params += "&search_type=" + searchType;
	params += "&city=" + cityCode;
	if(params.length > 0&&url.indexOf('?')==-1) {
		params = "?" + params;
	}
	else
		params = "&" + params;
	window.location.href = url  + params + other;
}

function query(){
	var keywords = $("#keywords").val();
	var searchType = search.getSearchType();
	var cityCode  = search.getCity();
	if(($.trim(keywords)=="" || keywords == "请输入关键字" || isDefault(promptArray,keywords)) && cityCode == "100000"){
		$("#total_number").hide();
		beginchangefont();
		return ;
	}
	var result = isDefault(promptArray,keywords);
	if(result || undefined){
		keywords = "";
	}
	savekeyword("keywords",keywords);
	var url = "keywords=" + encodeURIComponent(keywords);
	url += "&search_type=" + searchType;
	url += "&city=" + cityCode;
	window.location.href = path + "/search?" + url;
}

function initGlobal() {
  initSearchBox();
  initNavigation();
  $("body").click(function(evt) {
     var evt = window.event ? window.event: evt,target = evt.srcElement || evt.target;
     if(target.nodeName.toLowerCase() == "a" || target.id == "city_sa_2" || target.id == "city"){
     	return;
     }else{
    	if(search.getCity() != "100000"){
    		var defaultCode = GetCookie('defaultCity');
    		var param = "";
    		var title = "";
	 		if(defaultCode != "100000" && defaultCode == search.getCity()){
	 		 	title = "取消默认";
				param = "recall";
	 		}else{
	 			title = "设为默认";
	 			param = "default";
	 		}
    		$("#sa_1 #defaultSpan").remove();
    		var span = "<span id=\"defaultSpan\" ><a href='javascript:instal(\""+param+"\");' class='default'>"+title+"</a></span>";
    		$("#sa_1").append(span);
    	}
    	document.getElementById("city_sa_2").style.display="none";
    	$("#sa_1 a").removeClass("now");
     }
  });
};

function initNavigation() {
  for (var i = 0; i < 5; i++) {
    var lis = $("#icon_li" + i);
    var divs = document.getElementById("icon_div" + i);
    var points = $("#icon_point" + i);
    cssAni(lis, divs, points, 7);
  };
};

function isTerritory(cityCode,territory)
{
	var isTerritory = false;
	for(var i=0;i < territory.length;i++)
	{
		if(cityCode.toString().substring(0,2) == territory[i])
		{
			isTerritory = true;
			break;
		}	
	}
	return isTerritory;
}

//加载城市
function loadCity(cityCode,isTitle){
	search.setCity(cityCode);
	//加载城市数据
	$.getScript(resourcePath + "/js/city/city.js",function(){
		var array = new Array();
		var classId = "";
		if(isTerritory(cityCode,territory)) //如果是直辖市 >> 这里走
		{
			if(cityCode % 10000 == 0){
				classId = "c_province";
			}else {
				classId = "c_city";
			}
			initMunicipalitiesNavigation(province,municipalities,cityCode,classId,isTitle);
			array = municipalities;
		}else{ 
			if(cityCode == 100000) {
				classId = "country";
			}else if(cityCode % 10000 == 0){
				classId = "c_province";
			}else if(cityCode % 100 == 0){
				classId = "c_city";
			}
			//初始化导航 >> 普通省市走这步
			initCityNavigation(area,city,province,cityCode,classId,isTitle);
			if(cityCode == 100000) {
				array = province;
			}else if(cityCode % 10000 == 0){
				array = city;
			}else if(cityCode % 100 == 0){
				array = area;
			}
		}
		//填充数据
		initCityContainer(array,cityCode,classId);
		if(isTitle=="false" && classId != ""){
			isLoad = true;
			$("#"+classId).addClass("now");	
		}
	});	
}
/**
 * 直辖市导航初始化
 * @param municipalities 直辖市数据数组
 * @param cityCode 当前城市code 
 */
function initMunicipalitiesNavigation(province,municipalities,cityCode,classId,isTitle)
{
	var content = '<a href="javascript:loadCity(100000,\'true\');" id="country" >全国</a>';
	if(cityCode % 10000 == 0)
	{
		content += "&gt;" + getMunicipalitiesCityLink(province,cityCode) + defaultspan("none");
	} else {
		var provinceCode = cityCode.toString().substring(0,2)+"0000";
		var provinceName = getMunicipalitiesCityLink(province,provinceCode);
		var cityName = getMunicipalitiesCityLink(municipalities,cityCode);
		content += "&gt;" + provinceName + "&gt;" + cityName + defaultspan("block");
	}
	$("#sa_1").html(content);
	 //初始化导航样式
	initNavigationClass(classId,isTitle);
}

/**
 * 直辖市导航链接
 * @param municipalities 直辖市数据数组
 * @param cityCode 当前城市code 
 */
function getMunicipalitiesCityLink(municipalities,cityCode)
{
	var content = "";
	var classId = "";
	if(cityCode % 10000 == 0){
		for (var i = 0; i < municipalities.length; i++) {
			if(municipalities[i].id == cityCode) {
				content = '<a id="c_province" href="javascript:loadCity('+municipalities[i].id+',\'true\');">'+municipalities[i].name+'</a>';
			}
		}
	}else{
		for (var i = 0; i < municipalities.length; i++) {
			if(municipalities[i].id == cityCode) {
				content = " <span>" + municipalities[i].name + "</span>";
			}
		}
	}
	return content;
}

//填充数据
function initCityContainer(obj,cityCode,classId){
	if(obj == null )return ;
	var div = $("#city_sa_2");
	var html = "";
	for (var i = 0; i < obj.length; i++) {
		if(cityCode == obj[i].pid){
			html += "<a href=\"javascript:loadCity("+obj[i].id+",'false');\">"+obj[i].name+"</a> ";
		}
	}
	if(html != ""){
		html = "<ul id=\"city\">"+html+"</ul>";
		$("#city_sa_2").html(html);
	}else{
		$("#city_sa_2").hide();
	}
	
}
//初始化导航
function initCityNavigation(area,city,province,cityCode,classId,isTitle){
	var div = $("#sa_1");
	if(cityCode == 100000) {
		var content = '<a href="javascript:loadCity(100000,\'true\');" id="country" >全国</a>';
		div.html(content);
		//初始化导航样式
		initNavigationClass(classId,isTitle);
		return;
	}
	 var content = '<a href="javascript:loadCity(100000,\'true\');" id="country" >全国</a>';
	 if(cityCode % 10000 == 0){
		content += "&gt;" + getCityLink(province,cityCode,false) + defaultspan("none");
	 }else if(cityCode % 100 == 0){
		cityCode += "";
	 	var parent = cityCode.substring(0,2)+"0000";
	 	var provinceName = getCityLink(province,parent,false);
	 	var count = 0;
	 	for (var i = 0; i < area.length; i++) {
	 		if(area[i].pid == cityCode){
	 			count ++;
	 		}
	 	}
	 	var cityName;
	 	if(count==0){
	 	 	cityName = getCityLink(city,cityCode,true);
	 	 	content += "&gt;" + provinceName + "&gt;" + cityName + defaultspan("block");
	 	}else{
	 		cityName = getCityLink(city,cityCode,false);
	 		content += "&gt;" + provinceName + "&gt;" + cityName + defaultspan("none");
	 	}
	 }else {
	 	var areaName = getCityLink(area,cityCode,false);
	 	cityCode += "";
	 	var parent = cityCode.substring(0,4)+"00";
	 	var ctiyName = getCityLink(city,parent,false);
	 	parent = cityCode.substring(0,2)+"0000";
	 	var provinceName = getCityLink(province,parent,false);
		content += "&gt;" + provinceName + "&gt;" + ctiyName + "&gt;" + areaName + defaultspan("block");
	 }
	 div.html(content);
	 //初始化导航样式
	 initNavigationClass(classId,isTitle);
}
//初始化导航样式
function initNavigationClass(classId,isTitle){
	var obj = $("#city_sa_2");
 	if(isTitle=="true"){
		obj.toggle();
		var style = $.trim(obj.attr("style"))//.toLowerCase();
		//IE6 下为DISPLAY: block 格式 
		if("" == style || "display: block;" == style || "DISPLAY: block" == style ){
			$("#"+classId).addClass("now");
		} else {
			$("#defaultSpan").show();
		}
	};
}

function defaultspan(display){
	var span = "";
	var isdefault = GetCookie("defaultCity");
	var title = "";
	var param = "";
	if(isdefault != "100000" && isdefault == search.getCity()){
		title = "取消默认";
		param = "recall";
	}else{
		title = "设为默认";
		param = "default";
	}
	if(display=="none"){
		span = " <span id=\"defaultSpan\" style=\"display:"+display+"\" ><a href='javascript:instal(\""+param+"\")' class='default'>"+title+"</a></span>"
	}else{
		span = " <span id=\"defaultSpan\" ><a href='javascript:instal(\""+param+"\");' class='default'>"+title+"</a></span>"
	}
	return span;
}
//设置 取消默认
function instal(instal){
	if(instal == "default"){
		SetCookie("defaultCity",search.getCity());
		$("#defaultSpan").html("<font color=\"#ff6600\">设置成功</font>");
		setTimeout(function(){
			$("#defaultSpan").html("<a href='javascript:instal(\"recall\");' class='default'>取消默认</a></span>");
		},500);
	}else{
		SetCookie("defaultCity",100000);
		$("#defaultSpan").html("<font color=\"#ff6600\">取消成功</font>");
		setTimeout(function(){
			search.setCity(100000);
			$("#sa_1").html("<a href=\"javascript:loadCity(100000,\'true\');\" id=\"country\">全国</a>");
		},500);
	}
}

//获取导航链接
function getCityLink(array,cityCode,isNull){
	var content = "";
	var classId = "";
	if(cityCode % 100 != 0 || isNull){
		for (var i = 0; i < array.length; i++) {
			if(array[i].id == cityCode) {
				content = " <span>" + array[i].name + "</span>";
			}
		}
	}else{
		for (var i = 0; i < array.length; i++) {
			if(array[i].id == cityCode) {
				if(cityCode % 10000 == 0){
					classId = "c_province";
				}else if (cityCode % 100 == 0){
					classId = "c_city";
				}else {
					classId = "c_area";
				}
				content = '<a id="'+classId+'" href="javascript:loadCity('+array[i].id+',\'true\');">'+array[i].name+'</a>';
			}
		}	
	}
	return content;
}


function changefont() {
	var getfont = $("#keywords");
	flamtimes++;
	if (flamtimes % 2 == 0) {
		r = 255;
		g = 255;
		b = 255;
	} else {
		r = 255;
		g = 240;
		b = 225;
	}
	if (getfont != null) {
		getfont.css("background","rgb(" + r + "," + g + "," + b + ")");
	}
	
	if (flamtimes < 4) {
		setTimeout("changefont()", 200);
	}
}

function beginchangefont() {
	flamtimes = 0;
	$("#keywords").val("请输入关键字");
	keywordColor(true);
	changefont();
	setTimeout("reset()",600);
}

function reset() {
	var index = search.getSearchType();
	if (index == 4) {
		index++;
	}
	var val = promptArray[index];
	$("#keywords").val(val);
	if(search.getSearchType()==0){
		$("#total_number").show();
	}
}
