/*---------------
 * jQuery Findmynearest Plugin by Engage Interactive
 * Copyright (c) 2009 Engage Interactive
 * Author: Neil Charlton
 * Version: 1.0
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires: 
 	1. jQuery v1.3 or later
 	2. Google Maps API
	3. A locations datasource containing id, name, latitude and longtitude
---------------*/

var iQueue = 0;
var ourLocs = [];
	
(function($) {

	findmynearest = function( options ){
	
			var geocoder = "", latlng = null, loglat = "", loglng = "";
			var defaults = {
					sEmptyMessage: "<h4>Sorry&hellip;</h4><p style=\"padding:0 30px;\">We couldn&rsquo;t find any matches. Why not try searching using one of the following:</p><p class=\"bottom\" style=\"padding:0 30px;\">&raquo; A full UK postcode (no spaces)<br />&raquo; A UK city, town or village<br />&raquo; A UK landmark (e.g. Big Ben)</p>",
					dataSource: "/locations/locationsJsonList",
					resultsDiv: "results",
					addressFieldId: "address",
					searchTotal:5,
					resultsUrl: '/location/',
					logger: true,
					sBrand: 'rouge',
					resultType: 'list',
					resultTitle: '<h4>Closest restaurants...</h4>'
					};

			var settings = $.extend( {}, defaults, options );


			showloader = function(){
				$( "#" + settings.resultsDiv ).html('');
				$( "#" + settings.resultsDiv ).slideDown( "slow", function(){
						
				} );
				$( "#" + settings.resultsDiv ).html('<div id="loading">Loading results&hellip;</div>');
			}

			hideloader = function(){
				$( "#" + settings.resultsDiv ).slideUp( "slow", function(){
					setTimeout(function() {
						$('#fmn-form button').attr("disabled",false);
						iQueue = 0;
						//** Specific to locations page on rouge
						if( typeof window.hideResultsShowMap == 'function' ){
							hideResultsShowMap();
						}
					},500);
				} );
			}

			checkInputs = function() { return ( settings.dataSource == '' ) }

			getResults = function( id, name, dist, data ){

				var km = (parseFloat(dist / 1000)).toFixed(1) + "km";
				var miles = (parseFloat(dist / 1609)).toFixed(1) + " miles";
				if( settings.resultType == 'list' ){
					return '<li><a href=\"' + settings.resultsUrl + '' + name.replace(/ /g,"-") + '" title="Click for full details about this restaurant" class="aLocation">' + name + '</a> ' + miles + '</li>';
				}
				if( settings.resultType == 'table' ){

					return '<tr> \
								<td width="180"><a href="/location/' + name.replace(/ /g,"-") + '">' + name + '</a><br /><strong>Tel:</strong> ' + data.telephone + '</td> \
		\
								<td width="130"> \
								<address> \
								' + data.address + '</address> \
								</td> \
								<td width="160">Distance from you<br /> \
								<span class="distance">' + miles + '</span></td> \
		\
							</tr>';
				}
			}

			printMessage = function( sMessage ){
				$("#loading").hide();
				$( "#" + settings.resultsDiv ).html( '<div id="results_content">' + sMessage + '</div>' );
			}

			//** Disable button click again
			$('#fmn-form button').attr("disabled","disabled");

			if( iQueue < 1 ){
				showloader();
				iQueue = iQueue + 1;
			}

			$( "#" + settings.addressFieldId ).focus(function(){
				hideloader();
			});
	
			if( checkInputs( ) ) { alert( "You must pass a datasource URL" ); return true; };

			var searchTerm = $( "#" + settings.addressFieldId ).val();
			if( searchTerm == '' || searchTerm.match( /Where are you/ ) ){
				printMessage( settings.sEmptyMessage );
				return false;
			}

			// special case for london  if( searchTerm.toLowerCase() == 'selfridges' ) searchTerm = "Selfridges, London";
			
			
			var sSt = $( "#" + settings.addressFieldId ).attr( "value" );
			if( sSt.toLowerCase() == 'london' ){
				var sStr = "<h4>Please try and refine your search</h4><p style=\"padding:0 30px;\">We have many restaurants in London so if you could try and be a bit more specific that would really help.</p><p class=\"bottom\" style=\"padding:0 30px;\">\
				 			For example, try entering a London suburb such as 'Islington', a postcode or even a popular landmark.</p>";
				printMessage( sStr );
				return false;
			}
			
			if( searchTerm.toLowerCase() == 'euston' ) searchTerm = "Euston station";

			/* get the locations json from the webservice  */
			$.getJSON( settings.dataSource, 
				function(data){
				if( !data ){
					printMessage( "There was a problem, please try again" );
					return false;
				}

			  	$.each(data.items, function(i,item){
					var address = item.address_1 + '<br />' + item.town_city + '<br />' + item.postcode;
					ourLocs[item.id] = new Array( item.lng, item.lat, item.name, item.uid, address, item.telephone );
			    });
				data = "";
			});


			var places = [];
			if (GBrowserIsCompatible()) {
		        geocoder = new GClientGeocoder();
		    }

			geocoder.getLatLng( searchTerm + ",uk", function( point ){ 
				if( !point ){
					printMessage( settings.sEmptyMessage );
				}
				else
				{
					var centerpoint = new GLatLng( point.lat(), point.lng() )

					loglat = point.lat();
					loglng = point.lng();

					// delay the execution of this script to give json time to populate ourLocs
					setTimeout(function() {

						$.each( ourLocs, function(i,n){ 

							if( this[2] != undefined )
							{
								var lat = parseFloat( this[1] );
							    var lng = parseFloat( this[0] );
							    var latlng = new GLatLng( lat, lng );
								var name = this[2];
								var id = this[4];
								if( !isNaN( lat ) ){
		                                 	places.push( { latlng:latlng , name:name, id:id, address:this[4], telephone:this[5] } );
								}
							}
						});


						/* Calculate the distances */
						for (i=0; i<places.length; i++) {
			          		places[i].dist = places[i].latlng.distanceFrom( centerpoint );
						}

						places.sort(function (a,b) {return (a.dist - b.dist)});

						var iCnt = 0;
						var sOut = ( settings.resultType == 'list' ) ? '' + settings.resultTitle + '<ul class="find_my_nearest">' : '<div id="results_content"><table class="find_my_nearest">';
						var sOutClosing = ( settings.resultType == 'list' ) ? '</ul>' : '</table></div>';
						for ( var key in places ) {
							if( iCnt < settings.searchTotal ){
								sOut += getResults( places[key].id, places[key].name, places[key].dist, places[key] );
							}
							iCnt++;
						}

						/* We have some results so animate the results div */

						if( places.length > 1 && iQueue ==1 ){

							printMessage( sOut + sOutClosing );

							if( settings.logger ){
								$.post( "/locations/logfindmynearest", { brand: settings.sBrand, term: searchTerm, lng: loglng, lat: loglat }, function(data){

								} );
							}
							iQueue = 0;
						}
					}, 1000);	
				}
				return false;
			});
	
	};
	


})(jQuery);
