(function($) {
	$.googlemaps = {
            newLang: false,
			url : "?",
			isSuperAdmin : false,
			lat: 0,
			lang: 0,
			preview_status: false,
			MapID: false,
			name: false,
			local: "",
			street: "",
			city: "",
			zip: "",
			phone: "",
			fax: "",
			gsm: "",
			mail: "",
			lat: "",
			long: "",
			country: "",
			imgPath: "",
			css: "",
			earth: "",
			road: "",
			controls: "",
			overview: "",
			type: "",
			info: "",
			zoom: "",
			scale: "",
            scriptPath: "/js/modules/googlemaps/setData.js",
			params: new Array("name","street","city","country","zip","phone","fax","gsm","mail","lat","long","width","height"),
			paramsSelect: new Array("earth","road","controls","overview","type","info","zoom","scale"),
			
			setValues: function()
			{
				var frame=$(".map_values");
				for(key in this.params)
				{
					if(this.params[key]=="mail")
						var elem=data.email;
					else
                    {
                        var code=("var elem=data."+this.params[key]+";");
                        eval(code);
                    }
					var inp="<input id='G"+this.params[key]+"' value='"+escape(elem)+"' type='input'/>";
					$(frame).append(inp);
				}
				for(key in data.params)
				{
					var label=data.params[key].label;
					if(label=="MapType")
						inpId="type";
					else
						inpId=label.toLowerCase();
					
					var inp="<input id='G"+inpId+"' value='"+data.params[key].value+"' type='input'/>";
					$(frame).append(inp);
				}
                
				this.getValues();
				$.googlemaps.preview_status=true;
				load();
			},
			
			getValues: function()
			{
				for(key in this.params)
				{
					code=' this.'+this.params[key]+'=$("#G'+this.params[key]+'").val(); ';
					eval(code);
				}
				for(key in this.paramsSelect)
				{
					code=' this.'+this.paramsSelect[key]+'=$("#G'+this.paramsSelect[key]+'").val(); ';
                    eval(code);
					eval(code);
				}
				$.googlemaps.lang=$.googlemaps.long;

			},
			setInfoContent: function()
			{
				var html="<div id='infoDIV' style='text-align: left;'>";
				var layout="<div style='margin:2px; overflow: hidden;'>xxxContentxxx</div>";
				var first_bloque=true;
				var second_bloque=true;
				for(key in this.params)
				{
                    
					if(this.params[key]=="width" || this.params[key]=="height" || this.params[key]=="zip")
						continue;
					var content=eval("this."+this.params[key]);
					if(content && content!="null" && this.params[key]=="name")
						content="<strong>"+unescape(content)+"</strong><br/><br/>";
                    else if(this.params[key]=="city")
                    {
                        textValue="";
                        if(this.zip && this.zip!="null")
                            textValue+=this.zip;
                        if(content && content!="null")
                            textValue+=" "+content;
                        content=textValue;                        
                    }
					else if(content && content!="null" && (this.params[key]=="phone" || this.params[key]=="mail" || this.params[key]=="fax" || this.params[key]=="gsm"))
					{
                        if(this.params[key]=="mail")
                            content="<div  class='"+this.params[key]+"' border=0 align=absmiddle />&nbsp;</div>&nbsp;&nbsp;<a href='mailto:"+content+"'>"+content+"</a>";
                        else     
                            content="<div class='"+this.params[key]+"' border=0 align=absmiddle >&nbsp;</div>&nbsp;&nbsp;"+content;

						if(first_bloque)
						{
							first_bloque=false;
							content="<br/>"+content;
						}
					}

                    if(content && content!="null" && this.params[key]!="lat" && this.params[key]!="long")
					    eval(' html+=layout.replace("xxxContentxxx","'+unescape(content)+'")');
				}
				html+="</div>";
				return html;
			},
			
			initEarth: function(){
				$("#map").html("&nbsp;");
				google.earth.createInstance('map', $.googlemaps.initEarthCallBack, $.googlemaps.failureEarthCallBack); 
			},
			initEarthCallBack: function(instance){
				ge = instance; 
				ge.getWindow().setVisibility(true); 
				
				var lookAt = ge.createLookAt('');
				lookAt.setLatitude(parseFloat($.googlemaps.lat)); 
				lookAt.setLongitude(parseFloat($.googlemaps.lang)); 
				lookAt.setRange(1000.0); //default is 0.0 
				ge.getView().setAbstractView(lookAt);

				var placemark = ge.createPlacemark(''); 
				placemark.setName(unescape($.googlemaps.name));
				
				var icon = ge.createIcon(''); 
				icon.setHref(this.imgPath+"/MapAPIMarker.png"); 
				
				var style = ge.createStyle(''); //create a new style 
				style.getIconStyle().setIcon(icon); //apply the icon to the style 
				placemark.setStyleSelector(style); //apply the style to the placemark 
				
				var point = ge.createPoint(''); 
				point.setLatitude(parseFloat($.googlemaps.lat)); 
				point.setLongitude(parseFloat($.googlemaps.lang)); 
				placemark.setGeometry(point); 
				
				ge.getFeatures().appendChild(placemark);
				ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
				ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);
				ge.getLayerRoot().enableLayerById(ge.LAYER_TERRAIN, true);
				ge.getOptions().setStatusBarVisibility(true);

				ge.getNavigationControl().setVisibility(ge.VISIBILITY_SHOW);
				
			},
			
			failureEarthCallBack: function(){
				return;
			},

			loadRoad: function(){
				//$("#fromAddress").val(unescape($.googlemaps.city)+", "+unescape($.googlemaps.country));
                $("#fromStreet").val(" ");
                $("#fromCity").val(unescape($.googlemaps.city));
                $("#fromCountry").val(unescape($.googlemaps.country));
				$("#directions").html("&nbsp;");
				$('#fromAddress').css({ "font-size" :"10px","font-family":"verdana","color":"#666666","border":"1px solid #cccccc"});
				$("#locale").css({"height":"16px","font-size":"10px","font-family":"verdana","color":"#666666"});
				$("#MyButton").css({"height":"16px","font-size":"10px","font-family":"verdana","color":"#666666","border":"1px solid #cccccc"});
				$("#directions").css({"font-size":"10px","font-family":"verdana","color":"#666666","padding":"0px","text-align":"left"});
				$("#directions").css({"width":(($.googlemaps.width/2)-20)+"px","height":($.googlemaps.height-140)+"px"});
				$("#fromAddress").css({"width":(($.googlemaps.width/2)-44)+"px"});
				$("#MyFormtable").css({"width":(($.googlemaps.width/2)-20)+"px","top":(0-$.googlemaps.height-6)+"px","left":($.googlemaps.width-157)+"px"});
				$("#MyMapContainer").css({"width":($.googlemaps.width)+"px"});
				$("#MyForm").css({"width":($.googlemaps.width/2)+"px","height":($.googlemaps.height)+"px"});
				$("#map_canvas").css({"width":($.googlemaps.width)+"px","height":$.googlemaps.height+"px"});
                 
                mapDIV=$("#map");
				map = new GMap2(document.getElementById("map"));

				map.addControl(new GLargeMapControl3D());
                  
				gdir = new GDirections(map,document.getElementById("directions"));
				GEvent.addListener(gdir, "load", onGDirectionsLoad);
				GEvent.addListener(gdir, "error", handleErrors);

				setDirections(unescape($.googlemaps.city)+", "+unescape($.googlemaps.country), new GLatLng($.googlemaps.lat,$.googlemaps.lang));
			
			},
			ShowHideRoad: function()
			{
				var elem=$("#MyForm");
				var button=$("#MyFormOpener");
				var statusFrame=($(elem).css("display")!="none") ? true : false;
				
                if(this.newLang==true)
                {
                    
                    this.newLang=false;
                    this.loadRoad();  
                }
                else if(statusFrame==false)
				{
					$(elem).show();
					$(button).hide();

                    var newWidth=($.googlemaps.width/2)-20;
                    var oldWidth= $("#Gmap_content").width();
                    oldWidth=parseInt(oldWidth);
                    
                    var coef=oldWidth/100;                   
                    coef=newWidth/coef;                  
                    coef=oldWidth-oldWidth*coef/100; 
                            
                    $("#map").css("width",coef+"px");
                    this.loadRoad();         
				}
				else
				{	
                    var oldWidth= $("#Gmap_content").width();                   
                    $("#map").css("width",oldWidth);  
                    
					$(elem).hide();
                    load();
					$(button).show();
				}  	
			},
			
			getChildStyle: function()
			{
				element_current=$("#directions");
				var first_elem=$(element_current).children(" :first");
				if(typeof(first_elem)=="undefined")
					return;
				$("#element_current").css({"width":$.googlemaps.width +"px"});
			}
		}
	})(jQuery);

