/**
 * @author Ged
 */

var column = new Array();
var column_num = 0;
var location_initialize = true;
var init_locs = [98, 0, 0];
var types = ['country', 'state', 'city'];

function process_location(field, field_id)
{
	field = field + 1;
	column_num = field;
	
	if(column_num < 3)
	{
		empty_locations(column_num);
		
		add_option('0|Loading...');

		var url = '/phplib/mapfunctions.php?func=getList&args[]='+types[column_num]+'&args[]='+field_id;
		GDownloadUrl(url, function(data, responseCode)
				{
					if(responseCode == 200)
						fill_options(data);
					else if(responseCode == -1)
				    	alert("Data request timed out. Please try later.");
				  	else
				    	alert("Request resulted in error. Check file is retrievable.");						
				}
		);
		return;
	}
	
	if(typeof(map) != 'undefined' && map) update_map();
}

function fill_options(x)
{
	empty_locations(column_num);
	
	var dataSet = x.split('#');
	
	for(i = 0; i < dataSet.length; i++)
	{
		if(dataSet[i] == '') continue;
		add_option(dataSet[i]);
	}
	
	var id = 0;
	if(location_initialize)
	{
		if(id = init_locs[column_num])
		{
			select_item(column_num, id);
			
			if(++column_num <= 2) {
				add_option('0|Loading...');
				
				var url = '/phplib/mapfunctions.php?func=getList&args[]='+types[column_num]+'&args[]='+id;
				GDownloadUrl(url, function(data, responseCode)
						{
							if(responseCode == 200)
								fill_options(data);
							else if(responseCode == -1)
						    	alert("Data request timed out. Please try later.");
						  	else
						    	alert("Request resulted in error. Check file is retrievable.");						
						}
				);
				return;
			}
		}
		location_initialize = false;
	}
	
	if(typeof(map) != 'undefined' && map) update_map();
}

function add_option(data)
{
	pair = data.split('|');
	myEle = document.createElement('option');
	myEle.value = pair[0];
	myEle.text = pair[1];
	
	with(column[column_num])
	{
		try {add(myEle);}     // this will work for IE, Gecko will throw an Exception...
		catch(ex) {add(myEle, null);}     // ... catch it and do it the right way
	}
}

function empty_locations(cn)
{
	while(cn <= 2) column[cn++].length = 0;
}

function select_item(cn, item_id)
{
	with(column[cn])
	{
		var i = 0;
		if(item_id)
		{
			for(i = 0; i < length; i++)
			{
				if(options[i].value == item_id) break;
			}
			if(i == length) i = 0;
		}
		options[i].selected = true;
	}
}

//================================== Map function ===========================

var map = null;
var mgr = null;
var icon = null;

function init()
{
	with(document)
	{
		column[0] = getElementById('SEARCHcountry_id');
		column[1] = getElementById('SEARCHstate_id');
		column[2] = getElementById('SEARCHcity_id');
	}
	
	if (GBrowserIsCompatible())
		initMap();
}

function initMap()
{
	icon = new GIcon();
	icon.image = "images-matelas/carte/icon_simmons.png";
	icon.iconSize = new GSize(22, 30);
	icon.iconAnchor = new GPoint(11, 30);
	icon.infoWindowAnchor = new GPoint(5, 1);
   
    map = new GMap2(document.getElementById("map"));
 	map.enableContinuousZoom();
	map.addControl(new GSmallZoomControl());
	map.enableScrollWheelZoom();
	
	map.setCenter(new GLatLng(0,0));
	
	mgr = new MarkerManager(map, {trackMarkers: true});

	GEvent.addListener(map,"click", function(overlay, latlng)
	{     
  	 	if (overlay)
      	{ 
  	 		
  	 		if (overlay.infoTab)
				overlay.openInfoWindowTabsHtml(overlay.infoTab);
  	 		/*
  	 		
  	 		if (overlay.html)
				overlay.openInfoWindowTHtml(overlay.html);*/
  		}
  	});
 
	process_location(-1, 0);
}

function createMarker (point, title, html, infoT)
{
	var marker = new GMarker(point, {title: title, icon:icon});
	marker.infoTab = infoT;
	marker.html = html;

	return marker;
}

