var _pspRed = 75.01;
var _dspRed = 14.01;
var _aspRed = 18/01;
var _pspAmber = 10;
var _dspAmber = 4;
var _aspAmber = 5;
var _map;
var _host = "www.AMSeafoods.co.uk";
var _data;
var _codata;
var _zone = "";

function deleteResult(idx, cellkey)
{
	if (confirm("Are you sure that you want to delete this result?"))
	{
		var nl = getNodeList(_data, "/root/pos[@key='" + cellkey + "']");
		var ne = (nl.length  > 0) ? nl[0] : null;
		if (ne != null)
		{
			var hnl = ne.selectNodes("hist");
			var test = hnl[idx].attributes[0].nodeName;
			var timestamp = hnl[idx].getAttribute(test + "date");
			if (savedeletion(cellkey, test, timestamp))
			{
				ne.removeChild(hnl[idx]);
				setHistory(ne);
			}
			else
			{
				alert("Failed to delete reading.");
			}
		}
	}
}

function drawGMap()
{
	if (GBrowserIsCompatible())
		_map = new GMap2(document.getElementById('ctlMap'));
	document.getElementById('ctlMap').style.height = (screen.availHeight-340) + "px";
	document.getElementById('ResultHistory').style.left = (screen.availWidth-240) + "px";
}

// A Rectangle is a simple overlay that outlines a lat/lng bounds on the
// map. It has a border of the given weight and color and can optionally
// have a semi-transparent background color.
function Rectangle(bounds, opt_weight, opt_color, opt_text, opt_textcolor) {
  this.bounds_ = bounds;
  this.weight_ = opt_weight || 2;
  this.color_ = opt_color || "#888888";
  this.text_ = opt_text || "";
  this.textcolor_ = opt_textcolor || "#000000";
}
Rectangle.prototype = new GOverlay();

// Creates the DIV representing this rectangle.
Rectangle.prototype.initialize = function(map) {
  // Create the DIV representing our rectangle
  var div = document.createElement("div");
  div.style.border = this.weight_ + "px solid " + this.color_;
  div.style.position = "absolute";
  div.id = this.text_;
  setCtrlInnerText(div, this.text_);
	
  div.align="center";
  div.style.color = this.textcolor_;
  div.style.fontSize= "9pt"
  div.style.fontFamily="Tahoma";

  // Our rectangle is flat against the map, so we add our selves to the
  // MAP_PANE pane, which is at the same z-index as the map itself (i.e.,
  // below the marker shadows)
  map.getPane(G_MAP_MAP_PANE).appendChild(div);

  this.map_ = map;
  this.div_ = div;

  setDivLight(div);
}

// Remove the main DIV from the map pane
Rectangle.prototype.remove = function() {
  this.div_.parentNode.removeChild(this.div_);
}

// Copy our data to a new Rectangle
Rectangle.prototype.copy = function() {
  return new Rectangle(this.bounds_, this.weight_, this.color_, this.backgroundColor_, this.opacity_);
}

// Redraw the rectangle based on the current projection and zoom level
Rectangle.prototype.redraw = function(force) {
  // We only need to redraw if the coordinate system has changed
  if (!force) return;

  // Calculate the DIV coordinates of two opposite corners of our bounds to
  // get the size and position of our rectangle
  var c1 = this.map_.fromLatLngToDivPixel(this.bounds_.getSouthWest());
  var c2 = this.map_.fromLatLngToDivPixel(this.bounds_.getNorthEast());

  // Now position our DIV based on the DIV coordinates of our bounds
  this.div_.style.width = Math.abs(c2.x - c1.x) + "px";
  this.div_.style.height = Math.abs(c2.y - c1.y) + "px";
  this.div_.style.left = (Math.min(c2.x, c1.x) - this.weight_) + "px";
  this.div_.style.top = (Math.min(c2.y, c1.y) - this.weight_) + "px";
  
  setDivLight(this.div_);
  
  if (_map!=null && _map.getZoom() > 6)
	  setCtrlInnerText(this.div_, this.text_);
  else
      setCtrlInnerText(this.div_, "");

}

function setDivLight(div)
{
  var clr;
  switch(getLight(getCtrlInnerText(div)))
  {
	   case 2:
		clr = "#ff0000";break;
	   case 1:
	    clr = "#f0aa10";break;
	   case 0:
	    clr = "#00ff10";break;
	   default:
	    clr=0;break;
  }
  if(clr!=0)
  {
	div.style.backgroundColor=clr;
	div.style.filter = "alpha(opacity:80)";
	div.style.KHTMLOpacity = 80;
	div.style.MozOpacity = 80;
	div.style.opacity = 80;
  }
}

