/***** Details section *****/
// Translations of popup window in Map
var vTo;
var vFrom;
var vDirection;
var vGo;
var vMessage="";;
var vLocation;
var map;
var smallControl;
var TypeControl;
var closeControl;
var address1;
var address2;
var address3;
var toAddress;
var address;
var marker;
var mapSizeG = 0;
var geocoder;

function translate(langType)
{
	if(langType=="de" || langType=="en" || langType=="it" || langType=="fr"){
			if(langType=="de"){
				vTo="Nach";
				vFrom="Von";
				vDirection="Route berechnen!";
				vGo="Los";
				vLocation="Strasse, Stadt";
			}
			  if(langType=="it"){
				vTo="Per";
				vFrom="Da";
				vDirection="Ottieni indicazioni!";
				vGo="Vai";
				vLocation="Via, Dove";
			}
				if(langType=="fr"){
				vTo="Par";
				vFrom="D'";
				vDirection="Description de chemins!";
				vGo="Aller";
				vLocation="Rue, Ville";
			}
		  if(langType=="en"){
				vTo="To";
				vFrom="From";
				vDirection="Get Directions!";
				vGo="Go";
				vLocation="Street, City";
			 }
	 }else{
				vTo="To";
				vFrom="From";
				vDirection="Get Directions!";
				vGo="Go";
				vLocation="Street, City";
	 }

}

function translateError(langType){
	if(langType=="de" || langType=="en" || langType=="it" || langType=="fr"){
			if(langType=="de"){
				vMessage="Bitte Ihren Standort angeben";
			}
			  if(langType=="it"){
				vMessage="Specificare la propria posizione";
			}
				if(langType=="fr"){
				vMessage="Pr&#233;cisez votre emplacement";
			}
		  if(langType=="en"){
				vMessage="Please, specify your location";
			 }
	 }else{
				vMessage="Please, specify your location";
	 }
}
// Get Directions block
	var map1;
	var directionsPanel;
    var directions;
    var addressMarker;
	var localLang= gup('lang') != "" ? gup('lang') : "de";
	translate(localLang);

	 // Get Directions call.
    function initialize() {
		var shortFrom=document.getElementById("Fromaddress").value;
		
		if((shortFrom!=vLocation) && (shortFrom!="")){
			var fromAddress=document.getElementById("Fromaddress").value;
			var toAddress=document.getElementById("Toaddress").value;
			map1 = new GMap2(document.getElementById("cg_map"));
			map1.addControl(smallControl);
			map1.addControl(typeControl);
			
			addCloseButton(map1);
			directionsPanel = document.getElementById("route");
			directions = new GDirections(map1, directionsPanel);
			GEvent.addListener(directions, "load", onGDirectionsLoad);
	    	GEvent.addListener(directions, "error", handleErrors);
			setDirections(fromAddress, toAddress, localLang );
	 	}
	 	else {
			translateError(localLang); // set error message
			loadMap("","","");
	 	}
    }

  	function setDirections(fromAddress, toAddress, locale) {
		var url = 'ajax/savemap';
	
		new Ajax.Request(url, {
			method: 'post',
			parameters: {frommap: fromAddress, tomap: toAddress, localemap: locale},		
			onSuccess: function(transport) {
				 directions.load("from: " + fromAddress + " to: " + toAddress,
	      		{ "locale": locale });
			}
		});
	     
    }
    

   function handleErrors(){
  	loadMap('','','','',true);
   	if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
    	alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + directions.getStatus().code);
   	else if (directions.getStatus().code == G_GEO_SERVER_ERROR)
    	alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + directions.getStatus().code);
   	else if (directions.getStatus().code == G_GEO_MISSING_QUERY)
    	alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For direction requests, this means that no query was specified in the input.\n Error code: " + directions.getStatus().code);
   	else if (directions.getStatus().code == G_GEO_BAD_KEY)
    	alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directions.getStatus().code);
   	else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
    	alert("A direction request could not be successfully parsed.\n Error code: " + directions.getStatus().code);
   	else 
   		alert("An unknown error occurred.");
   
}

