/**
 *
 * This contains the javascript that is specific to single photospot pages
 *
 *
 *
 *
 *
 */
//create some global variables
var googleMap = null;
var osMap = null;
var osMarkers = null;

// marker containers //
var googlePhotospot = null;
var osPhotospot = null;
var googleParkingMarkers = new Array;
var osParkingMarkers = new Array;
var googleRestrictedParkingMarkers = new Array;
var osRestrictedParkingMarkers = new Array;
var googleRouteMarkers = new Array;
var osRouteMarkers = new Array;
var googleViewMarkers = new Array;
var osViewMarkers = new Array;

jQuery(document).ready(function() {
	
	initialize_google();
	initialize_os();
	initialize_controls();
	

});


function initialize_google(){
	
	var latlng = new google.maps.LatLng(53.45,-1.30);
	var myOptions = {
		zoom: 4,
		mapTypeControl: true,
		mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
		navigationControl: true,
		navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	googleMap = new google.maps.Map(document.getElementById("map_canvas_google"), myOptions);
	
	if ( !osPhotospot && osMap ){
		populateMapData();
	}
	
}

function initialize_os(){
	
	//first we restrict the extent that you can pan around the map
	var options = {};
	//the osMap variable refers to a div element whose size we have set in the html body
	osMap = new OpenSpace.Map('map_canvas_os', options);
	//set centre of map and zoom level
	osMap.setCenter(new OpenSpace.MapPoint(430218.5, 383541.8), 5);

	//add the layer for the markers
	osMarkers = new OpenLayers.Layer.Markers("Markers");		
	osMap.addLayer(osMarkers);
	
	if ( !googlePhotospot && googleMap ){
		populateMapData();
	}
	
}

function initialize_controls(){
	
	jQuery('a.map_switch').click(function(){
		
		if ( jQuery(this).text() == 'Show Ordnance Survey Map' ) {
			jQuery(this).text('Show Google Map');
		} else {
			jQuery(this).text('Show Ordnance Survey Map');
		}
		
		jQuery('div.mapwrap').toggleClass('deselected');

	});

}








function setMapsPosition(Lat,Lng,zoom){

	//do google map
	var gPos = new google.maps.LatLng(Lat,Lng);
	googleMap.setCenter(gPos);

	//do OS map
	var osLngLat = new OpenLayers.LonLat( Lng , Lat );
	var gridProjection = new OpenSpace.GridProjection();
	var osPos = gridProjection.getMapPointFromLonLat(osLngLat);
	osMap.setCenter(osPos);
	
	//do zooming
	switch( zoom ){
		case 'close':
		googleMap.setZoom(15);
		osMap.zoomTo(8);
		break;
		default:
		googleMap.setZoom(8);
		osMap.zoomTo(3);
		break;
	}
}




/**
 *	Gets the home value set for the user
 *	and centres the maps there
 */
function populateMapData(){

	itemSlug = window.location.toString();
	itemSlug = itemSlug.replace(DOMAIN,'').split('/');
	itemSlug = itemSlug[0];

	//use ajax to get the users home
	jQuery.getJSON(DOMAIN + "ajax/photospot/data/" + itemSlug + '/',
	function(data){
		home_town = data.town;

		if ( data.photospot != '' ){
			coords = coordsFromString(data.photospot);
			placePhotospotMarker(coords[0],coords[1]);
			setMapsPosition(coords[0],coords[1],'close');
		}
		
		if ( data.parking != '' && data.parking != '()' ){
			var parking_coords = data.parking.split('),(');
			for( var p = 0; p < parking_coords.length; p++ ){
				
				var pc = coordsFromString( parking_coords[p] );
				placeParkingMarker( pc[0], pc[1]);
				
			}
		}
		
		if ( data.restricted_parking != '' ){
			var restricted_parking_coords = data.restricted_parking.split('),(');
			for( var rp = 0; rp < restricted_parking_coords.length; rp++ ){
				
				var rpc = coordsFromString( restricted_parking_coords[rp] );
				placeRestrictedParkingMarker( rpc[0], rpc[1]);
				
			}
		}
		
		if ( data.route != '' ){
			var route_coords = data.route.split('),(');
			for( var r = 0; r < route_coords.length; r++ ){
				
				var r = coordsFromString( route_coords[r] );
				placeRouteMarker( r[0], r[1]);
							
			}
		}
		
		if ( data.view != '' ){
			var view_coords = data.view.split('),(');
			for( var v = 0; v < view_coords.length; v++ ){
				
				var v = coordsFromString( view_coords[v] );
				placeViewMarker( v[0], v[1]);
							
			}
		}
		
		
		if ( data.azimuth.length > 0 ){
			plotSolarPolygon( data.azimuth );
		}
	
	});


}




function radToDeg(angleRad) 
{
  return (180.0 * angleRad / Math.PI);
}

function degToRad(angleDeg) 
{
  return (Math.PI * angleDeg / 180.0);
}


function plotSolarPolygon( azimuthArray ){
	
	var gridProjection = new OpenSpace.GridProjection();
	
	googlePointArray = new Array();
	osPointArray = new Array();
		
	googlePointArray.push(googlePhotospot.getPosition());
	var OsLonLat = new OpenLayers.LonLat(googlePhotospot.getPosition().lng(),googlePhotospot.getPosition().lat());
	var OsMapPoint = gridProjection.getMapPointFromLonLat( OsLonLat ); //The OS object
	osPointArray.push(new OpenLayers.Geometry.Point(OsMapPoint.getEasting(), OsMapPoint.getNorthing()));
	
	for( var az = 0; az < azimuthArray.length; az++ ){
		
		pointasgoogle = calcSolarCoords(azimuthArray[az]);
		googlePointArray.push( pointasgoogle );
		
		OsLonLat = new OpenLayers.LonLat(pointasgoogle.lng(),pointasgoogle.lat());
		OsMapPoint = gridProjection.getMapPointFromLonLat( OsLonLat );
		
		osPointArray.push(new OpenLayers.Geometry.Point(OsMapPoint.getEasting(), OsMapPoint.getNorthing()));
	}
	
	solarArea = new google.maps.Polygon({
    paths: googlePointArray,
    strokeColor: "#999999",
    strokeOpacity: 0.8,
    strokeWeight: 0,
    fillColor: "#fbff8e",
    fillOpacity: 0.3
	});
  
	solarArea.setMap(googleMap);

	//do it for OS
	var solarLayer = new OpenLayers.Layer.Vector("Solar Layer");
	
   
    //define our particular line styling, including width and colour of the line:
    var style_solar =
          {
           strokeColor: "#999999",
     strokeOpacity: 0.8,
     strokeWidth: 0,
            fillColor: "#fbff8e",
           fillOpacity: 0.3
         };
  
	//create a polygon feature from the array of points and using the style from above
    var linearRing = new OpenLayers.Geometry.LinearRing(osPointArray);
    var polygonFeature = new OpenLayers.Feature.Vector(linearRing, null, style_solar);
    solarLayer.addFeatures([polygonFeature]);
	//add it to the map
	osMap.addLayer(solarLayer);

	//add the sunrise line
	var googleSunriseCoordinates = [
    googlePhotospot.getPosition(),
    googlePointArray[1]
	];
  
	var googleSunriseLine = new google.maps.Polyline({
    path: googleSunriseCoordinates,
    strokeColor: "#FFCC33",
    strokeOpacity: 1,
    strokeWeight: 2
	});

	googleSunriseLine.setMap(googleMap);

	OsLonLat = new OpenLayers.LonLat(googlePhotospot.getPosition().lng(),googlePhotospot.getPosition().lat());
	OsMapPoint = gridProjection.getMapPointFromLonLat( OsLonLat ); //The OS object
	
	var osSunriseCoordinates = [
	new OpenLayers.Geometry.Point(OsMapPoint.getEasting(), OsMapPoint.getNorthing()),
	osPointArray[1]	
	]

	var style_sunrise =
    {
    strokeColor: "#FFCC33",
    strokeOpacity: 1,
    strokeWidth: 2
    };
  
	//create a polygon feature from the array of points and using the style from above
    var lineString = new OpenLayers.Geometry.LineString(osSunriseCoordinates);
    var osSunriseLine = new OpenLayers.Feature.Vector(lineString, null, style_sunrise);
    solarLayer.addFeatures([osSunriseLine]);
	




	
	
	
	//add the sunset line
	var googleSunsetCoordinates = [
    googlePhotospot.getPosition(),
    googlePointArray[googlePointArray.length-1]
	];
  
	var googleSunsetLine = new google.maps.Polyline({
    path: googleSunsetCoordinates,
    strokeColor: "#CC99FF",
    strokeOpacity: 0.8,
    strokeWeight: 2
	});

	googleSunsetLine.setMap(googleMap);

	var osSunsetCoordinates = [
	new OpenLayers.Geometry.Point(OsMapPoint.getEasting(), OsMapPoint.getNorthing()),
	osPointArray[osPointArray.length-1]	
	]

	var style_sunset =
    {
    strokeColor: "#CC99FF",
    strokeOpacity: 1,
    strokeWidth: 2
    };
  
	//create a polygon feature from the array of points and using the style from above
    lineString = new OpenLayers.Geometry.LineString(osSunsetCoordinates);
    var osSunsetLine = new OpenLayers.Feature.Vector(lineString, null, style_sunset);
    solarLayer.addFeatures([osSunsetLine]);



	
}


function calcSolarCoords(direction) {

    //alert("Direction = " + direction)
    var zoom  = googleMap.getZoom()
    var scale = (zoom > 3) ? 3/Math.pow(2,zoom) : 0.375
    var center = googlePhotospot.getPosition()
    var lat1 = degToRad(center.lat())
    var lng1 = degToRad(center.lng())
      var lat = Math.asin(Math.sin(lat1)*Math.cos(scale)+Math.cos(lat1)*Math.sin(scale)*Math.cos(degToRad(direction)))
      var dlon = -Math.atan2(Math.sin(degToRad(direction))*Math.sin(scale)*Math.cos(lat1), Math.cos(scale)-Math.sin(lat1)*Math.sin(lat))
      var lon = ( (lng1 - dlon + Math.PI) % (2*Math.PI) ) - Math.PI
      var endpt = new google.maps.LatLng(radToDeg(lat), radToDeg(lon))
    
	return endpt;

}




/**
 * Creates a photospot marker and updates the form with the details.
 */
function placePhotospotMarker( Lat, Lng ){
		
	//get the location objects
	var GoogleLatLng = new google.maps.LatLng(Lat,Lng); //The google object
	var gridProjection = new OpenSpace.GridProjection();
	var OsLonLat = new OpenLayers.LonLat(Lng,Lat);
	var OsMapPoint = gridProjection.getMapPointFromLonLat( OsLonLat ); //The OS object
		
	//get the url for the marker
	var markerImageUrl = DOMAIN + 'themes/default/images/photospot_marker.png';
		
	//Create the google MarkerImage
	var image = new google.maps.MarkerImage( markerImageUrl,
		// This marker is 20 pixels wide by 32 pixels tall.
		new google.maps.Size(32, 40),
		// The origin for this image is 0,0.
		new google.maps.Point(0,0),
		// The anchor for this image is the base of the flagpole at 0,32.
		new google.maps.Point(16, 40)
		);

	//Create the google Marker - this is automatically attached to the map.	
	googlePhotospot = new google.maps.Marker({
		position: GoogleLatLng,
		map: googleMap,
		flat: true,
		icon: image,
		clickable: false,
		draggable: false,
		title: 'Photospot'
		});

	//Create the OS Marker Image
	var size = new OpenLayers.Size(32, 40);
	var offset = new OpenLayers.Pixel( -16 , -40);
	icon = new OpenLayers.Icon( markerImageUrl, size, offset);
		
	//Create the OS Marker and add it to the markers layer on the map
	osPhotospot = new OpenLayers.Marker(OsMapPoint, icon);
	osMarkers.addMarker(osPhotospot);
	
}

function placeParkingMarker( Lat, Lng ){
	
	//get the location objects
	var googleLatLng = new google.maps.LatLng(Lat,Lng); //The google object
	var gridProjection = new OpenSpace.GridProjection();
	var OsLonLat = new OpenLayers.LonLat(Lng,Lat);
	var OsMapPoint = gridProjection.getMapPointFromLonLat( OsLonLat ); //The OS object
		
	//add an ?i=x to the end for ID purposes later on.
	//get the marker number, we are using google as the default, but actually
	//it doesn't matter which of the arrays are used, the should be the same.
	var markerImageUrl = DOMAIN + 'themes/default/images/parking_marker.png?i=' + googleParkingMarkers.length;

	//Create the google MarkerImage
	var image = new google.maps.MarkerImage( markerImageUrl,
	// This marker is 20 pixels wide by 32 pixels tall.
	new google.maps.Size(15, 15),
	// The origin for this image is 0,0.
	new google.maps.Point(0,0),
	// The anchor for this image is the base of the flagpole at 0,32.
	new google.maps.Point(7, 7)
	);

	//Create the google Marker - this is automatically attached to the map.	
	var googleParkingMarker = new google.maps.Marker({
	position: googleLatLng,
	map: googleMap,
	flat: true,
	icon: image,
	clickable: false,
	draggable: false,
	title: 'Parking'
	});
	
	//Create the OS Marker Image
	var size = new OpenLayers.Size(15, 15);
	var offset = new OpenLayers.Pixel( -7 , -7);
	icon = new OpenLayers.Icon(markerImageUrl, size, offset);
		
	//Create the OS Marker and add it to the markers layer on the map
	var osParkingMarker = new OpenLayers.Marker(OsMapPoint, icon);
	osMarkers.addMarker(osParkingMarker);
		
	//add the marers to the appropriate array
	googleParkingMarkers.push(googleParkingMarker);
	osParkingMarkers.push(osParkingMarker);
	
}

function placeRestrictedParkingMarker( Lat, Lng ){
	
	//get the location objects
	var googleLatLng = new google.maps.LatLng(Lat,Lng); //The google object
	var gridProjection = new OpenSpace.GridProjection();
	var OsLonLat = new OpenLayers.LonLat(Lng,Lat);
	var OsMapPoint = gridProjection.getMapPointFromLonLat( OsLonLat ); //The OS object
		
	//add an ?i=x to the end for ID purposes later on.
	//get the marker number, we are using google as the default, but actually
	//it doesn't matter which of the arrays are used, the should be the same.
	var markerImageUrl = DOMAIN + 'themes/default/images/restricted_parking_marker.png?i=' + googleRestrictedParkingMarkers.length;

	//Create the google MarkerImage
	var image = new google.maps.MarkerImage( markerImageUrl,
	// This marker is 20 pixels wide by 32 pixels tall.
	new google.maps.Size(15, 15),
	// The origin for this image is 0,0.
	new google.maps.Point(0,0),
	// The anchor for this image is the base of the flagpole at 0,32.
	new google.maps.Point(7, 7)
	);

	//Create the google Marker - this is automatically attached to the map.	
	var googleRestrictedParkingMarker = new google.maps.Marker({
	position: googleLatLng,
	map: googleMap,
	flat: true,
	icon: image,
	clickable: false,
	draggable: false,
	title: 'Restricted Parking'
	});
	
	//Create the OS Marker Image
	var size = new OpenLayers.Size(15, 15);
	var offset = new OpenLayers.Pixel( -7 , -7);
	icon = new OpenLayers.Icon(markerImageUrl, size, offset);
	
	//Create the OS Marker and add it to the markers layer on the map
	var osRestrictedParkingMarker = new OpenLayers.Marker(OsMapPoint, icon);
	osMarkers.addMarker(osRestrictedParkingMarker);
		
	//add the marers to the appropriate array
	googleRestrictedParkingMarkers.push(googleRestrictedParkingMarker);
	osRestrictedParkingMarkers.push(osRestrictedParkingMarker);
	
}


function placeRouteMarker( Lat, Lng ){
	
	//get the location objects
	var googleLatLng = new google.maps.LatLng(Lat,Lng); //The google object
	var gridProjection = new OpenSpace.GridProjection();
	var OsLonLat = new OpenLayers.LonLat(Lng,Lat);
	var OsMapPoint = gridProjection.getMapPointFromLonLat( OsLonLat ); //The OS object
		
	//add an ?i=x to the end for ID purposes later on.
	//get the marker number, we are using google as the default, but actually
	//it doesn't matter which of the arrays are used, the should be the same.
	var markerImageUrl = DOMAIN + 'themes/default/images/route_marker_' + (googleRouteMarkers.length+1) + '.png';

	//Create the google MarkerImage
	var image = new google.maps.MarkerImage( markerImageUrl,
	// This marker is 20 pixels wide by 32 pixels tall.
	new google.maps.Size(28, 25),
	// The origin for this image is 0,0.
	new google.maps.Point(0,0),
	// The anchor for this image is the base of the flagpole at 0,32.
	new google.maps.Point(14, 25)
	);

	//Create the google Marker - this is automatically attached to the map.	
	var googleRouteMarker = new google.maps.Marker({
	position: googleLatLng,
	map: googleMap,
	flat: true,
	icon: image,
	clickable: false,
	draggable: false,
	title: 'Route'
	});
	
	//Create the OS Marker Image
	var size = new OpenLayers.Size(28, 25);
	var offset = new OpenLayers.Pixel( -14 , -25);
	icon = new OpenLayers.Icon(markerImageUrl, size, offset);
	
	
	//Create the OS Marker and add it to the markers layer on the map
	var osRouteMarker = new OpenLayers.Marker(OsMapPoint, icon);
	osMarkers.addMarker(osRouteMarker);
	
	
	//add the marers to the appropriate array
	googleRouteMarkers.push(googleRouteMarker);
	osRouteMarkers.push(osRouteMarker);
		
}

function placeViewMarker( Lat, Lng ){
	
	//get the location objects
	var googleLatLng = new google.maps.LatLng(Lat,Lng); //The google object
	var gridProjection = new OpenSpace.GridProjection();
	var OsLonLat = new OpenLayers.LonLat(Lng,Lat);
	var OsMapPoint = gridProjection.getMapPointFromLonLat( OsLonLat ); //The OS object
		
	//add an ?i=x to the end for ID purposes later on.
	//get the marker number, we are using google as the default, but actually
	//it doesn't matter which of the arrays are used, the should be the same.
	var markerImageUrl = DOMAIN + 'themes/default/images/view_marker.png?i=' + googleViewMarkers.length;

	//Create the google MarkerImage
	var image = new google.maps.MarkerImage( markerImageUrl,
	new google.maps.Size(15, 15), //size
	new google.maps.Point(0,0), //origin
	new google.maps.Point(7, 7) //attachmentpoint
	);

	//Create the google Marker - this is automatically attached to the map.	
	var googleViewMarker = new google.maps.Marker({
	position: googleLatLng,
	map: googleMap,
	flat: true,
	icon: image,
	clickable: false,
	draggable: false,
	title: 'View'
	});
	
	//Create the OS Marker Image
	var size = new OpenLayers.Size(15, 15);
	var offset = new OpenLayers.Pixel( -7 , -7);
	icon = new OpenLayers.Icon(markerImageUrl, size, offset);
	
	
	//Create the OS Marker and add it to the markers layer on the map
	var osViewMarker = new OpenLayers.Marker(OsMapPoint, icon);
	osMarkers.addMarker(osViewMarker);
	
	
	//add the marers to the appropriate array
	googleViewMarkers.push(googleViewMarker);
	osViewMarkers.push(osViewMarker);
		
}


function coordsFromString( latLngString ){
		
		var newstring = latLngString.replace('(','');
		newstring = newstring.replace(')','');
		var latLng = newstring.split(',');
		return latLng;
		
	}
