//var debug = true;
var debug = false;

var map; // the global gmap
var request; // the global xmlhttprequest 

var aBuoy = new Array();
var aImage = new Array();
var aImageW = new Array();
var aImageH = new Array();
var aLat = new Array();
var aLon = new Array();
var aMarker = new Array();
var centerLat; var centerLon; // these will be assigned vals in the eval(buoys) 

var baseIcon; // baseIcon used for buoy markers
var	mapEnabledForClicks; // flag used to hold map activation (true/false)
var geocoder = null; // used for zip to latlng translation

// --
// Called by <body> onload
// --
function load(bid, showreport) {
	// create the geocoder
	geocoder = new GClientGeocoder();

	// initialize the map
	map = new GMap2(document.getElementById("GMap"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GScaleControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GOverviewMapControl());
  map.setCenter(new GLatLng(37, -100), 3);
	GEvent.addListener(map, "click", GEmapClick);
	activateMap(true);

	// Create a base icon for all of our markers that specifies the
	// shadow, icon dimensions, etc.
	baseIcon = new GIcon();
	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25);

	// show the search box
	showSearchBox();

	if(bid!="") { // a buoy id was passed in
		plotBuoysByBuoy(bid,100);
	
		if(showreport=="1"){	
	    document.getElementById("stats").style.display = "block";
			activateMap(false);
		}
	}
}

// --
// Event callback for map click
// marker: GMarker clicked
// point: GLatLng at click point
// --
function GEmapClick(marker,point) {
	if(debug)
		GLog.write("entering GEmapClick()");
	if(marker) {
		// A map click is generated when a marker is clicked.  We ignore it here.
	} else {
		if(mapEnabledForClicks) { 
			// kludgy!!
			var dist = document.getElementById("distance").value;
			var url = "zc2.php"
			var pars ="lat="+point.lat()+"&lon="+point.lng()+"&dist="+dist;
if(debug)
	GLog.write("GEmapClick url: " + url + " pars: " + pars);
			new Ajax.Request(url, {
				method: 'get',
				parameters: pars,
				onSuccess: function(transport) {
if(debug)
	GLog.write("GEmapClick Ajax Response " + transport.responseText);
					CBplotBuoys(transport,point,"click");
				},
				onFailure: function() { alert("new Ajax.Request failed");}
			});
		}
	}
}

// --
// callback for the Ajax.Request created in mapClick
// response: repsonse from the Ajax.request
// point: point clicked
// type: "zip" or "bid"
// --
function CBplotBuoys(response,point,type) {
	if(debug)
		GLog.write("entering CBplotBuoys()");
	eval(response.responseText); //	fills the aBuoy, aLat & aLon arrays (global)
	map.clearOverlays(); // clear the map of previous markers
	addMarker(point,type); // add the user click point to the map
	var bounds = new GLatLngBounds(); // this will be used to zoom the map 
	bounds.extend(point); // include the user click point into the bounds
	plotBuoys(bounds); // --
}