function onGDirectionsLoad(){ 
      // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = directions.getStatus().code;
  // and yada yada yada...

}

	// Below is standard map, pointing to client destination
    function loadMap(info1,info2,info3,route,error) {
		
		if(info1!='')
			address1 = info1;
		else
			info1 = address1;
		if(info2!='')
			address2 = info2;
		else
			info2 = address2;
		if(info3!='')	
			address3 = info3;
		else
			info3 = address3;
			
		var errorInfo=info1; // catch error messages for users that does no enter street, city for the route calculation. value is initially null.
      	
      	if (GBrowserIsCompatible()) {
      		
        	map = new GMap2(document.getElementById("cg_map"));
        	
			
			// translate address to geocode
			geocoder = new GClientGeocoder();
		
			if (route == true) {
				map.addControl(new GSmallMapControl());
				map.addControl(new GMapTypeControl());
			}
			
			if (error == true) {
			
				resizeGMap(1);
				//resetButtons(map);
				/*
				smallControl = new GSmallMapControl();
				typeControl =  new GMapTypeControl();
			
				map.addControl(smallControl);
				map.addControl(typeControl);
				addCloseButton(map);
				*/
			}
			
			if(info1=='')
				address = info2 + ", " + info3;
			else
				address = info1 + ", " + info2 + ", " + info3;
				
			toAddress = info1 + ", " + info2 + ", " + info3; 
				//This address is used on info window to display the location of the client. street, city is used such that street, city could be entered also in from field
			  	if (geocoder) {
					geocoder.getLatLng(
						address,
					  	function(point) {
							if (point) {
						  		map.setCenter(point, 15);
						  		marker = new GMarker(point);
						  		map.addOverlay(marker);
						  		GEvent.addListener(marker, "click", function() {	  			
						        	marker.openInfoWindowHtml("<form action='javascript:initialize();'><table class='small'><tr><td><b>"+vDirection+"</b></td></tr> <tr><td><b>"+vTo+":</b> "+toAddress+"</td></tr><tr><td><b>"+vFrom+": </b><input type='hidden' name='Toaddress' id='Toaddress' value='"+address+"'><input type='text'  name='Fromaddress' id='Fromaddress' value='"+vLocation+"'><input type='submit' value='"+vGo+"'></td></tr><tr><td><font color='red'>"+vMessage+"</font></td></tr></table> </form>");
						        	resizeGMap(1);
						        });
						  		
						  		
							} else {
							
								address = info2 + ", " + info3;
								
								geocoder.getLatLng(
									address,
								  	function(point) {
										if (point) {
									  		map.setCenter(point, 15);
									  		marker = new GMarker(point);
									  		map.addOverlay(marker);
									  		GEvent.addListener(marker, "click", function() {	  			
									        	marker.openInfoWindowHtml("<form action='javascript:initialize();'><table class='small'><tr><td><b>"+vDirection+"</b></td></tr> <tr><td><b>"+vTo+":</b> "+toAddress+"</td></tr><tr><td><b>"+vFrom+": </b><input type='hidden' name='Toaddress' id='Toaddress' value='"+address+"'><input type='text'  name='Fromaddress' id='Fromaddress' value='"+vLocation+"'><input type='submit' value='"+vGo+"'></td></tr><tr><td><font color='red'>"+vMessage+"</font></td></tr></table> </form>");
									        	resizeGMap(1);
									        });
									  		
									  		
										} else {
											if(document.getElementById("cg_map"))
												document.getElementById("cg_map").style.display = "none";
										}
								  	}
								);
								
							}
					  	}
					);
				}
	      }
	      
    }
    
    function resizeGMap(mapSize) {
		container = document.getElementById('cg_map');
		
		mapSizeG = mapSize;
		/* Set size 
			1 = small
			2 = large */
		if (mapSize == 1) {
			mapWidth = 536;
			mapHeight = 420;
			// enable mouse scrolling
			map.enableScrollWheelZoom();
		}
		else {
			mapWidth = 306;
			mapHeight = 165;
			map.disableScrollWheelZoom();
		}
		
		container.style.width = mapWidth + 'px';
		container.style.height = mapHeight + 'px';
		
		if (document.getElementById('detail_view')){
			var h1 = $('detail_view').getStyle('height').replace(/px/, "");
			var h2 = $('media_container').getStyle('height').replace(/px/, "");
			var myheight = parseInt(h1) + parseInt(h2);
			
			$('box_content').setStyle({ height: myheight });
			
			map.checkResize();
		}
		
		smallControl = false;
		typeControl = false;
		if (mapSize == 1) {
			
			// Add controls
			smallControl = new GSmallMapControl();
			typeControl =  new GMapTypeControl();
			
			
			map.addControl(smallControl);
			map.addControl(typeControl);
			
			// Add close button
			addCloseButton(map);
			
		}
		
		if (mapSize == 1) {
			GEvent.addListener(marker, "click", function() {
	        	marker.openInfoWindowHtml("<form action='javascript:initialize();'><table class='small'><tr><td><b>"+vDirection+"</b></td></tr> <tr><td><b>"+vTo+":</b> "+toAddress+"</td></tr><tr><td><b>"+vFrom+": </b><input type='hidden' name='Toaddress' id='Toaddress' value='"+address+"'><input type='text'  name='Fromaddress' id='Fromaddress' value='"+vLocation+"'><input type='submit' value='"+vGo+"'></td></tr><tr><td><font color='red'>"+vMessage+"</font></td></tr></table> </form>");
	        });
		
		}
	}
	
	function addCloseButton(map) {
		function closeButtonControl() {
		}
		
		closeButtonControl.prototype = new GControl();
		closeButtonControl.prototype.initialize = function(map) {
			
			var container = document.createElement("div");
			
			var zoomInDiv = document.createElement("div");
			zoomInDiv.setAttribute('id', 'closeButton');
			this.setButtonStyle_(zoomInDiv);
			container.appendChild(zoomInDiv);
			zoomInDiv.appendChild(document.createTextNode("Close"));
			GEvent.addDomListener(zoomInDiv, "click", function() {
				resetButtons(map);
			});
							
			map.getContainer().appendChild(container);
			return container;
		}
		
		closeButtonControl.prototype.getDefaultPosition = function() {
			return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 28));
		}
			
		// Sets the proper CSS for the given button element.
		closeButtonControl.prototype.setButtonStyle_ = function(button) {
		
			/*
			button.style.textDecoration = "none";
			button.style.color = "black";
			button.style.backgroundColor = "white";
			button.style.font = "arial";
			button.style.fontWeight = "bold";
			button.style.border = "1px solid black";
			button.style.padding = "2px";
			button.style.marginTop = "20px";
			button.style.textAlign = "center";
			button.style.width = "6em";
			button.style.cursor = "pointer";
			
			*/
			  button.style.textDecoration = "none";
			  button.style.color = "#000000";
			  button.style.backgroundColor = "white";
			  button.style.font = "small Arial";
			  button.style.border = "1px solid black";
			  button.style.padding = "1px";
			  //button.style.marginBottom = "3px";
			  button.style.textAlign = "center";
			  button.style.width = "4.7em";
			  button.style.height = "1.2em";
			  button.style.cursor = "pointer";
		}
		closeControl = map.addControl(new closeButtonControl());
		
	}
	
	
	function resetButtons(map) {
		
		//alert(directions);
		if (directions != undefined)
			directions.clear();
		resizeGMap(2);
		
		if (geocoder) {
			geocoder.getLatLng(
				address,
			  	function(point) {
					if (point) {
				  		map.setCenter(point, 15);
				  		marker = new GMarker(point);
				  		map.addOverlay(marker);
					}
			  	}
			);
		}
			
		document.getElementById('route').innerHTML = '';
		map.removeControl(smallControl);
		map.removeControl(typeControl);
		document.getElementById('closeButton').parentNode.removeChild(document.getElementById('closeButton'));
		
	}
    
    
    function checkResize (resize) {
    	
    	if (mapSizeG != 1){
			resizeGMap(resize);
    	}
    	
    }
/***** Details section END *****/