function setDirections(fromAddress, toAddress) {
    var lang=$.googlemaps.local;
	locale=lang.toLowerCase()+"_"+lang.toUpperCase();
    fromAddress="";
    if($("#fromStreet").val()!="")
        fromAddress+=$("#fromStreet").val()+" , ";
    if($("#fromCity").val()!="")
        fromAddress+=$("#fromCity").val()+" , ";
    if($("#fromCountry").val()!="")
        fromAddress+=$("#fromCountry").val();

	gdir.load("from: " + fromAddress + " to: " + new GLatLng($.googlemaps.lat,$.googlemaps.lang), { "locale": locale });
	$.googlemaps.getChildStyle();
}

function onGDirectionsLoad(){ 
}

function handleErrors(){
	if (gdir.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: " + gdir.getStatus().code);
	else if (gdir.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: " + gdir.getStatus().code);
	else if (gdir.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 directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	else if (gdir.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: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	else
		alert("An unknown error occurred.");
}

var MapIconMaker = {};
MapIconMaker.createMarkerIcon = function(opts) {
  var width = opts.width || 32;
  var height = opts.height || 32;
  var primaryColor = opts.primaryColor || "#ff0000";
  var strokeColor = opts.strokeColor || "#000000";
  var cornerColor = opts.cornerColor || "#ffffff";
  var baseUrl = "http://chart.apis.google.com/chart?cht=mm";
  var iconUrl = baseUrl + "&chs=" + width + "x" + height + 
	  "&chco=" + cornerColor.replace("#", "") + "," + primaryColor.replace("#", "") + "," + strokeColor.replace("#", "") + "&ext=.png";
  var icon = new GIcon(G_DEFAULT_ICON);
  icon.image = iconUrl;
  icon.iconSize = new GSize(width, height);
  icon.shadowSize = new GSize(Math.floor(width*1.6), height);
  icon.iconAnchor = new GPoint(width/2, height);
  icon.infoWindowAnchor = new GPoint(width/2, Math.floor(height/12));
  icon.printImage = iconUrl + "&chof=gif";
  icon.mozPrintImage = iconUrl + "&chf=bg,s,ECECD8" + "&chof=gif";
  var iconUrl = baseUrl + "&chs=" + width + "x" + height + 
	  "&chco=" + cornerColor.replace("#", "") + "," + primaryColor.replace("#", "") + "," + strokeColor.replace("#", "");
  icon.transparent = iconUrl + "&chf=a,s,ffffff11&ext=.png";
  icon.imageMap = [
	  width/2, height,
	  (7/16)*width, (5/8)*height,
	  (5/16)*width, (7/16)*height,
	  (7/32)*width, (5/16)*height,
	  (5/16)*width, (1/8)*height,
	  (1/2)*width, 0,
	  (11/16)*width, (1/8)*height,
	  (25/32)*width, (5/16)*height,
	  (11/16)*width, (7/16)*height,
	  (9/16)*width, (5/8)*height
  ];
  for (var i = 0; i < icon.imageMap.length; i++) {
	icon.imageMap[i] = parseInt(icon.imageMap[i]);
  }
  return icon;
}

function load() {
    
    if (GBrowserIsCompatible()) {
        if(!$.googlemaps.preview_status && !$.googlemaps.MapID)
           return;
        $("#map").html("&nbsp;");
        $("#Gmap_content").show();
        
		$("#MyForm").hide();
        $(".getInfoSize").hide();
		
        if($.googlemaps.earth=="True")
        {
        	$.googlemaps.initEarth();
        	return;
        }	
        else if($.googlemaps.road=="True")
        {
        	$.googlemaps.loadRoad();
        	return;
        }
        $(".getInfoSize").show();
        
        var map = new GMap2(document.getElementById("map"));
        if(typeof($.googlemaps.zoom)=="undefined")
            $.googlemaps.zoom=15;
		map.setCenter(new GLatLng($.googlemaps.lat,$.googlemaps.lang),parseInt($.googlemaps.zoom));
		map.enableScrollWheelZoom();
		
		if($.googlemaps.controls=="Small")
			map.addControl(new GSmallZoomControl3D());
		else
			map.addControl(new GLargeMapControl3D());
		if($.googlemaps.type=="True")
		{
			map.addControl(new GMapTypeControl());
			map.addMapType(G_PHYSICAL_MAP);
		}	
		if($.googlemaps.overview=="True")
			map.addControl(new GOverviewMapControl());

		if($.googlemaps.sacle=="True")
			map.addControl(new GScaleControl());

		if($.googlemaps.info=="Window")
			map.openInfoWindowHtml(map.getCenter(),$.googlemaps.setInfoContent()+"<div style='text-align: left' class='logoFrame''><div class='logoIMG'  >&nbsp;</div></div>");
		else if($.googlemaps.info=="Marker")
		{
			var newIcon = MapIconMaker.createMarkerIcon({ "width" : 30, "height": 30, "primaryColor": "#0000ff" });  
             
			if(isBack==1)
            {
                var marker = new GMarker(map.getCenter(), {draggable: true ,icon: newIcon });  
                GEvent.addListener(marker, "mouseup", function() { //onDblClick
                    var center = marker.getPoint();
                    center = center.toString();
                    center = center.replace("(","");
                    center = center.replace(")","");
                    center = center.replace(" ","");
                    center = center.split(",");
                    $.googlemaps.lat=center[0];
                    $.googlemaps.lang=center[1];
                    $(".latToChange", window.parent.document).val($.googlemaps.lat);
                    $(".longToChange", window.parent.document).val($.googlemaps.lang);
                });
                
                GEvent.addListener(marker, "dblclick", function() {
                    map.openInfoWindowHtml(new GLatLng($.googlemaps.lat,$.googlemaps.lang),$.googlemaps.setInfoContent()+"<div style='text-align: left' class='logoFrame'><div class='logoIMG'  >&nbsp;</div></div>");
                });    
            }
            else
            {
                var marker = new GMarker(map.getCenter(), { icon: newIcon });
                GEvent.addListener(marker, "click", function() { map.openInfoWindowHtml(new GLatLng($.googlemaps.lat,$.googlemaps.lang),$.googlemaps.setInfoContent()+"<div style='text-align: left' class='logoFrame'><div class='logoIMG'  >&nbsp;</div></div>"); });
            }
			map.addOverlay(marker);
		}	
        else
        {
            var newIcon = MapIconMaker.createMarkerIcon({ "width" : 30, "height": 30, "primaryColor": "#0000ff" });  
            if(isBack==1)
            {
                var marker = new GMarker(map.getCenter(), {draggable: true ,icon: newIcon });  
                GEvent.addListener(marker, "mouseup", function() { //onDblClick
                    var center = marker.getPoint();
                    center = center.toString();
                    center = center.replace("(","");
                    center = center.replace(")","");
                    center = center.replace(" ","");
                    center = center.split(",");
                    $.googlemaps.lat=center[0];
                    $.googlemaps.lang=center[1];
                    $(".latToChange", top.document).val($.googlemaps.lat);
                    $(".longToChange", top.document).val($.googlemaps.lang);
                });
                
                GEvent.addListener(marker, "dblclick", function() {
                    map.openInfoWindowHtml(new GLatLng($.googlemaps.lat,$.googlemaps.lang),$.googlemaps.setInfoContent()+"<div style='text-align: left' class='logoFrame'><div class='logoIMG'  >&nbsp;</div></div>");
                });    
            }
            
            else
            {
                var marker = new GMarker(map.getCenter(), { icon: newIcon });
                GEvent.addListener(marker, "click", function() { map.openInfoWindowHtml(new GLatLng($.googlemaps.lat,$.googlemaps.lang),$.googlemaps.setInfoContent()+"<div style='text-align: left' class='logoFrame'><div class='logoIMG'  >&nbsp;</div></div>"); }); 
            }
            
            $(".getInfoSize").html("<table border='0px' class='mapSize'><tr><td>"+$.googlemaps.setInfoContent()+"<div style='text-align: left' class='logoFrame'><div class='logoIMG'  >&nbsp;</div></div></td></tr></table>");
            newMapSize=$(".mapSize").height();
            map.openInfoWindowHtml(map.getCenter(),"<div style='height: "+newMapSize+"px;'>"+$.googlemaps.setInfoContent()+"<div style='text-align: left' class='logoFrame'><div class='logoIMG'  >&nbsp;</div></div></div>");
            map.addOverlay(marker);  
        }          
	}
}

function getPopupIFrame()
{
    $.googlemaps.setValues(data);  	
}

var map;
var gdir;
var geocoder = null;
var addressMarker;

function addresseTranslate()
{
    
    if(!$.googlemaps.OldLang)
        lang_code="";
    else
        lang_code=$.googlemaps.OldLang;
    
    var exeptions=new Array();
    exeptions[0]="Olen";
    exeptions[1]="Givet";
    exeptions[1]="Tielen";
    in_exeptions=false;
    for(key in exeptions)
    {
        if(data.city.toLowerCase()==exeptions[key].toLowerCase())
        {
            in_exeptions=true;
            break;    
        }
    }
    if(in_exeptions)
        lang_code="en";
    
    if($.googlemaps.local.toLowerCase()=="fr" && data.country.toLowerCase()=="belgique")
        lang_code="fr";
    
    google.language.translate((data.city)+", "+(data.country),lang_code,$.googlemaps.local, function(result) {
          if (!result.error) {
            var transResult=result.translation;
            transResult=transResult.split(",");
            data.city=transResult[0];
            country=transResult[1];
            if(typeof(country)=="string")
                country=country.replace(" en ","");
            data.country= country;
            google.language.translate("street,number,city,country,Plan your route,Replan","en",$.googlemaps.local, function(resultLocal) {
                  if (!resultLocal.error) {
                        var transResult=resultLocal.translation;
                        transResult=transResult.split(",");
                        $("#fromStreetTitle").html(unescape(transResult[0])+", "+unescape(transResult[1]));
                        $("#fromCityTitle").html(unescape(transResult[2]));
                        $("#fromCountryTitle").html(unescape(transResult[3]));
                        $("#MyFormOpener").val(unescape(transResult[4]));
                        $("#MyButton").val(unescape(transResult[5]));
                  }
                  if($.googlemaps.newLang==false)
                    initValues();
                  else
                    $.googlemaps.ShowHideRoad();
            }); 
          }
          else if($.googlemaps.newLang==false)
             initValues();
          else
            $.googlemaps.ShowHideRoad();                    
    });          
}

function initValues()
{
    var Datawidth=parseInt(data.width);
    var Dataheight=parseInt(data.height);
    var DataPourcent=data.pourcent;
    var sizeType="px";
    if(DataPourcent!=false)
    {
        sizeType="%";   
        if(Datawidth>100)
            Datawidth=100;
        if(Dataheight>100)
            Dataheight=100;
        
    }

    $("#map").css({ "width" : Datawidth+sizeType , "height" : Dataheight+sizeType });
    if(DataPourcent==true)
    {
        $("html").css({ "height" : Dataheight+sizeType, "width" : Datawidth+sizeType });
        $("body, #Gmap_content, #map").css({ "height" : "100%", "width" : "100%" });
        var mapOffset=$("#map").offset();
        Datawidth=$("#map").width() - mapOffset.left;        
        Dataheight=$("#map").height() - mapOffset.top;  
        data.width=Datawidth;
        data.height=Dataheight;
    }
    if(isType=="True")
        DataheightTop=Dataheight-30;    
    else
        DataheightTop=Dataheight;
    if(isURL==1)
    {
        $("#MyFormOpener").css({ "top" : "5px" , "left" : (Datawidth-155)+"px" });        
        $("#MyForm").css({ "top" : "0px" , "left" : (Datawidth-290)+"px" });  
    }   
    else
    {
        $("#MyFormOpener").css({ "top" : "5px" , "right" : "5px" });        
        $("#MyForm").css({ "top" : "0px" , "right" : "0px" });      
    }
    getPopupIFrame();   
}

