var jsonObj;
var resultsLength = 0;											// number of returned results
var selectedResult = -1;										// Means if enter is hit will go to results page
var searchTimeout = undefined;
var displayPopup = -1;											// -1 never shown | 0 hidden | 1 shown
var initialFieldValues = [];

jQuery(document).ready(function($){

	jQuery('.clearOnFocus').each(function(){
		initialFieldValues[$(this).attr("id")] = $(this).attr("value");
	});

	jQuery('.clearOnFocus').focus(function(){
		field = $(this);
		
		field.removeClass("input-blurred");
		if ( field.attr("value") == initialFieldValues[field.attr("id")] )
			field.attr("value" , "");
	});

	jQuery('.clearOnFocus').blur(function(){
		field = $(this);
		
		field.addClass("input-blurred");
		if (field.attr("value") == "" )
			field.attr("value" , initialFieldValues[field.attr("id")]);
	});


	jQuery('.input-search').attr("autocomplete","off");

	jQuery('.searchSuggest').keydown(function(event){
		if ((event.keyCode == 13) && (selectedResult > -1))	{
			event.preventDefault();								// If any returned result is selected - prevent accidental form submit
		}
		switch (event.keyCode)	{
			case 38:
				//UP arrow key
				cycle = false;
				selectPrev(cycle);
				break;
			case 40:
				//DOWN arrow key
				cycle = false;
				selectNext(cycle);
				break;
			default:
				break;
		}															// END switch
	});

	jQuery('.searchSuggest').keyup(function(event){
		if (event.keyCode == 27) {
			jQuery(this).attr("value", "");							// Reset query input at ESC
			highlightResult(-1);
		}
		q_string = jQuery(this).attr("value");
		str = jQuery.trim(q_string);
		if(str.length > 2) {									// Only send ajax calls for query strings grater than 2c
			switch (event.keyCode)	{
				//De pus case pe alt ctrl shift caps sa nu mai faca Ajax
				case 9:		// TAB
				case 16:	// SHIF
				case 17:	// CTRL
				case 18:	// ALT
				case 20:	// CAPS
				case 37:	// LEFT
				case 39:	// RIGHT
				case 38:	// UP arrow key
				case 40:	// DOWN arrow key
					//DO nothing - avoid ajax call
					break;
				case 13:
					//ENTER key
					followSelectedLink();
					break;
				default:
					if (searchTimeout) {
						window.clearTimeout(searchTimeout);
					}
					searchTimeout = window.setTimeout(function() { ajaxSearch(q_string); }, 300);
					break;
			}															// END switch
		}
		else	{
			jQuery('.searchSuggestBox').hide();						// IF query string <= 2 - hide the suggest box
			selectedResult = -1;									// Reset the selected result
			displayPopup = -1;										// do not redisplay popup
		}
	});																	// END keyUp event process routine
	
	jQuery('body').click(function(){
		jQuery('.searchSuggestBox:visible').hide(1,function(){
			displayPopup = 0;
			selectedResult = -1;										// also resets the selected result
		});							// clicking outside the suggest box hides it
	});

	jQuery('input[name="q"]').focus(function(){
		if (!displayPopup)	{
			jQuery('.searchSuggestBox').show();
		}
	});

	jQuery('.triggerHideFalse').click(function(event){
		event.stopPropagation();									// clicking inside the suggest box does not Hide it
	});

	jQuery('#search-suggest-form').submit(function(){
		str = jQuery.trim(jQuery('input[name="q"]').attr('value')); 
		if( str == "" || str == initialFieldValues[jQuery('input[name="q"]').attr('id')])	{
			return false;
		}
	});

});																		// END document.ready

