///// Onload Events

var onload_events = new Array();

function set_onload(f)
{
	var i = onload_events.length;
	onload_events[i] = f;
}

function do_onload()
{
	if(onload_events.length == 0) return;

	for(var i=0; i<onload_events.length; i++)
	{
		eval(onload_events[i] + "()");
	}
}

onload=do_onload;


///// Menu Pop-Ups

function menu_pu()
{
	if(document.all && document.getElementById)
	{
		var pu = new Array("t-menu","l-menu");

		for(var i=0; i<pu.length; i++)
		{
			var nav_root = document.getElementById(pu[i]);

			if(nav_root)
			{	
				for(var j=0; j<nav_root.childNodes.length; j++)
				{
					var node = nav_root.childNodes[j];
		
					if(node.nodeName=="LI")
					{
						node.onmouseover=function()
						{
							this.className+=" over";
							this.style.zIndex = "1000";
						}
						node.onmouseout=function()
						{
		  					this.className=this.className.replace(" over", "");
							this.style.zIndex = "50";
						}
					}
				}
			}
		}
	}
}

set_onload("menu_pu");

///// Form Functions

function trim(s)
{
	return s.replace(/^\s+|\s+$/g, '');
}

function valid_email(ea)
{
	var email_reg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
	var regex = new RegExp(email_reg);
	return regex.test(ea);
  }

function validate(f,el)
{
	var address = trim(document.getElementById(el).value);
	var valid = valid_email(address);

	if(!valid)
	{
		alert("\"" + address + "\" is not a valid email address. A valid email address is required to submit this form.");
		f.focus();
		f[el].select();
		return false;
	}
	else return true;
}

function form_focus()
{
	var f = document.forms[0];
	
	if(f == null)
		return;

	for(var i=0; i<f.elements.length; i++)
	{
		if(f.elements[i].type.indexOf("text") > -1 && f.elements[i].disabled != true)
		{
			f.elements[i].focus();
			break;
		}
	}
}

// Decided against loading the form focus onload
//set_onload("form_focus");

function toggle_search(obj,action)
{
	var input = obj;
	var default_text = "Search Site";

	if(action)
	{
		if(input.value == default_text)
		{
			input.value = "";
			input.style.color = "#30302f";
		}
	}
	else
	{
		if(input.value == "")
		{
			input.value = default_text;
			input.style.color = "#bbb";
		}
	}
}

///// Content Body Check 
// It's possible that the left menu height to be larger than the content
// The problem with that it is since the background image (which contains the white background) is within the content element
// So the left menu "overhangs" the white background
// We need to make the content height at least as large as the left menu height (actually more, some padding would look good)
function content_height()
{
	var p_content = document.getElementById("p-content"); // Main content area
	var c_left = document.getElementById("c-left"); // The left menu
	var a_right = document.getElementById("a-right"); // The right insets within the content (Firefox doesn't include this height in the content height)
	var page_tools = document.getElementById("page-tools");
	var placeholder = document.getElementById("placeholder");
	var h1 = p_content.getElementsByTagName("h1")[0];
	var c_article = document.getElementById("c-article");

	if(!a_right) a_right = 0;

	p_content_height = parseInt(p_content.offsetHeight);
	menu_height = parseInt(c_left.offsetHeight);
	right_height = parseInt(a_right.offsetHeight);
	page_tools_height = (page_tools) ? parseInt(page_tools.offsetHeight) : 0;
	placeholder_height = (placeholder) ? parseInt(placeholder.offsetHeight) : 0;
	h1_height = parseInt(h1.offsetHeight);
	c_article_height = parseInt(c_article.offsetHeight);

	//alert(p_content_height);
	//alert(menu_height);
	//alert(right_height);
	//alert(page_tools_height);
	//alert(placeholder_height);
	//alert(h1_height);
	//alert(c_article_height);


	//p_content_height = c_article_height + placeholder_height + page_tools_height + h1_height + menu_height;
	//p_content.style.height = p_content_height + "px";

	//alert(p_content_height);

	if(p_content_height < right_height) right_height = p_content_height + right_height;

	check_height = (right_height > menu_height) ? right_height : menu_height;

	//alert(check_height);
	//alert(p_content_height);

	if(p_content_height < check_height)
	{
		p_content.style.height = (check_height) + "px";
	}
}

