//HANDLES MOST AJAX CONTENT FOR SITE SEARCH - SPEAKS WITH site_search.js
(function( $ )
{
	$.fn.returnSearch = function() 
	{
		
	
	obj = this;
	var myTimer;
	
	var searchString;
	var liveResultString = "";
	
	var liveDataJqxhr;
	
	/*set hover states for general search results*/
	function setHovers() {
		/* work hover stateas*/
		$('ul.work-results img').mouseenter(function() {
			selection = $(this).closest('li');
			selection.find('a.article').css({'color': '#2ba2cc'});
		});
		$('ul.work-results img').mouseleave(function() {
			selection = $(this).closest('li');
			selection.find('a.article').css({'color': '#3f3f3f'});
		});
		$('a.article').mouseenter(function() {
			$(this).css({'color': '#2ba2cc'});
		});
		$('a.article').mouseleave(function() {
			$(this).css({'color': '#3f3f3f'});
		});
		/*news hover states*/
		$('a.search-read-more').mouseenter(function() {
			selection = $(this).closest('li');
			selection.find('a.article').css({'color': '#2ba2cc'});
		});
		$('a.search-read-more').mouseleave(function() {
			selection = $(this).closest('li');
			selection.find('a.article').css({'color': '#3f3f3f'});
		});
		
		$('a.more-info').mouseenter(function() {
			selection = $(this).closest('li');
			selection.find('a.article').css({'color': '#2ba2cc'});
		});
		$('a.more-info').mouseleave(function() {
			selection = $(this).closest('li');
			selection.find('a.article').css({'color': '#3f3f3f'});
		});
		
	}
	
	this.fetchLiveData = function() {
		var searchStringData = $('#search-input').val();
		if(searchStringData.length <2) searchStringData = "";
		$('#search-results').html("").hide();
		$('#suggested-search').show();
		//$('#searchSuggestions').html(liveResultString);
		$('#searchSuggestions').html("");
		
		$('#search-overlay').fadeTo('fast',0.95);
		$('#search-overlay-2').fadeTo('fast',0.95);
		$('a.close-search').fadeTo('fast',1);
			
		if (liveDataJqxhr) { // another request is running, stop it
			liveDataJqxhr.abort();
			liveDataJqxhr = null;
		}

		if (searchStringData) {
			liveDataJqxhr = $.get(
				'/api-xml/search/general-search/searchtype/live',
				{
					'searchterm' : searchStringData
				}, 
				function(result) {
					liveResultString = "";
					$('#searchSuggestions').html("");
					$(result).find('match title').each(function(){
						liveResult = $(this).text();
						liveResultSanitized = $('<div/>').text(liveResult).html(); 
						//liveResultString = '<a href="#" onclick = "$.fn.fetchGeneralData(\''+ liveResult + '\');">' + liveResult + '</a><br />';
						//liveResultString += '<li><a href="#" class="suggestion" onclick="$.fn.fetchGeneralData(\'' + liveResultSanitized + '\'); return false;">'+liveResult+'</a></li>';
						liveResultString += '<li><a href="#!/search/' + liveResultSanitized + '" class="suggestion">'+liveResultSanitized+'</a></li>';
						//if(searchStringData.length > 4) alert(liveResultString);
							
						//$('#search-results').html("");
					});
					$('#searchSuggestions').html(liveResultString);
				}
			);
		}
	};
	
	
	
	$.fn.fetchGeneralData = function(newData) {
		
		var itemsFound = I18n.t('items_found');
		var oneItemFound = I18n.t('item_found');
		var readMore = I18n.t('read_more');
		
		var workNum = 0;
		var newsNum = 0;
		var contactNum = 0;
		var workNumber = '0 '+ itemsFound;
		var newsNumber = '0 '+ itemsFound;
		var contactNumber = '0 '+ itemsFound;
		var workString ="";
		var newsString ="";
		var contactString ="";
		
		$('#searchSuggestions').html('');
		$('#search-input').val("");
		//$('#search-input').trigger();
		$('#search-overlay').fadeTo('fast', 1);
		$('#search-overlay-2').fadeTo('fast', 1);
		$('#suggested-search').hide();
		generalData = newData;
		$.get(
			'/api-xml/search/general-search/searchtype/general',
			{
				'searchterm' : generalData
			}, 
			function(result)	{
				// TODO: Escape the variables for HTML 
				/*COUNT THE NUMBER OF RESULTS FOR THE WORK, NEWS AND CONTACTS*/
				$(result).find('work').each(function() {
					$(this).find('match').each(function() {
						title =  $(this).find('title').text();
						id = $(this).find('id').text();
						img = $(this).find('small_asset_source').text();
						mediaTitle = $(this).find('media_title').text();
						mediaDescription = $(this).find('media_description').text();
						workString += '<li><a href="#" onclick=\'$.fn.goToSearch(' + 0 + ',' + id +'); return false;\'><img src="' + img + '" width = 140/></a><div id="descrip">' + '<h4><a href="#" class="article" onclick=\'$.fn.goToSearch(' + 0 + ',' + id +'); return false;\'>' + title + '</a></h4><h5>' + mediaTitle +'</h5><p>' + mediaDescription + '</div><div class="clear"></div></li>';
							 
						 workNum++;
						 
						 if (workNum == 1) {
							 
							 workNumber = workNum + ' ' + oneItemFound;
							 
						 }
						 else {
							 
							workNumber = workNum + ' ' + itemsFound;
							 
						 }
						 
						});
						
					});
					
						
				$(result).find('news').each(function() {
					$(this).find('match').each(function() {
						title =  $(this).find('title').text();
						source = $(this).find('source').text();
						url = $(this).find('url').text();
						newsString += '<li><div id="descrip">' + '<h4><a href="' + url + '" class="article" target="_blank">' + title + '</a></h4><a href="' + url + '" class="more-info" target="_blank">' + source + '</a>&nbsp;&nbsp;<a href="' + url + '" class="search-read-more" target="_blank">'+readMore+'</a></div><div class="clear"></div></li>';
							 
						 newsNum++;
						 
						 if (newsNum == 1) {
							 
							 newsNumber = newsNum + ' ' + oneItemFound;
							 
						 }
						 else {
							 
							newsNumber = newsNum + ' ' + itemsFound;
							 
						 }
						 
						});
						
					});
					openSearchTitle = '<div id="center-content"><h1>'+I18n.t('search_results_for')+':</h1><h2>' + $('<div/>').text(generalData).html() +'</h2>';
					
					openSearchStats = '<ul class="result-stats"><li><a href="#" class="stat" onclick="return false;" id="work-stat">'+I18n.t('work')+':&nbsp;' + workNum + '</a></li>' + '<li><a href="#" class="stat"  onclick="return false;" id="news-stat">'+I18n.t('news')+':&nbsp;' + newsNum + '</a></li>'/* + '<li><a href="#" class="stat"  onclick="return false;" id="contact-stat">contacts:&nbsp;' + contactNum + '</a></li>*/ + '</ul><div class="clear"></div></div>';
					
					fullWorkString = '<div id="result-category"><div id="center-content"><div id="result-descrip"><h2 class="work">'+I18n.t('WORK')+'</h2><h3>' + workNumber + '</h3></div><div id="result-list"><ul class="work-results">' + workString + '</ul></div><div class="clear"></div></div></div>';
					
					fullNewsString = '<div id="result-category"><div id="center-content"><div id="result-descrip"><h2 class="news">'+I18n.t('NEWS')+'</h2><h3>' + newsNumber +'</h3></div><div id="result-list"><ul class="news-results">' + newsString + '</ul></div><div class="clear"></div></div></div>';
					
					fullContactString = '<div id="result-category"><div id="center-content"><div id="result-descrip"><h2 class="contact">CONTACT</h2><h3>' + 0 + ' '+itemsFound+'</h3></div><div id="result-list">' + "insert loop here" + '</div><div class="clear"></div></div>';
							
					closeSearchContent = '</div>';
					
					compleSearchString = openSearchTitle + openSearchStats + fullWorkString + fullNewsString /*+ fullContactString*/ + closeSearchContent;
					
					$('#searchSuggestions').html("");
					$('#suggested-search').hide();
					$('#search-results').show();
					$('#search-results').html(compleSearchString);
					$.fn.siteSearch.closeSearchIntent();
					$('ul.result-stats').SearchScroll();
					contentHeight = $('#content-wrapper').height();
					$('#search-overlay').css({height: contentHeight + 700});
					$('#search-results').css({height: contentHeight + 700});
					setHovers();
				
			}
		);
		
	}
	
		
	this.initiate = function () {
			
		//myTimer = setTimeout("obj.fetchLiveData();",400);
		obj.fetchLiveData();
	
	};
	
	this.kill = function () {
		//alert("killed");
		clearTimeout(myTimer);	
	
	};
	
	$.fn.globalTimerKill = function() {
		clearTimeout(myTimer);	
	};
	
	this.keydown(function() {
		obj.kill();
	
	});
	
	this.keyup(function(event) {
		if (event.which == '13') {
			
			return;
		}
		else {
		
		obj.initiate();	
		
		}
	
	});
	
	$.fn.goToSearch = function (pageId, itemId) {
		
		//$.fn.siteSearch.exitSearch();
		//document.location.hash='!&pageid=' + pageId + '&itemid=' + itemId;
		Backbone.history.navigate('&pageid=' + pageId + '&itemid=' + itemId, true);
		//alert(pageId +',' + itemId);
		
	}
	
		
	  	};
})( jQuery );
