var loadCenter 	= [ 53.26267, -3.033105 ];
var maxZoom 	= 11;
var offsetZoom	= 6;
var currentZoom = 0;
var slidePos	= 0;

var zoomForce;

var map;
var ll;
var point;
var opts;
var marker;

var newIcon;
var normIcon;
var newMarketOpts;
var normMarketOpts;

var currentMarker = null;
var currentMarkerId = null;
var existingMarkers = [ ];

var xml;

var directions;

var searchLL;
var locationsProximity = [ ];
var locationsIds = [ ];

var branchId;
var branchLL;

var gotDirections = false;

function initMap () {
	map = new google.maps.Map2(document.getElementById('map'));
	
	map.setCenter(new google.maps.LatLng(loadCenter[0],loadCenter[1]),offsetZoom);
	map.disableDoubleClickZoom();
	map.disableScrollWheelZoom();
	//map.disableDragging();
	
	directions = new GDirections(map,document.getElementById('mapDirectionsContainer'));
	
	initControls();
	
	initXML();
	
}

function initControls () {
	$('#slider').slider({ 'steps': maxZoom, 'change': sliderMoved, 'min': 0, 'max': maxZoom });
	
	$('#zoomOut').bind('click',function () {
		slidePos--;
		
		doZoom(this);
				
	});
	
	$('#zoomIn').bind('click',function () {
		slidePos++;
		
		doZoom(this);
		
	});
	
	$('#moveLeft').bind('click',function () {
		map.panDirection(+1,0);
		
		this.blur();
		
	});
	
	$('#moveUp').bind('click',function () {
		map.panDirection(0,+1);
		
		this.blur();
		
	});
	
	$('#moveDown').bind('click',function () {
		map.panDirection(0,-1);
		
		this.blur();
		
	});
	
	$('#moveRight').bind('click',function () {
		map.panDirection(-1,0);
		
		this.blur();
		
	});
	
	$('#officeLocations').bind('click',function () {
		$('#enableOfficeLocations').each(toggleCheckBox);
		
		hideLocations();
		
		this.blur();
		
	});
	
	$('#newOfficeLocations').bind('click',function () {
		$('#enableNewOfficeLocations').each(toggleCheckBox);
		
		hideNewLocations();
		
		this.blur();
		
	});
	
	$('#mapControls input').bind('click',function () {
		$(this).each(toggleCheckBox);
		
	});
	
	$('#Monaco').bind('click',function () {
		showWindow(26);
	
	});
	
	$('#mapDirectionsClose').bind('click',function () {
		$('#mapDirectionsContainer').hide();
		
	});
	
	$('#mapDirectionsHref').bind('click',function () {
		showPostcodeWindow();
		
	});
	
}

function initXML () {
	$.get('data/locations.xml',null,parseXML,'xml');
	
}

function parseXML (d, s) {
	xml = d;
	
	createIcon();
	
	initMarkers();
	
	initLocations();
	
	$.getScript('include/custominfowindow.js');
	
}

function createIcon () {
	var size = new GSize(31,33);
	var anchor = new GPoint(15,33);
	var window = new GPoint(15,0);
	var loc = 'images/locations/points/';
	
	newIcon = new GIcon();
	normIcon = new GIcon();
		
	newIcon.image = loc + 'newpoint.png';
	newIcon.iconSize = size;
	newIcon.iconAnchor = anchor;
	newIcon.infoWindowAnchor = window;
	
	normIcon.image = loc + 'normpoint.png';
	normIcon.iconSize = size;
	normIcon.iconAnchor = anchor;
	normIcon.infoWindowAnchor = window;

	newMarketOpts = { 'icon': newIcon };
	normMarketOpts = { 'icon': normIcon };
	
}

