 $(document).ready(function() {

   $('#CommentShowLink').click(function(){
     $('#Commented').toggle(400);
   });
   $('#UseOfMapLink').click(function(){
     $('#UseOfMap').toggle(400);
   });
    $('#SendFeedbackLink').click(function(){
     $('#SendFeedback').toggle(400);
   });
   //http://www.malsup.com/jquery/form/#code-samples
   // bind form using ajaxForm 
    $('#FeedbackForm').ajaxForm({ 
        // target identifies the element(s) to update with the server response 
        //target: '#FeedbackMessage', 
 
        // success identifies the function to invoke when the server response 
        // has been received; here we apply a fade-in effect to the new content 
        success: function() { 
            //$('#FeedbackMessage').fadeIn('slow');
			document.getElementById('FeedbackForm').style.display = 'none';
			document.getElementById('ThankYou').style.display = 'block';
			document.getElementById('Message').value = '';
			setTimeout("document.getElementById('ThankYou').style.display = 'none'",3000);
			setTimeout("document.getElementById('FeedbackForm').style.display = 'block'",3000);
			$('textarea#Message').autoResize({
				// On resize:
				onResize : function() {
					$(this).css({opacity:0.8});
				},
				// After resize:
				animateCallback : function() {
					$(this).css({opacity:1});
				},
				// Quite slow animation:
				animateDuration : 300,
				// More extra space:
				extraSpace : 20
			});
        } 
    });
	//http://james.padolsey.com/javascript/jquery-plugin-autoresize
	$('textarea#Message').autoResize({
    // On resize:
    onResize : function() {
        $(this).css({opacity:0.8});
    },
    // After resize:
    animateCallback : function() {
        $(this).css({opacity:1});
    },
    // Quite slow animation:
    animateDuration : 300,
    // More extra space:
    extraSpace : 20,
	limit: 150
});
 });

function CancelFeedback() {
	document.getElementById('Message').value = '';
	document.getElementById('SendFeedback').style.display = 'none';
}

function AnimateSearchResults() {
$(document).ready(function(){
	$("#SearchResults").animate({ backgroundColor: "#F7F275" }, 500);
	$("#SearchResults").animate({ backgroundColor: "#FFFFFF" }, 4000);
});
}

function AnimateGeoResults() {
	$(document).ready(function(){
	$("#GeoResults").animate({ backgroundColor: "#F7F275" }, 500);
	$("#GeoResults").animate({ backgroundColor: "#FFFFFF" }, 4000);
});
}

function HideSearchResults() {
	document.getElementById('SearchResultsHeadline').style.display = 'none';
	document.getElementById('SearchResults').style.display = 'none';
	document.getElementById('DetailSearchResults').style.display = 'none';
}

function HideGeoResults() {
	document.getElementById('GeoResults').style.display = 'none';
}

function RemoveAllHelpBoxes() {
	document.getElementById('ExtraViewHelpBox').style.display = 'none';
	document.getElementById('SearchHelpBox').style.display = 'none';
	document.getElementById('ListHelpBox').style.display = 'none';
	document.getElementById('ZoomHelpBox').style.display = 'none';
	document.getElementById('LinkBox').style.display = 'none';
}

function ShowListHelp() {
	RemoveAllHelpBoxes();
	document.getElementById('ListHelpBox').style.display = 'block';
}

