/*
Google map functions
*/


var map;
var geocoder;
var radius = null;
var cat = null;
var marker = null;
var marker_array 	= new Array();
marker_array["normal"]	="/images/icons/icon_map_normal.png";
marker_array["active"]	="/images/icons/icon_map_active.png";
marker_array["seen"]	="/images/icons/icon_map_seen.png";

var markers_visted	=	new Array();
var last_seen_marker="";
var baseIcon 					= new GIcon();
baseIcon.iconAnchor 		= new GPoint(20, 40);
baseIcon.infoWindowAnchor	= new GPoint(35, 0);

var elm_icon_loading	= new Object();

var img_refresh		=	'<img src="/templates/v5/images/bt_refresh.png">';
var img_refresh_ani	=	'<img src="/templates/v5/images/bt_refresh_loading.gif">';

var user_control=0;


var mySlide_info	= new Object();

// ====== Array for decoding the failure codes ======
var reasons=[];
reasons[G_GEO_SUCCESS]            = "Success";
reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";


// arrange for our onunload handler to "listen" for onunload events
if (window.attachEvent) {
	window.attachEvent("onunload", function() {
		GUnload();      // Internet Explorer
	});
} else {
	window.addEventListener("unload", function() {
		GUnload(); // Firefox and standard browsers
	}, false);
}

//	catch key strokes
document.onkeydown = capturekeyDown;
function capturekeyDown(e){
	if (document.all){
		var evnt = window.event;
    	keycode = evnt.keyCode;
	}else{
    	keycode = e.keyCode;
	}
  	if(keycode==13){
	  	searchLocations()
	}
}

//	loading states
function map_loading(state){
	elm_loading		=	document.getElementById("map_loading");
	//elm_icon_loading=	document.getElementById("bt_map_loading");
	if(state==1){
		//	loading map
		elm_loading.style.display="";
		//elm_icon_loading.innerHTML=img_refresh_ani;
	}else{
		elm_loading.style.display="none";
		//elm_icon_loading.innerHTML=img_refresh;
	}
}

//	basic load map 
function load_map(lat,lng,elm_map) {
	if (GBrowserIsCompatible()) {
		geocoder = new GClientGeocoder();
       	map = new GMap2(document.getElementById(elm_map));
       	map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GScaleControl());
		map.addControl(new GHierarchicalMapTypeControl());
		map.addControl(new GOverviewMapControl());
		map.setCenter(new GLatLng(lat,lng), 5);

	}
}

//	search map only as it detects user movement
function load_map_search(lat,lng,zoom){
	if(zoom=="") zoom=5;
	if (GBrowserIsCompatible()) {
		geocoder = new GClientGeocoder();
       	map = new GMap2(document.getElementById('search_map'));
       	//map.addControl(new GLargeMapControl());
		//map.addControl(new GMapTypeControl());
		//map.addControl(new GScaleControl());
		map.addControl(new GHierarchicalMapTypeControl());
		map.addControl(new GOverviewMapControl());
		map.setCenter(new GLatLng(lat,lng),zoom);
		
		map.addControl(
			new TextualZoomControl(),
          	new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,7)));
        	map.enableContinuousZoom();
 
        	var otherOpts = { 
          		buttonStartingStyle: {display:"block",color:"black",background:"white",width:"9em",textAlign:"center",
            	fontFamily:"Verdana",fontSize:"10px",fontWeight:"bold",border:"1px solid gray",paddingBottom:"1px",cursor:"pointer"},
          		buttonHTML: ""+lang_drag_zoom+"",
          		buttonZoomingHTML: ""+lang_drag_zoom_inst+"",
          		buttonZoomingStyle: {background:"yellow"},
         	 	backButtonHTML: ""+lang_drag_zoom_back+"",  
         	 	backButtonStyle: {display:"none",marginTop:"3px",background:"#FFFFC8"},
          		backButtonEnabled: true
			}
			map.addControl(new DragZoomControl({}, otherOpts, {}), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,39)));


		//clusterer = new Clusterer(map);
		GEvent.addListener(map,'dragend',function(){
           user_move_map();
		}); 
		GEvent.addListener(map,'zoomend',function(){
          	user_move_map();
		}); 
		
		 // ====== Create a Client Geocoder ======
      	geo = new GClientGeocoder(); 
	  	user_move_map();
	}
	
}



