// --------------------------------------------------------------------------------
// ow_cssswitch.js
// Matthew Hogg 20-Apr-2004
// Contains core functions for generation and population of stylesheet switcher.
// --------------------------------------------------------------------------------
// IOTBS2.0 :: Invasion of the Body Switchers - Look Who's Switching Too
// --------------------------------------------------------------------------------
// This copyright statement must remain in place for both personal and commercial use
// GNU General Public License -- http://www.gnu.org/copyleft/gpl.html
// --------------------------------------------------------------------------------
// Original concept by Andy Clarke -- http://www.stuffandnonsense.co.uk/
// DOM scripting by brothercake -- http://www.brothercake.com/
// Create element and attributes based on a method by beetle -- http://www.peterbailey.net/
// --------------------------------------------------------------------------------

// --------------------------------------------------------------------------------
// This function is run upon page loading and sets up the stylewheet switcher.
// Modify this to change the options available via the switcher.
// --------------------------------------------------------------------------------

ow_f_AppendLoadEvent(
function() {
	var switcher = new switchManager("html", "/site-nsbi/styles/");
	var swch = new bodySwitcher("css_switch", "Text size:", "no", "");
	swch.defineClass("default", "A");
	swch.defineClass("big", "A");
	swch.defineClass("bigger", "A");
}
);

// --------------------------------------------------------------------------------
// switchManager functions.
// --------------------------------------------------------------------------------

function switchManager(canvas, path, useCookie) {
	switcher = this;
	this.canvas = canvas == "body" && typeof document.body != "undefined" ? document.body : document.getElementsByTagName(canvas)[0];
	this.initial = this.canvas.className;
	if (this.initial == "") { this.initial = "itobs"; }
	this.path = (typeof path != "undefined" && path != "" ? path : null);
	this.itoken = /(\:\[[0-9]+\])/;
	if (this.path != null) {
		this.tokenrefs = ["", -1];
		this.linkeles = document.getElementsByTagName("link");
	}
	this.master = null;
	this.string  = "";
	this.idstring = "";
	this.isop = typeof window.opera != "undefined";
	this.isie = typeof window.attachEvent != "undefined" && !this.isop;
	this.iskde = navigator.vendor == "KDE";
	
	this.cookie = this.read();
	
	if (typeof window.attachEvent != "undefined") {
		window.attachEvent("onunload", function() {
			var closures = ["onchange", "onclick", "onkeydown", "checker"];
			for (var i = 0; i<document.all.length; i++) {
				for(var j = 0; j < closures.length; j++) {
					document.all[i][closures[j]] = null;
				}
			}
		});
	}
};

switchManager.prototype.set = function(days) {
	var thedate = new Date();
	thedate.setTime(thedate.getTime() + ( days * 24 * 60 * 60 * 1000));
	var info = this.idstring;
	if (info == "") { thedate.setTime(0); }
	document.cookie = "OWCSSSwitch=" + info+ ";expires=" + thedate.toGMTString()+ ";path=/";
};

switchManager.prototype.read = function() {
	this.cookie = null;
	if (document.cookie && document.cookie.indexOf("OWCSSSwitch=") != -1) {
		this.idcookie = [];
		this.cookie = document.cookie.split("OWCSSSwitch=")[1].split(";")[0].split("&");
		var tmp = "", len = this.cookie.length;
		for (var i = 0; i < len; i++) {
			this.cookie[i] = this.cookie[i].split("=");
			if (this.cookie[i].length > 1) {
				if (this.path != null && this.itoken.test(this.cookie[i][1])) { this.tokenrefs = [this.cookie[i][0],parseInt(this.cookie[i][1].split(":[")[1], 10)]; }
				this.cookie[i][1] = this.cookie[i][1].replace(this.itoken, "");
				tmp += " " + this.cookie[i][1] + " ";
				this.idcookie[i] = this.cookie[i];
			}
		}
		this.cookie = tmp;
	}
	return this.cookie;
};

