//Global Variables
var allowedBounds;
var mapCenter;
var map;
var mapEle;
var maxWidth;
var maxHeight;
var minZoom;
var radiusInMiles;
var container;
var opacity;
var circle;
var circleCentre;
var centerMarker;
var circleUnits;
var circleRadius;
var autoZoom;
var autoCentre;
var horizontal;
var vertical;
var rightSide;
var leftSide;
var hideWorld;
//GV End

function MapMoveEnd(){
	var center = map.getCenter();
	//document.getElementById("message").innerHTML = center.toString();
	//document.getElementById("bounds").innerHTML =map.getBounds().toString();

	if(!allowedBounds.contains(center)){
		map.returnToSavedPosition();
	}else{
		map.savePosition();
	}
}//MapMoveEnd End

function MapZoomEnd(oldLevel,  newLevel){
	if(newLevel < minZoom)
		map.setZoom(minZoom);
		
	if(!allowedBounds.contains(map.getCenter())){
		map.returnToSavedPosition();
	}else{
		map.setCenter(circleCentre); // Note freaky spelling of centre
		map.savePosition();
		SMD();
	}
}//MapZoomEnd End

function MapClick(marker, point) {
    AutoCompleteClearTxtBs();
    drawCircle(point);
	var eastNorth =Transform(point.lat(),point.lng(),0);
	SetGLocation(eastNorth);
	SMD();	
}//MapClick End

function ChangeLocation(eastnorth){
	if (eastnorth + "" != "null" ) {
		var en = eastnorth.split(',');
		drawCircle(ne2ll(en[0],en[1]));
		map.setCenter(circleCentre);
	}
}

function MaximizeMap(){
	if(map.getSize().width < maxWidth){
			resizeMap();
	}else{
		map.checkResize();
	}
}//MaximizeMap End


function resizeMap(){
	var tempWidth;
	var tempHeight;
	var mapSize  = map.getSize();
	
	if(mapSize.width< maxWidth)
		tempWidth = mapSize.width + 20;
	
	if(mapSize.height < maxHeight)
		tempHeight = mapSize.height + 20;
	
	mapEle.style.width=tempWidth+'px';
	mapEle.style.height=tempHeight+'px';
	
	map.checkResize();
	mapSize = map.getSize();
	
	if(mapSize.width< maxWidth || mapSize.height < maxHeight)
		window.setTimeout(resizeMap,50);
}//resizeMap End

function load() {
  if (GBrowserIsCompatible()) {
	Init();

	mapCenter = new GLatLng(54.876606654108684, -4.39453125);
	map = new GMap2(document.getElementById("map"), {draggableCursor:"crosshair"});
	map.addControl(new GLargeMapControl());       
	map.setCenter(mapCenter, minZoom);
	map.savePosition();
    	
	GEvent.addListener(map, "moveend", MapMoveEnd);
	GEvent.addListener(map,"zoomend", MapZoomEnd);									
	GEvent.addListener(map, "click", MapClick);
	
	if(hideWorld)
		HideWorld();
		
	if(document.getElementById("LocationCoordinates").value.length > 0){
		try{
			ChangeLocation(document.getElementById("LocationCoordinates").value);
		}catch(err){
		}
	}
	
	
  }
}//load End

function resetZoom(){
	mapCenter = new GLatLng(54.876606654108684, -4.39453125);
	// NMG: Only pan if zoom level isn't changing as otherwise it looks odd.
	if (map.getZoom() == minZoom) {
		map.panTo(mapCenter);
	} else {
		map.setZoom(minZoom);
		map.setCenter(mapCenter);
	}
}

function resetMap(){
	mapCenter = new GLatLng(54.876606654108684, -4.39453125);
	// NMG: Only pan if zoom level isn't changing as otherwise it looks odd.
	if (map.getZoom() == minZoom) {
		map.panTo(mapCenter);
	} else {
		map.setZoom(minZoom);
		map.setCenter(mapCenter);
	}
	if (circle) map.removeOverlay(circle); 
	if (horizontal) map.removeOverlay(horizontal);
	if (vertical) map.removeOverlay(vertical);
	document.getElementById("LocationCoordinates").value = null;
	document.getElementById("LocationNameHiddenField").value = null
}

function Init(){
	//GUnload();
	/**Constants**/
	allowedBounds = new GLatLngBounds(new GLatLng(48.980216985374994, -10.986328125), new GLatLng(60.973107109199404, 2.197265625));
	mapEle = document.getElementById("map");
	minZoom = 5;
	opacity = 0.25;
	maxWidth = 780;
	maxHeight = 500;
	circle = null;
	circleCentre = null;
	radiusInMiles = document.getElementById('MapRadius').value;
	hideWorld = false; // Seems to not be working in IE8.

	LMD();
}

function SMD() {
	var latlng = mapCenter.lat()+","+mapCenter.lng();
	setCookie("mc",latlng, 1);
}

