

// Check for IE6-ness.
function isIE6()
{
	if (document.all
			&& navigator.appVersion.indexOf("MSIE 6.") != -1)
	{
		return true;
	}
	return false;
}

// Check for IE7-ness
function isIE7()
{
	if (document.all
			&& navigator.appVersion.indexOf("MSIE 7.") !=-1)
	{
		return true;
	}
	return false;
}


// Why can't javascript to xpath queries on HTML DOMs by default?
function findChildren(topnode, tagname, classname)
{
	var results = new Object();

	if (topnode) {
		var elems = topnode.getElementsByTagName(tagname);
		var i = 0;
		var j = 0;
		while (i < elems.length) {
			if (elems[i].className == classname) {
				results[j] = elems[i];
				++j;
			}
			++i;
		}
	}

	return results;
}


// From http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
function windowWidth(doc)
{
	if (doc.defaultView) {
		return doc.defaultView.innerWidth;
	}
	if (doc.documentElement.clientWidth) {
		return doc.documentElement.clientWidth;
	}
	return 0;
}


function windowHeight(doc)
{
	if (doc.defaultView) {
		return doc.defaultView.innerHeight;
	}
	if (doc.documentElement.clientHeight) {
		return doc.documentElement.clientHeight;
	}
	return 0;
}


function bodyWidth(doc) {
	elem = doc.getElementsByTagName('body');
	if (!elem || !elem[0]) {
		alert('foo!');
	}
	return elem[0].clientWidth;
}


function bodyHeight(doc) {
	elem = doc.getElementsByTagName('body');
	if (!elem || !elem[0]) {
		alert('foo!');
	}
	return elem[0].clientHeight;
}


function elemPos(elem)
{
	if (!elem) {
		return null;
	}

	var pos = new Object();
	pos.outerTop = elem.offsetTop;
	pos.outerLeft = elem.offsetLeft;

	var p = elem.offsetParent;
	while (p) {
		pos.outerTop += p.offsetTop;
		pos.outerLeft += p.offsetLeft;
		p = p.offsetParent;
	}

	pos.outerWidth = elem.offsetWidth;
	pos.outerHeight = elem.offsetHeight;
	pos.outerRight = pos.outerLeft + pos.outerWidth;
	pos.outerBottom = pos.outerTop + pos.outerHeight;

	return pos;
}


function elemWidth(doc, id)
{
	var elem = doc.getElementById(id);
	if (!elem || !elem.offsetWidth) {
		return 0;
	}
	return elem.offsetWidth;
}


function elemHeight(doc, id)
{
	var elem = doc.getElementById(id);
	if (!elem || !elem.offsetHeight) {
		return 0;
	}
	return elem.offsetHeight;
}


function bordertable_start(id_table, id_centercell)
{
	var result = "";

	result += "<table class='border'";
	if (id_table) {
		result += " id='" + id_table + "'";
	}
	result += ">\n";
	result += "<tr>";
	result += "<td class='topleft'></td>";
	result += "<td class='topcenter'></td>";
	result += "<td class='topright'></td>";
	result += "</tr>\n";
	result += "<tr>";
	result += "<td class='middleleft'></td>";
	result += "<td class='middlecenter'";
	if (id_centercell) {
		result += " id='" + id_centercell + "'";
	}
	result += ">";

	return result;
}


function bordertable_end()
{
	var result = "";

	result += "</td>";
	result += "<td class='middleright'></td>";
	result += "</tr>\n";
	result += "<tr>";
	result += "<td class='bottomleft'></td>";
	result += "<td class='bottomcenter'></td>";
	result += "<td class='bottomright'></td>";
	result += "</tr>\n";
	result += "</table>\n";

	return result;
}


function bordertable_bordersize(bordertable)
{
	var size = new Object();
	size.width = 0;
	size.height = 0;

	var elemsTop = findChildren(bordertable, "td", "topcenter");
	var elemsLeft = findChildren(bordertable, "td", "middleleft");
	var elemsBottom = findChildren(bordertable, "td", "bottomcenter");
	var elemsRight = findChildren(bordertable, "td", "middleright");

	if (!elemsTop || !elemsTop[0]
			|| !elemsLeft || !elemsLeft[0]
			|| !elemsBottom || !elemsBottom[0]
			|| !elemsRight || !elemsRight[0])
	{
		alert('missing');
		return size;
	}

	size.width = elemsLeft[0].offsetWidth + elemsRight[0].offsetWidth;
	size.height = elemsTop[0].offsetHeight + elemsBottom[0].offsetHeight;

	return size;
}


function imgswap(src, name)
{
	if (document.images) {
		document.images[name].src = src;
	}
}


/** Vertically align an element in the middle of its parent element.
 */
function
vertical_align_middle(elem)
{
	if (!elem || !elem.style) {
		return;
	}
	var topmargin = (elem.parentNode.clientHeight - elem.offsetHeight) / 2;
	//elem.style["margin-top"] = topmargin + "px";
	elem.style["marginTop"] = topmargin + "px";
}


function
horizontal_align_right(elem)
{
	if (!elem || !elem.style) {
		return;
	}
	var margin = (elem.parentNode.clientWidth - elem.offsetWidth) - 5;
	elem.style["marginLeft"] = margin + "px";
}


function
vertical_equalise_heights()
{
	var max = 0;
	for (var i = 0; i < arguments.length; ++i) {
		var val = parseInt(arguments[i].offsetHeight);
		if (val > max) {
			max = val;
		}
	}
	for (var i = 0; i < arguments.length; ++i) {
		arguments[i].style.height = max + "px";
	}
}