function ajaxSearch(q_string) {
	jQuery.ajax({
		 type: "GET",
		 url: "/search/gss/",
		 data: {q: q_string, num: 6},
		 success: function(json) {
			jsonObj = jQuery.evalJSON(json);
			resultsLength = jsonObj.length;

			jQuery('.searchSuggestResults').empty();

			if (!resultsLength)	{
				drawZeroResults();
			}
			else	{
				for (i=0;i<resultsLength;i++)	{
					if (!jsonObj[i].featured)	{
						drawNormalLine(jsonObj[i],i)
					}
					else {
						drawFeaturedLine(jsonObj[i],i);
					}
				}												// END json interation
				drawAllResultsLink();
			}

			jQuery('li.suggest-featured > a.suggest-link').click(function(){
				ajaxTrack(jQuery('input[name="q"]').attr('value'), jQuery(this).attr('href'), featured=1);	// track the click of a featured link
			});
		
			jQuery('li.suggest-normal > a.suggest-link').click(function(){
				ajaxTrack(jQuery('input[name="q"]').attr('value'), jQuery(this).attr('href'), featured=0);	// track the click of a regular link
			});
		
			jQuery('li.suggest-results a.suggest-link').click(function(){
				jQuery('#search-suggest-form').submit();														// submit the form via JS
				return false;
			});
			
			jQuery('.searchSuggestBox').show();
			displayPopup = 1;
		 }													// END json retrieve
	 });													// END ajax call
}

function ajaxTrack(q, url, featured)	{
	jQuery.ajax({
		 type: "GET",
		 url: "/search/track/",
		 data: {"q": q, "url": url, "featured": featured}
	});														// END ajax call
}

function drawFeaturedLine(lineData,index)	{
		jQuery('<li class="suggest-featured' + (!index ? ' suggest-first' : '') +'"></li>').html('<a class="suggest-link liner" href="' + lineData.url + '" title="' + lineData.title + '" id="suggest-index-' + index + '">		\
																	<span class="suggest-img" style="background-image:url(' + lineData.img + ')"></span>		\
																	<span class="suggest-title">' + lineData.title + '</span>			\
																	<span class="suggest-desc">' + lineData.desc + '</span>			\
																</a>																\
															').appendTo('.searchSuggestResults');
}

function drawNormalLine(lineData,index)	{
		jQuery('<li class="suggest-normal' + (!index ? ' suggest-first' : '') +'"></li>').html('<a class="suggest-link liner" href="' + lineData.url + '" title="' + lineData.title + '" id="suggest-index-' + index + '">		\
																	<span class="suggest-title">' + lineData.title + '</span>			\
																	<span class="suggest-desc">' + lineData.desc + '</span>			\
																</a>																\
															').appendTo('.searchSuggestResults');
}

function drawAllResultsLink()	{
	jQuery('<li class="suggest-results"></li>').html('<a href="#" id="suggest-index-' + resultsLength + '" class="suggest-link">See all search results</a>').appendTo('.searchSuggestResults');
}

function drawZeroResults()		{
	jQuery('<li class="suggest-no-results"></li>').html('Your search did not match any results<br/>').appendTo('.searchSuggestResults');
}

function selectPrev(cycle)	{
	cycle = cycle || false;			// cycle options is disabled by default
	if (selectedResult > -1)	{
		selectedResult--;
		highlightResult(selectedResult);
	}
	else	{
		if (cycle)	{
			selectedResult = resultsLength;
			highlightResult(selectedResult);
		}
	}
}

function selectNext(cycle)	{
	cycle = cycle || false;			// cycle options is disabled by default
	if (selectedResult != (resultsLength || -1))	{
		selectedResult++;
		highlightResult(selectedResult);
	}
	else	{
		if (cycle)	{
			selectedResult = 0;
			highlightResult(selectedResult);
		}
	}
}

function followSelectedLink()	{
	if (selectedResult == -1) 	{
		return false;											// if input field is focused - do nothing - submit form
	}
	else if (selectedResult == resultsLength)	{
		jQuery('#search-suggest-form').submit();				// if "see all" is selected - submit form via JS
	}
	else	{
		ajaxTrack(jQuery('input[name="q"]').attr('value'), jsonObj[selectedResult].url, jsonObj[selectedResult].featured);	// track query_string, followed_URL, and if_featured
		window.location = jsonObj[selectedResult].url;			// Redirect to selected URL - via keys
	}
}

function highlightResult(currentResult)	{
	if (currentResult == -1)	{
		jQuery('.suggest-link').removeClass('selected-result');
		jQuery('.input-search').removeClass('input-blurred');
		jQuery('.input-td').css('background-color','#fff');			// to be removed after porting the site to new layout
	}
	else	{
		jQuery('.input-td').css('background-color','#e3e0dd');		// to be removed after porting the site to new layout
		jQuery('.input-search').addClass('input-blurred');
		jQuery('.suggest-link').removeClass('selected-result');
		jQuery('#suggest-index-' + currentResult).addClass('selected-result');
	}
}