function get_url(the_url,lat,lng,map_zoom){
	remove_advert_info();	// close advert info box if open
	//	NOTE - map_zoom set to allow code to define bounds, otherwise the map bounds are as defined by the user
	map_loading(1);

	//	add essential data to url
	var id_cat 		= document.getElementById('map_cat').value;
	if(id_cat!="")	the_url+="&id_cat="+id_cat;
	the_url+="&the_lang="+lang_lang+"&num_results=100";
	
	//	show url on page for debug
	document.getElementById('show_url').value=the_url;
	
	GDownloadUrl(the_url, function(data) {
		var xml = GXml.parse(data);
		var markers = xml.documentElement.getElementsByTagName("marker");
		map.clearOverlays();	//	remove all icons 
		markers_visted.length=0; // remove previously seen markers from array
		var bounds = new GLatLngBounds();
      	//alert(the_type);
		var show_point="1";
		for (var i = 0; i < markers.length; i++) {
        	var point 		= new GLatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
			
			if(user_control==55){
				//check if point is inside the viewing area of the map
            	bounds = map.getBounds();
				if (!bounds.contains(point) == true) show_point="0";
			}else{
				show_point="1";
			}
			
			if(show_point=="1"){
				bounds.extend(point);
				/*
				if(the_type=="zones")		add_marker_zones(markers[i],point);
				else if(the_type=="regions")add_marker_regions(markers[i],point);
				else if(the_type=="areas")	add_marker_areas(markers[i],point);
				else						*/
				add_marker(markers[i],point);
				//alert(map.getBoundsZoomLevel(bounds));
			}
      	}
		var elm_msg=document.getElementById("address_alternatives");
		if(markers.length<1){
			elm_msg.innerHTML ='<div style="color:red; text-align:center;">'+lang_no_adverts_found+'</div>';
			var myFx = new Fx.Scroll(window).toElement('search_map');
			if(lat!=''){
				//	center map first (mainly incase there are no adverts)
				//alert("new center...");
				point=new GLatLng(lat,lng);
				map.setCenter(point,10);
				map.addOverlay(new GMarker(point));
			}
		}else{
			elm_msg.innerHTML ="";
			if(map_zoom){
				map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
			}
		}
		map_loading(0);
	});
}




function searchLocations() {
	var the_address="";
	var elm_msg=document.getElementById("address_alternatives");
	var address_txt		= document.getElementById('addressInput').value;
	
	if(address_txt==""){
		//	call adverts just with ids - no need to geocode address
		alert("no address");
		map_adverts(country_code,id_region,"");
		
	}else{
		the_address += address_txt;
	
		//if(the_region!="")	the_address += ", "+the_region;
		//the_address +=", "+country_code;
		////alert(the_address);
		
		user_control="0"; //	 reset
		
		/*
		geocoder.getLatLng(address, function(latlng) {
			if (!latlng)	alert(address + ' not found');
			else			get_adverts_near(latlng);
		});
		*/
		// ====== Perform the Geocoding ======        
		
		geo.getLocations(the_address, function (result){
			map.clearOverlays(); 
			//alert(result.Status.code);
			if (result.Status.code == G_GEO_SUCCESS) {
				// ===== If there was more than one result, "ask did you mean" on them all =====
	 			if (result.Placemark.length > 1) { 
	     			elm_msg.innerHTML = lang_title_address_alertnatives+'<br><hr>';
	                // Loop through the results
	                for (var i=0; i<result.Placemark.length; i++) {
	                  	var p = result.Placemark[i].Point.coordinates;
	                  	elm_msg.innerHTML += (i+1)+": <a href='javascript:get_adverts_near(" +p[1]+","+p[0]+")'>"+ result.Placemark[i].address+"<\/a><br>";
		                }
					var myFx = new Fx.Scroll(window).toElement('search_map');
				}
				// ===== If there was a single marker =====
	            else {
					elm_msg.innerHTML = "";
	                var p = result.Placemark[0].Point.coordinates;
	                get_adverts_near(p[1],p[0],address_txt)
					//place(p[1],p[0]);
	     		}
	   		}
			// ====== Decode the error status ======
	        else {
				var reason="Code "+result.Status.code;
	       		if (reasons[result.Status.code]) {
	                reason = reasons[result.Status.code]
				}
				alert('Could not find "'+the_address+ '" ' + reason);
			}
		
		});
	}

}
function get_adverts_near(lat,lng,address_txt) {
	var radius 		= document.getElementById('radiusSelect').value;
	var the_address_txt=address_txt;
	var the_url = "/includes/ajax/search_map.ajax.php?lat="+lat+"&lng="+lng+"&radius="+radius+"&the_address_txt="+the_address_txt;
	get_url(the_url,lat,lng,true);
}

