﻿
function isNumberKey(evt)
{
     var charCode = (evt.which) ? evt.which : event.keyCode
     if (charCode > 31 && (charCode < 48 || charCode > 57))
     {
        if (charCode == 46)
        {
            return true;
        }
        return false;
     }
     return true;
}
function checkPriceRange(val){
            var reg=/^([0-9]+)[.]([0-9]{2})$/;
            var reg1=/^([0-9]+)[.]([0-9]{1})$/;
            var reg2=/^([0-9]+)[.]([0-9]{0})$/;
            var reg3=/^([0-9]+)$/;  
            var reg4=/^[.]([0-9]{2})$/;
            var reg5=/^[.]([0-9]{1})$/;
            if(reg.test(val) || reg1.test(val) || reg2.test(val) || reg3.test(val) || reg4.test(val) || reg5.test(val))
            return true;
            return false;
        } 
function ShowHideAdvancesearch(ele){
    var trSearch2 = _$("tr_search2");
    var trSearch3 = _$("tr_search3");
    var btnGO = _$('ctl00_AdvancedSearch1_btnSSearch');
    var btnSearch = _$('ctl00_AdvancedSearch1_btnASearch');
    var div_Error_Message_Simple = _$('ValidationSummary2');
    var div_Error_Message_Advance = _$('ValidationSummary1');
    if(trSearch2 != null){
        if(trSearch2.style.display==''){
            display(trSearch2,'none');
            display(trSearch3,'none');
            ele.innerHTML = "Advanced Search";
            //divSearch.setAttribute("class","search-simple");
            display(btnGO,'');
            display(div_Error_Message_Simple,'none');
            display(div_Error_Message_Advance,'none');
            //btnSearch.style.display = 'none';
        }else{
            display(trSearch2,'');
            display(trSearch3,'');
            ele.innerHTML = "Simple Search";        
            //divSearch.setAttribute("class","search-advance");
            display(btnGO,'none');
            display(div_Error_Message_Simple,'none');
            display(div_Error_Message_Advance,'none');
            //btnSearch.style.display = '';
        }
    }
    return false;
}
function searchClick(ele){
    Cookies();
    //Getting store
    var storeDrp = _$('ctl00_AdvancedSearch1_drpSStore');
    var storeSelectedIndex = storeDrp.selectedIndex;
    var storeName = storeDrp.options[storeSelectedIndex].text;
    var StoreId = storeDrp.options[storeSelectedIndex].value;
    //Getting brand
    var brandDrp = _$('ctl00_AdvancedSearch1_drpSBrand');
    var brandSelectedIndex = brandDrp.selectedIndex;
    var brandName = brandDrp.options[brandSelectedIndex].text;
    var arrayBrand;
    arrayBrand = brandDrp.options[brandSelectedIndex].value.split(",");
    var BrandId = arrayBrand[0];
    var BrandCategoryID = arrayBrand[1];
    var BrandCode = arrayBrand[2];
    var BrandCodeId = arrayBrand[3];
    //Getting Category
    var categoryDrp = _$('ctl00_AdvancedSearch1_drpSCategory');
    var catSelectedIndex = categoryDrp.selectedIndex;
    var classCatName = categoryDrp.options[catSelectedIndex].text; 
    var arrayCategory = categoryDrp.options[catSelectedIndex].value.split(",");
    var ClassCode=arrayCategory[0];
    var ClassCatId=arrayCategory[1];
    //Getting Search Key Word
    var textSearchKey = _$('ctl00_AdvancedSearch1_txtSKeywords').value;
    var trSearch2 = document.getElementById("tr_search2");
    var div_Error_Message_Simple = _$('ValidationSummary2');
    var div_Error_Message_Advance = _$('ValidationSummary1');
    textSearchKey =textSearchKey.trim();//Added line for trimming white space
    if((textSearchKey == "Keywords" || textSearchKey =="") && StoreId == 0)
    {
        if(trSearch2.style.display =='none'){
           return displayErrorMessage(div_Error_Message_Simple,"Please input valid Search Criteria.");            
        }
        else{
           return displayErrorMessage(div_Error_Message_Advance,"Please input valid Search Criteria.");
        }
    }
    else
    {
        div_Error_Message_Simple.style.display = 'none';
        div_Error_Message_Advance.style.display = 'none';
    }
    if(textSearchKey != "Keywords" && textSearchKey !="")
    {
        if (textSearchKey.match("\t"))
        {
            textSearchKey = textSearchKey.replace("\t", "");
        }
    }
    textSearchKey = generateURL(textSearchKey);
    var keyWord;
    if(textSearchKey == "Keywords" || textSearchKey =="")
    {
         keyWord = "EmptyKey";
    }
    else
    {
        keyWord = textSearchKey;
    }
    // Getting values for advance controls.
    var strFrom = _$('ctl00_AdvancedSearch1_txtFrom').value;
    var strTo = _$('ctl00_AdvancedSearch1_txtTo').value;
    strFrom = (strFrom=='' || strFrom == 'From $' || trSearch2.style.display == 'none') ? '0' : strFrom;
    strTo = (strTo=='' || strTo == 'To $' || trSearch2.style.display == 'none') ? '0' : strTo;
    if(strFrom != 0){
        if(!checkPriceRange(strFrom)){
           return displayErrorMessage(div_Error_Message_Advance,"Please input valid Search Criteria.");
        }
    }
    if(strTo != 0){
        if(!checkPriceRange(strTo)){
            return displayErrorMessage(div_Error_Message_Advance,"Please input valid Search Criteria.");
        }
    }
    strFrom = parseFloat(strFrom);
    strTo = parseFloat(strTo);
    if(strFrom > strTo){
           return displayErrorMessage(div_Error_Message_Advance,"Please input valid Search Criteria.");
    }
    var checkBox = _$('td_gradeCheckBox');
    var arr_check = checkBox.getElementsByTagName("INPUT");
    var strGrades = "Grade";
    for(var i = 0; i<arr_check.length; i++)
    {
        if(arr_check[i]!=null && arr_check[i].parentNode !=null && arr_check[i].checked){
            if(strGrades == 'Grade')
                strGrades = arr_check[i].parentNode.getAttribute("val");
            else
                strGrades += ','+arr_check[i].parentNode.getAttribute("val");               
        }
    }
    BrandCode = (BrandCode == '0')?('Brand'):(BrandCode);
    ClassCode = (ClassCode == '0')?('Class'):(ClassCode);
    //Storing value in cookie, replacing old value.
    storeValueInCookies(keyWord, storeName, brandName, classCatName, strGrades, strFrom, strTo);
    brandName = (brandName == '--- All Brands ---')?('Brand'):(brandName);
    classCatName = (classCatName == '--- All Categories ---')?('Class'):(classCatName);
    if(StoreId != "0" && BrandId == "0" && ClassCode == "Class" && keyWord == "EmptyKey" && strFrom == 0 && strTo == 0 && strGrades == "Grade"){
        //OLD LINE//window.location = getBasePageURL() + "/Store-Brands/" + StoreId + ".aspx"; //need to change this address with live address
        window.location = getBasePageURL() + "/camera?s=" + StoreId; //need to change this address with live address
        return;
    }if (StoreId != 0 && BrandCode == "FI" && ClassCode == "Class" && keyWord == "EmptyKey" && strFrom == "0" && strTo == "0" && strGrades == "Grade")
    {
        // OLD LINE //window.location = getBasePageURL() + "/Search-Filter-Classes/" + generateURL(storeName) + "/" +
        //generateURL(brandName) +  "/" + "NA" + "/" + "FI" + "/" + StoreId + "/" + BrandCategoryID + "/" + 
        //BrandCodeId + ".aspx";
        window.location = getBasePageURL() + "/Camera/format-" + generateURL(brandName) +  "/system-NA?s=" + StoreId + "&bc=" + BrandCategoryID + "&bcode=FI&bco=" + BrandCodeId;
    }
    //Implemented to redirect on selection of Store = camera and Brand = Filter and Class = Filter.
    //Redirects to classcategory of contents page.
    else if (StoreId != 0 && BrandCode == "FI" && ClassCode == "24" && keyWord == "EmptyKey" && strFrom == "0" && strTo == "0" && strGrades == "Grade")
    {
        window.location = getBasePageURL() + "/FilterRangeTableOfContent.aspx?STORE_ID=" + StoreId +
        "&B_CODE=" + "FI" + "&C_CODE=" + "24" + "&C_CAT_ID=" + ClassCatId + "&STORE_NAME=" + generateURL(storeName) +
        "&BRAND_NAME=" + generateURL(brandName) + "&REDIRECTION_NAME=SE";
    }
    else if(StoreId != 0 && BrandCode != "Brand" && ClassCode == "Class" && keyWord == "EmptyKey" && strFrom == "0" && strTo == "0" && strGrades == "Grade"){
        window.location = getBasePageURL() + "/Camera/format-NA" +  "/system-" + generateURL(brandName) + "?s=" + StoreId + "&bc=" + BrandCategoryID + "&bcode="+BrandCode+"&bco=" + BrandCodeId;
    }
    else
    {
        //OLD LINE //window.location = getBasePageURL() + "/Search-Products/" + StoreId + "/" + BrandCode + "/" + ClassCode + "/" + keyWord + "/"+strGrades+"/"+strFrom+"/"+strTo+"/SE.aspx";    
        window.location = getBasePageURL() + "/search?store=camera&brand=" + generateURL(brandName)+"&category="+generateURL(classCatName)+"&k="+generateURL(keyWord)+"&s="+StoreId+"&bcode=" + BrandCode +
        "&ccode=" + ClassCode + "&grade=" + strGrades+"&sprice="+strFrom+"&eprice="+strTo+"&r=SE&e";        
    }
   
}  
function displayErrorMessage(ele,msg){display(ele,'');ele.innerHTML = msg;return false;}
function display(ele,val){if(ele!=null && ele.style!=null)ele.style.display=val;}
function _$(id){return document.getElementById(id);}
function storeValueInCookies(keyWord, storeName, brandName, classCatName, strGrades, strFrom, strTo)
{
    var exdate = new Date();
    exdate.setMinutes(exdate.getMinutes()+5);    
    if(brandName == '--- All Brands ---')
        brandName = ' ' + brandName;
    if(classCatName =='--- All Categories ---')
        classCatName = ' ' + classCatName;
    document.cookie = "KEH5687 = " + storeName + "#" + brandName + "#" + classCatName + "#" + keyWord +"#"+strGrades+"#"+strFrom+"#"+strTo + ";expires=" + exdate.toUTCString() + "; path=/";
}
function generateURL(searchKey)
{
    var stringURL = searchKey;
        stringURL = ReplaceAll(stringURL, "&", "scamp");
        stringURL = ReplaceAll(stringURL, "/", "scfs");
        stringURL = ReplaceAll(stringURL, "\\", "scbs");
        stringURL = ReplaceAll(stringURL, "%", "scpe");
        stringURL = ReplaceAll(stringURL, "'", "scsi");
        stringURL = ReplaceAll(stringURL, " ", "-");
        stringURL = ReplaceAll(stringURL, "*", "scas");
        stringURL = ReplaceAll(stringURL, ".", "scdo");
        return stringURL;
} 
function ReplaceAll(Source,stringToFind,stringToReplace){
  var temp = Source;
    var index = temp.indexOf(stringToFind);
        while(index != -1){
            temp = temp.replace(stringToFind,stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
}
function filterKey(evt)
{
     var charCode = (evt.which) ? evt.which : event.keyCode;
     //restricting ' and #
     if(charCode == 39 || charCode == 35 || charCode == 34 || charCode == 92 || charCode == 60 || charCode == 94 || charCode == 62 || charCode == 58 || charCode == 59  || charCode == 124)
     {
        return false;
     }
     return true;
}
function selectChange(ch){
    var storeDropDown = _$('ctl00_AdvancedSearch1_drpSStore');;
    var brandDropDown = _$('ctl00_AdvancedSearch1_drpSBrand');
    var categoryDropDown = _$('ctl00_AdvancedSearch1_drpSCategory');
    if(ch == 'store'){
        if(isValidSelection(storeDropDown)){
            //Empty both dropdowns
            emptyDropDown(brandDropDown);
            emptyDropDown(categoryDropDown);
        }else{
            // Load Brand Dropdown
            loadDropDownsFromServer(storeDropDown,brandDropDown,'store');
        }
    }else{
        if(isValidSelection(brandDropDown)){
            // Empty Category DropDown
            emptyDropDown(categoryDropDown);
        }else{
            //Load Category DropDown
            loadDropDownsFromServer(brandDropDown,categoryDropDown,'brand');
        }
    }
}
function isValidSelection(eleDropDown){
    var selectedIndex = eleDropDown.selectedIndex;
    var selectedValue = eleDropDown.options[eleDropDown.selectedIndex].value.split(',')[0];
    return (selectedIndex == 0 || selectedValue == 0)
}
function loadDropDownsFromServer(dropDownFrom, dropDownTo, info){
    // Get selected Brand ID
    var key = dropDownFrom.options[dropDownFrom.selectedIndex].value.split(',')[0];
    // Make http call to get category values
    var xmlhttp=initXMLHttp();
    if (xmlhttp!=null)
    {
        var today = new Date();
        var fullUrl=getBasePageURL()+'/Migration/ShowCategory.aspx?info='+info+'&key='+key+'&uniq='+today.getMilliseconds();
        if(window.location.protocol == 'https:'){
            fullUrl='https://www.keh.com/Migration/ShowCategory-secure.aspx?info='+info+'&key='+key+'&uniq='+today.getMilliseconds();
        }
        xmlhttp.onreadystatechange=function (){
            if(xmlhttp.readyState == 4){
                var result=xmlhttp.responseText;
                result = result.split("#")[0];
                loadValues(dropDownTo,result,xmlhttp.responseXML);
            }
        }
        xmlhttp.open('GET',fullUrl,true)
        xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlhttp.send(null);
    }
    else
    {
      alert("Your browser does not support XMLHTTP.");
    }
}
function loadValues(eleDropDown, values, xml){
    // load values in category drop down
    emptyDropDown(eleDropDown);
    if (navigator.userAgent.indexOf('MSIE') !=-1){
        // Code for IE
        var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(values); 
        var optionArray = xmlDoc.getElementsByTagName('option');
        for(var i=0;i<optionArray.length;i++){
            var option = new Option(optionArray[i].firstChild.nodeValue,optionArray[i].getAttribute("value"));
            if(optionArray[i].getAttribute("style")){
                option.style.color='red';
            }
            eleDropDown.options.add(option);
        }
    }else{
        values = values.replace('<select>','');
        values = values.replace('</select>','');
        eleDropDown.innerHTML += values;
    }
}
function emptyDropDown(ele){
    if(ele){
        // Sp Case: starting from 1 to leave default option.
        for (var i = ele.options.length-1;i>0;i--) {
            ele.options[i] = null;
        }
    }
}
    function Cookies1()
    {
          if (navigator.cookieEnabled)
          {
                return true;
          }
          else
          {
              //alert('You will require cookies enabled to use functionality.');
              //window.location.replace("CookiesInstructions.aspx");
              window.location.href = "CookiesInstructions.aspx";
          }        
    }
            
  function Cookies()
  {
    if(document.cookie.indexOf("TemporaryTestCookie=")  ==  -1) 
    {
      window.location.href = "/CookiesInstructions.aspx";
       return false;
    }
    else
    {
       return true;
    }
  }   
document.cookie = "TemporaryTestCookie=yes;" ;
