// JavaScript Document
var totalData;
var isLoading = false;
var options = jQuery.extend({
    googleOptions: "&entqr=0&ud=1&sort=date:D:L:d1&output=xml_no_dtd&oe=UTF-8&ie=UTF-8&client=result_only&proxystylesheet=result_only&site=hk&tid=psearch_all",
    googleurl: "http://search.standardchartered.com/search?q=",
    googleJsonOptions: "&entqr=0&ud=1&sort=date:D:L:d1&output=xml_no_dtd&oe=UTF-8&ie=UTF-8&client=result_only&proxystylesheet=result_psearch_151&site=hk&num=6&callback=?",
    googleJsonOptions2icons: "&entqr=0&ud=1&sort=date:D:L:d1&output=xml_no_dtd&oe=UTF-8&ie=UTF-8&client=result_only&proxystylesheet=result_psearch_151_1&site=hk&num=6&callback=?",
    googleJsonOptions1icon: "&entqr=0&ud=1&sort=date:D:L:d1&output=xml_no_dtd&oe=UTF-8&ie=UTF-8&client=result_only&proxystylesheet=result_psearch_151_2&site=hk&num=6&callback=?",
    googleJsonOptions0icon: "&entqr=0&ud=1&sort=date:D:L:d1&output=xml_no_dtd&oe=UTF-8&ie=UTF-8&client=result_only&proxystylesheet=result_psearch_151_3&site=hk&num=6&callback=?"
    
});
var config = jQuery.extend({
    /*
	searchURL: 'http://presearchhk.standardchartered.com/presearchhk/getBox.action',
	searchURL_EN: 'http://presearchhk.standardchartered.com/presearchhk/getBox.action',
	searchURL_ZH: 'http://presearchhk.standardchartered.com/presearchhk/getBox.action',
	*/
	searchURL: 'http://origin.standardchartered.com/presearchhk/getBox.action',
	searchURL_EN: 'http://origin.standardchartered.com/presearchhk/getBox.action',
	searchURL_ZH: 'http://origin.standardchartered.com/presearchhk_zh/getBox.action',
	
	isIe6: false,
	defaultCatgStr: "Recommendation of the results",
	defaultCatgStr_EN: "Recommendation of the results",
	defaultCatgStr_ZH: "建議搜尋",
	otherCatgStr: "Other results",
	otherCatgStr_EN: "Other results",
	otherCatgStr_ZH: "其他搜尋結果",
	allSearchStr_EN: "View all search results",
	allSearchStr_ZH: "所有搜尋結果",
	noShortCutStr_EN: "No shortcut found",
	noShortCutStr_ZH: "沒有結果符合您的搜尋關鍵字",
	noShortCutMsgStr_EN: "Try another search or click this link to see all results for",
	noShortCutMsgStr_ZH: "按此瀏覽所有結果或重新搜尋",
	searchingStr_EN: "Searching",
	searchingStr_ZH: "正在搜尋中",
	triggerLength: 2,
	chinesePad: ''
});
    
function callback(adddata) {
	//this.callGoogle = true;
	for (var i=0;i<adddata.results.length;i++) {
        totalData.results.push(adddata.results[i]);
    }
    formatOutput(totalData);
}

function handleAjaxResponse(data) {
	totalData = data;
	var pquery = data.query;
	$.ajaxSetup({
      async: false
    }); 
	if(pageLang == 'zh') {
		pquery = form.encoded.value;
	}
    // handle if pre-defined keyword return only one result
    if (data.results.length == 0) {
    	jQuery.getJSON(options.googleurl+pquery+options.googleJsonOptions);
    } else if (data.results.length == 1) {
        jQuery.getJSON(options.googleurl+pquery+options.googleJsonOptions2icons);
    } else if (data.results.length == 2) {
    	jQuery.getJSON(options.googleurl+pquery+options.googleJsonOptions1icon);
    } else if (data.results.length == 3) {
    	jQuery.getJSON(options.googleurl+pquery+options.googleJsonOptions0icon);
    } else {
    	formatOutput(totalData);
    }
}