function
horizontal_equalise_widths()
{
	var max = 0;
	for (var i = 0; i < arguments.length; ++i) {
		var val = parseInt(arguments[i].offsetWidth);
		if (val > max) {
			max = val;
		}
	}
	for (var i = 0; i < arguments.length; ++i) {
		arguments[i].style.width = max + "px";
	}
}


/** Functions for dealing with labels. */
var Labels = {
	/** Private cache of previously downloaded labels */
	_cache: {},

	/** Download labels named in parameters
	 *
	 * Useful for downloading a bunch of labels you know you're going to need
	 * all at once, saving multiple round-trips to the server.
	 */
	download: function() {
		var url = urlbase_ajax + 'labels.xml';
		for (var i = 0, j = 0; i < arguments.length; ++i) {
			if (Labels._cache[arguments[i]]) {
				continue;
			}
			url += (j == 0 ? '?' : '&') + 'name=' + arguments[i];
			++j;
		}
		if (j == 0) {
			return;
		}
		var response = octalXmlHttpSync(url);
		if (!response
				|| !response.responseXML)
		{
			return;
		}
		var labels = response.responseXML.getElementsByTagName('label');
		for (var i = 0; i < labels.length; ++i) {
			var label = labels.item(i);
			Labels._cache[label.getAttribute('name')] = octalDomText(label);
		}
	},

	/** Get the value of a named label */
	get: function(name) {
		Labels.download(name);
		return Labels._cache[name];
	}
}


/** Turn the main menu into a hover menu */
function hoverMenuCreate(topmenu, menuurl, options)
{
	var menutree = octalXmlHttpSync(menuurl);
	for (var i = 0;
			menutree
			&& menutree.responseXML
			&& topmenu
			&& topmenu.childNodes
			&& topmenu.childNodes.length
			&& i < topmenu.childNodes.length;
			++i)
	{
		var topmenuitem = topmenu.childNodes.item(i);
		if (!topmenuitem.tagName
				|| topmenuitem.tagName.toLowerCase() != 'div'
				|| !(octalClass_inlist(topmenuitem, 'menu_d')
					|| octalClass_inlist(topmenuitem, 'menu_a')))
		{
			continue;
		}

		var menutreesubitems = octalHovermenuSubitems(
				octalHovermenuFind(menutree.responseXML.documentElement,
					octalDomText(topmenuitem)));
		if (!menutreesubitems
				|| !menutreesubitems.length
				|| menutreesubitems.length == 1)
		{
			continue;
		}

		octalHovermenuAdd(topmenuitem,
				octalHovermenuFromMenuitems(
					topmenuitem.ownerDocument,
					menutreesubitems),
				options);
		octalClass_add(topmenuitem, 'hasflyout');
	}
}


var basket = {
	items: function() {
		if (basket._items) {
			return basket._items;
		}
		return basket._parse(octalXmlHttpSync(
					urlbase_ajax + 'basket.xml'));
	},

	add: function(id) {
		return basket._parse(octalXmlHttpSync(
					urlbase_ajax + 'basket.xml?add=' + id));
	},

	del: function(id) {
		return basket._parse(octalXmlHttpSync(
					urlbase_ajax + 'basket.xml?del=' + id));
	},

        set: function(id, val) {
                 if (val) {
                     return basket.add(id);
                 }
                 else {
                     return basket.del(id);
                 }
         },

	contains: function(id) {
		var all = basket.items();
		for (var i = 0; i < all.length; ++i) {
			if (all[i] == id) {
				return true;
			}
		}
		return false;
	},

	_items: null,

	_parse: function(response) {
		basket._items = [];
		if (!response
				|| !response.responseXML)
		{
			return basket._items;
		}
		var ids = response.responseXML.getElementsByTagName('id');
		for (var i = 0; i < ids.length; ++i) {
			basket._items.push(parseInt(octalDomText(ids.item(i))));
		}
		return basket._items;
	}
};

/*
 * IE7 doesn't use it's proprietary "filter:alpha" support unless the
 * element on which it is defined has a "height" or "width" set.
 * Unforunately, the menu elements need to be auto-widthified, but if
 * you set their height to a fixed value then their width screws up
 * something silly. So, when trying to fix the opacity-not-working bug,
 * you introduce another bug which is worse.
 * This fixes the width of the menu items to the width of the widest
 * item if the items are not already all the same width.
 * If they are already the same width, it seems to get extra pixels from
 * somewhere and keeps making the menu wider, which is bad.
 */
function hoverMenuEqualWidth(source, menu) {
	if (!octalIE
			|| !source
			|| !menu
			|| !menu.childNodes
			|| !menu.childNodes.length)
	{
		return;
	}
	if (!source.x_octal) {
		source.x_octal = {};
	}
	if (source.x_octal.hovermenuequalwidth) {
		return;
	}

	var max = 0;
	for (var i = 0; i < menu.childNodes.length; ++i) {
		var submenu = menu.childNodes.item(i);
		var val = parseInt(submenu.offsetWidth);
		if (val > max) {
			max = val;
		}
	}
	for (var i = 0; i < menu.childNodes.length; ++i) {
		var submenu = menu.childNodes.item(i);
		submenu.style.width = max + 'px';
	}
	source.x_octal.hovermenuequalwidth = 1;
}


/** Function to ajaxify forms with "nation", "region", "city" and "suburb" selectors.
 *
 * We put an event handler on the selectors so that when it changes,
 * the "smaller" selectors update to only contain relevant items.
 */
octalAddEventListener(window, 'load', function() {
		for (var i = 0; i < document.forms.length; ++i) {
			location_dropdown_dynamicise(document.forms[i],
				urlbase_ajax + 'locations.xml?nation={0}&region={1}&city={2}&suburb={3}',
				Labels.get('list_opt_any'));
		}
	});