// --
// plot the buoys in the aBuoy, aLat, aLon, etc arrays
// bounds containes the click/zip point if this function was called from
// CBplotBuoys, else it is an 'empty' bounds when called from plotBuoysByBuoy
// --
function plotBuoys(bounds) {
	if(debug)
		GLog.write("entering plotBuoys()");
	var buoyList; // used to hold the html that will be put in the buoyList div
	var opts = new Object(); // GMarker options
	var image; var url; var offset = 0; var buoyList=""; var i=0;

	for(i=0; i<aBuoy.length;i++) {
		//GLog.write("i: " + i +" buoy "+aBuoy[i]+" lat: "+aLat[i]+" lon: "+aLon[i],"red");

		// create a point
		var point = new GLatLng(aLat[i],aLon[i]);
		var icon = new GIcon(baseIcon); // baseIcon created in load()
		if(offset < 26) { // create a lettered icon for this marker
			image = "http://www.google.com/mapfiles/marker"+String.fromCharCode("A".charCodeAt(0)+offset)+".png";
			offset = offset +1;
		} else { // we are out of letters
		  image = "http://www.google.com/mapfiles/marker.png";
		}

		icon.image = image;
		opts.icon = icon;
		opts.title = "Buoy " + aBuoy[i];
		opts.img = aImage[i];
		aMarker[i] = new GMarker(point,opts);

		GEvent.addListener(aMarker[i],"click",GEvent.callbackArgs(this,GEmarkerClick,aMarker[i],aBuoy[i], aImage[i], aImageW[i], aImageH[i], aLat[i], aLon[i]));
		map.addOverlay(aMarker[i]);

		bounds.extend(point); // extend the bounds to include this point

		// create the html 
		var ret = "<div id='buoyItem'>";
   	ret += "<p>";
		// click on the marker symbol to trigger the marker click behavior
    ret += "<A onclick='GEvent.trigger(aMarker["+i+"],\"click\")' style='cursor:pointer'>";
    ret += "<IMG src='"+image+"'>";
    ret += "</A>";
		// click on the 'Buoy XXXXX' to trigger the showBuoy routine
		//ret += "<A HREF=\"#\" onclick=\"showBuoy('"+aBuoy[i]+"','"+aImage[i]+"','"+aImageW[i]+"','"+aImageH[i]+"')\">";
		// click on the 'Buoy XXXXX' to trigger the marker click behavior
    ret += "<A onclick='GEvent.trigger(aMarker["+i+"],\"click\")' style='cursor:pointer'>";
   	ret += "<strong>Buoy "+aBuoy[i]+"</strong></A>";
//		ret += "<span title=\" Click to add Buoy "+aBuoy[i]+" to favorites \" class=\"popup\"><img onclick=\"addtofavs('"+aBuoy[i]+"','"+aLat[i]+"','"+aLon[i]+"','<?php echo $userdata['session_logged_in']?>')\" src=\"images/gr_plus.png\" ";
//		ret += "style=\"float:right; margin-right:20px;\" height=8 width=8></span>";
   	ret += "<br>Lat: "+aLat[i] +" Lon: "+aLon[i]+"</p></div>";
    //GLog.write("ret: "+ret,"red");
    buoyList += ret;
	} //end for(

	// recenter the map and zoom to the bounds that creates all of the markers
	map.setCenter(new GLatLng(centerLat, centerLon));
	map.setZoom(map.getBoundsZoomLevel(bounds));
	// put the buoyList html into the bl div
 	(document.getElementById("bl")).innerHTML = buoyList;
  (document.getElementById("buoyList")).style.display = "block";
  (document.getElementById("bl")).style.display = "block";
	// add code to hide/show the div using the blue triangle
  (document.getElementById("buoyListLegend")).innerHTML = "<IMG onclick='hideshow(\"bl\",\"imgBLL\")' id='imgBLL' class='hideshow' height='17' width='17' src='images/small-down19.gif'>Nearby Buoys ("+document.forms[0].distance.value +" Miles)";

}

// -- 
// Add the green arrow marker at the passed in point
// type: "click" or "zip"
// -- 
function addMarker(point,type) {
	if(debug)
		GLog.write("entering addMarker()");
  // create the icon
  var icon = new GIcon();
  icon.image = "http://maps.google.com/mapfiles/arrow.png";
  icon.shadow = "http://www.google.com/intl/en_us/mapfiles/arrowshadow.png";
  icon.iconSize = new GSize(34, 34);
  icon.shadowSize = new GSize(37, 34);
  icon.iconAnchor = new GPoint(9, 34);
  icon.infoWindowAnchor = new GPoint(9, 2);
  icon.infoShadowAnchor = new GPoint(18, 25);
  // set the opts for the icon
  var opts = new Object(); // GMarker options
  opts.icon = icon;
	if(type == "click") {
  	opts.title = "You clicked here";
	} else if(type == "zip") {
  	opts.title = "ZIP " + document.forms[0].zipbid.value;
	} 
  // create the marker and add it to the map!!
  map.addOverlay(new GMarker(point, opts));
}

// --
//  Event callback for a marker click
// --
function GEmarkerClick(marker,bid,img,h,w,lat,lon)  {
if(debug)
	GLog.write("entered GEmarkerClick");
	// close any info window that might be open
	map.closeInfoWindow();
	// turn on the loading message
	loadMessage(1);
	// call home and get the info to put in the marker window/balloon
	var url = 'cv3.php';
	var pars ="bid="+bid+"&img="+img+"&imgw="+w+"&imgh="+h+"&th=1";
	if(debug)
		GLog.write("GEmarker Click url: " + url + " pars: " + pars);
	new Ajax.Request(url, {
		method: 'get',
		parameters: pars,
		onSuccess: function(transport) {
if(debug)
	GLog.write("GEmarkerClick Ajax Response " + transport.responseText);
			loadMessage(0); // turn off the load message
			marker.openInfoWindowHtml(transport.responseText);
			initButtons(); // 'activate' the buttons
		},
		onFailure: function() { 
			loadMessage(0); // turn off the load message
			alert('something is amiss . . '); 
		}
	});
	// load the report table
	var pars ="bid="+bid+"&lat="+lat+"&lon="+lon;
	var url = 'report.php';
	
	new Ajax.Updater('statsRows',url, {
		method: 'get',
		parameters: pars,
		onFailure: function() {
			alert('hmmmm, not right'); 
		},
		onSuccess: function(t) {
if(debug)
	GLog.write("GEmarkerClick Ajax2 Response " + transport.responseText);
			initButtons();
		}
	});
	return false; // so that the HREF isn't followed
}