function formatOutput(data)
{
    //console.log(["inside getJSON" , data]);
		
	$('#q').removeClass('searchSpinner');
	$("#searchResults").empty();
	$('#searchResults').hide();

	this.isLoading = false;
	this.showResult = false;
	//disablePopup();
	this.groupedResult = groupByCategory(data);
	var num = this.groupedResult.length;
	
	if(num > 6)
		num = 6;						
		
	if(num > 0)
	{
		addCacheValue(data.query,data);	
	}
						
	for(var i=0;i<num;i++)
	{
		this.showResult = true;
		this.type = this.groupedResult[i]["type"];
		//alert(this.type);
		groupedResultDetails = this.groupedResult[i];
		var ulStr = "";
		if(i == 0 && this.type != config.defaultCatgStr) {
			//first title for normal result
			ulStr = "<ul class='searchCategory'><li class='firstTitle'><!--img src=images/"+ getCategoryIcon((this.type).toLowerCase()) + " /--><span>" + this.type + "</span></li>";
		} else if(this.type == config.defaultCatgStr){
			//first title for hard code default result
			if(pageLang == 'zh') {
				ulStr = "<ul class='searchCategory'><li class='firstTitle'><span>"+config.noShortCutStr_ZH+"</span></li><li class='noResult'><a href='/search/zh/index.html?q="+data.query+options.googleOptions+"'>"+config.noShortCutMsgStr_ZH+" '"+data.query+"'</a>.</li>";
				ulStr += "<ul class='searchCategory'><li class='midTitle'><!--img src=images/"+ getCategoryIcon((this.type).toLowerCase()) + " /--><span>" + config.defaultCatgStr_ZH + "</span></li>";
			} else {
				ulStr = "<ul class='searchCategory'><li class='firstTitle'><span>"+config.noShortCutStr_EN+"</span></li><li class='noResult'><a href='/search/en/index.html?q="+data.query+options.googleOptions+"'>"+config.noShortCutMsgStr_EN+" '"+data.query+"'</a>.</li>";
				ulStr += "<ul class='searchCategory'><li class='midTitle'><!--img src=images/"+ getCategoryIcon((this.type).toLowerCase()) + " /--><span>" + this.type + "</span></li>";
			}
			
		} else {
			if(this.type == config.otherCatgStr) {
				if(pageLang == 'zh') {
					ulStr = "<ul class='searchCategory'><li class='midTitle'><!--img src=images/"+ getCategoryIcon((this.type).toLowerCase()) + " /--><span>" + config.otherCatgStr_ZH + "</span></li>";
				} else {
					ulStr = "<ul class='searchCategory'><li class='midTitle'><!--img src=images/"+ getCategoryIcon((this.type).toLowerCase()) + " /--><span>" + config.otherCatgStr_EN + "</span></li>";
				}
			} else {
				ulStr = "<ul class='searchCategory'><li class='midTitle'><!--img src=images/"+ getCategoryIcon((this.type).toLowerCase()) + " /--><span>" + this.type + "</span></li>";
			}
		}
		for(var j=0;j<groupedResultDetails.length;j++)
		{
			var moreURL = groupedResultDetails[j]["moreURL"];
			var content = groupedResultDetails[j]["content"];
			var name = groupedResultDetails[j]["name"];								
			var icon = groupedResultDetails[j]["icon"];
			
			moreURL = addOmniture(moreURL);
			
			if(j < getNumberofItemsToDisplay(num))
			{		
				if(icon==""){
						ulStr += "<li><a href='" + moreURL  + "' target='_blank' ><span class='sContent' style='margin-left: 0px'><b>"+ name + "</b><br>" + content + "</span></a></li>";											
				}else{
						ulStr += "<li><a href='" + moreURL  + "' target='_blank' ><span class='imgIcon'><img width='40' height='40' src='"+icon+"' /></span><span class='sContent'><b>"+ name + "</b><br>" + content + "</span></a></li>";	
				}
				
			}else{
				break;
			}
		}
		if(i < num - 1 && this.type != config.defaultCatgStr){
			ulStr += "</ul>";
			$(ulStr).appendTo('#searchResults');								
		}else if(this.type == config.defaultCatgStr) {
			ulStr += "<li class='lastSearch' style='height: 20px; *margin-top: 0px;'></li></ul>";
			$(ulStr).appendTo('#searchResults');
		}else{
			if(pageLang == 'zh') {
				ulStr += "<li class='lastSearch'><a href='/search/en/index.html?q="+data.query+options.googleOptions+"'><span class='lastSearchSpan'>"+config.allSearchStr_ZH+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></a></li></ul>";
			} else {
				ulStr += "<li class='lastSearch'><a href='/search/en/index.html?q="+data.query+options.googleOptions+"'><span class='lastSearchSpan'>"+config.allSearchStr_EN+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></a></li></ul>";
			}
			$(ulStr).appendTo('#searchResults');								
		}
		
	}
	
	//alert(this.showResult);	
	//console.log(["this.showResult" , this.showResult]);
	if(this.showResult  && jQuery.trim($('#q').val()) != "" ){
		//console.log(["inside the show result",jQuery.trim($('#q').val())]);
		// resset call google
		//callGoogle = false;
		loadPopup();
		$('#searchResults').show();
	}
	// move this section back to top
	//else if(jQuery.trim($('#q').val()) != "" && !callGoogle){
        
        // call google mini to get more results
		//jQuery.getJSON(options.googleurl+data.query+options.googleJsonOptions);
		//callGoogle = true;
	//}		
	else if(jQuery.trim($('#q').val()) != ""){
        //resset call google
        //callGoogle = false;
        this.isLoading = false;
        loadPopup();
        ulStr = "<ul class='searchCategory'><li class='firstTitle'><span>No shortcut found</span></li><li class='noResult'>Try another search or click this <a href='/search/en/index.html?q="+data.query+options.googleOptions+"'>link</a> to see all results for '"+data.query+"'.</li><li class='lastSearch' style='height: 20px; *margin-top: 5px; *height: 15px'></li></ul>";
        $(ulStr).appendTo('#searchResults');
        $('#searchResults').show();
            
    }else if(jQuery.trim($('#q').val()) == ""){
		$('#searchResults').hide();
	}
}

