/**
 * 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		  = 100;
var acURL		  = null;
var acSearchId	  = null;
var acResultsId	  = null;
var acSearchField = null;
var acResultsDiv  = null;

function setAutoComplete(field_id, results_id, get_url){

	// initialize vars
	acSearchId  = "#" + field_id;
	acResultsId = "#" + results_id;
	acURL 		= get_url;

	// create the results div
	$("body").append('<div id="' + results_id + '" style="z-index:500;"></div>');

	// register mostly used vars
	acSearchField	= $(acSearchId);
	acResultsDiv	= $(acResultsId);

	// reposition div
	repositionResultsDiv();
	
	// on blur listener
	acSearchField.blur(function(){ setTimeout("clearAutoComplete()", 200) });

	// on key up listener
	acSearchField.keyup(function (e) {

		// 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
		setTimeout(function () {autoComplete(lastVal)}, acDelay);
	});
}

// treat the auto-complete action (delayed function)
function autoComplete(lastValue)
{
	// get the field value
	var part = 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
	
	//added by requirements functionality
		/*
	   if ((window.document.getElementById('bycomp').checked == true) && (window.document.getElementById('bycategory').checked == true))
	   	  acURL = $('#template_url').val() + "/class/ajax.receiver.php?searchby=3&module=search_auto_complete&part=";
	   else if (window.document.getElementById('bycategory').checked == true) {
	        acURL = $('#template_url').val() + "/class/ajax.receiver.php?searchby=2&module=search_auto_complete&part=";
	      
	   }
	   else if (window.document.getElementById('bycomp').checked == true)
		    acURL = $('#template_url').val() + "/class/ajax.receiver.php?searchby=1&module=search_auto_complete&part=";
	   else {
		   window.document.getElementById('bycomp').checked =true;
			acURL = $('#template_url').val() + "/class/ajax.receiver.php?searchby=1&module=search_auto_complete&part=";
	   }
	   */
		/*
	 if (window.document.getElementById('radio-3').checked == true)	
	 	return;
		*/
	
	 acURL = $('#__BASEURL__').val() + "ajax.receiver.html?searchby=3&module=search_auto_complete&part=";

	$.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 = '';

			// create a div for each result
			for(i=0; i < ansLength; i++) {
				newData += '<div class="unselected" searchoption="' + json[i].searchoption + '" searchid="' + json[i].searchid  + '" qmurl ="' + json[i].qmurl +'" >' + json[i].description + '</div>';
				
				if (part.toLowerCase() == json[i].description.toLowerCase()){
					setFormActionURL(json[i].qmurl);	
				}
			}
			
			
			// update the results div
			acResultsDiv.html(newData);
			acResultsDiv.css("display","block");
			setResetFormActionURL();
			
			
		
					
			// for all divs in results
			var divs = $(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";
				setFormActionURL(this);
				
			})
		
			// on click copy the result text to the search field and hide
			divs.click( function() {
			
				acSearchField.val(this.childNodes[0].nodeValue);
				setFormActionURL(this);
				$('#frmSearchCompany').submit();
				clearAutoComplete();
			});

		} else {
			
			 setResetFormActionURL();
			clearAutoComplete();
			
		}
	});
}


function setResetFormActionURL() {

	if ($('#txtSearchBox').val()!= '') {
		$('#frmSearchCompany').attr("action", $('#__BASEURL__').val() + "companies/"  +  encodeURI($('#txtSearchBox').val().toLowerCase() + ".html") + "?curlang=" + $('#__LANG__').val() );	
	}else {
		$('#frmSearchCompany').attr("action", $('#__BASEURL__').val() + "index.php?curlang=" + $('#__LANG__').val() );		
	}
	
		$('#txtSearchOption').val("by-keywords");
		$('#txtSearchId').val(0);
		$('#txtLastPath').val("");
		$('#txtCurPage').val(0);
		$('#txtPreviousPage').val(0);
		$('#txtLastPage').val(0);
		
}
function setFormActionURL(obj) {
	var linkurl ;	

	if ($(obj).length > 0)
		linkurl	= $(obj).attr("qmurl");
	else {
		linkurl	= obj;
	}
	$('#frmSearchCompany').attr("action", $('#__BASEURL__').val() + "companies/"  +  linkurl  + "?curlang=" + $('#__LANG__').val() );	
	$('#txtSearchOption').val("by-keywords");
	$('#txtSearchId').val(0);
	$('#txtLastPath').val("");
	/*

	 $('#txtCurPage').val(0);
		$('#txtPreviousPage').val(0);
		$('#txtLastPage').val(0);
	if ($(obj).attr("searchoption")=="by-company") {
	
	 $('#frmSearchCompany').attr("action", $('#__TEMPLATEPATH__').val() + "companies/information/" + linkurl.toLowerCase() );
	 $('#txtSearchOption').val($(obj).attr("searchoption"));
	 $('#txtLastPath').val( linkurl.toLowerCase());
	}else if($(obj).attr("searchoption")=="by-category-url") {
	 $('#frmSearchCompany').attr("action", $('#__TEMPLATEPATH__').val() + "companies/" + linkurl.toLowerCase() );	
	 $('#txtSearchOption').val($(obj).attr("searchoption"));
	 $('#txtLastPath').val( linkurl.toLowerCase());
	}else {
	
		//$('#frmSearchCompany').attr("action", $('#__TEMPLATEPATH__').val() + "search-companies/"  + $('txtSearchBox').val());
		$('#frmSearchCompany').attr("action", $('#__TEMPLATEPATH__').val() + "search-companies/"  + $('txtSearchBox').val());
		$('#txtSearchOption').val("by-keywords");
		$('#txtSearchId').val(0);
		$('#txtLastPath').val("");
		
		
    }
	*/
	
				
}
// clear auto complete box
function clearAutoComplete()
{
	acResultsDiv.html('');
	acResultsDiv.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
	acResultsDiv.css("position","absolute");
	acResultsDiv.css("left", sf_left - 1);
	acResultsDiv.css("top", sf_top + sf_height + 10);
	acResultsDiv.css("width", sf_width  +  8 + "px");
}


// treat up and down key strokes defining the next selected element
function updownArrow(keyCode) {
	if(keyCode == 40 || keyCode == 38){

		if(keyCode == 38){ // keyUp
			if(acListCurrent == 0 || acListCurrent == -1){
				acListCurrent = acListTotal-1;
			}else{
				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){
				acSearchField.val(this.childNodes[0].nodeValue);
				$('#txtSearchOption').val($(this).attr("searchoption"));
				$('#txtSearchId').val($(this).attr("searchid"));
				this.className = "selected";
				
				setFormActionURL(this);
			} else {
				this.className = "unselected";
			}
		});

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