// IOTBS1.3[DC] :: Invasion of the Body Switchers: "The Director's Cut"
// ***********************************************
// This copyright statement must remain in place for both personal and commercial use
// BSD License -- see license.txt for licensing information
// ***********************************************
// 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/
//
// Changed by Øyvind Smestad to put classes also on switcher elements -- http://www.ixd.no/
// (so they can be styled individualy)
//************************************************
function iotbs() { //open initialisation function 
//************************************************

//initialise the preferences manager ('canvas-element')
switcher = new switchManager('body');

/*****************************************************************************
 Define switching controls
*****************************************************************************/


//create a new switcher control ('container-id', 'label', '"selected" text')
var fontsizeSwitcher = new bodySwitcher('fontsize-switcher', 'Skriftstørrelse:', '*');

//add a new class option ('classname', 'label')
fontsizeSwitcher.defineClass('default', 'A');
fontsizeSwitcher.defineClass('larger', 'A');
fontsizeSwitcher.defineClass('largest', 'A');

var colorSwitcher = new bodySwitcher('color-switcher', 'Kontrast:', '*');
colorSwitcher.defineClass('default', 'Normal');
colorSwitcher.defineClass('high-contrast', 'Høy');


/*****************************************************************************
*****************************************************************************/



//close initialisation function
};


//global switch manager reference
var switcher;


//DOM-ready watcher
function domReady()
{
	//start or increment the counter
	this.n = typeof this.n == 'undefined' ? 0 : this.n + 1;

	//if DOM methods are supported, and the body element exists
	if(typeof document.getElementsByTagName != 'undefined' && (document.getElementsByTagName('body')[0] != null || document.body != null))
	{
		//if this is not mac/ie
		if(!(typeof document.all != 'undefined' && typeof window.opera == 'undefined' && typeof document.mimeType == 'undefined'))
		{
			//initialise IOTBS
			iotbs();
		}
	}

	//otherwise if we haven't reached 60 (so timeout after 15 seconds)
	else if(this.n < 60)
	{
		//restart the watcher
		setTimeout('domReady()', 250);
	}
};
//start the watcher
domReady();


//switch manager 
function switchManager(canvas)
{
	//string for storing the overall custom classname
	//I was originally storing it in the body class name directly
	//but 1.7+ mozilla builds were not honouring the trailing whitespace we need
	this.string  = '';
	
	//store reference to canvas element
	//if the canvas is 'body' and the document.body object exists, use that reference
	//because in older moz builds (eg ns7.1) document.getElementsByTagName('body')[0] is undefined
	//unless this script is in the body section (which it isn't)
	this.canvas = canvas == 'body' && typeof document.body != 'undefined' ? document.body : document.getElementsByTagName(canvas)[0];

	//store the initial classname
	this.initial = this.canvas.className;
	
	//if the default classname is empty, add "iotbs"
	//because we need there to be at least one classname already - 
	//the leading and trailing space in each custom classname is required, 
	//but you can't set a classname attribute as " something" (beginning with a leading space)
	//because that fails in some Opera 7 builds
	if(this.initial == '')
	{
		this.initial = 'itobs';
	}
	
	//look for a stored cookie
	this.cookie = this.read();

	//if it exists
	if(this.cookie != null)
	{
		//store cookie value to string
		this.string = this.cookie;
		
		//set new canvas class name
		this.canvas.className = this.initial + this.string;
	}


	//add a DOM memory cleaner for win/ie
	if(typeof window.attachEvent != 'undefined')
	{
		window.attachEvent('onunload', function()
		{
			//for each item in the document.all collection
			for(var i=0; i<document.all.length; i++)
			{
				//set its onclick property to null
				//so that if this object is one of our selectors
				//the property can be garbage collected
				document.all[i]['onclick'] = null;
			}
		});
	}
};

//set a cookie method
switchManager.prototype.set = function(days)
{
	//format expiry date
	var thedate = new Date();
	thedate.setTime(thedate.getTime() + ( days *24*60*60*1000));
	
	//store the string, replacing spaces with '#' so that leading spaces are preserved
	var info = this.string.replace(/ /g,'#');
	
	//if the value is empty, set its expiry in the past to delete the cookie
	if(info == '') { thedate.setTime(0); }
	
	//create the cookie
	document.cookie = 'bodySwitcher=' + info
		+ '; expires=' + thedate.toGMTString() 
		+ '; path=/';
};