function openLoadingBox() {
	
	if ($("#searchResults").is(':hidden')) {
		$("#searchResults").empty();
		/*
		if(jQuery.browser.msie && jQuery.browser.version.substr(0,1)=="6"){
			var windowWidth = document.documentElement.clientWidth;
			var windowHeight = document.documentElement.clientHeight;
			$('#backgroundPopup').width(windowWidth);
			$('#backgroundPopup').height(windowHeight+30);
		}
		*/
		$('#topsearch form').css({'z-index':'100'});
		var ulStr = "";
		if(pageLang == 'zh') {
			ulStr = "<ul class='searchCategory'><li class='firstTitle'><span>"+config.searchingStr_ZH+" ...</span></li>";
		} else {
			ulStr = "<ul class='searchCategory'><li class='firstTitle'><span>"+config.searchingStr_EN+" ...</span></li>";
		}
		ulStr += "<li class='loading'><span class='imgIcon loadingImg'><img width='20' height='20' src='/_images/psearch/loading.gif' /></span><span class='sContent'><b></b><br></span></li>";	
		ulStr += "<li class='lastSearch'><span class='lastSearchSpan'>&nbsp;</span></li></ul>";
		$(ulStr).appendTo('#searchResults');
		loadPopup();
		$('#searchResults').show();
	}
}

function groupByCategory(data)
{
	var prevCategory = "";
	var countCategory = -1;
	var cnt = 0;
	var searchTypeResult = new Array();	
		searchTypeResult[countCategory] = new Array();
	//var searchTypeResult[countCategory] = new Array();
	jQuery.each(data.results,function(i,item){
		var searchValues = new Array();	
		var type = item.type;

		if(prevCategory	!= item.type )
		{	
			
			cnt = 0;			
			countCategory++;	
			searchTypeResult[countCategory] = new Array();
			searchTypeResult[countCategory]["type"] = item.type;
			//searchValues["name"] = item.name;
			//check if input is Chinese, if not do a white space trim
			if(pageLang == 'zh') {
				searchValues["name"] = trimChineseItem(item.name, 20);
				searchValues["content"] = trimChineseItem(item.content, 40);
			} else {
				searchValues["name"] = trimItem(item.name, 45);
				searchValues["content"] = trimItem(item.content, 100);
			}
			searchValues["moreURL"] = item.moreDetailsUrl;
			searchValues["icon"] = item.iconPath;
			searchTypeResult[countCategory][cnt] = searchValues;							
			//alert(item.type + " category " + countCategory + " count " + cnt) ;
		}else{
			cnt = cnt + 1;
			//alert(item.type + " category " + countCategory + " count " + cnt) ;
			//searchValues["name"] = item.name;
			if(pageLang == 'zh') {
				searchValues["name"] = trimChineseItem(item.name, 20);
				searchValues["content"] = trimChineseItem(item.content, 40);
			} else {
				searchValues["name"] = trimItem(item.name, 45);
				searchValues["content"] = trimItem(item.content, 100);
			}
			searchValues["moreURL"] = item.moreDetailsUrl;
			searchValues["icon"] = item.iconPath;			
			searchTypeResult[countCategory][cnt] = searchValues;				
		}
		prevCategory = item.type;
	});
	return searchTypeResult;
}

