/* ######## BEGIN: Events */
/* <http://tanny.ica.com/ica/tko/tkoblog.nsf/dx/domcontentloaded-for-browsers-part-ii> */
/* <http://tanny.ica.com/ica/tko/test.nsf/js/events.js> */

// written by Dean Edwards, 2005
// with input from Tino Zijdel, Matthias Miller, Diego Perini
// http://dean.edwards.name/weblog/2005/10/add-event/
function addEvent(element, type, handler) {
	// Modification by Tanny O'Haley, http://tanny.ica.com to add the
	// DOMContentLoaded for all browsers.
	if (type == "DOMContentLoaded" || type == "domload") {
		addDOMLoadEvent(handler);
		return;
	}
	
	if (element.addEventListener) {
		element.addEventListener(type, handler, false);
	} else {
		// assign each event handler a unique ID
		if (!handler.$$guid) handler.$$guid = addEvent.guid++;
		// create a hash table of event types for the element
		if (!element.events) element.events = {};
		// create a hash table of event handlers for each element/event pair
		var handlers = element.events[type];
		if (!handlers) {
			handlers = element.events[type] = {};
			// store the existing event handler (if there is one)
			if (element["on" + type]) {
				handlers[0] = element["on" + type];
			}
		}
		// store the event handler in the hash table
		handlers[handler.$$guid] = handler;
		// assign a global event handler to do all the work
		element["on" + type] = handleEvent;
	}
};
// a counter used to create unique IDs
addEvent.guid = 1;

function removeEvent(element, type, handler) {
	if (element.removeEventListener) {
		element.removeEventListener(type, handler, false);
	} else {
		// delete the event handler from the hash table
		if (element.events && element.events[type]) {
			delete element.events[type][handler.$$guid];
		}
	}
};

function handleEvent(event) {
	var returnValue = true;
	// grab the event object (IE uses a global event object)
	event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
	// get a reference to the hash table of event handlers
	var handlers = this.events[event.type];
	// execute each event handler
	for (var i in handlers) {
		this.$$handleEvent = handlers[i];
		if (this.$$handleEvent(event) === false) {
			returnValue = false;
		}
	}
	return returnValue;
};

function fixEvent(event) {
	// add W3C standard event methods
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
};
fixEvent.preventDefault = function() {
	this.returnValue = false;
};
fixEvent.stopPropagation = function() {
	this.cancelBubble = true;
};

// End Dean Edwards addEvent.

// Tino Zijdel - crisp@xs4all.nl This little snippet fixes the problem that the onload attribute on 
// the body-element will overwrite previous attached events on the window object for the onload event.
if (!window.addEventListener) {
	document.onreadystatechange = function(){
		if (window.onload && window.onload != handleEvent) {
			addEvent(document, 'DOMContentLoaded', window.onload);
			window.onload = handleEvent;
		}
	}
}

// Here are my functions for adding the DOMContentLoaded event to browsers other
// than Mozilla.

// Array of DOMContentLoaded event handlers.
window.onDOMLoadEvents = new Array();
window.DOMContentLoadedInitDone = false;

// Function that adds DOMContentLoaded listeners to the array.
function addDOMLoadEvent(listener) {
	window.onDOMLoadEvents[window.onDOMLoadEvents.length]=listener;
}

// Function to process the DOMContentLoaded events array.
function DOMContentLoadedInit() {
	// quit if this function has already been called
	if (window.DOMContentLoadedInitDone) return;

	// flag this function so we don't do the same thing twice
	window.DOMContentLoadedInitDone = true;

	// iterates through array of registered functions 
	for (var i=0; i<window.onDOMLoadEvents.length; i++) {
		var func = window.onDOMLoadEvents[i];
		func();
	}
}

function DOMContentLoadedScheduler() {
	// quit if the init function has already been called
	if (window.DOMContentLoadedInitDone) return true;
	
	// First, check for Safari or KHTML.
	// Second, check for IE.
	//if DOM methods are supported, and the body element exists
	//(using a double-check including document.body, for the benefit of older moz builds [eg ns7.1] 
	//in which getElementsByTagName('body')[0] is undefined, unless this script is in the body section)
	if(/KHTML|WebKit/i.test(navigator.userAgent)) {
		if(/loaded|complete/.test(document.readyState)) {
			DOMContentLoadedInit();
		} else {
			// Not ready yet, wait a little more.
			setTimeout("DOMContentLoadedScheduler()", 250);
		}
	} else if(document.getElementById("__ie_onload")) {
		return true;
	} else if(typeof document.getElementsByTagName != 'undefined' && (document.getElementsByTagName('body')[0] != null || document.body != null)) {
		DOMContentLoadedInit();
	} else {
		// Not ready yet, wait a little more.
		setTimeout("DOMContentLoadedScheduler()", 250);
	}
	
	return true;
}

// Schedule to run the init function.
setTimeout("DOMContentLoadedScheduler()", 250);

// Just in case window.onload happens first, add it there too.
addEvent(window, "load", DOMContentLoadedInit);

// If addEventListener supports the DOMContentLoaded event.
if(document.addEventListener)
	document.addEventListener("DOMContentLoaded", DOMContentLoadedInit, false);

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
	document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
	var script = document.getElementById("__ie_onload");
	script.onreadystatechange = function() {
		if (this.readyState == "complete") {
			DOMContentLoadedInit(); // call the onload handler
		}
	};
/*@end @*/

/* ######## END: Events */

function callbackWhenElementReady(id, callback)
{
	var obj = document.getElementById(id);
	if (obj && (obj.nextSibling || obj.textContent))
	{
		callback(obj);
	}
	else
	{
		setTimeout(function() { callbackWhenElementReady(id, callback); } , 1);
	}
}

