var mapviewer, panZoomWidget, markers, icons, oLocalInfo;
var searcher;
var findNearestType;


function onLoad() {
  //Add the map 
  mapviewer = MMFactory.createViewer( document.getElementById( 'mapviewer' ) );
  mapviewer.goToPosition( new MMLocation( new MMLatLon( 51.2, -1.1 ) , 8 ) );
  mapviewer.addWidget(new MMPanZoomWidget());
  mapviewer.addWidget ( new MMMapTypeWidget () );
  searcher = new MMSearchRequester(function (type, target, results, error_code) {
	  endSearch(type, target, results, error_code);
  });
  
//  oLocalInfo = new  MMLocalInfoWidget('','Local Information', new MMBox(), 'localinfo' );
//  oLocalInfo.addDataSource( 'mm.poi.global.general.atm', {'title': 'ATMs'} );
//  oLocalInfo.addDataSource( 'mm.poi.global.general.metrostation', {'title': 'Tube stations'} );
//  oLocalInfo.addDataSource( 'mm.poi.global.general.touristinformation', {'title': 'Tourist information'} );
//  localInfoContainer = document.getElementById('localinfo');
//  oLocalInfo.setContainer ( localInfoContainer );
//  mapviewer.addWidget(oLocalInfo);
  
  /*
  var oLocalInfo2 = new  MMLocalInfoWidget('','Petrol Stations', new MMBox(), 'localinfo' );
  oLocalInfo2.addDataSource( 'mm.poi.global.general.gasstation', {'title': 'Petrol Stations'} );
  AttractionsContainer = document.getElementById('attractions');
  oLocalInfo2.setContainer ( AttractionsContainer );
  mapviewer.addWidget(oLocalInfo2);
  */
  
  mapviewer.addEventHandler( 'endSearchRequest', endSearch );
  mapviewer.addEventHandler( 'endGeocode', endGeocode );
  markers = new Array();
  
  icons = new Array();
  icons['station'] = new MMIcon('images/icons/station.gif');
  icons['station'].iconSize = new MMDimensions( 19, 22 );
  icons['station'].iconAnchor = new MMPoint( 9, 21 );
  icons['station'].infoBoxAnchor = new MMPoint(9,0);
  icons['station'].groupName  = 'points';
  
  icons['point'] = new MMIcon('images/icons/youarehere.gif');
  icons['point'].iconSize = new MMDimensions( 19, 22 );
  icons['point'].iconAnchor = new MMPoint( 9, 21 );
  icons['point'].infoBoxAnchor = new MMPoint(9,0);
  icons['point'].groupName = 'points';
  icons['point'].zIndex = 1000;
  
  icons['attraction'] = new MMIcon('images/icons/attraction.gif');
  icons['attraction'].iconSize = new MMDimensions( 19, 22 );
  icons['attraction'].iconAnchor = new MMPoint( 9, 21 );
  icons['attraction'].infoBoxAnchor = new MMPoint(9,0);
  icons['attraction'].groupName = 'points';
}

function findPOI(coords) {
	var poipin;
	var locat = {};
	var poipinLayer = new Microsoft.Maps.EntityCollection();

	if (coords.lat != undefined) {
		locat = { lat: coords.lat, lon: coords.lon };
	}
	else {
		locat = { lat: coords.latitude, lon: coords.longitude };
	}
	

	$.getJSON("http://spatial.virtualearth.net/REST/v1/data/c2ae584bbccc4916a0acf75d1e6947b4/NavteqEU/NavteqPOIs?spatialFilter=nearby(" + locat.lat + "," + locat.lon + ",5)&$filter=EntityTypeID%20eq%20'3578'&$top=30&$format=json&key=ApjrUrVu4vvxhVzRyht8BPVfmb7XvuP6xeW_ZoHm09oJy6kyWSDEtFKL167aX_Wm&jsonp=?", function (getResults) {
		$("#localinfo").html("<a href='#'><img src='images/icons/mm_poi_global_general_atm.gif' alt=''/>" + getResults.d.results.length + "</a>");

		for (var i = 0; i < getResults.d.results.length; i++) {
			poipin = new Microsoft.Maps.Pushpin({ latitude: getResults.d.results[i].Latitude, longitude: getResults.d.results[i].Longitude });
			poipin.setOptions({ icon: "images/icons/marker.png", height: 25, width: 25 });
			poipin.infobox = new Microsoft.Maps.Infobox(poipin.getLocation(),
			{
				title: getResults.d.results[i].Name,
				description: getResults.d.results[i].AddressLine + "<br />" + getResults.d.results[i].Locality,
				showPointer: true,
				visible: false,
				offset: new Microsoft.Maps.Point(0, 15),
				zIndex: 999
			});
			poipinLayer.push(poipin);
			poipinLayer.push(poipin.infobox);
			Microsoft.Maps.Events.addHandler(poipin, 'click', displayPOIInfobox);
		}

		mapviewer.map.entities.push(poipinLayer);

	});
}

