//<![CDATA[
	var map = null;
	var geocoder = null;
	var baseIcon = null;
	var gdir = null;
	var country = "dk";
	var language = "da";
	var xmlDoc = null;
	var markerGroups = null;
	var markerGroupsLength = null;
	var markerGroupsImagesLoaded = 0;
	var clusterGroups = null;
	var svPanorama = null;
	var svOverlay = null;
	
	var FLASH_UNAVAILABLE = 603;
	var NO_NEARBY_PANO = 600;
		
	function MoveEndListener() 
	{
		if (document.getElementById("message") == null)
			return;
		if (debug == false)
			return;
			
		var center = map.getCenter();
		var zoom = map.getZoom();
		document.getElementById("message").innerHTML = center.toString() + "<br>zoom:" + zoom.toString();
	}	

	function addAddress(markerTitle, address, content, markerArray, iconPath, bShow) 
	{
		geocoder.getLatLng(
			address,
			function(point) {
				if (!point) {
//					alert(address + " for " + content + " not found");
				} else {				
					addPoint(markerTitle, point, content, markerArray, iconPath, bShow);
				}
			}
		);
	} 

	function addPoint(markerTitle, point, content, markerArray, iconPath, bShow) 
	{

		var markerIcon = baseIcon;
		if (iconPath != "")		
			markerIcon = new GIcon(baseIcon, iconPath);		

		markerIcon.iconSize = new GSize(16, 16);
		markerIcon.image = iconPath;
		
		var imgPreloader = new Image();
		// once image is preloaded, resize image container
		// this is done in order to make sure that the right marker size is registered in cluster module
		imgPreloader.onload = (function () {

		    var marker = new GMarker(point, { icon: markerIcon, title: markerTitle });

		    GEvent.addListener(marker, 'click', function () {
		        map.panTo(point);
		        marker.openInfoWindowHtml(content);
		        svPanorama.setLocationAndPOV(point)
		       // document.getElementById("panorama").style.display = 'block';

		        if (parent.document.getElementById("dealer_iframe") != null) {
		        parent.document.getElementById("dealer_iframe").height = "900px";
				if(document.getElementById("panorama")!=null)
				{
		        document.getElementById("panorama").style.height = '300px';
				}
		        parent.document.getElementById("dealer_iframe").style.height = '900px';
		        parent.document.getElementById("tab-content").style.height = '900px';
				if(document.getElementById("divPanContainer")!=null)
				{
		        document.getElementById("divPanContainer").style.display = 'block';
				}
                }
              });

		 
		    if (!bShow)
		        marker.hide();

		    markerArray.push(marker);

		    markerIcon.iconSize = new GSize(imgPreloader.width, imgPreloader.height);
		    markerGroupsImagesLoaded++;

		    var iCount = 0;
		    for (var i = 0; i < markerGroups.length; i++) {
		        // markerGroupsLength is an array of integers that holds the length of each markerGroup
		        iCount += markerGroupsLength[i];
		    }

		    // Once all images have been loaded then refresh the cluster
		    if (markerGroupsImagesLoaded == iCount) {

		        for (var t = 0; t < markerGroups.length; t++) {
		            if ((markerGroups[t] != null) && (clusterGroups[t] == null)) {
		                var clusterMarkerIcon = new GIcon();
		                clusterMarkerIcon.image = '/sitecore modules/dealerlocator/images/group.gif';
		                clusterMarkerIcon.iconSize = new GSize(24, 24);
		                clusterMarkerIcon.iconAnchor = new GPoint(12, 12);
		                clusterMarkerIcon.infoWindowAnchor = new GPoint(12, 12);

		                var clusterHover = document.getElementById(hidMoreLocations).innerHTML;
		                // create a ClusterMarker
		                if (clusterGroups[0] == null)
		                    clusterGroups[0] = new ClusterMarker(map, { clusterMarkerTitle: clusterHover, clusterMarkerClick: myClusterClick, clusterMarkerIcon: clusterMarkerIcon });
		                clusterGroups[0].addMarkers(markerGroups[t]);
		                clusterGroups[0].intersectPadding = 0;
		                clusterGroups[0].refresh(true);
		            }
		        }
		    }

		}).bind(this);

		imgPreloader.src = iconPath;	

	}
	
	function setupDepartmentMarkers() 
	{	
		for (var i in departmentInfoList) {
			var layer = departmentInfoList[i];
			var markers = [];
			for (var j in layer["places"]) {
				var place = layer["places"][j];
				var address = place["address"];      
				if (address != null)
					addAddress(place["name"], address[0] + ", " + address[1] + ", " + address[2], place["name"], markerGroups[0], "", true);
			}
		}
	}

	
	function toggleMarkerVisiblity(t)   
	{
			if (clusterGroups[t] != null)
			{
				clusterGroups[t].enable(!clusterGroups[t].enabled);	
			}		        					          
	}

	function setupMarkersAsync() 
	{

		var request = GXmlHttp.create();
	if(document.getElementById("panorama")!=null)
	{
	document.getElementById("panorama").height=0;
	}
	  if (parent.document.getElementById("tab-content") != null) { 
									if(parent.$.browser.msie) {
										parent.document.getElementById("tab-content").style.height = '600px';
									} else {
										parent.document.getElementById("tab-content").style.height = '620px';
									}
								}
		request.open("GET", "/sitecore%20modules/dealerlocator/data/dynamicdata.aspx?id=" + sItemID + "&filters=" + sSelectionFilter+ "&zipcode=" + sZipCode, true);
			    
		request.onreadystatechange = function() {
							
			if (request.readyState == 4) 
			{	
					
				xmlDoc = GXml.parse(request.responseText.replace("\r","").replace("\n",""));        
				
				if (xmlDoc == null)
					alert("Markerlist is empty!!");

				// obtain the array of markers and loop through it               
				var markerlist = xmlDoc.documentElement.getElementsByTagName("markers");                

				markerGroups = new Array(markerlist.length);
				markerGroupsLength = new Array(markerlist.length);
				clusterGroups = new Array(markerlist.length);				

				var markers = xmlDoc.documentElement.getElementsByTagName("markers")[0];  
				if (markers != null && (markers.getAttribute("lat") != 'NaN') && (markers.getAttribute("lng") != 'NaN')) 
					MapCenter(markers.getAttribute("lat"), markers.getAttribute("lng"), sZoomFactor);

				for (var t = 0; t < markerlist.length; t++) 
				{        					        
					var bVisible = false;
					if (markerlist[t].getAttribute("visible").toLowerCase() == "true")
						bVisible = true;
					
					var icon = markerlist[t].getAttribute("icon");                
					
					markerGroups[t] = new Array();					
					for (var i = 0; i < markerlist[t].childNodes.length; i++) 
					{
						var marker = markerlist[t].childNodes[i];
						
						// markerGroupsLength is an array of integers that holds the length of each markerGroup
						markerGroupsLength[t] = markerlist[t].childNodes.length;
						
						var content = "";

						// Get html content, using three crossbrowser methods (http://blog.coderlab.us/2005/09/22/using-the-innertext-property-with-firefox)
						if (typeof(marker.text) != "undefined")
							content = marker.text;
						else if (typeof(marker.textContent) != "undefined")
							content = marker.textContent;
						else if (typeof(elem.innerText) != "undefined")
							content = marker.innerText;
													
						if ((content == null) || (content == ""))						
							content = marker.getAttribute("html");
						
						var label = marker.getAttribute("label");
						var link = marker.getAttribute("link");
						var phone1 = marker.getAttribute("phone1");
						var phone2 = marker.getAttribute("phone2");
						var fax = marker.getAttribute("fax");
						var mailto = marker.getAttribute("mailto");
						var date = marker.getAttribute("date");						
						var image = marker.getAttribute("image");						
						var address = marker.getAttribute("address");								
						var addressList = address.split(";");	

						var html = "";						
						if ((label != null) && (label != ""))
							html = html + "<h3>" + label + "</h3>";

						if ((image != null) && (image != ""))
						{
							html = html + "<div class='articleImg'><img src='" + image +
									"' class='imgSingle'></img></div>";							
						}

						if ((content != null) && (content != ""))
							html = html + content;
						
						if (((content == null) || (content == "")) &&	(addressList != null) && (addressList.length > 2))
						//	html = html + "<p>" + addressList[0] + "<br>" + addressList[2] + " " + addressList[1] + "<br></p>";
						{

							html = html+"<p>";
							var j=0;
							for (j=0;j<3;j++)
							{
								if (addressList[j] !=null && addressList[j].strip() != "" && addressList[j].strip() != ".")
									html = html + addressList[j] + "<br>"; 
							}
							// Zip code and city
							if ((addressList[3] !=null && addressList[3] != "") || (addressList[4] !=null && addressList[4] != "") )
								html = html + addressList[3] + " "+ addressList[4]+"<br>"; 
								//country
							if (addressList[5] !=null && addressList[5] != "")
								html = html + addressList[5] + "<br>";
							
						}
						html = html+"<p>";
						if ((phone1 != null) && (phone1 != ""))
							html = html + document.getElementById(hidPhone).innerHTML +": " + phone1 + "<br>";
						if ((phone2 != null) && (phone2 != ""))
							html = html + document.getElementById(hidPhone).innerHTML +": " + phone2 + "<br>";	
													
						if ((fax != null) && (fax != ""))
							html = html + document.getElementById(hidFax).innerHTML +": " + fax + "<br>";	
											
						if ((link != null) && (link != ""))
							html = html + document.getElementById(hidLink).innerHTML +": <a href='http://" + link.replace('http://', '') + "' target='_blank'>" + link + "</a><br>";							

						if ((mailto != null) && (mailto != ""))
							html = html + document.getElementById(hidEmail).innerHTML +": <a href='mailto:" + mailto + "' target='_blank'>" + mailto + "</a><br>";							
						html = html+"</p>";
						html = html + "<div class='hr'><hr/></div>";
						html = "<div class='iwstyle' style='min-width:250px; width:250px;'>" + html + "</div>";
						
						var lat = parseFloat(marker.getAttribute("lat"));
						var lng = parseFloat(marker.getAttribute("lng"));
						if ((! isNaN(lat)) && (!isNaN(lng)))
						{
							var point = new GLatLng(lat,lng); 
							addPoint(label, point, html, markerGroups[t], icon, bVisible)
						}
					}	        					
				}
			}
		}
		request.send(null);
	}
			
	function load() 
	{		
		if (GBrowserIsCompatible()) 
		{							
			map = new GMap2(document.getElementById("map"));
			map.addControl(new GLargeMapControl()); 
			map.addControl(new GMapTypeControl());						
			map.addControl(new GOverviewMapControl());
			
			GEvent.addListener(map, "moveend", MoveEndListener);			
			
			if ((sStartPosition != "") && (sZoomFactor != ""))
			{
				var startPositionList = sStartPosition.split(",");	
				map.setCenter(new GLatLng(parseFloat(startPositionList[0]), parseFloat(startPositionList[1])), parseFloat(sZoomFactor), G_NORMAL_MAP);			
			}
			else
			{
				map.setCenter(new GLatLng(56.145549500679074, 10.799560546875), 7, G_NORMAL_MAP);			
			}
			
			geocoder = new GClientGeocoder();
			geocoder.setBaseCountryCode(country);

			// Create a base icon for all of our markers that specifies the
			// shadow, icon dimensions, etc.
			baseIcon = new GIcon();
			baseIcon.shadow = "http://www.google.com/mapfiles/transparent.png";
			baseIcon.shadowSize = new GSize(37, 34);
	
			baseIcon.iconAnchor = new GPoint(4, 4); //(9, 34);
			baseIcon.infoWindowAnchor = new GPoint(9, 2);
			baseIcon.infoShadowAnchor = new GPoint(18, 25); // (18, 25);
			baseIcon.image = "/sitecore modules/dealerlocator/images/search.gif";
			
			setupMarkersAsync();
//			add Streetview Panorama panel under the map
			svPanorama=new GStreetviewPanorama(document.getElementById("panorama"));
			GEvent.addListener(svPanorama, "error", handleNoFlash);
		
			svOverlay = new GStreetviewOverlay();
		}
	}

    function handleNoFlash(errorCode) {
      /*if (errorCode == FLASH_UNAVAILABLE) {
        alert("Error: Flash doesn't appear to be supported by your browser");
        return;
      }*/
      // If there is no flash, we could put a message here if we wanted to ####

        if (errorCode == NO_NEARBY_PANO) {
          
           /// document.getElementById("panorama").style.display = 'none';
            if (parent.document.getElementById("dealer_iframe") != null) {
								if(parent.$.browser.msie) {
									parent.document.getElementById("dealer_iframe").height = "600px";
								} else {
									parent.document.getElementById("dealer_iframe").height = "620px";
								}
					if(document.getElementById("panorama")!=null)
					{			
                document.getElementById("panorama").innerHTML = "";
                document.getElementById("panorama").height="0";
				}
								if(parent.$.browser.msie) {
									parent.document.getElementById("dealer_iframe").style.height = '600px';
								} else {
									parent.document.getElementById("dealer_iframe").style.height = '620px';
								}
                if (parent.document.getElementById("tab-content") != null) { 
									if(parent.$.browser.msie) {
										parent.document.getElementById("tab-content").style.height = '600px';
									} else {
										parent.document.getElementById("tab-content").style.height = '620px';
									}
								}
								if(document.getElementById("divPanContainer")!=null)
								{
                document.getElementById("divPanContainer").style.display = 'none';
}
            }
        }
       
       
      return;
    }

	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.");
	}

	function checkLayer(index, name) {
		toggleMarkerVisiblity(index);
	}

	function MapCenter(lat, lng, zoom)
	{
		if (zoom == "") zoom = 7;
		map.setCenter(new GLatLng(lat, lng), parseInt(zoom));		
	}

	// *** ClusterMaps ***
	function myClusterClick(args) 
	{
		var iCluster = -1;
		for (var t=0; t<clusterGroups.length; t++)
		{
			if ((clusterGroups[t] != null) && (clusterGroups[t] == this))
			{			
				iCluster = t;
				continue;
			}
		}
		
		args.cluster.defaultClickAction=function()			
		{
			map.setCenter(args.clusterMarker.getLatLng(), map.getBoundsZoomLevel(args.clusterMarker.clusterGroupBounds));			
			delete args.cluster.defaultClickAction;
		}

		var html='<div style="height:10em; overflow:auto; width:24em"><h4>'+args.clusteredMarkers.length+' '+document.getElementById(hidLocation).innerHTML+':</h4>';
		for (i=0; i<args.clusteredMarkers.length; i++) 
		{			
			html+='<a href="javascript:clusterGroups[' + iCluster.toString() + '].triggerClick('+args.clusteredMarkers[i].index+')">'+args.clusteredMarkers[i].getTitle()+'</a><br />';
		}
		html+='<br /></div>';
		map.openInfoWindowHtml(args.clusterMarker.getLatLng(), html);
		map.setCenter(args.clusterMarker.getLatLng(), map.getZoom());
	}
	
//]]>

