/*
* A Prototypical(Object Oriented) implementation of CSS dynamic loading
* Author: Andrew Powell, Copyright &copy; 2008
* Version: 1.0
* Date: 01/08/2008
*/

/**
* Create a CSSLoader class that is used to keep a track on the selected style sheet
**/
function CSSLoader() {
	this.cssIndex = 0;
	this.cssArray = new Array("css/blue_glow.css", "css/white_glow.css", "css/blue.css");	
}

/*
* Called when the page is loaded to load the selected style
*/
CSSLoader.prototype.loadStyle = function() {
	var styleIndex = getCookieValue("sdtcStyle");
	if(styleIndex != undefined) {
		this.loadStyleFromIndex(styleIndex);
	}
}

/*
* Load the style from the given index
*/
CSSLoader.prototype.loadStyleFromIndex = function(styleIndex) {
	this.addToPage(styleIndex);
	// Store the style index in the cookies
	writePersistentCookie("sdtcStyle", styleIndex + "", "years", 1);
}

/*
* Remove the old styles before the new ones are added
*/
CSSLoader.prototype.removeOldStyles = function() {
	/* Get the head element of the html document */
	var headElement = document.getElementsByTagName("head")[0];
	/* List the child node of the head tag */
	var children = headElement.childNodes;
	
	/* Remove old style from the DOM */
	for(var i = 0; i < children.length; i++) {
		if(children[i].tagName == "LINK") {
			if(children[i].href.lastIndexOf(this.cssArray[this.cssIndex]) != -1) {
				headElement.removeChild(children[i]);
			}
		}
	}
}

/*
* Add the style sheet with the given index to the page
*/
CSSLoader.prototype.addToPage = function(styleIndex) {
	// Remove the old styles first
	this.removeOldStyles();
	var headElement = document.getElementsByTagName("head")[0];
	// Add the new style to the DOM
	var cssNode = document.createElement("link");
	cssNode.type = "text/css";
	cssNode.rel = "stylesheet";
	// Remember to set the media type so that we don't interfere with the print stylesheet
	cssNode.media = "screen";
	cssNode.href = this.cssArray[styleIndex];
	headElement.appendChild(cssNode);
	
	// Add IE specific styles that override standard style settings
	if(isIE && Detector.getVersion() <= 6) {
		// Add the new style to the DOM
		var cssNode2 = document.createElement("link");
		cssNode2.type = "text/css";
		cssNode2.rel = "stylesheet";
		// Remember to set the media type so that we don't interfere with the print stylesheet
		cssNode2.media = "screen";
		cssNode2.href = "css/iespecific.css";
		headElement.appendChild(cssNode2);
	}
}

/*
* Called when the user chooses to change the style
*/
CSSLoader.prototype.changeStyle = function(selectionElement) {
	this.cssIndex = selectionElement.value == 9999 ? 0 : selectionElement.value;
	this.addToPage(this.cssIndex);
	// Store the style index in the cookies for 1 year
	writePersistentCookie("sdtcStyle", this.cssIndex + "", "years", 1);
}

new CSSLoader().loadStyle();