﻿// -- MSIE 6.0 & 7.0
var ie7 = /MSIE 7.0/g.test(navigator.userAgent),
ie6 = /MSIE 6.0/g.test(navigator.userAgent),
classAttr = (ie7 || ie6) ? "className":"class";

// default string for search box
var origVal = searchWordsInput.val();
searchWordsInput.focus(function(){
    if (this.value == origVal) {
        this.value = '';
    };
});
searchWordsInput.blur(function(){
    if (this.value == '') {
        this.value = origVal;
    };
});

function redirectToProduct(prodID) {
    $.ajax({
        type: "POST",
        url: "/webservices/JSONsearch.asmx/getURLByRowID",
        data: "{ theID: '"+prodID+"' }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function(msg,status,err)
        {
        
        //alert(msg + ' / ' + staus + ' ' + err);
        },
        success: function(msg)
        {
            
            window.location = msg.d;
        }
    });
};

// -- global vars for kbd nav
window.ajaxSearchResults = [];
window.kbdIdx = -1;
window.highlightedElement = null;
window.hasKbdHighlight = false;

// ajax post 
var isLoading = false;
$(document).ready(function() {

    $("#cDIV_Loader").ajaxStart(function(){
        $(this).toggle();
        $("#cDIV_SearchResults").css("display","block");
        isLoading = true;
    })
    .ajaxStop(function(){
        $(this).toggle();
        isLoading = false;
    });
    
    // -- keyboard navigation
    
    searchWordsInput.keydown(function(e) {
        if ( e.which == 13 ) {
             $(this).keyup();
             return false;
         }
      
    });
    
	searchWordsInput.keyup(function(e) {
	    if(this.value.length > 1 && this.value != origVal) {
	        var keyId = e.which,
	        len = window.ajaxSearchResults.length;
	        if(keyId == 13) {
	            if(window.hasKbdHighlight){ 
	                window.ajaxSearchResults[window.kbdIdx].onclick();	                
	            };
	            return false;
	        } else if (keyId > 36 && keyId < 41 ){
                if (keyId == 37) { // left
                    window.kbdIdx -= Math.round(len/2);
                    if(window.kbdIdx < 0) {
                        window.kbdIdx += Math.round(len/2);
                    };
                } else if(keyId == 38) { // up
                    window.kbdIdx > 0 && window.kbdIdx--;
                } else if(keyId == 39) { // right
                    window.kbdIdx += Math.round(len/2);
                    if(window.kbdIdx >= len) {
                        window.kbdIdx -= Math.round(len/2);
                    };                    
                } else if(keyId == 40) { // down
                    window.kbdIdx < (len-1) && window.kbdIdx++;
                };
                
                if(window.highlightedElement != null){
                    window.highlightedElement.style.backgroundColor = "";
                };
                if( window.ajaxSearchResults[window.kbdIdx]) window.ajaxSearchResults[window.kbdIdx].style.backgroundColor = "#DBEEFD";
                window.highlightedElement = window.ajaxSearchResults[window.kbdIdx];
                window.hasKbdHighlight = true;
                
	        } else {
               (throttle(function(){
	                if(!isLoading){PostToServer();}
                },800))();
            }; 
        };
    });
    
    
    function throttle(f, delay){
        var timer = null;
        return function(){
        var context = this, args = arguments;
        clearTimeout(timer);
        timer = window.setTimeout(function(){
            f.apply(context, args);
            },
            delay || 250);
        };
    } ;
});  

// highlight matched words 
function highlight(str,filters) {        
    var matches = str.split(" "),
    len = matches.length;
    
    while(len--) {
        var word = matches[len];
        if (word != "" && word.length > 1) {
            for(var y in filters) {
                var filter = filters[y].toLowerCase(),
                regex = new RegExp(filter, "gi");
                if (regex.test(word)) {
                    word = "<span class='theHighlight'>" + word + "</span>"
                    matches.splice(len,1,word);
                };
            };
        };
    };
    
    return matches.join(" ");
};  


// --- POST TO SERVER
function PostToServer() {
    var theWords = searchWordsInput.val().trim().makeSafe();
    window.kbdIdx = -1;    
    window.hasKbdHighlight = false;
    if (theWords != '')
    {
        $.ajax({
            type: "POST",
            url: "/webservices/JSONsearch.asmx/FindResults",
            data: "{ theWords: '" + theWords + "', theEBID: '" + $(".theEBID").val() + "' }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function(msg,status,err)
            {
            //alert(msg + ' / ' + staus + ' ' + err);
            },
            success: function(msg)
            {
                $("#cDIV_ListLeft").html('');
                $("#cDIV_ListRight").html('');

                var list = $("#cDIV_ListLeft").append('<ul></ul>').find('ul');
                var list2 = $("#cDIV_ListRight").append('<ul></ul>').find('ul');
                var liArr1 = [], liArr2 = [];
                
                var fLen = 0;
                var filters = theWords.split(" ");
                while(fLen < filters.length) {
                    if (filters[fLen].length < 2) {
                        filters.splice(fLen,1);
                    } else {
                        fLen++;
                    };
                };
                
                var putLeft = true;
                $.each(
                msg.d, function(index,object)
                {
                    if(index != 0) {
                        var li = document.createElement("li");
                                    
                        li.innerHTML = highlight(object._ProductName,filters);
                        li.onclick = function(){
                           redirectToProduct(object._ProductID);
                        };
                        
                        if (putLeft){
                            liArr1.push(li);
                        }else{
                            liArr2.push(li);
                        }
                        putLeft = !putLeft;
                    }
                });
                
                list.append(liArr1);
                list2.append(liArr2);
                window.ajaxSearchResults = [];
                window.ajaxSearchResults = window.ajaxSearchResults.concat(liArr1,liArr2);
                setTimeout(function(){
                    $(document).click(function(){
                        $("#cDIV_SearchResults").css("display","none");
                        $(document).unbind("click");
                    });
                },1);
                
                var max = 30;
                if(msg.d[0]._ProductID < 30){max=msg.d[0]._ProductID}
                $("#cDIV_ListBottom").html('<b>Showing top ' + max + ' of ' + msg.d[0]._ProductID + ' results</b>');
                $("#cDIV_ListTop").html('<p><b>Show all results for <span id="freeText">"' + theWords + '"</span> in <a href="/search?cat=3&txt=' + theWords + '&st=0" class="searchResultCat"><img src="/images/search/glasses.png" /></a> <a href="/search?cat=4&txt=' + theWords + '&st=0" class="searchResultCat"><img src="/images/search/sunglasses.png" /></a> <a href="/search?cat=2&txt=' + theWords + '&st=0" class="searchResultCat"><img src="/images/search/contacts.png" /></a> <a href="/search?cat=1&txt=' + theWords + '&st=0" class="searchResultCat"><img src="/images/search/accessories.png" /></a>  Or, choose a product below</b></p>');
                isLoading = false;
            }
        });
    } else {
        $("#cDIV_ListLeft").html('');
        $("#cDIV_ListRight").html('');
        $("#cDIV_SearchResults").css("display","none");
        $(document).unbind("click");
    }
};
