/***
@title:
Live Search

@version:
2.0

@author:
Andreas Lagerkvist

@date:
2008-08-31

@url:
http://andreaslagerkvist.com/jquery/live-search/

@license:
http://creativecommons.org/licenses/by/3.0/

@copyright:
2008 Andreas Lagerkvist (andreaslagerkvist.com)

@requires:
jquery, jquery.liveSearch.css

@does:
Use this plug-in to turn a normal form-input in to a live ajax search widget. The plug-in displays any HTML you like in the results and the search-results are updated live as the user types.

@howto:
jQuery('#q').liveSearch({url: '/ajax/search.php?q='}); would add the live-search container next to the input#q element and fill it with the contents of /ajax/search.php?q=THE-INPUTS-VALUE onkeyup of the input.

@exampleHTML:
<form method="post" action="/search/">

	<p>
		<label>
			Enter search terms<br />
			<input type="text" name="q" />
		</label> <input type="submit" value="Go" />
	</p>

</form>

@exampleJS:
jQuery('#jquery-live-search-example input[name="q"]').liveSearch({url: WEBROOT +'?module=SearchResults&q='});
***/
jQuery.fn.liveSearch = function (conf) {
	var config = jQuery.extend({
		url:			'/?module=SearchResults&q=', 
		id:				'jquery-live-search', 
		duration:		400, 
		typeDelay:		1000,
		useType: 		'explore',
		loadingClass:	'loading', 		
		onSlideUp:		function () {}
	}, conf);
	var liveSearch	= jQuery('#' + config.id);
	var this_xmlhttprequest;
	if (!liveSearch.length) {
		liveSearch = jQuery('<div id="' + config.id + '"></div>').appendTo(document.body).hide().slideUp(0);

		jQuery(document.body).click(function(event) {
			var clicked = jQuery(event.target);

			if (!(clicked.is('#' + config.id) || clicked.parents('#' + config.id).length || clicked.is('input'))) {				
				liveSearch.slideUp(config.duration, function () {
					config.onSlideUp();
				});
			}
		});
	}

	return this.each(function () {
		var input		= jQuery(this).attr('autocomplete', 'off');
		var results	= parseInt(liveSearch.css('paddingLeft'), 10) + parseInt(liveSearch.css('paddingRight'), 10) + parseInt(liveSearch.css('borderLeftWidth'), 10) + parseInt(liveSearch.css('borderRightWidth'), 10);

		input
			.focus(function () {
				if (this.value !== '') {
					//original
					//if (liveSearch.html() == '') {					
					if ((liveSearch.html() == '')&&(this.useType != "explore")) {	
						
						this.lastValue = '';
						input.keyup();
					}
					else {
						liveSearch.slideDown(config.duration);
					}
				}
			})
			.keyup(function () {
				if (this.value != this.lastValue) {
					input.addClass(config.loadingClass);

					var q = this.value;

					if (this.timer) {
						clearTimeout(this.timer);
					}

					this.timer = setTimeout(function () {
						
						//don't run the query unless 2 letters have been typed.
						
						if(q.length > 2)
						{		
							if(this_xmlhttprequest != undefined)
							{
								this_xmlhttprequest.abort();		
							}
							
							showLoadingResults();
							
							this_xmlhttprequest = jQuery.get(config.url + q, function (data) {
								hideLoadingResults();																						   
								input.removeClass(config.loadingClass);
	
								if (data.length && q.length) {
									var tmpOffset	= input.offset();
									var inputDim	= {
										left:		tmpOffset.left, 
										top:		tmpOffset.top, 
										width:		input.outerWidth(), 
										height:		input.outerHeight()
									};
	
									inputDim.topNHeight	= inputDim.top + inputDim.height;
									inputDim.widthN	= inputDim.width - results;
	
									liveSearch.css({
										position:	'absolute', 
										left:		inputDim.left + 'px', 
										top:		inputDim.topNHeight + 'px',
										width:		inputDim.widthN + 'px'
									});
									
									this_xmlhttprequest.abort();
									clearTimeout(this.timer);
									
									if(config.useType == "explore")
									{										
										$("#"+config.id).html("");
										processSearchJSON(data, config.useType, config.id);										
									}
									else
									{								
										liveSearch.html(processSearchJSON(data, config.useType, config.id)).slideDown(config.duration);		
									}									
								}
								else {
									liveSearch.slideUp(config.duration, function () {
										config.onSlideUp();
									});
								}
							});
							
						}
						else
						{
							setMessage("<label>The search will only begin once a minimum of 2 letters have been defined.</label>");
						}	
					}, config.typeDelay);

					this.lastValue = this.value;
				}
			});
	});
};