function ShowZoomHelp() {
	RemoveAllHelpBoxes();
	document.getElementById('ZoomHelpBox').style.display = 'block';
}
function ShowSearchHelp() {
	RemoveAllHelpBoxes();
	document.getElementById('SearchHelpBox').style.display = 'block';
}
function ShowExtraViewHelp() {
	RemoveAllHelpBoxes();
	document.getElementById('ExtraViewHelpBox').style.display = 'block';
}
function ShowLink() {
	RemoveAllHelpBoxes();
	document.getElementById('LinkBox').style.display = 'block';
}
function ShowLink() {
	RemoveAllHelpBoxes();
	var bounds = googleMap.getBounds();
	var zoom = googleMap.getBoundsZoomLevel(bounds);
	var lat = googleMap.getCenter().lat();
	var lng = googleMap.getCenter().lng();
		
	if (googleMap.getCurrentMapType() == G_NORMAL_MAP) {
		var v = 1;
	}
	if (googleMap.getCurrentMapType() == G_SATELLITE_MAP) {
		var v = 2;
	}
	if (googleMap.getCurrentMapType() == G_HYBRID_MAP) {
		var v = 3;
	}
	if (googleMap.getCurrentMapType() == G_PHYSICAL_MAP ) {
		var v = 4;
	}
	
	document.getElementById('LinkBox').style.display = 'block';
	var LinkValue = "http://www.campingpladser-danmark.dk/?lat=" + lat.toFixed(4) + "&lng=" + lng.toFixed(4) + "&z=" + zoom + "&v=" + v;
	
	document.getElementById('Link').value = LinkValue;
	//document.getElementById('LinkExample').innerHTML = "<a href=" + LinkValue + " target=_blank>Se eksempel</a> <span class=Help>(&#229;bner i nyt vindue)</span>";	
	
	document.getElementById('Link').select();
}
	function FormCheck() {
	
	if (document.MyForm.SearchStr.value == "") {
		alert('SÃ¸gefeltet er tomt. Indtast venligst et sÃ¸geord.');
		return false;
	}
	
	if (document.MyForm.SearchFor[0].checked) {
		//alert('Lokalitet');
		document.getElementById("SearchInputLocalHidden").value = document.getElementById("SearchInput").value;
		var What;
		What = document.MyForm.SearchStr.value;
		WriteSearchFrase(What);
		showAddress();
		return false;
	}
	else {
		document.getElementById("SearchInputCampingHidden").value = document.getElementById("SearchInput").value;
		SearchResults_html = "";
		document.getElementById("DetailSearchResults").style.display = "none";
		var What;
		What = document.MyForm.SearchStr.value;
		SearchData(What);
		return false;
	}
		
	}
 
   var googleMap = null;
	var progressBar = [];
	var batch = [];
	var num = 0;
	var maxNum;
	var to_htmls = [];
   var from_htmls = [];
   var marker; //Geocode
   var geo;//Geocode
   var reasons=[];//Geocode

	
	var SearchResults_html = "";
      var gmarkers = [];
      var htmls = [];
      var i = 0;
	
	// === Create an associative array of GIcons() ===
   var gicons = [];
   gicons["campingplads"] = new GIcon(G_DEFAULT_ICON, "images/campingplads-icon.png");
   gicons["campingplads"].iconSize = new GSize(18,17);
   gicons["campingplads"].iconAnchor = new GPoint(9, 9);
   gicons["campingplads"].shadow = "images/blank.png";
   gicons["campingplads"].shadowSize = new GSize(1, 1);
   gicons["campingplads"].infoWindowAnchor = new GPoint(9, 9);
   
   function switchLayer(checked,layer){
  if(checked)googleMap.addOverlay(layer);
  if(!checked)googleMap.removeOverlay(layer);
}

	  
   	function initialize() {
		
		document.MyForm.SearchInput.focus();
		
	   googleMap = new GMap2(document.getElementById('googleMap'));
	   
		var customUI = googleMap.getDefaultUI();
		customUI.controls.scalecontrol = false;
		googleMap.setUI(customUI);
		googleMap.setCenter(new GLatLng(CenterLat, CenterLng), CenterZoom); //CenterLat, CenterLng, CenterZoom defineres i default.asp
		googleMap.enableScrollWheelZoom();
		googleMap.setMapType(mapView); //mapView defineres i default.asp
		//googleMap.addControl(new GOverviewMapControl(new GSize(150,150)));
	   
	   
	   progressBar = new ProgressbarControl(googleMap, {width:150});
	   
		LoadData("include/campingpladser.xml");
		resizeAndCenterMap();
		
		
		// ====== Create a Client Geocoder ======
      geo = new GClientGeocoder(); 

      // ====== Array for decoding the failure codes ======
      reasons[G_GEO_SUCCESS]            = "Succes";
      reasons[G_GEO_MISSING_ADDRESS]    = "Manglende adresse: Adressen har ikke en gyldig vÃ¦rdi.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Ukendt adresse:  Der kan ikke findes en geografisk placering for den angivne adresse.";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "UtilgÃ¦ngelig adresse:  Af juridiske grunde kan den angivne adresse ikke vises.";
      reasons[G_GEO_BAD_KEY]            = "Forkert API-nÃ¸gle: API-nÃ¸glen er enten ugyldig eller gÃ¦lder ikke dette domÃ¦ne.";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "For mange forespÃ¸rgsler: Den daglige kvote for lokations-sÃ¸gninger er overskredet.";
      reasons[G_GEO_SERVER_ERROR]       = "Serverfejl: SÃ¸gningen kunne ikke foretages pga en serverfejl hos Google.";

        }
	
	  // ====== Plot a marker after positive reponse to "did you mean" ======
      function place(lat,lng) {
       point = new GPoint(lng,lat);
		marker = new GMarker(point);
			GEvent.addListener(marker,"click", function() {
			  marker.openInfoWindowHtml("'<strong>"+ document.getElementById("SearchInputLocalHidden").value +"</strong>'<br><em><span class=small>(Omtrentlig placering. <a href=http://www.google.com target=_blank>Leveret af Google</a>.)</span></em><div style='margin-top: 8px;'>Gr&#248;nne telte (<img src='images/campingplads-icon-small.png' width='18' height='12' border='0' />) indikerer campingpladser. <br>Klik p&#229; et telt for at se flere oplysninger om pladsen.</div><div style='margin-top: 8px;'><a href='javascript:ShowZoomHelp()'>Hvordan zoomer jeg?</a></div>");
			});
		googleMap.addOverlay(marker);
		GEvent.trigger(marker,"click"); //åbner infoboksen automatisk
		googleMap.setCenter(new GLatLng(lat, lng), 8);
       //document.getElementById("GeoResults").innerHTML = "";
	   document.getElementById("GeoResults").style.display = "none";
	   document.MyForm.SearchInput.focus();
      }

      // ====== Geocoding ======
      function showAddress() {
        var search = document.getElementById("SearchInput").value + ", Danmark";
        // ====== Perform the Geocoding ======        
        geo.getLocations(search, function (result)
          {
				//fjerner
				if (marker != null ) {
					googleMap.removeOverlay(marker);
				} 
            if (result.Status.code == G_GEO_SUCCESS) {
              // ===== If there was more than one result, "ask did you mean" on them all =====
              if (result.Placemark.length > 1) { 
                document.getElementById("GeoResults").innerHTML = "<img src='images/SearchResult-close.png' width='12' height='12' border='0' vspace='0' hspace='0' title='Fjern s&#248;geresultat' onclick='HideGeoResults();' style='cursor: pointer; margin-right: 15px;' align='right' /><font color=red><strong>Mente du:</strong></font>";
                // Loop through the results
                for (var i=0; i<result.Placemark.length; i++) {
                  var p = result.Placemark[i].Point.coordinates;
                  document.getElementById("GeoResults").innerHTML += "<br>"+(i+1)+": <a href='javascript:place(" +p[1]+","+p[0]+")'>"+ result.Placemark[i].address+"<\/a>";
					document.getElementById("GeoResults").style.display = "block";
                }
				AnimateGeoResults();
              }
              // ===== If there was a single marker =====
              else {
                //document.getElementById("GeoResults").innerHTML = "";
					document.getElementById("GeoResults").style.display = "none";
                var p = result.Placemark[0].Point.coordinates;
                place(p[1],p[0]);
              }
            }
            // ====== Decode the error status ======
            else {
              var reason="Code "+result.Status.code;
              if (reasons[result.Status.code]) {
                reason = reasons[result.Status.code]
              } 
              //alert('Could not find "'+search+ '" ' + reason);
			  alert(reason);
            }
          }
        );
      }
		
	//}
	
	// get window width independent of browser
	function getWWidth() {
		var myWidth = 0;
		if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
			myWidth = window.innerWidth;
		} else if( document.documentElement && document.documentElement.clientWidth) {
    //IE 6+ in 'standards compliant mode'
			myWidth = document.documentElement.clientWidth;
		} else if( document.body && document.body.clientWidth ) {
    //IE 4 compatible
			myWidth = document.body.clientWidth;
		}
		var LeftColumWidth = 318;
		myWidth = myWidth - LeftColumWidth
		return myWidth;
	}
