var map = null;	
var points = [];
var venues = [];
var venueList = [];
var filteredList = [];
var mapLoaded = false
var siteRoot = "../";
var siteMapImagesRoot = "../i/map/";
var activeMarkers = [];
var batch = [];
var mgr = null;
var mIcon = new GIcon(G_DEFAULT_ICON);

// Init - Stuff to do on page load
jQuery(document).ready(function(){                     });



function showMapDetails(venueID)	{
	$.get(
		"/content/venueDetails.asp", 
		 {	venueID: venueID, fromType: 'map' 	},
		 function(data){	
			jQuery("#mapDetails").css( 'display', 'block' );
			jQuery("#mapDetails").html( data );

			// google tracking
			var title = data.match(/<h3.*>(.*)<\/h3>/);
			//alert('/venueDetails/' + title[1]);
			pageTracker._trackPageview('/mapDetails/' + title[1])
		}
	);
}



function getVenuesForRegion(region)	{

	$('.loading').css('display', 'block');

	$.getJSON("mapJSON.asp",	{	region: region	}, function(venuesObj){
		venueList = venuesObj.Venues;
		// catch no results
		if (venueList.length == 0)		{
			alert('no results found, please refine your search and try again');
		}	else	{
			createMarkers(venueList);
		}
	});
}

function checkField(dbVal, formVal)	{
	if (formVal == 1)	{
		if (dbVal == 1)		{
			return true;
		}	else	{
			return false;
		}
	}	else	{
		// not ticked in the form so always ok
		return true;
	}
}

function filterVenues()	{

	quaMin = $('#qualityMapMin').val();
	quaMax = $('#qualityMapMax').val();
	deMin = $('#delegateMapMin').val();
	deMax = $('#delegateMapMax').val();

	cCent = $('#chkConference').attr('checked') ? 1 : 0;
	uVen = $('#chkUnusual').attr('checked') ? 1 : 0;
	uExc = $('#chkExclusive').attr('checked') ? 1 : 0;
	cExc = $('#chkExcellence').attr('checked') ? 1 : 0;
	vRes = $('#chkResidential').attr('checked') ? 1 : 0;
	hoRe = $('#chkHotels').attr('checked') ? 1 : 0;



	// Need to default to all on
	// If user click box then all that meet the criteria need to be displayed
	filteredList = [];

	if (cCent == 1 || uVen == 1 || uExc == 1 || cExc == 1 || vRes == 1 || hoRe == 1)	{
		strEval = '';
		cCent == 1 ? strEval += 'cCent == venue.cCent || ' : '';
		uVen == 1 ? strEval += 'uVen == venue.uVen || ' : '';
		uExc == 1 ? strEval += 'uExc == venue.uExc || ' : '';
		cExc == 1 ? strEval += 'cExc == venue.cExc || ' : '';
		vRes == 1 ? strEval += 'vRes == venue.vRes || ' : '';
		hoRe == 1 ? strEval += 'hoRe == venue.hoRe || ' : '';

		strEval = strEval.substring(0, strEval.length - 4);
	}	else	{
		strEval = 'true == true'
	}

	$.each(venueList, 
		function(i, venue){
			//$('#mapDetails').html(strEval + ' - ' + eval(strEval));
			if (((venue.stars >= quaMin) && (venue.stars <= quaMax)) && ((venue.totalD >= deMin) && (venue.totalD <= deMax)) && (eval(strEval)))	{
				filteredList.push(venue);
			}
		}
	);

	if (filteredList.length == 0)		{
		$.each(activeMarkers, 
			function(i, marker){	map.removeOverlay(marker);	}
		);
		alert('no results found, please refine your search and try again');
	}	else	{
		createMarkers(filteredList);
	}
	
}

// Init the map 
function initialize() {
	if (GBrowserIsCompatible()) {
		// Create google map object
		map = new GMap2(document.getElementById("map_canvas"));
		// Set default location 
		map.setCenter(new GLatLng(55.858358, -4.264755), 11);
		// Size control
		map.addControl(new GLargeMapControl3D());
		// The little overview map
		//map.addControl(new GOverviewMapControl(new GSize(166, 100)));

		// Add markers to the map
		//createMarkers();

		// scale to fit 
		//fitMap(map, points);

		// Try to speed up adding loads of markers
		mgr = new MarkerManager(map);

	}
}


