// 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) // IE
		{
			// Firefox wants "padding-top", and IE wants "paddingTop"
			// So we'll pass "padding-top" and convert it for IE
			var ix  = el_css.indexOf("-");

			if(ix > -1)
			{
				var new_css = el_css.split("-");
				for(var i=0; i<new_css.length; i++)
				{
					if(i>0)
					{
						new_css[i] = new_css[i].substring(0,1).toUpperCase() + new_css[i].substring(1,new_css[i].length);
					}
				}

				el_css = new_css.join("");
			}

			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;
}

// Trim

function trim(s)
{
	return s.replace(/^\s+|\s+$/g, '');
}

String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.ltrim = function()
{
	return this.replace(/^\s+/g,"");
}

String.prototype.rtrim = function()
{
	return this.replace(/\s+$/g,"");
}

// Form Functions

function valid_email(ea)
{
	var email_reg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
	var regex = new RegExp(email_reg);
	return regex.test(ea);
 }

function valid_zip(zip)
{
	var zip_reg = "^([0-9]{5})$";
	var regex = new RegExp(zip_reg);
	return regex.test(zip);
}

function validate(f,el)
{
	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;
		}
	}
}

// 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: Print Page

function print_page()
{
	if(window.print)
	{
		window.print();
		return;
	}
}

// Page Tools: Email Link

function email_link()
{
	var page_url = window.location.href;
	var page_title = document.getElementsByTagName("h1");
	var site = "Hughes Relocation Services";

	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;
}

// Window Dimensions

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;
}

// Various Content Height Checks
// Some content is absolutely positioned and can "overlap" other elements on the page.
// We can script some checks to ensure the page flows appropriately.

function content_height()
{
	// Photographs and Mini Quote

	var p_featured = document.getElementById("p-featured");

	if(!p_featured) return;

	var p_featured_height = p_featured.offsetHeight;

	// Mini Quote
	var mini_quote = document.getElementById("p-mini-quote");
	var mini_quote_padding = parseInt(get_style(mini_quote,"padding-top").replace("px","")) + parseInt(get_style(mini_quote,"padding-bottom").replace("px",""));
	var mini_quote_height = mini_quote.offsetHeight;
	//alert(mini_quote_padding);

	if(mini_quote_height > p_featured_height)
	{
		p_featured.style.height = mini_quote_height + "px";
	}
	else
	{
		mini_quote.style.minHeight = (p_featured_height - mini_quote_padding) + "px";
	}

	// Left Navigation and Article

	var c_menu = document.getElementById("c-menu");

	if(!c_menu) return;

	var c_menu_height = c_menu.offsetHeight;

	var c_article = document.getElementById("c-article");
	var c_article_height = c_article.offsetHeight;
	var c_article_padding = parseInt(get_style(c_article,"padding-top").replace("px","")) + parseInt(get_style(c_article,"padding-bottom").replace("px",""));

	if(c_article_height < c_menu_height)
	{
		c_article.style.height = (c_menu_height - c_article_padding) + "px";
	}
}

set_onload("content_height");

// User Adjusted Text Size

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";
}

// Cursor Position

function getPosition(e)
{
    e = e || window.event;

    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + 
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + 
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }
    return cursor;
}

// Mini Quote

function set_contact()
{
	var s_box = document.getElementById("ContactMeVia");

	s_box.onchange = get_contact;

	get_contact();
	
}

function get_contact()
{
	var s_box = document.getElementById("ContactMeVia");
	var s_box_selected = s_box.options[s_box.selectedIndex].value;
	var td = document.getElementById("contact-value");

	var c_values = td.getElementsByTagName("input");

	for(var i=0; i<c_values.length; i++)
	{
		if(c_values[i].id.indexOf(s_box_selected) > -1)
		{
			c_values[i].style.display = "block";
		}
		else
		{
			c_values[i].style.display = "none";
		}
	}

}

/* Quote Validation */

function validate_quote()
{

	var validate = 1;

	var req = get_req();

	for(var i=0; i<req.length; i++)
	{
		// All fields are text input fields (so far), so this should be pretty simple
		if((req[i].nodeName.toLowerCase() == "input" && req[i].type == "text") || (req[i].nodeName.toLowerCase() == "textarea"))
		{
			var f_value = trim(req[i].value); // trim() is located in scripts.js

			// If the value is blank, we need to alert the user
			if(f_value == "")
			{
				req[i].className = "req-alert";

				validate = validate - 1; // Update the main validation check (whether or not to let the user proceed);
			}
			else
			{
				req[i].className = ""; // Clear out any previously set CSS class
			}
		}
	}

	if(validate < 1)
	{
		alert("Please complete the estimate by entering all required fields");
		return false;
	}
	else
	{
		return;
	}
}

///// Cookies

function set_cookie(n,v,d) // Name, Value, Days
{
	if(d)
	{
		var date = new Date();
		date.setTime(date.getTime()+(d*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else
	{
		expires = "";
	}
	document.cookie = n + "=" + v + expires + "; path=/";
}

function get_cookie(n)
{
	var name = n + "=";
	var ca = document.cookie.split(';');

	for(var i=0; i<ca.length; i++)
	{
		var c = ca[i].ltrim();
		//var c = ca[i];
		if(c.indexOf(name) == 0)
		{
			return c.substring(name.length,c.length);
		}
	}
}

function set_referrer()
{
	var is_referred = (document.referrer && (document.referrer.indexOf("hughesrelo") < 0)) ? true : false;

	if(is_referred)
	{
		var referred_from = document.referrer;
		// Set a cookie with a name pair for "referred_from" so we can determine what site linked to us
		set_cookie("referred_from",referred_from);
	}

	write_referrer("SiteReferrer");
}

function write_referrer(o) // object
{
	var site = get_cookie("referred_from");
	if(!site) site = "None";

	var hidden = document.getElementById(o);

	if(hidden) 	hidden.value = site;
}

// Toggle Panel
// Show/Hide objects
function toggle_panel(id,value)
{
	var panel = document.getElementById(id);

	if(!value || value=="")
	{
		value = (panel.style.display == "block") ? "none" : "block";
	}
	else
	{
		value = value;
	}

	panel.style.display = value;
}
