/**
 * This file contains functions related to using the search functions of the page. 
 * Some of these functions are related to the header pages and use some of those functions too. 
 *
 * Global Variables
 * totalSearchResultCount
 *
 */


/**
 * Executes a search after a delay and if the search is not redundant.
 * @param event a keyboard event
 */
function searchHandler( event )
{

	var unicode = event.keyCode ? event.keyCode : event.charCode;

	var searchText = document.getElementById("searchText").value;


	if (unicode == 27)																	// escape key
	{
		document.getElementById("searchText").blur();
		document.getElementById("searchText").value = "SEARCH";
	} else if (unicode == 13 || (searchText.length > 3 && searchText != lastSearch) ) 	// enter key
	{

		searchHeaderReady = [ 0, 0 ]; // specifies the readiness of the video search results and the update posts seperately. 

		searchRequest ( searchText, true ); // true specifies that this is a request from this handler and not from the delay timer.

	}

}


/** Recieves keywords to search, but delays a predefined amount of time to execute the search. Any new command overrides a previous command
  * A keyword value of null cancels the search.  
  * @param someKeywords keywords to search for. 
  * @param refreshTimer boolean 
  */
function searchRequest ( someKeywords, refreshTimer )
{

	// if there are no keywords
	if (someKeywords == null)
	{
		clearTimeout(newDelay);
		return false;
	}

	var timerDelay = 600;

	if (refreshTimer == false)
	{
		clearTimeout(newDelay);
				

		// Google Analytics
		pageTracker._trackPageview( "search: " + someKeywords );

		$.get("lib/json.php?searchVideos=" + someKeywords, function ( data ) { grandma.searchVideosHandler ( data ) });
		$.get("lib/json.php?searchTexts=" + someKeywords, function ( data ) { grandma.searchTextsHandler ( data ) });

		lastSearch = someKeywords;

	} else 
	{
		try // to delete the current timer for a true refreshTimer value
		{
			clearTimeout(newDelay);
		} catch ( e )
		{
			// no timer to delete. looks like this is the first time through
		} finally
		{
			newDelay = setTimeout( "searchRequest(\"" + someKeywords + "\", false);", timerDelay);
		}	

	}

	return false;

}



/**
 * Puts new information into specified columns and updates a count on total results.
 */
function updateSearchHeaderPage( aColumn, aBody, aResultCount)
{
	
	var myBodyDiv 	= $("#headerPageContent");
	var myTitleSpan	= $("#headerPageTitleText");
	
	
	if (searchHeaderReady[0] == 0 && searchHeaderReady[1] == 0)
	{
		headerPageClear();			
		totalSearchResultCount = 0;
		myBodyDiv.append("<div id=\"searchResultsVideoColumn\"></div><div id=\"searchResultsTextColumn\"></div><div id=\"briansthing\"></div>")

	}

    var myVideoColumn 	= $("#searchResultsVideoColumn");	
	var mySeparator		= $("#briansthing");
    var myTextColumn	= $("#searchResultsTextColumn");
		
	if (aColumn == 0)
	{
		searchHeaderReady[0] = 1;
		myVideoColumn.append(aBody);
		
		totalSearchResultCount += aResultCount;
	}

	if (aColumn == 1)
	{
		
		searchHeaderReady[1] = 1;
		myTextColumn.append(aBody);
		totalSearchResultCount += aResultCount;
		
	}

	// write what we gave it
	$(myTitleSpan).empty();
	$(myTitleSpan).append("Search Results for " + lastSearch + " ("+totalSearchResultCount+")");	

	// handle drawer smartl;y
	if (upperDrawerIsClosed)
	{
		toggleUpperDrawer();
	}
	
	
}


/**
 * Makes HTML based on data recieved from database and gives it to updateSearchHeaderPage()
 */
function searchTextsHandler ( jsonData )
{
	
	var characterLimit = 100;
	
	var myTextData 	= eval ("(" + jsonData + ")");
	var myName;
	var myDescription;
		
	var textColumnContainer = document.createElement("div");
	
	var aDivTag, aSpanTag, anATag;
	var oneRow;
		
	var myHTML;
	
	aDivTag = document.createElement("div");
	aDivTag.innerHTML = "Updates";
	aDivTag.className = "searchResultsHeader";
	textColumnContainer.appendChild(aDivTag);
	
	myHTML = "<div><div class=\"searchResultsHeader\">";
	
	var i = -1, w = 0; 
	
	for (i in myTextData)
	{
		
		w = parseInt(i) + 1;
		
		oneText = myTextData[i];
		
		myTitle = oneText.myTitle;
		myTags = oneText.myTags;
		myDescription = oneText.myBody;
		
		myDescription = myDescription.length < characterLimit ? myDescription : myDescription.substr(0, characterLimit) + "...";
		
		// @TODO in order to be clickable, has to know which show and video. Where does text go??
		myShow = 0; // stuff
		myId = oneText.myId;
		
		myHTML += "<div class=\"searchResultRow\"><a href=\"#commandCloseDrawer&s=" + myTags.getShowKey() + "&p=" + myId + "\" onclick=\"clickHandler(this); return false;\"><div class=\"searchResultTitle\">" + w + ". " + myTitle + "</div><span class=\"textSearchResultDescription\">"+myDescription+"</span></a></div>";
		

		
	}

	myHTML += "</div></div>";

	if (i == -1)
	{
	
		myHTML = "No updates found";		
	
	}
	
	updateSearchHeaderPage ( 1, myHTML, w );
	
} // END of searchTextsHandler


/**
 * Makes HTML based on data recieved from database and gives it to updateSearchHeaderPage()
 */
function searchVideosHandler ( jsonData )
{
	
	var DESCRIPTION_MAX = 150;
	
	var myVideoData 	= eval ("(" + jsonData + ")");
	var myTitle;
	var myDescription;
	var myThumbURL;
	
	var oneVideo;	
	
	var videoColumnContainer = document.createElement("div");
		videoColumnContainer.id = "videoColumnContainer";
		
	videoColumnContainer = $("#videoColumnContainer");
	
	var myHTML ;
	
	myHTML = "<div id=\"videoColumnContainer\"><div class=\"searchResultsHeader\">Videos</div>";
		
	var i = -1, w=0;
	
		
	for ( i in myVideoData )
	{
	
		
		oneVideo = new VideoItem ( myVideoData[i] );

		myTitle 		= oneVideo.getTitle();
		myDescription 	= oneVideo.getDescription().length < DESCRIPTION_MAX ? oneVideo.getDescription() : oneVideo.getDescription().substr(0, DESCRIPTION_MAX) + "...";;
		myThumbURL 		= oneVideo.getThumb();
		
		
		w = parseInt(i) + 1;
		myHTML += "<div class=\"videoSearchResultRow\"><img src=\""+myThumbURL+"\" class=\"videoSearchResultThumbnail\"><div class=\"searchResultTitle\"><a href=\"#commandCloseDrawer&s=" + oneVideo.getShowKey() + "&v=" + oneVideo.getId()+"\" onclick=\"clickHandler(this); return false;\">"+ w + ". " + myTitle + "</a></div>"+myDescription+"</div>";

	}

	myHTML += "</div></div>";
	
	if (i == -1)
	{
	
		myHTML = "No videos found";
	
	}


	updateSearchHeaderPage (0, myHTML, w);
	
} // END of searchVideosHandler