function LMD() {
//Load Map Center
		var mc = getCookie("mc");
		if(mc.length > 0){
			var t = mc.split(',');
			mapCenter = new GLatLng(t[0],t[1]);
		}else{
			mapCenter = new GLatLng(54.876606654108684, -4.39453125);
		}
//Load Autozoom value		
		var aZ = getCookie("aZ");
		if(aZ == 'false'){
			document.getElementById('autozoom').checked = autoZoom = false;
		}else{
			document.getElementById('autozoom').checked = autoZoom = true;
		}
//load Autocentre value
		var aC = getCookie("aC");
		if(aC == 'false'){
			document.getElementById('autocentre').checked = autoCentre = false;
		}else{
			document.getElementById('autocentre').checked = autoCentre = true;
		}
}
function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1){ 
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
	return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
return "";
}

function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}


function drawCircle(center) {
	circleRadius = radiusInMiles;

	//var center = point;
	if(allowedBounds.contains(center)){
	
		var circlePoints = Array();
		var bounds = new GLatLngBounds();
		
		with (Math) {
			var rLat = (circleRadius/3963.189) * (180/PI);
			var rLng = rLat/cos(center.lat() * (PI/180));

			for (var a = 0; a <= 360; a += 8) {
	
				var aRad = a*(PI/180);
				var x = center.lng() + (rLng * cos(aRad));
				var y = center.lat() + (rLat * sin(aRad));
				var point = new GLatLng(parseFloat(y),parseFloat(x));
				bounds.extend(point);
				circlePoints.push(point);
            }
        }

		
		if(autoZoom)
			map.setZoom(map.getBoundsZoomLevel(bounds)-1);

		if(autoCentre){
			map.panTo(center);
		}
		
		if (circle) map.removeOverlay(circle);
	
		//GPolygon			  (points,  strokeColor?,    strokeWeight?,strokeOpacity,fillColor,fillOpacity?)
		circle = new GPolygon(circlePoints,'#000000',1, opacity , '#ff0000', opacity);
		
		circleCentre = center;

		drawCross(center);
		 
		map.addOverlay(circle);
		
	}
}

function drawCross(point){
	var x = point.lng();
	var y = point.lat();
	var sw = allowedBounds.getSouthWest();
	var ne = allowedBounds.getNorthEast();
	/*GPolyline(points,  color?,  weight?,  opacity?)*/
	
	if (vertical) map.removeOverlay(vertical);
	if (horizontal) map.removeOverlay(horizontal);
	
	horizontal = new GPolyline([
			new GLatLng(y,sw.lng()-100),
			new GLatLng(y,ne.lng()+50)
		], "#ff0000", 1, 0.2);
	
	vertical = new GPolyline([
			new GLatLng(sw.lat()-50, x),
			new GLatLng(ne.lat()+50, x)
		], "#ff0000", 1, 0.2);
	map.addOverlay(vertical);
	map.addOverlay(horizontal);

}

function AutoZoom_Click(){
	autoZoom = document.getElementById('autozoom').checked;
	if(autoZoom){
		document.getElementById('autocentre').checked = true;
		autoCentre = true;
	}
	setCookie("aZ",autoZoom,1);
	setCookie("aC",autoCentre,1);
}
function AutoCentre_Click(){
	autoCentre = document.getElementById('autocentre').checked;
	if(!autoCentre){
		document.getElementById('autozoom').checked = false;
		autoZoom = false;
	}
	
	setCookie("aZ",autoZoom,1);
	setCookie("aC",autoCentre,1);
}

function radius_changed(rad){
	radiusInMiles = rad;
	if(circleCentre != null)
		drawCircle(circleCentre);
}

/*function ToggleWorld(){
	if(leftSide == null || rightSide == null){
		GetHiddenWorld();
	}else{
		if(document.getElementById("hideWorld").checked){
			map.addOverlay(rightSide);
			map.addOverlay(leftSide); 				
		}else{
			map.removeOverlay(leftSide); 
			map.removeOverlay(rightSide); 
		}
	}
}*/


function HideWorld(){
	GDownloadUrl("worldpolygon.xml", function(data, responseCode) {	
		var xml = GXml.parse(data);
		var left = xml.documentElement.getElementsByTagName("Left");
		var right = xml.documentElement.getElementsByTagName("Right");
		
		rightSide = ParsePolygon(right[0].childNodes);
		map.addOverlay(rightSide); 
		
		leftSide = ParsePolygon(left[0].childNodes);
		map.addOverlay(leftSide); 
	});	
}

function ParsePolygon(points){
	var worldPoints = Array();
	//alert(points.length);
	for (var i = 0; i < points.length; i++) {
		var p = points[i].text.split(',');
		var point = new GLatLng(parseFloat(p[0]),parseFloat(p[1]));
		worldPoints.push(point);
	}
	return new GPolygon(worldPoints,'#99B3CC',(map.getZoom()/17), 1 , '#99B3CC', 1);
}

