//// 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;

//// Return an Elements Position;

function find_pos(obj)
{
	var cur_left = cur_top = 0;

	if(obj.offsetParent)
	{
		cur_left = obj.offsetLeft;
		cur_top = obj.offsetTop;

		while (obj = obj.offsetParent)
		{
			cur_left += obj.offsetLeft;
			cur_top += obj.offsetTop;
		}
	}
	return [cur_left,cur_top];
}

//// Get A CSS Value

function get_style(el,el_css)
{
	var css_value = el.style[el_css];

	if(!css_value) // If it's not an inline style
	{
		if(el.currentStyle)
		{
			css_value = el.currentStyle[el_css];
		}
		else if(window.getComputedStyle)
		{
			css_value = document.defaultView.getComputedStyle(el,null).getPropertyValue(el_css);
		}
		else
		{
			css_value = null;
		}
	}

	return css_value;
}

//// Menu Pop-Ups

var pu_current = false;
var pu_focus = false;
var pu_all = new Array();
var pu_timer = false;

function set_top_pu()
{
	var page = document.getElementById("page");
	var menu = document.getElementById("t-menu");
	var menu_a  = menu.getElementsByTagName("a");

	for(var i=0; i<menu_a.length; i++)
	{
		if(menu_a[i].id && (menu_a[i].id.indexOf("tab-") == 0))
		{
			var popup_id = menu_a[i].id.replace("tab-","pu-");
			var popup = document.getElementById(popup_id);
			pu_all[pu_all.length] = popup;

			// Find the text left pos in the tab
			var pos = find_pos(menu_a[i]);
			var new_left = (pos[0] - page.offsetLeft) - 20; // The "20" is just for style

			// If the menu overlaps the page (hangs to the right), we need to move it "inside" the page, and align the right sides
			// 1. Find the right of both the page and the proposed pu menu
			var page_right = page.offsetLeft + page.offsetWidth;
			var pu_right = pos[0] + parseInt(get_style(popup,"width"));
			if(pu_right > page_right) new_left = (pos[0] - page.offsetLeft) - (pu_right - page_right);

			popup.style.left = new_left + "px"; // TO DO: We don't want a menu that extends past the page (that may cause scrollbars)

			menu_a[i].onmouseover = function()
			{
				pu_all_off();
				clearTimeout(pu_timer);
				var menu_popup = document.getElementById(this.id.replace("tab-","pu-"));
				menu_popup.style.display = "block";
				pu_focus = true;
			}
			menu_a[i].onmouseout = function()
			{
				pu_current = this.id.replace("tab-","pu-");
				pu_focus = false;
				pu_timer = setTimeout("pu_off()",500); // HACK
			}
			popup.onmouseover = function()
			{
				this.style.display = "block";
				pu_focus = true;
			}
			popup.onmouseout = function()
			{
				//this.style.display = "none";
				pu_focus = false;
				pu_current = this.id.replace("tab-","pu-");
				pu_timer = setTimeout("pu_off()",500); // HACK
			}
		}
	}
}

set_onload("set_top_pu");

function pu_all_off()
{
	if(pu_all.length > 0)
	{
		for(var i=0; i<pu_all.length; i++)
		{
			pu_all[i].style.display = "none";
		}
	}
}

function pu_off()
{
	if(!pu_focus)
	{
		var pu = document.getElementById(pu_current);
		pu.style.display = "none";
	}
}

///// 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,captcha)
{
	var address = trim(document.getElementById(el).value);
	var valid = (valid_email(address)) ? 1 : 0;

	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";
		}
	}
}

///// 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 || t[i].className && t[i].className.indexOf("border-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 = "Circles of Air, Circles of Stone";

	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 get_window()
{
	// Window inner dimensions
	var window_x, window_y;

	if(self.innerHeight) // all except Explorer
	{
		//window_x = self.innerWidth;
		window_x = document.body.offsetWidth;
		window_y = self.innerHeight;
	}
	else if(document.documentElement && document.documentElement.clientHeight) // Explorer 6 Strict Mode
	{
		window_x = document.documentElement.clientWidth;
		window_y = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
		window_x = document.body.clientWidth;
		window_y = document.body.clientHeight;
	}

	var window_dim = new Array(window_x, window_y);
	return window_dim;
}

// Used to add the gradient on the bottom of each page.
function set_container()
{
	var window_dim = get_window();
	var container = document.getElementById("container");

	if(container.offsetHeight < window_dim[1])
	{
		container.style.height = window_dim[1] + "px";
	}
}

//set_onload("set_container");

// ARTICLE HEIGHT CHECK
// It's possible that the right menu height to be larger than the content
// The problem is that the right menu is positioned absolutely and doen't "push" the bottom area underneath
// So the right menu "overhangs" the white background
// We need to make the content height at least as large as the right menu height (actually more, some padding would look good)
function article_height()
{
	var right = document.getElementById("c-right").offsetHeight;
	var article = document.getElementById("c-article");
	var left = document.getElementById("c-left");

	if(left)
	{
		left = left.offsetHeight;
		if(left > right) right = left;
	}

	if(article.offsetHeight < right)
	{
		article.style.height = right + "px";
	}

	set_container();
}

set_onload("article_height");

function text_size(el,ix)
{
	var sizes = new Array(".85em","1em","1.15em");
	var article = document.getElementById("c-article");
	article.style.fontSize = sizes[ix];

	var div = document.getElementById("text-size");
	var a = div.getElementsByTagName("a");

	for(var i=0; i<a.length; i++)
	{
		a[i].className = "";
	}

	el.className = "on";
}

function set_photograph()
{
	var container = document.getElementById("t-photo");
	var photo = document.getElementById("p-photo");
	var photos = get_photographs();
	var path = "/images/top-photos/";

	// Set the photograph
	var r_number = Math.floor(Math.random() * photos.length);
	photo.style.backgroundImage = "url(" + path + photos[r_number] + ")";

/*
	// Create the caption
	var caption = document.createElement("div");
	caption.id = "p-caption";

	var caption_text = document.createTextNode(photos[r_number].replace(/-/g," ").split(".")[0]);
	caption.appendChild(caption_text);
	container.appendChild(caption);
*/
}

function set_tabs()
{
	var tabs = document.getElementById("tabs-menu");
	var a = tabs.getElementsByTagName("a");
	var blocks = document.getElementById("tabs-content").childNodes;

	for(var i=0; i<a.length; i++)
	{
		a[i].onmouseover = function()
		{
			// Clear out everything
			for(var j=0; j<blocks.length; j++)
			{
				if(blocks[j].nodeType == 1)
				{
					blocks[j].style.display = "none";
				}
			}

			for(var j=0; j<a.length; j++)
			{
				a[j].parentNode.className = "";
			}

			this.parentNode.className = "on";

			var block = document.getElementById(this.id.toString().replace("tab-","tc-"));
			block.style.display = "block";

			article_height();
		}

		for(var j=0; j<blocks.length; j++)
		{
			if(blocks[j].nodeType == 1)
			{
				blocks[j].style.display = "none";
			}
		}		
	}

	for(var i=0; i<a.length; i++)
	{
		if(a[i].parentNode.className && a[i].parentNode.className == "on")
		{
			//alert(a[i].id.toString().replace("tab-","wn-"));
			document.getElementById(a[i].id.toString().replace("tab-","tc-")).style.display = "block";
		}
	}

	article_height();
}
