var gmrt_site_select;
var display_current_coordinates;

$(document).ready(function(){
	load();
	$('#gmrt_site').change(gmrt_site_select);
	display_current_coordinates();
});

$(window).unload(function(){ GUnload(); });

function load(){
	// initiate variables for markers
	var num_markers = 0;
	var marker = new Array();
	var tmp;
	marker[1] = null;
	marker[2] = null;
	var ptLat = new Array();
	ptLat[1] = 90;
	ptLat[2] = -90;
	var ptLong = new Array();
	ptLong[1] = -180;
	ptLong[2] = 180;
	env = '';
	var tminx, tmaxx;
	var tminy, tmaxy;
	var cnt_x, cnt_y;
	var icon = new GIcon();
	var focusSiteZoom = false;
	icon.image = "http://www.marine-geo.org/services/google/icons/cross_icon.png";
	icon.iconAnchor = new GPoint(7, 7);
	
	// create map
	var map = new GMap2(document.getElementById("map"));
	var FORMAT_DEFAULT="image/png";
	var POLAR_RADIUS = 6343000.0;
	var EQUATORIAL_RADIUS = 6356752.0;
	
	var DEG2RAD=0.017453292519943295;
	var PI=3.14159267;
	function dd2MercMetersLng(p_lng) {
		return EQUATORIAL_RADIUS*(p_lng*DEG2RAD);
	} 
	
	function dd2MercMetersLat(p_lat) {
		if (p_lat >= 85) p_lat=85;
		if (p_lat <= -85) p_lat=-85;
		return POLAR_RADIUS*Math.log(Math.tan(((p_lat*DEG2RAD)+(PI/2.0)) /2.0));
	}
	
	CustomGetTileUrl=function(a,b,c) {
		if (this.myMercZoomLevel == undefined) {
	    	this.myMercZoomLevel = 15;
		}
	
		if (this.myFormat == undefined) {
	    	this.myFormat = FORMAT_DEFAULT;
		}
	
		if (typeof(window['this.myStyles'])=="undefined") this.myStyles="";
		var lULP = new GPoint(a.x*256,(a.y+1)*256);
		var lLRP = new GPoint((a.x+1)*256,a.y*256);
		var lUL = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lULP,b,c);
		var lLR = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lLRP,b,c);

		var lBbox = 0.0;
		var lSRS = "";
	
		if (map.getZoom() < 5) { 
			// use mercator projection when viewimg large areas
			lBbox=dd2MercMetersLng(lUL.x)+","+dd2MercMetersLat(lUL.y)+","+dd2MercMetersLng(lLR.x)+","+dd2MercMetersLat(lLR.y);
			lSRS="EPSG:3395";
		}
		else {
			// use geographic projection when viewing details
			lBbox=lUL.x+","+lUL.y+","+lLR.x+","+lLR.y;
			lSRS="EPSG:4326";
	
		}
	
		var lURL=this.myBaseURL;
		lURL+="&REQUEST=GetMap";
		lURL+="&SERVICE=WMS";
		lURL+="&VERSION=1.1.1";
		lURL+="&LAYERS="+this.myLayers;
		lURL+="&STYLES="+this.myStyles;
		lURL+="&FORMAT="+this.myFormat;
		lURL+="&BGCOLOR=0xFFFFFF";
		lURL+="&TRANSPARENT=TRUE";
		lURL+="&SRS="+lSRS;
		lURL+="&BBOX="+lBbox;
		lURL+="&WIDTH=256";
		lURL+="&HEIGHT=256";
		lURL+="&reaspect=false";
		//document.write("<br>"+lURL + "<br/>")
		//alert(" url is " + lURL);
		return lURL;
	}
	
	function customOpacity() { return this.myOpacity; }
	// create tile layer for 1 to 10 zoom levels
