//
//	form handlers

function genericFormSubmitDisableForm (form)
{
	var e;
	for (var i = form.elements.length; i--;)
	{
		e = form.elements[i];
		
		switch (e.type)
		{
			case "hidden":
				break;
			
			default:
				if (!e.disabled)
				{
					e._genericFormSubmit_enableMe = true;
					e.disabled = true;
				}
				break;
		}
	}
}

function genericFormSubmitHandler (form)
{
	window.setTimeout((function () { genericFormSubmitDisableForm(form); }), 1);
	return true;
}

function genericFormResponseEnableForm (form)
{
	var e;
	for (var i = form.elements.length; i--;)
	{
		e = form.elements[i];
		
		switch (e.type)
		{
			case "hidden":
				break;
			
			default:
				if (e.disabled && e._genericFormSubmit_enableMe) 
				{
					e._genericFormSubmit_enableMe = false;
					e.disabled = false;
				}
				break;
		}
	}
}

function genericFormResponseHandler (type, result, evt, request)
{
	switch (type)
	{
		case "load":

			if (result.urchin)
				urchinTracker(result.urchin);

			if (result.message)
				alert(result.message);

			if (request.formNode)
				genericFormResponseEnableForm(request.formNode);

			if (result.reset)
				request.formNode.reset();

			if (result.windowOpen)
			{
				switch (typeof result.windowOpen)
				{
					case "array":
						var w = window.open(result.windowOpen[0], result.windowOpen[1], result.windowOpen[2], result.windowOpen[3]);
						break;
					
					default:
						var w = window.open(result.windowOpen)
						break;
				}
			}

			if (result.eval)
				eval(result.eval);

			if (result.redirect)
			{
				window.location.href = result.redirect;
				break;
			}

			if (result.reload)
			{
				window.location.reload();
				break;
			}

			break;

		case "error":
			alert("An error occurred when attempting to perform this action. Please try again later.");
			genericFormResponseEnableForm(request.formNode);
			break;
			
		default:
			alert("Unhandled form result type: "+ type);
			genericFormResponseEnableForm(request.formNode);
			break;
	}
}

//
//	other stuff

standardFadeDuration = 200;

function numberToCurrency (n)
{
	//
	//	very basic number-to-currency function, only works for this format: -$...,000,000.00
	
	if (isNaN(n))
		return "";
	
	var sign = (n < 0 ? "-" : "") +"$";
	
	var dollars = Math.floor(Math.abs(n)).toString();
	var cents = Math.round((n * 100) % 100);
	
	if (cents < 10)
		cents = "0"+ cents;
	else
		cents = cents.toString();
	
	var rxp = /(\d+)(\d{3})/;
	while (rxp.test(dollars))
		dollars = dollars.replace(rxp, "$1,$2");
	
	return sign + dollars +"."+ cents;
}

function clearMe (inp, val)
{
	//
	//	clears the value of given input node (inp) if the current value is equal to (val)

	if (inp.value == val)
		inp.value = "";
}

function toggleDivFade (id)
{
	//
	//	looks for a node with the supplied id and toggles it hidden/visible with fading

	var e = dojo.byId(id);
	if (!e)
		return;

	if (e.style.display != "block")
		dojo.fx.html.fadeShow(e, standardFadeDuration);
	else
		dojo.fx.html.fadeHide(e, standardFadeDuration);
}

function currentNav (id)
{
	//
	//	marks the nav node with the supplied id as current by setting the css class

	var e = dojo.byId(id);
	if (!e)
		return;

	e.className = "current";
}

function shopClick ()
{
	if (sessionCart.items.length)
		window.location.href = "default.asp?mod=cart";
	else
		window.location.href = "default.asp?mod=products";
}

function renderSessionCart ()
{
	//
	//	renders the innerHTML content of the cart box

	if (typeof sessionCart == "undefined" || !sessionCart)
		return;

	var node = dojo.byId("cartBox");
	if (!node)
		return;

	if (sessionCart.items.length)
		node.innerHTML = 'Your cart contains '+ sessionCart.qty +' item/s<br /><br />';
	else
		node.innerHTML = "Your cart is empty";

	var node = dojo.byId("cartBoxContainer");
	if (!node)
		return;
	dojo.fx.html.fadeShow(node, standardFadeDuration);

	var node = dojo.byId("cartBoxBg");
	node.src = "images/cart_"+ (sessionCart.qty ? "full" : "empty") +".png";
	//node.style.backgroundImage = "url(images/cart_"+ (sessionCart.qty ? "full" : "empty") +".png)";
}

