// Rupiz Compare Javascript Document
// Created By   : Raman Sachin Omar/Vinod Chandra
// Created On   : 29th Nov, 2008
// Description  : Auto Suggestion in Mobile Section + Global Search Module

function ChangeCategory(category)
{
    var ddlValue = category.value;
    var arrValue = ddlValue.split("$"); 
    var categoryId = arrValue[0];
    if (categoryId == "85"  || categoryId == "23"  || categoryId == "24"  || categoryId == "25")
    {
        MK();        
    }
    else
    {
        MKStop();
    }       
}

function MK()
{   
    var c = document.getElementById("txtSearch");
    c.onkeypress = null;
    c.onfocus = function()
    {
        var cc = document.getElementById("txtSearchValue");
        if(this != null && cc != null)
        {var oTextbox = new AutoSuggestControl(this,cc,new StateSuggestions());}
    };    
}

function MKStop()
{
    var c = document.getElementById("txtSearch");
    c.onfocus = null;
    c.onkeypress = function(e)
    {
        var evt = e ? e : window.event;
        var bt = document.getElementById('btnGlobalSeacrh');
        if(evt.which || evt.keyCode)
        {
    	    if ((evt.which == 13) || (evt.keyCode == 13))
    	    {
    		    bt.click();
    		    evt.returnValue=false;
                evt.cancel = true;
    	    }
        }
        else
        {
    	    return true
        }
    };
        
    var cc = document.getElementById("txtSearchValue");
    if(c != null && cc != null)
    {
        var oTextbox = new AutoSuggestControl(c,cc,null);
    }
}

function FindSearch(url, defaulturl, text)
{  
    if (defaulturl != "" )
    {
        if(text != "")
        {
            window.parent.location.href = wsUrl+url+text; 
            window.parent.location.replace(wsUrl+url+text);
        }
        else
        {
             window.parent.location.href = wsUrl+defaulturl; 
             window.parent.location.replace(wsUrl+defaulturl);
        }
    }
    else
    {
        if (url!= "")
        {
            window.parent.location.href = wsUrl+url+text; 
            window.parent.location.replace(wsUrl+url+text);
        }
        else
        {    
            window.parent.location.href = defaulturl; 
            window.parent.location.replace(defaulturl);
        }
    }
}

function FindMobileSearch(url)
{
    window.parent.location.href = url; 
    window.parent.location.replace(url);
}

function ValidateSearch(ddl, txt, btn)
{
    var ddlValue = document.getElementById(ddl).value;
    var arrValue = ddlValue.split("$");    
    var catId = arrValue[0];
    var url = arrValue[1];
    var defaulturl = arrValue[2];
    var text = document.getElementById(txt).value;
    var w = document.forms[0].ctl00$ucgs$ddlCategory.selectedIndex;
    var catName = document.forms[0].ctl00$ucgs$ddlCategory.options[w].text;
    if(catId == "0")
    {
        alert("Pleae select a catergory");
        document.getElementById(ddl).focus();
        return false;
    }
    else if((catId == "1" || catId == "2" || catId == "3" || catId == "4" || catId == "5" || catId == "6"|| catId == "7" || catId == "8" || catId == "9" || catId == "10" || catId == "11" || catId == "12" || catId == "13" || catId == "15" || catId == "16" || catId == "17" || catId  == "20" || catId  == "21" || catId  == "22") && text == "")
    {
        alert("Pleae enter the text");
        document.getElementById(txt).focus();
        return false;
    }
    else
    {
        var hidValue = document.forms[0].txtSearchValue.value;
        if (text != "" )
        {
            if (catId == "23" || catId == "24" || catId == "25" || catId == "85")
            {
                if (hidValue.toLowerCase().match("h")!= null)
                {   
                    FindMobileSearch(wsUrl + "mobile/phone/deals.aspx?phonename=" + text.replace(/ /g,"-"));
                }
                else if (hidValue.toLowerCase().match("m")!= null)
                {
                    FindMobileSearch(wsUrl + "mobile/phone/brand.aspx?name=" + text.replace("Phones", "").replace("phones", "").replace(" ", ""));
                }
                else if (hidValue.toLowerCase().match("n")!= null)
                {
                    FindMobileSearch(wsUrl + "mobile/network.aspx?name=" + text.replace("Network", "").replace("network", "").replace(" ", ""));
                }
                else
                {               
                    FindMobileSearch(wsUrl + "mobile/");
                }
            }
            else
            {
                FindSearch(url, defaulturl, text);
            }
        }
        else
        {           
            FindSearch(url, defaulturl, text);            
        }
    }
}