//	var tileDoq = new GTileLayer(new GCopyrightCollection(""), 2, 10);

	var d = new Date();
	var copyright = new GCopyright(1,
		new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0,
		"Bathymetry &copy;"+d.getFullYear()+" <a href='http://www.marine-geo.org'>MGDS</a>");
	var copyrightCollection = new GCopyrightCollection("");
	copyrightCollection.addCopyright(copyright);
	var tileDoq= new GTileLayer(copyrightCollection,2,16);

	tileDoq.myLayers = 'topo';
	tileDoq.myFormat = 'image/jpeg';
	tileDoq.myBaseURL = 'http://www.marine-geo.org/services/wms?';
	tileDoq.getTileUrl = CustomGetTileUrl;
	tileDoq.getOpacity = function(){
		return 1.0;
	}
	
	var gmrt_layer = [tileDoq];
	var gmrt_hybrid_layer = [tileDoq, G_HYBRID_MAP.getTileLayers()[1]];
	
	var bathymetry = new GMapType(gmrt_layer, G_SATELLITE_MAP.getProjection(), "GMRT", G_SATELLITE_MAP);
	var bathyhybrid = new GMapType(gmrt_hybrid_layer, G_SATELLITE_MAP.getProjection(), "Labels", G_SATELLITE_MAP);

	map.getMapTypes().length = 0;
	map.addMapType(bathymetry);
	map.addMapType(bathyhybrid);
	
	map.setCenter(new GLatLng(41.0, -73.9), 2);
	var givenmaptypes = map.getMapTypes();
	map.setMapType(givenmaptypes[0]);
	map.addControl(new GSmallMapControl());
	map.addControl(new GScaleControl());
	map.addControl(new GMapTypeControl());
	
	map.enableDoubleClickZoom();
	map.enableContinuousZoom();
	map.enableScrollWheelZoom();
	new GKeyboardHandler(map, window);
	
	var bounds = map.getBounds();
	var center = map.getCenter();
	
	var current_zoom_level = 2;
	var last_zoom_level = 1;
	
	GEvent.addListener(map, 'click', select_corner);
	GEvent.addListener(map, 'zoomend', detect_zoom);
	//GEvent.addListener(map, 'drag', detect_drag);
	
	/*if (typeof setBoundingBox == 'function') {
		setBoundingBox();
	}*/
		
	gmrt_site_select = function(){
		fnClear();
		switch (document.getElementById("gmrt_site").value) {
			case '0': // reset
				document.gmrt.west.value = -180;
				document.gmrt.east.value = 180;
				document.gmrt.south.value = -78;
				document.gmrt.north.value = 81;
				break;
			case 'Antarctic': // everything south of 60S
				document.gmrt.west.value = -180;
				document.gmrt.east.value = 180;
				document.gmrt.south.value = -78;
				document.gmrt.north.value = -60;
				break;
			case 'Arctic': // everything north of 72N
				document.gmrt.west.value = -180;
				document.gmrt.east.value = 180;
				document.gmrt.south.value = 72;
				document.gmrt.north.value = 81;
				break;
			case 'MARGINS': // entire world
				document.gmrt.west.value = -180;
				document.gmrt.east.value = 180;
				document.gmrt.south.value = -78;
				document.gmrt.north.value = 81;
				break;
			case 'NJT':
				document.getElementById('west').value = 130;
				document.gmrt.east.value = 138;
				document.gmrt.south.value = 30;
				document.gmrt.north.value = 35;
				break;
			case 'CA':
				document.gmrt.west.value = -95;
				document.gmrt.east.value = -80;
				document.gmrt.south.value = 5;
				document.gmrt.north.value = 17;
				break;
			case 'RS':
				document.gmrt.west.value = 30;
				document.gmrt.east.value = 51;
				document.gmrt.south.value = 9;
				document.gmrt.north.value = 33.5;
				break;
			case 'GoC':
				document.gmrt.west.value = -117;
				document.gmrt.east.value = -108;
				document.gmrt.south.value = 22;
				document.gmrt.north.value = 32;
				break;
			case 'PNG':
				document.gmrt.west.value = 134;
				document.gmrt.east.value = 153;
				document.gmrt.south.value = -12;
				document.gmrt.north.value = 0;
				break;
			case 'NZ':
				document.gmrt.west.value = 165;
				document.gmrt.east.value = 190;
				document.gmrt.south.value = -50;
				document.gmrt.north.value = -35;
				break;
			case 'IBM':
				document.gmrt.west.value = 138;
				document.gmrt.east.value = 150;
				document.gmrt.south.value = 10;
				document.gmrt.north.value = 36;
				break;
			case 'Ridge2000': // entire world
				document.gmrt.west.value = -180;
				document.gmrt.east.value = 180;
				document.gmrt.south.value = -78;
				document.gmrt.north.value = 81;
				break;
			case 'EPR_8-11_N':
				document.gmrt.west.value = -106;
				document.gmrt.east.value = -102;
				document.gmrt.south.value = 8;
				document.gmrt.north.value = 11;
				break;
			case 'JdF-Endeavour':
				document.gmrt.west.value = -129.5;
				document.gmrt.east.value = -128.5;
				document.gmrt.south.value = 47.5;
				document.gmrt.north.value = 48.5;
				break;
			case 'Lau_Basin':
				document.gmrt.west.value = -178;
				document.gmrt.east.value = -173.5;
				document.gmrt.south.value = -23;
				document.gmrt.north.value = -19;
				break;
		}
	
		var centerInputLat = (parseFloat(document.gmrt.north.value) + parseFloat(document.gmrt.south.value)) / 2.0;
		var centerInputLon = (parseFloat(document.gmrt.east.value) + parseFloat(document.gmrt.west.value)) / 2.0;
	
		var zoomLevel = map.getBoundsZoomLevel(new GLatLngBounds(new GLatLng(document.gmrt.south.value, document.gmrt.west.value), new GLatLng(document.gmrt.north.value, document.gmrt.east.value)));
		focusSiteZoom = true;
		map.setCenter(new GLatLng(centerInputLat, centerInputLon), zoomLevel);
		GEvent.trigger(map, 'click', null, new GPoint(document.gmrt.west.value, document.getElementById('north').value));
		GEvent.trigger(map, 'click', null, new GPoint(document.gmrt.east.value, document.getElementById('south').value));
		
	}
	
	display_current_coordinates = function(){
		var centerInputLat = (parseFloat(document.gmrt.north.value) + parseFloat(document.gmrt.south.value)) / 2.0;
		var centerInputLon = (parseFloat(document.gmrt.east.value) + parseFloat(document.gmrt.west.value)) / 2.0;
	
		var zoomLevel = map.getBoundsZoomLevel(new GLatLngBounds(new GLatLng(document.gmrt.south.value, document.gmrt.west.value), new GLatLng(document.gmrt.north.value, document.gmrt.east.value)));
		focusSiteZoom = true;
		map.setCenter(new GLatLng(centerInputLat, centerInputLon), zoomLevel);
		GEvent.trigger(map, 'click', null, new GPoint(document.gmrt.west.value, document.getElementById('north').value));
		GEvent.trigger(map, 'click', null, new GPoint(document.gmrt.east.value, document.getElementById('south').value));
	}

	function detect_zoom(oldLevel, newLevel){
		// clear bounding box when zooming
		if (focusSiteZoom) {
			focusSiteZoom = false;
			return;
		}
		else {
			fnClear();
		}
		/*if (newLevel > oldLevel) {
			num_markers = 0;
			map.clearOverlays();
			document.getElementById('north').value = '';
			document.getElementById('south').value = '';
			document.getElementById('west').value = '';
			document.getElementById('east').value = '';
			document.getElementById('corners_set').value = 'false';
		}*/
	}
	/*function detect_drag(){
		// clear bounding box after dragging
		num_markers = 0;
		map.clearOverlays();
		document.getElementById('north').value = '';
		document.getElementById('south').value = '';
		document.getElementById('west').value = '';
		document.getElementById('east').value = '';
		document.getElementById('corners_set').value = 'false';
	}*/
	
	function select_corner(overlay, point){
		if (document.getElementById('corners_set').value == 'true') {
			num_markers = 0;
			map.clearOverlays();
			
			document.getElementById('north').value = '';
			document.getElementById('south').value = '';
			document.getElementById('west').value = '';
			document.getElementById('east').value = '';
			document.getElementById('corners_set').value = 'false';
		}
		else 
			if (point) {
				if (num_markers == 2) 
					return;
				num_markers++;
				
				marker[num_markers] = new GMarker(point, icon);
				//marker[num_markers] = new GMarker(point);
				map.addOverlay(marker[num_markers]);
				
				point.x = point.x * 1000;
				point.y = point.y * 1000;
				point.x = Math.round(point.x);
				point.y = Math.round(point.y);
				point.x = point.x / 1000;
				point.y = point.y / 1000;
				
				
				ptLat[num_markers] = point.y;
				ptLong[num_markers] = point.x;
				
				if (num_markers == 1) {
					document.getElementById('north').value = point.y;
					document.getElementById('west').value = point.x;
				}
				else 
					if (num_markers == 2) {
						document.getElementById('south').value = point.y;
						document.getElementById('east').value = point.x;
					}
				if (num_markers == 2) {
					var crossDateline = false;
					//				Test for crossing the dateline
					if (ptLong[1] != 180 && ptLong[2] != 180 && ((ptLong[2] < 0 && ptLong[1] > 0) || (ptLong[1] < 0 && ptLong[2] > 0))) {
						//					alert('Selection crosses dateline');
						var deltaLon = Math.abs(ptLong[1] - ptLong[2]);
						if (deltaLon > 180) {
							crossDateline = true;
						}
					}
					
					drawPolylines();
					if (ptLong[2] < ptLong[1]  && !crossDateline ) {
                                                tmp = ptLong[1];
                                                ptLong[1] = ptLong[2];
                                                ptLong[2] = tmp;
                                                document.getElementById('west').value = ptLong[1];
                                                document.getElementById('east').value = ptLong[2];
                                        }

					if (ptLat[2] > ptLat[1]) {
						tmp = ptLat[1];
						ptLat[1] = ptLat[2];
						ptLat[2] = tmp;
						document.getElementById('north').value = ptLat[1];
						document.getElementById('south').value = ptLat[2];
					}
					
					
					//				If first click is in Western Hemisphere and the dateline is crossed then first click is east value
					//				add 360 to first click to get that east value as a positive number
					if (crossDateline && (ptLong[1] < 0)) {
						document.getElementById('west').value = ptLong[2];
						document.getElementById('east').value = ptLong[1] + 360.0;
					}
					//				If first click is in Eastern Hemisphere and the dateline is crossed then first click is east value
					//				add 360 to first click to get that east value as a positive number
					if (crossDateline && (ptLong[2] < 0)) {
						document.getElementById('west').value = ptLong[1];
						document.getElementById('east').value = ptLong[2] + 360.0;
					}
					if (ptLong[2] == ptLong[1] || ptLat[2] == ptLat[1]) {
						document.getElementById('north').value = '';
						document.getElementById('south').value = '';
						document.getElementById('west').value = '';
						document.getElementById('east').value = '';
					}
					document.getElementById('corners_set').value = 'true';
				}
				
			}
	}
	
	function drawPolylines(){
		var mid1_lat = -1;
		var mid1_long = -1;
		var mid2_lat = -1;
		var mid2_long = -1;
		mid1_lat = ptLat[1];
		mid1_long = ptLong[2];
		mid2_lat = ptLat[2];
		mid2_long = ptLong[1];
		
		var points = [];
		points.push(new GPoint(ptLong[1], ptLat[1]));
		points.push(new GPoint(mid1_long, mid1_lat));
		points.push(new GPoint(ptLong[2], ptLat[2]));
		points.push(new GPoint(mid2_long, mid2_lat));
		points.push(new GPoint(ptLong[1], ptLat[1]));
		thisEnv = new GPolyline(points, "#000000");
		map.addOverlay(thisEnv);
	}
	
	function fnClear(){
		num_markers = 0;
		map.clearOverlays();
		
		document.getElementById('north').value = '';
		document.getElementById('south').value = '';
		document.getElementById('west').value = '';
		document.getElementById('east').value = '';
		document.getElementById('corners_set').value = 'false';
	}
	
	function fnClaraDDKJRKEKEKSOSOOS(){
                num_markers = 0;
                map.clearOverlays();

                document.getElementById('north').value = '';
                document.getElementById('south').value = '';
                document.getElementById('west').value = '';
                document.getElementById('east').value = '';
                document.getElementById('corners_set').value = 'false';
        }
	

	function fnRemovePolyline(){
		map.removeOverlay(thisEnv);
	}
}