function positionSessionCart ()
{
	//
	//	positions the cartbox on the screen relative to scrolling (*sigh* @ ie6)

	if (typeof sessionCart == "undefined" || !sessionCart)
		return;

	var cartbox = dojo.byId("cartBoxContainer");
	if (!cartbox)
		return;

	var curright = dojo.style.getUnitValue(cartbox, "right").value;
	var curtop = dojo.style.getUnitValue(cartbox, "top").value;

	var fixedheightoffset = -10;
	var pageheight = dojo.style.getContentHeight(dojo.byId("pagediv"));
	var pagewidth = dojo.style.getBorderBoxWidth(dojo.byId("pagediv"));
	var cartboxheight = cartbox.offsetHeight;
	var viewportheight = dojo.html.getViewportHeight();
	var viewportwidth = dojo.html.getViewportWidth();
	var viewportscroll = dojo.html.getScrollTop();
	var top = fixedheightoffset + viewportheight - cartboxheight + viewportscroll;
	if (top > pageheight - cartboxheight)
		top = pageheight - cartboxheight;
	if (top < 460)
		top = 460;
	var right = -10+(viewportwidth-pagewidth)/2;
	if (isNaN(curtop))
		curtop = top;
	dojo.style.setPositivePixelValue(cartbox, "top", top - (top-curtop)*0.7);
	dojo.style.setPositivePixelValue(cartbox, "right", right);
}

function cartAdd (id)
{
	//
	//	invoke the cart-add handler directly

	var content = {
		"dojo.submit.action": "cart-add",
		"product": id
	};
	var qtyField = "qty-"+ id;
	content[qtyField] = 1;
	
	var x = dojo.io.bind({
		url: "handler.asp",
		method: "POST",
		content: content,
		handle: cartAddFormResponseHandler,
		mimetype: "text/json",
		sendTransport: true
	});
}

function goCart ()
{
	window.location.href = "default.asp?mod=cart";
}

function renderCartTable ()
{
	//
	//	renders the contents of the cart table

	if (typeof sessionCart == "undefined" || !sessionCart)
		return;

	var cartTable = dojo.byId("cartTable");
	if (!cartTable)
		return;
}

memberFormToggleStack = 0;
function decreaseMemberFormToggleStack () { memberFormToggleStack--; }

function myAppendCell (row, text, className)
{
	var cell = row.insertCell(row.cells.length);
	cell.innerHTML = text;
	if (className)
		cell.className = className;
	return cell;
}

function receiveMyDownloads (type, result, evt, request)
{
	switch (type)
	{
		case "load":
			var table = dojo.byId("myDownloadsTable");
			var tbody = table.getElementsByTagName("tbody")[0];

			dojo.style.hide(table);

			for (var i = tbody.rows.length; i--;)
				tbody.deleteRow(i);

			var item, row, cell, previousProduct, downloadURL;
			for (var i = 0; i < result.items.length; i++)
			{
				item = result.items[i];
			
				if (previousProduct != item.ContentfileContent)
				{
					row = tbody.insertRow(tbody.rows.length);
					row.className = "header";
					cell = myAppendCell(row, item.ContentHeader, "header");
					cell.colSpan = 2;
					previousProduct = item.ContentfileContent;
				}

				var downloadURL = "order-download.asp?id="+ item.ContentfileID;

				row = tbody.insertRow(tbody.rows.length);
				row.className = "data row-mod2-"+ (i%2);
				myAppendCell(row, '<a href="'+ downloadURL +'">'+ item.ContentfileFilename +'</a>', "data data-filename");
				myAppendCell(row, '<a href="'+ downloadURL +'">'+ ((item.ContentfileFilesize)/1024000).toFixed(1) +' mb</a>', "data data-size");
			}

			dojo.fx.html.fadeShow(table, standardFadeDuration);
			break;
	}
}

function orderClick (evt)
{
	var row = evt.currentTarget;
	if (!/^orderrow\-(\d+)$/.test(row.id))
		return;
	var id = parseInt(RegExp.$1);
	var orderURL = "default.asp?mod=order&order="+ id;
	window.location.href= orderURL;
}