function getCookie(name)
{
	for (var i = 0; i < document.cookie.split('; ').length; i++)
	{
		var crumb = document.cookie.split('; ')[i].split('=');
		if (crumb[0] == name && crumb[1] != null)
		{
			return crumb[1];
		}
	}
}

function getParam(name, defVal)
{
	var start = location.search.indexOf("?"+name+"=");
	if (start < 0)
	{
		start = location.search.indexOf("&"+name+"=");
	}
	if (start < 0)
	{
		return defVal;
	}
	start += name.length+2;
	
	var end = location.search.indexOf("&",start)-1;
	if (end < 0)
	{
		end = location.search.length;
	}
	
	var result='';
	for (var i=start; i<=end; ++i)
	{
		var c = location.search.charAt(i);
		result = result + (c=='+' ? ' ' : c);
	}
	
	return unescape(result);
	
}

function getWindowWidth()
{
	var w = 800;
	if (self.outerWidth)
	{
		w = self.outerWidth;
	}
	else if (document.all || navigator.userAgent.indexOf('WebKit') > -1)
	{
		w = document.body.clientWidth;
	}
	else if (document.layers)
	{
		w = window.innerWidth;
	}
	else if (screen.width)
	{
		w = screen.width;
	}
	return w;
}

function getWindowHeight()
{
	var h = 600;
	if (self.outerHeight)
	{
		h = self.outerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
	{
		h = document.documentElement.clientHeight;
	}
	else if (window.innerHeight)
	{
		h = window.innerHeight;
	}
	else if (document.layers)
	{
		h = window.innerHeight;
	}
	else if (screen.height)
	{
		h = screen.height;
	}
	return h;
}

function showPopup(url, id, width, height, scrollbars, resizable, statusbar)
{
	
	var w = getWindowWidth(), h = getWindowHeight();
	
	var leftPos = (w-width)/2, topPos = (h*0.4)-(height/2);
	
	if (window.screenLeft)
	{
		leftPos += window.screenLeft;
	}
	if (window.screenTop)
	{
		topPos += window.screenTop;
	}
	
	var wnd = window.open(url,id,
		'width='+width+',height='+height+',top='+topPos+',left='+leftPos+
		",resizable=" + (resizable?'yes':'no') +
		",scrollbars=" + (scrollbars?'yes':'no') +
		",status=" + (statusbar?'yes':'no') +
		",menubar=no,location=no,toolbar=no");
	
	if (wnd && wnd.focus)
	{
		wnd.focus();
	}
	
	return wnd;
	
}

function doPreventDefault(evt)
{

	// prevent default action in standard supporting browsers
	if (evt.preventDefault)
	{
		evt.preventDefault();
	}
	
	// prevent default action in IE 6
	evt.returnValue = false;
	return false;

}

function hasClass(obj, className)
{
	return (' '+obj.className+' ').indexOf(' '+className+' ') > -1;
}

function addClass(obj, className)
{
	if (!hasClass(obj, className))
	{
		obj.className += ' ' + className;
	}
}

function removeClass(obj, className)
{
	obj.className = (' '+obj.className+' ').replace(' '+className+' ', ' ');
}


function getElementsByClassName(oElm, strTagName, strClassName)
{
	var arrElements = (strTagName == "*" && document.all) ? document.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for (var i=0; i<arrElements.length; i++)
	{
		oElement = arrElements[i];      
		if (oRegExp.test(oElement.className))
		{
			arrReturnElements.push(oElement);
		}   
	}
	return arrReturnElements;
}

function getBaseURL()
{
	var baseURL = '';
	if (document.body.baseURI)
	{
		baseURL = document.body.baseURI;
	}
	else
	{
		var baseElements = document.getElementsByTagName("base");
		if (baseElements && baseElements.length)
		{
			baseURL = baseElements[0].href;
		}
	}
	baseURL = baseURL+""; // make sure it's a string
	if (baseURL.length && baseURL.substring(baseURL.length-1) != '/')
	{
		baseURL += '/';
	}
	return baseURL;
}

function getSizeTestDiv()
{
	var div = document.getElementById('SizeTestDiv');
	if (div == null)
	{
		div = document.createElement('div');
		div.id = 'SizeTestDiv';
		div.style.width = '100%';
		div.style.height = '100%';
		div.style.position = 'fixed';
		div.style.left = 0;
		div.style.top = 0;
		div.style.visibility = 'hidden';
		div.style.zIndex = -1;
		document.body.appendChild(div);
	}
	return div;
}

function getCurrentSize()
{
	
	var result = [];
	
	if (navigator.appName == 'Microsoft Internet Explorer')
	{
		var oldOverflow = document.body.style.overflow;
		document.body.style.overflow = 'hidden';
		var div = getSizeTestDiv();
		result.width = div.offsetWidth;
		result.height = div.offsetHeight;
		document.body.style.overflow = oldOverflow;
	}
	else if (navigator.appName == 'Opera')
	{
		result.width = parseInt(window.innerWidth) - 16;
		result.height = parseInt(window.innerHeight) - 16;
	}
	else
	{
		var div = getSizeTestDiv();
		result.width = div.scrollWidth;
		result.height = div.scrollHeight;
	}
	
	return result;
	
}

function stripUrlPath(url)
{
	var path = ""+url;
	if (path.indexOf('://') < 0 && path[0] != '/')
	{
		path = getBaseURL() + path;
	}
	var i = path.indexOf('://');
	if (i > 0)
	{
		path = path.substring(i+3);
		var i = path.indexOf('/');
		if (i > 0)
		{
			path = path.substring(i);
		}
	}
	return path;
}

function doAnalytics(url)
{
	if (typeof(urchinTracker) == 'function')
	{
		urchinTracker(stripUrlPath(url));
	}
}