switchManager.prototype.save = function(ident, chosen, ind, obj) {
	this.ident = ident;
	this.idstring = this.idstring.replace(this.ident + "=", "");
	var len = obj.classes.length;
	for (var i = 0; i < len; i++) {
		this.string = this.string.replace(" " + obj.classes[i] + " ","");
		var reg = new RegExp("(" + obj.classes[i] + ")" + "(\:\[[0-9]+\])?" + "&", "");
		this.idstring = this.idstring.replace(reg,"");
	}
	if (chosen != "default") {
		this.string += " " + chosen + " ";
		this.idstring += this.ident + "=" + chosen;
		if (this.master == obj) { this.idstring += ":[" + ind + "]"; }
		this.idstring +=  "&";
	}
	if (this.path != null) {
		if (this.master != obj) {
			var linkele = document.getElementById(this.ident + "_stylesheet");
			if (linkele != null) {
				var sheetpath = this.path + this.ident + "_" + chosen + ".css";
				if (this.isop) { setTimeout(function() { linkele.href = sheetpath; }, 10); }
				if (this.isie) {
					var request = new ActiveXObject("Microsoft.XMLHTTP");
					request.open("GET", sheetpath, true);
					request.send(null);
					request.onreadystatechange = function() {
						if (request.readyState == 4 && request.status == 200) { linkele.href = sheetpath; }
					};
				}
				linkele.href = sheetpath;
			}
		} else {
			len = this.alternates.length;
			for (i = 0; i < len; i++) { this.alternates[i].disabled = i != ind; }
		}
	} else {
		this.canvas.className = this.initial + this.string;
	}
	this.set(365);
};

switchManager.prototype.integrate = function(obj, divid) {
	this.master = obj;
	this.alternates = [document.getElementById(divid + "_stylesheet")];
	var inscope = false;
	var len = this.linkeles.length;
	for (var i = 0; i < len; i++) {
		if (i > 0 && this.linkeles[i - 1] == this.alternates[0]) { inscope = true;}
		if (inscope) {
			if (this.linkeles[i].getAttribute("title") != null && this.linkeles[i].getAttribute("rel") != null && /(alternat)(iv)?(e stylesheet)/i.test(this.linkeles[i].rel)) {
				this.alternates[this.alternates.length] = this.linkeles[i];
			} else {
				inscope = false;
				break;
			}
		}
	}
	var isenabled = 0;
	var watcher = window.setInterval(function() {
		var len = switcher.alternates.length;
		for (var i = 0; i<len; i++) {
			if (!switcher.alternates[i].disabled) {
				if (i != isenabled) {
					isenabled = i;
					obj.update(i);
					switcher.save(divid, switcher.alternates[i].href.split(divid + "_")[1].split(".css")[0], i, obj);
				}
				break;
			}
		}
	}, 55);
};

switchManager.prototype.create = function(tag, attrs) {
	var ele = (typeof document.createElementNS != "undefined") ? document.createElementNS("http://www.w3.org/1999/xhtml",tag) : document.createElement(tag);
	if (typeof attrs != "undefined") {
		for (var i in attrs) {
			switch (i) {
				case "text" : ele.appendChild(document.createTextNode(attrs[i])); break;
				case "class" : ele.className = attrs[i]; break;
				case "for" : ele.setAttribute("htmlFor", attrs[i]); break;
				default : ele.setAttribute(i, ""); ele[i] = attrs[i]; break;
			}
		}
	}
	return ele;
};

// --------------------------------------------------------------------------------
// bodySwitcher functions.
// --------------------------------------------------------------------------------

