﻿var iypKeySuggestParam = {
"Lang":"EN",
"HostURL":iypCommonAPI_HostURL, // 本JS文件所在的Server（如：http://yp.com.hk）
"HostURL_IKS":iypKeywordSuggestion_HostURL, //项目iyp_keyword_suggestion所在的Server（如：http://yp.com.hk）
"Width":430,
"Type":"IYP"
}
window.document.write("<link href=\""+ iypCommonAPI_HostURL + "/iypCommonAPI/KeywordSuggestion/iypKeySuggest.css\" type=\"text/css\" rel=\"stylesheet\" />");

var iSearchHistoryLeng = 0;
var arrIypSearchHistory;
var iyp_keyword_suggestion;
var iypKeywordSuggestData;
var iypKeywordSuggestType,iypKeywordSuggestType_History;
var iypKeywordSuggestTitle,iypKeywordSuggestTitle_History ,iypKeywordSuggest_BottomHtml;
function setIypKeywordSuggest(sLang){  
  switch(sLang.toLowerCase()){
    case "ch":
      iypKeywordSuggestType =  new Array("<span class=\"Company\">公司</span>","<span class=\"Category\">類別</span>","<span class=\"HotSearches\">熱門搜尋</span>","<span class=\"Category\">地址</span>");
      iypKeywordSuggestType_History =  new Array("公司","類別","熱門搜尋","地址");
      iypKeywordSuggestTitle = "yp 網上搜尋建議"; iypKeywordSuggestTitle_History = "yp 網上搜尋記錄";
      iypKeywordSuggest_BottomHtml = "<div class=\"bottom\"><a href=\"http://yp.com.hk/home_e10/ch/html/contactus/contactus.aspx?filename=advertise_with_us.html\">放置廣告?</a></div>";
      break;
    case "sc":
      iypKeywordSuggestType = new Array("<span class=\"Company\">公司</span>","<span class=\"Category\">类别</span>","<span class=\"HotSearches\">热门搜索</span>","<span class=\"Category\">地址</span>");
      iypKeywordSuggestType_History =  new Array("公司","类别","热门搜索","地址");
      iypKeywordSuggestTitle = "yp 网上搜索建议"; iypKeywordSuggestTitle_History = "yp 网上搜索记录";
      iypKeywordSuggest_BottomHtml = "<div class=\"bottom\"><a href=\"http://gb.yp.com.hk/han3/7/6/9/0/0/0/0/yp.com.hk/home_e10/sc/html/contactus/contactus.aspx?filename=advertise_with_us.html\">放置广告?</a></div>";
      break;
    default:
      iypKeywordSuggestType =  new Array("<span class=\"Company\">Company</span>","<span class=\"Category\">Category</span>","<span class=\"HotSearches\">Hot searches</span>","<span class=\"Category\">Address</span>");
      iypKeywordSuggestType_History =  new Array("Company","Category","Hot searches","Address");
      iypKeywordSuggestTitle = "yp web search suggestions"; iypKeywordSuggestTitle_History = "yp web search history";
      iypKeywordSuggest_BottomHtml = "<div class=\"bottom\"><a href=\"http://yp.com.hk/home_e10/en/html/contactus/contactus.aspx?filename=advertise_with_us.html\">Place an ads?</a></div>";
  }
}
function iypKeywordSuggest_Load(divID, textID, searchFunName, iWidth, sLang, sType){
  if(iWidth != undefined) iypKeySuggestParam.Width = iWidth;
  if(sLang != undefined) iypKeySuggestParam.Lang = sLang;
  if(sType != undefined) iypKeySuggestParam.Type = sType;
  $("#" + divID).html("<div id=\"iypKeySuggest_" + textID + "\" class=\"iypKeywordSuggest\"></div>");
  setIypKeywordSuggest(iypKeySuggestParam.Lang);
  var iypKeywordSuggestLi = "<div class=\"title\" style=\"width:" +  (iypKeySuggestParam.Width - 220) + "px;\">{0}</div><div class=\"type\">{2}</div><div class=\"percentage\"><div class=\"bg\" style=\"margin-left: {1}px;\"></div></div>";
  $("#" + textID).attr("autocomplete", "off").keyup(function(event) {    
    var keyword = $.trim($(this).val());
    if(keyword.length > 0){
      var keycodes = event.keyCode ? event.keyCode : event.charCode;
      if (keycodes == 40) { $("#iypKeySuggest_" + textID).show("fast"); $("#iypKeySuggest_" + textID + " li:first").focus(); return false; }
      if (keycodes >= 48 && keycodes <= 126 || keycodes == 8 || keycodes == 32) {
        arrIypSearchHistory = getIypKeySuggestHistory();
        var sUrl = "/iyp_keyword_suggestion/keyword_result_cache.aspx?format=json&type=" + iypKeySuggestParam.Type + "&keyword=" + encodeURIComponent(keyword) + "&jsoncallback=?";        
        $.getJSON(iypKeySuggestParam.HostURL_IKS + sUrl, function (data){        
          iypKeywordSuggest_Bind(textID,data,iypKeySuggestParam.Width,iypKeywordSuggestLi,keyword);          
          iypKeywordSuggest_Event(textID,searchFunName);
        });
      }    
    }
    else{$("#iypKeySuggest_" + textID).hide("fast");}
  });
  $("#" + textID).dblclick(function(){ if(iSearchHistoryLeng > 0 && $.trim($(this).val()).length > 0){ $("#iypKeySuggest_" + textID).show("fast"); }});
  $(document).click(function() { $("#iypKeySuggest_" + textID).hide("fast"); });
}
function iypKeywordSuggest_Event(textID,searchFunName){
  $("#iypKeySuggest_" + textID+" li").unbind().keydown(function(event) {
    var keycodes = event.keyCode ? event.keyCode : event.charCode;
    var index = $(this).attr("tabindex");
    if (keycodes == 13) { $("#iypKeySuggest_" + textID).hide("fast");eval(searchFunName);}
    if (keycodes == 27 || keycodes == 13) {$("#" + textID).focus(); $("#iypKeySuggest_" + textID).hide("fast"); return false;}
    if (keycodes == 40 || keycodes == 38) {
      if (keycodes == 40) index++;
      if (keycodes == 38) index--;
      index = (index > $("#iypKeySuggest_" + textID +" li").length +iSearchHistoryLeng) ? $("#iypKeySuggest_" + textID +" li").length +iSearchHistoryLeng : index;
      if (index < 0) { $("#iypKeySuggest_" + textID).hide("fast");}
      else {var bolddiv = $("#iypKeySuggest_" + textID +" li[tabindex=" + index + "]").focus(); }
      return false;
    }
  }).focus(function() {
    $("#iypKeySuggest_" + textID+" li").removeClass("selectLI");
    $("#" + textID).val( $("#iypKeySuggest_" + textID + " li:eq(" + $(this).attr("tabindex") + ") .title").text());
    $(this).addClass("selectLI");
  }).mouseover(function() { $(this).focus(); }
  ).click(function() {$("#iypKeySuggest_" + textID).hide("fast");eval(searchFunName);}
  );
}
function iypKeywordSuggest_Bind(textID,data,iWidth,iypKeywordSuggestLi,keyword){
  var iframeHeight = 0;  
  var sHtml = "<div style=\"background-color: #f8f8f8;z-index: 10001;\"><ul>";
  sHtml += getIypKeySearchHistory(iypKeywordSuggestLi,keyword);
  if(data.results.length + iSearchHistoryLeng <= 0){$("#iypKeySuggest_" + textID).hide("fast"); return false;};
  if(data.results.length > 0){
    iypKeywordSuggestData = data.results;
    sHtml += "<div style=\"height:25px;\"><div style=\"font-size:9pt;float:left;\">" + iypKeywordSuggestTitle +  "</div><div style=\"float:right;cursor: pointer;\"><img src=\"" + iypKeySuggestParam.HostURL + "/iypCommonAPI/KeywordSuggestion/close.gif\"></div></div>";
    $.each(data.results, function(i,item){
        sHtml += "<li tabindex=\"" + (i+iSearchHistoryLeng) + "\">"  + iypKeywordSuggestLi.replace("{0}",item.title).replace("{1}",(1-item.percentage) * 100).replace("{2}",iypKeywordSuggestType[item.type]) +  "</li>";
    }); 
    iframeHeight += 57 + (data.results.length * 23);
  }
  sHtml += "</ul></div>" + iypKeywordSuggest_BottomHtml;
  if(iSearchHistoryLeng >0){ iframeHeight += 50 + (iSearchHistoryLeng * 23)  }
  sHtml = "<div class=\"Content\" style=\"width:" + iWidth +"px;\">" + sHtml + "</div>";
  if($.browser.msie & $.browser.version < 7.0) sHtml = "<iframe style=\"position: absolute; z-index: -1; width: " + iWidth + "px; height: " + iframeHeight + "px;\" frameborder=0></iframe>" + sHtml; 
  $("#iypKeySuggest_" + textID).show("fast").html(sHtml);
}
function getIypKeySearchHistory(iypKeywordSuggestLi,keyword){
  iSearchHistoryLeng  = 0;
  var sHtml = "<div style=\"height:25px;font-size:9pt;\">" + iypKeywordSuggestTitle_History +  "</div>";
  var myHistory = new Array();     
  var iKeyLeng = keyword.length;
  for(var i=0;i< arrIypSearchHistory.length;i++ ){
    myHistory = arrIypSearchHistory[i];
    if(myHistory[0].substring(0,iKeyLeng).toLowerCase() == keyword.toLowerCase()){
      var sTypeHistory = "";  if(myHistory[2] >= 0) sTypeHistory = iypKeywordSuggestType_History[myHistory[2]];
      sHtml += "<li tabindex=\"" + iSearchHistoryLeng + "\">"  + iypKeywordSuggestLi.replace("{0}",myHistory[0]).replace("{1}",(1-myHistory[1]) * 100).replace("{2}",sTypeHistory) +  "</li>";
      iSearchHistoryLeng ++; if(iSearchHistoryLeng >= 3) break;
    }
  }
  sHtml += "<div style=\"border-top: 1px dotted; height:15px; margin-top: 8px;\"></div>";
  if(iSearchHistoryLeng == 0) sHtml= "";
  return sHtml; 
}
function setIypKeySuggestHistory(textID){
  var selTextVal = $("#" + textID).val();
  var sPercentage = "",sType = "";
  var isHistory_data = false,isHistory_cookie = false;
  if(selTextVal.length > 0){
    if(iypKeywordSuggestData != null){
      $.each(iypKeywordSuggestData, function(i,item){
        if(item.title.toLowerCase() == selTextVal.toLowerCase()){ sPercentage = item.percentage; sType = item.type; isHistory_data = true;}    
      });
    }
    var myTime = new Date();
    if(arrIypSearchHistory == undefined) arrIypSearchHistory = getIypKeySuggestHistory();
    var iHistoryLength = arrIypSearchHistory.length;
  	for(var i=0;i< iHistoryLength;i++ ){
  	  if(selTextVal.toLowerCase() == arrIypSearchHistory[i][0].toLowerCase()){
  	    if(isHistory_data) arrIypSearchHistory[i][1] = sPercentage;
  	    if(isHistory_data) arrIypSearchHistory[i][2] = sType;
  	    arrIypSearchHistory[i][3] ++;
  	    arrIypSearchHistory[i][4] = myTime;
  	    isHistory_cookie = true;
  	    break;
  	  }
	  }
    if(!isHistory_data && !isHistory_cookie) {sPercentage = "0.5"; sType = "-1";}
	  if(!isHistory_cookie){
      arrIypSearchHistory[iHistoryLength] = new Array();
      arrIypSearchHistory[iHistoryLength][0] = selTextVal;
      arrIypSearchHistory[iHistoryLength][1] = sPercentage;
      arrIypSearchHistory[iHistoryLength][2] = sType;
      arrIypSearchHistory[iHistoryLength][3] = 1;
      arrIypSearchHistory[iHistoryLength][4] = myTime;
	    iHistoryLength ++;
	  }
    arrIypSearchHistory.sort( function(x, y){ return x[3]==y[3] ? (Date.parse(x[4])<=Date.parse(y[4])?1:-1) : (x[3]<y[3]?1:-1) });
    if(iHistoryLength > 50){ arrIypSearchHistory = arrIypSearchHistory.remove(iHistoryLength);iHistoryLength=50;}
    var sHistoryCookie = "";
    for(var i=0;i<iHistoryLength;i++){
      if(i>0) sHistoryCookie += "|"; sHistoryCookie += encodeURIComponent(arrIypSearchHistory[i][0]) + ";" + arrIypSearchHistory[i][1] + ";" + arrIypSearchHistory[i][2] + ";" + arrIypSearchHistory[i][3] + ";" + arrIypSearchHistory[i][4];
　  }
    IypHistoryCookie(sHistoryCookie);      
  }
}
function getIypKeySuggestHistory(){
  var sHistoryCookie = IypHistoryCookie();
  var arrHistory = new Array();       
  if(sHistoryCookie != ""){
    for(var i= 0; i < sHistoryCookie.split("|").length; i++){
      arrHistory[i] = new Array();
      arrHistory[i][0] = decodeURIComponent(sHistoryCookie.split("|")[i].split(";")[0]);
      arrHistory[i][1] = sHistoryCookie.split("|")[i].split(";")[1];
      arrHistory[i][2] = sHistoryCookie.split("|")[i].split(";")[2];
      arrHistory[i][3] = sHistoryCookie.split("|")[i].split(";")[3];
      arrHistory[i][4] = sHistoryCookie.split("|")[i].split(";")[4];    
    }
  }
  return arrHistory; 
}
Array.prototype.remove = function(i) {i--;  if(i<0) return this;  else return this.slice(0,i).concat(this.slice(i+1,this.length));}
function IypHistoryCookie(sValue){
  var sCookieName = iypKeySuggestParam.Type + "keyword_suggestion";
  if(sValue == undefined){
    var iLeng = IypCookieHelper(sCookieName);
    var sCookie =""; for(var i=1;i<=iLeng;i++){ sCookie +=  IypCookieHelper(sCookieName +"_" + i); }
    return sCookie;
  }
  else{
    var iLeng = Math.floor(sValue.length / 3072); if(sValue.length % 3072 != 0) iLeng++;
    IypCookieHelper(sCookieName, iLeng);
    for(var i=1;i<=iLeng;i++){ IypCookieHelper(sCookieName +"_" + i, sValue.substring((i-1) * 3072,i * 3072)); }  
  }
}

function IypCookieHelper(name,value){
  if(value == undefined){
      var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
      if(arr != null) return unescape(arr[2]); return null;
  }
  else{
      var exp  = new Date();    //new Date("December 31, 9998");
      exp.setTime(exp.getTime() + 3650*24*60*60*1000);
      document.cookie = name + "="+ escape (value) + ";path=/;expires=" + exp.toGMTString();
  }
}