function getRetailer (state_id)
{
	mgr.clearMarkers();

	GDownloadUrl("/phplib/mapfunctions.php?func=getRetailers&args[]="+state_id, function(data, responseCode)
    	{
			if(responseCode == 200)
			{
    			var infoTabs;
    			var point;
    			var xml = GXml.parse(data);

   				var markers = xml.documentElement.getElementsByTagName("marker");
   			 	var allMarkers = [];
   			 	var list_distr = "<p>Vous trouverez ci-dessous la liste complète de nos distributeurs correspondante à votre recherche :</p>\n";
				 
   			 	
    			for (var i = 0; i < markers.length; i++)
        		{
    				
    				if(parseFloat(markers.item(i).getAttribute("lat")) + parseFloat(markers.item(i).getAttribute("lng")) > 0)
    				{
	    				var html = "<span class='titleMarker'>"+markers.item(i).getAttribute("title")+"</span><br/><br/><span class='descMarker'>"+markers[i].getElementsByTagName("address").item(0).firstChild.nodeValue+"</span>";
	    				
	    				infoTabs = [
	    					    new GInfoWindowTab("Adresse", "<span class='descMarker'>"+markers[i].getElementsByTagName("address").item(0).firstChild.nodeValue+"</span>"),
	    					    new GInfoWindowTab("Contact", "<span class='descMarker'>"+markers[i].getElementsByTagName("contact").item(0).firstChild.nodeValue+"</span>")
	    					    ];
			    		
	      				point = new GLatLng(parseFloat(markers.item(i).getAttribute("lat")), parseFloat(markers.item(i).getAttribute("lng")));
	      		
	      				allMarkers.push( createMarker(point, markers.item(i).getAttribute("title"), html, infoTabs) );
    				}
    				//else
    				list_distr += addDistr(markers.item(i).getAttribute("title"), markers[i]);
    			}
    			
    			document.getElementById('list').innerHTML = list_distr;
    			
    			mgr.addMarkers(allMarkers, 9, 17);
    			mgr.refresh();
			}
			else if(responseCode == -1)
		    	alert("Data request timed out. Please try later.");
		  	else
		    	alert("Request resulted in error. Check file is retrievable.");
		}
	);
}

function update_map()
{
	if (map)
	{
		var params = '';
		var country_id = 0, state_id = 0, city_id = 0;

		with (document)
		{
			country_id = getElementById("SEARCHcountry_id").value;

			if (country_id > 0)
			{
				params = 'args[]=' + country_id;
				state_id = getElementById("SEARCHstate_id").value;
				
				if (state_id > 0)
				{
					params = 'args[]=' + state_id;
					city_id = getElementById("SEARCHcity_id").value;
					
					if (city_id > 0)
					{
						params = 'args[]=' + city_id;
					}
					else
						getRetailer (state_id);
				}
				else
					clean_list();
			}
		}

		if (country_id > 0)
		{
			GDownloadUrl("/phplib/mapfunctions.php?func=getLocation&"+params, function(data, responseCode)
		   	    	{
						if(responseCode == 200)
						{
							var xml = GXml.parse(data);
							
							var location = xml.documentElement.getElementsByTagName("location");
							
							var point = new GLatLng(parseFloat(location.item(0).getAttribute("lat")), parseFloat(location.item(0).getAttribute("lng")));
							var zoom = parseInt(location.item(0).getAttribute("zoom"));
							
							if(zoom > 0)
								map.setCenter(point, zoom);
							else if (city_id > 0)
								map.setCenter(point, 12);
							else if (state_id > 0)
								map.setCenter(point, 9);
							else if (country_id > 0)
								map.setCenter(point, 5);
						}
						else if(responseCode == -1)
					    	alert("Data request timed out. Please try later.");
					  	else
					    	alert("Request resulted in error. Check file is retrievable.");	
		   	    	}
			);
		}
		else
			map.setCenter(new GLatLng(48.835152, 12.471800), 4);
	}
}

function addDistr(name, marker)
{
	var desc = "<div class='distrib'>\n";
	desc += "<h3>"+name+"</h3>\n";
	desc += "<p>"+marker.getElementsByTagName("address").item(0).firstChild.nodeValue+"</p>\n";
	desc += "<p>"+marker.getElementsByTagName("contact").item(0).firstChild.nodeValue+"</p>\n";
	desc += "</div>\n\n";
	
	return desc;
}

function clean_list()
{
	document.getElementById('list').innerHTML = "";
}