function createMarkers(vList)	{

	// Clear out our arrays ready for our next lot of points
	activeMarkers = [];
	points = [];
	batch = [];

	$.each(vList, 
		function(i, venue){	createMarker(venue.mapLoc.lat, venue.mapLoc.lng, venue.vName, venue.vID);	}
	);

	// clear old
	mgr.clearMarkers()
	// add new
	mgr.addMarkers(batch, 0);
	// show
	mgr.refresh();

	fitMap(map, points);

	$('.loading').css('display', 'none');
}


function createMarker(Lat, Lng, title, id)	{

	var mOptions = { icon: mIcon, title : title };
	var mLoc = new GLatLng(Lat, Lng);

	// list of points so we can fit the points to the map window
	points.push(mLoc)

	var mMarker = new GMarker(mLoc, mOptions);
	batch.push(mMarker);

	GEvent.addListener(mMarker, "click", function() {
		this.id = id;
		showMapDetails(this.id);
	});

	// list of markers so we can remove them again when needed
	activeMarkers.push(mMarker);
}



function starChange()	{
	stars = $('select#quality').val();
	filterVenues();
}

function mapToGallery()	{
	$("#mapApp").slideUp("slow");
	if (!$("#highlight").hasClass('noDisplay'))	{		
		$("#mapApp").queue(function () {
			jQuery("#highlight").slideDown("slow");
			jQuery("#mapApp").dequeue();
		});
	}
}

function viewGoogleMap()	{
	// First remove the highlight if it exists


	if ($("#highlight").hasClass('noDisplay'))	{		$("#highlight").slideUp("slow");	}
	
	$("#highlight").queue(function () {
		jQuery("#highlight").css('display', 'none');
		$('#region-select').css('display', 'block');


		jQuery("#mapApp").css('display', 'block');
		$("#mapApp").slideDown("slow");

		// Squirt in the new one
		$("#mapApp").queue(function () {
			$.get(
				"/content/mapRegionChooser.asp", 
				 {	},
				 function(data){	
					// Squirt the map holder html into our page 
					jQuery("#mapApp").html(data);
				 }
			);
		});

		jQuery("#mapApp").dequeue();
		jQuery("#highlight").dequeue();
		
		
	});
}


function mapApp(region)	{

	// can be called from the form
	if (region == -1)	{
		region = $("input[name='chk-Regions']:checked").val();
	}
	
	//alert(region);
	//return true;

	$("#mapApp").queue(function () {
		$.get(
			"/content/mapApp.asp", 
			 {	venueID: region	},
			 function(data){	

				//alert(data);

				// Squirt the map holder html into our page 
				jQuery("#mapApp").html(data);


				// Quality slider
				/*
				sliDelegate = $('select#qualityMapMin, select#qualityMapMax').selectToUISlider({	labels: 0,	steps: 6, max: 6, min: 0,	sliderOptions: {
					change:function(e, ui) {
						filterVenues();
					} 
				}}).next();
				$('#qualityMapMin').css('display', 'none');
				$('#qualityMapMax').css('display', 'none');
				*/


				// Deligate slider
				sliDelegate = $('select#delegateMapMin, select#delegateMapMax').selectToUISlider(	{	labels: 0,	steps: 100, max: 100, min: 0,	sliderOptions: {
					change:function(e, ui) {
						filterVenues();
					} 
				}}).next();
				$('#delegateMapMin').css('display', 'none');
				$('#delegateMapMax').css('display', 'none');
				
				

				// Fire up the google map code
				initialize();

				// Grab our venues array
				getVenuesForRegion(region);
				//createMarkers(venueList);


				//alert(region);
				$('#mapArea').val(region);

			 }
		);
	});

	jQuery("#mapApp").dequeue();
	jQuery("#highlight").dequeue();
}


function playPauseGallery()	{
	if (jQuery('#playPause').attr('src').indexOf('pause') == -1)	{
		// is paused now so play
		interval = setInterval("galleryNext(false)", 5000);
		jQuery('#playPause').attr('src','../i/galleryNav_pause.gif');
	}	else	{
		// is playing so pause
		clearInterval(interval);
		jQuery('#playPause').attr('src','../i/galleryNav_play.gif');
	}
}

