/*\
 | Copyright (C) 2009-2010 Link Digital
 | http://www.linkdigital.com.au/
 | All rights reserved.
 | Unauthorised copying, distribution or derivation is prohibited.
\*/


/****************************** Helper Functions ******************************/

Array.min	= function (array)	{ return Math.min.apply (Math, array); };
Array.max	= function (array)	{ return Math.max.apply (Math, array); };

/****************************** General Utility *******************************/

// Set all <a> tags with rel="ext" to open in new window
function a_init_ext (element)
{
	if (!(element = $ (element)))	return;

	element.observe ("click", function (event) { window.open (this.readAttribute ("href")); event.stop (); });
}


// Swap an image src on mouseover
function img_init_hovr (element)
{
	if (!(element = $ (element)))	return;

	element.src	= element.src.replace ('bnav_', 'bfix_');

	element.up ().observe ("mouseover",	function (event) { element.src	= element.src.replace ('bfix_', 'bnav_'); });
	element.up ().observe ("mouseout",	function (event) { element.src	= element.src.replace ('bnav_', 'bfix_'); });
}

// Set an input text box to clear its default text on focus
function input_init_srch (element)
{
	if (!(element = $ (element)))	return;

	var temp		= $F (element);

	element.setValue (element.readAttribute ("title"));
	element.defaultValue	= $F (element);

	element.observe ("focus", function ()
	{
		if ($F (this) === this.defaultValue)
		{
			this.clear ();
			this.removeClassName ("dflt");
		}
	});

	element.observe ("blur",  function ()
	{
		if (!this.present ())
		{
			this.setValue (this.defaultValue);
			this.addClassName ("dflt");
		}
	});

	if (temp)
		element.setValue (temp);
	else	element.addClassName ("dflt");
}

// Set an input password box to show plaintext until focus
function input_init_pass (element)
{
	if (!(element = $ (element)))	return;
	element.removeClassName ("lc_pass");
	element.setValue ("");

	//var newelem = element.clone (); 		// IE won't let us just change the type attribute, OR clone the element >:(
	var newelem = new Element ("input",
	{
		name:		"-1",
		type:		"text",
		value:		"Password",
		title:		"Password",
		tabindex:	parseInt (element.getAttribute ("tabindex")) + 1,
		className:	element.className
	});

	element.twin = newelem;
	newelem.twin = element;

	newelem.observe ("focus", function () { this.replace (this.twin); this.twin.activate (); });	// this.twin.focus doesn't work right in IE for some reason
	element.observe ("blur",  function () { if (!this.present ()) this.replace (this.twin); });

	element.focus ();
	element.blur ();
}


/********************************** Gallery ***********************************/
/*
var GallerySwaps	= [];	// This is now done via CSS, which is better.

function a_init_swap (element)
{
	if (!(element = $ (element)))	return;

	GallerySwaps.push (element.down ());

	element.observe ("mouseover", function (event)
	{
		GallerySwaps.each (function (img, n)
		{
			img.setStyle ({ visibility: "visible" });
		});
		this.down ().setStyle ({ visibility: "hidden" });
	});

	element.observe ("mouseout", function (event)
	{
		GallerySwaps.each (function (img, n)
		{
			img.setStyle ({ visibility: "hidden" });
		});
	});
}
*/
/********************************** Cookies ***********************************/

// Make cookies easier to deal with
var CookieJar =
{
	set: function (name, value, days)
	{
		var expires = "";

		if (days)
		{
			var date = new Date ();
			date.setTime (date.getTime () + (days * 86400000));
			expires = "; expires=" + date.toGMTString ();
		}

		document.cookie = name + "=" + value + expires + "; path=/";
	},

	get: function (name)
	{
		var ca		= document.cookie.split (";");

		for (var i = ca.length; i--; )
		{
			var c = ca[i].trim ().split ("=");
			if (c[0] == name) return c[1];
		}

		return null;
	},

	clr: function (name)
	{
		this.set (name, "", -1);
	}
};


/******************************* Image Rotator ********************************/