// Instead of callling "content_height()" onload, we'll call it from the footer.aspx file. No need to wait for images to load to do this.

///// Table Row Shading

function zebra_table()
{
	var t = document.getElementsByTagName("table");

	for(var i=0; i<t.length; i++)
	{
		if((t[i].className && t[i].className.indexOf("listing-table") > -1 || t[i].className && t[i].className.indexOf("option-table") > -1) &&  t[i].className && t[i].className.indexOf("no-zebra") < 0)
		{
			var r = t[i].rows;

			for(var j=0; j<r.length; j++)
			{
				if(r[j].className.indexOf("shade") > -1) r[j].className = r[j].className.replace("shade","");
				if(j%2 == 0) r[j].className+= " shade";
			}
		}
	}
}

set_onload("zebra_table");

///// Table Row Highlighting

function highlight_row()
{
	var t = document.getElementsByTagName("table");

	for(var i=0; i<t.length; i++)
	{
		if(t[i].className && t[i].className.indexOf("listing-table") > -1)
		{
			var table = t[i];

			for(var j=0; j<table.rows.length; j++)
			{
				table.rows[j].onmouseover = function()
				{
					if(this.className.length > 0)
					{
						this.className = this.className + " liter";
					}
					if(this.className == "")
					{
						this.className = "liter";
					}

					//alert("onmouseover: " + this.className);
				}
				table.rows[j].onmouseout = function()
				{
					//alert("onmouseout BEFORE: " + this.className);
					if(this.className.indexOf("liter") == 0)
					{
						//alert("liter");
						this.className = "";
					}
					if(this.className.indexOf(" liter"))
					{
						//alert(" liter");
						this.className = this.className.replace(" liter","");
					}

					//alert("onmouseout AFTER: " + this.className);
				}
			}
		}
	}
}

set_onload("highlight_row");

//// Table Sort

var SORT_COLUMN_INDEX;

function sortables_init() {
    // Find all tables with class sortable and make them sortable
    if (!document.getElementsByTagName) return;
    tbls = document.getElementsByTagName("table");
    for (ti=0;ti<tbls.length;ti++) {
        thisTbl = tbls[ti];
        if (((' '+thisTbl.className+' ').indexOf("listing-table") != -1) && ((' '+thisTbl.className+' ').indexOf("no-sort") < 0)) {
            //initTable(thisTbl.id);
            ts_makeSortable(thisTbl);
        }
    }
}

function ts_makeSortable(table) {
    if (table.rows && table.rows.length > 0) {
        var firstRow = table.rows[0];
    }
    if (!firstRow) return;
    
    // We have a first row: assume it's the header, and make its contents clickable links
    for (var i=0;i<firstRow.cells.length;i++) {
        var cell = firstRow.cells[i];
        var txt = ts_getInnerText(cell);
        cell.innerHTML = '<a href="javascript:void(0)" class="sort-header" onclick="ts_resortTable(this);return false;"><span class="sort-span">'+txt+'</span><span class="sortarrow"></span></a>';
    }
}

function ts_getInnerText(el) {
	if (typeof el == "string") return el;
	if (typeof el == "undefined") { return el };
	if (el.innerText) return el.innerText;	//Not needed but it is faster
	var str = "";
	
	var cs = el.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		switch (cs[i].nodeType) {
			case 1: //ELEMENT_NODE
				str += ts_getInnerText(cs[i]);
				break;
			case 3:	//TEXT_NODE
				str += cs[i].nodeValue;
				break;
		}
	}
	return str;
}

