/*
	Author: 				Alex CHOI
	Last modified Date:		20 Feb 2009
	Ajax module :			canon.ajax.auto_complete
*/
var lookAheadArray = null;
var suggestionDiv = null;
var cursor;
var inputTextField;
var submitButton;
var sourceInputText;
var loadingImage;
var urlbase = '/suggestion';
var searchCounter = 0;
var searchLanguage = "en";
var resultMap ;
var curResultList;

//Image Adj
var loadingImageTopAdj=0;
var loadingImageLeftAdj=0;

//Searching Type
var curSearchType = "Product";

//Current direct location
var curUrlSearch ="";
var curUrlItemInfo = "";

//Redirect location
var urlProductSearch = "../catalog/productsearch.do?productItemName=";
var urlProductItemInfo = "../catalog/productiteminfo.do?productItemID=";
var urlPremiumSearch = "../premium/premiumsearch.do?name=";
var urlPremiumItemInfo = "../premium/premiuminfo.do?productItemId=";

//Image path
var urlImagePath = "/public/productItem/";
var urlImageNotFound ="../images/common/image_not_available90x90.jpg";

//Product Icon location
var urlProductIcon ="/public/productItem/";

//Width control
var curWidthExtension = 0;

//More result message
var txtENMoreResults ="more results...";
var txtTCMoreResults ="\u66F4\u591A\u7684\u641C\u5C0B\u7D50\u679C...";

//No record found
var txtENNoRecordFound ="Sorry, no product found,<br/>Please try again.";
var txtTCNoRecordFound ="\u627E\u4E0D\u5230\u76F8\u95DC\u7522\u54C1<br/>\u8ACB\u518D\u5617\u8A66";

function createDiv(){
    suggestionDiv = document.createElement("div");
    suggestionDiv.style.zIndex = "10";
    /* suggestionDiv.style.opacity ="0.9"; */
    suggestionDiv.style.repeat = "repeat";
    //suggestionDiv.style.filter = "alpha(opacity=90)";
    suggestionDiv.className = "suggestions";
    suggestionDiv.id = "suggestionList";
    suggestionDiv.style.visibility = "hidden";
    suggestionDiv.style.overflow = "hidden";
    suggestionDiv.style.width = inputTextField.offsetWidth + curWidthExtension;
    suggestionDiv.style.backgroundColor = "white";
    suggestionDiv.style.autocomplete = "off";
    suggestionDiv.style.fontSize="11px";
    suggestionDiv.style.fontFamily ="Verdana, Arial, Helvetica, sans-serif";
    suggestionDiv.style.fontWeight ="bold";
    suggestionDiv.style.textAlign ="right";
    

    //suggestionDiv.style.backgroundImage = "url(transparent50.png)";
    //when the user clicks on the a suggestion, get the text (innerHTML)
    //and place it into a inputTextField
    suggestionDiv.onmouseup = function()
    {
        inputTextField.focus();
    }
    suggestionDiv.onmouseover = function(inputEvent)
    {
        inputEvent = inputEvent || window.event;
        sugTarget = inputEvent.target || inputEvent.srcElement;
        highlightSuggestion(sugTarget);
        //alert(sugTarget);
    }
    suggestionDiv.onmousedown = function(inputEvent)
    {
        inputEvent = inputEvent || window.event;
        sugTarget = inputEvent.target || inputEvent.srcElement;
        if (sugTarget.firstChild != null){
        /*
            inputTextField.value = sugTarget.firstChild.nodeValue;
		    hideSuggestions();
	        window.location= curUrlItemInfo + resultMap[sugTarget.firstChild.nodeValue];	
	    */
        
        	if ( ! hasAttribute( sugTarget, "href" ) ) {
		        inputTextField.value = sugTarget.firstChild.nodeValue;
		        hideSuggestions();
	    	    window.location= curUrlItemInfo + resultMap[sugTarget.firstChild.nodeValue];	   
        	}else{
        		if (sugTarget.getAttribute("href")!="")
	        		window.location = sugTarget.getAttribute("href");
        	}
        	
	    }

    }
    document.body.appendChild(suggestionDiv);
}