//	detect user drag
function user_move_map(){
	user_control=1;
	//	get adverts within bounds defined by the user
	var bounds = map.getBounds();
	var south_lat	= bounds.getSouthWest().lat();
	var north_lat	= bounds.getNorthEast().lat(); 
	var west_lng	= bounds.getSouthWest().lng();
	var east_lng	= bounds.getNorthEast().lng();
	var the_url = "/includes/ajax/search_map.ajax.php?res_type=bounds&south_lat="+south_lat+"&north_lat="+north_lat+"&east_lng="+east_lng+"&west_lng=" + west_lng;
	get_url(the_url,"","","");
}

//	get all adverts within area or region defined
function map_adverts(country_code,id_region,id_area){
	alert("why here???");
	var id_cat 	= document.getElementById('map_cat').value;
	var the_url = "/includes/ajax/search_map.ajax.php?res_type=adverts&country_code="+country_code+"&id_region="+id_region+"&id_area="+id_area;
	get_url(the_url,"","");
}

//	function to place single makerer - draggable marker and send cords to hidden fields if defined
function add_advert_marker(point,draggable,icon_type,marker_title){
	icon=create_icon(icon_type);
	//alert(icon_id);
	//alert(marker_title);
	if(draggable==1){
		marker = new GMarker(point, {"icon": icon, "draggable": true,"title" :marker_title});
		document.getElementById("lat").value = marker.getPoint().lat();
		document.getElementById("lng").value = marker.getPoint().lng();
		GEvent.addListener(marker, "dragend", function() {
			document.getElementById("lat").value = marker.getPoint().lat();
			 document.getElementById("lng").value = marker.getPoint().lng();
		});
	}else{
		marker = new GMarker(point, {"icon":icon,"title":marker_title});
	}
	map.addOverlay(marker);
}