function initMarkers () {
	$('office',xml).each(function (i) {
		ll = $(this).find('ll').text().split(',');
		point = new GLatLng(ll[0],ll[1]);
		opts = ($(this).find('openingdate').text() ? newMarketOpts : normMarketOpts);
		opts.title = $(this).find('officename').text() + ($(this).find('openingdate').text() ? ' (New office)' : '');
		marker = new GMarker(point,opts);
		
		existingMarkers.push(marker);
		
		GEvent.addListener(marker,'click',function () {	
			if (currentMarker !== null) {
				closeOverlay();
				
			}		
				
			this.overlay = new customWindow(this,generateInfoWindowContent(i));
			
			map.panTo(new GLatLng(this.getPoint().lat(), this.getPoint().lng()));
    		map.addOverlay(this.overlay);
			
			currentMarker = this;
			currentMarkerId = i;
			
			showContent(i);
			
			if (searchLL && gotDirections) {
				getDirections();
				
			}
			 
		});
		
		map.addOverlay(marker);
		
	});
	
}

function initLocations () {	
	$('.locationSearch').keypress(function (e) {
		if (e.which == 13) {
			doSearch(this);
			
		}
		
	});
	
	$('office',xml).each(function (i) {
		if ($(this).find('location').text() == 'uk') {
			$('#UKLocations').append('<li class="UKLocationsOffice"><a href="#map" onclick="showWindow(' + i + ')">' + $(this).find('officename').text() + '</a></li>');
			
		}
		
	});
	
	$('#tabs > ul').tabs();
	
	swfobject.embedSWF('include/locPanel.swf','flashSearchLocations','190','260','6.0.0');
	
}

function toggleCheckBox () {
	this.checked = !this.checked;
	
}

function hideNewLocations () {
	for (var i = 0; i < existingMarkers.length; i++) {
		if (existingMarkers[i].getTitle().indexOf('(New office)') != -1) {
			if (existingMarkers[i].isHidden()) {
				existingMarkers[i].show();
				
			} else {
				existingMarkers[i].hide();
				
			}
			
		}
		
	}
	
}

function hideLocations () {
	for (var i = 0; i < existingMarkers.length; i++) {
		if (existingMarkers[i].getTitle().indexOf('(New office)') == -1) {
			if (existingMarkers[i].isHidden()) {
				existingMarkers[i].show();
				
			} else {
				existingMarkers[i].hide();
				
			}
			
		}
		
	}
	
}

function sliderMoved (e, ui) {
	currentZoom = ui.value + offsetZoom; 
	slidePos = ui.value;
	
	if (!zoomForce) {
		map.setZoom(Math.round(currentZoom));
		
	} else {
		zoomForce = null;
		
	}
	
}

function doZoom (el) {
	$('#slider').slider('moveTo',slidePos);
		
	el.blur();

}

function showWindow (i) {
	GEvent.trigger(existingMarkers[i],'click');
	
}

function closeOverlay() {
	if (currentMarker) {
		map.removeOverlay(currentMarker.overlay);
		currentMarker.show();
		
		if (!arguments[0]) {
			$('#tabs div').html('Please select an office to see more information about it.');
			
		}
		
	}
	
	$('#postcodeContainer').hide();
	
}

function generateInfoWindowContent (i) {
	var content = $(xml).find('office').eq(i);
	var address = jQuery.trim(content.find('address').text());
	var html;
	
	html = '<div class="infoWindow"><div class="infoWindowBg" onclick="closeOverlay();"></div><a href="#map" onclick="closeOverlay()" class="infoWindowClose"></a><div class="infoWindowAddress">' +
		'<strong id="infoWindowOfficeName">' + content.find('officename').text() + '</strong><br /><span id="infoWindowOfficeAddress"> ' + address + '</span>, ' +
		'<span id="infoWindowOfficePostcode">' + content.find('postcode').text() + '</span><br /><a href="javascript:;" onclick="showPostcodeWindow();" class="infoWindowDirections">Get Directions</a>' +
		'<div class="infoWindowPhone"><div class="infoWindowPhoneNumber">Telephone: ' + content.find('telephone').text() + '</div></div></div></div>';
	
	return html;
	
}

