var keysearch1 = true;
var keysearch2 = true;

j$(function() {
	
	var currentItem = [null,null] ;
	var lastKeyword = ["", ""];
	var isReady = [true, true];	
	
	function setCurrentItem ( no, item )
	{
	   var vMatching = j$("#matching" + no);
	   var vList = vMatching.find("li");	   
	   if (  item == null || vList.length == 0 )  
	   { 
		   vMatching.hide(); 
		   return; 
	   }
	   
	   if ( item >= vList.length ) item = vList.length - 1 ;
	   vList.css("background", "");
	   if ( item >= 0 ) vList.eq(item).css("background", "#E0EAF3");
	   vMatching.show();
	}
	
	j$("#searchTerm")
		.bind("keyup", function( event ){typeAHead(event, '')})
		.bind("focus", function(){ searchTextboxFocus('') })
		.bind("blur", function(){ setTimeout( function() { searchTextBoxBlur(''); }, 200 ) })
		.bind("keypress", function( event ) {keyPressed(event, '')});				
	//	.bind("keydown", function(l) {if (l.keyCode == 13) {keysearch1=true;keysearch2=false;submitSearchFormOnTop();}})

	j$("#searchTerm2")
		.bind("keyup", function( event ){ typeAHead(event, '2')})
		.bind("focus", function(){ searchTextboxFocus('2') })		
		.bind("blur", function(){ setTimeout( function() { searchTextBoxBlur('2'); }, 200 ) })
		.bind("keypress", function( event ) {keyPressed(event, '2')});		
	//	.bind("focus", function(){typeAHead(2)})
	//	.bind("keydown", function(l) {if (l.keyCode == 13) {keysearch1=false;keysearch2=true;submitSearchFormOnTop2();}})
	//	.bind("blur", function(){ setTimeout( function() { hideTypeAHead(2); }, 200 ) });
	
	function typeAHead(event, no)
	{
		var curIndex = no.length ;		
        if (  ! isReady[curIndex] ) return;
		var loc = {};
		loc.matching = [];
		loc.searchTerm = j$("#searchTerm" + no).val();
		loc.storeId = j$("#storeId" + no).val();
		loc.solr = j$("#solr" + no).val();

     	var upKey = 38 ;
		var downKey = 40 ;
		var enterkey = 13 ;
		
    	if ( event.keyCode == upKey || event.keyCode == downKey )
   		{
   		   var vMatching = j$("#matching" + no);
   		   var vList = vMatching.find("li");	   
   		   
   		   if ( vList.length == 0 ) return;
           if ( event.keyCode == upKey )  		   
       	   {
        	  if ( currentItem[curIndex] == null ) currentItem[curIndex] = vList.length -1 ;
        	  else  currentItem[curIndex]--;
       	   }
           if ( event.keyCode == downKey )  		   
       	   {
        	  if ( currentItem[curIndex] == null ) currentItem[curIndex] = 0 ;
        	  else   currentItem[curIndex]++ ;
       	   }
	       if ( currentItem[curIndex] < 0 ) currentItem[curIndex] = vList.length -1 ;
		   if ( currentItem[curIndex] >= vList.length ) currentItem[curIndex] = 0 ;
     	   setCurrentItem(no, currentItem[curIndex] );
     	   return;
   		}
		
		if ( event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 27 ) lastKeyword[curIndex] = "" ;
		if ( event.keyCode == 27 ) 
		{
			j$("#searchTerm" + no).val('');
			setCurrentItem(no, null );
		}	

		if ( event.keyCode < 48 && event.keyCode != 8 && event.keyCode != 46 ) return ;

		 
		loc.searchTerm = escapeRegExp({text:loc.searchTerm});
		
		if ( loc.searchTerm.length <= 1 ) 
		{
			setCurrentItem(no,null);	
			return ;
		}

		if ( lastKeyword[curIndex] == loc.searchTerm ) return ;

        isReady[curIndex] = false ;
		strUrl = siteUrl + 'com/b2c/search/solrAutoComplete.cfc?term=' + loc.searchTerm + '&storeId=' + loc.storeId + '&solr=' + loc.solr;
		
		j$.ajax({
			url: strUrl ,
			data: { method:'GET_SOLR_AUTOCOMPLETE' },
			type: 'GET',
			dataType: 'JSON',
			timeout:5000,
			async: true,
			success: function(json) {
				var myObject = eval('(' + json + ')');
				loc.matching = myObject;
				if (loc.matching.length > 0) 
				{
					displayMatching({arr:loc.matching, searchTerm:loc.searchTerm, no:no});
					currentItem[curIndex] = -1 ;
				} 
				else 
				{
					setCurrentItem(no,null);	
					j$("#matching" + no).empty();					
				}
				lastKeyword[curIndex] = loc.searchTerm;
		        isReady[curIndex] = true ;
			}
		});
	}

    function keyPressed( event, no) 
    {
		var enterkey = 13 ;
    	if ( event.keyCode != enterkey ) return true ;

		var curIndex = no.length ;
		
 		var vMatching = j$("#matching" + no);
   		var vList = vMatching.find("li");	   
        
   		if ( vMatching.is(":visible") && vList.length > 0 && 0 <= currentItem[curIndex] && currentItem[curIndex] <= vList.length -1 )
   		{
   			var keyword = vList.eq(currentItem[curIndex]).text();
   			j$("#searchTerm"+no).val(keyword);
   		}
		keysearch1 = no == '';
		keysearch2 = no != ''; 
   		
   		if ( keysearch1 ) submitSearchFormOnTop();   		
   		else submitSearchFormOnTop2() ;
    }

	function escapeRegExp(arguments){
		var loc = {};
		
	    loc.specials = ['/', '.', '*', '+', '?', '|','(', ')', '[', ']', '{', '}', '\\'];
		loc.sRE = new RegExp('(\\' + loc.specials.join('|\\') + ')', 'g');

		return arguments.text.replace(loc.sRE, '\\$1');
	} 

	function displayMatching(arguments) {
		var loc = {};
		
		loc.pattern = new RegExp( "(" + arguments.searchTerm + ")", "gi" ); 
		loc.pattern.compile(loc.pattern);
		
		loc.arrDisplay = [];
		
		for ( loc.i = 0; loc.i < arguments.arr.length; loc.i++ ){
			
			loc.str = arguments.arr[ loc.i ];
			loc.arrDisplay.push(loc.str.replace(loc.pattern, "<span class='typeaheadhl'>$1</span>"));
		}
		
		var no = arguments.no ;
		var curIndex = no.length ;
		
		j$("#matching" + arguments.no).html("<ul><li>" + loc.arrDisplay.join("</li><li>") + "</li></ul>").show();
		j$("#matching" + arguments.no + " li").bind("click", function(){
			j$("#searchTerm").val(j$(this).text());
			j$("#searchTerm" + no).val(j$(this).text());
			submitSearchFormOnTop();
		}).each ( function ( index ) {
			j$(this).mouseover( function (){
				setCurrentItem( no , index );
				currentItem[curIndex] = index ;
			});
		});
	}	
	
	function searchTextboxFocus( no )
	{
		var vSearchTerm = j$("#searchTerm" + no);
		var vKeyword = vSearchTerm.val();
		var vDefault = vSearchTerm[0].defaultValue;
		var curIndex = no.length ;
		
		if ( vKeyword == vDefault ) vSearchTerm.val("");
		else { 
			    setCurrentItem( no , -1 );
		        currentItem[curIndex] = -1 ;
	         }
	}

	function searchTextBoxBlur ( no )
	{
		var vSearchTerm = j$("#searchTerm" + no);
	    var vDefault = vSearchTerm[0].defaultValue;
	    var curIndex = no.length ;
	    
		if ( ! j$.trim( vSearchTerm.val() ) ) vSearchTerm.val(vDefault);
	    setCurrentItem( no , null );
        currentItem[curIndex] = -1 ;

	}	
	
});


