/*
Title:				Maps based on Bing Maps Javascript
Author: 			Sapient
Date Modified:		November 2009
Version:			1.0
Requires:			base.js
*/

EnjoyEngland.Maps =
{
	dataGenerator : {
		tempData: [],
		data: [],
		maxItems: 50,
		counters: 
			{
				primary: 0,
				secondary: 0,
				updates: 0
			},
		maxFilters: function ()
			{
				return visitEnglandChecked;
			},
		recieveData: function (data)
			{
				if ((data && data.d.results) && this.maxFilters() !== this.tempData.length + 1)
					{
						this.tempData.push(data.d.results)
					}
				else if (data && data.d.results)
					{
						this.tempData.push(data.d.results);
						setTimeout(function ()
							{
								EnjoyEngland.Maps.dataGenerator.tempData.sort(function (a, b)
									{
										return a.length - b.length
									});
								EnjoyEngland.Maps.dataGenerator.extractData();
							}, 10);
					}
			},
		extractData: function ()
		{
			var addedNumber = 0,
				app = this,
				countBuffer = 0;
			app.counters.master = Math.floor(app.maxItems % app.maxFilters()) + Math.floor(app.maxItems / app.maxFilters());
			app.counters.secondary = Math.floor(app.maxItems / app.maxFilters());
			$(EnjoyEngland.Maps.dataGenerator.tempData).each(function (i)
			{
				var totalPerSection = 0,
					data = this;
				if (i === 0)
				{
					totalPerSection = app.counters.master;
				}
				else
				{
					totalPerSection = app.counters.secondary;
				}
				totalPerSection = totalPerSection + countBuffer;
// console.log("countBuffer = " + countBuffer + " totalPerSection = " + totalPerSection + " Length = " + data.length + " LESS = " + (data.length <= totalPerSection).toString())
				if (data.length <= totalPerSection)
				{
					for (var i = 0; i <= (data.length - 1); i++)
						{
							app.data.push(data[i]);
						}
					countBuffer = totalPerSection - data.length;
				}
				else
				{
					totalPerSection = totalPerSection + countBuffer;
					data = data.splice(0, totalPerSection)
					for (var i = 0; i <= (data.length - 1); i++)
					{
						app.data.push(data[i]);
					}
					countBuffer = 0;
				}
				// console.log("LENGTH = " + app.data.length)
			})
			
			if(app.data.length > 0)
				{
					myparseNearbyMMPins(app.data);	
				}
		}
	},
	BMap:
	{
		// Constant Values
		//APIKey: 'AjJM2YLAl4GjAtT5DjiM332wjJWM__htvwNKoGkRafW3OPh81cZP1AMMWCy-my5h', //www.enjoyengland.com
		APIKey: 'AjJM2YLAl4GjAtT5DjiM332wjJWM__htvwNKoGkRafW3OPh81cZP1AMMWCy-my5h', //localhost
		dataSource: {
			accessId: '9da400fe10fc4eb4b9a2361b415f7c61',
			dataSourceName: 'EEBingMap',
			entityTypeName: 'FourthCoffeeShops'
		},
		
		// Flags and 'private' variables
		apiInserted: false,
		map: null,
		hostMapDiv: null, // Will contain reference to div element hosting the mapDiv
		mapDiv: null, // Will be dynamically created inside div with id=idMapDiv for each new map, and destroyed on exit
		mmPinLayer: null,
		pinsLoaded: false,
		editorialMarkers: [],
		
		// Pin setup
		pins:
		{
			url: EnjoyEngland.path + '/images/icons-pins.png',
			images:
			{
				cluster: { url:EnjoyEngland.path + '/images/pins/' + 'ee-pin-01.png', anchor:[9,18], size:[21,27] },
				attractions: { url:EnjoyEngland.path + '/images/pins/' + 'ee-pin-02.png', anchor:[9,18], size:[21,27] },
				accommodation: { url:EnjoyEngland.path + '/images/pins/' + 'ee-pin-03.png', anchor:[9,18], size:[21,27] },
				events: { url:EnjoyEngland.path + '/images/pins/' + 'ee-pin-04.png', anchor:[9,18], size:[21,27] },
				destinationguides: { url:EnjoyEngland.path + '/images/pins/' + 'ee-pin-05.png', anchor:[9,18], size:[21,27] },
				ideas: { url:EnjoyEngland.path + '/images/pins/' + 'ee-pin-06.png', anchor:[9,18], size:[21,27] },
				tics: { url:EnjoyEngland.path + '/images/pins/' + 'ee-pin-07.png', anchor:[9,18], size:[21,27] },
				pointofinterest: { url:EnjoyEngland.path + '/images/pins/' + 'ee-pin-02.png', anchor:[9,18], size:[21,27] }
			},
			icons: {}
		},
		
		//Values to pass in when calling getMap(), with defaults set
		idMapDiv: null,  // Should contain div that will contain new map. Must have height & width
		mapClass: null,
		width: 300,
		height: 300,
		onloadFunction: null,
		mapCenter:{
			latitude: 53.0,
			longitude: -2.2 
		},
		mapZoom: 6,
		mapStyle: 'Shaded', // Shaded, Road, Hybrid, Aerial
		culture: mapCulture, // Global variable - Must be from list at http://msdn.microsoft.com/en-us/library/cc469974.aspx
 		show3D: false,
 		showMMPins: false, // Show pins loaded from Bing SDS (Was MultiMap) (Ideas, DGs, TICs)
 		showMMPinsOnStart: false, // Show Bing SDS pins on initial load
 		showAlphabetMarkers: false, // Markers with Alphabets for Tellus Results
 		ie7Fix: false, // include ie7 fix for map over flash. Probably only needed for Carousel
 		markers:[],
		/* Sample item
		markers: 
		{
			id_123:
			{
				pinOnly: false,
				title:'Marker Title goes here',
				coordinates:{ latitude:52.20974,longitude:0.11647},
				description:'Sample marker 1',
				image: { url:'/path/to/thumbnail/image.png'},
				link:
				{
					url:'/path/to/link.htm',
					title:'Title Text for link'
				},
				category:'ideas', //Option from list in pins.images above
				external: false,
				showInfoBox: true
			},
			id_124:
			{
				pinOnly: true,
				coordinates:{ latitude:52.20974,longitude:0.11647},
				category:'ideas' //Option from list in pins.images above
			}
		}
		  
		*/
 		
		/* Functions Begin */
 		
		/*
		 * getMap()
		 * General function to initiate the process of creating a VEMap object on the <div> specified by id.
		 * 
		 * A valid idMapDiv is required.
		 * 
		 */
		getMap: function()
		{
			//Force important defaults
			this.onloadFunction = null;
			this.ie7Fix = false;
			this.showAlphabetMarkers = false;
			this.markers = [];

			// Parse all arguments to update EnjoyEngland.Maps.BMap member variables.
			for (var n in arguments[0]) { this[n] = arguments[0][n]; }

			// First save idMapDiv and fnOnloadMap to local constructor variables for use by callback function.
			this.hostMapDiv = (this.idMapDiv ? $( '#'+ this.idMapDiv) : null );
			
			// Only continue if valid browser type
			if ( jQuery.browser.msie || jQuery.browser.mozilla || jQuery.browser.safari )
			{

				this.mapDiv = $( '<div id="BingMap" class="' + this.mapClass + ' map-loading" style="width:' + this.width + 'px; height:' + this.height + 'px;"></div>' );
						
				this.hostMapDiv.append( this.mapDiv );

				if( this.ie7Fix && navigator.userAgent.indexOf('MSIE') > -1 && navigator.userAgent.indexOf('MSIE 8') == -1 )
				{
					var ie7CrashFix = $('<iframe style="display:none;display/**/:block;position:absolute;top:0;left:0;z-index:-1;filter:mask();height: expression(parseInt(parentNode.offsetHeight , 10 ).toString().replace(//\..*$/,"") +"px");width: expression(parseInt(parentNode.offsetWidth , 10 ).toString().replace(//\..*$/,"") +"px");"></iframe>');
					this.hostMapDiv.append(ie7CrashFix);
				}

				// Only continue if valid map div has been created
				if ( this.mapDiv)
				{
					// If window.VEMap does not exist, then call getAPI() which will then add openMap() as a callback function when opening the map
					if (!window.VEMap)
					{
						this.getAPI();
					}
					// If window.VEMap exists, then Bing Maps API is already loaded, so call openMap() to actually open the map
					else
					{
						this.openMap();
					}
				}
			}
			else
			{
				this.hostMapDiv.html( 'Virtual Earth is not supported by your browser.' );
			}
			
		},
		
		//Load the Bing Scripts if not already loaded
		getAPI: function()
		{
			if ( !EnjoyEngland.Maps.BMap.apiInserted )
			{
				//Set apiInserted flag to prevent multiple insertions of API script tags.
				// If a second call comes along, then the callbacks should hopefully still work. Verify!!!!
				EnjoyEngland.Maps.BMap.apiInserted = true;
			
				// Add script blocks to load the BingMaps API with work around for non IE
				if ( !jQuery.browser.msie)
				{
					this.insertJS('http://dev.virtualearth.net/mapcontrol/v6.3/js/atlascompat.js');
				}

				this.insertJS('http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.3&mkt=' + this.culture + '&onScriptLoad=EnjoyEngland.Maps.BMap.openMap');
			}
		},
		
		//Will be run as callback for initial API load, or directly if API already loaded.
		openMap: function()
		{
			//On first time through, load pins
			if (!this.pinsLoaded)
			{
				// set up pins
				jQuery.each( this.pins.images, function( key, value )
				{
					EnjoyEngland.Maps.BMap.pins.icons[ key ] = new VECustomIconSpecification();
					EnjoyEngland.Maps.BMap.pins.icons[ key ].Image = this.url;
					EnjoyEngland.Maps.BMap.pins.icons[ key ].ImageOffset = new VEPixel( this.anchor[0], this.anchor[1] );
				} );
				
				this.pins.icons.empty = new VECustomIconSpecification();
				this.pins.icons.empty.Image = EnjoyEngland.path + '/images/blank.png';
				this.pins.icons.emptyImageOffset = new VEPixel( 9, 18 );
				this.pinsLoaded = true;
			}
			
			this.map = new VEMap( 'BingMap' );
			this.map.SetCredentials( this.APIKey );
			this.map.SetDashboardSize(VEDashboardSize.Normal);

			this.map.onLoadMap = this.onloadMap; //This is callback function set in EnjoyEngland.Maps.BMap.onloadFunction by parent map object.

			var mapOptions = new VEMapOptions();
			mapOptions.DashboardColor = "black";

			this.map.LoadMap( 
				new VELatLong( this.mapCenter.latitude,this.mapCenter.longitude ), 
				this.mapZoom, 
				VEMapStyle[this.mapStyle], // map style 
				false, // fixed map
				VEMapMode.Mode2D, // map mode 
				this.show3D, // show3D
	            true,  // show map mode switch
	            0, // tile buffer
	            mapOptions // options
	            
			);

		},
		
		onloadMap: function()
		{
			//Need to use "EnjoyEngland.Maps.BMap." rather than "this." within this function
			
			// setup Bing map
			EnjoyEngland.Maps.BMap.map.HideScalebar();
			EnjoyEngland.Maps.BMap.map.ClearInfoBoxStyles();
			$( '#MSVE_navAction_toggleGlyphWrapper, #MSVE_navAction_separator3' ).hide();
		
			// remove loading spinner
			EnjoyEngland.Maps.BMap.mapDiv.removeClass('map-loading');
			
			// fix page scrolling issue in Firefox
			if (navigator.userAgent.indexOf( 'Firefox/3.5' ) != -1 ) EnjoyEngland.Maps.BMap.mapDiv.bind( 'DOMMouseScroll', function(e) { e.preventDefault();} );

			// generate editorial and DG pins
			jQuery.each( EnjoyEngland.Maps.BMap.markers, function( key, value )
			{
				var marker = this;
				var target = marker.external && marker.external == 'true' ? 'target="_blank"' : '';
				var newPin = new VEShape( VEShapeType.Pushpin, new VELatLong( marker.coordinates.latitude, marker.coordinates.longitude ) );
 
 				//newPin.SetCustomIcon( EnjoyEngland.Maps.BMap.pins.icons[ marker.category ] );
				//Pins with alphabets for TellUsResultsMap
				if (EnjoyEngland.Maps.BMap.showAlphabetMarkers) {
					newPin.SetCustomIcon('<img src="' + EnjoyEngland.Maps.BMap.pins.icons[marker.category].Image + '"/><span style="position:relative;top:-28px;*top:-24px;text-align:center;left:5px;font-size:0.7em;color:#fdfeff;font-weight:bold;display:block;width:11px">' + (String.fromCharCode(key + 65)) + '</span>');
				}else{
					newPin.SetCustomIcon( EnjoyEngland.Maps.BMap.pins.icons[ marker.category ] );
				}
				
				if (!marker.pinOnly)
				{ 
					if(EnjoyEngland.Maps.BMap.mapDiv.hasClass('BingMapCustom')) {
						var currentURL = marker.link.url ? marker.link.url: '#';
						var currentLinkTitle = marker.link.title ? marker.link.title: '';
						var imageContent = marker.image ? '<a href="' + currentURL + '" class="image" ' + target + '"title="'+currentLinkTitle+'"><img src="' + marker.image.url + '" /></a>' : '';
						
						newPin.SetDescription(imageContent+'<div class="content"><h4><a href="'+currentURL+'" title="'+currentLinkTitle+'">'+marker.title+'</a></h4><p>'+marker.description+'</p><a class="moreLink" href="'+currentURL+'" '+target+'>'+currentLinkTitle+'</a></div>' );
					} else {
						var imageContent = marker.image ? '<a href="' + this.link.url + '" class="image" ' + target + '><img src="' + this.image.url + '" /></a>' : '';
	
						newPin.SetDescription('<div class="content"><p>' + this.description + '</p><a data-index="'+ this.iIndex +'" href="' + this.link.url + '" class="moreLink" ' + target + '>' + this.link.title + '</a></div>' );
					}
				}

				EnjoyEngland.Maps.BMap.editorialMarkers[ this.markerId ] = { data:marker, bMarker:newPin };

				// draw icon
				EnjoyEngland.Maps.BMap.map.AddShape( newPin );
				
				
				//add new marker object into array
				//EnjoyEngland.Maps.BMap.pinmarkers[key] = newPin;
				if (!marker.pinOnly && marker.showInfoBox) EnjoyEngland.Maps.BMap.map.ShowInfoBox(newPin);	
				
			} );
			
			// setup Multimap ClientZone Layer if specified
			if (EnjoyEngland.Maps.BMap.showMMPins) EnjoyEngland.Maps.MMPinLayer.setup(EnjoyEngland.Maps.BMap.showMMPinsOnStart);

			// Invoke the passed-in callback function set in EnjoyEngland.Maps.BMap.onloadFunction by parent map object.
			if ( EnjoyEngland.Maps.BMap.onloadFunction && typeof EnjoyEngland.Maps.BMap.onloadFunction === 'function') EnjoyEngland.Maps.BMap.onloadFunction();
				
		},
		
		unload: function()
		{
			if ( EnjoyEngland.Maps.BMap.map ) 
			{
				EnjoyEngland.Maps.BMap.map.Dispose();
				EnjoyEngland.Maps.BMap.map = null;
			}

			//Throw away contents of Map div, particularly for Carousel  
			if ( EnjoyEngland.Maps.BMap.hostMapDiv )
			{
				//EnjoyEngland.Maps.BMap.hostMapDiv.empty();
				$('#BingMap').remove();
			}
		},

		panAndZoom: function(newLat, newLon, newZoom) 
		{
			this.map.SetCenterAndZoom(new VELatLong(newLat, newLon), newZoom);
		},

		replaceMarkers: function() 
		{

		},

		showPopup: function(markerId)
		{
			//alert('Show popup for id ' + markerId);
			var currMarker = EnjoyEngland.Maps.BMap.editorialMarkers[markerId].bMarker;
			this.panAndZoom(currMarker.Latitude, currMarker.Longitude, 8); //Zoom should be stored with the marker
			EnjoyEngland.Maps.BMap.map.ShowInfoBox(currMarker);
		},


		//EnjoyEngland.Maps.BMap Helper Functions
		
		insertJS: function (filename) {
	        var fileref = document.createElement('script');
	        fileref.setAttribute('type', 'text/javascript');
	        fileref.setAttribute('src', filename);
	        document.getElementsByTagName('head')[0].appendChild(fileref);
	    }
	

	},

	MMPinLayer:
	{
		setup: function(initPinLoad)
		{
			EnjoyEngland.Maps.BMap.mmPinLayer = new VEShapeLayer();

			var clusterOptions = new VEClusteringOptions();
			clusterOptions.Icon = EnjoyEngland.Maps.BMap.pins.icons.cluster;
			clusterOptions.Callback = function( clusters )
			{  
				// The function specified in the Callback must take an array of VEClusterSpecification Class objects.  
				if ( clusters != null ) 
				{  
					for ( var i = 0; i < clusters.length; i++ )
					{  
						// VEClusterSpecification, http://msdn.microsoft.com/en-us/library/cc966730.aspx  
						// this has an array of your shapes that have been clustered .Shapes                  
						var cluster = clusters[i];  
		 
						// VEClusterSpecification.GetClusterShape();  
						// returns:A VEShape Class representing the pushpin cluster.   
						// Returns null if a VEClusterSpecification object was returned from the VEShapeLayer.GetClusteredShapes Method.  
						var clusterShape = clusters[i].GetClusterShape();  
		 
						var description = '<ul class="keyContent">';  
						for ( var s = 0; s < cluster.Shapes.length; s++)
						{
							var shape = cluster.Shapes[s];
							description += '<li style="background-image:url(' + shape._customIcon + ')"><a href="' + shape.url + '">' + shape.name + '</a></li>';
						}
						description += '</ul>';
						
						//add back to the cluster shape  
						clusterShape.SetDescription(description);  
					}
				} 
			};
			EnjoyEngland.Maps.BMap.mmPinLayer.SetClusteringConfiguration( VEClusteringType.Grid, clusterOptions );

			EnjoyEngland.Maps.BMap.map.AddShapeLayer( EnjoyEngland.Maps.BMap.mmPinLayer );

			if (initPinLoad) EnjoyEngland.Maps.MMPinLayer.getNearbyMMPins();

			EnjoyEngland.Maps.BMap.map.AttachEvent( 'onchangeview', EnjoyEngland.Maps.MMPinLayer.getNearbyMMPins );
		},
 
        getNearbyMMPins: function()
		{
		//	alert('getNearbyMMPins');
			//Create array of checked pins in Destination Finder key panel
            var pinFilter = [],
	   		 	checked = $('#destFinderPanel input[type=checkbox]:checked');
           		visitEnglandChecked = checked.length;
				
				EnjoyEngland.Maps.dataGenerator.tempData = null;
				EnjoyEngland.Maps.dataGenerator.data = null;
				
				EnjoyEngland.Maps.dataGenerator.tempData = [];
				EnjoyEngland.Maps.dataGenerator.data = [];
				
			checked.each(function()
            	{					
            		var searchFilter = '(sector eq \'' + $(this).val() + '\') and ((locale eq \'all\') Or (locale eq \'' + langEE + '\'))';					
					var mapCenter = EnjoyEngland.Maps.BMap.map.GetCenter();
					//Note results are ordered by sector descending. This is why sector for Fatwire-sourced entries are prefixed with "FW-"
					// so they are returned before Attractions, Events and Accommodation.
					//A 'nearby' spatial filter with a range of 700 miles should cover all of England, regardless of the map centre.
					var data = { 
						'spatialFilter': 'nearby(' + mapCenter.Latitude + ',' + mapCenter.Longitude + ',' + 400 + ')',
						'$top': 50, 
						'$orderby': 'Sector',
						'$filter':searchFilter,
						'$format': 'json',
						'key': 'AjJM2YLAl4GjAtT5DjiM332wjJWM__htvwNKoGkRafW3OPh81cZP1AMMWCy-my5h',
						'jsonp': 'recievePinData'
					};
					
					$.ajax({ 
								url: 'http://spatial.virtualearth.net/REST/v1/data/'
									 + EnjoyEngland.Maps.BMap.dataSource.accessId + '/' 
									 + EnjoyEngland.Maps.BMap.dataSource.dataSourceName  + '/' 
									 + EnjoyEngland.Maps.BMap.dataSource.entityTypeName, 
								data: data,
								dataType:'jsonp', 
								success : EnjoyEngland.Maps.dataGenerator.recieveData
							});				
            	});
		},
		parseNearbyMMPins: function( json )
		{
			//alert('parseNearbyMMPins');
            // delete existing markers
			EnjoyEngland.Maps.BMap.mmPinLayer.DeleteAllShapes();

	        if ( json && json.record_sets && json.record_sets[ 'd' ] && json.record_sets[ 'd' ].results)
	        {
				jQuery.each( json.record_sets[ 'd' ].results, function( index, item )
				{
					// add a marker
					var newProdPin = new VEShape( VEShapeType.Pushpin, new VELatLong( item.Latitude, item.Longitude ) );

					var iconId;
					switch ( item.sector )
					{
					
						case 'Accommodation':
						case 'Acc':
							iconId = 'accommodation';
							break;
						case 'Attractions':
						case 'Att': 
							iconId = 'attractions';
							break;
						case 'Events':
						case 'Evt': 
							iconId = 'events';
							break;
					
						case 'Idea': 
						case 'FW-Idea': 
							iconId = 'ideas';
							break;
						case 'DG': 
						case 'FW-DG': 
							iconId = 'destinationguides';
							break;
						case 'TIC': 
							iconId = 'tics';
							break;
						default:
							break;
					}

					newProdPin.SetCustomIcon( EnjoyEngland.Maps.BMap.pins.icons[ iconId ] );
					newProdPin.name = item.Name;
					newProdPin.url = item.Url;

					var heading = item.Url ? '<h4><a href="' + item.Url + '">' + item.Name + '</a></h4>' : '<h4>' + item.Name + '</h4>';
					var detail = '';
					if ( item.Street ) detail += item.Street + '<br />';
					if ( item.Street2 ) detail += item.Street2 + '<br />';
					if ( item.Town ) detail += item.Town + '<br />';
					if ( item.PostalTown ) detail += item.PostalTown + '<br />';
					if ( item.County ) detail += item.County + '<br />';
					if ( item.PostalCode ) detail += item.PostalCode + '<br/>';
					if ( item.Sector == 'TIC' && item.Phone ) detail += '<br /><br />P:&nbsp;' + item.Phone;
					if ( item.Sector == 'TIC' && item.Email ) detail += '<br />E:&nbsp<a href="mailto:' + item.Email + '">' + item.Email + '</a>'
					newProdPin.SetDescription( '<div class="content content-imageless">' + heading + '<p>' + detail + '</p></div>' );

					EnjoyEngland.Maps.BMap.mmPinLayer.AddShape(newProdPin);
				} );
			}
		}
	},

	DestinationFinder:
	{
        mapState: {
        	mapCenter: {
        		latitude: 53.0,
        		longitude: -2.2 
			},
			mapZoom: 6,
			mapStyle: 'Shaded',
			searchText: 'SEARCH',
			pinFilter: ['FW-DG', 'FW-Idea', 'TIC']
      	},

		showMMPinsOnStart: true,
		mapTopPosition: '167px',

		//Triggered by onload callback of getMap
		attachMapFind: function()
		{
			//Add click event to search button
			// Note that search happens using the VEMap.Find() method, NOT against the MultiMap ClientZone database.
			// The map.Find() method pans and zooms the map to the found location, then the map.onchangeview event fires the 
			// (re)loading of the MultiMap pins using the MM Search API.
		
			$('#destFinderSearch').bind('click',function(){
				var searchText = $('#destFinderInputText').val() + ', UK';
				EnjoyEngland.Maps.BMap.map.Find(null, searchText);
				return false;
			});
			$("#frmDestFinderSearch").submit(function(){
				$('#destFinderSearch').click();
			  return false;
			});
		},
		
		setupHTML: function ()
		{

			EnjoyEngland.Maps.DestinationFinder.getState();
			
			$("#destFinderInputText").val(EnjoyEngland.Maps.DestinationFinder.mapState.searchText);
		
			$("#destFinderInputText").focus(function() {
				if ($(this).val() == EnjoyEngland.Maps.DestinationFinder.mapState.searchText) {
					$(this).val('');
				}
		    });
			
			$("#destFinderInputText").blur(function() {
				if ($.trim($(this).val()) == '') {
					$(this).val(EnjoyEngland.Maps.DestinationFinder.mapState.searchText);
				}
		    });

			//Add click event to Filter checkboxes and set checks 
			$('#destFinderPanel input[type="checkbox"]').each( function(){

				currBox = $('#' + this.id);
				currBox.click( EnjoyEngland.Maps.MMPinLayer.getNearbyMMPins );
				
				if ( $.inArray(this.value, EnjoyEngland.Maps.DestinationFinder.mapState.pinFilter ) > -1 ) 
				{
					currBox.attr('checked', 'checked');
				}
				else
				{
					currBox.removeAttr('checked');
				}	
			});
			
			$("li#navTabDestFinder a").removeClass("destinationFinderPopup");
			$("li#navTabDestFinder a").addClass("destinationFinderPopupOpen");
			
			EnjoyEngland.Maps.DestinationFinder.mapTopPosition = "0px";
/* 

			var resultsCookie = EnjoyEngland.Cookies.read('xResultsCookie');
			if (resultsCookie && EnjoyEngland.Cookies.read ('resultsFlag') == 'true') {
				$("#destFinderPanel").css("top","26px");
			}else{
				$("#destFinderPanel").css("top","-14px");
			}
*/
			var windowHeight=$("body").height();

			EnjoyEngland.Maps.DestinationFinder.getInitLocationFromQueryString();

			EnjoyEngland.Maps.BMap.getMap({
				idMapDiv: 'destinationFinderMap',
				mapClass: 'destinationFinderMap',
//				idMapDiv: 'content',
//s				mapClass: 'destFinder',
				width: 660,
				height: 438,
				mapCenter: {
					latitude: EnjoyEngland.Maps.DestinationFinder.mapState.mapCenter.latitude,
					longitude: EnjoyEngland.Maps.DestinationFinder.mapState.mapCenter.longitude
				},
				mapZoom: EnjoyEngland.Maps.DestinationFinder.mapState.mapZoom,
				mapStyle: EnjoyEngland.Maps.DestinationFinder.mapState.mapStyle,
				onloadFunction: EnjoyEngland.Maps.DestinationFinder.attachMapFind,
				showMMPins: true,
				showMMPinsOnStart: EnjoyEngland.Maps.DestinationFinder.showMMPinsOnStart
			});
			
			$("#destinationFinderMap").append("<div id='dfResetBtn'>Reset</div>");
			$("#dfResetBtn").click(EnjoyEngland.Maps.DestinationFinder.resetMap);
			 
			$("#BingMap").css("top",EnjoyEngland.Maps.DestinationFinder.mapTopPosition);

			window.onbeforeunload = EnjoyEngland.Maps.DestinationFinder.saveState;
		},
		
		getInitLocationFromQueryString: function ()
		{
			
			var urlQSParams = {};
			(function () {
			    var e,
			        a = /\+/g,  // Regex for replacing addition symbol with a space
			        r = /([^&=]+)=?([^&]*)/g,
			        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
			        q = window.location.search.substring(1);

			    while (e = r.exec(q))
			    	urlQSParams[d(e[1])] = d(e[2]);
			})();

			if (urlQSParams["lat"])  EnjoyEngland.Maps.DestinationFinder.mapState.mapCenter.latitude = urlQSParams["lat"];
			if (urlQSParams["lon"])  EnjoyEngland.Maps.DestinationFinder.mapState.mapCenter.longitude = urlQSParams["lon"];
			if (urlQSParams["zoom"]) EnjoyEngland.Maps.DestinationFinder.mapState.mapZoom = urlQSParams["zoom"];

		},

		openToPoint: function (lat, lon, zoom)
		{
			//Redirects to Destination Finder page and sets location & zoom
			window.location = urlDestFinder + '?lat='+lat +'&lon='+lon+'&zoom='+zoom; 
		},
		
		// Save centre, zoom and filter settings in cookie
		saveState: function() {

			var map = EnjoyEngland.Maps.BMap.map;

			//Create array of checked pins in Destination Finder key panel
            var pinFilterArr = [];
            $('#destFinderPanel input[type=checkbox]:checked').each(function()
            {
            	pinFilterArr.push($(this).val());
            });

            //If in Birdseye or Oblique Map Style, set to matching Aerial view and zoom before saving the cookie
            if (map.GetMapStyle() == VEMapStyle.Birdseye )
            {
            	map.SetMapStyle(VEMapStyle.Aerial);
            	map.SetZoomLevel (18);
            }	
            else if ( map.GetMapStyle() == VEMapStyle.BirdseyeHybrid )
            {
            	map.SetMapStyle(VEMapStyle.Hybrid);
            	map.SetZoomLevel (18);
            }

            var mapCenter = map.GetCenter(); 

            var mapState = {
            	mapCenter:{
            		latitude: mapCenter.Latitude,
            		longitude: mapCenter.Longitude 
    			},
    			mapZoom: map.GetZoomLevel(),
    			mapStyle: map.GetMapStyle(),
    			pinFilter: pinFilterArr,
    			searchText: $("#destFinderInputText").val()
           	};

   			EnjoyEngland.Cookies.remove('MapState');  			
			EnjoyEngland.Cookies.write('MapState', mapState);

		},
		
		// Get saved centre, zoom and filter settings from cookie if it exists, and update map
		getState: function() {
			
			var mapState = EnjoyEngland.Cookies.read('MapState'); 
			
			if (mapState)
			{
				switch (mapState.mapStyle) {
					case('a'):
						mapState.mapStyle = 'Aerial';
						break;
					case('h'):
						mapState.mapStyle = 'Hybrid';
						break;
					case('o'):
						mapState.mapStyle = 'Birdseye';
						break;
					case('b'):
						mapState.mapStyle = 'BirdseyeHybrid';
						break;
					case('r'):
					default:
						mapState.mapStyle = 'Shaded';
						break;
				}
				EnjoyEngland.Maps.DestinationFinder.mapState = mapState;
			}
		},
		
		resetMap: function() 
		{
			EnjoyEngland.Maps.DestinationFinder.mapState = {
	        	mapCenter: {
	        		latitude: 53.0,
	        		longitude: -2.2 
				},
				mapZoom: 6,
				mapStyle: 'Shaded',
				searchText: 'SEARCH',
				pinFilter: ['FW-DG', 'FW-Idea', 'TIC']
	      	},

			EnjoyEngland.Maps.BMap.panAndZoom (
					EnjoyEngland.Maps.DestinationFinder.mapState.mapCenter.latitude,
					EnjoyEngland.Maps.DestinationFinder.mapState.mapCenter.longitude,
					EnjoyEngland.Maps.DestinationFinder.mapState.mapZoom
			);
			
			EnjoyEngland.Maps.BMap.map.SetMapStyle(VEMapStyle.Road);
	      	
			$("#destFinderInputText").val(EnjoyEngland.Maps.DestinationFinder.mapState.searchText);

			$('#destFinderPanel input[type="checkbox"]').each( function(){

				currBox = $('#' + this.id);
				if ( $.inArray(this.value, EnjoyEngland.Maps.DestinationFinder.mapState.pinFilter ) > -1 ) 
				{
					currBox.attr('checked', 'checked');
				}
				else
				{
					currBox.removeAttr('checked');
				}	
			});
			EnjoyEngland.Maps.MMPinLayer.getNearbyMMPins();
		}
	}
};