function keyDownHandler(inEvent ){

    switch(inEvent.keyCode) {
    	/* left and right arrow */
    	case 37:
    		hideSuggestions();  
    		break;
    	case 39:
    	   	hideSuggestions();  
    		break;
    
        /* up arrow */
        case 38:
        
            if (suggestionDiv.childNodes.length > 0 && cursor > 0)
            {
                var highlightNode = suggestionDiv.childNodes[--cursor];
                highlightSuggestion(highlightNode);
				copyProductItemNameToSearchBox( cursor );

            }else if (suggestionDiv.childNodes.length > 0 && cursor == 0)
            {
            	cursor = suggestionDiv.childNodes.length-1-1;
            	//fix ie problem
            	if (cursor > 9)
            		cursor = 9;
            		
                var highlightNode = suggestionDiv.childNodes[cursor];
                highlightSuggestion(highlightNode);
				copyProductItemNameToSearchBox( cursor );
            }
        break;
        /* Down arrow */
        case 40:
             if (suggestionDiv.childNodes.length > 0 && ( (cursor == suggestionDiv.childNodes.length-2)  || (cursor >= 9) ) )
             {
             	cursor=0;
             	var newNode = suggestionDiv.childNodes[cursor];
                highlightSuggestion(newNode);
				copyProductItemNameToSearchBox( cursor );
             }else if (suggestionDiv.childNodes.length > 0 && cursor <= suggestionDiv.childNodes.length-1)
             {
                var newNode = suggestionDiv.childNodes[++cursor];
                highlightSuggestion(newNode);
				copyProductItemNameToSearchBox( cursor );
             }
        break;
        /* Enter key = 13 */
        case 13:
    	    if (suggestionDiv.style.visibility == "hidden"){
        	//Do Search
        		window.location = curUrlSearch + inputTextField.value;
	        }else{
    	    //Redirect to product item
       	        hideSuggestions();        
		        window.location = curUrlItemInfo + curResultList[cursor].pxrfnbr;        
        	}
        	showLoadingImage();
        break;
    }
}

function keyUpHandler(inEvent) {
    var enteredText = inputTextField.value;
    var iKeyCode = inEvent.keyCode;
	
	if (iKeyCode>=37 && iKeyCode<=40){
		return null;
	}
	
	if (iKeyCode==27){
		//restore text
		inputTextField.value = unescape( sourceInputText);
	}
	
    if (iKeyCode == 32 || iKeyCode == 8 || ( 45 < iKeyCode && iKeyCode < 112) || iKeyCode > 123) /*keys to consider*/
    {
        if (enteredText.length > 0){
        
            if ( trim( inputTextField.value ) == "" )
            {
          	  searchCounter++;
			  self.setTimeout("mainSearchProcess('" + sourceInputText +"',"+ reloadArrayList+")",500);
            }
            else
            {
          	  sourceInputText = removeSpecialCharacters( trim( inputTextField.value ) );
          	  if ( sourceInputText == "" )
          	  {
   	            showLoadingImage();
   	            // Directly Submit the request.
   	            reloadArrayList( null );
        		}
        		else
        		{
	          	  searchCounter++;
			  	self.setTimeout("mainSearchProcess('" + sourceInputText +"',"+ reloadArrayList+")",500);
        	  }
            }
        
        }else{
        	hideSuggestions();
        }
    }
}

function mainSearchProcess( enteredText, funcComplete ){
	searchCounter--;
	if (searchCounter >0){
		return null;
	}
	if (enteredText.length <= 0){
		hideSuggestions;
		return null;
	}

    // Final check the input text is empty or not
    if ( trim( inputTextField.value ) == "" )
    {
		hideSuggestions;
		return null;
    }

   	showLoadingImage();
	if (curSearchType=="Product"){
		SearchEngine.getProductItemLike(enteredText, funcComplete);
	}else{
		SearchEngine.getPremiumItemLike(enteredText, funcComplete);		
	}
}