function StateSuggestions()
{
    this.requestSuggestions =  function (oAutoSuggestControl, bTypeAhead)
    {        
        var sTextboxValue = oAutoSuggestControl.textbox.value;
        //if (sTextboxValue.length > 3){
            var ajax = GetHttpObject();
            if(ajax != null){                
                ajax.onreadystatechange = function(){
                    if(ajax.readyState == 4 && ajax.status == 200){
                        var doc = ajax.responseXML;  
                        var cnt = doc.getElementsByTagName('searchresult').length;
                        var aSuggestions = [];
                        var aValues = [];
                        for(i=0; i<cnt;i++){                                                      
                            // names
                            if(doc.getElementsByTagName("searchresult")[i].childNodes[1].textContent){
                                aSuggestions[i] = doc.getElementsByTagName("searchresult")[i].childNodes[1].textContent;           
                            }else{
                                aSuggestions[i] = doc.getElementsByTagName("searchresult")[i].childNodes[1].text;    
                            }
                            // values
                            if(doc.getElementsByTagName("searchresult")[i].childNodes[2].textContent){
                                aValues[i] = doc.getElementsByTagName("searchresult")[i].childNodes[2].textContent;     
                            }else{
                                aValues[i] = doc.getElementsByTagName("searchresult")[i].childNodes[2].text;
                            }  
                        }
                        oAutoSuggestControl.autosuggest(aSuggestions,aValues,bTypeAhead);             
                    }  
                }            
                ajax.open("GET",(wsUrl+"getautosuggest.aspx?m=" + oAutoSuggestControl.textbox.value.toLowerCase()),true);
                ajax.send(null);
            }                
        //}    
    }   
}

function AutoSuggestControl(oTextbox,oHiddenbox,oProvider)
{
    this.cur = -1;
    this.layer = null;
    this.provider = oProvider;
    this.textbox = oTextbox;
    this.hidden = oHiddenbox;
    if (oProvider != null)
    {this.init();}
    else
    {this.stop();}    
}

AutoSuggestControl.prototype.init = function()
{
    var oThis = this;
    this.textbox.onkeyup = function(oEvent)
    {
        if(!oEvent)
        {
            oEvent = window.event;
        }    
        oThis.handleKeyUp(oEvent);
    };

    this.textbox.onkeydown = function (oEvent)
    {
        if (!oEvent)
        {
            oEvent = window.event;
        }    
        return oThis.handleKeyDown(oEvent);
    };

    this.textbox.onblur = function()
    {
        oThis.hideSuggestions();
    };
    
    this.createDropDown();
};

AutoSuggestControl.prototype.stop = function(){
    var oThis = this;
    this.textbox.onkeyup = function(oEvent)
    {
        if(!oEvent)
        {
            oThis.hideSuggestions();
        }    
    };
    this.textbox.onkeydown = function (oEvent)
    {     
        if(!oEvent)
        {
            oEvent = window.event;
        }
        return oThis.handleKeyDownOnDeactivate(oEvent);    
    };
    this.textbox.onblur = function()
    {
        oThis.hideSuggestions();
    };
};

AutoSuggestControl.prototype.handleKeyUp = function (oEvent){
    var iKeyCode = oEvent.keyCode;
    //for backspace (8) and delete (46), shows suggestions without typeahead
    if (iKeyCode == 8 || iKeyCode == 46) {
        this.provider.requestSuggestions(this, false);        
    //make sure not to interfere with non-character keys
    } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
        //ignore
    } else {
        //request suggestions from the suggestion provider with typeahead
        this.provider.requestSuggestions(this, true);
    }
};

AutoSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) {
    
    switch(oEvent.keyCode) {
        case 38: //up arrow
            this.previousSuggestion();
            break;
        case 40: //down arrow 
            this.nextSuggestion();
            break;
        case 13: //enter
            if(window.event) window.event.cancelBubble = true;             
	        if(oEvent.stopPropagation) oEvent.stopPropagation();
            document.forms[0].btnGlobalSeacrh.click();
            this.hideSuggestions();
            return false;
            break;
    }
};

AutoSuggestControl.prototype.handleKeyDownOnDeactivate = function (oEvent /*:Event*/) {    
    switch(oEvent.keyCode) {        
        case 13: //enter
            if(window.event) window.event.cancelBubble = true;     
	        if(oEvent.stopPropagation) oEvent.stopPropagation();
            document.forms[0].btnGlobalSeacrh.click();                           
            return false;
            break;
    }
};

AutoSuggestControl.prototype.hideSuggestions = function () 
{
    if(this.layer)
        this.layer.style.visibility = "hidden";    
};

AutoSuggestControl.prototype.createDropDown = function () {
    var oThis = this;    
    this.layer = document.createElement("div");
    this.layer.className = "suggestions";
    this.layer.style.visibility = "hidden";
    this.layer.style.width = this.textbox.offsetWidth;
    document.body.appendChild(this.layer);   
};