function linkCMS_Splash (splashID, xmlPath)
{
	var splashX		= 0;
	var splashZ		= 0;
	var splashM		= 0;
	var splashL		= $ (splashID + "_links");
	var splash1;
	var splash2;

	if (!(splashID = $ (splashID))) return 0;

	new Ajax.Request (xmlPath,
	{
		method: 	"get",
		onSuccess:	splash_Init,
		onFailure:	function (response) { alert ("FAIL: " + response); }
	});


	function splash_Init (response)
	{
		var xml 	= response.responseXML;

		var imgs	= xml.getElementsByTagName ("image");
		var tFade	= xml.getElementsByTagName ("fadeInTime")[0].getAttribute ("val");
		var tHold	= xml.getElementsByTagName ("holdTime"  )[0].getAttribute ("val");

		splashM 	= imgs.length;

		splashID.store ("tFade",	tFade);
		splashID.store ("tHold",	tHold);

		$R (0, splashM, true).each (function (x)
		{
			var src			= imgs[x].getAttribute ("uri");
			var rel 		= imgs[x].getAttribute ("rel");
			var ttl 		= imgs[x].getAttribute ("title");
			var href		= imgs[x].getAttribute ("link");

			var img			= new Image (); 				// Helps ensure the image loads properly
			img.src 		= src;

			var elI 		= new Element ("img",
			{
				id:		"splashImg" + x,
				alt:		ttl,
				src:		src
			});

			elI.store ("prev", "splashImg" + ((x - 1 + splashM) % splashM));	// Because Modulo doesn't work on negative numbers
			elI.store ("next", "splashImg" + ((x + 1 + splashM) % splashM));

			if (x)	elI.hide ();

			if (href !== "")							// If we have an associated link, add that too
			{
				var elA 	= new Element ("a");
				if (href)	elA.setAttribute ("href", href);
				if (rel)	elA.setAttribute ("rel",  rel);

				splashID.insert (elA, "bottom");
				elA.insert (elI, "bottom");
			}
			else	splashID.insert (elI, "bottom");				// No link, just add the image

			if (splashL)
			{
				var elL 		= new Element ("a",
				{
					id:		"splashLnk" + x,
					title:		ttl,
					href:		"#"
				});

				elL.update (x + 1);
				elL.store ("jump", x);
				elL.observe ("click", function (event) { splash_Jump (this.retrieve ("jump")); event.stop (); });

				splashL.insert (elL, "bottom");
			}
		});

		if (splashM > 1) splash_Next ();
	}


	function splash_Next ()
	{
		var elI 		= $ ("splashImg" + splashX);
		var elP 		= $ (elI.retrieve ("prev"));
		var elN 		= $ (elI.retrieve ("next"));

		splashX 		= ++splashX % splashM;

		elP.hide ();

// -- Slide effect
		var w			= elN.getWidth ();
		var m			= "absolute";
		var f			= splashID.retrieve ("tFade");
		var h			= splashID.retrieve ("tHold");
		elI.setStyle ({zIndex:	 0, left:	0});
		elN.setStyle ({zIndex:	 1, left:	w + "px"});
		elN.show ();

		splash1 		= new Effect.Move (elN.id,
		{
			x:		0,
			//y:		0,
			mode:		m,
			duration:	f,
			delay:		h,
			afterFinish:	splash_Next
		});

		splash2 		= new Effect.Move (elI.id,
		{
			x:		0 - w,
			//y:		0,
			mode:		m,
			duration:	f,
			delay:		h
		});
/*
// -- Fade effect
		elI.setStyle ({zIndex:	 0});
		elN.setStyle ({zIndex:	 1});

		splash1 		= new Effect.Appear (elN.id,
		{
			from:		0,
			to:		1,
			duration:	splashID.retrieve ("tFade"),
			delay:		splashID.retrieve ("tHold"),
			afterFinish:	splash_Next
		});
*/
	}


	function splash_Jump (jumpTo)
	{
		var elI 		= $ ("splashImg" + splashX);
		var elN 		= $ ("splashImg" + jumpTo);

		splashX 		= jumpTo % splashM;

		elN.hide ();

// -- Fade effect
		elI.setStyle ({zIndex:	 0});
		elN.setStyle ({zIndex:	 1, left:	0});

		splash1.cancel ();
		splash2.cancel ();

		splash1 		= new Effect.Appear (elN.id,
		{
			from:		0,
			to:		1,
			duration:	splashID.retrieve ("tFade"),
			//delay:		splashID.retrieve ("tHold"),
			afterFinish:	splash_Next
		});
	}

	return 1;
}


/******************************** Load Things *********************************/

// Load everything
document.observe ("dom:loaded", function ()
{
/*	// Count AJAX objects
	var complex	= 0;
	var ajax	= 0;

	Ajax.Responders.register
	({
		onCreate:	function () { ++ajax; },
		onComplete:	function () { if (!--ajax) linkCMS_Load (); }		// Load normal stuff once AJAX has finished
	});


	// Complex stuff - uncomment as needed
	complex		+= linkCMS_Splash ("splash", "/site/splash.xml");		// Image Rotator


	// Normal stuff
	if (!complex)*/	   linkCMS_Load ();
});


// Normal stuff
function linkCMS_Load ()
{
	$$ ("a[rel~=ext]").each 		(a_init_ext);		// Anchor OnClicks
	//$$ ("a[rel~=swap]").each 		(a_init_swap);		// Gallery Image hovers

	//$$ ("input.lc_srch").each		(input_init_srch);	// Search field niceness
	//$$ ("input.lc_pass").each		(input_init_pass);	// Password field niceness

	//$$ (".lc_hide").invoke			('hide');		// Hide stuff that can't be put in <noscript> tags.
	//$$ (".lc_show").invoke			('show');		// Show stuff that is only of use to people with scripts enabled.
}