// get window height independent of browser
	function getWHeight() {
		var myHeight = 0;
		if( typeof( window.innerHeight ) == 'number' ) {
			myHeight = window.innerHeight;
		} else if( document.documentElement && document.documentElement.clientHeight) {
			myHeight = document.documentElement.clientHeight;
		} else if( document.body && document.body.clientHeight ) {
			myHeight = document.body.clientHeight;
		}
		var TopRowHeight = 175;
		myHeight = myHeight - TopRowHeight
		return myHeight;
	}
// set div size
	function setDivSize() {
				document.getElementById("googleMap").style.width = getWWidth()+'px';
				document.getElementById("googleMap").style.height = getWHeight()+'px';
	}
	
	
// resize map keeping same centre
	function resizeAndCenterMap() {
		var mapcenter = googleMap.getCenter();
		setDivSize();
		googleMap.checkResize();
		googleMap.setCenter(mapcenter);
	}
	
	wiki = new GLayer("org.wikipedia.en")
		pano = new GLayer("com.panoramio.all")
		tube = new GLayer("com.youtube.all")
		
	// Monitor the window resize event and let the map know when it occurs 
			if (window.attachEvent) {	// IE
				window.attachEvent("onresize", function() {resizeAndCenterMap();} ); 
			} else { 					// others
				window.addEventListener("resize", function() {resizeAndCenterMap();} , false); 
			} 
			

	function LoadData(url) {
		
		// ===== Start with an empty GLatLngBounds object =====     
      //var bounds = new GLatLngBounds();
		
	   var request = GXmlHttp.create();
	   request.open('GET', url, true);
	   request.onreadystatechange = function() {
  	      if (request.readyState == 4) {
		var xmlDoc = request.responseXML;
		var markers = xmlDoc.documentElement.getElementsByTagName("marker");
		for (var i = 0; i < markers.length; i++) {
  		   var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
		   
		   // ==== Each time a point is found, extent the bounds ato include it =====
          //bounds.extend(point);
		   
		   var campingname = markers[i].getAttribute("campingname");
		   var campingID = markers[i].getAttribute("id");
		   var starnumber = markers[i].getAttribute("starnumber");
		   var icon = "campingplads"
		   
		   var marker = createMarker(point,icon,campingname,starnumber,campingID);
		   	
			batch.push(marker);
		   	  
			progressBar.start(batch.length);
			maxNum = batch.length;
			setTimeout('addMarkers()',10);
		
		//googleMap.addOverlay(marker);
			
		}
			

          // ===== determine the centre from the bounds ======
          //googleMap.setCenter(bounds.getCenter());
		  //googleMap.setZoom(7);
		
  	    }
      }

		
	  request.send(null);
	}
	
	function createMarker(point,icon,campingname,starnumber,campingID) {
           var marker = new GMarker(point,gicons[icon]);

		   GEvent.addListener(marker, 'click', function(){ 
				marker.openExtInfoWindow(
              googleMap,
              "custom_info_window_red",
              "<div>Loading...</div>",
              {
                ajaxUrl: "ajaxwindow.asp?campingID="+campingID, 
                beakOffset: 1
              }
									); 
										});
			
		 
		
		 gmarkers[i] = marker;
        htmls[i] = campingID;

        i++;
		 
           return marker;
     }
	 
	  // This function picks up the click and opens the corresponding info window
      function myclick(i) {
        //gmarkers[i].openInfoWindowHtml(htmls[i]);
		gmarkers[i].openExtInfoWindow(
              googleMap,
              "custom_info_window_red",
              "<div>Indl&aelig;ser...</div>",
              {
                ajaxUrl: "ajaxwindow.asp?campingID="+htmls[i], 
                beakOffset: 1
              }
									); 
      }
	
   
   function addMarkers() {
	     num = num + 1;
	     
	     //progressBar.updateLoader(1);
	     var marker = batch.pop();
	     googleMap.addOverlay(marker);

	     if (num < maxNum) {
	        //setTimeout('addMarkers()',10);
	     }
	     else {
			progressBar.remove();

	     }
	  }
	  
	
	function SearchData(What)
{
	var xmlhttp;
	if (window.XMLHttpRequest)
		{
			// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		}
		else if (window.ActiveXObject)
			{
				// code for IE6, IE5
				xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
	else
		{
			alert("Your browser does not support XMLHTTP!");
		}

	xmlhttp.onreadystatechange=function()
	{
			if(xmlhttp.readyState==4)
		{
			n = 0;
			//document.getElementById("SearchResults").innerHTML=xmlhttp.responseText;
			var xmlDoc = xmlhttp.responseXML;
			var markers = xmlDoc.documentElement.getElementsByTagName("marker");
				for (var i = 0; i < markers.length; i++) {
				
				var ordernumber = markers[i].getAttribute("ordernumber");
				var campingname = markers[i].getAttribute("campingname");
				
				SearchResults_html += '<a href="javascript:myclick('+ ordernumber +')">'+ campingname +'</a><br>';
				n = i+1;
				}
			
			if (n < 1) {
				SearchResults_html = "Ingen resultater ved s&#248;gning efter '"+What+"'. <br />Se evt. vores <a href='javascript:ShowSearchHelp()'>hj&#230;lp til s&#248;gning</a>.";
				}
			
			document.getElementById("SearchResults").innerHTML= SearchResults_html;
			document.getElementById("SearchResults").style.display = "block";
			document.getElementById("SearchResultsHeadline").style.display = "block";
			
			if (n > 1) {
				document.getElementById("DetailSearchResults").style.display = "block";
				document.getElementById("DetailLink").innerHTML= "Vis detaljer om disse "+n+" campingpladser";
				}
				
			document.getElementById("SearchResultsHeadline").innerHTML = '<div class="LeftBoxHeadline">Campingplads-s&#248;gning ('+n+' stk.) <img src="images/SearchResult-close.png" width="12" height="12" border="0" vspace="0" hspace="0" title="Fjern s&#248;geresultat" onclick="HideSearchResults();" style="cursor: pointer; margin-left: 8px;" /></div>';
			AnimateSearchResults();
		}
	}
	xmlhttp.open("GET","include/data-ajax.asp?Action=Search&Type=Camping&SearchStr="+What,true);
	xmlhttp.send(null);
}

	function WriteSearchFrase(What)
{
	var xmlhttp;
	if (window.XMLHttpRequest)
		{
			// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		}
		else if (window.ActiveXObject)
			{
				// code for IE6, IE5
				xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
	else
		{
			alert("Your browser does not support XMLHTTP!");
		}

	xmlhttp.onreadystatechange=function()
	{
			if(xmlhttp.readyState==4)
		{
			
		}
	}
	xmlhttp.open("GET","include/data-ajax.asp?Action=Search&Type=Geo&SearchStr="+What,true);
	xmlhttp.send(null);
}

