/*
===========================================
  Globals
=========================================== 
*/

var map = null;
var mapControl = null;
var breakout_zoom = 7;
var county_locations = assignLocations();
var sidepanel_list = new Array();

/*
===========================================
  	IMPORTANT:
	All the URLs below will changed on the
	live site, make sure to update them
=========================================== 
*/

var online_test_link = 'http://www.rsa.ie/RSA/Learner-Drivers/The-Driving-Test/Apply-online/';
var xml_source       = '../../../../Templates/RSA/xml/markers.xml';
var dtc_icon         = "../../../../Templates/RSA/Images/map_dtc_icon.png";
var ctc_icon         = "../../../../Templates/RSA/Images/map_vtn_icon.png";
var bullet           = "../../../../Templates/RSA/Images/bullet.png";
var icon_shadow      = "../../../../Templates/RSA/Images/map_icon_shadow.png"

/*
===========================================
  Initialise
=========================================== 
*/
$(
	function() {
		$(window).load(
			function () {
			}
		);
		
		// Insert the Map
		if ($('#map').length > 0) {
			insertMap();
		}
		
		if($('#showcounty').length > 0) {
			$('#showcounty').change(
				function() {
					showCounty($(this).val());
				}
			);
		}
		
		if($('.map-options input[type=radio]').length > 0) {
			$('.map-options input[type=radio]').bind(($.browser.msie ? "click" : "change"), 
				function () {
					checkZoom();
				}
			);
		}
	}
);

/*
===========================================
   Add the map to the page
=========================================== 
*/
function insertMap() {
	if (GBrowserIsCompatible()) {
		// Set the defaults for the Google Map
		map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(53.402982, -7.624512), 6);
		map.setUIToDefault();
		
		// Add a listener to wait for map zoom
		GEvent.addListener(map, "zoomend", function() {
			checkZoom();
		});

		// Load all the markers onto the map
		loadCountyMarkers();
		
		// Trigger the page unload function
		$(window).unload(
			function () { 
				GUnload();
			} 
		);
	}
}

/*
===========================================
  Load the test centres from the XML file
=========================================== 
*/
function loadTestCentres(sidepanel) {
	if (sidepanel === undefined) 
	{
		sidepanel = $('#showcounty').val();
		if(sidepanel != '')
			sidepanel_list.length = 0;
	}
	else
	{
		sidepanel_list.length = 0;
	}

	$.ajax({
	    type: "GET",
	    url: xml_source,
	    cache: false,
	    dataType: "xml",
	    success: function(xml) {
	        map.clearOverlays();
	        var centre_type = checkCentreType();

	        $(xml).find('marker').each(function() {
	            var current_type = $(this).find('centretype').text();

	            if (current_type == centre_type) {
	                // Set the store location
	                var storeLocation = new GLatLng($(this).find('latitude').text(), $(this).find('longitude').text());

	                // Get the store details
	                var name = $(this).find('name').text();
	                var myRegExp = new RegExp("'","g"); 
	                name = name.replace(myRegExp, "-");
	                myRegExp = new RegExp("\"","g"); 
	                name = name.replace(myRegExp, "");
	                var address1 = $(this).find('address1').text();
	                myRegExp = new RegExp("'","g"); 
	                address1 = address1.replace(myRegExp, "-");
	                myRegExp = new RegExp("\"","g"); 
	                address1 = address1.replace(myRegExp, "");
	                var address2 = $(this).find('address2').text();
	                myRegExp = new RegExp("'","g"); 
	                address2 = address2.replace(myRegExp, "-");
	                myRegExp = new RegExp("\"","g"); 
	                address2 = address2.replace(myRegExp, "");
	                var address3 = $(this).find('address3').text();
	                myRegExp = new RegExp("'","g"); 
	                address3 = address3.replace(myRegExp, "-");
	                myRegExp = new RegExp("\"","g"); 
	                address3 = address3.replace(myRegExp, "");
	                var phone = $(this).find('telephone').text();
	                var county = $(this).find('county').text();
	                var wait = $(this).find('wait').text();
	                var pass = $(this).find('pass').text();
	                var cat1 = $(this).find('cat1').text();
	                var cat2 = $(this).find('cat2').text();
	                var cat3 = $(this).find('cat3').text();

	                // Setup a new icon
	                var icon = new GIcon();

	                // Set icon image depending on type of test centre
	                if (centre_type == 'dtc')
	                    icon.image = dtc_icon;
	                else
	                    icon.image = ctc_icon;

	                // Other settings including icon shadow
	                icon.shadow = icon_shadow;
	                icon.iconSize = new GSize(20, 29);
	                icon.shadowSize = new GSize(38, 29);
	                icon.iconAnchor = new GPoint(10, 29);
	                icon.infoWindowAnchor = new GPoint(10, 1);

	                // Add an event listener to the marker
	                var marker = new GMarker(storeLocation, icon);

	                // Create the HTML for the marker
	                var html = '<div class="marker-details"><h1>' + name + '</h1><p>';
	                if (address1 != '') html += address1;
	                if (address2 != '') html += '<br />' + address2;
	                if (address3 != '') html += '<br />' + address3;
	                if (phone != '') html += '<br /><strong>Telephone:</strong> ' + phone;
	                if (wait != '') html += '<br /><img src="' + bullet + '" /> <strong>Waiting Time:</strong> ' + wait + ' weeks';
	                if (pass != '') html += '<br /><img src="' + bullet + '" /> <strong>Pass Rate:</strong> ' + pass;

	                if (centre_type == 'dtc') {
	                    html += '<br /><img src="' + bullet + '" /> <a href="' + online_test_link + '">Apply for your test online</a><br /><img src="' + bullet + '" /> <a href="#" onclick="window.print(); return false;">Print this map</a>';
	                }
	                else {
	                    html += '<br /><strong>Type of Test:</strong>';

	                    if (cat1 == 'Yes') {
	                        html += ' ADR ';
	                    }
	                    if (cat2 == 'Yes') {
	                        html += ' HGV ';
	                    }
	                    if (cat3 == 'Yes') {
	                        html += ' LGV ';
	                    }

	                    $(this).find('testtypes type').each(function() {
	                        html += '<br /><img src="' + bullet + '" /> ' + $(this).text();
	                    });
	                }

	                html += '</p></div>';

	                // Add an onclick event to the marker
	                GEvent.addListener(marker, "click", function() {
	                    marker.openInfoWindowHtml(html);
						 if (centre_type == 'dtc')
	                    	pgView('/virtual/Contact-Us/Driving-Test-Centres/map/county-'+county_locations[county][2].toLowerCase()+'/centre-'+name.toLowerCase());
		                else
							pgView('/virtual/Contact-Us/CVT-Centres/map/county-'+county_locations[county][2].toLowerCase()+'/centre-'+name.toLowerCase());
	                });

	                // Assign this to the sidepanel if it's in the county required
	                if (sidepanel != 0 && county == sidepanel)
	                    sidepanel_list[sidepanel_list.length] = new Array(name, address1, address2, address3, marker, html, county, centre_type);

	                // Add the marker to the map						
	                map.addOverlay(marker);
	            }
	        });
	        populateSidepanel();
	    }
	});	
}

