addLoadEvent(jsSet);
addLoadEvent(labelColumns);
addLoadEvent(initThemeSwitcher);

/*
if (document.all && window.attachEvent) {
	var ts = new domFunction(initThemeSwitcher, {'global' : 'id', 'head' : 'tag'});
} else {
	addLoadEvent(initThemeSwitcher);
}
*/

/*-  Add Load Event
----------------------------------------------------------------------*/
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}


/*-  "Tag" the outermost #page-wrap-outer div, so our CSS "knows" if JS is enabled
----------------------------------------------------------------------*/
function jsSet() {
	var pageWrap = document.getElementById("page-wrap-outer");
	pageWrap.className = "pulchritude" + pageWrap.className;
}


/*-  Markup cleanup
----------------------------------------------------------------------*/
/* Add an incrementing "column-X" class to each .col */
function labelColumns() {
	var rows = cssQuery(".row");
	for (var i = 0; i < rows.length; i++) {
		var cols = cssQuery(".col", rows[i]);
		for (var j = 0; j < cols.length; j++) {
			/*
				Since IE5/Mac has a whitespace parsing bug (http://macedition.com/cb/ie5macbugs/#whitespace), let's put column-X in the beginning to avoid any parsing errors.
			*/
			cols[j].className = "column-" + (j + 1) + " " + cols[j].className;
		}
	}
}


/*-  Switcher functions
----------------------------------------------------------------------*/
// Set the active stylesheet
function setActiveTheme(title) {
	var i, oneLink;
	var cssSlug = new RegExp("_share/themes/([a-z]+)/css/", "i");
	var linkSlug = new RegExp("theme-([a-z]+)", "i");

	// First, we'll set the active stylesheet.
	for (i = 0; (oneLink = document.getElementsByTagName("link")[i]); i++) {
		/*
			Process this <link /> if it:
				- Is of a type "text/css",
				- Has a title, and
				- Has a media type that contains the word "screen"
		*/
		if (oneLink.getAttribute("type") == "text/css" && oneLink.getAttribute("title") && oneLink.getAttribute("media").indexOf("screen") != -1) {
			oneLink.disabled = true;
			// If the URL contains the slug, then set this stylesheet as "active".
			if (cssSlug.exec(oneLink.getAttribute("href"))[1] == title) {
				oneLink.disabled = false;
			}
		}
	}
	
	// Now, loop through the widget's links, and set the appropriate link to "active"
	widgets = cssQuery("li li a");

	for (j = 0; j < widgets.length; j++) {
		var liParent = getParent(widgets[j], "li");
		var liClass = liParent.getAttribute("id");
		liParent.className = "";

		if (linkSlug.exec(liClass)[1] == title) {
			liParent.className = "active";
		}
	}

	setCookie("styleness", title, 365);
}


/*-  Cookie functions
----------------------------------------------------------------------*/
// Set the cookie
function setCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = ";expires="+date.toGMTString();
	} else {
		expires = "";
	}
	document.cookie = name+"="+value+expires+";";
}

// Read the cookie
function readCookie(name) {
	var needle = name + "=";
	var cookieArray = document.cookie.split(';');
	for(var i=0;i < cookieArray.length;i++) {
		var pair = cookieArray[i];
		while (pair.charAt(0)==' ') {
			pair = pair.substring(1, pair.length);
		}
		if (pair.indexOf(needle) == 0) {
			return pair.substring(needle.length, pair.length);
		}
	}
	return null;
}


/*-  IE Fix: Son of Suckerfish
----------------------------------------------------------------------*/
sfHover = function() {
	var sfEls = document.getElementById("global").getElementsByTagName("LI");
	for (var i=0; i < sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className += (this.className.length > 0 ? " ": "") + "sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className = this.className.replace(new RegExp("( ?|^)sfhover\\b"), "");
		}
	}
}

if (document.all) {
	if (window.attachEvent) {
		window.attachEvent("onload", sfHover);
	} else {
		var old = window.onload; 
		window.onload = function() { if (old) old(); sfHover(); }
	}
}


/*-  Miscellaneous functions
----------------------------------------------------------------------*/
// Find full word (needle) in a string (haystack)
function findWord(needle, haystack) {
	return haystack.match(needle + "\\b");
}

// Get parent element
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);
}


/*-  DF1.1 :: domFunction 
	DOM scripting by brothercake -- http://www.brothercake.com/
	GNU Lesser General Public License -- http://www.gnu.org/licenses/lgpl.html
----------------------------------------------------------------------*/

// DOM-ready watcher
function domFunction(f, a)
{
	//initialise the counter
	var n = 0;
	
	//start the timer
	var t = setInterval(function()
	{
		//continue flag indicates whether to continue to the next iteration
		//assume that we are going unless specified otherwise
		var c = true;

		//increase the counter
		n++;
	
		//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(typeof document.getElementsByTagName != 'undefined' && (document.getElementsByTagName('body')[0] != null || document.body != null))
		{
			//set the continue flag to false
			//because other things being equal, we're not going to continue
			c = false;

			//but ... if the arguments object is there
			if(typeof a == 'object')
			{
				//iterate through the object
				for(var i in a)
				{
					//if its value is "id" and the element with the given ID doesn't exist 
					//or its value is "tag" and the specified collection has no members
					if
					(
						(a[i] == 'id' && document.getElementById(i) == null)
						||
						(a[i] == 'tag' && document.getElementsByTagName(i).length < 1)
					) 
					{ 
						//set the continue flag back to true
						//because a specific element or collection doesn't exist
						c = true; 

						//no need to finish this loop
						break; 
					}
				}
			}

			//if we're not continuing
			//we can call the argument function and clear the timer
			if(!c) { f(); clearInterval(t); }
		}
		
		//if the timer has reached 60 (so timeout after 15 seconds)
		//in practise, I've never seen this take longer than 7 iterations [in kde 3 
		//in second place was IE6, which takes 2 or 3 iterations roughly 5% of the time]
		if(n >= 60)
		{
			//clear the timer
			clearInterval(t);
		}
		
	}, 250);
};