var no_records_msg = "Sorry! There are no records of this species yet.";
var no_species_msg = "Sorry! There are no species of that name. Please try searching again.";
var protected_species_msg = "This animal or plant is on the EYE Project's Protected Species list and records for this species are not available. <a href=\"/protectedspecies\">Find out why...</a>";

function resetMessage()
{
	$("#searchSpeciesMessages").html("");	
}

function setMessage(message)
{
	$("#searchSpeciesMessages").html(message);	
}

function processSearchJSON(data, useType, id)
{
	var noimageurl = media_url+"sumo/tpl/img/content/search.results.image.blank.png";
	var newdata = eval(data);
	resetMessage();
	var searchTerm = "";
	
	if(newdata[1] != undefined)
	{
		
		searchTerm = $("#"+id).val();
		var html = "";
		
		resetRecordTable("matchedrecords");
		addColumnHeadingRecordTable("matchedrecords");
		
		if(newdata[0].SearchType == "SpeciesRecords")
		{						
			$("#searchterm").html(searchTerm);
			$("#searchterm").val(searchTerm);
			showNumberOfMatches(newdata[newdata.length-1].Count-1);
			if(newdata[newdata.length-1].Count>0)
			{
				for(var i = 1; i < newdata[newdata.length-1].Count+1; i++)
				{
					//var species_id = newdata[i][0].species_id;
					//var description = newdata[i][1].description;
					//var location = newdata[i][2].location;									
					var datetime = processNonPrettyDateTime(String(newdata[i][3].observed_datetime));
					var species = String(newdata[i][4].species);								
					//var user = newdata[i][5].created_by;
					//var record_id = newdata[i][6].id;
					
					var species__common_name = species.substring(0, species.indexOf("("));
					var species__scientific_name = species.substring(species.indexOf("("), species.length);
					
					html += "<label>Species:"+species+"</label><br>";
					html += "<label>Description:"+newdata[i][1].description+"</label><br>";
					
					html += "<hr>";
					var index;
					if(useType == "explore")
					{		
						if(i == 1)
						{
							index = 0;	
						}
						else
						{
							index = i;	
						}
					
						//orig
						var overlay_marker = processMarkers(index, newdata[i][0].species_id, newdata[i][6].id, species__common_name, species__scientific_name, newdata[i][2].location, newdata[i][1].description, datetime);
						
						addMarkerToCluster(overlay_marker);
						
						var row = createMatchedRecords(i, newdata[i][0].species_id, newdata[i][6].id, species__common_name, species__scientific_name, newdata[i][2].location,  newdata[i][1].description, datetime);	
						appendNewRowRecords("matchedrecords", row);
					}
					
				}
				
				checkClustering();				
			}
			else if(newdata[1].Protected)
			{
				if(newdata[1].Protected == true)
				{
					resetRecordTable("matchedrecords");
					/*clearAllMarkers();			
					addKMLExtent();*/
					refreshClusters();
					openDialog("notification", protected_species_msg);
				}
			}
			else
			{
				resetRecordTable("matchedrecords");
				/*clearAllMarkers();
				addKMLExtent();*/
				refreshClusters();
				openDialog("notification", no_records_msg);
			}
			
		}
		else if(newdata[0].SearchType == "Species")
		{						
			showNumberOfMatches(newdata[newdata.length-1].Count-1);
			if(newdata[newdata.length-1].Count)
			{
				for(var i = 1; i < (newdata[newdata.length-1].Count+1); i++)
				{
					
					var common_name = newdata[i][0].common_name;
					var protected = newdata[i][2].protected;
					var scientific_name = newdata[i][1].scientific_name;
					var species_id = newdata[i][3].id;					
					var primary_image = newdata[i][5].primary_image;
					var secondary_image = newdata[i][6].secondary_image;
					var tertiary_image = newdata[i][7].tertiary_image;
					
					var primary_image_photo_credit = newdata[i][8].primary_image_photo_credit;
					
					var name = String(common_name+" ("+scientific_name+")");					
					var link_id = "species_common_name_"+species_id;
					var species_detail_link = species_detail_url+species_id;
					
					if (protected == "True")
					{
						html += "<li style=\"width:200px; height: 250px;\">";	
					}
					else
					{
						html += "<li style=\"width:200px; height: 200px;\">";	
					}
							
					//primary image / secondary image / tertiary image all point at primary image field in model
					//primary image = 400 * 400
					//secondary image = 200 * 200
					//tertiary image = 128 * 128
							
					if((primary_image == "")&&(secondary_image == "")&&(tertiary_image == ""))
					{												
						//<em>"+scientific_name+"</em>
						
						html += "<span><a id=\"id_"+link_id+"\" href=\"#\" style=\"font-size:10pt;\" alt=\""+name+"\" title=\""+name+"\" onclick=\"selectSpecies('"+species_id+"');\">"+common_name+"</a></span><br><br><a href=\"#\"><img class=\"image\" title=\""+name+"\" alt=\""+name+"\" onclick=\"selectSpecies('"+species_id+"');\" src=\""+noimageurl+"\" alt=\"No Image Available\"/></a>";	
					}
					else
					{
						/*if(primary_image != "")
						{							
							html += "<span><a href=\"#\" alt=\""+name+"\" title=\""+name+"\" onclick=\"selectSpecies('"+species_id+"');\">"+common_name+"<br></a><span><br><br><a href=\"#\"><img class=\"image\" onclick=\"selectSpecies('"+species_id+"');\" alt=\""+name+"\" src=\""+media_url+primary_image+"\" id=\"species_primary_image_"+species_id+"\"/></a><br>";
						}
						
						else if(secondary_image != "")
						{															
								html += "<span><a href=\"#species_no_image_"+species_id+"\" alt=\""+name+"\" title=\""+name+"\" onclick=\"selectSpecies('"+species_id+"');\">"+common_name+"<br><em>"+scientific_name+"</em></a><span><br><br><a href=\"#\"><img class=\"image\" onclick=\"selectSpecies('"+species_id+"');\" alt=\""+name+"\" src=\""+media_url+secondary_image+"\" id=\"species_secondary_image_"+species_id+"\"/></a><br>";
						}
						
						else */if(tertiary_image != "")
						{					
						
							html += "<span><a id=\"id_"+link_id+"\" href=\"#\" style=\"font-size:10pt;\" alt=\""+name+"\" title=\""+name+"\" onclick=\"selectSpecies('"+species_id+"');\">"+common_name+"</a></span><br><br><a href=\"#\"><img class=\"image\" title=\""+name+"\" alt=\""+name+"\" onclick=\"selectSpecies('"+species_id+"');\" src=\""+media_url+tertiary_image+"\" alt=\""+name+"\"/></a>";
							
							if (primary_image_photo_credit != "")
							{
								html += "<br><label>Credit: "+primary_image_photo_credit+"</label>";
							}
						
							//html += "<span><a id=\"id_"+link_id+"\" href=\"#species_no_image_"+species_id+"\" alt=\""+name+"\" title=\""+name+"\" onclick=\"selectSpecies('"+species_id+"');\">"+common_name+"</a></span><br><br><a href=\"#\"><img class=\"image\" onclick=\"selectSpecies('"+species_id+"');\" alt=\""+name+"\" src=\""+media_url+tertiary_image+"\" id=\"species_tertiary_image_"+species_id+"\"/></a>";
						}
					}
								
					html += "<br><div style=\"padding-top:5px;\"><a alt=\"Click to view\" style=\"font-size:10pt;\" href=\""+species_detail_link+"\">More info...</a><label  id=\""+link_id+"\" style=\"visibility: hidden; height:0px;\" val=\""+common_name+"\">"+common_name+"</label></div><br>";	
					//what about show all species records for user xxx

					if (protected == "True")
					{
						html += "<span style=\"font-size:10pt;\">Protected Species Status:</span><a style=\"font-size:10pt;\" href=\"/protectedspecies\">Find out more... </a><br />";//This animal or plant is on the EYE Project's Protected Species list.
					}
					
					html += "<hr>";
					html += "</li>";
				}
			}
			else
			{
				resetRecordTable("matchedrecords");				
				openDialog("notification", no_species_msg);
			}			
		}				
		return html;		
	}
	else
	{
		return "<label>No matches found</label>"	
	}
}

function selectSpecies(id)
{	
	//setting the hidden value
	$("#id_0-species").val(id);	
	var name = $("#species_common_name_"+id).html();			
	
	openDialog("next_step"," <label id=\"speciesname\"><strong>Selected species: "+name+"</strong></label><br/><div><div><p>Please click 'Next Step' to continue, or 'Cancel' to return to species search.</p><br><div style=\"text-align:center;\"><input type=\"button\" class=\"button\" value=\" Next Step\" onClick=\"document.forms[0].submit();\"/><input type=\"button\"  style=\"margin-left:10px;\" onClick=\"clearSelectedSpecies(); closeDialog('next_step');\" class=\"button\" value=\"Cancel\"/></div> ");
	
}

function clearSelectedSpecies()
{
	//$("#nextstepinstruct_0").hide();	
	$("#speciesname").html("Selected species:");	
}

function showLoadingResults()
{
	$("#loadingResults").show();
	$("#loadingResults").css("visibility", "visible");
}

function hideLoadingResults()
{
	$("#loadingResults").hide();
	$("#loadingResults").css("visibility", "hidden");
}