function displayPOIInfobox(e) {
	if (e.targetType == "pushpin") {
		var title = e.target.infobox._title;
		var html = this.target.infobox._description;
		$('#infoboxDescription').html("").html(html);
		$('#infoboxTitle').html("").html(title);
		$('#infoBox').css('position', 'absolute').css('zIndex', '2000').css('width', "220px").css('height', '80px').css('top', '170px').css('left', '230px').css('visibility', 'visible').css('display', 'inherit');
		$('#infoboxTitle').css("visibility", "visible");
	}
}

function closePOIInfobox() {
	$('#infoBox').css("visibility", "hidden");
	$('#infoboxTitle').css("visibility", "hidden");
}


function gotoStation(strCrs){
  if (strCrs == undefined){
	var elStation = document.getElementById('ddlStations');
	strCrs = elStation.options[elStation.selectedIndex].value;
  }
  mapviewer.removeAllOverlays();
  markers = new Array();
  objSearch = new MMSearch();
  objSearch.radius_units = 'miles';
  objSearch.filters = new Array();
  objSearch.count = 1;
  objSearch.filters.push( new MMSearchFilter('nearest_station_crs', 'Eq', strCrs) );
  objSearch.logic = 'AND';
  objSearch.filters.push(new MMSearchFilter('item_type', 'Eq', 'station'));
  searcher.search(objSearch);
  //mapviewer.goToPosition( new MMLocation (objSearch, 16));
}

function endGeocode( type, target, location, error_code ) {
  if( error_code == 'MM_GEOCODE_MULTIPLE_MATCHES') {
	  alert( 'Please note that multiple possible locations have been found for this address' );
  }
  else if( error_code) {
	  alert( 'There was a problem geocoding that address: '+error_code );
	  return;
  } 
  markers.push(createGeoMarker(location));
  var elType = document.getElementById('ddlType');
  var strType = elType.options[elType.selectedIndex].value;
  findPoints(location.coords, strType, (strType == 'station' ? 3 : 10));

  
}

function findPoints(coords, type, count){
  if (count==undefined){
	count=3;
  }
  //alert(strType);
  objSearch = new MMSearch();
  objSearch.radius_units = 'miles';
  //objSearch.max_distance = 5;
  objSearch.point = coords;
  objSearch.count = count;
 
  objSearch.filters = new Array();
  objSearch.logic = 'AND';
  if (type!=undefined && type!='' && type !="All"){
	objSearch.filters.push( new MMSearchFilter('item_type', 'Eq', type) );
  }
  searcher.search(objSearch);
  //mapviewer.goToPosition( new MMLocation (objSearch, 16));
}

function locationSearch(){
	findNearestType = "";
  var bResult = true;
  if (typeof(Page_ClientValidate) == 'function') {
	bResult = Page_ClientValidate('');
  }

  if (bResult){
	var strSearch = trim(document.getElementById('txtMapSearch').value + '');
	mapviewer.removeAllOverlays();
	markers = new Array();

	var address = new MMAddress();
	address.qs = strSearch;
	address.country_code = "GB";
	var geocoder = new MMGeocoder(locationCB);
	geocoder.geocode(address);
  }
}

function locationCB(a) {
	var search = new MMSearch();
	if (a && a.length > 0) {
	    var filter = $('#ddlType option:selected').text();
	    var count = 10;
	    if (filter == "Station")
	        count = 3;
	    if (filter == "Attraction")
	        count = 7;

        findPoints(a[0].coords, filter, count);

		markers.push(createGeoMarker(a[0]));

		setTimeout(function () {
			$('.routeMarker img').each(function () {
				if (this.src.indexOf("youarehere") != -1) {
					if (!$(this).parent()[0]._id)
						this.title = $(this).parent()[0].cm1001_er_der.entity._id;
					else
						this.title = $(this).parent()[0]._id;
				}
			});
		}, 1000);
	}
	else {
		alert("The location cannot be found. Please try again using a more specific postcode (eg. SE1)");
	}
}



