RegExp.escape = function(str){
  var specials = new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"); // .*+?|()[]{}\
  return str.replace(specials, "\\$&");
}
var timeout = false;
$(document).ready(function(){
    incrementalFindSetup();
});
var incrementalFindCache = {};
var incrementalFindCount = -1;
function incrementalFindSetup(){
    //Disable autocomplete on the form so the autocomplete doesn't overlap incremental find for the searchbox.
    $("form").attr("autocomplete", "off");
    //Need to disable it on the input for chrome.
    $("input.search_input").attr("autocomplete", "off");
    var incrementalFindIndex = incrementalFindCount;
    var selectedLI = $("incremental_find_results > li:eq(" + incrementalFindIndex + ")");
    $("input.search_input").keyup( function(e) {
        if(e.keyCode == 38 || e.keyCode == 40) {
            //handle the up and down arrows
            $(selectedLI).toggleClass("incremental_find_highlight");
            if(e.keyCode == 40){ //down arrow keypress
                incrementalFindIndex += 1;
            }
            else{ //up arrow keypress
                incrementalFindIndex -= 1;
            }
            if (incrementalFindIndex >= incrementalFindCount){
                //if they press down arrow pass the end of the list reset back to the top
                incrementalFindIndex = 0;
            }
            else if (incrementalFindIndex < 0){
                //if they press up arrow pass the beginning of the list reset back to the bottom
                incrementalFindIndex = incrementalFindCount - 1;
            }
            selectedLI = $("#incremental_find_results > li:eq(" + incrementalFindIndex + ")");
            $(selectedLI).toggleClass("incremental_find_highlight");
            $("input.search_input").val($(selectedLI).text());
        }
        else if(e.keyCode != 13 && e.keyCode != 37 && e.keyCode != 39 && $("input.search_input").val().length >= 3)  {
            var searchVal = $("input.search_input").val().toLowerCase();
            if (timeout){
                clearTimeout(timeout);
            }
            incrementalFindIndex = -1;
            if(incrementalFindCache[searchVal]){
                buildIncrementalFindList(searchVal, incrementalFindCache[searchVal]);
            }
            else{
                //Don't execute this function unless they pause from typing for 200 milliseconds
                //This cuts down on unecessary requests to the server
                timeout = setTimeout(function() {populateIncrementalFind(searchVal)}, 200);
            }
        }
        else{
            $("#incremental_find_results > li").remove();
            $("#incremental_find_results").hide();
        }
    });
}

function populateIncrementalFind(searchVal){
    //get keyword suggests when they have typed more than 3 characters
    $.getJSON("/IncrementalFind.ashx",{func: "get_keywords", input_value: searchVal},
        function(result){
            //cache the results 
            incrementalFindCache[searchVal] = result.keywords;
            buildIncrementalFindList(searchVal, result.keywords);
        }
    );
}

function buildIncrementalFindList(searchTerm, keywordsArray){
    if(searchTerm==$("input.search_input").val().toLowerCase()){
        incrementalFindCount = $(keywordsArray).size();
        if(incrementalFindCount > 0){
            $("#incremental_find_results").show();
        }
        else{
            $("#incremental_find_results").hide();
        }
        $("#incremental_find_results > li").remove();
        $.each(keywordsArray, function( intIndex, objValue ){
                var RegularExpression = new RegExp(RegExp.escape(searchTerm),"i");
                $("#incremental_find_results").append("<li>" + searchTerm.toLowerCase() + "<b>" + objValue.replace(RegularExpression,"") + "</b>" + "</li>");
             }
        );
        $("#incremental_find_results > li").click(function() {
            $('input.search_input').val($(this).text());
            $('input.search_button').click();
        });
        $("#incremental_find_results > li").mouseover(function() {
            $(this).addClass("incremental_find_highlight");
        });
        $("#incremental_find_results > li").mouseout(function() {
            $(this).removeClass("incremental_find_highlight");
        });
    }
}

var BrowserName = navigator.appName.substr(0,2);
var bType = "";
var pagefooter = "";
	
if(BrowserName == "Mi")
{
	bType = "ie";
}
else if(BrowserName == "Ne")
{
	bType = "moz";
}

// checks keypress event and browser type
function isEnterKey(e)
{
	var key;

	if(window.event)
	{
		key = window.event.keyCode;     //IE
	}
	else
	{
		key = e.which;     //firefox
	}
	
	if(key == 13)
	{
		return true;
	}
	else
	{
		//Handle Enter key for Mac. Safari browsers
		if(typeof document.getElementById != "undefined")
		{
			if(navigator.userAgent.toLowerCase().indexOf("safari")!=-1)
			{
				if(key == 3)
					return true;
			}
		}
		return false;
	}
}

