/**
 * @author apellet
 */



	LocalSearch = function ( map, nb_result )
	{
		this.map = map;
		this.arrResults = new Array ();
		this.searchers = new Array ();
    		this.searcher = new GlocalSearch();
    		if ( nb_result == 8 )
    		{
	    		this.searcher.setResultSetSize ( GSearch.LARGE_RESULTSET);
    		}
    		else if ( nb_result == 4 )
    		{
	    		this.searcher.setResultSetSize ( GSearch.SMALL_RESULTSET);
    		}
    		else 
    		{
	    		this.searcher.setResultSetSize ( GSearch.SMALL_RESULTSET);
    		}
		this.searcher.setNoHtmlGeneration();
		this.searcher.setCenterPoint ( map.getCenter() );
		this.searcher.setSearchCompleteCallback(this,
	                                         this.searchComplete,
	                                         [this.searcher]);
      		this.searchers["local"] = this.searcher;
      		
      		this.icon = i_proxi;
      		
		
		
		this.initDom ();
		this.initTemplateBubble ();
	};
	LocalSearch.prototype = 
	{
		icon : null,
		arrResults : [],
		searchers : [],
		searcher : null,
		map : null,
		res : null,
		current : null,
		el_bubble : null,
		tmpl_bubble : null,
		marker : null,
		
		initDom : function ()
		{
			var div_bubble = document.createElement ('div');
			div_bubble.setAttribute ( 'id', 'bubble_local_search' );
			document.body.appendChild ( div_bubble );

			
		},
		initTemplateBubble : function ()
		{
			var h = "";
			h += '<div class="bubble_station">';
			h += '<div class="title">${name}</div>';
			h += '</div>';
	
			
		},
		searchComplete : function ()
		{
			var bounds = new GLatLngBounds ();
			for ( var i = 0; i<this.arrResults.length; i++ )
			{
		    	this.map.removeOverlay ( this.arrResults[i] );
				delete this.arrResults[i];
			}
			if ( home != null )
				this.map.removeOverlay ( home );
			this.map.closeInfoWindow ();
			
			this.arrResults = new Array ();
			this.res = arguments[0].results;
			
			$("#msg-valide").css ( 'display', 'none');
			$("#btn-validate-geoc").attr('disabled', 'true');
			
			var h = document.getElementById ('listeAdresses');
			var tmp = "<ul><li>" + msg_selection_liste + "<ol>";
			
			
			
			for ( var i=0; i<arguments[0].results.length;i++)
    		{
    			/*for ( var item in arguments[0].results[i])
    			{
    				console.log ( "%s %o",item,arguments[0].results[i] [ item ] );
    			}*/
			
				var m = new GMarker ( new GLatLng (arguments[0].results[i].lat, arguments[0].results[i].lng), {icon:this.icon,title:arguments[0].results[i].titleNoFormatting} );
				GEvent.bind ( m, "click", this, GEvent.callbackArgs ( this, this.openInfo, m, i ) );
				this.map.addOverlay ( m );
				this.arrResults.push ( m );
				tmp += "<li><a href='javascript:localiseItemLocalSearch(" + i + ");'>" + arguments[0].results[i].titleNoFormatting + " (" + arguments[0].results[i].streetAddress + ")" + "</a></li>";
				bounds.extend ( m.getLatLng () );
			
			
			}
			tmp += "</ol></li></ul>";
			h.innerHTML = tmp;
			var z = map.getBoundsZoomLevel( bounds );
			this.map.setCenter ( bounds.getCenter (), z );
		},
		
		locateItem : function ( ind )
		{
			this.map.addOverlay ( this.arrResults[ind] );
			this.map.setCenter ( this.arrResults[ind].getLatLng() );
			
			//ADRESSE
			try{
				//console.log ( this.res[ind].titleNoFormatting + " (" + this.res[ind].streetAddress + ") " );
				var t = this.res[ind].titleNoFormatting;
				if (this.res[ind].streetAddress != '') {
					t += " (" + this.res[ind].streetAddress + ")";
				}	
				$("#adr_txt").val ( t );
				
				if ( this.res[ind].aero == '1' )
				{
					//this.current = this.res[ind].latlng;
					
				}
			}
			catch ( error )
			{
				$("#adr_txt").val ( '' );
			}	
			
			//VILLE
			try{
				//console.log ( this.res[ind].titleNoFormatting + " (" + this.res[ind].streetAddress + ") " );
				$("#adr_ville").val ( this.res[ind].city );
			}
			catch ( error )
			{
				$("#adr_ville").val ( '' );
			}	
			
			//CP
			try{
				//console.log ( this.res[ind].titleNoFormatting + " (" + this.res[ind].streetAddress + ") " );
				var line = this.res[ind].addressLines[1];
				var cp = line.split(" ")[0];
				
				$("#adr_cp").val ( cp );
			}
			catch ( error )
			{
				$("#adr_cp").val ( '' );
			}	
			
			cur_adresse = new struct_adresse ( {adr:this.res[ind].streetAddress, cp:$("#adr_cp").val(), ville:$("#adr_ville").val()} );
			cur_adresse.setLatLng ( this.arrResults[ind].getLatLng() );
			cur_adresse.setType ( $("#type_search").val() );
			cur_adresse.setName ( this.res[ind].titleNoFormatting );
			
			//console.log ( cur_adresse );
			
			//this.arrResults.push ( m );
			//h.innerHTML += "<div>" + arguments[0].results[i].titleNoFormatting + "<a href='javascript:localiseItemLocalSearch(" + i + ");'>voir</a></div>"
		},
		
		executeSearch : function ( txt )
    	{
			if ( txt == txt_local_search_aeroport )
			{
				$("#adr_txt").val ( '' );
				$("#adr_ville").val ( '' );
				$("#adr_cp").val ( '' );
				
				var bounds = new GLatLngBounds ();
				for ( var i = 0; i<this.arrResults.length; i++ )
				{
			    	this.map.removeOverlay ( this.arrResults[i] );
					delete this.arrResults[i];
				}
				
				if ( home != null )
					this.map.removeOverlay ( home );
					
				this.map.closeInfoWindow ();			
				this.arrResults = new Array ();
				
			
				$("#msg-valide").css ( 'display', 'none');
				$("#btn-validate-geoc").attr('disabled', 'true');
			
				var h = document.getElementById ('listeAdresses');
				var tmp = "<ul><li>" + msg_selection_liste + "<ol>";
			
			
			
				/*for ( var i=0; i<arguments[0].results.length;i++)
	    		{
	    			var m = new GMarker ( new GLatLng (arguments[0].results[i].lat, arguments[0].results[i].lng), {icon:this.icon,title:arguments[0].results[i].titleNoFormatting} );
					GEvent.bind ( m, "click", this, GEvent.callbackArgs ( this, this.openInfo, m, i ) );
					this.map.addOverlay ( m );
					this.arrResults.push ( m );
					tmp += "<li><a href='javascript:localiseItemLocalSearch(" + i + ");'>" + arguments[0].results[i].titleNoFormatting + " (" + arguments[0].results[i].streetAddress + ")" + "</a></li>";
					bounds.extend ( m.getLatLng () );
				
				
				}*/
				
					var t1 = new GMarker( new GLatLng ( 40.464861, -3.570773 ), {title:'Aeropuerto T1',icon:i_proxi} );
					GEvent.bind ( t1, "click", this, GEvent.callbackArgs ( this, this.openInfo, t1, 0 ) );
					this.map.addOverlay ( t1 );
					this.arrResults.push ( t1 );
					tmp += "<li><a href='javascript:localiseItemLocalSearch(0);'>" + "Aeropuerto T1" + "</a></li>";
					bounds.extend ( t1.getLatLng () );
					
					
					
					var t2 = new GMarker( new GLatLng ( 40.469483, -3.569444 ), {title:'Aeropuerto T2-T3',icon:i_proxi} );
					GEvent.bind ( t2, "click", this, GEvent.callbackArgs ( this, this.openInfo, t2, 1 ) );
					this.map.addOverlay ( t2 );
					this.arrResults.push ( t2 );
					tmp += "<li><a href='javascript:localiseItemLocalSearch(1);'>" + "Aeropuerto T2-T3" + "</a></li>";
					bounds.extend ( t2.getLatLng () );
					
					
					
					var t3 = new GMarker( new GLatLng ( 40.491743, -3.593625 ), {title:'Aeropuerto T-4',icon:i_proxi} );
					GEvent.bind ( t3, "click", this, GEvent.callbackArgs ( this, this.openInfo, t3, 2 ) );
					this.map.addOverlay ( t3 );
					this.arrResults.push ( t3 );
					tmp += "<li><a href='javascript:localiseItemLocalSearch(2);'>" + "Aeropuerto T4" + "</a></li>";
					bounds.extend ( t3.getLatLng () );
				
				this.res = new Array ();
				this.res.push ( {titleNoFormatting:"Aeropuerto T1",city:"Madrid", streetAddress:'', aero:'1', latlng:t1.getLatLng() } );
				this.res.push ( {titleNoFormatting:"Aeropuerto T2-T3",city:"Madrid", streetAddress:'', aero:'1', latlng:t2.getLatLng() } );
				this.res.push ( {titleNoFormatting:"Aeropuerto T4",city:"Madrid", streetAddress:'', aero:'1', latlng:t3.getLatLng() } );
				
				tmp += "</ol></li></ul>";
				h.innerHTML = tmp;
				var z = map.getBoundsZoomLevel( bounds );
				this.map.setCenter ( bounds.getCenter (), z );
			}
			else
			{
				this.searcher.setCenterPoint ( this.current );
    			this.searchers["local"].execute (txt);
			}
    		
    	},
		openInfo : function (m, i)
		{
			/*var d = new String(this.distance ( m.getLatLng (), this.current ));
			
			if ( d.indexOf(".")>0 )
			{
				d = d.substring(0, d.indexOf(".")+2);
			}*/
			
		
			//m.openInfoWindowHtml ( "<div style='font-weight:bold;font-size:12px;margin-bottom:6px;'>" + this.res[i].titleNoFormatting + "</div>" + "<div>" + "<img style='border:2px solid #445daf;' width='150' height='100' src='"+this.res[i].staticMapUrl+"'/>" + "</div>" + "<div id='localSearch_res' style='font-size:10px;'>distance : "+d+" kms</div>" );
			
			m.openInfoWindowHtml ( "<div style='font-weight:bold;font-size:12px;margin-bottom:6px;'>" + this.res[i].titleNoFormatting + "</div>" + "<div>"  + "</div>" );
		},
		distance : function ( latlng1, latlng2 )
		{
			var R = 6371; // km
			var dLat = (latlng2.lat() - latlng1.lat() ).toRad();
			var dLon = (latlng2.lng() - latlng1.lng() ).toRad(); 
			var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
		    	    Math.cos(latlng1.lat().toRad()) * Math.cos(latlng2.lat().toRad()) * 
		        	Math.sin(dLon/2) * Math.sin(dLon/2); 
			var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
			var d = R * c;
			return d;
		},
		getDomProxi : function ( vis )
		{
			vis = true;
			var det = '<div id="detail_proxi_bubble" style="display:' + (vis==true?'block':'none') + ';"><input type="text" id="proxi_bublle_txt"/><button onclick=\'ls.executeSearch(document.getElementById ("proxi_bublle_txt").value);\'>ok</button>';
			det += '<div style="font-size:9px;">';
			det += '<a href="javascript:ls.executeSearch(\'boulanger\');">Boulangeries</a> - ';
			det += '<a href="javascript:ls.executeSearch(\'creche\');">Crèches</a> - ';
			det += '<a href="javascript:ls.executeSearch(\'ecole\');">Ecoles</a> - ';
			det += '<a href="javascript:ls.executeSearch(\'cinema\');">Cin&eacute;mas</a> - ';
			det += '<a href="javascript:ls.executeSearch(\'parking\');">Parkings</a></div>';
			det += '</div>';
			
			
			return '<div style="display:' + (vis==true?'block':'none') + ';" id="titre_proxi_bubble">Rechercher à proximité : </div>' + det;
		},
		showProxiDetail : function ()
		{
			var el = $("#detail_proxi_bubble");
			var el2 = $("#titre_proxi_bubble");
			var vis = false;
			
			if ( el.css('display') == "none" )
			{
				el.css('display', 'block');
				el2.css('display', 'none');
				vis = true;
			}
			else if ( el.css('display') == "block" )
			{
				el.css('display', 'none');
				el2.css('display', 'block');
			}
		}
	};
	Number.prototype.toRad = function() {  // convert degrees to radians
  return this * Math.PI / 180;
};
Number.prototype.toDeg = function() {  // convert radians to degrees (signed)
  return this * 180 / Math.PI;
};

Number.prototype.toBrng = function() {  // convert radians to degrees (as bearing: 0...360)
  return (this.toDeg()+360) % 360;
};
