//***********************************************************
// Shared Functionality
//***********************************************************
JSON = function () {
    function f(n) { 
        return n < 10 ? '0' + n : n;
    }
    Date.prototype.toJSON = function () {
        return this.getUTCFullYear()   + '-' +
        f(this.getUTCMonth() + 1) + '-' +
        f(this.getUTCDate())      + 'T' +
        f(this.getUTCHours())     + ':' +
        f(this.getUTCMinutes())   + ':' +
        f(this.getUTCSeconds())   + 'Z';
    };
    var m = {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"' : '\\"',
        '\\': '\\\\'
    };
    function stringify(value, whitelist) {
        var a,i,k,l,v,r = /["\\\x00-\x1f\x7f-\x9f]/g;
        switch (typeof value) {
            case 'string':
                return r.test(value) ?
                    '"' + value.replace(r, function (a) {
                        var c = m[a];
                        if (c) {
                            return c;
                        }
                        c = a.charCodeAt();
                        return '\\u00' + Math.floor(c / 16).toString(16) +
                                                   (c % 16).toString(16);
                    }) + '"' :
                    '"' + value + '"';
            case 'number':
                return isFinite(value) ? String(value) : 'null';
            case 'boolean':
            case 'null':
                return String(value);
            case 'object':
                if (!value) {
                    return 'null';
                }
                if (typeof value.toJSON === 'function') {
                    return stringify(value.toJSON());
                }
                a = [];
                if (typeof value.length === 'number' &&
                        !(value.propertyIsEnumerable('length'))) {
                    l = value.length;
                    for (i = 0; i < l; i += 1) {
                        a.push(stringify(value[i], whitelist) || 'null');
                    }
                    return '[' + a.join(',') + ']';
                }
                if (whitelist) {
                    l = whitelist.length;
                    for (i = 0; i < l; i += 1) {
                        k = whitelist[i];
                        if (typeof k === 'string') {
                            v = stringify(value[k], whitelist);
                            if (v) {
                                a.push(stringify(k) + ':' + v);
                            }
                        }
                    }
                } else {
                    for (k in value) {
                        if (typeof k === 'string') {
                            v = stringify(value[k], whitelist);
                            if (v) {
                                a.push(stringify(k) + ':' + v);
                            }
                        }
                    }
                }
                return '{' + a.join(',') + '}';
        }
    }
    return {
        stringify: stringify,
        parse: function (text, filter) {
            var j;
            function walk(k, v) {
                var i, n;
                if (v && typeof v === 'object') {
                    for (i in v) {
                        if (Object.prototype.hasOwnProperty.apply(v, [i])) {
                            n = walk(i, v[i]);
                            if (n !== undefined) {
                                v[i] = n;
                            }
                        }
                    }
                }
                return filter(k, v);
            }
            if (/^[\],:{}\s]*$/.test(text.replace(/\\./g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
                j = eval('(' + text + ')');
                return typeof filter === 'function' ? walk('', j) : j;
            }
        throw new SyntaxError('parseJSON');
        }
    };
}();

function ajaxObject(url, source) {  
	var that=this;
	this.updating = false;
	this.abort = function() {
		if (that.updating) { 
			that.updating=false;
			that.AJAX.abort();
			that.AJAX=null;
		}  
	}
	this.update = function(passData,postMethod) {
		try {
			netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
		} catch (e) {
		}
		if (that.updating) { return false; }
		that.AJAX = null;
		if( !window.XMLHttpRequest ) XMLHttpRequest = function(){
				try{ return new ActiveXObject("MSXML3.XMLHTTP") }catch(e){}
				try{ return new ActiveXObject("MSXML2.XMLHTTP.3.0") }catch(e){}
				try{ return new ActiveXObject("Msxml2.XMLHTTP") }catch(e){}
				try{ return new ActiveXObject("Microsoft.XMLHTTP") }catch(e){}
				throw new Error("Could not find an XMLHttpRequest alternative.")
		}
		that.AJAX=new XMLHttpRequest();
		if (that.AJAX==null) {
			return false;
		} else {
			that.AJAX.onreadystatechange = function() {
				if (that.AJAX.readyState==4) {
					that.updating=false;
					that.callback(that.AJAX.responseText,source);
					that.AJAX=null;
				}
			}
			that.updating = new Date();
			if ((postMethod) || postMethod=="POST") {
				var uri=urlCall+'?'+that.updating.getTime();
				that.AJAX.open("POST", uri, true);
				that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				that.AJAX.setRequestHeader("Content-Length", passData.length);
				that.AJAX.send(passData);
			} else {
				var uri=urlCall+'?'+passData+'&timestamp='+(that.updating.getTime());
				that.AJAX.open("GET", uri, true);
				that.AJAX.send(null);
			}
			return true;
		}
	}
	var urlCall = url;
	this.callback = function () { };
}

String.prototype.endsWith = function(s) {
    if (this.length>s.length) {
        if (this.substring(this.length-s.length).toLowerCase()==s.toLowerCase()) {
            return true;
        }
    }
    return false;
}	

String.prototype.startsWith = function(v) {
    if (this.substring(0,v.length).toLowerCase()==v.toLowerCase()) {
        return true;
    } else {
        return false;
    }
}

String.prototype.contains = function(s) {
    if (this.toLowerCase().indexOf(s.toLowerCase())>-1) {
        return true;
    } else {
        return false;
    }
}

String.prototype.preceedZeros = function(l) {
    var v=""
    if (this.length<l) {
        for (var i=0;i<(l-this.length);i++) {
            v = v + "0"
        }
    }
    return v + this
}

function $(s) { return document.getElementById(s) }

//***********************************************************
// Boot
//***********************************************************

if (document.location.href.endsWith("style=none")) {
    document.styleSheets[0].disabled=true
}

//***********************************************************
// On Load
//***********************************************************

function IsLoaded() {
    if (document.location.href.endsWith("style=none")) {
        var i = document.getElementsByTagName("a")
        for (var v=0;v<i.length;v++) { if (i[v].href.endsWith("?")) i[v].href=i[v].href + "style=none" }
        $('modeswitch').innerHTML="<a href='" + document.location.href.replace("?style=none","") + "'>Switch to design mode</a>"
    } else {
        $('modeswitch').innerHTML="<a href='" + document.location.href + "?style=none'>Switch to plain mode</a>"
    }
}

//***********************************************************
// Insert Functionality
//***********************************************************

function InsertDate(into) {
	o = document.getElementById(into)
	var day="";
	var month="";
	var ampm="";
	var ampmhour="";
	var myweekday="";
	var year="";
	mydate = new Date();
	myday = mydate.getDay();
	mymonth = mydate.getMonth();
	myweekday= mydate.getDate();
	weekday= myweekday;
	myyear= mydate.getYear();
	myhours = mydate.getHours();
	ampmhour = (myhours > 12) ? myhours - 12 : myhours;
	ampm = (myhours >= 12) ? 'PM' : 'AM';
	mytime = mydate.getMinutes();
	myminutes = ((mytime < 10) ? ':0' : ':') + mytime;
	year = (myyear > 100) ? myyear : 1900 + myyear;
	if(myday ==0)
	day = " Sunday, ";
	else if(myday == 1)
	day = " Monday, ";
	else if(myday == 2)
	day = " Tuesday, ";
	else if(myday == 3)
	day = " Wednesday, ";
	else if(myday == 4)
	day = " Thursday, ";
	else if(myday == 5)
	day = " Friday, ";
	else if(myday == 6)
	day = " Saturday, ";
	if(mymonth == 0) {
	month = "January ";}
	else if(mymonth ==1)
	month = "February ";
	else if(mymonth ==2)
	month = "March ";
	else if(mymonth ==3)
	month = "April ";
	else if(mymonth ==4)
	month = "May ";
	else if(mymonth ==5)
	month = "June ";
	else if(mymonth ==6)
	month = "July ";
	else if(mymonth ==7)
	month = "August ";
	else if(mymonth ==8)
	month = "September ";
	else if(mymonth ==9)
	month = "October ";
	else if(mymonth ==10)
	month = "November ";
	else if(mymonth ==11)
	month = "December ";
	o.innerHTML = day + month + myweekday;
}

var DataMoorings, DataMarinas

function InsertList(into, id) {
	url="http://www.hha.co.uk/proxy.php"
	ajaxRequest = new ajaxObject(url,into); 
	ajaxRequest.callback = ProcessList
	ajaxRequest.update("proxy_url=library/json_internal_list.asp%3Fid=" + id);
}

function ProcessList(r, into) {
    var o
	try {
	    o = JSON.parse(r)
	    eval(into + "=o")
	} catch(_err) {
	}
}

function InsertContactList(into, id) {
	o = $(into)
	o.innerHTML='<span class="loader">loading...</span>'
	url="http://www.hha.co.uk/proxy.php"
	ajaxRequest = new ajaxObject(url,into); 
	ajaxRequest.callback = DrawContactList
	ajaxRequest.update("proxy_url=library/json_internal_list.asp%3Fid=" + id);
}

function DrawContactList(r, into) {
    var d, t = ""
	try {
	    d = JSON.parse(r)
	} catch(_err) {
	}
	o = $(into)
	o.innerHTML=t
	t="<select id='combo_contactdetails' onchange=\"ChangeContact(this)\"><option></option>"
	if (d.items) {
	    for (var i=0;i<d.items.length;i++) {
	        t = t + "<option value=\"" + StringifyContact(d.items[i]).replace(/"/g,"\"") + "\">" + d.items[i].name + "</option>"
	    }
	}
	t = t + "</select><div id='data_contactdetails' class='hide'></div>"
	o.innerHTML=t
}

function ChangeContact(o) {
    d=$('data_contactdetails')
    if (!(o.value=="")) { 
        d.className='show';
        d.innerHTML=o.options[o.selectedIndex].value
    } else {
        d.className='hide';
    }
}

function StringifyContact(item) {
    var t = ""
    if (item.name) if (!(item.name=="")) t = t + "<strong>" + item.name + "</strong><br />"
    if (item.tel) if (!(item.tel=="")) t = t + "Tel: " + item.tel + "<br />"
    if (item.fax) if (!(item.fax=="")) t = t + "Fax: " + item.fax + "<br />"
    if (item.email) if (!(item.email=="")) t = t + "Email: <a href='mailto:" + item.email + "'>click here</a>" + "<br />"
    if (item.web) if (!(item.web=="")) t = t + "Website: <a href='http://" + item.web + "'>click here</a>" + "<br />"
    if (item.note) if (!(item.note=="")) t = t + "<small>" + item.note + "</small><br />"
    return t
}

function InsertFiles(into, id, limit, order, classname, comments) {
	o = $(into)
	o.innerHTML='<span class="loader">loading...</span>'
	url="http://www.hha.co.uk/proxy.php"
	o._class=classname
	o._comments=comments
	ajaxRequest = new ajaxObject(url,into); 
	ajaxRequest.callback = DrawFiles
	ajaxRequest.update("proxy_url=library/json_files.asp%3Fid=" + id + "%26limit=" + limit + "%26order=" + order);
}

function DrawFiles(r,o) {
	var o = $(o)
	var d, t = ''
	try {
	    d = JSON.parse(r)
	} catch(_err) {
	    t = '<p>There was a problem getting the file data.</p>'
	}
	o.innerHTML=t
	if (d.files) {
		t = '<ul>'
		if (d.files.length==0) {
			t = '<p>There are currently no files to display.</p>'
		}
		for (i=0;i<d.files.length;i++) {
		    if (o._class=="") {
		        if (d.files[i].filename.endsWith("doc")) o._class = "ico_doc"
		        if (d.files[i].filename.endsWith("dot")) o._class = "ico_doc"
		        if (d.files[i].filename.endsWith("pdf")) o._class = "ico_pdf"
		        if (d.files[i].filename.endsWith("xls")) o._class = "ico_xls"
		        if (d.files[i].filename.endsWith("jpg")) o._class = "ico_image"
		        if (d.files[i].filename.endsWith("gif")) o._class = "ico_image"
		        if (d.files[i].filename.endsWith("bmp")) o._class = "ico_image"
		        if (d.files[i].filename.endsWith("png")) o._class = "ico_image"
		        if (o._class=="") o._class = "ico_file"
		    }
			t = t + '<li class="' + o._class + '"><a href="proxy.php?proxy_url=library/files/' + d.files[i].filename + '">' + d.files[i].name +'</a> <small>[' + d.files[i].ref +'] ' + d.files[i].description +'</small>'
			if (o._comments==true) t = t + '<div class="commentarea" id="comment_' + d.files[i].id + '"><ul><li class="ico_comment"><small><a class="comment" href="javascript:" onclick="InsertComments(' + d.files[i].id + ')">' + d.files[i].comments +' Comments</a></small></li></ul></div>'
			t = t + '</li>'
		}
		t = t + '</ul>'
	} else {
		t = '<p>The was a problem getting file data.</p>'
	}
	o.innerHTML = t
}

function InsertComments(s) {
    var o = $('comment_' + s)
	o.innerHTML='<small><span class="loader">loading...</span></small>'
	url="http://www.hha.co.uk/proxy.php"
	ajaxRequest = new ajaxObject(url,s); 
	ajaxRequest.callback = DrawComments
	ajaxRequest.update("proxy_url=library/json_comments.asp%3Fid=" + s);
}

function DrawComments(r,s) {
	var d, o, t = ''
	try {
	    d = JSON.parse(r)
	} catch(_err) {
	    t = '<small>There was a problem getting the comments.</small>'
	}
    o = $('comment_' + s)
	o.innerHTML=t
	if (d.comments) {
		t = '<ul>'
		for (i=0;i<d.comments.length;i++) {
			t = t + '<li class="ico_comment"><small><strong>' + d.comments[i].name +'</strong><br />' + d.comments[i].comment + '</small></li>'
		}
		t = t + '<li class="ico_comment_new"><div id="commentnew_' + s + '"><small>Name:</small><br /><input id="commentname_' + s + '" style="width:100%;" class="text" /><br /><small>Email:</small><br /><input id="commentemail_' + s + '" style="width:100%;" class="text" /><br /><textarea id="commenttext_' + s + '" style="width:100%;" class="textarea"></textarea><br><a href="javascript:" onclick="PostComment(' + s + ')">Post Comment</a></li></ul>'
	} else {
		t = '<small>The was a problem getting the comments.</small>'
	}
	o.innerHTML = t
}


var oharwichdata,ofelixstowedata,omistleydata,ohighlowdata,olandguarddata,oshotleydata

function InsertNav(harwichdata,felixstowedata,mistleydata,highlowdata,landguarddata,shotleydata) {
	oharwichdata = document.getElementById(harwichdata)
	ofelixstowedata = document.getElementById(felixstowedata)
	omistleydata = document.getElementById(mistleydata)
	ohighlowdata = document.getElementById(highlowdata)
	olandguarddata = document.getElementById(landguarddata)
	oshotleydata = document.getElementById(shotleydata)
	if (oharwichdata) { oharwichdata.innerHTML='<span class="loader">loading...</span>' }
	if (ofelixstowedata) { ofelixstowedata.innerHTML='<span class="loader">loading...</span>' }
	if (omistleydata) { omistleydata.innerHTML='<span class="loader">loading...</span>' }
	if (ohighlowdata) { ohighlowdata.innerHTML='<span class="loader">loading...</span>' }
	if (olandguarddata) { olandguarddata.innerHTML='<span class="loader">loading...</span>' }
	if (oshotleydata) { oshotleydata.innerHTML='<span class="loader">loading...</span>' }
	url="http://www.hha.co.uk/proxy.php"
	ajaxRequest = new ajaxObject(url); 
	ajaxRequest.callback = DrawNav
	ajaxRequest.update("proxy_url=misonline/weather.json");
}

function DrawNav(r) {
	var d, t = ''
	try {
	    d = JSON.parse(r)
	} catch(_err) {
	    t = '<p>There was a problem getting the file data.</p>'
	}
	if (oharwichdata) { oharwichdata.innerHTML=t }
	if (ofelixstowedata) { ofelixstowedata.innerHTML=t }
	if (omistleydata) { omistleydata.innerHTML=t }
	if (ohighlowdata) { ohighlowdata.innerHTML=t }
	if (olandguarddata) { olandguarddata.innerHTML=t }
	if (oshotleydata) { oshotleydata.innerHTML=t }
	if (d.tide) {
		if (oharwichdata) { 
			oharwichdata.innerHTML='<strong>Predicted</strong> : ' + TrimNav(d.harwich[0].predicted) + '<br /><strong>Actual</strong> : ' + TrimNav(d.harwich[0].actual) + '<br /><strong>Surge</strong> : ' + TrimNav(d.harwich[0].surge)
		}
		if (ofelixstowedata) { 
			ofelixstowedata.innerHTML='<strong>Actual</strong> : ' + TrimNav(d.felixstowe[0].actual) 
		}
		if (omistleydata) { 
			omistleydata.innerHTML='<strong>Actual</strong> : ' + TrimNav(d.mistley[0].actual) 
		}
		if (ohighlowdata) { 
			for (i=0;i<d.tide.length;i++) {
				ohighlowdata.innerHTML=ohighlowdata.innerHTML + '<strong>' + d.tide[i].type + ' Tide @ ' + d.tide[i].time + '</strong> : ' + d.tide[i].height + 'm<br />'
			}
		}
		if (olandguarddata) { 
			olandguarddata.innerHTML=olandguarddata.innerHTML + '<strong>Speed</strong> : ' + TrimNav(d.languard[0].speed) + '<br />'
			olandguarddata.innerHTML=olandguarddata.innerHTML + '<strong>Direction</strong> : ' + TrimNav(d.languard[0].direction) + '<br />'
			olandguarddata.innerHTML=olandguarddata.innerHTML + '<strong>Gust</strong> : ' + TrimNav(d.languard[0].gust)
		}
		if (oshotleydata) { 
			oshotleydata.innerHTML=oshotleydata.innerHTML + '<strong>Speed</strong> : ' + TrimNav(d.shotley[0].speed) + '<br />'
			oshotleydata.innerHTML=oshotleydata.innerHTML + '<strong>Direction</strong> : ' + TrimNav(d.shotley[0].direction) + '<br />'
		}
	} else {
		if (oharwichdata) { olivetidaldata.innerHTML='<p>The was a problem getting navigation data.</p>' }
		if (ofelixstowedata) { ofelixstowedata.innerHTML='<p>The was a problem getting navigation data.</p>' }
		if (omistleydata) { omistleydata.innerHTML='<p>The was a problem getting navigation data.</p>' }
		if (ohighlowdata) { ohighlowdata.innerHTML='<p>The was a problem getting navigation data.</p>' }
		if (olandguarddata) { olandguarddata.innerHTML='<p>The was a problem getting navigation data.</p>' }
		if (oshotleydata) { oshotleydata.innerHTML='<p>The was a problem getting navigation data.</p>' }
	}
}

function TrimNav(s) {
	return s.substring(0,s.indexOf("("))	
}

function InsertHTML(o, s) {
	o = $(o)
	o.innerHTML=s
}

var AdjustMins = 0, AdjustHeight = 0, PredictedData

function InsertPredictedToday(so, sd) {
	o = $(sd)
    d = new Date()
    o.value = d.getDay().toString().preceedZeros(2) + "/" + (d.getMonth()+1).toString().preceedZeros(2) + "/" + d.getFullYear().toString().substring(2,4)
    InsertPredicted(so,sd)
}

function InsertPredicted() {
        o = $("data_predicted")
        g = $("graph_predicted")
		d = $("predicted_date")
		if (d.isValid==false) {
		    alert("Please enter a valid date.")
		    return false;
		}
		o.innerHTML='<span class="loader">loading...</span>'
		if (g) g.innerHTML='<span class="loader">loading...</span>'
		url="http://www.hha.co.uk/proxy.php"
		ajaxRequest = new ajaxObject(url); 
		ajaxRequest.callback = DrawPredicted
		ajaxRequest.update("proxy_url=misonline/predicted.json%3Fdate=" + d.value.substring(0,2) + "-" + d.value.substring(3,5) + "-" + d.value.substring(6,8));
}

function DrawPredicted(r) {
	var t=''
	try {
	    PredictedData = JSON.parse(r)
	} catch(_err) {
	    t = '<p>There was a problem getting the predicted data.</p>'
	    return false;
	}
	RefreshPredicted()
}

function RefreshPredicted() {
    var t=""
    var d=PredictedData
	var o=$("data_predicted")
	o.innerHTML=t
	if (!(AdjustMins==0) || !(AdjustHeight==0)) {
	    t = "<div class='warn'><small>The heights displayed below are an estimate based on adjusting the time by " + AdjustMins + "min(s) and the heights by " + AdjustHeight + ".</small></div>"
	}
	t = t + "<table cellpadding='2' cellspacing='0' border='0' width='100%'>"
    t = t + "<tr><td>&nbsp;&nbsp;</td><td><strong>Time</strong></td><td><strong>Value</strong></td><td><strong>Time</strong></td><td><strong>Value</strong></td></tr>"
	for (i=0;i<(d.predicted.length/2);i++) {
		t = t + "<tr><td>&nbsp;&nbsp;</td><td>" + FixPredictedTime(d.predicted[i].time) + "</td><td>" + FixPredictedValue(d.predicted[i].value) + "</td><td>" + FixPredictedTime(d.predicted[i+12].time) + "</td><td>" + FixPredictedValue(d.predicted[i+12].value) + "</td></tr>"
	}
	t = t + "</table>"
	o.innerHTML=t
	o=$("graph_predicted")
	if (!o) return true; 
	t="<div style='padding-top:25px;'>"
	var h=300
	for (i=0;i<d.predicted.length;i++) {
		t = t + "<div style='float:left'><div style='width:8px; height:" + ((1-d.predicted[i].value/5)*h) + "px;'></div><div style='background:#94B8D8; width:8px; height:" + ((d.predicted[i].value/5)*h) + "px;'></div></div>"
		//"<div style='width:" + parseInt((d.predicted[i].value/5)) + "%;height:15px;background:#94B8D8;'></div>"
	}
	t = t + "<div style='float:none; clear:both;'></div></div>"
	o.innerHTML=t
}

function FixPredictedValue(s) {
    return Number(Number(s)+AdjustHeight).toFixed(3)
}

function FixPredictedTime(s) {
    var hh=Number(s.substring(0,2))
    var mm=Number(s.substring(3,5))
    //alert(hh + " " + mm)
    if (AdjustMins<0) {
        hh=hh-1
        if (hh<0) hh=23
        mm=60+AdjustMins
    }
    if (AdjustMins>0) {
        mm=AdjustMins
    }
    return hh.toString().preceedZeros(2) + ":" + mm.toString().preceedZeros(2)
}

function TidalDifferences(id) {
	if (id=="0") {
	    AdjustMins=0
	    AdjustHeight=0
	}
	if (id=="1") {
	    AdjustMins=25
	    AdjustHeight=0.2
	}
	if (id=="2") {
	    AdjustMins=25
	    AdjustHeight=0.3
	}
	if (id=="3") {
	    AdjustMins=20
	    AdjustHeight=0.1
	}
	if (id=="4") {
	    AdjustMins=29
	    AdjustHeight=0
	}
	if (id=="5") {
	    AdjustMins=23
	    AdjustHeight=0
	}
	if (id=="6") {
	    AdjustMins=42
	    AdjustHeight=0
	}
	if (id=="7") {
	    AdjustMins=11
	    AdjustHeight=0
	}
	if (id=="8") {
		//result="<strong>Time</strong> : -(0 to 60)"
	}
	if (id=="9") {
	    AdjustMins=-11
	    AdjustHeight=0
	}
	if (id=="10") {
	    AdjustMins=-31
	    AdjustHeight=0
	}
	if (id=="11") {
	    AdjustMins=40
	    AdjustHeight=0
	}
	if (id=="12") {
	    AdjustMins=12
	    AdjustHeight=0
	}
	if (id=="13") {
	    AdjustMins=0
	    AdjustHeight=0
	}
	if (id=="14") {
	    AdjustMins=27
	    AdjustHeight=0
	}
	if (id=="15") {
	    AdjustMins=32
	    AdjustHeight=0
	}
	if (id=="16") {
	    AdjustMins=-2
	    AdjustHeight=0
	}
}


//***********************************************************
// Validation Functionality
//***********************************************************

function validateEmail(o) {
    if(o.value.contains("@") && o.value.contains(".")) { o.isValid=true } else { o.isValid=false }
}

function validateDate(o, sep, format) {
    s = o.value.split(sep)
    o.isValid=true
    
    if (s.length==3) {
        if (isNaN(s[0])==false && isNaN(s[1])==false && isNaN(s[2])==false) {
            if (!((s[0]+s[1]+s[2]).length==format.length)) {
                if (!(s[2].length==2) && !(s[2].length==4)) o.isValid=false
                if (format.endsWith("yyyy")) {
                    if (s[2].length==2 && Number(s[2])<40) s[2]=String(Number(s[2])+2000)
                    if (s[2].length==2 && Number(s[2])>=40) s[2]=String(Number(s[2])+1900)
                } else {
                    if (s[2].length==4) s[2]=String(s[2]).substring(2,4)
                }
                if (o.isValid==true) o.value=s[0].preceedZeros(2) + sep + s[1].preceedZeros(2) + sep + s[2]
            }
        } else {
            o.isValid=false
        }
    } else {
        o.isValid=false
    }
}


//***********************************************************
// FLASH Functionality
//***********************************************************

function FlashAtlasTime(sTime) {
	if (document.all) {
		omap=$("map")
		omap.SetVariable("newLayer",  sTime)
	} else {
		vmap=$("omap")
		vmap.SetVariable("newLayer",  sTime)	
	}
}

function popupMarina(ID) {
	var smap="", theItem
	owin=$("popup")
	oflash=$("ins_map")
	otext=$("ins_data")
	if (DataMarinas.items) {
	    for (var i=0; i<DataMarinas.items.length; i++) {
	        if (DataMarinas.items[i].id==ID) {
	            theItem = DataMarinas.items[i]
	        }
	    }
	    if (theItem) {
		    oflash.innerHTML='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" align="middle" width="433" height="386" codeBase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0"><embed src="maps/viewer.swf?mapfile=maps/' + theItem.mapfilename +'&imgdir=maps/" quality="high" bgcolor="#ffffff" width="433" height="386" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"/><param name="Movie" value="maps/viewer.swf?mapfile=maps/' + theItem.mapfilename +'&imgdir=maps/"></param><param name="Src" value="maps/viewer.swf?mapfile=maps/' + theItem.mapfilename +'&imgdir=maps/"></param><param name="Play" value="-1"></param><param name="Loop" value="-1"></param><param name="Quality" value="High"></param><param name="SAlign"></param><param name="Menu" value="-1"></param><param name="Base"></param><param name="AllowScriptAccess" value="sameDomain"></param><param name="Scale" value="ShowAll"></param><param name="DeviceFont" value="0"></param><param name="EmbedMovie" value="0"></param><param name="BGColor" value="FFFFFF"></param><param name="SWRemote"></param><param name="MovieData"></param><param name="SeamlessTabbing" value="1"></param><param name="Profile" value="0"></param><param name="ProfileAddress"></param><param name="ProfilePort" value="0"></param><param name="AllowNetworking" value="all"></param><param name="AllowFullScreen" value="false"></param></object>'
		    otext.innerHTML='<h1>' + theItem.name + '</h1><p>' + theItem.description.replace(/'/g,"\'").replace(/\r/g,"<br />") + '</p>' + InsertMarinaFacilities(theItem.facillities) + '<p><a href="javascript:" onclick="closeMarina()">Go back to the map</a></p>'
		    owin.style.display="block"
	    }
	}
}

function InsertMarinaFacilities(sFacilities) {
		Facilities = new Array()
		Facilities = ["VHF CH 80","Visitor's Berths","Restaurant/Bar","Showers","Launching Slip","Electricity","Sanitation Pump Out","Diesel","Petrol","LPG Gas (Engine)","Chandlery","Gas Bottles","Laundrette","Provisions","Boat Hoist & Cranage","Scrubbing Berth","Workshop","Road Transport","Rubbish Bins", "Hazardous Waste/Oil"]
		sOutput=""
		if (sFacilities.length==20) {
			sOutput = "<table cellspacing='0' cellpadding='0' width='100%'>"
			for (i=0;i<10;i++) {
				if (sFacilities.charAt(i)=="1") {
					sA="<img src='_stuff/ico_bullet2.png' />"
				} else {
					sA="<img src='_stuff/ico_bullet3.png' />"
				}
				if (sFacilities.charAt(i+10)=="1") {
					sB="<img src='_stuff/ico_bullet2.png' />"
				} else {
					sB="<img src='_stuff/ico_bullet3.png' />"
				}
				sOutput=sOutput + "<tr><td>" + sA + "</td><td>" + Facilities[i] + "</td><td>" + sB + "</td><td>" + Facilities[i+10] + "</td></tr>"
			}
			sOutput=sOutput + "</table>	"
		}
		return sOutput
}

function closeMarina() {
	owin=document.getElementById("popup")
	owin.style.display="none"
}

function popupMooring(ID) {
	var smap=""
	var smap="", theItem
	owin=$("popup")
	oflash=$("ins_map")
	otext=$("ins_data")
	if (DataMoorings.items) {
	    for (var i=0; i<DataMoorings.items.length; i++) {
	        if (DataMoorings.items[i].id==ID) {
	            theItem = DataMoorings.items[i]
	        }
	    }
	    if (theItem) {
		    oflash.innerHTML='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" align="middle" width="433" height="386" codeBase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0"><embed src="maps/viewer.swf?mapfile=maps/' + theItem.mapfilename +'&imgdir=maps/" quality="high" bgcolor="#ffffff" width="433" height="386" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"/><param name="Movie" value="maps/viewer.swf?mapfile=maps/' + theItem.mapfilename +'&imgdir=maps/"></param><param name="Src" value="maps/viewer.swf?mapfile=maps/' + theItem.mapfilename +'&imgdir=maps/"></param><param name="Play" value="-1"></param><param name="Loop" value="-1"></param><param name="Quality" value="High"></param><param name="SAlign"></param><param name="Menu" value="-1"></param><param name="Base"></param><param name="AllowScriptAccess" value="sameDomain"></param><param name="Scale" value="ShowAll"></param><param name="DeviceFont" value="0"></param><param name="EmbedMovie" value="0"></param><param name="BGColor" value="FFFFFF"></param><param name="SWRemote"></param><param name="MovieData"></param><param name="SeamlessTabbing" value="1"></param><param name="Profile" value="0"></param><param name="ProfileAddress"></param><param name="ProfilePort" value="0"></param><param name="AllowNetworking" value="all"></param><param name="AllowFullScreen" value="false"></param></object>'
		    otext.innerHTML='<h1>' + theItem.title + '</h1><p><small>' + theItem.description.replace(/'/g,"\'").replace(/\r/g,"<br />") + '</small></p><p><a href="javascript:" onclick="closeMarina()">Go back to the map</a></p>'
		    owin.style.display="block"
	    }
	}
}

function closeMooring() {
	owin=document.getElementById("mapwindow")
	owin.style.display="none"
}

//***********************************************************
// POST Functionality
//***********************************************************

function PostComment(id) {
    n = $('commentname_' + id)
    e = $('commentemail_' + id)
    t = $('commenttext_' + id)
    o = $('commentnew_' + id)
    if (!(t.value=="")) {
		s="id=%id%%26name=%name%%26email=%email%%26comment=%text%"
		s=s.replace("%name%",escape(n.value.replace(/ /g,"^")))
		s=s.replace("%email%",escape(e.value.replace(/ /g,"^")))
		s=s.replace("%text%",escape(t.value.replace(/ /g,"^")))
		s=s.replace("%id%",id)
	    o.innerHTML='<span class="loader">posting...</span>'
		url="http://www.hha.co.uk/proxy.php"
		ajaxRequest = new ajaxObject(url,'$(\'commentnew_' + id + '\').innerHTML=\'<small><strong>' + n.value +'</strong><br />' + t.value + '</small>\''); 
		ajaxRequest.callback = FinishedComment
		ajaxRequest.update("proxy_url=library/json_postcomment.asp%3F" + s);
    } else {
        alert("Please ensure you enter a comment.")
    }
}

function FinishedComment(r,id) {
	var d, t
    eval(id)
	t = 'Your comment has been submitted and is waiting to be mediated.'
	try {
	    d = JSON.parse(r)
	} catch(_err) {
	    t = 'There was a problem submitting your request.'
	}
	alert(t)	
}

function PostSubscription() {
    if ($("email").isValid==true) {
        s=document.getElementById("submit")
		e=document.getElementById("email")
		t=""
		for (var i=1; i < 8; i++) {
		   o=$("subscribe"+i)
		   if (o.checked) {
			  t = t + o.value + ",";
		   }
		}
		p="id=%ids%%26email=%email%"
		p=p.replace("%email%",escape(e.value.replace(/ /g,"^")))
		p=p.replace("%ids%",t)
	    s.innerHTML='<span class="loader">posting...</span>'
		url="http://www.hha.co.uk/proxy.php"
		ajaxRequest = new ajaxObject(url); 
		ajaxRequest.callback = FinishedSubscription
		ajaxRequest.update("proxy_url=library/json_subscribe.asp%3F" + p);
    } else {
        alert("Please ensure you enter a valid email address.")
    }
}

function FinishedSubscription(r) {
	var d, t
	t = 'Your subscription has been registered.  You can unsubscribe at any time using the links in the sent emails.'
	try {
	    d = JSON.parse(r)
	} catch(_err) {
	    t = 'There was a problem submitting your request.'
	}
	s=$("submit")
	s.className=""
	alert(t)	
}

//***********************************************************
// TABS Functionality
//***********************************************************

var oldTab=""
function SelectTab(s) {
    if (!(oldTab=="")) {
        t = $("tab_" + oldTab)
        c = $("content_" + oldTab)
        t.className = t.className.replace("selected","")
        c.className = c.className.replace("show","hide")
    }
    t = $("tab_" + s)
    c = $("content_" + s)
    t.className = t.className=t.className + " selected"
    c.className = c.className.replace("hide","show")
    oldTab=s
}

//***********************************************************
// Calculator Functionality - NEEDS WORK
//***********************************************************


function formatCurrency(strValue)
{
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + '&pound;' + dblValue + '.' + strCents);
}

function chkValue(ival, ilow, ihigh, iret) {
	if (ival>ilow && ival<=ihigh) {
		return iret
	} else {
		return 0
	}
}

function calcCharges() {

	var iType = document.getElementById("Type").value
	var iGT = document.getElementById("GT").value
	var iDraft = document.getElementById("Draft").value
	var aErr = false
	var tmpPilot = 0
	var tmpConser = 0
	
	if (iType<1 || iType>3) {
		aErr=true
		alert("Please select a valid type")
	} else if (isNaN(iGT)==true) {
		aErr=true
		alert("Please enter a valid number in the Gross Tonnage box")
	} else if (isNaN(iDraft)==true || iDraft=="") {
		aErr=true
		alert("Please enter a valid number in the Max. Draft box")
	}
	
	if (aErr==false) {
		if (iType==1) {
			tmpPilot+=chkValue(iGT,0,10000,531)
			tmpPilot+=chkValue(iGT,10000,18500,638)
			tmpPilot+=chkValue(iGT,18500,25000,796)
			tmpPilot+=chkValue(iGT,25000,9999999,954)
		} else {
			tmpPilot+=chkValue(iGT,0,3500,459)
			tmpPilot+=chkValue(iGT,3500,4000,510)
			tmpPilot+=chkValue(iGT,4000,4500,551)
			tmpPilot+=chkValue(iGT,4500,5000,466)
			tmpPilot+=chkValue(iGT,5000,6000,602)
			tmpPilot+=chkValue(iGT,6000,7000,612)
			tmpPilot+=chkValue(iGT,7000,8000,648)
			tmpPilot+=chkValue(iGT,8000,9000,694)
			tmpPilot+=chkValue(iGT,9000,10000,714)
			tmpPilot+=chkValue(iGT,10000,11000,755)
			tmpPilot+=chkValue(iGT,11000,12000,765)
			tmpPilot+=chkValue(iGT,12000,13000,785)
			tmpPilot+=chkValue(iGT,13000,14000,801)
			tmpPilot+=chkValue(iGT,14000,15000,816)
			tmpPilot+=chkValue(iGT,15000,16000,847)
			tmpPilot+=chkValue(iGT,16000,17000,872)
			tmpPilot+=chkValue(iGT,17000,18000,882)
			tmpPilot+=chkValue(iGT,18000,19000,913)
			tmpPilot+=chkValue(iGT,19000,20000,928)
			tmpPilot+=chkValue(iGT,20000,22500,939)
			tmpPilot+=chkValue(iGT,22500,25000,964)
			tmpPilot+=chkValue(iGT,25000,27500,979)
			tmpPilot+=chkValue(iGT,27500,60000,989)
			tmpPilot+=chkValue(iGT,60000,80000,1030)
			tmpPilot+=chkValue(iGT,80000,100000,1051)
			tmpPilot+=chkValue(iGT,100000,125000,1127)
			tmpPilot+=chkValue(iGT,125000,150000,1479)
			tmpPilot+=chkValue(iGT,150000,175000,1688)
		}
		if (iType==1) {
			tmpConser+=(chkValue(iGT,0,10000,0.0092)*iGT)
			tmpConser+=(chkValue(iGT,10000,18500,0.0107)*iGT)
			tmpConser+=(chkValue(iGT,18500,25000,0.0158)*iGT)
			tmpConser+=(chkValue(iGT,25000,9999999,0.0190)*iGT)
		} else if (iType==2) {
			tmpConser=iGT*0.0188
		} else {
			tmpConser+=(chkValue(iGT,0,5000,0.0173)*iGT)
			tmpConser+=(chkValue(iGT,5000,10000,0.0202)*iGT)
			tmpConser+=(chkValue(iGT,10000,15750,0.0318)*iGT)
			tmpConser+=(chkValue(iGT,15750,25000,0.1125)*iGT)
			tmpConser+=(chkValue(iGT,25000,100000,0.1150)*iGT)
			tmpConser+=(chkValue(iGT,100000,9999999,0.1250)*iGT)
			if (iGT>15750 && iDraft<8.6) {
				tmpConser=iGT*0.0423
			}
		}
	}
	
	document.getElementById("results").innerHTML="<h2>Results</h2><p><strong>Pilotage</strong> : " + formatCurrency(tmpPilot) + "<br /><strong>Conservancy</strong> : " + formatCurrency(tmpConser) + "</p>"

}



function ContactDetails(id) {
	objresult=document.getElementById("contactdata")
	var contact=""
	var tel=""
	var fax=""
	var email=""
	if (id=="1") {
		tel="+44 (0) 1255 243030"
		fax="+44 (0) 1255 241302"
		email="enquiry@hha.co.uk"
	}
	if (id=="2") {
		contact="Tina Wood"
		tel="+44 (0) 1255 243030"
		fax="+44 (0) 1255 504946"
		email="pec@hha.co.uk"
	}
	if (id=="3") {
		contact="Lin Keating"
		tel="+44 (0) 1255 243030"
		fax="+44 (0) 1255 240933"
		email="ntm@hha.co.uk"
	}
	if (id=="4") {
		tel="+44 (0) 1255 243030"
		fax="+44 (0) 1255 241302"
		email="enquiry@hha.co.uk"
	}
	if (id=="5") {
		tel="+44 (0) 1255 243030"
		fax="+44 (0) 1255 241302"
		email="accounts@hha.co.uk"
	}
	if (id=="6") {
		contact="Glyn Phillips"
		tel="+44 (0) 1255 243030"
		fax="+44 (0) 1255 507183"
		email="environment@hha.co.uk"
	}
	if (id=="7") {
		contact="John Adams"
		tel="+44 (0) 1255 243030"
		fax="+44 (0) 1255 241325"
		email="notification@hha.co.uk"
	}
	if (id=="8") {
		tel="+44 (0) 1255 243030"
		fax="+44 (0) 1255 240933"
		email="recruitment@hha.co.uk"
	}
	if (id=="9") {
		email="webmaster@hha.co.uk"
	}
	r=""
	if (!(contact=="")) {
		r=r+"<p><strong>Contact</strong> : " + contact + "</p>"	
	}
	if (!(tel=="")) {
		r=r+"<p><strong>Telephone</strong> : " + tel + "</p>"	
	}
	if (!(fax=="")) {
		r=r+"<p><strong>Fax</strong> : " + fax + "</p>"	
	}
	if (!(email=="")) {
		r=r+"<p><strong>Email</strong> : <a href='mailto:" + email + "'>" + email + "</a></p>"	
	}
	objresult.innerHTML=r
}