﻿jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1}var expires='';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()}var path=options.path?'; path='+options.path:'';var domain=options.domain?'; domain='+options.domain:'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('')}else{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]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break}}}return cookieValue}};

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){
    case "ch":
      iypKeywordSuggestType =  new Array("<span class=\"Company\">公司</span>","<span class=\"Category\">類別</span>","<span class=\"HotSearches\">熱門搜尋</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>");
      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>");
      iypKeywordSuggestType_History =  new Array("Company","Category","Hot searches","");
      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(textID,sLang,iWidth,sHostURL,searchFunName){
  if(sLang == undefined) sLang = "en";  setIypKeywordSuggest(sLang);
  if(iWidth == undefined) iWidth = 470;
  if(sHostURL == undefined) sHostURL = ""; sHostURL += "/iyp_keyword_suggestion";  
  window.document.write("<link href=\""+ sHostURL + "/s2/iypKeySuggest.css\" type=\"text/css\" rel=\"stylesheet\" />");
  var iypKeywordSuggestLi = "<div class=\"title\" style=\"width:" +  (iWidth - 220) + "px;\">{0}</div><div class=\"type\">{2}</div><div class=\"percentage\"><div class=\"bg\" style=\"margin-left: {1}px;\"></div></div>";
  window.document.write("<div id=\"iypKeySuggest_" + textID + "\" class=\"iypKeywordSuggest\"></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 = sHostURL + "/keyword_result_cache.aspx?format=json&keyword=" + encodeURIComponent(keyword) + "&jsoncallback=?";
        $.getJSON(sUrl, function (data){
          iypKeywordSuggest_Bind(textID,data,iWidth,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; font-size:9pt;\">" + iypKeywordSuggestTitle +  "</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()){
      sHtml += "<li tabindex=\"" + iSearchHistoryLeng + "\">"  + iypKeywordSuggestLi.replace("{0}",myHistory[0]).replace("{1}",(1-myHistory[1]) * 100).replace("{2}",iypKeywordSuggestType_History[myHistory[2]]) +  "</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 = "3";}
	  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){
  if(sValue == undefined){
    var iLeng = $.cookie("iyp_keyword_suggestion");
    var sCookie =""; for(var i=1;i<=iLeng;i++){ sCookie +=  $.cookie("iyp_keyword_suggestion_" + i); }
    return sCookie;
  }
  else{
    var iLeng = Math.floor(sValue.length / 3072); if(sValue.length % 3072 != 0) iLeng++;
    $.cookie("iyp_keyword_suggestion", iLeng, {expires: 3650, path:"/"});
    for(var i=1;i<=iLeng;i++){ $.cookie("iyp_keyword_suggestion_" + i, sValue.substring((i-1) * 3072,i * 3072), {expires: 3650, path:"/"}); }  
  }
}