$(document).ready( function(){
	if ($('#destinationFinderMap').length>0) EnjoyEngland.Maps.DestinationFinder.setupHTML();
});


function recievePinData(json)
{
	setTimeout(function ()
	{
		EnjoyEngland.Maps.dataGenerator.recieveData(json)
	}, 0);
}

function myparseNearbyMMPins( json )
		{
		//	alert('parseNearbyMMPins'+json.d.__copyright);
            //delete existing markers
			
			//alert("myparseNearbyMMPins")
			EnjoyEngland.Maps.BMap.mmPinLayer.DeleteAllShapes();

	        if(json.length > 0) //if ( json &&  json.d.results)
	        {
				jQuery.each( json , function( index, item )
				{
					// add a marker
					var newProdPin = new VEShape( VEShapeType.Pushpin, new VELatLong( item.Latitude, item.Longitude ) );

					var iconId;
					switch ( item.sector )
					{
					
						case 'Accommodation':
						case 'Acc':
							iconId = 'accommodation';
							break;
						case 'Attractions':
						case 'Att': 
							iconId = 'attractions';
							break;
						case 'Events':
						case 'Evt': 
							iconId = 'events';
							break;
					
						case 'Idea': 
						case 'FW-Idea': 
							iconId = 'ideas';
							break;
						case 'DG': 
						case 'FW-DG': 
							iconId = 'destinationguides';
							break;
						case 'TIC': 
							iconId = 'tics';
							break;
						default:
							break;
					}

					newProdPin.SetCustomIcon( EnjoyEngland.Maps.BMap.pins.icons[ iconId ] );
					newProdPin.name = item.name;
					newProdPin.url = item.url;

					var heading = item.url ? '<h4><a href="' + item.url + '">' + item.name + '</a></h4>' : '<h4>' + item.name + '</h4>';
					var detail = '';
					if ( item.street ) detail += item.street + '<br />';
					if ( item.street2 ) detail += item.street2 + '<br />';
					if ( item.town ) detail += item.Town + '<br />';
					if ( item.postal_town ) detail += item.postal_town + '<br />';
					if ( item.CountryRegion ) detail += item.CountryRegion + '<br />';
					if ( item.PostalCode ) detail += item.PostalCode + '<br/>';
					if ( item.sector == 'TIC' && item.Phone ) detail += '<br /><br />P:&nbsp;' + item.Phone;
					if ( item.Sector == 'TIC' && item.Email ) detail += '<br />E:&nbsp<a href="mailto:' + item.Email + '">' + item.Email + '</a>'
					newProdPin.SetDescription( '<div class="content content-imageless">' + heading + '<p>' + detail + '</p></div>' );

					EnjoyEngland.Maps.BMap.mmPinLayer.AddShape(newProdPin);
				} );
			}
		}
	
