﻿/************************
Properties and variables
*************************/
var map; var bounds; var zoomlevel; var center; var maptype; 
var mapMinZoom = 0; var mapMaxZoom = 8; var overlay; var tooltipwrap; var tooltip;
var regions;var countries;var mgr;var langCode;var toogleBtnSecuritas;var toogleBtnNormalMap; var mapcanvas;
var regionObjects = [];var regionsShown;
var gobackwrapper;var goBackBtn;


/*******************
Initialize methods
********************/
function windowResizeCallback() {
	if (map && mapcanvas) {
		if(!gobackwrapper)
		{
			gobackwrapper = $('gobackwrapper');
		}
		if (gobackwrapper.style.display == 'block') {
			showHideRegionMarkers(false);
		}
		else {
			removeRegions();
			addRegions();
			mgr.refresh();
		}
	}
}

function loadGPMap() {
	if (GBrowserIsCompatible()) {
		if (!map) {
			window.onresize = windowResizeCallback;
		}
		var loader = $('waiting');
		mapcanvas = $('mapcanvas');
		// Get the map object
		map = new GMap2(mapcanvas);
		// Disable all the stuff
		map.disablePinchToZoom(); map.disableDragging();
		// Setup the controls that should be available
		setupMapControls();  
		showHideGoBackButton(false);
		// Set the selected Map type
		map.setMapType(maptype);

		// get the bounds of the map and set the center
		bounds = map.getBounds(); map.setCenter(bounds.getCenter(), 1);
		// initialize the icon and the values
		initializeBaseIcon(); 

		if (!regions) {
			regions = [];
			regionObjects = [];
			addRegions();
		}
		if (!countries) {
			countries = [];
			addValues();
		}
		// Add the overlay for the first time
		AddQuadOverlay();
		// Init the tooltip handler
		tooltipwrap = $("tooltipmarker");
		tooltipwrap.style.display = "none";
		tooltip = $("lbltooltip");
		loader.style.display = "none";
		// Refresh the manager
		mgr.refresh();
	}
}



/* GET AND ADD DATA
*******************************************************/
var africameast;var asia;var europe;var northamerica;var southamerica; // Region Name variables
var amn;var an;var en;var nan;var san; // Region Name variables
var amp;var ap;var ep;var nap;var sap; // Region Point variables
function addRegions() {
	var mapcanvaswrapper = $('mapcanvas');
	var gobackbtn = $('gobackwrapper');
	if (mapcanvaswrapper) {
		if (mapcanvaswrapper.style.display == 'block' || !mapcanvaswrapper.style.display) {
			if (gobackbtn.style.display == 'none') {
			
				if(!amp){amp = new GLatLng(2.5, 23);}
				if(!ap){ap = new GLatLng(34, 106);}
				if(!ep){ep = new GLatLng(56, 10);}
				if(!nap){nap = new GLatLng(49, -97);}
				if(!sap){sap = new GLatLng(-18, -59);}
				
				africameast = CreateRegionMarker(amp, amn, 'wraptooltipmarker');
				asia = CreateRegionMarker(ap, an, 'wraptooltipmarkersmall');
				europe = CreateRegionMarker(ep, en, 'wraptooltipmarkersmall');
				northamerica = CreateRegionMarker(nap, nan, 'wraptooltipmarker');
				southamerica = CreateRegionMarker(sap, san, 'wraptooltipmarkersmall');

				regions = [africameast, asia, europe, northamerica, southamerica];
				initializeRegions(regions, map);
			}
		}
	}
}
function initializeRegions(regionarr, mapobj) {
	if (!mgr) {
		mgr = new MarkerManager(mapobj, { trackMarkers: true });
	}
	mgr.addMarkers(regionarr, 0,2);
	
}