function toggleGroup(type) {
	for (var i = 0; i < markers[type].length; i++) {
		var marker = markers[type][i];
		if (marker.isHidden()) {
		  marker.show();
		} else {
		  marker.hide();
		}
	} 
}

function changeMapDisplayType(toWhich)	{
	// reset styles
	jQuery('#G_NORMAL_MAP').attr('class','');
	jQuery('#G_SATELLITE_MAP').attr('class','');
	jQuery('#G_PHYSICAL_MAP').attr('class','');

	// set active
	jQuery('#'+toWhich).attr('class','on');

	// change map
	map.setMapType(eval(toWhich));
}




function createIcon(imgPath, sizeX, sizeY, aPointX, aPointY)	{
	var mIcon = new GIcon(G_DEFAULT_ICON);
	mIcon.image = imgPath;
	mIcon.shadow = '';
	mIcon.iconSize = new GSize(sizeX, sizeY);
	mIcon.iconAnchor  = new GPoint(aPointX, aPointY);
	return mIcon;
}


// My functions
function moveMapTo(Lat, Lng)	{
	if (GBrowserIsCompatible()) {
		map.panTo(new GLatLng(Lat, Lng));
	}
}


function showDetails(title, text, link)	{		
	jQuery('#popupImageCaption').html(title + '&nbsp;')
	jQuery('#DPText').html(text)
	if (link != '')	{
		jQuery('#moreHolder').html('<a href="' + link + '">+ more</a>');
	}	else	{
		jQuery('#moreHolder').html('');
	}
	jQuery('#detailsPopup').css('display','block');
}

function light(popupImg)	{
	// alert(popupImg)
	jQuery('#modalLargeImage').attr('src', popupImg)
	jQuery('#largeImage').jqmShow();
}

function makeSmall(img)	{
	aImg = img.split('.');
	//return aImg[0] + '_s.' + aImg[1];
	return aImg[0] + '_s.gif'
}


function hideMarker(which)	{

	var marker = markers[which][0];
	if (marker.isHidden()) {
		jQuery('#m' + which).attr('src','../i/gpin_' +which+ '_s.gif');
	}	else	{
		jQuery('#m' + which).attr('src','../i/gpin_' +which+ '_s_on.gif');
	}

	toggleGroup(which);
}




function galleryNext(stop)	{
	if (stop)	{	clearInterval(interval);		}

	galleryPosition = galleryPosition+1;
	if (galleryPosition >= galleryArray.length)	{	galleryPosition = 0;	}
	changeGallery(galleryPosition);
}

function galleryBack(stop)	{
	if (stop)	{	clearInterval(interval);		}

	galleryPosition = galleryPosition-1;
	if (galleryPosition < 0)	{	galleryPosition = galleryArray.length - 1;	}
	changeGallery(galleryPosition);
}

function hideAppTypes()	{
	// Hide both panels
	jQuery('#map').hide();
	jQuery('#gallery').hide();

	// reset the rollovers on the buttons
	jQuery('#mbsport').attr('src','../i/mapButton_sport.png');
	jQuery('#mbvenue').attr('src','../i/mapButton_venue.png');
	jQuery('#mbmap').attr('src','../i/mapButton_map.png');
}

function changeGallery(arrayIndex)	{
	jQuery('#gallery').css("background","url('" + galleryArray[arrayIndex].image + "')");
	jQuery('#galleryDetails').html('<b>' + galleryArray[arrayIndex].title.toUpperCase() + '</b> - ' + galleryArray[arrayIndex].text);
	jQuery('#galleryNavPageCount').text((arrayIndex + 1)+ '/' + (galleryArray.length) )
	galleryPosition = arrayIndex;
}

function initGallery(galleryType)	{

	switch (galleryType) {
		case 'sport': 
			galleryArray = sport;
			break;

		case 'venue': 
			galleryArray = venue;
			break;
	}

	changeGallery(0);

	clearInterval(interval);
	interval = setInterval("galleryNext(false)", 5000);
}



function fitMap(map, points) {
	var bounds = new GLatLngBounds();
	for (var i=0; i< points.length; i++) {
		bounds.extend(points[i]);
	}

	//alert(bounds.getSouthWest() + " - " + bounds.getNorthEast());

	//alert(map.getBoundsZoomLevel(bounds));

	//map.setZoom(map.getBoundsZoomLevel(bounds) - 1);
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());
}