function bodySwitcher(divid, label, isnative, selected) {
	if (switcher.path != null && !switcher.isie && typeof isnative != "undefined" && isnative == "yes") { switcher.integrate(this, divid); }
	this.classes = [];
	if (document.getElementById(divid) == null) { return false; }
	this.labels = [];
	var attrs = { "id" : "select_" + divid };
	this.dl = document.getElementById(divid).appendChild(switcher.create("dl", attrs));
	attrs = { "text" : label } ;
	this.dl.appendChild(switcher.create("dt", attrs));
	this.selected = typeof selected != "undefined" ? selected : "";
	return true;
};

bodySwitcher.prototype.defineClass = function(key, val) {
	this.classes[this.classes.length] = key;
	if (typeof this.dl == "undefined") { return false; }
	var self = this;
	this.labels[this.labels.length] = val;
	var item = this.dl.appendChild(switcher.create("dd"));
	if (this.dl.childNodes.length == 2) item.id = "swchFirst";
	item.className = "selected " + key;
	if (key == "default") {
		var link = item.appendChild(document.createTextNode(val + this.selected));
	} else if (switcher.cookie != null && switcher.cookie.indexOf(' ' + key + ' ') != -1) {
		link = item.appendChild(document.createTextNode(val + this.selected));
		if (key != "default") {
			var defitem = this.dl.childNodes[1];
			defitem.className = "default";
			this.dl.childNodes[1].removeChild(defitem.firstChild);
			var attrs = { "href" : "javascript:void(\"" + this.classes[0] + "\", \"" + this.labels[0] + "\")", "text" : this.labels[0] };
			link = defitem.appendChild(switcher.create("a", attrs));
		}
	} else {
		item.className = key;
		attrs = { "href" : "javascript:void(\"" + key + "\", \"" + val + "\")", "text" : val};
		link = item.appendChild(switcher.create("a", attrs));
	}
	item.onclick = function() {
		if (this.getElementsByTagName("a").length == 0) { return false; }
		var items = self.dl.getElementsByTagName("dd");
		var len = items.length;
		var dd = new Array(0);
		for (var i = 0; i < len; i++) if (items[i].className != "swchSeparator") dd[dd.length] = items[i];
		len = dd.length;
		for (var i = 0; i < len; i++) {
			if (dd[i] == this) {
				var ind = i;
				break;
			}
		}
		switcher.save(self.dl.id.replace("select_", ""), self.classes[ind], ind, self);
		self.redraw(ind, this);
		return true;
	};
	return true;
};

bodySwitcher.prototype.defineSeparator = function(sep) {
	if (typeof this.dl == "undefined") { return false; }
	var self = this;
	var item = this.dl.appendChild(switcher.create("dd"));
	if (this.dl.childNodes.length == 2) item.id = "swchFirst";
	item.className = "swchSeparator";
	attrs = { "text" : sep };
	link = item.appendChild(switcher.create("span", attrs));
	return true;
};

bodySwitcher.prototype.redraw = function(ind, link) {
	var items = this.dl.getElementsByTagName("dd");
	var len = items.length;
	var dd = new Array(0);
	for (var i = 0; i < len; i++) if (items[i].className != "swchSeparator") dd[dd.length] = items[i];
	len = dd.length;
	for(var i = 0; i < len; i++) {
		if (dd[i].firstChild.nodeName == "#text") {
			dd[i].className = this.classes[i];
			dd[i].removeChild(dd[i].firstChild);
			var attrs = { "href" : "javascript:void(\"" + this.classes[i] + "\", \"" + this.labels[i] + "\")", "text" : this.labels[i] };
			dd[i].appendChild(switcher.create("a", attrs));
		}
	}
	// setting this focus causes the wrong element to be focussed, and then the colour (white) causes it to be hidden
	// dd[(ind == len - 1 ? 0 : ind + 1)].firstChild.focus();
	link.removeChild(link.firstChild);
	link.appendChild(document.createTextNode(this.labels[ind] + this.selected));
	dd[ind].className += " selected";
};

bodySwitcher.prototype.update = function(ind) {
	if (typeof this.dl != "undefined") { this.redraw(ind, this.dl.getElementsByTagName("dd")[ind]); }
};