function reloadArrayList(productitem_infos){

    // Final check the input text is empty or not
    if ( trim( inputTextField.value ) == "" )
    {
	  // Hidden the Search Loading Icon.
	  document.getElementById('search_loading_icon').style.visibility="hidden";
	  hideSuggestions;
      return ;
    }
    
   	cursor = -1;

	//Remove all html tag in pxtcname and pxenname
	for(var loop=0; loop<productitem_infos.length; loop++){
		productitem_infos[loop].pxenname = removeHTMLTags(productitem_infos[loop].pxenname);
		productitem_infos[loop].pxtcname = removeHTMLTags(productitem_infos[loop].pxtcname);
	}
	
    if ( trim( removeSpecialCharacters( inputTextField.value ) ) == "" )
    {
	  // No matching product found. 
	  document.getElementById('search_loading_icon').style.visibility="hidden";
	  lookAheadArray = new Array();
	  showMessage();
      return ;
    }
    
	//var items = dwr.util.toDescriptiveString(productitem_infos, 2);
	var curArrayList = new Array();
	curResultList = productitem_infos;
	
	if (productitem_infos.length == 0){
	//No matching product found. 
		document.getElementById('search_loading_icon').style.visibility="hidden";
	}else{
		resultMap = new Object();
		
		if (searchLanguage =="tc"){
			for(var loop=0; loop<productitem_infos.length; loop++){
				curArrayList[loop] = productitem_infos[loop].pxtcname;
				resultMap[productitem_infos[loop].pxtcname]=productitem_infos[loop].pxrfnbr;
			}
		}else{
			for(var loop=0; loop<productitem_infos.length; loop++){
				curArrayList[loop] = productitem_infos[loop].pxenname;
				resultMap[productitem_infos[loop].pxenname]=productitem_infos[loop].pxrfnbr;
			}
		}
	}
	lookAheadArray = curArrayList;
	showMessage();
}

function showMessage(){
    var potentials = new Array();
    var enteredText = inputTextField.value;

	showSuggestions(lookAheadArray);
/*
	if (lookAheadArray.length > 0){
		showSuggestions(lookAheadArray);	
	}else{
		hideSuggestions();
	}	
*/
}

function hideSuggestions ()
{
    suggestionDiv.style.visibility = "hidden";
}

function highlightSuggestion(suggestionNode)
{
	//parentNode
	var snp = suggestionNode.parentNode;
	var isTableNode = false;
	
	//check level.
	if (suggestionNode.parentNode != suggestionDiv){
		suggestionNode = getSuggestionNode(suggestionNode) ;
	}
	//console.println( getSuggestionNodeLevel(suggestionNode)  );
    for (var i=0; i < suggestionDiv.childNodes.length; i++)
    {
        var sNode = suggestionDiv.childNodes[i];
        if (sNode == suggestionNode)
        {
            sNode.className = "current"
        }
        else if (sNode.className == "current")
        {
            sNode.className = "";
        }
    }
}

function showLoadingImage(){
   	//submit button relocate
    loadingImage.style.top  = findPos(inputTextField)[1] + loadingImageTopAdj;
    loadingImage.style.left = findPos(inputTextField)[0] + loadingImageLeftAdj + inputTextField.offsetWidth;
    loadingImage.style.position ="absolute";
    loadingImage.style.visibility="visible";
}

function setLoadingImageAdj(x, y){
	loadingImageLeftAdj = x;
	loadingImageTopAdj  = y;
}

function init (field, loadImage, button, language, searchType)
{
	curSearchType = searchType;
	
	if (curSearchType == "Product"){
		//Assign redirect location
		curUrlSearch = urlProductSearch;
		curUrlItemInfo = urlProductItemInfo;
	}else{
		//Assign redirect location
		curUrlSearch = urlPremiumSearch;
		curUrlItemInfo = urlPremiumItemInfo;
		
		curWidthExtension=100;
	}
	searchLanguage = language;
   	inputTextField = document.getElementById(field);
   	submitButton = document.getElementById(button);
   	loadingImage = document.getElementById(loadImage);
   
   	submitButton.onclick = function(inEvent){
   		var keywords = inputTextField.value;
		window.location = curUrlSearch + keywords;
   	}
   	

   	cursor = -1;

    inputTextField.onkeyup = function (inEvent)
    {

        if (!inEvent)
        {
            inEvent = window.event;
        }
        keyUpHandler(inEvent);
    }

    inputTextField.onkeydown = function (inEvent)
    {
        if (!inEvent)
        {
            inEvent = window.event;
        }
        keyDownHandler(inEvent);
    }
    inputTextField.onblur = function ()
    {
        hideSuggestions();
    }

    createDiv();
}

function selectRange(start , end )
{
    if (inputTextField.createTextRange) {
        var sRange = inputTextField.createTextRange();
        sRange.moveStart("character", start);
        sRange.moveEnd("character", end - inputTextField.value.length);
        sRange.select();
    } else if (inputTextField.setSelectionRange) {
        inputTextField.setSelectionRange(start, end);
    }
    inputTextField.focus();
}