function ts_resortTable(lnk) {
    // get the span
    var span;
    for (var ci=0;ci<lnk.childNodes.length;ci++) {
        if (lnk.childNodes[ci].tagName && lnk.childNodes[ci].tagName.toLowerCase() == 'span') span = lnk.childNodes[ci];
    }
    var spantext = ts_getInnerText(span);
    var td = lnk.parentNode;
    var column = td.cellIndex;
    var table = getParent(td,'TABLE');
    
    // Work out a type for the column
    if (table.rows.length <= 1) return;
    var itm = ts_getInnerText(table.rows[1].cells[column]);
    sortfn = ts_sort_caseinsensitive;
    if (itm.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}/)) sortfn = ts_sort_date;
    //if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/)) sortfn = ts_sort_date;
    if (itm.match(/^[£$]/)) sortfn = ts_sort_currency;
    if (itm.match(/^[\d\.]+$/)) sortfn = ts_sort_numeric;
    SORT_COLUMN_INDEX = column;
    var firstRow = new Array();
    var newRows = new Array();
    for (i=0;i<table.rows[0].length;i++) { firstRow[i] = table.rows[0][i]; }
    for (j=1;j<table.rows.length;j++) { newRows[j-1] = table.rows[j]; }

    newRows.sort(sortfn);

    if (span.getAttribute("sortdir") == 'down') {
       	//ARROW = '&nbsp;&uarr;';
		ARROW = "<img src=\"/images/tables/sort-down.gif\" border=\"none\" width=\"9\" heigth=\"5\" alt=\"Column Sorted Descending\" />"
        newRows.reverse();
        span.setAttribute('sortdir','up');
    } else {
      	//ARROW = '&nbsp;&darr;';
		ARROW = "<img src=\"/images/tables/sort-up.gif\" border=\"none\" width=\"9\" heigth=\"5\" alt=\"Column Sorted Ascending\" />"
        span.setAttribute('sortdir','down');
    }

    // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
    // don't do sortbottom rows
    for (i=0;i<newRows.length;i++) { if (!newRows[i].className || (newRows[i].className && (newRows[i].className.indexOf('sortbottom') == -1))) table.tBodies[0].appendChild(newRows[i]);}
    // do sortbottom rows only
    for (i=0;i<newRows.length;i++) { if (newRows[i].className && (newRows[i].className.indexOf('sortbottom') != -1)) table.tBodies[0].appendChild(newRows[i]);}
    
    // Delete any other arrows there may be showing
    var allspans = document.getElementsByTagName("span");
    for (var ci=0;ci<allspans.length;ci++) {
        if (allspans[ci].className == 'sortarrow') {
            if (getParent(allspans[ci],"table") == getParent(lnk,"table")) { // in the same table as us?
                allspans[ci].innerHTML = '';
            }
        }
    }
        
    span.innerHTML = ARROW;
	zebra_table();
}

function getParent(el, pTagName) {
	if (el == null) return null;
	else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())	// Gecko bug, supposed to be uppercase
		return el;
	else
		return getParent(el.parentNode, pTagName);
}

function returnDate(s)
{
	var date_time = new Array(4);

	var ss = s.toLowerCase();

	// Does it have the time too?
	var just_month = (ss.indexOf(" ") == -1) ? true : false;

	// Which is is "/" or "-" as the delimeter
	var del = /^\d{1,2}[/]/;	
	del = (del.test(s)) ? "/" : "-";

	// Month
	date_time[0] = ss.substring(0,ss.indexOf(del));
	if(date_time[0].length < 2) date_time[0] = "0" + date_time[0];
	ss = ss.substring(ss.indexOf(del)+1,ss.length);

	// Date
	date_time[1] = ss.substring(0,ss.indexOf(del));
	if(date_time[1].length < 2) date_time[1] = "0" + date_time[1];
	ss = ss.substring(ss.indexOf(del)+1,ss.length);

	// Year
	date_time[2] = (just_month) ? ss.substring(0,ss.length) : ss.substring(0,ss.indexOf(" "));

	if(date_time[2].length < 3)
	{
		if(parseInt(date_time[2]) < 50) date_time[2] = "20" + date_time[2];
		else if(parseInt(date_time[2]) >= 50) date_time[2] = "19" + date_time[2];
	}

	if(!just_month)
	{
		ss = ss.substring(ss.indexOf(" "),ss.length);

		var meridian = false;

		if(ss.indexOf("pm") > -1)
		{
			ss = ss.replace("pm","");
			meridian = "PM";
		}
		if(ss.indexOf("am") > -1)
		{
			ss = ss.replace("am","");
			meridian = "AM";
		}

		ss = ss.replace(/^\s+|\s+$/g,"");

		var time  = ss.split(":");

		if(time[0] < 12 && meridian == "PM") time[0] = parseInt(time[0]) + 12;

		var the_time = (time[0] * 60) + parseInt(time[1]);

		var number_of_digits = 4
		var digits = new Array("0000","000","00","0","");

		date_time[3] =digits[the_time.toString().length].toString() + the_time.toString();
	}
	else
	{
		date_time[3] = "";
	}

	// It needs to be YEAR + MONTH + DAY

	var date_string = date_time[2] + date_time[0] + date_time[1] + date_time[3]

	return date_string;
}