function setCtrlInnerText(ctrl, textvalue)
{
	if (ctrl.tagName == "INPUT")
	{
		ctrl.value = textvalue;
	}
	else
	{
		switch(navigator.appName)
		{
			case "Netscape":
				ctrl.textContent = textvalue;
				break;
			case "Microsoft Internet Explorer":
				ctrl.innerText = textvalue;
				break;
		}
	}
}

function getCtrlInnerText(ctrl)
{
    var ret = "";
    
	if (ctrl.tagName == "INPUT")
	{
		ret = ctrl.value
	}
	else
	{
		switch(navigator.appName)
		{
			case "Netscape":
				ret = ctrl.textContent;
				break;
			case "Microsoft Internet Explorer":
				ret = ctrl.innerText;
				break;
		}
	}
	return ret;
}

function setInitialPoints()
{
	_map.setCenter(new GLatLng(55,-4), 7);

	_data = getDocument("http://" + _host + "/tdata.asp");

	var nl = getNodeList(_data, "/root/pos");
	for (i=0; i<nl.length; i++)
	{
		var ne = nl[i];
		var w = ne.getAttribute("w") * 1;
		var n = ne.getAttribute("n") * 1;
		var txt = ne.getAttribute("key");
		addBlock(ne, n, w, txt);
	}
		
	GEvent.addListener(_map, "click", function(marker, point) { editLink(point); } );
}

function addBlock(ne, n, w, zone)
{
	var rectBounds = new GLatLngBounds(new GLatLng(n, w), new GLatLng(n-0.25, w+0.50));
	var r = new Rectangle(rectBounds, 1, "#80b0ba", zone, "#808080");
	_map.addOverlay(r);
}

function getLight(zone)
{
	var nl = getNodeList(_data, "/root/pos[@key='" + zone + "']");
	var ne = (nl.length  > 0) ? nl[0] : null;

	if (nl.length > 0)
	{
		var ne = nl[0];
		var psp = ne.getAttribute("psp") || 0;
		var dsp = ne.getAttribute("dsp") || 0;
		var asp = ne.getAttribute("asp") || 0;
		var pspco = ne.getAttribute("pspco") || 0;
		var dspco = ne.getAttribute("dspco") || 0;
		var aspco = ne.getAttribute("aspco") || 0;
	
		var light=-1;
	    if (pspco > 0 || dspco > 0 || aspco > 0)
			light = 0;
		if (psp >= _pspAmber || dsp >= _dspAmber || asp >= _aspAmber)
			light = 1;
		if (psp >= _pspRed || dsp >= _dspRed || asp >= _aspRed)
			light = 2;
	}
	
	return light;
}

function editLink(point)
{
	var key="--";
	var psp="";
	var asp="";
	var dsp="";
	var pspco="";
	var aspco="";
	var dspco="";
	
	var slat = Math.floor(point.lat() + 0.25) + getDoc(point.lat() + 0.25, 4);
	var slng = Math.floor(point.lng()) + getDoc(point.lng(), 2);

	var nl = getNodeList(_data, "/root/pos[@n=" + slat + " and @w=" + slng + "]");
	var ne = (nl.length  > 0) ? nl[0] : null;
		
	if (ne != null)
	{
		var w = ne.getAttribute("w") * 1;
		var n = ne.getAttribute("n") * 1;
		psp = ne.getAttribute("psp");
		dsp = ne.getAttribute("dsp");
		asp = ne.getAttribute("asp");
		pspco = ne.getAttribute("pspco");
		dspco = ne.getAttribute("dspco");
		aspco = ne.getAttribute("aspco");
		pspprod = ne.getAttribute("pspprod") || "W";
		dspprod = ne.getAttribute("dspprod") || "W";
		aspprod = ne.getAttribute("aspprod") || "W";
		key = ne.getAttribute("key");
	}
	
	_zone = key;

	if ((pspco > 0 || dspco > 0 || aspco > 0) && key != "") 
		document.getElementById('ResultHistory').style.visibility = "";
	else
		document.getElementById('ResultHistory').style.visibility = "hidden";
	
	setCtrlInnerText(document.getElementById("cellkey"),key);

	setInput("psp", getFormattedNumber(psp, 1), pspco, pspprod, ne==null || _canedit == "N" || _map.getZoom() != 7);
	setInput("dsp", getFormattedNumber(dsp, 1), dspco, dspprod, ne==null || _canedit == "N" || _map.getZoom() != 7);
	setInput("asp", getFormattedNumber(asp, 1), aspco, aspprod, ne==null || _canedit == "N" || _map.getZoom() != 7);
	
	if (ne != null)
		setHistory(ne);
}