function trimItem(itemName, itemLength) {
	$("#tempItem").append(itemName);
	itemName = $("#tempItem").text();
	$("#tempItem").empty();
	
	if (itemName.length > itemLength) {
		while (itemName.length > itemLength) {
            var words = "";
            words = itemName.split(' ');
            words.pop();
            var wordsLength = words.length;
            --wordsLength;
            var newTitle = "";
            for (var i = 0; i < wordsLength ; i++) {
                newTitle += words[i]+" ";
            }
            itemName = newTitle;
        }
        itemName = itemName+" ..."
	}
    return itemName;
}

function trimChineseItem(itemName, itemLength) {
	$("#tempItem").append(itemName);
	itemName = $("#tempItem").text();
	$("#tempItem").empty();
	
	if (itemName.length > itemLength) {
		itemName = itemName.substring(0,itemLength);
        itemName = itemName+" ..."
	}
    return itemName;
}

function getNumberofItemsToDisplay(numberOfCategory)
{
	var cnt = numberOfCategory;
	var numberOfItem = 0;
	if(cnt == 1)
		numberOfItem = 6;
	else if(cnt == 2)
		numberOfItem = 5;
	else if(cnt == 3)
		numberOfItem = 3;
	else if(cnt == 4)
		numberOfItem = 3;
	else if(cnt == 5)
		numberOfItem = 3;
	else if(cnt == 6)
		numberOfItem = 3;
	else if(cnt == 7)
		numberOfItem = 3;		
		
	return numberOfItem;	
}

var cacheObject;
function addCacheValue(key,value)
{
	if(cacheObject == null)
		cacheObject = new Array();
		
	cacheObject[key] = value;
}

function hasValue(key)
{
	var hasVal = false;
	if(cacheObject != null){
			if(cacheObject[key] != null)
			{
				hasVal = true;
			}
	}
	return hasVal;
}

function getCachedValue(key)
{
	var cachedResult;	
		if(cacheObject[key] != null)
		{
			cachedResult = cacheObject[key];
		}
	return cachedResult;
}

function clearCache()
{
	cacheObject = new Array();
}

function getCategoryIcon(catname)
{
	var icon = "";
	switch(catname)
	{
		
		case "product":
		icon = "icon_search1.gif";
		break;
		case "creditcard":
		icon = "icon_search2.gif";
		break;
		case "about us":
		icon = "icon_search1.gif";
		break;
		case "jobs":
		icon = "icon_search2.gif";
		break;	
		default:
		icon = "icon_search2.gif";
		break;
		
	}
	return icon;
}

//Clear search field
function clearSearchField(q)
{
	if(q[0].value == ' search' || q[0].value == ' 搜尋'){
	   q[0].value='';
	}
}

function fillSearchField(q)
{	
	$('#hid').val(q[0].value);
	if(q[0].value == ''){
		if(pageLang == 'zh') {
			q[0].value=' 搜尋';
		} else {
			q[0].value=' search';
		}
	}
}

var popupStatus = 0;

//loading popup with jQuery magic!
function loadPopup(){
	//loads popup only if it is disabled
	//alert("load");
	if(config.isIe6) {
		$("select").hide();
	}
	if(popupStatus==0){
		$("#backgroundPopup").css({
			"opacity": "0.6"
		});
		$("#backgroundPopup").fadeIn("normal");
		popupStatus = 1;
	}
}

//disabling popup with jQuery magic!
function disablePopup(){
	//disables popup only if it is enabled
	//alert("unload");
	
	if(popupStatus==1){
		$("#backgroundPopup").fadeOut("fast");
		popupStatus = 0;
		//location.reload();
		setTimeout(function(){
			$('#pageMenu').css({'z-index':'11'});
			$('#pageOnlineBanking').css({'z-index':'15'});
			$('#pageLocalSites').css({'z-index':'16'});
		},500);
	}
	if(config.isIe6) {
		setTimeout(function(){
			$("select").show();
		},500);
	}
}

