﻿// JScript File

///// For Header Search Added By Manoj kumar on 03Nov 2009 
////modifi by vikas Singh
//Search for Global search Deal,Video,Photo,mobile
var wsUrl = "http://www.Shopcorn.co.uk/";    
//var wsUrl = "http://172.16.15.45/ShopcornUK/";
//var wsUrl = "http://localhost/ShopcornUK/";

 
  
  ////////////////////////// Encode Decode ////////////////////////////////////
  
  
var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) 
	{
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) 
	{
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
        //document.write(output);
        document.getElementById("ctl00_ContentPlaceHolder1_hdstxt").value = output;
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) 
	{
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) 
	{
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

  
  
  ///////////////////////////////////////////////////////////////
  
  
  
  
function GetHttpObject(){
    var xmlHttpObj;
    try {   
        xmlHttpObj = new XMLHttpRequest();              
        return xmlHttpObj;
    }
    catch (e){        
        try{
            xmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");                   
            return xmlHttpObj; 
        }
        catch (e){           
            try{
                xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");                      
                return xmlHttpObj;      
            }
            catch (e)
            {        
                alert("Sorry, Your browser does not support AJAX!");        
                return null;        
            }     
        }   
    }     
} 
function trimStr(str) 
{
  return str.replace(/^\s+|\s+$/g, '');
}

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"), "");
}

//Validation For PostCode
function validatePostalCode(contents, objref)
{
    
     size = contents.length;
     contents = contents.toUpperCase(); //Change to uppercase
     while (contents.slice(0,1) == " ") //Strip leading spaces
      {
        contents = contents.substr(1,size-1);
        size = contents.length
      }
     while(contents.slice(size-1,size)== " ") //Strip trailing spaces
      {
        contents = contents.substr(0,size-1);
          size = contents.length
      }
     document.getElementById(objref).value = contents; //write back to form field
     if (size < 6 || size > 8)
     { //Code length rule
      alert(contents + " Bah! Invalid PostCode: Wrong Length!");
      document.getElementById(objref).focus();
      return false;
      }
     if (!(isNaN(contents.charAt(0))))
     { //leftmost character must be alpha character rule
       alert(contents + " Bah! Invalid PostCode: Cant start with a Number!");
       document.getElementById(objref).focus();
       return false;
      }
     if (isNaN(contents.charAt(size-3)))
     { //first character of inward code must be numeric rule
       alert(contents + " Bah! Invalid PostCode: Alphabet in wrong position!");
       document.getElementById(objref).focus();
       return false;
      }
     if (!(isNaN(contents.charAt(size-2))))
     { //second character of inward code must be alpha rule
       alert(contents + " Bah! Invalid PostCode: Number in wrong position!");
       document.getElementById(objref).focus();
       return false;
      }
     if (!(isNaN(contents.charAt(size-1))))
     { //third character of inward code must be alpha rule
       alert(contents + " Bah! Invalid PostCode: Number in wrong position!");
       document.getElementById(objref).focus();
       return false;
      }
     if (!(contents.charAt(size-4) == " "))
     {//space in position length-3 rule
       alert(contents + " Bah! Invalid PostCode: Wrong spacing!");
       document.getElementById(objref).focus();
       return false;
       }
     count1 = contents.indexOf(" ");
     count2 = contents.lastIndexOf(" ");
     if (count1 != count2)
      {//only one space rule
       alert(contents + " Bah! Invalid PostCode: Only one space allowed!");
       document.getElementById(objref).focus();
       return false;
      }      
      return true;
}
  function FindMobileSearch(url){
     //alert(url);   
    try
    {
     window.location.href = url;  
    window.location.replace(url);
  
    }
    catch(ex)
    {
        alert("error"+ex.description);
    }
} 


