﻿// JScript File
var map = '' ;
var myOptions = '';
var markerArray = [];
var theDomain = 'http://' + window.location.hostname;
var imgSrc;
var selectedMarker = '';
var infowindow = '';

function initaliseWindow(){
	infowindow = new google.maps.InfoWindow({ maxWidth: 360});
}


/*Parses data from XML into Google Maps Regional Information
This is region only data, not campsite data */
function parse(data, mapdiv)  {
	//Set the Google map format 
     var latlng = new google.maps.LatLng(48.402391829093915, 9.140625);
     var myOptions = {
        panControl: false,
        scrollwheel: false,
        mapTypeControl: false,
        draggable: false,
        streetViewControl: false,
        disableDoubleClickZoom: true,
        zoomControl: false,
        zoomControlOptions: {style: google.maps.ZoomControlStyle.SMALL   },
        zoom: 4,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.TERRAIN
    };
    map = new google.maps.Map(document.getElementById(mapdiv), myOptions);
	
	// JQuery go through regional data 
   $(data).each(function(index, value){
        var region = value.split(',');
        var objName = region[0];
        var lat = region[1];
        var lon = region[2];
		var lnk = theDomain + region[3];
		var placeMarker = region[4];
        //Add the Google markers
        var image =  theDomain + '/mapimages/regions/' + placeMarker + '_icon.png';
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(lat, lon),
            map: map,
            icon: image,
            url: lnk    
        });
		/*Add Google click listener to make the region markers
		into link buttons */
        google.maps.event.addListener(marker, 'click', function() {window.location.href = marker.url;});
        marker.setMap(map);  
    });
}
/* Parse Data from XML for the campsite and apartment level of google */
function parseChildRegions(data, regionGroup, parcLabel)  {
	
    var zoomLevel;
    var zoomLat;
    var zoomLon;
    var borderCoords;    
    
    $(data).each(function(index, value){
      /*Get the zoom levels of the region information*/
      switch (index) {
            case 0:
                zoomLevel = value;
                break;
            case 1:
                zoomLat = value;
                break;
            case 2:
                zoomLon = value;
                break;
            case 3: 
                borderCoords = value.split("~");
        }   
    });
	//Set the Google map format 
     var latlng = new google.maps.LatLng(zoomLat, zoomLon);
     myOptions = {
        panControl: false,
        scrollwheel: true,
        mapTypeControl: false,
        draggable: true,
        streetViewControl: false,
        disableDoubleClickZoom: false,
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.LARGE,   
            position: google.maps.ControlPosition.LEFT_BOTTOM
            },
        zoom: parseInt(zoomLevel),
		minZoom: 2,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.TERRAIN
    };
    map = new google.maps.Map(document.getElementById("canvas_map_region"), myOptions);  

    /*Set google listeners*/
    google.maps.event.addListener(map, 'dragend', function(event) {        
		/*Get a new list of campsites available in the new Google view*/
        getDraggedSites(parcLabel);
    });
    google.maps.event.addListener(map, 'zoom_changed', function(event) {
		/*Get a new list of campsites available in the new Google view*/        
        getDraggedSites(parcLabel);
		/*Centre the map on a marker if it has been selected */
		if (selectedMarker != ''){
        	map.setCenter(selectedMarker);
        }
    });
   //Get Site information, Call the webservice
      $.ajax({
        type: 'POST',
        url: theDomain + '/webservices/googlemaps/CampsiteFilter.asmx/GetSites',
        data: '{ regionGroup: \'' + regionGroup + '\' }',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(data) {
                $(data).each(function(index, value){
					/*Create the campsite and apartment markers*/
                    placeMarkers(value, infowindow, parcLabel);
                });
        },
        error: function(xmlRequest){
            alert(xmlRequest.status);
            alert(xmlRequest.statusText);
            alert(xmlRequest.responseText);
        }
    });
}
/* Writes the marker to the Google Map */
function placeMarkers(value, infowindow, parcLabel){
	//Get the url and check country so link to campsite matches folder structure
	var siteStructure = '';
	var theprefix = '';
	var url = new String(theDomain);
	var lnth = url.length - 2;
	theprefix = url.substring(lnth);
	switch (theprefix) {
            case 'nl':
                siteStructure = '/camping/';
                break;
			case 'be':
                siteStructure = '/camping/';
                break;
			case 'de':
				siteStructure = '/reiseziele/';
				break;				
            default: 
                siteStructure = '/sites/';
    }   
	
    var site = value.split('|');
    var objCode = site[0];
	if (objCode != '')
	{		

		var lat = site[4];
		var lon = site[5];
		var accommType = site[6];
		var name = site[1];
		var area = site[2];
		var descr = site[9];
		var img = site[8];
		//var linkage = site [10];
		//Add the markers
		var image =  theDomain + '/mapimages/' + accommType + 'Icon.png';
		var contentString = '<div id="contentInfo">' +
		'<div class="h2Style">' + name + '</div>' +
		'<div class="h3Style">' + area + '</div>' +
		'<div class="backgroundSite"><img src="' + theDomain + '/' + img + '" /></div><p>' +  descr + '</p>'+
		//'<a  href="'+ theDomain + siteStructure + linkage +'" ><img class="selectPark" src="' + theDomain + '/mapimages/viewpark.png" title="'+parcLabel+'" /></a>' +
		'<a  href="'+ theDomain + '/' + objCode +'" ><img class="selectPark" src="' + theDomain + '/mapimages/viewpark.png" title="'+parcLabel+'" /></a>' +	
		'</div>' ;
		/* Set the Google marker */
		var marker = new google.maps.Marker({
			position: new google.maps.LatLng(lat, lon),
			map: map,
			icon: image,
			shadow: theDomain + '/mapimages/ec_icon_shadow.png',		
			title: $("<div/>").html(name).text()
		});
		/* Build the Google listener so the window info box will appear onclick */
		google.maps.event.addListener(marker, 'click', function() {
			infowindow.setContent(contentString);
			infowindow.open(map,this);
			selectedMarker =  new google.maps.LatLng(lat, lon);
		});
		/* Add respective listeners to the Google Marker */
		google.maps.event.addListener(infowindow, 'closeclick', function(){
				selectedMarker = '';
		});
		google.maps.event.addListener(marker, 'mouseover', function() {
			marker.setIcon(theDomain + '/mapimages/' + accommType + 'Icon_shadow.png');
		});
		google.maps.event.addListener(marker, 'mouseout', function() {
			marker.setIcon(theDomain + '/mapimages/' + accommType + 'Icon.png');
		});
	}
}
/* This function is used when a user moves around the Google maps */
function getDraggedSites(parcLabel){
	
	/*Get the Google boundaries */
    var theCenter = map.getCenter();
    var theBoundary = map.getBounds();
    var neLat = theBoundary.getNorthEast().lat().toString();
    var neLon = theBoundary.getNorthEast().lng().toString();
    var swLat = theBoundary.getSouthWest().lat().toString();
    var swLon = theBoundary.getSouthWest().lng().toString();
      //Get Site information, Call the webservice
     $.ajax({
            type: 'POST',
            url: theDomain + '/webservices/googlemaps/CampsiteFilter.asmx/GetSitePanning',
            data: '{ neLat: \'' + neLat + '\', neLon: \'' + neLon  + '\', swLat: \'' + swLat + '\', swLon: \'' + swLon  + '\' }',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(data) {
                    $(data).each(function(index, value){
                        placeMarkers(value, infowindow, parcLabel);
                    });
            },
            error: function(xmlRequest){
                alert(xmlRequest.status);
                alert(xmlRequest.statusText);
                alert(xmlRequest.responseText);
            }
        });    
}