/*
===========================================
  Load just county markers
=========================================== 
*/
function loadCountyMarkers() {
	$.ajax({
		type: "GET",
		url: xml_source,
		cache: false,
		dataType: "xml",
		success: function(xml) {
			map.clearOverlays();
			var county_count = new Array();
			var centre_type  = checkCentreType();

			$(xml).find('marker').each(function() {
				// Get the county
				var county = $(this).find('county').text();
				var current_type = $(this).find('centretype').text();
				
				if(current_type==centre_type)
				{
					if(county_count[county] == undefined)
						county_count[county] = 1;
					else
						county_count[county] += 1;
				}
			});
			plotCountyMarkers(county_count);
		}
	});
}

/*
===========================================
  Load just county markers
=========================================== 
*/

function plotCountyMarkers(county_count)
{
	// Setup a new icon
	var icon = new GIcon();
	var count = 0;
	
	// Get the type of icon to display
	var centre_type = checkCentreType();
	if (centre_type == 'dtc')
		icon.image = dtc_icon;
	else
		icon.image = ctc_icon;
	
	// Other settings including icon shadow
	icon.shadow = icon_shadow;
	icon.iconSize = new GSize(20, 29);
	icon.shadowSize = new GSize(38, 29);
	icon.iconAnchor = new GPoint(10, 29);
	icon.infoWindowAnchor = new GPoint(10, 1);
	
	// Get the total number of counties to map
	var count = county_count.length;
	
	for (key in county_count) {
		// Set the LatLong of the county
		var countyLocation = new GLatLng(county_locations[key][0],county_locations[key][1]);
		// Set the title text of the marker
		var centre_text = county_count[key]==1 ? 'Centre' : 'Centres';
		var title = county_locations[key][2]+': '+county_count[key]+' Test '+centre_text;
		// Add an event listener to the marker
		var marker = new GMarker(countyLocation,{icon: icon, title: title});
		
		GEvent.addListener(marker, "click",
			(function(key) {
				return function() {
					// Zoom to county
					showCounty(key);
					if (centre_type == 'dtc')
						pgView('/virtual/Contact-Us/Driving-Test-Centres/map/county-'+county_locations[key][2].toLowerCase()+'/centre-zoom');
					else
						pgView('/virtual/Contact-Us/CVT-Centres/map/county-'+county_locations[key][2].toLowerCase()+'/centre-zoom');
				};
			})(key)
		);
		
		// Add the marker to the map
		map.addOverlay(marker);
	}
}