function valsearch()
{
   try{ var baseurl= document.getElementById("hdburl").value;
    var str = "Enter your text...." ;
    var stx = trim(document.getElementById("ctl00_ucheader_txtsearch").value,' ');
    var sty = trim(document.getElementById("SelsearchCat").value,' ');
    var txtval = trim(document.getElementById("ctl00_ucheader_txtsearch").value,' ');
    var loc = "";
    if(txtval == "" || txtval == str)    
        {
            if(document.getElementById("SelsearchCat").value == "broadband" || document.getElementById("SelsearchCat").value == "utility")
             alert("Please Enter PostCode !");
            else
             alert("Please Enter Search Text !");
            document.getElementById("ctl00_ucheader_txtsearch").value="";
            document.getElementById("ctl00_ucheader_txtsearch").focus();        
            return false;          
        }
        if(sty == "broadband" || sty == "utility"|| sty == "deal"|| sty == "video"|| sty == "photo")
        {       if(sty == "broadband" || sty == "utility")
                {
                    if(!validatePostalCode(txtval, "ctl00_ucheader_txtsearch"))
                    return false;
                    else if (sty == "broadband")
                    {
                    loc = baseurl +"broadband/search-result.aspx?postcode=" + stx;
                    }
                    else if (sty == "utility")
                    {
                    loc = baseurl +"utilities/default.aspx?sitesearch=y&postcode=" + stx;
                    }
               }
              else
               {
                   stx = Base64.encode(stx);
                   //alert(stx);
                  loc = baseurl +"deal-box/search-result.aspx?searchtext=" + stx + "&searchtype=" + sty;
               }  //alert(loc);
                    window.location.replace(loc);
                    window.location=loc;       
                 
        }
       if(sty == "mobile" )
        {
            var hidValue = document.forms[0].txtSearchValue.value;
        // alert(hidValue);
            if (hidValue.toLowerCase().match("h")=="h")
            {   
                FindMobileSearch(wsUrl + "mobile/mobile-deals.aspx?phonename=" + txtval.replace(/ /g,"-"));
            }
            else if (hidValue.toLowerCase().match("m")=="m")
            {
                FindMobileSearch(wsUrl + "mobile/mobile-gallery.aspx?name=" + txtval.replace("Phones", "").replace("phones", ""));
            }
            else if (hidValue.toLowerCase().match("n")=="n")
            {
                 FindMobileSearch(wsUrl + "mobile/network.aspx?name=" + txtval.replace("Network", "").replace("network", "").replace(" ", ""));
            }
            else
            {               
                FindMobileSearch(wsUrl + "mobile/");
            }
         }
         return true;
      }catch(ex){
            alert(ex.description);
        }
            
       
}  

function cleartext()
{
  var str = "Enter your text...." ;
  var str1 = "Enter your PostCode...." ;
  var txt = document.getElementById("ctl00_ucheader_txtsearch").value;
  if(txt == str || txt==str1)
   document.getElementById("ctl00_ucheader_txtsearch").value = "";   
  return true;
}

function hidDiv()
{
  document.getElementById('dealsubmit').style.display="none";
}
function Showdiv()
{
    if(document.getElementById('dealsubmit').style.display=="inline")
    {
        document.getElementById('dealsubmit').style.display="none";
    }
    else
    {  
        document.getElementById('dealsubmit').style.display="inline";
    }
}

function clickButton(e,buttonid)
{
    var key;
    if(window.event)
    key = window.event.keyCode;     //IE
    else
    key = e.which;     //firefox
    if (key == 13)
        {
            var btn = document.getElementById(buttonid);
            if (btn != null)
            { btn.click();}
            return false;            
        }  
}
function selchange()
{
     var sel= document.getElementById("SelsearchCat").value;
     var str = "Enter your text...." ;
     var str1 = "Enter your PostCode...." ;
     var txt = document.getElementById("ctl00_ucheader_txtsearch").value;  
    if(sel=="broadband" || sel=="utility" )
      {
        if(txt == str || txt=="")
        document.getElementById("ctl00_ucheader_txtsearch").value = str1;      
      }      
      if(sel=="deal" || sel=="video" || sel=="photo"||sel=="mobile" )
         if(txt == str1 || txt=="")
            document.getElementById("ctl00_ucheader_txtsearch").value = str;
     if(sel=="mobile")
        { 

           MK();   //start autoSuggestions              
        }
        else
        {
            MKStop();   //stop autoSuggestions     
        }              
}
function MK()
{  
    var c = document.getElementById("ctl00_ucheader_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("ctl00_ucheader_txtsearch");
    c.onfocus = null;
    c.onkeypress = function(e)
    {
        var evt = e ? e : window.event;
        var bt = document.getElementById('btnGSearch');
        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 StateSuggestions()
{
    this.requestSuggestions =  function (oAutoSuggestControl, bTypeAhead)
    {        
        var sTextboxValue = oAutoSuggestControl.textbox.value;

        if (sTextboxValue.length > 1){
            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].btnGSearch.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].btnGSearch.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('btnGSearch');           
	        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);
    }
};