/* Parse the XML data for the sub regions information */
function parseSubRegion(data, regionGroup)  {
    var zoomLevel;
    var zoomLat;
    var zoomLon;
    var children; 
    $(data).each(function(index, value){
      /*Get the zoom levels*/
      switch (index) {
            case 0:
                zoomLevel = value;
                break;
            case 1:
                zoomLat = value;
                break;
            case 2:
                zoomLon = value;
                break;
            case 3:
                children = value.split("^");
                break;
        }   
    });
      //Set the Google map format 
     var latlng = new google.maps.LatLng(zoomLat, zoomLon);
     myOptions = {
        panControl: false,
        scrollwheel: false,
        mapTypeControl: false,
        draggable: true,
        streetViewControl: false,
        disableDoubleClickZoom: true,
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.LARGE,   
            position: google.maps.ControlPosition.LEFT_BOTTOM
            },
        zoom: parseInt(zoomLevel),
		minZoom: 2,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.TERRAIN
    };
   
   map = new google.maps.Map(document.getElementById("canvas_map_region"), myOptions);  
   /* JQuery loop through the region data */
    $(children).each(function(index, value){
        var region = value.split('|');
        var objName = region[0];
		if (objName != '')
		{		
			var lat = region[1];
			var lon = region[2];
			var lnk = theDomain + region[3];
			var placeMarker = region[4]; 
			//Add the Google markers
			var image =  theDomain + '/mapimages/regions/' + placeMarker + '_icon.png';
			var marker = new google.maps.Marker({
				position: new google.maps.LatLng(lat, lon),
				map: map,
				icon: image,
				url: lnk    
			});
			/*Add Google click listener to make the region markers
			into link buttons */
			google.maps.event.addListener(marker, 'click', function() {window.location.href = marker.url;});
			marker.setMap(map);   
		}
    });
}