function setHistory(node)
{
	var rh = document.getElementById("InnerResultHistory");
	var content = "";
	var nl = node.selectNodes("hist");
	for (i=0 ;i<nl.length; i++)
	{
		var icontent = "";
		icontent += addContentForTest(i, node.getAttribute("key"), nl[i], "psp");
		icontent += addContentForTest(i, node.getAttribute("key"), nl[i], "dsp");
		icontent += addContentForTest(i, node.getAttribute("key"), nl[i], "asp");
		if (icontent != "") 
			icontent = "<TR>" + icontent + "</TR>";
		content += icontent;
	}
	rh.innerHTML = "<TABLE width='100%'>" + content + "</TABLE>";
}

function addContentForTest(idx, cellkey, node, test)
{
	var content = "";
	if (node.selectSingleNode("@" + test) != null)
	{
		content += "<TD class='ResultHistory'>" + test + "</TD><TD class='ResultHistory'>" + getFormattedNumber(node.getAttribute(test),1) + "</TD><TD class='ResultHistory'>" + node.getAttribute(test+"prod") + "</TD><TD class='ResultHistory'>" + node.getAttribute(test + "date").substring(0,16) + "</TD><TD class='ResultHistory'>" + getCompanyShortName(node.getAttribute(test + "co")) + "</TD>";
		if (_canedit == "Y")
			content += "<TD><a style='text-decoration:none' href='javascript:deleteResult(" + idx + ",\"" + cellkey + "\")'><img src='delete.jpg'></a></TD>";
	}
	return content;
}

function setInput(figure, value, compid, product, hide)
{
	document.getElementById(figure).disabled = hide;
	document.getElementById(figure+"prod").disabled = hide;
	
	setCtrlInnerText(document.getElementById(figure),value);
	setCtrlInnerText(document.getElementById(figure + "co"),getCompanyName(compid));  
	document.getElementById(figure + "prod").value =  product;

	showSave(figure,false);
}

function getCompanyName(code)
{
	if (code == null || code == "")
		return "No reading";
		
	var ret = "[unknown]";
	
	if (_codata == null)
		_codata = getDocument("http://" + _host + "/tcompany.asp");

	var nl = getNodeList(_codata, "/root/user[@id=" + code + "]");
	if (nl.length > 0)
		ret = nl[0].getAttribute("name");
		
	return ret;	
}

function getCompanyShortName(code)
{
	if (code == null || code == "")
		return "No reading";
		
	var ret = "[unknown]";
	
	if (_codata == null)
		_codata = getDocument("http://" + _host + "/tcompany.asp");

	var nl = getNodeList(_codata, "/root/user[@id=" + code + "]");
	if (nl.length > 0)
		ret = nl[0].getAttribute("shortname");
		
	return ret;	
}

function getFormattedNumber(nvalue, numdecplaces)
{
	if (nvalue == null || nvalue == "")
		nvalue = 0;

	var mult = Math.pow(10,numdecplaces);
	
	var ret = Math.round(nvalue * mult);
	ret = ret / mult;
	
	if (numdecplaces > 0)
	{
		var charsafterdot = ("Z" + ret).length - ("Z" +ret).indexOf(".") - 1;
		if (("Z" +ret).indexOf(".") == -1)
			ret = ret + ".";
		ret = ret + "0000000000".substring(0, charsafterdot - 1);
	}
	return ret;
}

function getDoc(posvalue, num)
{
	var ret=0;
	var decval = posvalue - Math.floor(posvalue)
	for (i=0; i<num; i++)
		if (decval >= (1/num)*i && decval < (1/num)*(i+1))
			ret = (1/num)*i
	return ret;
}

function zoom(level)
{
	if (_map != null)
	{
		if (level >0)
			_map.zoomIn()
		else
			_map.zoomOut();
	}
	
	document.getElementById("zoomin").disabled = !(_map != null && _map.getZoom() < 9);
	document.getElementById("zoomout").disabled = !(_map != null && _map.getZoom() > 6);
}