function addValues() {

	// Get the geocoder
	if (!geocoder) { geocoder = new GClientGeocoder(); }
	var countriesLbl = $('lblcountries').innerHTML.split('|');
	var countriesLblpoints = getElementsByClassName(document, 'a', 'countrylink');
	var countryName;var countryUrl;var countryLang;var longitude;var latitude;
	if (countriesLbl.length > 0) {
		var pageId;
		var mapPoint;
		for (var countryIndex = 0; countryIndex < countriesLbl.length; countryIndex++) {
			var country = countriesLbl[countryIndex].split(',');
			countryName = country[0];
			countryUrl = country[1];
			pageId = country[2];
			countryLang = country[3];
			getPointOnAddress(countryName, countryUrl, pageId, countryLang);
		}
	}
	if (countriesLblpoints.length > 0) {
		for (var countryIndex = 0; countryIndex < countriesLblpoints.length; countryIndex++) {
			var country = countriesLblpoints[countryIndex];
			countryName = country.title;
			countryUrl = country.href;
			longitude = country.innerHTML.split(',')[2];
			latitude = country.innerHTML.split(',')[3];
			getPointOnPoint(new GLatLng(latitude, longitude), countryName, countryUrl);
		}
	}

	addCountries();
}

var counter = 0;
var regionMarkers = [];
var regionIcon;
function CreateRegionMarker(point, iconName, cssclass) {
	// Initialize the Base Icon if not.
	if (baseIcon == 'undefined') initializeBaseIcon();
	if (!regionIcon) {
		regionIcon = new GIcon(baseIcon);
		regionIcon.iconSize = new GSize(1, 1);
		regionIcon.iconAnchor = new GPoint(1, 1);
	}
	var csscode = cssclass;
	if (csscode == 'undefined' || csscode == null) { csscode = 'wraptooltipmarker'; }
	
	// Set up our GMarkerOptions object
	markerOptions = { icon: regionIcon };
	var marker = new GMarker(point, markerOptions);
	// Add the Region Marker code
	var top = map.fromLatLngToDivPixel(marker.getLatLng()).y + elmPos.Y($("mapcanvas")) - (15 - counter * 3) + 'px';
	var left = map.fromLatLngToDivPixel(marker.getLatLng()).x + elmPos.X($("mapcanvas")) - 93 + 'px';
	var newRegionDiv = createRegionMarkerCode(iconName, top, left, "", "", "regionmarker-" + iconName, cssclass);
	addEvent(newRegionDiv, 'click', function() {
		counter++;
		// Zoom to new level
		window.setTimeout(function() {
			map.setCenter(marker.getLatLng(), 3);
			map.panTo(marker.getLatLng());
		}, 0);

		window.setTimeout(function() { showHideGoBackButton(true); }, 0);
		window.setTimeout(function() { showHideRegionMarkers(false); }, 0);
	});
	return marker;
}
function createRegionMarkerCode(content, top, left, width, height, id, cssclass) {
	
	var newdiv = document.createElement('div');
	newdiv.setAttribute('id', escape(id));

	newdiv.setAttribute('class', cssclass);
	newdiv.className = cssclass;
	
	if (width) {newdiv.style.width = width;}
	if (height) {newdiv.style.height = 300;}
	if ((left || top) || (left && top)) {
		if (left) {	newdiv.style.left = left;}
		if (top) {newdiv.style.top = top;}
	}
	else { newdiv.style.display = 'none'; }
	if (content) { newdiv.innerHTML = content; }
	else { newdiv.innerHTML = "-"; }
	regionObjects.push(newdiv);
	document.body.appendChild(newdiv);
	return newdiv;
}
// Creates a marker whose info window displays the letter corresponding
// to the given index.
function CreateCountryMarker(point, countryName, countryUrl) {
	// Initialize the Base Icon if not.
	if (baseIcon == 'undefined') initializeBaseIcon();
	
	// Set up our GMarkerOptions object
	markerOptions = { icon: baseIcon };
	var marker = new GMarker(point, markerOptions);
	// Add event handler
	GEvent.addListener(marker, 'mouseout', function() {
		marker.setImage(baseIcon.image);
		tooltipwrap.style.display = "none";
	});
	GEvent.addListener(marker, 'mouseover', function() {
		tooltipwrap.style.display = "block";
		tooltipwrap.style.top = map.fromLatLngToDivPixel(marker.getLatLng()).y + elmPos.Y($("mapcanvas")) - (28 - counter * 3) + 'px';
		tooltipwrap.style.left = map.fromLatLngToDivPixel(marker.getLatLng()).x + elmPos.X($("mapcanvas")) + 1 + 'px';
		if (document.all) { tooltipwrap.innerText = countryName; }
		else { tooltip.innerHTML = countryName; }
	});
	// Hook on the click event
	GEvent.addListener(marker, "click", function() {window.location = countryUrl;});
	return marker;
}
function addCountries() {
	if (!mgr) {return;}
	mgr.addMarkers(countries, 2, 5);
	
}
var globalName;
function getPointOnAddress(name, url, pid, lang) {
	if (name != globalName && name != '') {
		try {
			if (geocoder) {
				geocoder.getLatLng(
								name,
								  function(point) {
								  	if (!point) {
								  		return null;
								  	} else {
								  		var collectedMarker = CreateCountryMarker(point, name, url);
								  		countries.push(collectedMarker);
								  		addCountryCoordinatesToPage(point.lng(), point.lat(), pid, lang);
								  	}
								  }
								);
			}
		}
		catch (tjo) { return null; }
	}
}
function getPointOnPoint(point, name, url) {
	var collectedMarker = CreateCountryMarker(point, name, url);
	countries.push(collectedMarker);
}