/* Loads the Google map to the home page */
function initialize(mapID) {

	/* Set some of the design elements of home page */
	/* Remove the checkboxes and green panel*/
	var searchElement = document.getElementById("searchBox");
	if (searchElement != null){
		document.getElementById("searchBox").style.backgroundImage = 'none';
	}
	if (document.getElementById('air') != null){
    	document.getElementById('air').style.display = 'none';
	}
	if (document.getElementById('port') != null){
    	document.getElementById('port').style.display = 'none';
	}
	if (document.getElementById('train') != null){
    	document.getElementById('train').style.display = 'none';
	}
	if (document.getElementById('searchBox') != null){
		document.getElementById("searchBox").style.backgroundImage = "url(" + theDomain  + "/mapimages/mapCheckBoxPanel_blank.png)";
	}
    if (document.getElementById('xzoomButton') != null){
		document.getElementById("xzoomButton").style.display = 'none';
		/*imgSrc = document.getElementById("xzoomButton");
    	var path = theDomain + '/mapimages/zoomOutBtn.png';
	    imgSrc.setAttribute("src",path);*/
	}
	var theprefix = '';
	var url = new String(theDomain);
	var lnth = url.length - 2;
	theprefix = url.substring(lnth);
	switch (theprefix) {
            case 'nl':
				if (document.getElementById('lnkUSA') != null){
					var lnkUSASrc = '';
					lnkUSASrc = document.getElementById("lnkUSA");
					var path = 'campings/noord-amerika.html';
					lnkUSASrc.setAttribute("href",path);
				}	
                break;
			case 'be':
				if (document.getElementById('lnkUSA') != null){
					var lnkUSASrc = '';
					lnkUSASrc = document.getElementById("lnkUSA");
					var path = 'campings/noord-amerika.html';
					lnkUSASrc.setAttribute("href",path);
				}	
                break;	
			case 'de':
				if (document.getElementById('lnkUSA') != null){
					var lnkUSASrc = '';
					lnkUSASrc = document.getElementById("lnkUSA");
					var path = '/reiseziele/camping_usa.html';
					lnkUSASrc.setAttribute("href",path);
				}	
                break;							
            default: 
           /*Do Nothing*/
    }   
	
		/*Get the XML data for the top level regions */
    	$.ajax({
        type: 'POST',
        url: theDomain + '/webservices/googlemaps/CampsiteFilter.asmx/GetTopLevelRegions',
        data: '{}',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(data) {
			/* Parse the XML data*/
           parse(data, mapID);
        },
        error: function(xmlRequest){
            alert(xmlRequest.status);
            alert(xmlRequest.statusText);
            alert(xmlRequest.responseText);
        }
    });


}
/* Loads the Google map to the region pages */
function initializeRegion() {
	 initaliseWindow();
    /*Get the hidden html value of the region id */
	var regionGroup = $('input[id=hidRegionGroup]').val();
	var parcLabel = 'View parc details';
	//sect default for parcLabel
	if (document.getElementById('hidParcLinkText') != null){
		parcLabel = $('input[id=hidParcLinkText]').val();
	}
	//var regionGroup = regionID;
	//var regionGroup = 'FR';
    var regexpression = '^[0-9]';
    var method = '';
    var objName = ''
	/* Check to see if a number is within the hidden field, all top regions 
	have no numeric character assignned to it*/
    if (regionGroup.search(regexpression) == -1) {
        //if failed
        method = 'getregions';
        objName = 'GetSubRegions'
		/* Sub Regions require only a blank green panel, hide all check boxes  */
		document.getElementById("searchBox").style.backgroundImage = "url(" + theDomain  + "/mapimages/mapCheckBoxPanel_blank.png)";
	 	document.getElementById('air').style.display = 'none';
        document.getElementById('port').style.display = 'none';
        document.getElementById('train').style.display = 'none';
    }else {
        method = 'getsites';
        objName = 'GetRegionalSiteInfo';
        //The background image url here instead of hard coding in the css file
        document.getElementById("searchBox").style.backgroundImage = "url(" + theDomain  + "/mapimages/mapCheckBoxPanel.png)";
		/* Check to see if the website has apartments assigned to it and 
		display apartment key panel appropriatly */
		setApartmentKey();
    }
    $.ajax({
		/*Parse the method into the webservice dependent on whether or not 
		it is a child region on site level requirement
		*/
        type: 'POST',
        url: theDomain + '/webservices/googlemaps/CampsiteFilter.asmx/' + objName,
        data: '{ regionGroup: \'' + regionGroup + '\' }',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(data) {
            if (method == 'getregions'){
				/* Parse the XML data to Google Maps*/
	            parseSubRegion(data, parcLabel);
            } else {           
			   /*Parse XML data to Google Maps */
               parseChildRegions(data, regionGroup, parcLabel);
            }
        },
        error: function(xmlRequest){
            alert(xmlRequest.status);
            alert(xmlRequest.statusText);
            alert(xmlRequest.responseText);
        }
    });
	/* Display the zoom out button over Google Maps */
    imgSrc = document.getElementById("xzoomButton");
    var path = theDomain + '/mapimages/zoomOutBtn.png';
    imgSrc.setAttribute("src",path);
	 //Check status of the checkboxes
	deleteCheckBoxStatus();

}