function showSuggestions(suggestions)
{
    var sDiv = null;
	suggestionDiv.innerHTML="";
	
	if (suggestions.length == 0){
	    	sDiv = document.createElement("A");
	    	sDiv.setAttribute("href", "");
	    	if (searchLanguage == "en")
		    	sDiv.innerHTML = txtENNoRecordFound;
		    else
		    	sDiv.innerHTML = unescape (txtTCNoRecordFound);
	        suggestionDiv.appendChild(sDiv);		    	    
	}else{
	    for (i=0; i < suggestions.length; i++)
	    {
	    	var pxrfnbr = curResultList[i].pxrfnbr;
	    	var folderNo = Math.floor(pxrfnbr / 100);
	    	
	        sDiv = document.createElement("div");
	        sDiv.style.verticalAlign = "middle";
	        if (curResultList[i].pxsiconname !=null && curResultList[i].pxsiconext!=null)
	        {
	          var photoImage = "/px_small_"+ pxrfnbr+ "." + curResultList[i].pxsiconext;
		      sDiv.innerHTML ="<table width='100%' border='0'><tr><td width='40' valign='middle'><img src='" + urlImagePath + folderNo + photoImage + "' border='0' width='40' height='40'></td><td class='norm_text' valign='middle'>"+ suggestions[i]+"</td></tr></table>";
		    }
		    else{
		        sDiv.innerHTML ="<table width='100%' border='0'><tr><td width='40' valign='middle'><img src='"+ urlImageNotFound +"' border='0' width='40' height='40'></td><td class='norm_text' valign='middle'>"+suggestions[i]+"</td></tr></table>";	    
		    }
	        //sDiv.appendChild(document.createTextNode(suggestions[i]));
	        suggestionDiv.appendChild(sDiv);
	    }
	    
	    //Attach list all option in the list
	    if (suggestions.length >= 10){
	    	var curRedirctURL = "";
	    	if (curSearchType == "Product"){
	    		curRedirectURL = urlProductSearch + sourceInputText;
	    	}else{
	    		curRedirectURL = urlPremiumSearch + sourceInputText;
	    	}
	    	
	    	sDiv = document.createElement("A");
	    	sDiv.setAttribute("href", curRedirectURL);
	    	if (searchLanguage == "en")
		    	sDiv.innerHTML = txtENMoreResults;
		    else
		    	sDiv.innerHTML = unescape (txtTCMoreResults);
	        suggestionDiv.appendChild(sDiv);	    	
	    }
	}
    
    sDiv = document.createElement("iframe");
    sDiv.style.verticalAlign = "middle";
    suggestionDiv.appendChild(sDiv);
       
    suggestionDiv.style.top = (findPos(inputTextField)[1]+inputTextField.offsetHeight) + "px";
    suggestionDiv.style.left = findPos(inputTextField)[0]-curWidthExtension + "px";
    suggestionDiv.style.position   = "absolute";
    suggestionDiv.style.visibility = "visible";
    document.getElementById('search_loading_icon').style.visibility="hidden";
}


function typeAhead(suggestion)
{
    if (inputTextField.createTextRange || inputTextField.setSelectionRange)
    {
        var iLen = inputTextField.value.length;
        inputTextField.value = suggestion;
        selectRange(iLen, suggestion.length);
    }
}

function copyProductItemNameToSearchBox( position ){
	if ( position >=0 && position < curResultList.length){
		if(searchLanguage=='en'){
			inputTextField.value = curResultList[position].pxenname;
		}else{
		    inputTextField.value = curResultList[position].pxtcname;	            
		}
	}
}

/*
	Common Javascript Utils
*/
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);

		return [curleft,curtop];
	}
}

function removeHTMLTags(strInputCode){
 	strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1){
 	 	return (p1 == "lt")? "<" : ">";
 	});
 	return strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
}

function getSuggestionNode( childNode ){
	if (childNode != null)
	{
		var previousNode = childNode;
		for (var level=0; level < 6; level++){
			if (previousNode.parentNode == null){
				return null;
			}
			if (previousNode.parentNode == suggestionDiv){
				return previousNode;
			}
			previousNode = previousNode.parentNode;
		}
	}
	//unknown node
	return null;
}

function removeSpecialCharacters(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|', '\'',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, ' ');
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function hasAttribute(elm,attribute){
	return elm.getAttribute(attribute) != null;
}