function receiveMyOrders (type, result, evt, request)
{
	switch (type)
	{
		case "load":
			var table = dojo.byId("myOrdersTable");
			var tbody = table.getElementsByTagName("tbody")[0];

			dojo.style.hide(table);

			for (var i = tbody.rows.length; i--;)
				tbody.deleteRow(i);

			var item = result.items[0];
			var row = tbody.insertRow(tbody.rows.length);
			row.className = "header";
			myAppendCell(row, "Date/Time", "header header-date");
			myAppendCell(row, "Order No.", "header header-order");
			myAppendCell(row, "Total", "header header-total");
			myAppendCell(row, "Status", "header header-status");

			for (var i = 0; i < result.items.length; i++)
			{
				var item = result.items[i];
				var row = tbody.insertRow(tbody.rows.length);
				row.className = "data row-mod2-"+ (i%2);
				row.id = "orderrow-"+ item.ContentID;
				var orderURL = "default.asp?mod=order&amp;order="+ item.ContentNumber1;
				var orderDate = new Date(item.Content_CD);

				dojo.event.connect(row, "onclick", orderClick);
				myAppendCell(row, '<a href="'+ orderURL +'" onclick="return false;">'+ orderDate.formatDate("d/m/y h:i A") +'</a>', "data data-date");
				myAppendCell(row, '<a href="'+ orderURL +'" onclick="return false;">'+ item.ContentNumber1 +'</a>', "data data-order");
				myAppendCell(row, '<a href="'+ orderURL +'" onclick="return false;">'+ numberToCurrency(item.ContentCurrency4) +'</a>', "data data-total");
				myAppendCell(row, '<a href="'+ orderURL +'" onclick="return false;">'+ orderStatus(item) +'</a>', "data data-status");
			}

			dojo.fx.html.fadeShow(table, standardFadeDuration);
			break;
	}
}

function showMemberForm (id)
{
	if (memberFormToggleStack>0)
		return;

	var nodeId, node;
	for (var i = memberFormList.length; i--;)
	{
		nodeId = memberFormList[i];
		if (nodeId == id)
			continue;
		node = dojo.byId(memberFormList[i]);
		if (!node)
			continue;
		dojo.style.hide(node);
	}

	node = dojo.byId(id);
	if (!node)
		return;

	if (node.style.display == "block")
		return;

	memberFormToggleStack++;
	dojo.fx.html.fadeShow(node, standardFadeDuration, decreaseMemberFormToggleStack);

	switch (id)
	{
		case "myDownloads":
			if (myDownloadsFirst)
			{
				var x = dojo.io.bind({
					url: "handler.asp",
					method: "POST",
					content: {"dojo.submit.action": "mydownloads"},
					handle: receiveMyDownloads,
					mimetype: "text/json",
					sendTransport: true
				});

				myDownloadsFirst = false;
			}
			break;

		case "myOrders":
			if (myOrdersFirst)
			{
				var x = dojo.io.bind({
					url: "handler.asp",
					method: "POST",
					content: {"dojo.submit.action": "myorders"},
					handle: receiveMyOrders,
					mimetype: "text/json",
					sendTransport: true
				});

				myOrdersFirst = false;
			}
			break;
	}
}