function setApartmentKey(){
 //Check to see if there any apartments viewable on the website, if so overwrite panel key image
 $.ajax({
        type: 'POST',
        url: '/webservices/googlemaps/CampsiteFilter.asmx/GetApartmentStatus',
        data: '{}',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(data) {
           if (data == 'false'){
                document.getElementById("searchBox").style.backgroundImage = "url(" + theDomain + "/mapimages/mapCheckBoxPanel_CampsiteOnly.png)";
           }
        },
        error: function(xmlRequest){
            alert(xmlRequest.status);
            alert(xmlRequest.statusText);
            alert(xmlRequest.responseText);
        }
    });

}
/* Get the travel icon for the Google Maps */
function getTravelFilters(){
    var searchString = '';
	/* Check to see which checkboxes the user has checked */
    $("input:checkbox[name=travel]:checked").each(function(){
        searchString += $(this).val();
    });
    //Do the search on the checked values
     $.ajax({
        type: 'POST',
        url: theDomain + '/webservices/googlemaps/CampsiteFilter.asmx/GetAllTravelCoord',
        data: '{ filtered: \'' + searchString + '\' }',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(data) {
			/* Parse the data to Google Maps */
            addTravelIcons(data);
        },
        error: function(xmlRequest){
            alert(xmlRequest.status);
            alert(xmlRequest.statusText);
            alert(xmlRequest.responseText);
        }
    });
    
}

function addTravelIcons(data)  {
	/* Set the markers to blank first */
    deleteOverlays();
	/* Loop over XML data for travel keys */
    $(data).each(function(index, value){
            var transport = value.split(',');
            var transType = transport[0];
            var transName = transport[1];
            var lat = transport[2];
            var lon = transport[3];
            //Add the markers
            var image =  theDomain + '/mapimages/' + transType.replace(' ', '') + 'icon.png';
		/* Add the marker to the Google maps */    
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(lat, lon),
            map: map,
            icon: image,
            title: transName
        });
        markerArray.push(marker);
        marker.setMap(map);         
    });
}

// Deletes all markers in the array by removing references to them
function deleteOverlays() {
  if (markerArray) {
    for (i in markerArray) {
      markerArray[i].setMap(null);
    }
    markerArray.length = 0;
  }
}

function deleteCheckBoxStatus() {
 	$("input:checkbox[name=travel]:checked").each(function(){
		 $(this).attr('checked', false);
	});
}

function styleForIPad(){
		var isiPad = navigator.userAgent.match(/iPad/i) != null;
		var isTrue = Boolean(isiPad);
		if ( isTrue ){
			document.write("<style type=\"text/css\" media=\"screen\">");
			document.write("#searchBox .checkboxAir{margin:6px 0 0px 37px;}");
			document.write("#searchBox .checkboxPort{margin:6px 0 0px 115px;}");
			document.write("#searchBox .checkboxTrain{margin:6px 0 0px 94px;}");
			document.write("</style>");						
		}
}