/* CONTROLS
*******************************************************/
function setupMapControls() {
	map.removeMapType(G_SATELLITE_MAP);
	map.removeMapType(G_HYBRID_MAP);
}
/* MARKERS
*******************************************************/
var baseIcon;
function initializeBaseIcon() {
	baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadowSize = new GSize(0, 0);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.iconSize = new GSize(18, 26);
	baseIcon.iconAnchor = new GPoint(18, 26);
	baseIcon.image = "/gfx/gm/fyrkantspin2.png";
	
}

/* TOGGLE FUNCTIONALITY - SHOW/HIDE
********************************************************/
function showHideGoBackButton(show) {
	if(!goBackBtn)
	{
		goBackBtn = document.getElementById("lblgoback");
	 }
	if (show) {
		$('gobackwrapper').style.display = 'block';
		addEvent(goBackBtn, 'click', function() {
			map.disableDoubleClickZoom();
			map.disablePinchToZoom();
			window.setTimeout(function() { showHideGoBackButton(false); }, 0);
			window.setTimeout(function() { showHideRegionMarkers(true); }, 50);
			window.setTimeout(function() {
				map.setCenter(bounds.getCenter(), 1);
				map.panTo(new GLatLng(0, 0));
			}, 0);

			removeRegions();
			window.setTimeout(function() { addRegions(); }, 1500);
		});
	}
	else {$('gobackwrapper').style.display = 'none';}
}
function showHideRegionMarkers(show) {
	var regionMarkers = getElementsByClassName(document, "div", "wraptooltipmarker");
	for (var nr = 0; nr < regionMarkers.length; nr++) {
		var regionMarkerObj = regionMarkers[nr];
		if (show) {regionMarkerObj.style.display = 'block';}
		else { regionMarkerObj.style.display = 'none'; }
	}
	regionMarkers = getElementsByClassName(document, "div", "wraptooltipmarkersmall");
	for (var nr = 0; nr < regionMarkers.length; nr++) {
		var regionMarkerObj = regionMarkers[nr];
		if (show) { regionMarkerObj.style.display = 'block'; }
		else { regionMarkerObj.style.display = 'none'; }
	}
}