function ts_sort_date(a,b)
{
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);

	dt1 = returnDate(aa);
	dt2 = returnDate(bb);

    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
}

function ts_sort_currency(a,b) { 
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    return parseFloat(aa) - parseFloat(bb);
}

function ts_sort_numeric(a,b) { 
    aa = parseFloat(ts_getInnerText(a.cells[SORT_COLUMN_INDEX]));
    if (isNaN(aa)) aa = 0;
    bb = parseFloat(ts_getInnerText(b.cells[SORT_COLUMN_INDEX])); 
    if (isNaN(bb)) bb = 0;
    return aa-bb;
}

function ts_sort_caseinsensitive(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
}

function ts_sort_default(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
}

set_onload("sortables_init");

///// Page Tools

function print_page()
{
	if(window.print)
	{
		window.print();
		return;
	}
}

function email_link()
{
	var page_url = window.location.href;
	var page_title = document.getElementsByTagName("h1");
	var site = "Northampton Township";

	if(page_title[0].innerText)
	{
		page_name = page_title[0].innerText;
	}
	else
	{
		page_name = page_title[0].textContent;
	}

	var email_subject = "A Link To The " + site + " Website";
	var email_body = "A link to the '" + escape(page_name) + "' page at the " + site + " website has been sent to you. %0D%0DYou can visit this page at: " + page_url + "%0D%0DThank you.%0D%0D------------------------%0DThis email was auto generated from the " + site + " website.";
	window.open("mailto:?subject=" + email_subject + "&body=" + email_body);
	return;
}

function set_patch()
{
	if(window.XMLHttpRequest) // IE 7, mozilla, safari, opera 9
	{
		var path = window.location.pathname.split("/")[2];
		var is_police = (path == "police") ? true : false;
		var is_fire = (path == "fire-marshal") ? true : false;
		
		if(is_police)
		{
			var police_patch = document.getElementById("f-patch-police");
			police_patch.style.display = "block";
		}
		
		if(is_fire)
		{
			var fire_patch = document.getElementById("f-patch-fire");
			fire_patch.style.display = "block";
		}
	}
}

/* Documents */

function toggle_document_listing()
{
	var ul = document.getElementsByTagName("ul");

	var doc_list = new Array();
	var cat_list = new Array();

	for(var i=0; i<ul.length; i++)
	{
		if(ul[i].className == "document-listing")
		{
			doc_list[doc_list.length] = ul[i];
		}
		
		if(ul[i].className  == "d-l-documents")
		{
			cat_list[cat_list.length] = ul[i];
		}
	}

	for(var i=0; i<cat_list.length; i++)
	{
		var cat_parent = parent_object(cat_list[i]);

		var strong = first_child(cat_parent);

		var a  = document.createElement("a");
		a.appendChild(document.createTextNode(strong.innerHTML));
		a.setAttribute("href","javascript:void(0)");

		var div = document.createElement("div");
		div.className = "list-toggle";
		div.appendChild(a);

		cat_parent.insertBefore(div,strong);
		cat_parent.removeChild(strong);
		cat_parent.className = "li-collapse";

		a.onclick = function(){
			var li_parent = parent_object(parent_object(this))
			var list = li_parent.getElementsByTagName("ul")[0];
			list.style.display = (list.style.display == "block") ? "none" : "block";
			li_parent.className = (list.style.display == "block") ? "li-expand" : "li-collapse";			
			};

		cat_list[i].style.display = "none";
	}
}

function next_object(el)
{
	var o = el;
	do o = o.nextSibling;
	while (o && o.nodeType != 1);
	return o;
}

function previous_object(el)
{
	var o = el;
	do o = o.previousSibling;
	while (o && o.nodeType != 1);
	return o;
}

function parent_object(el)
{
	var o = el;
	do o = o.parentNode;
	while (o && o.nodeType != 1);
	return o;
}

function first_child(el)
{
	var o = el;
	o = o.firstChild;
	while (o.nodeType != 1)
	{
		o = o.nextSibling;
	}
	return o;
}