// --
// submit action for the zipform
// -- 
function findBuoys() {
	// get all of the form values
	var type = document.getElementById("findtype").value;
	var bidzip = document.getElementById("zipbid").value;
	var dist = document.getElementById("distance").value;

	bidzip = bidzip.toUpperCase();
	document.getElementById("zipbid").value = bidzip;

	// validate content of zipbid
	var regexp = /[0-9]{5}/;
	if(type == "zip") {
		if(!regexp.test(bidzip)) { // validate numbers only
			alert(bidzip + " is not a valid ZIP Code");
		} else {
			plotBuoysByZip(bidzip,dist);
		}
	} else { // validate numbers and letters only
		regexp = /[0-9,A-Z]{5}/;
		if(!regexp.test(bidzip)) {
			alert("Invalid Buoy ID");
		} else {
			// validate with the db and go . . . 
			plotBuoysByBuoy(bidzip, dist);
		}
	}
}

// --
// hide and show the divs in leftcontent.php
// -- 
function hideshow(element,img) {
	hidden = document.getElementById(element).style.display;
	if(hidden == "none") {
		document.getElementById(element).style.display="block";
		document.getElementById(img).src="images/small-down19.gif";
	} else {
		document.getElementById(element).style.display="none";
		document.getElementById(img).src="images/small-next19.gif";
	}
}

function initButtons(){
  document.getElementById("showStats").onclick=function(){
    document.getElementById("stats").style.display = "block";
		activateMap(false);
  }
  document.getElementById("hideStats").onclick=function(){
    document.getElementById("stats").style.display = "none";
    document.getElementById("showStats").style.display = "block";
    document.getElementById("hideStats").style.display = "none";
		activateMap(false);
  }
}

// --
// show the FAQ
// --
function showFAQ() {
	document.getElementById("faqbox").style.display = "block";
	activateMap(false);
}

// --
// hide the FAQ
// --
function closeFAQ() {
	document.getElementById("faqbox").style.display = "none";
	activateMap(true);
}

// --
// hide the wind report table
// --
function closeWindTable() {
	document.getElementById("stats").style.display = "none";
	activateMap(true);
}

// --
// quirky way to go about disabling the map 
// (used while the wind report table is displayed)
// -- 
function activateMap(flag) {
	mapEnabledForClicks = flag;
	if(flag) {
		map.enableDragging();
	} else {
		map.disableDragging();
	}
}

// --
// show the 'Loading . . . ' message
// -- 
function loadMessage(flag) {
	var state = 'block';
	if (!flag) {
		state = 'none';
	}
	document.getElementById("loadMsg").style.display = state;
}

// --
// toggle the buoy search box
// --
function showSearchBox() {
	// if its showing, hide it.  if its hidden, show it
	var flag=document.getElementById("searchformdiv").style.display;
	var top = 0;
	if(flag=='block') {
		flag='none';
		top = '0px';
	} else {
		flag='block';
		top = '23px';
	}
	document.getElementById("searchformdiv").style.display = flag;
	document.getElementById("GMap").style.top = top;
}
// --
// plot the zip and nearby buoys
// --
function plotBuoysByZip(zip,dist) {
if(debug) GLog.write("entering plotBuoysByZip()");
	var url = "getZipLatLng.php";
	var pars = "zip="+zip;
if(debug) GLog.write("url: " + url);
if(debug) GLog.write("pars: " + pars);
	new Ajax.Request(url, {
		method: 'get',
		parameters: pars,
		onSuccess: function(transport) {
			// getZipLatLng.php returns "lat|lng" on success else returns "|"
			var latlng = transport.responseText;
if(debug) GLog.write("latlng: "+latlng);
			if(latlng.length == 1) {
				// no lat lng returned
if(debug) GLog.write("no lat lng returned");
				alert(zip + " is not a valid ZIP code.");
			} else {
				var coord = latlng.split("|");
				var url = "zc2.php"
				var pars ="lat="+coord[0]+"&lon="+coord[1]+"&dist="+dist;
if(debug) GLog.write("url: " + url);
if(debug) GLog.write("pars: " + pars);
				new Ajax.Request(url, {
					method: 'get',
					parameters: pars,
					onSuccess: function(transport) {
						var point = new GLatLng(coord[0],coord[1]);
if(debug) GLog.write("plotBuoysByZip Ajax Response " + transport.responseText);
						CBplotBuoys(transport,point,"zip");
					},
					onFailure: function() { alert("new Ajax.Request failed");}
				}); // end Ajax Second request
			} // end else
		}, // end onSuccess first Ajax Request
		onFailure: function() { alert("first Ajax.Request failed");}
	}); // end first Ajax request
} // end function