/*
===========================================
  Function to show specific counties
=========================================== 
*/

function showCounty(county)
{
	if(county!='')
	{
		var zoom = map.getZoom();
		if(zoom!=8)
			map.setZoom(8);
		else
			loadTestCentres(county);
		map.setCenter(new GLatLng(county_locations[county][0],county_locations[county][1]));
	}
}

/*
===========================================
  Show different icon types depending on zoom
=========================================== 
*/

function checkZoom()
{
	var zoom = map.getZoom();
	if(zoom >= 8)
		loadTestCentres();
	else
		loadCountyMarkers();
}

/*
===========================================
  Check what kind of test centres to show
=========================================== 
*/

function checkCentreType()
{
	var selected = $('.map-options input:checked').attr('id');
	if (selected == 'rsa-testcentre')
		return 'dtc';
	else
		return 'ctc';
}

/*
===========================================
  Lash the test centres into the sidepanel
=========================================== 
*/
function populateSidepanel()
{
	var total_centres = sidepanel_list.length;
	var liClass = '';
	
	if(total_centres > 0)
	{
		var centre_html = '<ul>';
		for(i=0;i<total_centres;i++)
		{
			liClass = (i%2==0) ? ' class="even"' : '';
			centre_html += '<li'+liClass+'><a href="#" id="sp'+i+'" onclick="showCentre('+i+');';
			if (sidepanel_list[i][7]=='dtc')
				centre_html += ' pgView(\'/virtual/Contact-Us/Driving-Test-Centres/dropdown/county-'+county_locations[sidepanel_list[i][6]][2].toLowerCase()+'/centre-'+sidepanel_list[i][0].toLowerCase()+'\');';
			else
				centre_html += ' pgView(\'/virtual/Contact-Us/CVT-Centres/dropdown/county-'+county_locations[sidepanel_list[i][6]][2].toLowerCase()+'/centre-'+sidepanel_list[i][0].toLowerCase()+'\');';
			centre_html += ' return false;"><h3>'+sidepanel_list[i][0]+'</h3><p>';
			if(sidepanel_list[i][1]!='') centre_html += sidepanel_list[i][1];
			if(sidepanel_list[i][2]!='') centre_html += ', '+sidepanel_list[i][2];
			if(sidepanel_list[i][3]!='') centre_html += ', '+sidepanel_list[i][3];
			centre_html += '</p></a></li>';
		}
		centre_html += '</li>';
		$('#map-locations').html(centre_html);
	}
}

/*
===========================================
  Pop open the Test Centre
=========================================== 
*/

function showCentre(i)
{
	sidepanel_list[i][4].openInfoWindowHtml(sidepanel_list[i][5]);
}

/*
===========================================
  Assign counties to array
=========================================== 
*/

function assignLocations()
{
	var a = new Array();
	a[1]  = new Array(53.33395522745,-6.272611661,'Dublin');
	a[2]  = new Array(53.65002736,-6.68038649267,'Meath');
	a[3]  = new Array(53.1584612880,-6.90632871966,'Kildare');
	a[4]  = new Array(52.9762654725,-6.0451768411187,'Wicklow');
	a[5]  = new Array(53.7273798444,-7.79358941406,'Longford');
	a[6]  = new Array(53.096040595,-7.908538857467,'Offaly');
	a[7]  = new Array(53.524338231,-7.342952742,'Westmeath');
	a[8]  = new Array(53.0390439834,-7.29400750362,'Laois');
	a[9]  = new Array(53.717047,-6.349113585,'Louth');
	a[10] = new Array(52.8344881467682864,-6.9186402001592,'Carlow');
	a[11] = new Array(52.6534668367059717,-7.2480053748417,'Kilkenny');
	a[12] = new Array(52.2506772464,-7.1118272939,'Waterford');
	a[13] = new Array(52.33380127767,-6.47231964887,'Wexford');
	a[14] = new Array(52.27266432377,-9.70207581,'Kerry');
	a[15] = new Array(51.8928466,-8.4662617539984,'Cork');
	a[16] = new Array(52.845066787529,-8.984881619132,'Clare');
	a[17] = new Array(52.6584631285742,-8.624995459,'Limerick');
	a[18] = new Array(52.35862389252,-7.70717318,'Tipperary');
	a[19] = new Array(53.277184502,-9.05647148783695,'Galway');
	a[20] = new Array(53.85722137523,-9.29829184392,'Mayo');
	a[21] = new Array(53.76599258834,-8.4902629975,'Roscommon');
	a[22] = new Array(54.269413793188,-8.474957035,'Sligo');
	a[23] = new Array(53.9503715558,-8.0878817580,'Leitrim');
	a[24] = new Array(54.65479716457,-8.1098959344472,'Donegal');
	a[25] = new Array(53.992247327311,-7.3593206748,'Cavan');
	a[26] = new Array(54.2449336845,-6.970013354848,'Monaghan');
	return a;
}