dojo.event.connect(window, "onload", function () {
	var hash = window.location.hash;
	if (hash)
		showMemberForm(hash.replace(/\#/,""));
});

Date.prototype.formatDate = function (input, time) {
	// formatDate :
	// a PHP date like function, for formatting date strings
	// See: http://www.php.net/date
	//
	// input : format string
	// time : epoch time (seconds, and optional)
	//
	// if time is not passed, formatting is based on
	// the current "this" date object's set time.
	//
	// supported:
	// a, A, B, d, D, F, g, G, h, H, i, j, l (lowercase L), L,
	// m, M, n, O, r, s, S, t, U, w, W, y, Y, z
	//
	// unsupported:
	// I (capital i), T, Z

	var switches =    ["a", "A", "B", "d", "D", "F", "g", "G", "h", "H",
					   "i", "j", "l", "L", "m", "M", "n", "O", "r", "s",
					   "S", "t", "U", "u", "w", "W", "y", "Y", "z"];
	var daysLong =    ["Sunday", "Monday", "Tuesday", "Wednesday",
					   "Thursday", "Friday", "Saturday"];
	var daysShort =   ["Sun", "Mon", "Tue", "Wed",
					   "Thu", "Fri", "Sat"];
	var monthsShort = ["Jan", "Feb", "Mar", "Apr",
					   "May", "Jun", "Jul", "Aug", "Sep",
					   "Oct", "Nov", "Dec"];
	var monthsLong =  ["January", "February", "March", "April",
					   "May", "June", "July", "August", "September",
					   "October", "November", "December"];
	var daysSuffix = ["st", "nd", "rd", "th", "th", "th", "th", // 1st - 7th
					  "th", "th", "th", "th", "th", "th", "th", // 8th - 14th
					  "th", "th", "th", "th", "th", "th", "st", // 15th - 21st
					  "nd", "rd", "th", "th", "th", "th", "th", // 22nd - 28th
					  "th", "th", "st"];                        // 29th - 31st

	function a() {
		// Lowercase Ante meridiem and Post meridiem
		return self.getHours() > 11? "pm" : "am";
	}
	function A() {
		// Uppercase Ante meridiem and Post meridiem
		return self.getHours() > 11? "PM" : "AM";
	}

	function B(){
		// Swatch internet time. code simply grabbed from ppk,
		// since I was feeling lazy:
		// http://www.xs4all.nl/~ppk/js/beat.html
		var off = (self.getTimezoneOffset() + 60)*60;
		var theSeconds = (self.getHours() * 3600) +
						 (self.getMinutes() * 60) +
						  self.getSeconds() + off;
		var beat = Math.floor(theSeconds/86.4);
		if (beat > 1000) beat -= 1000;
		if (beat < 0) beat += 1000;
		if ((""+beat).length == 1) beat = "00"+beat;
		if ((""+beat).length == 2) beat = "0"+beat;
		return beat;
	}

	function d() {
		// Day of the month, 2 digits with leading zeros
		return new String(self.getDate()).length == 1?
		"0"+self.getDate() : self.getDate();
	}
	function D() {
		// A textual representation of a day, three letters
		return daysShort[self.getDay()];
	}
	function F() {
		// A full textual representation of a month
		return monthsLong[self.getMonth()];
	}
	function g() {
		// 12-hour format of an hour without leading zeros
		return self.getHours() > 12? self.getHours()-12 : self.getHours();
	}
	function G() {
		// 24-hour format of an hour without leading zeros
		return self.getHours();
	}
	function h() {
		// 12-hour format of an hour with leading zeros
		if (self.getHours() > 12) {
		  var s = new String(self.getHours()-12);
		  return s.length == 1?
		  "0"+ (self.getHours()-12) : self.getHours()-12;
		} else {
		  var s = new String(self.getHours());
		  return s.length == 1?
		  "0"+self.getHours() : self.getHours();
		}
	}
	function H() {
		// 24-hour format of an hour with leading zeros
		return new String(self.getHours()).length == 1?
		"0"+self.getHours() : self.getHours();
	}
	function i() {
		// Minutes with leading zeros
		return new String(self.getMinutes()).length == 1?
		"0"+self.getMinutes() : self.getMinutes();
	}
	function j() {
		// Day of the month without leading zeros
		return self.getDate();
	}
	function l() {
		// A full textual representation of the day of the week
		return daysLong[self.getDay()];
	}
	function L() {
		// leap year or not. 1 if leap year, 0 if not.
		// the logic should match iso's 8601 standard.
		var y_ = Y();
		if (
			(y_ % 4 == 0 && y_ % 100 != 0) ||
			(y_ % 4 == 0 && y_ % 100 == 0 && y_ % 400 == 0)
			) {
			return 1;
		} else {
			return 0;
		}
	}
	function m() {
		// Numeric representation of a month, with leading zeros
		return self.getMonth() < 9?
		"0"+(self.getMonth()+1) :
		self.getMonth()+1;
	}
	function M() {
		// A short textual representation of a month, three letters
		return monthsShort[self.getMonth()];
	}
	function n() {
		// Numeric representation of a month, without leading zeros
		return self.getMonth()+1;
	}
	function O() {
		// Difference to Greenwich time (GMT) in hours
		var os = Math.abs(self.getTimezoneOffset());
		var h = ""+Math.floor(os/60);
		var m = ""+(os%60);
		h.length == 1? h = "0"+h:1;
		m.length == 1? m = "0"+m:1;
		return self.getTimezoneOffset() < 0 ? "+"+h+m : "-"+h+m;
	}
	function r() {
		// RFC 822 formatted date
		var r; // result
		//  Thu    ,     21          Dec         2000
		r = D() + ", " + j() + " " + M() + " " + Y() +
		//        16     :    01     :    07          +0200
			" " + H() + ":" + i() + ":" + s() + " " + O();
		return r;
	}
	function S() {
		// English ordinal suffix for the day of the month, 2 characters
		return daysSuffix[self.getDate()-1];
	}
	function s() {
		// Seconds, with leading zeros
		return new String(self.getSeconds()).length == 1?
		"0"+self.getSeconds() : self.getSeconds();
	}
	function t() {

		// thanks to Matt Bannon for some much needed code-fixes here!
		var daysinmonths = [null,31,28,31,30,31,30,31,31,30,31,30,31];
		if (L()==1 && n()==2) return 29; // leap day
		return daysinmonths[n()];
	}
	function U() {
		// Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
		return Math.round(self.getTime()/1000);
	}
	function u() {
		// milliseconds, with leading zeros
		var ms = String(self.getMilliseconds());
		switch (ms.length)
		{
			case 1:
				return "00"+ ms;
				break;
			
			case 2:
				return "0"+ ms;
				break;
			
			case 3:
				return ms;
				break;
		}
	}
	function W() {
		// Weeknumber, as per ISO specification:
		// http://www.cl.cam.ac.uk/~mgk25/iso-time.html

		// if the day is three days before newyears eve,
		// there's a chance it's "week 1" of next year.
		// here we check for that.
		var beforeNY = 364+L() - z();
		var afterNY  = z();
		var weekday = w()!=0?w()-1:6; // makes sunday (0), into 6.
		if (beforeNY <= 2 && weekday <= 2-beforeNY) {
			return 1;
		}
		// similarly, if the day is within threedays of newyears
		// there's a chance it belongs in the old year.
		var ny = new Date("January 1 " + Y() + " 00:00:00");
		var nyDay = ny.getDay()!=0?ny.getDay()-1:6;
		if (
			(afterNY <= 2) &&
			(nyDay >=4)  &&
			(afterNY >= (6-nyDay))
			) {
			// Since I'm not sure we can just always return 53,
			// i call the function here again, using the last day
			// of the previous year, as the date, and then just
			// return that week.
			var prevNY = new Date("December 31 " + (Y()-1) + " 00:00:00");
			return prevNY.formatDate("W");
		}

		// week 1, is the week that has the first thursday in it.
		// note that this value is not zero index.
		if (nyDay <= 3) {
			// first day of the year fell on a thursday, or earlier.
			return 1 + Math.floor( ( z() + nyDay ) / 7 );
		} else {
			// first day of the year fell on a friday, or later.
			return 1 + Math.floor( ( z() - ( 7 - nyDay ) ) / 7 );
		}
	}
	function w() {
		// Numeric representation of the day of the week
		return self.getDay();
	}

	function Y() {
		// A full numeric representation of a year, 4 digits

		// we first check, if getFullYear is supported. if it
		// is, we just use that. ppks code is nice, but wont
		// work with dates outside 1900-2038, or something like that
		if (self.getFullYear) {
			var newDate = new Date("January 1 2001 00:00:00 +0000");
			var x = newDate .getFullYear();
			if (x == 2001) {
				// i trust the method now
				return self.getFullYear();
			}
		}
		// else, do this:
		// codes thanks to ppk:
		// http://www.xs4all.nl/~ppk/js/introdate.html
		var x = self.getYear();
		var y = x % 100;
		y += (y < 38) ? 2000 : 1900;
		return y;
	}
	function y() {
		// A two-digit representation of a year
		var y = Y()+"";
		return y.substring(y.length-2,y.length);
	}
	function z() {
		// The day of the year, zero indexed! 0 through 366
		var t = new Date("January 1 " + Y() + " 00:00:00");
		var diff = self.getTime() - t.getTime();
		return Math.floor(diff/1000/60/60/24);
	}

	var self = this;
	if (time) {
		// save time
		var prevTime = self.getTime();
		self.setTime(time);
	}

	var ia = input.split("");
	var ij = 0;
	while (ia[ij]) {
		if (ia[ij] == "\\") {
			// this is our way of allowing users to escape stuff
			ia.splice(ij,1);
		} else {
			if (switches.exists(ia[ij])) {
				ia[ij] = eval(ia[ij] + "()");
			}
		}
		ij++;
	}
	// reset time, back to what it was
	if (prevTime) {
		self.setTime(prevTime);
	}
	return ia.join("");
}

Array.prototype.exists = function (x) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == x) return true;
	}
	return false;
}

tip_shop = '<img src="images/top_shop_on.png" width="131" height="57" alt="" class="image-png" />';
tip_members = '<img src="images/top_members_on.png" width="131" height="57" alt="" class="image-png" />';
tip_members_loggedin = tip_members;

function orderStatus (order)
{
	if (order.ContentBit3)
		return "CANCELLED";
	else if (order.ContentBit2)
		return "SHIPPED";
	else if (order.ContentBit1)
		return "PAID";
	else
		return "UNPAID";
}

function shadeUp (node)
{
	dojo.fx.html.fade(node, standardFadeDuration, 0.5, 1.0);
}

function shadeDown (node)
{
	dojo.fx.html.fade(node, standardFadeDuration, 1.0, 0.5);
}