// --
// plot the specified buoy and nearby buoys
// --
function plotBuoysByBuoy(bid, dist) {
if(debug)
	GLog.write("entering plotBuoysByBuoy()");
	// get the info for the desired bid
	var url = "getbuoyinfo.php";
	var pars = "bid="+bid;
if(debug)
	GLog.write("plotBuoysByBuoy url " + url + " pars " + pars);
	new Ajax.Request(url, { method: 'get', parameters: pars,
		onSuccess: function(transport) {
			var resp=transport.responseText;
if(debug)
	GLog.write("plotBuoysByBuoy resp " + resp );
			if(resp.length == 0) {
				alert("'"+bid+"' is not a valid buoy ID");
			} else {
				// now parse out the individual values
				var b = 0;
				var e = resp.indexOf("|");
				var bidlat = resp.substring(b,e);
				b=e+1; e = resp.indexOf("|",b);
				var bidlon = resp.substring(b,e);
				b=e+1; e = resp.indexOf("|",b);
				var bidimg = resp.substring(b,e);
				b=e+1; e = resp.indexOf("|",b);
				var bidimgh = resp.substring(b,e);
				b=e+1; 
				var bidimgw = resp.substring(b);
	
				// now get the nearby buoys
				var point = new GLatLng(bidlat, bidlon);
				var url = "zc2.php"
				var pars ="lat="+point.lat()+"&lon="+point.lng()+"&dist="+dist+"&omit="+bid;
if(debug)
	GLog.write("plotBuoysByBuoy url " + url + " pars " + pars);
				new Ajax.Request(url, {
					method: 'get',
					parameters: pars,
					onSuccess: function(transport) {
if(debug)
	GLog.write("plotBuoysByBuoys Ajax Response " + transport.responseText);
						// eval the response to fill the a* arrays
						eval(transport.responseText);
if(debug)
	GLog.write("plotBuoysByBuoys eval");
						// prepend the desired buoy to the top of the arrays
						aBuoy.splice(0,0,bid);
						aImage.splice(0,0,bidimg);
						aImageW.splice(0,0,bidimgw);
						aImageH.splice(0,0,bidimgh);
						aLat.splice(0,0,bidlat);
						aLon.splice(0,0,bidlon);
if(debug)
	GLog.write("plotBuoysByBuoys splice");
						// clear the map
						map.clearOverlays(); // clear the map of previous markers
if(debug)
	GLog.write("plotBuoysByBuoys clearOverlays");
						// now, plot the buoys
						plotBuoys(new GLatLngBounds());
if(debug)
	GLog.write("plotBuoysByBuoys plotBuoys");
					  // open the marker balloon for the desired buoy
						GEvent.trigger(aMarker[0],"click");
if(debug)
	GLog.write("plotBuoysByBuoys GEvent.trigger(aMarker . . )");
					},
					onFailure: function() { alert("new Ajax.Request failed");}
				});
			} // end else
		},
		onFailure: function() { 
			if(debug) GLog.write("Ajax call failed??");
		}
	});
}

// -- 
// Select a random buoy and display it
// --
function showRandomBuoy() {

	// close any info window that might be open
	map.closeInfoWindow();
	// turn on the loading message
	loadMessage(1);
	var url = "getrandombuoy.php"
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			var bid = transport.responseText;
			var dist = document.getElementById("distance").value;
			plotBuoysByBuoy(bid,dist);
		},
		onFailure: function() {
			alert("Buoy-o-matic isn't working just now . . . ");
		}
	});
}