function removeRegions() {
	if (regionObjects.length > 0) {
		for (var i = 0, il = regionObjects.length; i < il; i++) {
			try{
				if (regionObjects[i]) {
					purge(regionObjects[i]);
					document.body.removeChild(regionObjects[i]);
				}
			}
			catch(v){}
		}
		// Flush EventCache
		EventCache.flush();
		countries = null;
		regionMarkers = null;
		regions = null;
		
	}
}
function hideCountryPoints() {
	var countryPoints = $('countrypoints');
	if (countryPoints && countryPoints != null) { countryPoints.style.display = 'none'; }
}
/** MAP TYPE AND TILE FUNCTIONS
*******************************************************/
function TileToQuadKey(x, y, zoom) {
	var quad = "";
	for (var i = zoom; i > 0; i--) {
		var mask = 1 << (i - 1);
		var cell = 0;
		if ((x & mask) != 0)
			cell++;
		if ((y & mask) != 0)
			cell += 2;
		quad += cell;
	}
	return quad;
}
// One way to add tiles to the Google Map
function AddQuadOverlay() {

	// Set up the copyright information
	// Each image used should indicate its copyright permissions
	var myCopyright = new GCopyrightCollection("© ");
	myCopyright.addCopyright(new GCopyright('Securitas',
				  new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)),
				  0, '@2009 Securitas'));
	// Create the tile layer overlay and 
	// implement the three abstract methods
	var tilelayer = new GTileLayer(myCopyright, mapMinZoom, mapMaxZoom);
	var mercator = new GMercatorProjection(mapMaxZoom + 1);
	tilelayer.getTileUrl = function(a, b) {
		return "/gfx/gp/" + TileToQuadKey(a.x, a.y, b) + ".jpg";
	};

	// IE 7-: support for PNG alpha channel
	// Unfortunately, the opacity for whole overlay is then not changeable, either or...
	tilelayer.isPng = function() { return true; };
	tilelayer.getOpacity = function() { return 1; }

	overlay = new GTileLayerOverlay(tilelayer);
	map.addOverlay(overlay);
}

function AddTileOverlay() {

	// Set up the copyright information
	// Each image used should indicate its copyright permissions
	var myCopyright = new GCopyrightCollection("© ");
	myCopyright.addCopyright(new GCopyright('Securitas',
				  new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)),
				  0, '©2009 Securitas'));

	// Create the tile layer overlay and 
	// implement the three abstract methods
	var tilelayer = new GTileLayer(myCopyright, mapMinZoom, mapMaxZoom);
	var mercator = new GMercatorProjection(mapMaxZoom + 1);

	tilelayer.getTileUrl = function(tile, zoom) {
		if ((zoom < mapMinZoom) || (zoom > mapMaxZoom)) {
			return "http://www.maptiler.org/img/none.png";
		}
		var ymax = 1 << zoom;
		var y = ymax - tile.y - 1;
		var tileBounds = new GLatLngBounds(
			mercator.fromPixelToLatLng(new GPoint((tile.x) * 256, (tile.y + 1) * 256), zoom),
			mercator.fromPixelToLatLng(new GPoint((tile.x + 1) * 256, (tile.y) * 256), zoom)
			);
		if (bounds.intersects(tileBounds)) {
			return "tiles/" + zoom + "/" + tile.x + "/" + y + ".jpg";
		} else {
			return "http://www.maptiler.org/img/none.png";
		}
	}
	// IE 7-: support for PNG alpha channel
	// Unfortunately, the opacity for whole overlay is then not changeable, either or...
	tilelayer.isPng = function() { return true; };
	tilelayer.getOpacity = function() { return 1; }

	overlay = new GTileLayerOverlay(tilelayer);
	map.addOverlay(overlay);

}
// Function to call the WebService that saves the coordinates to the page
function addCountryCoordinatesToPage(longitude, latitude, pageid, lang) {
	Securitas.Services.GoogleMapService.SetCoordinatesOnAddress(longitude,
			latitude, pageid, lang, handleCountryReturnValue);
}
function handleCountryReturnValue(returnvalue) {
	alert("Added: " + returnvalue);
}

function purge(d) {
	var a = d.attributes, i, l, n;
	if (a) {
		l = a.length;
		for (i = 0; i < l; i += 1) {
			n = a[i].name;
			if (typeof d[n] === 'function') {
				d[n] = null;
			}
		}
	}
	a = d.childNodes;
	if (a) {
		l = a.length;
		for (i = 0; i < l; i += 1) {
			purge(d.childNodes[i]);
		}
	}
}