AutoSuggestControl.prototype.autosuggest = function (aSuggestions,aValues,bTypeAhead){
    if (aSuggestions.length > 0){
        if (bTypeAhead){
            this.typeAhead(aSuggestions[0],aValues[0]);
        }
        this.showSuggestions(aSuggestions,aValues);
    }else{
        document.getElementById("txtSearchValue").value = "";
        this.hideSuggestions();
    }
};
AutoSuggestControl.prototype.getLeft = function(){
    var oNode = this.textbox;
    var iLeft = 0;
    while(oNode.tagName != "BODY") {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;        
    }
    return iLeft;
};

AutoSuggestControl.prototype.getTop = function(){
    var oNode = this.textbox;
    var iTop = 0;
    while(oNode.tagName != "BODY") {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }
    return iTop;
};

AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode){
    for (var i=0; i < this.layer.childNodes.length; i++) {
        var oNode = this.layer.childNodes[i];
        if (oNode == oSuggestionNode) {
            oNode.className = "current"
        } else if (oNode.className == "current") {
            oNode.className = "";
        }
    }
};

AutoSuggestControl.prototype.nextSuggestion = function (){
    var cSuggestionNodes = this.layer.childNodes;
    if (cSuggestionNodes.length > 0 && this.cur < cSuggestionNodes.length-1){
        var oNode = cSuggestionNodes[++this.cur];
        this.highlightSuggestion(oNode);
        this.textbox.value = oNode.childNodes[0].childNodes[0].nodeValue;
        this.hidden.value = oNode.childNodes[1].childNodes[0].nodeValue;
    }
};

AutoSuggestControl.prototype.previousSuggestion = function () {
    var cSuggestionNodes = this.layer.childNodes;
    if (cSuggestionNodes.length > 0 && this.cur > 0) {
        var oNode = cSuggestionNodes[--this.cur];
        this.highlightSuggestion(oNode);
        this.textbox.value = oNode.childNodes[0].childNodes[0].nodeValue;
        this.hidden.value = oNode.childNodes[1].childNodes[0].nodeValue;
    }
};

AutoSuggestControl.prototype.selectRange = function(iStart, iLength){
    if (this.textbox.createTextRange) {
        var oRange = this.textbox.createTextRange(); 
        oRange.moveStart("character", iStart); 
        oRange.moveEnd("character", iLength - this.textbox.value.length);      
        oRange.select();        
    //use setSelectionRange() for Mozilla
    } else if (this.textbox.setSelectionRange) {
        this.textbox.setSelectionRange(iStart, iLength);
    }     
    this.textbox.focus();      
}; 

AutoSuggestControl.prototype.showSuggestions = function (aSuggestions,aValues){
    var oThis = this;
    var oDiv = null;
    this.layer.innerHTML = "";    
    var cnt = parseInt(((aSuggestions.length+aValues.length)/2));    
    for (var i=0; i < cnt; i++){
        oDiv = document.createElement("div");
        oInner1 = document.createElement("div");
        oInner1.appendChild(document.createTextNode(aSuggestions[i]));
        oInner2 = document.createElement("div");        
        oInner2.style.display = "none";
        oInner2.appendChild(document.createTextNode(aValues[i]));
        oDiv.appendChild(oInner1);
        oDiv.appendChild(oInner2);
        oDiv.onmousedown =
        oDiv.onmouseover = function (oEvent){
        oEvent = oEvent || window.event;
        if (oEvent.type == "mousedown"){
            oThis.textbox.value = this.childNodes[0].childNodes[0].nodeValue;
            oThis.hidden.value = this.childNodes[1].childNodes[0].nodeValue;         
            oThis.hideSuggestions();
            // On Click Fire Enter
            var evt = oEvent ? oEvent : window.event;
            var bt = document.getElementById('btnGlobalSeacrh');           
	        bt.click();
	        evt.returnValue=false;
            evt.cancel = true;  
            // End            
        } else if (oEvent.type == "mouseover") {
            oThis.highlightSuggestion(this);
        } else {
            oThis.textbox.focus();
        }
    };
        this.layer.appendChild(oDiv);
    }
    
    this.layer.style.left = this.getLeft() + "px";
    this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px";
    this.layer.style.visibility = "visible";

};

AutoSuggestControl.prototype.typeAhead = function (sSuggestion, sValue){
    if (this.textbox.createTextRange || this.textbox.setSelectionRange){
        var iLen = this.textbox.value.length; 
        this.textbox.value = sSuggestion;
        this.hidden.value = sValue;  
        this.selectRange(iLen, sSuggestion.length);
    }
};