function addOmniture(url) {
	if (url.match(/\?/)) {
		url += "&tid=psearch_option";
	} else {
		url += "?tid=psearch_option";
	}
	return url;
}

function doFFSearch() {
	//alert('Do FF Search');
	$('#q').keyup();
}

function doIESearch() {
	//alert('Do IE Search');
	$('#q').keyup();
}

$(document).ready(function($){
	if(jQuery.browser.msie && jQuery.browser.version.substr(0,1)=="6"){
		config.isIe6 = true;
	}
	if(config.isIe6){
		var windowWidth = document.documentElement.clientWidth;
		var windowHeight = document.documentElement.clientHeight;
		$('#backgroundPopup').width(windowWidth+windowWidth);
		$('#backgroundPopup').height(windowHeight+30);
	}
	
	if(pageLang == 'zh') {
		 config.triggerLength = 0;
		 config.chinesePad = ' ';
	 }

	$('#q').focus(function() {
		clearSearchField($('#q'));
	});

	$('#q').blur(function() {
		fillSearchField($('#q'));
	});
	
	//disable enter key
	textboxes = $("#q");

	if ($.browser.mozilla) {
		$(textboxes).keypress(checkForEnter);
		document.getElementById('q').addEventListener("input",doFFSearch,false);
	} else {
		$(textboxes).keydown(checkForEnter);
		//document.getElementById('q').attachEvent("onpropertychange",doIESearch);
	}

	function checkForEnter(event) {
		//alert('press');
		if (event.keyCode == 13) {
			currentTextboxNumber = textboxes.index(this);

			if (textboxes[currentTextboxNumber + 1] != null) {
				nextTextbox = textboxes[currentTextboxNumber + 1];
				nextTextbox.select();
			}
			event.preventDefault();
			return false;
		}
		//doPredictiveSearch();
		//alert(event.keyCode);
	}
	//disable enter key
	
	
	$('body').click(function(event){
		var $target = $(event.target);
		if(!this.isLoading && !($target.is('#q')) ){
			//clearCache();
			if(pageLang == 'zh') {
				$('#q').val(" 搜尋");
			} else {
				$('#q').val(" search");
			}
			////this.isLoading = false;		
			disablePopup();
			$("#searchResults").empty();	
			lastValue = "";
		}
	});
	//prepare q action
	$('#q').keyup(function(event) {
		
		var lastValue = "";

		 if(event.keyCode != 27 ){
			 //check input is English or not
			 if($('#q').val().charCodeAt(0) > 127) {
				 config.triggerLength = 0;
				 config.chinesePad = ' ';
			 } else {
				 config.triggerLength = 1;
				 config.chinesePad = '';
			 }
			 
			 if(jQuery.trim($('#q').val()) != "" && $('#q').val().length > config.triggerLength){
					if($('#q').val() != lastValue) {
						
		                var input = jQuery(this);
						var q = jQuery.trim(this.value);
						////var q = jQuery.trim($('#q').val());
						if(this.timer) {
							clearTimeout(this.timer);
						}
						
						//display loading search box //////////////
						openLoadingBox();
						$('#q').addClass('searchSpinner');
	
						this.isLoading = true;
						this.timer = setTimeout(function() {
						//disable caching
						//if(!hasValue(q)){
							if(pageLang == 'zh') {
								config.searchURL = config.searchURL_ZH;
								psearchEncode(q);
								q = form.encoded.value;
							} else {
								config.searchURL = config.searchURL_EN;
							}
							
							$.ajaxSetup({
				              async: false
				            }); 
							jQuery.getJSON(config.searchURL + "?query="+q+"&lang="+pageLang+"&jsonp=handleAjaxResponse&handleAjaxResponse=?");
						},300);
						lastValue = $('#q').val();
					}	
			} else {
				//when query length less than define value
				clearCache()
				lastValue = "";
				disablePopup();
				$("#searchResults").empty();
				$("#searchResults").hide();
			}
		 } else {
			//when key = esc
		 	//$('body').focus();
			clearCache();
			//document.frm.hid.focus();
			$("#btn").focus();
			if(pageLang == 'zh') {
				$('#q').val(" 搜尋");
			} else {
				$('#q').val(" search");
			}
			lastValue = "";
			disablePopup();
			$("#searchResults").empty();			
		 }
		});

});
	