function showContent (i) {
	var content = $(xml).find('office').eq(i); //$('office:nth-child(' + (i + 1) + ')',xml);
	
	$('#tab-1').html('<strong>About ' + content.find('officename').text() + '</strong><br /><br />' + content.find('officeinfo').text());
	$('#tab-2').html('<strong>Contact ' + content.find('officename').text() + '</strong><br /><br />' + 
						'Telephone: ' + content.find('telephone').text() + '<br />Facsimile: ' + content.find('fax').text() + 
						'<br /><br /><strong>Opening times</strong>: ' + content.find('openingtimes').text() + 
						'<br /><br /><strong>Counter service available</strong>: ' + (content.find('counter').text() == 'true' ? 'Yes' : 'No'));
	
	$('#tabs > ul').tabs('select',0);
	
}

function showPostcodeWindow () {
	if (currentMarkerId !== null) {
		closeOverlay(true);
	
		$('#postcodeContainer').show();
		$('#locationSearch2').focus();
		
	} else {
		alert('Please select a branch');
		
	}
	
}

function doSearch (f) {
	var val = $(f).val();
	
	gotDirections = false;
	
	if (val.length > 0) { 
		directions.clear();
		
		closeOverlay(($(f).attr('id') == 'locationSearch2' ? true : null));
		
		geocodePostCode(val,($(f).attr('id') == 'locationSearch2' ? 'geocode' : null));
		
	} else {
		alert('Please enter a valid UK postcode');
		
	}
	
}

function geocodePostCode (val) {
	var localSearch = new GlocalSearch();
        localSearch.setCenterPoint("uk"); 
	if (val.toLowerCase() != "monaco")
		val = val + " uk";
	var find = (arguments[1] == 'geocode' ? true : false);
	
	localSearch.setSearchCompleteCallback(null,function () {
		if (localSearch.results[0]) {
			searchLL = [ localSearch.results[0].lat, localSearch.results[0].lng ];
			
			if (find) {
				getDirections();
			
			} else { 
				findClosest();
				
			}
		
		} else {
			alert('Postcode not found');
		
		}
		
	});  
	
	localSearch.execute(val);
	
}

function findClosest () {
	var cal = new GLatLng(searchLL[0],searchLL[1]);
	
	locationsProximity = [ ];
	
	$('office',xml).each(function (i) {
		if ($(this).find('officename').text() != 'London Cavendish Square') {
			var latlng = $(this).find('ll').text().split(',');
			var val = cal.distanceFrom(new GLatLng(latlng[0],latlng[1]));
		
			val = Math.round(val / 100) / 10;
		
			locationsProximity.push(val);
		
			locationsIds[val] = i;
			
		}
		
	});
	
	locationsProximity.sort(function (a, b) {
		return a - b;
	
	});
	
	showWindow(locationsIds[locationsProximity[0]]);
	
}

function getDirections () {
	if (searchLL) {
		$(xml).find('office').eq(currentMarkerId).each(function(){
			branchLL = $(this).find('ll').text();
			
		});
		
		$('#mapDirectionsContainer').html('');
		
		directions.clear();
		
		closeOverlay(true);
		
		directions.load(searchLL[0] + ',' + searchLL[1] + ' to ' + branchLL);
		
		$('#mapDirectionsContainer').slideDown('normal');
		
		GEvent.addListener(directions,'addoverlay',setSliderPos);
		
		gotDirections = true;
		
	} else if ($('#locationSearch').val()) {
		doSearch($('#locationSearch'),'geocode'); 
			
	} else if (arguments[0] == 'force') {
		doSearch($('#locationSearch2'),'geocode'); 
	
	} else {
		alert('Please enter your postcode');
		
	}
	
}

function setSliderPos () {
	//GEvent.removeListener(setSliderPos);
	
	slidePos = map.getZoom() - offsetZoom;
	
	zoomForce = 'no';
	
	doZoom($('#map'));
	
}