function checkButtonId(txtPairingId)
{
	var btnId = document.getElementById('txtButtonFocus').value;
	
	if(txtPairingId == btnId)
	{
		return true;
	}
	return false;
}

var keyPress = "";
// for mozilla only
function readKey(e) {
		keyPress = e.keyCode;
}

function placeFooterMain() 
{ 
	var leftnav = document.getElementById('leftnav');
	var tblMain = document.getElementById('tblMain');
	var navHeight = leftnav ? (leftnav.offsetTop + leftnav.offsetHeight + 10) : 0;
	tblMain.height = (navHeight - 80) + 'px';
}

function setSearch(txtSearch)
{
	txtSearch.value = "";
	/*
	var terms = txtSearch.value;
	if(terms == "enter keyword or item #")
	{
		txtSearch.value = "";
	}
	*/
}

function isEndecaSearch()
{
	if(checkButtonId('endeca')==false || validateSearch()==false)
	{
		return false;
	}
	return true;
}


function checkSearch()
{
	var terms = document.getElementById('Header1:txtSearch').value;
	if(!((terms == "") || (terms == "enter keyword or item #"))) 
	{ 
		return false;
	}
}

// validates endecca search
function validateSearch() 
{
	var form = document.forms[0];
	var terms = "";
	var txtBox = "";
	
	// get search keyword from the default header or department header
	if(form.elements['Header1:txtSearch']!=null)
	{
		txtBox = form.elements['Header1:txtSearch'];
		terms = txtBox.value;
	}
	/*else if(document.getElementById('Header1:txtSearch')!=null)
	{
		txtBox = document.getElementById('_ctl2_txtSearch');
		terms = txtBox.value;
	}
	else if(form.elements['_ctl3:txtSearch']!=null)
	{
		txtBox = form.elements['_ctl3:txtSearch'];
		terms = txtBox.value;
	}*/
	else if(form.elements['Header1:txtSearchDept']!=null)
	{
		txtBox = form.elements['Header1:txtSearchDept'];
		terms = txtBox.value;
	}
	/*else if(form.elements['_ctl2:txtSearchDept']!=null)
	{
		txtBox = form.elements['_ctl2:txtSearchDept'];
		terms = txtBox.value;
	}
	//brands page
	else if(form.elements['_ctl3:txtSearchDept']!=null)
	{
		txtBox = form.elements['_ctl3:txtSearchDept'];
		terms = txtBox.value;
	}*/
	
	// Alert if terms equals nothing
	if((terms == "") || (terms == "enter keyword or item #")) 
	{
		alert("Please enter a search term.");
		txtBox.focus();
		return false;
	}
	return true;
}

// gets proper keyCode value from either ie or mozilla browsers
function validateEmail(txt)
{	
	var txtBox = document.getElementById(txt);
	if(echeck(txtBox.value))
	{
		return true;
	}
	txtBox.focus();	
	return false;
}
	
/**
* DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
*/

function echeck(str) {
	/*
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   alert("Invalid E-mail ID");
	   return false;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   alert("Invalid E-mail ID");
	   return false;
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	    alert("Invalid E-mail ID");
	    return false;
	}

	 if (str.indexOf(at,(lat+1))!=-1){
	    alert("Invalid E-mail ID");
	    return false;
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	    alert("Invalid E-mail ID");
	    return false;
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
	    alert("Invalid E-mail ID");
	    return false;
	 }
	
	 if (str.indexOf(" ")!=-1){
	    alert("Invalid E-mail ID");
	    return false;
	 }*/
	 //var filter = /^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}[^_]+$/;
	 var filter = /^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@(([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.))*[A-Za-z0-9]{1,63}\.([a-zA-Z][^_\W]{0}){2,6}$/;
	 if(filter.test(str)) {
		return true;
	 }	
	 else {
		alert("Invalid E-mail Address");
		return false;
	 }
	 					
}

function openSTPCC(url)
{
	newWin = window.open(url,"Rewards_Card","fullscreen=no,scrollbars=yes,toolbar=no,menubar=no,resizable=no,width=650,height=650");
	
}

// Handles Bill Me Later Popup windows
function openHowTo(url)
{
	newWin = window.open(url,"HowTo","fullscreen=no,scrollbars=no,toolbar=no,menubar=no,resizable=no,width=550,height=650");
}

function openMoreInfo(url,canScroll)
{
	if(canScroll=='no')
	{
		newWin = window.open(url,"MoreInfo","fullscreen=no,scrollbars=no,toolbar=no,menubar=no,resizable=no,width=550,height=650");
	}
	else
	{
		newWin = window.open(url,"MoreInfo","fullscreen=no,scrollbars=yes,toolbar=no,menubar=no,resizable=no,width=550,height=650");
	}
}