function getDocument(url)
{
	var doc = null;

    if (typeof window.ActiveXObject != 'undefined' ) 
    {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else 
    {
        req = new XMLHttpRequest();
        req.async=false;
    }
    req.open( "GET", url, false );
    req.send( null );

	doc = new ActiveXObject('Microsoft.XMLDOM');
	doc.loadXML(req.responseText);
	
	return doc;
}

function getNodeList(doc, xpath)
{
	var ret = null;
	switch(navigator.appName)
	{
		case "Netscape":
			var nl = doc.evaluate(xpath, doc, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE,null);
			var ret = [];
			var ne = nl.iterateNext();
			while (ne !=null)
			{
				ret.push(ne);
				ne = nl.iterateNext();
			}
			break;
		case "Microsoft Internet Explorer":
			ret = doc.selectNodes(xpath);
			break;
	}
	
	return ret;
}

function showSave(figure, state)
{
	document.getElementById("btnsave" + figure).style.visibility = (state) ? "" : "hidden";
	
	if (state)
		setCtrlInnerText(document.getElementById(figure + "co"), getCompanyName(_userno));
}

function save(figure)
{
	var value = document.getElementById(figure).value;
	var product = document.getElementById(figure + "prod").value;

	if (!isNumeric(value))
	{
		alert( "Value must be a number");
		return false;
	}
		
	var url = "http://" + _host + "/SaveToxinData.asp?user=" + _userno + "&zone=" + _zone + "&test=" + figure + "&value=" + value + "&product=" + product;
	
    if (typeof window.ActiveXObject != 'undefined' ) 
    {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else 
    {
        req = new XMLHttpRequest();
        req.async=false;
    }
    req.open( "GET", url, false );
    req.send( null );
    
	if (req.responseText == "ok")
	{
		var nl = getNodeList(_data, "/root/pos[@key='" + _zone + "']");
		var ne = (nl.length  > 0) ? nl[0] : null;
		if (ne.getAttribute(figure) != null)
		{
			var hnl = ne.selectNodes("hist");
			if (hnl.length > 10)
				ne.removeChild(hnl[hnl.length-1]);
			var e = _data.createElement("hist");
			e.setAttribute(figure, ne.getAttribute(figure));
			e.setAttribute(figure+"co", ne.getAttribute(figure+"co"));
			e.setAttribute(figure+"prod",ne.getAttribute(figure+"prod"));
			e.setAttribute(figure+"date",ne.getAttribute(figure+"date"));
			if (hnl.length == 0)
				ne.appendChild(e);
			else
				ne.insertBefore(e, hnl[0]);
		}
		ne.setAttribute(figure, value);
		ne.setAttribute(figure + "co", _userno);	
		ne.setAttribute(figure + "prod", product);
		ne.setAttribute(figure + "date", getDate());
		showSave(figure, false);
		
        this.setDivLight(document.getElementById(_zone));
        this.setHistory(ne);
	}
	else
		alert("There was an error writing result to database");

	
	return false;
}

function savedeletion(zone, test, timestamp)
{
	var url = "http://" + _host + "/DeleteToxinData.asp?zone=" + zone + "&test=" + test + "&timestamp=" + timestamp;
	
    if (typeof window.ActiveXObject != 'undefined' ) 
    {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else 
    {
        req = new XMLHttpRequest();
        req.async=false;
    }
    req.open( "GET", url, false );
    req.send( null );
    
    return (req.responseText == "ok");
}

function getDate()
{
	var ret = "";
	var dt = new Date();
	ret = ((dt.getDate() < 10) ? "0" : "") + dt.getDate() + "/";
	ret += ((dt.getMonth()+1 < 10) ? "0" : "") + (dt.getMonth()+1) + "/";
	ret += dt.getFullYear() + " ";
	ret += ((dt.getHours() < 10) ? "0" : "") + dt.getHours() + ":";
	ret += ((dt.getMinutes() < 10) ? "0" : "") + dt.getMinutes() + ":";
	ret += ((dt.getSeconds() < 10) ? "0" : "") + dt.getSeconds();
	return ret;
}

function isNumeric(vTestValue)
{
	var sField = vTestValue.replace(/^\s*|\s*$/g,"");
	
	if(sField.length==0) { return false; }
	else if(sField.length==1 && (sField.charAt(0) == '.' || sField.charAt(0) == ',' || (sField.charAt(0) == '-'))) { return false; }
	
	for(var x=0; x < sField.length; x++) {
		if((sField.charAt(x) >= '0' && sField.charAt(x) <= '9') || sField.charAt(x) == '.' || sField.charAt(x) == ',' || (sField.charAt(x) == '-' && x==0)) { /* do nothing */ }
		else { return false; }
	}
	
	return true;
}