function createAttractionMarker(record){
	var anchor, p, br;
	var marker = mapviewer.createMarker(record.point, { 'label': record.name.toString(), 'icon': icons['attraction'] });
  
  var div = document.createElement('div');
  var header = document.createElement('h1');
  marker.pushpin._id = record.name;
  header.innerHTML = record.name.toString();
  div.appendChild(header);


  if (record.start_date!=null){
	var dStart = new Date;
	dStart.setTime(Date.parse(record.start_date.toString().replace(/-/g, "/")))
	p = document.createElement('p');
	p.innerHTML = 'Starts: ' + dStart.toLocaleDateString();
	div.appendChild(p);
  }

  if (record.end_date!=null){
	var dEnd = new Date;
	dEnd.setTime(Date.parse(record.end_date.toString().replace(/-/g, "/")))
	p = document.createElement('p');
	p.innerHTML = 'Ends: ' + dEnd.toLocaleDateString();
	div.appendChild(p);
  }

  if (record.url.toString()!=''){
	anchor = document.createElement('a');
	anchor.href=record.url.toString();
	anchor.innerHTML = 'More information';
	p = document.createElement('p');
	p.appendChild(anchor);
	div.appendChild(p);
  }

  //anchor = $("<a href='#' onclick='javascript:findNearest('><Find Nearest Station</a>");

  anchor = document.createElement('a');
  anchor.href='#';
  $(anchor).bind('click', function () {
	  findNearest(record, 'station', 1);
	  return false;
  });
  anchor.innerHTML = 'Find nearest station';
  p = document.createElement('p');
  p.appendChild(anchor);
  div.appendChild(p);
  
  p = document.createElement('p');
  var addr = '';
  if ( record.AddressLine.toString() != '' ) addr += record.AddressLine;
  if ( record.Locality.toString() != '' ) addr += ( (addr != '') ? ', ' : '' ) + record.Locality.toString();
  if ( record.pc.toString() != '' ) addr += ( (addr != '') ? ', ' : '' ) + record.pc.toString(); 
  
  p.innerHTML = addr;
  div.appendChild(p);
  marker.setInfoBoxContent(div);
  return marker;
}

function createStationMarker(record){
  var marker = mapviewer.createMarker( record.point, {'label' : record.name.toString() , 'icon': icons['station']} );
  var p, anchor;
  var div = document.createElement('div');
  var header = document.createElement('h1');
  header.innerHTML = record.name.toString();
  div.appendChild(header);
  
  anchor = document.createElement('a');
  anchor.href='stationinfo.aspx?stn=' + record.nearest_station_crs.toString();
  anchor.innerHTML = 'Station information';
  p = document.createElement('p');
  p.appendChild(anchor);
  div.appendChild(p);
  
  anchor = document.createElement('a');
  anchor.target='_blank';
  anchor.href='pdfmaps/' + record.nearest_station_crs.toUpperCase() + '.pdf';
  anchor.innerHTML = 'Download station map';
  p = document.createElement('p');
  p.appendChild(anchor);
  div.appendChild(p);
  
  
  anchor = document.createElement('a');
  anchor.href='#';
  anchor.innerHTML = 'Find nearby attractions';
  $(anchor).bind('click', function () { findNearest(record, 'attraction', 8); return false; });
  p = document.createElement('p');
  p.appendChild(anchor);
  div.appendChild(p);

  anchor = document.createElement('a');
//  if(record.nearest_station_crs.toString().toLowerCase() == "rdg") {
//      anchor.href = 'networkmap.aspx#' + "BOA";
//    }
//  else {
	  anchor.href = 'networkmap.aspx#' + record.nearest_station_crs.toString();
	//}
  anchor.innerHTML = 'View station in network map';
  p = document.createElement('p');
  p.appendChild(anchor);
  div.appendChild(p);
 
  p = document.createElement('p');
  var addr = '';
  if (record.AddressLine.toString() != '') addr += record.AddressLine;
  if (record.Locality.toString() != '') addr += ((addr != '') ? ', ' : '') + record.Locality.toString();
  if ( record.pc.toString() != '' ) addr += ( (addr != '') ? ', ' : '' ) + record.pc.toString(); 
  p.innerHTML = addr;
  div.appendChild(p);
 
  marker.setInfoBoxContent(div);
  return marker;
}