//	add markers with advert details
function add_marker(the_marker,point){
	//alert("here??");
	var name 		= the_marker.getAttribute("name");
	var id_advert	= the_marker.getAttribute("id");
	var address 	= the_marker.getAttribute("address");
	var distance 	= parseFloat(the_marker.getAttribute("distance"));
	var foto		= the_marker.getAttribute("image");
	var region		= the_marker.getAttribute("region");
	var the_cat		= the_marker.getAttribute("cat");
	if(the_marker.getAttribute("prices")) var the_prices='<br>'+the_marker.getAttribute("prices");
	else var the_prices="";
	
	//var marker = new GMarker(point);
	
	if(foto!="")	the_image='<img src="/upload/phpThumb.php?src='+foto+'&q=40&w=160&h=110&zc=1&aoe=1&bc=b4b4b4&bg=EDF3F6" width="160" height="110" style=""><br>';
	else			the_image="";
	
	//	if no langua trablsaation - no title (we have category above)
	if(name!="")	the_title='<strong>'+name+'</strong><br>';
	else			the_title='';
	
	//prices
	
	var html = '<div style="width:160px; height:290px; position:relative;"><div style="margin-bottom:4px; padding-bottom:4px;">'+the_cat+'</div><div style="clear:both;">'+the_image+''+the_title+'<small>'+address+''+the_prices+'</small><div style="position:absolute; bottom:4px; left:0px;"><a href="/'+lang_lang+'/advert/'+id_advert+'" target="_blank">'+lang_more_info+'</a></div></div><div style="position:absolute; bottom:0px; right:0px;"><a href="javascript:remove_advert_info();" title="'+lang_close+'"><img src="/images/bt_map_close.png" alt="'+lang_close+'"></a></div></div></div>';
	
	var new_marker 	= createMarker(point,html,name);
	map.addOverlay(new_marker);
	
}

function create_icon(type){
	//alert(type);
	// marker = new GMarker(point,opt) 
	icon = new GIcon(baseIcon);
	icon.image = marker_array[type];
	icon.iconSize = new GSize(20,23);
	icon.iconAnchor = new GPoint(10, 23);
	return icon;
}

//	map markers
function createMarker(point,html,title) {
	icon=create_icon("normal");

	//icon.shadowSize = new GSize(25,20);
	var marker = new GMarker(point, {"icon": icon,"title" :title}); 
	/*
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});
	*/
	GEvent.addListener(marker, "click", function(){
		//	add side panel
		show_panel(html); 
		
		//	mark previously visited markers as seen
		for (i=0; i< markers_visted.length; i++ ) {
    		markers_visted[i].setImage(marker_array["seen"]);
 		}
		//	add marker to array of seen markers
		markers_visted.push(marker);
		
		//	change marker to active
		marker.setImage(marker_array["active"]);
	});
	return marker;
}


//	show side panel (mootools)
function show_panel(contents){
	remove_advert_info();
	var element = new Element('div', {  
		'id':'map_advert_info',
		'class': 'info_box',  
		'html': contents 
	}).inject('search_map','bottom');  
		
}
//	remove side panel
function remove_advert_info(){
	if ($('map_advert_info')){
		$('map_advert_info').dispose();
	}
}

//	get geo position (lat & lng) according to inf sent
//	add markers if defined
function get_geo(val,req_type,zoom_level,get_adverts,place_marker){
	var req = new Request({
		method: 'get',
		url: '/includes/ajax/mootools_geo.ajax.php',
		data: {'val':val,'type':''+req_type+'','lang':''+lang_lang+''},
		onRequest: function() { 
			//	do something here?
			
		},
		onComplete: function(response) {
			//alert(response);
			if(response!='KO'){
				//	reload map - is centering it enough????
				var geo_bits=response.split("~"); 
				point=new GLatLng(geo_bits[0],geo_bits[1]);
				//map.panTo(point);
				
				map.setCenter(point, zoom_level);
				if(get_adverts==1){
					//	only get adverts if defined
					user_move_map();
				}
				if(place_marker==1){
					icon = new GIcon(baseIcon);
					icon.image = marker_array["normal"];
					icon.iconSize = new GSize(20,23);
					icon.iconAnchor = new GPoint(10, 23);
					//icon.title = "su anuncio....";
					//icon.shadowSize = new GSize(25,20);
					var marker = new GMarker(point, {"icon": icon,"title" :"su anuncio....","draggable": true}); 
					map.addOverlay(marker); 
					//alert(marker.getPoint().lat());
					document.getElementById("lat").value = marker.getPoint().lat();
					document.getElementById("lng").value = marker.getPoint().lng();

					GEvent.addListener(marker, "dragend", function() {
						document.getElementById("lat").value = marker.getPoint().lat();
						document.getElementById("lng").value = marker.getPoint().lng();
					});
				}
			}
		}
	}).send();
}



