$(document).ready(function() {

	$("#map-container").prepend('<div class="loading">'+
		'<img src="includes/images/bg_loading.gif" width="16" height="16" alt="">'+
		'</div>');

  	var iconCoal = new GIcon(); 
    iconCoal.image = '/includes/images/maps_images/town.png';
    iconCoal.shadow = '';
    iconCoal.iconSize = new GSize(12, 12);
    iconCoal.shadowSize = new GSize(22, 20);
    iconCoal.iconAnchor = new GPoint(16, 16);
    iconCoal.infoWindowAnchor = new GPoint(5, 1);

    var iconFreight = new GIcon(); 
    iconFreight.image = '/includes/images/maps_images/town.png';
	iconFreight.shadow = '';
    iconFreight.iconSize = new GSize(12, 12);
    iconFreight.shadowSize = new GSize(22, 20);
    iconFreight.iconAnchor = new GPoint(16, 16);
    iconFreight.infoWindowAnchor = new GPoint(5, 1);
	
    var iconSEQ = new GIcon(); 
    iconSEQ.image = '/includes/images/maps_images/town.png';
	iconSEQ.shadow = '';
    iconSEQ.iconSize = new GSize(12, 12);
    iconSEQ.shadowSize = new GSize(22, 20);
    iconSEQ.iconAnchor = new GPoint(16, 16);
    iconSEQ.infoWindowAnchor = new GPoint(5, 1);
	
    var iconInterstate = new GIcon(); 
    iconInterstate.image = '/includes/images/maps_images/town.png';
	iconInterstate.shadow = '';
    iconInterstate.iconSize = new GSize(12, 12);
    iconInterstate.shadowSize = new GSize(22, 20);
    iconInterstate.iconAnchor = new GPoint(16, 16);
    iconInterstate.infoWindowAnchor = new GPoint(5, 1);
	
	
    var customIcons = [];
    customIcons["coal"] = iconCoal;
    customIcons["freight"] = iconFreight;
	customIcons["seq"] = iconSEQ;
	customIcons["interstate"] = iconInterstate;

    var markerGroups = { "coal": [], "freight": [], "seq": [], "interstate": [] };						   
	
	//CHECKS ALL BOX AT READY
	$('#coalCheckbox').attr('checked', 'checked');
	$('#freightCheckbox').attr('checked', 'checked');
	$('#seqCheckbox').attr('checked', 'checked');
	$('#interstateCheckbox').attr('checked', 'checked');
						   
     if (GBrowserIsCompatible()) {
		// Create map
		var lat = -23;
		var lng = 147;
		var initialZoom = 5; // Initial zoom level
		var disableZoom = true;

        var map = new GMap2(document.getElementById("map-homepage"), {backgroundColor:"#cccccc"}); // blue graident colour = #428bab

		map.setMapType(G_PHYSICAL_MAP);
		if (disableZoom) {
			map.disableDoubleClickZoom();	
		}
		
		if ((singleSegment != "showSEQOnly")) {
			var copyright = new GCopyright(1,
			  new GLatLngBounds(new GLatLng(-29.693143, 137.526855),new GLatLng(-9.541527, 156.621094) ), 
			  0, "&copy; QR Network");
		
			var copyrightCollection = new GCopyrightCollection('Map Data:');
			copyrightCollection.addCopyright(copyright);
	
			CustomGetTileUrl=function(a,b){
				if (b>=5 && b<=9) { // check zoom level
				
					var xMin = (25*(Math.pow(2,b-1))/16);
					var xMax = (29*(Math.pow(2,b-1))/16);
					var yMin = (16*(Math.pow(2,b-1))/16);
					var yMax = (20*(Math.pow(2,b-1))/16);
					
					if (b > 5) {
						xMax+=Math.pow(2,b-3);
						yMax+=Math.pow(2,b-3);
					}
				
					if (a.x>=xMin && a.x<=xMax && a.y>=yMin && a.y<=yMax) { // check location
						return "/includes/images/maps_images/Tiles5-9/"+b+"_"+a.x+"_"+a.y+".jpg";
					} else {
						return "/includes/images/maps_images/Tiles5-9/_blank.jpg";
					}
				} else {
					return G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
				}
			}
			
			var tilelayers = [new GTileLayer(copyrightCollection,5,9)];
			tilelayers[0].getTileUrl = CustomGetTileUrl;
	
			var custommap = new GMapType(tilelayers, new GMercatorProjection(15), "Old OS");
			map.addMapType(custommap);	
			
		}
		
		
		switch(singleSegment){
			case "showCoalOnly":
				lng = 150;
				initialZoom = 6;
				break;
			case "showFreightOnly":
				break;
			case "showSEQOnly":
				lat = -27.484517;
				lng = 153.023758;
				initialZoom = 10;
				map.setMapType(G_PHYSICAL_MAP);				
				G_PHYSICAL_MAP.getMaximumResolution  = function(){return 12};	
				break;
			case "showInterstateOnly":
				lat = -28.08817978175534;
				lng = 152.8365448780399;
				initialZoom = 8;			
				break;
			default:
				lat = -23;
				lng = 147;
				initialZoom = 5; // Initial zoom level
				break;
		}				
		
		map.setCenter(new GLatLng(lat, lng), initialZoom, custommap);

		// Add markers
		PlotXMLmarkers();	
		
		$(window).load(function() {
			// Add polygons
			addPolygons();								

			var t=setTimeout(function(){
				$("#map-container .loading").hide();	
				clearTimeout(t);
			} ,1500);
			
		});		
	
	}else{
		alert("You are using an older internet browser which does not support QR Network maps.");
	}

	//Plots the systems according to market
	function PlotXMLmarkers(){ 
		GDownloadUrl("/includes/xml/Systems/all.xml.axd", function(data) {
	//	GDownloadUrl("includes/xml/maps-systemsList.xml", function(data) {
			var xml = GXml.parse(data);
			var markers = xml.documentElement.getElementsByTagName("marker");
			
			for (var i = 0; i < markers.length;  i++) {
				if(markers[i].getAttribute("lat")=="" || markers[i].getAttribute("lng")==""){
						continue;
				}
				var id = markers[i].getAttribute("id");
				var name = markers[i].getAttribute("name");
				var label = markers[i].getAttribute("label");
				var address = markers[i].getAttribute("address");
				var type = markers[i].getAttribute("type");
				var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
										parseFloat(markers[i].getAttribute("lng")));
				FFcontent = markers[i].textContent;
				IEcontent = markers[i].text;
				
				// Only add relevant markers
				if ((singleSegment=="") || (singleSegment.toLowerCase()=="show"+type.toLowerCase()+"only")) {
					var marker = createMarker(point, name, label, address, type, id);
					map.addOverlay(marker);
				}				
			}
		});
	}//PlotXMLmarkers END		
	
	//CreateMarkers
	function createMarker(point, name, label, address, type, id) {
		var labelClass = type + "_label"
		var marker= new LabeledMarker(point, {icon: customIcons[type], labelText: label, labelVisibility: true, labelClass: labelClass,  labelOffset: new GSize(-20, -16)});
		markerGroups[type].push(marker);
		
		if (IEcontent == undefined){ 
			var html = FFcontent;
		}else{
			var html = IEcontent;
		}	  
		
		GEvent.addListener(marker, 'click', function() {
			anyOpen = true;
			this.openExtInfoWindow(
			  map,
			  "popup_window",
			  html
			  //{beakOffset: 3}
			);//openExtInfoWindow END
		});//Event Listener "Click" END	  
		
		return marker;
	}//CreateMarker END	  
	
	function addPolygons(){
		switch(singleSegment){
			case "showCoalOnly":
				map.addOverlay(polygon_Moura);
				map.addOverlay(polygon_Blackwater);
				map.addOverlay(polygon_Newlands);
				map.addOverlay(polygon_Goonyella);
				break;
			case "showFreightOnly":
				map.addOverlay(polygon_Western);
				map.addOverlay(polygon_SouthWestern);
				map.addOverlay(polygon_MaryboroughArea);
				map.addOverlay(polygon_CentralWest);
				map.addOverlay(polygon_MtIsa);
				map.addOverlay(polygon_NorthCoastLine1);
				map.addOverlay(polygon_NorthCoastLine2);
				map.addOverlay(polygon_NorthCoastLine3);
				map.addOverlay(polygon_NorthCoastLine4);
				map.addOverlay(polygon_Tablelands);
				break;
			case "showSEQOnly":
//				map.addOverlay(polygon_SEQ);
				break;
			case "showInterstateOnly":
				//map.addOverlay(polygon_Interstate);
				break;
			default:
				map.addOverlay(polygon_Western); // western
				map.addOverlay(polygon_Moura); // moura
				map.addOverlay(polygon_Blackwater); // blackwater
				map.addOverlay(polygon_Newlands); // newlands
				map.addOverlay(polygon_Goonyella); // goonyella
				map.addOverlay(polygon_SouthWestern); // south western
				map.addOverlay(polygon_MaryboroughArea); // maryborough area
				map.addOverlay(polygon_CentralWest); // central west
				map.addOverlay(polygon_MtIsa); // mt isa
				map.addOverlay(polygon_NorthCoastLine1); // north coast line 1
				map.addOverlay(polygon_NorthCoastLine2); // north coast line 2
				map.addOverlay(polygon_NorthCoastLine3); // north coast line 3
				map.addOverlay(polygon_NorthCoastLine4); // north coast line 4
				map.addOverlay(polygon_Tablelands); // north coast line 5
				map.addOverlay(polygon_SEQ); // seq
				map.addOverlay(polygon_Interstate); // interstate
				break;
		}			
	}
	
	//CHECKBOX Turns each group type on and off//
	function toggleGroup(type) {
		anyOpen = false;
		for (var i = 0; i < markerGroups[type].length; i++) {
			var marker = markerGroups[type][i];
			if (marker.isHidden()) {
			  marker.show();
			  showPolygons(type);
			} else {
			  marker.hide();
			  hidePolygons(type);
			  map.closeExtInfoWindow();
			}
		}
	}
	
	//Gets type from Checkbox toggle click and shows or greys lines according to group//
	function showPolygons(type){
		switch(type) {
			case "coal":
			map.addOverlay(polygon_Newlands);
			map.addOverlay(polygon_Goonyella);
			map.addOverlay(polygon_Blackwater);
			map.addOverlay(polygon_Moura);
			
				break;  
			case "freight":
			map.addOverlay(polygon_Western);
			map.addOverlay(polygon_SouthWestern);
			map.addOverlay(polygon_MaryboroughArea);
			map.addOverlay(polygon_CentralWest);
			map.addOverlay(polygon_MtIsa);
			map.addOverlay(polygon_NorthCoastLine1);
			map.addOverlay(polygon_NorthCoastLine2);
			map.addOverlay(polygon_NorthCoastLine3);
			map.addOverlay(polygon_NorthCoastLine4);
			map.addOverlay(polygon_Tablelands);
				break;
			case "seq":
			map.addOverlay(polygon_SEQ);
				break;  
			case "interstate":
			map.addOverlay(polygon_Interstate);
				break;   
		}
	}
	
	function hidePolygons(type){
		switch(type) {
			case "coal":
				
				map.removeOverlay(polygon_Moura);
				map.removeOverlay(polygon_Blackwater);
				map.removeOverlay(polygon_Newlands);
				map.removeOverlay(polygon_Goonyella);
				break;    
			case "freight":
				map.removeOverlay(polygon_Western);
				map.removeOverlay(polygon_SouthWestern);
				map.removeOverlay(polygon_MaryboroughArea);
				map.removeOverlay(polygon_CentralWest);
				map.removeOverlay(polygon_MtIsa);
				map.removeOverlay(polygon_NorthCoastLine1);
				map.removeOverlay(polygon_NorthCoastLine2);
				map.removeOverlay(polygon_NorthCoastLine3);
				map.removeOverlay(polygon_NorthCoastLine4);
				map.removeOverlay(polygon_Tablelands);
				break;
			case "seq":
				map.removeOverlay(polygon_SEQ);
				break;  
			case "interstate":
				map.removeOverlay(polygon_Interstate);
				break;   
		}
	}

	$("#coalCheckbox").click(function(){
		toggleGroup("coal"); 
	});
	
	$("#freightCheckbox").click(function(){
		toggleGroup("freight");
	});
	
	$("#seqCheckbox").click(function(){
		toggleGroup("seq");
	});
	
	$("#interstateCheckbox").click(function(){
		toggleGroup("interstate");
	});
	//CHECKBOX & TOGGLE END//
	
	//When the 'close' button in the popup box is hit, close all popup windows
	$("#btn-closePopup").click(function(){
		map.closeExtInfoWindow();
	});

});
