/*
 * All java script logic for the search suggestions.
 *
 * The code relies on the jQuery JS library to
 * be also loaded.
 *
 * The logic extends the JS namespace app.*
 */

(function(app){
	if (app) {
		// add searchsuggest to namespace
		app.searchsuggest = {
			// configuration parameters and required object instances
			acListTotal   :  0,
			acListCurrent : -1,
			acDelay       : 300,
			acURL         : null,
			acFormId      : null,
			acSearchId	  : null,
			acResultsId	  : null,
			acSearchField : null,
			acResultsDiv  : null,
			fieldDefault  : null,
			suggestionsJson: null,
			
			init : function(formId, fieldId, fieldDefault, resultsId, url) {
				// initialize vars
				app.searchsuggest.acFormId = "#" + formId;
				app.searchsuggest.acSearchId = "#" + fieldId;
				app.searchsuggest.acResultsId = "#" + resultsId;
				app.searchsuggest.acURL = url;
				app.searchsuggest.fieldDefault = fieldDefault;
				
				// disable browser auto comlete
				app.util.disableAutoComplete(fieldId);
				
				// create the results div
				jQuery("#header").append("<div id=\"" + resultsId + "\"></div>");
			
				// register mostly used vars (jQuery object)
				app.searchsuggest.acSearchField = jQuery(app.searchsuggest.acSearchId);
				app.searchsuggest.acResultsDiv = jQuery(app.searchsuggest.acResultsId);
			
				// reposition div
				app.searchsuggest.repositionResultsDiv();
			
				// on blur listener
				app.searchsuggest.acSearchField.blur(function(){ setTimeout("app.searchsuggest.clear()", 200) });
			
				// on key up listener
				app.searchsuggest.acSearchField.keyup(function(e) {
					
					// get keyCode (window.event is for IE)
					var keyCode = e.keyCode || window.event.keyCode;
					var lastVal = app.searchsuggest.acSearchField.val();
					// check an treat up and down arrows
					if(app.searchsuggest.updownArrow(keyCode)){
						return;
					}
						
					// check for an ENTER or ESC
					if(keyCode == 13 || keyCode == 27) {
						app.searchsuggest.clear();
						return;
					}
										
					// if is text, call with delay
					setTimeout(function() { app.searchsuggest.suggest(lastVal) }, app.searchsuggest.acDelay);
				});
				
				// on focus listener (clear default value)
				app.searchsuggest.acSearchField.focus(function() {
					var val = app.searchsuggest.acSearchField.val();
					if(val == app.searchsuggest.fieldDefault)
					{
						app.searchsuggest.acSearchField.val("");
					}
				});
				
				// on submit we do not submit the form, but change the window location
				// in order to avoid https to http warnings in the browser
				// only if it's not the default value and it's not empty
				jQuery(app.searchsuggest.acFormId).submit(function() {
					
					var searchUrl = jQuery(app.searchsuggest.acFormId).attr("action");
					var searchTerm = app.searchsuggest.acSearchField.val();		
					if (searchTerm != app.searchsuggest.fieldDefault && searchTerm != '') {
						
						var tabName = "";
						
						if(jQuery("#" + resultsId + " div.selected").attr("id") == undefined) {
							tabName = jQuery("#tabName").val();
						} else {
							tabName = jQuery("#" + resultsId + " div.selected").attr("id").split("_")[0];
						}
						
						var url = app.util.appendParamToURL(searchUrl, "q", searchTerm);
						url = app.util.appendParamToURL(url, "tabName", tabName);
						url = app.util.appendParamToURL(url, "cgid", "jack-spade");
						//url = app.util.appendParamToURL(url, "sz", "20");
						
						window.location = url;
					}
					return false;					
				});
			},
			
			// trigger suggest action
			suggest : function(lastValue)
			{
				// get the field value
				var part = app.searchsuggest.acSearchField.val();
			
				// if it's empty clear the resuts box and return
				if(part == "") {
					app.searchsuggest.clear();
					return;
				}
			
				// if it's equal the value from the time of the call, allow
				if(lastValue != part) {
					return;
				}
				
				// build the request url
				var reqUrl = app.util.appendParamToURL(app.searchsuggest.acURL, "q", part);
				
				
				// get remote data as JSON
				jQuery.getJSON(reqUrl, function(json) {
					// get the total of results
										
					// add content from cookie
					var _content = SearchCockieContent(part,"contentKeys");																			
					jQuery.each(_content,function(i,c){						
						json.suggestions.push(c);						
					})
						
					
					
					var ansLength = app.searchsuggest.acListTotal = json.suggestions.length;
			
										
					// if there are results populate the results div
					if(ansLength > 0) {
			
						var __strPlay = "";
						var __strShow = "";
						var __strAbout = "";
						
												
						var __divPlay = document.createElement('div');
						var __divShow = document.createElement('div');
						var __divAbout = document.createElement('div');
						
						
						__divPlay.id='__Play';												
						__divShow.id='__Show';
						__divAbout.id='__About';						
						
						// create a div for each result
						for(i=0; i < ansLength; i++) {
														
							switch(json.suggestions[i].type)
								{
								case 'btc':									
								  // do formatting here																		
									if(__divPlay.innerHTML==''){																														
										__strPlay = "<div id='btc_"  + removeWhiteSpaces(removeHtmlTag(json.suggestions[i].suggestion)) + "' class=\"unselected\">";
										__strPlay += "<div id='playHeader' class=\"searchHead\">Play</div>";
										__strPlay += "<div class=\"suggestionterm\">" + json.suggestions[i].suggestion + "</div>";
										__strPlay += "<div class=\"hits\">" + json.suggestions[i].hits + (json.suggestions[i].hits > 1 ? " results" : " result") +  "</div></div>";										
											
										jQuery(__divPlay).append(__strPlay);									
										    
									}else{												
										__strPlay = "<div id='btc_"  + removeWhiteSpaces(removeHtmlTag(json.suggestions[i].suggestion)) + "' class=\"unselected\">";
										__strPlay += "<div class=\"searchHead\"></div>";
										__strPlay += "<div class=\"suggestionterm\">" + json.suggestions[i].suggestion + "</div>";
										__strPlay += "<div class=\"hits\">" + json.suggestions[i].hits + (json.suggestions[i].hits > 1 ? " results" : " result") +  "</div></div>";
										
										jQuery(__divPlay).append(__strPlay);																																	
									}										
								  break;
								case 'aboutus':
								 // do formatting here
									if(__divAbout.innerHTML==''){											
										__strAbout = "<div id='aboutus_"  + removeWhiteSpaces(removeHtmlTag(json.suggestions[i].suggestion)) + "'  class=\"unselected\">";
										__strAbout += "<div id='AboutHeader' class=\"searchHead\">About Us</div>"
										__strAbout += "<div class=\"suggestionterm\">" + json.suggestions[i].suggestion + "</div>";
										__strAbout += "<div class=\"hits\">" + json.suggestions[i].hits + (json.suggestions[i].hits > 1 ? " results" : " result") +  "</div></div>";	
											
										jQuery(__divAbout).append(__strAbout);																				
									}else{
										__strAbout = "<div id='aboutus_"  + removeWhiteSpaces(removeHtmlTag(json.suggestions[i].suggestion)) + "'  class=\"unselected\">";
										__strAbout += "<div class=\"searchHead\"></div>"
										__strAbout += "<div class=\"suggestionterm\">" + json.suggestions[i].suggestion + "</div>";
										__strAbout += "<div class=\"hits\">" + json.suggestions[i].hits + (json.suggestions[i].hits > 1 ? " results" : " result") +  "</div></div>";	
										
										jQuery(__divAbout).append(__strAbout);
										
										
									}									
									
								  break;
								default:
                                    var _sugg=json.suggestions[i].suggestion;
                              
                                    if(__divShow.innerHTML==''){
                                                                                                                                
                                          var _NewItem = "<span class=\"searchResultHighlight\">" + 
                                                                  _sugg.substring(0, app.searchsuggest.acSearchField.val().length) +  
                                                                  "</span>" + 
                                                                  json.suggestions[i].suggestion.substring(app.searchsuggest.acSearchField.val().length , json.suggestions[i].suggestion.length);
                                                                                                                              
                                          __strShow = "<div id='product_"  + removeWhiteSpaces(removeHtmlTag(_NewItem)) + "' class=\"unselected\">";
                                          __strShow += "<div id='ShopHeader' class=\"searchHead\">Shop</div>"
                                          __strShow += "<div class=\"suggestionterm\">" + _NewItem + "</div>";
                                          __strShow += "<div class=\"hits\">" + json.suggestions[i].hits + "</div></div>";
                                          
                                          jQuery(__divShow).append(__strShow);
                                    }else{
                                          var _NewItem = "<span class=\"searchResultHighlight\">" + 
                                                                  _sugg.substring(0, app.searchsuggest.acSearchField.val().length) +  
                                                                  "</span>" + 
                                                                  json.suggestions[i].suggestion.substring(app.searchsuggest.acSearchField.val().length , json.suggestions[i].suggestion.length);
                                                                                                
                                          __strShow = "<div id='product_"  + removeWhiteSpaces(removeHtmlTag(_NewItem)) + "' class=\"unselected\">";
                                          __strShow += "<div class=\"searchHead\"></div>"
                                          __strShow += "<div class=\"suggestionterm\">" + _NewItem + "</div>";
                                          __strShow += "<div class=\"hits\">" + json.suggestions[i].hits + "</div></div>";
            
                                          jQuery(__divShow).append(__strShow);
                                          
                                    }                                                     
                              }                                                                                                                             
                        }
                  		
						//set Border	
						//if(__divPlay.innerHTML!='' && __divShow.innerHTML!='') __divShow.lastChild.className+=' contentDivider';                                
						//if(__divAbout.innerHTML!='' && __divPlay.innerHTML!='') __divPlay.lastChild.className+=' contentDivider';
						//if(__divAbout.innerHTML!='' && __divShow.innerHTML!='') __divShow.lastChild.className+=' contentDivider';

						
						//concat string suggestions
						var contHTML = __divShow.innerHTML + __divPlay.innerHTML + __divAbout.innerHTML 
						
						
						
						//dispose
						__divShow = null;
						__divPlay = null;
						__divAbout = null;
												
						app.searchsuggest.suggestionsJson = json.suggestions;
						
						// update the results div											
						app.searchsuggest.acResultsDiv.html(contHTML);
						app.searchsuggest.acResultsDiv.css("display","block");
						// reposition in case user resizes browser between searches
						app.searchsuggest.repositionResultsDiv();
						
						// for all divs in results
						var divs = jQuery(app.searchsuggest.acResultsId + " > div");
						
						// on mouse over clean previous selected and set a new one
						divs.mouseover( function() {
							divs.each(function(){ 
								if(this.className.indexOf('contentDivider') >-1){this.className = "unselected contentDivider"}else{this.className = "unselected"};
								});
							if(this.className.indexOf('contentDivider') >-1){this.className = "selected contentDivider"}else{this.className = "selected";}
						});
						
						// on click copy suggestion to search field, hide the list and submit the search
						divs.each(function(i){
							jQuery(this).click( function() {
								app.searchsuggest.acSearchField.val(removeHtmlTag(app.searchsuggest.suggestionsJson[i].suggestion));
								app.searchsuggest.clear();
								jQuery(app.searchsuggest.acFormId).append("<input type='hidden' name='tabName' id='tabName' value='" + this.id.split("_")[0] + "'/>");
								jQuery(app.searchsuggest.acFormId).submit();
							})
						});
					} else {
						//app.searchsuggest.clear();
					}
				});
			},
			
			// clear suggestions
			clear : function()
			{
				app.searchsuggest.acResultsDiv.html("");
				app.searchsuggest.acResultsDiv.css("display","none");
			},
			
			// reposition the results div accordingly to the search field
			repositionResultsDiv : function()
			{
				// get the input position
				var inPos = app.searchsuggest.acSearchField.offset();
				var inTop = inPos.top;
				var inLeft = inPos.left;
				
				// get the field size
				var inHeight = app.searchsuggest.acSearchField.height();
				var inWidth = app.searchsuggest.acSearchField.width();
				
				// apply the css styles
				app.searchsuggest.acResultsDiv.addClass("suggestions");
				//app.searchsuggest.acResultsDiv.css("position","absolute");
				//app.searchsuggest.acResultsDiv.css("left", inLeft + 7); // to tweak
				//app.searchsuggest.acResultsDiv.css("top", inTop + inHeight + 3);
				//app.searchsuggest.acResultsDiv.css("width", inWidth - 2); // to tweak
				app.searchsuggest.acResultsDiv.css("z-index", "999999999");
				
				app.searchsuggest.acListCurrent=-1;
			},
			
			// treat up and down key strokes defining the next selected element
			updownArrow : function(keyCode) {
				if(keyCode == 40 || keyCode == 38) {
					if(keyCode == 38) { // keyUp
						if(app.searchsuggest.acListCurrent == 0 || app.searchsuggest.acListCurrent == -1) {
							app.searchsuggest.acListCurrent = app.searchsuggest.acListTotal-1;
						} else {
							app.searchsuggest.acListCurrent--;
						}
					} else { // keyDown
						if(app.searchsuggest.acListCurrent == app.searchsuggest.acListTotal-1) {
							app.searchsuggest.acListCurrent = 0;
						} else {
							app.searchsuggest.acListCurrent++;
						}
					}
					
					// loop through each result div applying the correct style
					app.searchsuggest.acResultsDiv.children().each(function(i) {
						
						if(this.className.indexOf('contentDivider') >-1){
							this.className = "unselected contentDivider";
						}else{this.className = "unselected";}
																												
					});
					if(app.searchsuggest.acListCurrent > -1 && app.searchsuggest.acListCurrent <=app.searchsuggest.acListTotal){
							app.searchsuggest.acSearchField.val(removeHtmlTag(app.searchsuggest.suggestionsJson[app.searchsuggest.acListCurrent].suggestion));
							var divID = removeHtmlTag(app.searchsuggest.suggestionsJson[app.searchsuggest.acListCurrent].type) + "_" + removeWhiteSpaces(app.searchsuggest.acSearchField.val());
							jQuery('#' + divID).addClass("selected");							
					}
					
					
					return true;
				} else {
					// reset
					app.searchsuggest.acListCurrent = -1;
					return false;
				}
			}
		} // end searchsuggest
	} else {
		// namespace has not been defined yet
		alert("app namespace is not loaded yet!");
	}
	
	//read cockies
	function getCookie(name){
			if (document.cookie.length >0){
			   var start=document.cookie.indexOf(name + "=");			   
				  if (start!=-1){
						start=start + name.length+1;
						end=document.cookie.indexOf(";",start);	
					if (end==-1) end=document.cookie.length; return unescape(document.cookie.substring(start,end));
				}
			  }
		return "";
	}
	

	function SearchCockieContent(val,cname){        
        var res = new Array();  
        var content = eval('[' + getCookie(cname) + '];');
                                                  
        jQuery.each(content,function(i,_cont){
              if(_cont['suggestion'].substring(0,val.length).toUpperCase()==val.toUpperCase()){                     
                    var _NewText = "<span class='searchResultHighlight'>" + _cont['suggestion'].substring(0,val.length)  + '</span>' + _cont['suggestion'].substring(val.length,_cont['suggestion'].length);                                             
                    
                    var str = {'suggestion':  _NewText  ,'count': _cont['count'] ,'hits':   _cont['hits'],'type':   _cont['type']};
                    res.push(str);
              }           
        });         
        return res;
        
	}
	
	function removeHtmlTag(s){
		return s.replace(/<\/?[^>]+(>|$)/g, "");	
		//
	}
	
	function removeWhiteSpaces(s){
		return s.replace(/\s/g, "");		
	}
	
})(app);