function createGeoMarker(location){
  //var marker = mapviewer.createMarker(location.coords, { 'label': location.address.locality.toString() + " " + location.address.adminDistrict.toString(), 'icon': icons['point'] });
  //marker.setInfoBoxContent($('<h1>' + location.address.locality.toString() + " " + location.address.adminDistrict.toString() + '</h1>'));
  var address = location.address.locality ? (location.address.locality.toString() + " " + location.address.adminDistrict.toString()) : location.address.postalCode.toString();
  var marker = mapviewer.createMarker(location.coords, { 'label': address, 'icon': icons['point'] });
  marker.pushpin.id = address;
  marker.pushpin._id = address;
  marker.setInfoBoxContent($('<h1>' + address + '</h1>'));
  return marker;
}

function findNearest(record, type, count) {
	findNearestType = type;
	mapviewer.removeAllOverlays();
	markers = new Array();
	markers.push(createPointMarker(record));
	findPoints(record.point, type, count);
} 

function createPointMarker2(record) {
	if (findNearestType.length > 0)
		type = "All";
//        return createStationMarker(record);
//    if (findNearestType == "attraction")
//        return createAttractionMarker(record);

	var type = $('#ddlType option:selected').text();
	switch (record.item_type.toString()) {
	  case 'attraction':
		  if (type == "All" || type == "Attraction") {
			return createAttractionMarker(record);
		  }
	  case 'station':
		if (type == "All" || type == "Station") {
			return createStationMarker(record);
		}
  }
}

function createPointMarker(record) {
	switch (record.item_type.toString()) {
		case 'attraction':
			return createAttractionMarker(record);
		case 'station':
			return createStationMarker(record);
	}
}

function endSearch(type, target, results, error_code) {
	if (error_code) {
		switch (error_code) {
			case "MM_GEOCODE_FAILED":
				alert('The location cannot be found. Please try again using more specific postcode (eg. SE1)');
				break;
			case "MM_GEOCODE_MULTIPLE_MATCHES":
				alert('There were multiple matches');
				break;
			default:
				alert('There was a problem performing this search: ' + error_code);
				break;
		}
	}

	if (!results || !results.length) {
	    alert("Your search did not return any results. Please try again with a different location.");
	    return;
    }

	for (var rsCount = 0, rslen = results.length; rsCount < rslen; rsCount++) {
		for (var rCount = 0, rlen = results[rsCount].records.length; rCount < rlen; rCount++) {
			var mark = createPointMarker(results[rsCount].records[rCount]);
			markers.push(mark);
		}
	}
	mapviewer.declutterGroup('points', {}, MM_DECLUTTER_GRID);

	if (markers.length == 1) {
		markers[0].openInfoBox();
	}
	if (markers.length > 1) {
		mapviewer.goToPosition(mapviewer.getAutoScaleLocation(markers));
	}

	$('.routeMarker img').each(function () {
		//var title = this.parent.id;
		if (this.src.indexOf("attraction") != -1) {
			if(!$(this).parent()[0]._id)
				this.title = $(this).parent()[0].cm1001_er_der.entity._id;
			else
				this.title = $(this).parent()[0]._id;
		}
		if (this.src.indexOf("youarehere") != -1) {
			if (!$(this).parent()[0]._id)
				this.title = $(this).parent()[0].cm1001_er_der.entity._id;
			else
				this.title = $(this).parent()[0]._id;
		}
	});
	//oLocalInfo.refreshData();
}




function print_r(theObj){
  if(theObj.constructor == Array || theObj.constructor == Object){
	document.write("<ul>")
	for(var p in theObj){
	  if(theObj[p].constructor == Array || theObj[p].constructor == Object){
		document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
		document.write("<ul>")
		print_r(theObj[p]);
		document.write("</ul>")
	  } 
	  else {
		document.write("<li>["+p+"] => "+theObj[p]+"</li>");
	  }
	}
	document.write("</ul>")
  }
}

/**
*
*  Javascript trim, ltrim, rtrim
*  http://www.webtoolkit.info/
*
**/
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
