/**
 * @author matthias wilhelm / mindconnect
 */

 var lang=new Array()

lang["getDirections"]="Route Finder";
lang["zipCode"]="Zip Code";
lang["streetAddress"]="Street Address";
lang["city"]="City";
lang["country"]="Country";
lang["errNoDirectionResult"]="The address you've entered could not be found, please try again.";
lang["getDirectionToHere"]="Get directions To here";
lang["fillInAllFields"]="Please fill in all fields";

function getLanguage()
{
	var meta=document.getElementsByTagName('meta');
	for(var x=0;x<meta.length;x++)
	{
		if( meta[x].httpEquiv=="content-language" )  return  meta[x].content;
	}
}


if(getLanguage()=="de")
{
	lang["getDirections"]="Routenplaner";
	lang["zipCode"]="PLZ";
	lang["streetAddress"]="Strasse";
	lang["city"]="Ort";
	lang["country"]="Land";
	lang["errNoDirectionResult"]="Die Adresse, die Sie eingegeben haben, wurde nicht gefunden, bitte probieren Sie es nochmal! ";
	lang["getDirectionToHere"]="Get directions To here";
	lang["fillInAllFields"]="Bitte fuellen Sie alle Felder aus";
}


function googleMap(mapID,directionID)
{
	this.mapDiv=document.getElementById(mapID);
	if(directionID) this.dirDiv=document.getElementById(directionID);
	this.geocoder=new GClientGeocoder();
	
	this.mapObj;
	
	this.initMap=function()
	{
	   this.addVML();
	   this.mapObj = new GMap2(this.mapDiv);
       this.mapObj.addControl(new GLargeMapControl());
       this.mapObj.addControl(new GMapTypeControl());
       this.mapObj.addControl(new GOverviewMapControl());
	}
	
	this.setMarkerImg=function(img_src,opt,shadow_src,shadow_opt,type)
	{
		if(type==2)
		{
			this.gIconLager = new GIcon();
			this.gIconLager = new GIcon();
	        this.gIconLager.image = img_src;
	        this.gIconLager.iconAnchor = new GPoint(opt.ax,opt.ay);
	        this.gIconLager.iconSize = new GSize(opt.w,opt.h);
	        if(shadow_src)
			{
				this.gIconLager.shadow = shadow_src;
	        	this.gIconLager.shadowSize = new GSize(shadow_opt.w, shadow_opt.h);
			}
			
		}
		else
		{
			this.gIcon = new GIcon();
	        this.gIcon.image = img_src;
	        this.gIcon.iconAnchor = new GPoint(opt.ax,opt.ay);
	        this.gIcon.iconSize = new GSize(opt.w,opt.h);
	        if(shadow_src)
			{
				this.gIcon.shadow = shadow_src;
	        	this.gIcon.shadowSize = new GSize(shadow_opt.w, shadow_opt.h);
			}
		}
		
		
		
	}
	
	this.showMarker=function(addrString,latitude,longitude,type)
	{
	   var parentNode=this;
	   
	   if( latitude && longitude )
	   {
			 this.marker=new GLatLng(latitude,longitude);	   	
			 this.showMarkerByObj( this.marker,type);
	   }
	   else if(addrString)
	   {
			this.geocoder.getLatLng(addrString,function(point){ parentNode.marker=point;parentNode.showMarkerByObj(point,type); });
	   }
	 }
	 
	this.showMarkerByObj=function(lnglat,type)
	{
	   this.branch=lnglat;
	   
	   if(typeof lnglat =="object")
	   {
	   	  	this.mapObj.setCenter(lnglat, 14);
			var opt={  };
			if(type==2 && this.gIconLager) opt.icon=this.gIconLager;
			else if(this.gIcon) opt.icon=this.gIcon;
	   		
			var marker = new GMarker(lnglat,opt);
			
       		this.mapObj.addOverlay(marker);
	   }
	 }
	this.createDirectionDiv=function()
	 {
		if(typeof this.dirDiv != "object")
		{
			this.dirDiv=document.createElement('div');
			this.dirDiv.id="directions";
			this.mapDiv.parentNode.appendChild(this.dirDiv);
			
		}
	 }
	 
	this.showDirMsg=function(msg)
	{
		this.dirMsg=document.getElementById('googleDirMsg');
		
		if(msg=="")
		{
			this.dirMsg.style.display="none";
		}
		else
		{
			if(this.dirMsg.childNodes.length )
			{
				this.dirMsg.removeChild(this.dirMsg.childNodes[0]);
			}
			this.dirMsg.appendChild(document.createTextNode(msg));
			this.dirMsg.style.display="block";
		}
		
	}
	
	this.startDirSearch=function()
	{
				var address=document.getElementById('input_streetAddress').value;
				var zipCode=document.getElementById('input_zipCode').value;
				var city=document.getElementById('input_city').value;
				var country=document.getElementById('field_country').value;
				
				var routeTypeField=document.forms["gMaps"].elements["route"];
				
				var lat=document.getElementById('lat').value;
				var lng=document.getElementById('long').value;
				
				if(lat && lang && 1==0)
				{
					start=lat+","+lang;
				}
				else
				{
					var start=address+" , ";
					start+=zipCode;
					start+="  ";
					start+=city;
					start+="  ";
					start+=country;
				}
					
				var checkAddress=true;
				
					var latLager=document.getElementById('latLager');
					var lngLager=document.getElementById('longLager');
					
					if(latLager && latLager.value && lngLager && lngLager.value && 1==0)
					{
						lagerAddr=latLager.value+","+lngLager.value;
					}
					else if(document.getElementById('lagerAddress')) 
					{
						lagerAddr=document.getElementById('lagerAddress').value;
					}
				
				
				if( routeTypeField && routeTypeField[1].checked)
				{
					target=lagerAddr;
				}
				else if(routeTypeField && routeTypeField[2].checked)
				{
					start=document.getElementById('address').value;	
					target=lagerAddr;	
					checkAddress=false;
				}
				else
				{
					target=document.getElementById('address').value;		
				}
				
				if(!address && !zipCode && !city && checkAddress )
				{
					this.showDirMsg(lang["fillInAllFields"]);
				}
				else
				{
					this.showDirMsg("");
					this.getRouteFrom(start,target);
				}
	}
	
	
	this.showDirSearch=function(show)
	{
		/*if(!this.dirSearch)
		{
			this.dirSearch=document.createElement('div');
			var btn=document.getElementById('googleDirSubmit'); 
			
			var me=this;
			
			btn.onclick = function(){
			
			me.startDirSearch();
			
			}
			
		}*/
		
	}
	
	this.buildDirSearchInputField=function(varname,label)
	{
		var field=document.createElement('input');
		field.id="input_"+varname;
		var html=document.createElement('div');
		var labelfield=document.createElement('label');
		labelfield.htmlFor=field.id;
		labelfield.appendChild(document.createTextNode(label+":"));
		html.appendChild(labelfield);
		html.appendChild(field);
		
		return {field:field,html:html}
	}
	
	 this.getRouteFrom=function(from,to)
	 {
	 	this.showDirSearch(true);
		
		var me=this;
	
			//this.createDirectionDiv();
			this.dirDiv=document.getElementById("directions_1");
			
			if(!this.gdir)
			{
				this.gdir = new GDirections(this.mapObj, document.getElementById('directions_1'));
				GEvent.addListener(this.gdir, "load", function(){ me.onGDirectionsLoad();});
		   	    GEvent.addListener(this.gdir, "error",function(){ me.handleErrors();}  );
			}
			
			
			if(typeof to =="object")
			{
				this.gdir.load("from: "+from+" to: "+to.lat()+","+  to.lng(),{ "locale": "de" });
			}
			else
			{
				
				this.gdir.load("from: "+from+" to: "+to,{ "locale": "de" });
			}
		
	 }
	 
	 this.onGDirectionsLoad=function()
	 { 
      // Use this function to access information about the latest load()
      // results.
		
		if(!document.getElementById('getStatus'))
		{
			var dir=document.createElement('div');
			dir.id="getStatus";
			document.body.appendChild(dir);
		}
		document.getElementById("getStatus").innerHTML = this.gdir.getStatus().code;
	 }
	 
	 this.handleErrors=function()
	 {
		 this.showDirMsg(lang["errNoDirectionResult"]);
		 return;
		 
		 if (this.gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     this.showDirMsg("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: " + this.gdir.getStatus().code);
	   else if (this.gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     this.showDirMsg("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + this.gdir.getStatus().code);
	   
	   else if (this.gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     this.showDirMsg("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 directions requests, this means that no query was specified in the input.\n Error code: " + this.gdir.getStatus().code);

	//   else if (this.gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     this.showDirMsg("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + this.gdir.getStatus().code);
	     
	   else if (this.gdir.getStatus().code == G_GEO_BAD_KEY)
	     this.showDirMsg("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + this.gdir.getStatus().code);

	   else if (this.gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     this.showDirMsg("A directions request could not be successfully parsed.\n Error code: " + this.gdir.getStatus().code);
	    
	   else this.showDirMsg("An unknown error occurred."+ this.gdir.getStatus().code);
	 }
	 
	 this.addVML=function()
	{
	        if (!document.namespaces)
	                return;
	
	        for(var i =0; i< document.namespaces.length; i++)
	        {
	                if (document.namespaces(i).name=='v' )  return;
	                       
	        }
	        document.namespaces.add('v', 'urn:schemas-microsoft-com:vml');
	} 
	 
	 this.resize=function(height,width)
	 {
		if(height)this.mapDiv.style.height=height+"px";
		if(width)this.mapDiv.style.width=width+"px";
		this.mapObj.checkResize();
	 	this.mapObj.panTo(this.marker);
	 }
	 
	 this.showMarkerByType=function(type)
	 {
	 	if(type==2 && document.getElementById('lagerAddress') )
		{
			var lagerAddress=document.getElementById('lagerAddress').value;
			
			var latLager=document.getElementById('latLager').value;
			var lngLager=document.getElementById('longLager').value;
			
			map.showMarker(lagerAddress,latLager,lngLager,2);
		}
		else
		{
			var addr=document.getElementById('address').value;
			var lat=document.getElementById('lat').value;
			var lng=document.getElementById('long').value;
			map.showMarker(addr,lat,lng,1);
		}
	 }
}

var map;
var gdir;


window.onload=function()
{
	var addr=document.getElementById('address').value;
	var lat=document.getElementById('lat').value;
	var lng=document.getElementById('long').value;
	if(document.getElementById('lagerAddress')) 
	{
		var lagerAddress=document.getElementById('lagerAddress').value;
		var latLager=document.getElementById('latLager').value;
		var lngLager=document.getElementById('longLager').value;
	}
	
	if(addr || (lat && lng) )
	{
		map=new googleMap('gMap','');
		map.initMap();
	    map.setMarkerImg("http://www.leiner.at/img/V3/google_marker.png",{w:104,h:77,ax:28,ay:77},"http://www.leiner.at/img/V3/google_marker_shadow.png",{w:104,h:77},1 );
		map.setMarkerImg("http://www.leiner.at/img/V3/google_marker_lager.png",{w:104,h:77,ax:28,ay:77},"http://www.leiner.at/img/V3/google_marker_shadow.png",{w:104,h:77},2 );
		map.showMarker(addr,lat,lng);
		map.showDirSearch(true);
	}
}

window.onunload=GUnload;