//read a cookie method
switchManager.prototype.read = function()
{
	//set null reference so we always have something to return
	this.cookie = null;
	
	//if a cookie exists and it's ours
	if(document.cookie && document.cookie.indexOf('bodySwitcher=')!=-1)
	{
		//extract and store relevant information (turning '#' back into spaces)
		this.cookie = document.cookie.split('bodySwitcher=')[1].split(';')[0].replace(/#/g,' ');
	}
	
	return this.cookie;
};



//switcher-control constructor
function bodySwitcher(divid, label, selected)
{
	//don't continue if the container doesn't exist
	if(document.getElementById(divid) == null) { return false; }

	//create an associate array of classnames and labels for this option
	//so we can later iterate through and remove them from the custom classname string
	//and so we have scope-global references to the key and value for each item
	this.classes = [], this.labels = [];

	//definition list inside container div
	var attrs = { 'id' : 'select-' + divid };
	this.dl = document.getElementById(divid).appendChild(this.create('dl', attrs));

	//definition term [switcher heading containing label text]
	attrs = { 'text' : label };
	this.dl.appendChild(this.create('dt', attrs));
	
	//"selected" text
	this.selected = selected;
	
	return true;
};


//add a new class option method
bodySwitcher.prototype.defineClass = function(key, val)
{
	//don't continue if the list doesn't exist
	if(typeof this.dl == 'undefined') { return false; }
	
	//definition inside list
	var item = this.dl.appendChild(this.create('dd'));

	//add selected class name to definition
	item.className = 'selected';

	//if key is default
	if(key == 'default')
	{
		//add plain text inside definition
		var link = item.appendChild(document.createTextNode(val + this.selected));
	}
	
	//else if cookie exists and value contains this key
	else if(switcher.cookie != null && switcher.cookie.indexOf(' ' + key + ' ')!=-1) 
	{
		//add plain text inside definition
		link = item.appendChild(document.createTextNode(val + this.selected));
		
		//if this is *not* the default item
		if(key != 'default')
		{
			//turn default text back into a link
			//we're doing it this way, instead of just creating a default link
			//because at the point where the default item is created
			//we don't know whether it should be a link or not
			//so we create it as plain text to begin with, and convert it here
			//because we know, now, that the default should be a link
			this.defitem = this.dl.childNodes[1];
			
			//so .. store existing text
			this.text = this.defitem.firstChild.nodeValue;
			
			//remove selected class name 
			this.defitem.className = '';
			
			//remove the text node
			this.defitem.removeChild(this.defitem.firstChild);
			
			//and replace it with a link to select the default (ØS: added class)
			var attrs = { 'href' : 'javascript:void("' + this.classes[0] + '", "' + this.labels[0] + '")', 'text' : this.labels[0], 'class' : this.classes[0] };
			link = this.defitem.appendChild(this.create('a', attrs));
		}
	}

	//else if cookie doesn't exist or value doesn't contains this key
	else
	{
		//remove selected class name 
		item.className = '';
			
		//add link inside definition
		//javascript: uri is used to store key value
		//and so that the link is navigable with the keyboard (ØS: added class)
		attrs = { 'href' : 'javascript:void("' + key + '", "' + val + '")', 'text' : val, 'class' : key };
		link = item.appendChild(this.create('a', attrs));
	}
	
	//create a reference to 'this'
	var self = this;
	
	//bind onclick handler to list-item
	item.onclick = function()
	{
		//if this item has no link, don't continue
		if(this.getElementsByTagName('a').length == 0) { return false; }
		
		//run through classnames array
		var len = self.classes.length;
		for(var i=0; i<len; i++)
		{
			//remove this key (custom class name) from string
			switcher.string = switcher.string.replace(' ' + self.classes[i] + ' ','');
		}

		//get key from link href
		//unescaping is necessary in safari
		var key = unescape(this.firstChild.href).split('"')[1];

		//if it isn't default then add to string
		//we need both a leading and a trailing space to work with 
		//to avoid confusion with identical leading or trailing substrings in classnames,
		//such as "high" and "highcontrast" or "large-serif" and "small-serif"
		if(key != 'default')
		{
			switcher.string += ' ' + key + ' ';	
		}

		//get definitions in this list
		var items = self.dl.getElementsByTagName('dd');
		len = items.length;
		
		//for each definition
		for(i=0; i<len; i++)
		{
			//if it's the previously selected value it will only be a text node
			if(items[i].firstChild.nodeName == '#text')
			{
				//remove "selected" class name from definition
				items[i].className = '';

				//remove the text node
				items[i].removeChild(items[i].firstChild);
				
				//and replace it with a link to reselect this style (ØS: added class)
				var attrs = { 'href' : 'javascript:void("' + self.classes[i] + '", "' + self.labels[i] + '")', 'text' : self.labels[i], 'class' : self.classes[i] };
				var link = items[i].appendChild(self.create('a', attrs));
			}
		}
			
		//for each definition again
		//we're doing this as two discreet loops
		//because the first process needs to have run over the whole list already
		//so that the link we're sending focus to definitely exists
		for(i=0; i<len; i++)
		{
			//if it's this one
			if(items[i] == this)
			{
				//if this is the last item, send focus to the first item
				//if it's any other item, send focus to the next item
				//this is because the activated link just had the focus
				//and removing a focussed element can cause 
				//the page focus caret to be lost or reset to the top 
				//an added benefit is that it allows you to toggle between 
				//all styles in a group by repeatedly pressing enter
				items[ (i == len - 1 ? 0 : i + 1) ].firstChild.focus();
				
				//remove the link
				this.removeChild(this.firstChild);
				
				//add a text node label to replace the link
				this.appendChild(document.createTextNode(self.labels[i] + self.selected));

				//add "selected" class name to definition
				this.className = 'selected';
			}
		}
		
		//set new canvas class name
		switcher.canvas.className = switcher.initial + switcher.string;

		//store changes to a cookie which expires a year from now
		switcher.set(365);

		return true;
	};

	//store the classname 
	this.classes[this.classes.length] = key;
	
	//store the link text labels
	this.labels[this.labels.length] = val;
	
	return true;
};


//create element and attributes method -- http://www.codingforums.com/showthread.php?s=&postid=151108
bodySwitcher.prototype.create = function(tag, attrs)
{
	//detect support for namespaced element creation, in case we're in the XML DOM
	var ele = (typeof document.createElementNS != 'undefined') ? document.createElementNS('http://www.w3.org/1999/xhtml',tag) : document.createElement(tag);

	//run through attributes argument
	if(typeof attrs != 'undefined')
	{
		for(var i in attrs)
		{
			switch(i)
			{
				//create a text node
				case 'text' :
					ele.appendChild(document.createTextNode(attrs[i]));
					break;
				
				//create a class name
				case 'class' : 
					ele.className = attrs[i];
					break;
				
				//create a generic attribute using IE-safe attribute creation
				default : 
					ele.setAttribute(i,'');
					ele[i] = attrs[i];
					break;
			}
		}
	}
	return ele;
};




