/**
 * AutoComplete Field - JavaScript Code
 *
 * This is a sample source code provided by fromvega.
 * Search for the complete article at http://www.fromvega.com
 *
 * Enjoy!
 *
 * @author fromvega
 *
 */

// global variables
var acListTotal   		=  0;
var acListCurrent 		= -1;
var acDelay		  		= 500;
var acURL		  		= null;
var acSearchId	  		= null;
var acResultsId	  		= null;
var acSearchField 		= null;
var acResultsDiv  		= null;
var acResultsDivOuter	= null;
var curDivId 			= null;

function setAutoComplete(field_id, results_id, get_url){
		
		// initialize vars
		acSearchId  = "#" + field_id;
		acResultsId = "#" + results_id;
		acURL 		= get_url;

			
		// create the results div
		/*jQuery("body").append('<div id="' + results_id + '"></div>');*/
	
		// register mostly used vars
		acSearchField		= jQuery(acSearchId);
		acResultsDiv		= jQuery(acResultsId);
		acResultsDivOuter	= jQuery(acResultsId + 'Div');
		// reposition div
		repositionResultsDiv();
		
		// on blur listener
		acSearchField.blur(function(){ setTimeout("clearAutoComplete()", 200) });
	
		// on key up listener
		acSearchField.keyup(function (e) {
	
		if(e.keyCode != 40 && e.keyCode!=38 )
     	{

			jQuery(".shodowright").css("height",'24px');
			jQuery('#autoSuggestResults').html("<div style='background-color:#FFFFFF;'><img src="+IMAGE_PATH+"my_ps/6-0.gif> <b>Loading......</b></div>");
		}
			// get keyCode (window.event is for IE)
			var keyCode = e.keyCode || window.event.keyCode;
			var lastVal = acSearchField.val();

			// check an treat up and down arrows
			if(updownArrow(keyCode)){
				return;
			}
	
			// check for an ENTER or ESC
			if(keyCode == 13 || keyCode == 27){
				clearAutoComplete();
				return;
			}

			// if is text, call with delay
			if(trim(lastVal) !='')
			{
				setTimeout(function () {autoComplete(trim(lastVal))}, acDelay);
			}
			else
			{
				clearAutoComplete();
				return;
			}
		});
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

// treat the auto-complete action (delayed function)
function autoComplete(lastValue)
{ 

	if(librarySearchSelected == 'searchsource' )
	{ 

		// get the field value
		var part = trim(acSearchField.val());
		// if it's empty clear the resuts box and return
		if(part == ''){
			clearAutoComplete();
			return;
		}
	
		// if it's equal the value from the time of the call, allow
		if(lastValue != part){
			return;
		}
	
		// get remote data as JSON
		jQuery.getJSON(acURL + part, function(json){
	
			// get the total of results
			var ansLength = acListTotal = json.length;
	
			// if there are results populate the results div
			if(ansLength > 0){
	
				var newData = '';
				ansLengthLessOne = ansLength - 1;
				// create a div for each result
				//alert(ansLength);
				var LeftDivlength = 0;
				for(i=0; i < ansLength; i++) 
				{
					if(i == ansLengthLessOne )
					{	
						LeftDivlength += 24;
						newData += '<div class="unselected" id="'+ i +'" ><span class="sourcetextsrch" id="sourceName' + i + '">' + json[i]['sourceName'] + '</span>&nbsp;(' + json[i]['totalVideos'] + ')</div>';
					}else{
						LeftDivlength += 24;
						newData += '<div class="unselected" style="border-bottom: 1px solid #999999;" id="'+ i +'"><span class="sourcetextsrch" id="sourceName' + i + '">' + json[i]['sourceName'] + '</span>&nbsp;(' + json[i]['totalVideos'] + ')</div>';
					}
				}
	
				LeftDivlength = LeftDivlength + ansLengthLessOne;
				//alert(newData);
				// update the results div
				acResultsDiv.html(newData);
				//jQuery(".shodowright").css("height",LeftDivlength);
				jQuery(".shodowright").css("height",LeftDivlength);
				acResultsDivOuter.css("display","block");
				// for all divs in results
				var divs = jQuery(acResultsId + " > div");
			
				// on mouse over clean previous selected and set a new one
				divs.mouseover( function() {
					divs.each(function(){ this.className = "unselected"; });
					this.className = "selected";
				})
			
				// on click copy the result text to the search field and hide
				

				divs.click( function() {
					curDivId = jQuery(this).attr('id');
					acSearchField.val(jQuery('#sourceName' + curDivId).html());
					document.getElementById('frmLibSearch').submit();
					clearAutoComplete();
				});
	
			} else {
				clearAutoComplete();
			}
		});
	}
	else if(librarySearchSelected  =='searchuser')
	{
		
		
		// get the field value
		var part = trim(acSearchField.val());

		// if it's empty clear the resuts box and return
		if(part == ''){
			clearAutoComplete();
			return;
		}
	
		// if it's equal the value from the time of the call, allow
		if(lastValue != part){
			return;
		}


		// get remote data as JSON
		jQuery.getJSON(acURL + part, function(json){
	

			// get the total of results
			var ansLength = acListTotal = json.length;

			// if there are results populate the results div
			if(ansLength > 0){

				var newData = '';
				ansLengthLessOne = ansLength - 1;
				// create a div for each result
				//alert(ansLength);
				var LeftDivlength = 0;
				for(i=0; i < ansLength; i++) 
				{
					if(i == ansLengthLessOne )
					{	
						LeftDivlength += 24;
						//newData += '<div class="unselected" id="'+ i +'" ><span class="sourcetextsrch" id="userName' + i + '"><img src="'+json[i]['profile_pic']+'" width="16" height="16" />&nbsp;&nbsp;' + json[i]['userName'] + '</span>&nbsp;</div>';//(' + json[i]['user_follower'] + ')
						newData += '<div class="unselected" id="'+ i +'" ><img src="'+json[i]['profile_pic']+'" width="16" height="16" />&nbsp;&nbsp;<span class="sourcetextsrch" id="userName' + i + '">' + json[i]['userName'] + '</span>&nbsp;</div>';
					}else{
						LeftDivlength += 24;
						//newData += '<div class="unselected" style="border-bottom: 1px solid #999999;" id="'+ i +'"><span class="sourcetextsrch" id="userName' + i + '"><img src="'+json[i]['profile_pic']+'" width="16" height="16" />&nbsp;&nbsp;' + json[i]['userName'] + '</span>&nbsp;</div>';//(' + json[i]['user_follower'] + ')
						newData += '<div class="unselected" style="border-bottom: 1px solid #999999;" id="'+ i +'"><img src="'+json[i]['profile_pic']+'" width="16" height="16" />&nbsp;&nbsp;<span class="sourcetextsrch" id="userName' + i + '">' + json[i]['userName'] + '</span>&nbsp;</div>';
					}
				}
	
				LeftDivlength = LeftDivlength + ansLengthLessOne;
				//alert(newData);
				// update the results div
				acResultsDiv.html(newData);
				//jQuery(".shodowright").css("height",LeftDivlength);
				jQuery(".shodowright").css("height",LeftDivlength);
				acResultsDivOuter.css("display","block");
				// for all divs in results
				var divs = jQuery(acResultsId + " > div");
			
				// on mouse over clean previous selected and set a new one
				divs.mouseover( function() {
					divs.each(function(){ this.className = "unselected"; });
					this.className = "selected";
				})
			
				// on click copy the result text to the search field and hide
				

				divs.click( function() {
					curDivId = jQuery(this).attr('id');
					acSearchField.val(jQuery('#userName' + curDivId).html());
					document.getElementById('frmLibSearch').submit();
					clearAutoComplete();
				});
	
			} else {
				clearAutoComplete();
			}
		});
		
		
	}
}

// clear auto complete box
function clearAutoComplete()
{
	acResultsDiv.html('');
	acResultsDivOuter.css("display","none");
}

// reposition the results div accordingly to the search field
function repositionResultsDiv()
{
	// get the field position
	var sf_pos    = acSearchField.offset();
	var sf_top    = sf_pos.top;
	var sf_left   = sf_pos.left;
	// get the field size
	var sf_height = acSearchField.height();
	/*var sf_width  = acSearchField.width();*/

	// apply the css styles - optimized for Firefox
	acResultsDivOuter.css("position","absolute");
	/*acResultsDivOuter.css("left", sf_left - 2);
	acResultsDivOuter.css("top", sf_top + sf_height + 5);*/
	acResultsDivOuter.css("top", sf_top + sf_height + 2);
	/*acResultsDiv.css("width", sf_width - 2);*/
}

// treat up and down key strokes defining the next selected element
function updownArrow(keyCode)
{

	if((librarySearchSelected  =='searchuser' || librarySearchSelected == 'searchsource') && keyCode != 40 && keyCode != 38)
	{
	   acResultsDiv.html("<div style='background-color:#FFFFFF;'><img src="+IMAGE_PATH+"my_ps/6-0.gif> <b>Loading......</b></div>"); 
	   acResultsDivOuter.css("display","block");
	}
	
	if(keyCode == 40 || keyCode == 38)
	{
		
		if(keyCode == 38)
		{ // keyUp

			if(acListCurrent == 0 || acListCurrent == -1){
			//curDivId = jQuery(this).attr('id');
			//acSearchField.val(jQuery('#sourceName' + curDivId).html());	
				acListCurrent = acListTotal-1;
		}else
		{
				//alert(acListCurrent);
				acListCurrent--;
		}
	} 
	else
	{ // keyDown
		if(acListCurrent == acListTotal-1)
		{
			acListCurrent = 0;
		}
		else
		{
			acListCurrent++;
		}
	}
		// loop through each result div applying the correct style
		    
					
			acResultsDiv.children().each(function(i){
			if(i == acListCurrent)
			{
				//alert(i);
				acSearchField.val(jQuery(this).find('span').html());
				
				//alert(acSearchField.val());
				this.className = "selected";
			}
			else
			{
				this.className = "unselected";
			}
		});

		return true;
	} 
	else 
	{
		// reset
		acListCurrent = -1;
		return false;
	}
}