/************************************************************************************
Dynamic User Preference Script.
Copyright (C) 2005 Tony Aslett 
 
http://www.csscreator.com/
Version 1.6
updated 28 July 2005

This script enables users with JavaScript and cookies enabled to select 
different styles to be applied to your site.
For more info see http://www.csscreator.com/generator/userpref.php

Please leave this notice at the top of the script.
-----------------------------------------------------------------------------------------------------------------------------
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details. http://www.gnu.org/copyleft/gpl.html
************************************************************************************/

/* This display the controls */
function displayPreferenceControls(){
	/* Check if this will work before displaying controls */
	if(navigator.cookieEnabled && document.styleSheets && (document.styleSheets[0].addRule || document.styleSheets[0].insertRule)){
		document.write(
		"<form id='userpref' name='userpref'>"+
		// "<fieldset>"+
		// "<legend>Controlled Choices</legend>"+
		
		// USE A TEXT LINK:
		// "<a href=\"#\" onclick=\"addstyle('body', 'background-color:#00A', '')\">Blue</a>"+
		// USE AN IMAGE LINK:
		// "<a href=\"#\" onclick=\"addstyle('body', 'background-color:#00A', '')\"><img src='myimage.gif' width='10' height='10' alt='blue' /></a>"+
		
"<p>Text Size:<br />"+
"<span class=\"bnav\"><a href=\"#\" onclick=\"addstyle('body', 'font-size:clear', '')\">Default</a>"+
"<a href=\"#\" onclick=\"addstyle('body', 'font-size:x-small', '')\">Small</a>"+
"<a href=\"#\" onclick=\"addstyle('body', 'font-size:small', '')\">Med</a></span>"+
"<a href=\"#\" onclick=\"addstyle('body', 'font-size:medium', '')\">Large</a></p>"+

"<p>Text Family:<br />"+		
"<span class=\"bnav\"><a href=\"#\" onclick=\"addstyle('body', 'font-family:clear', '')\">Default</a>"+
"<a href=\"#\" onclick=\"addstyle('body', 'font-family:arial', '')\">Arial</a>"+
"<a href=\"#\" onclick=\"addstyle('body', 'font-family:serif', '')\">Serif</a></span>"+
"<a href=\"#\" onclick=\"addstyle('body', 'font-family:monospace', '')\">Monospace</a></p>"+

"<p><a href=\"#\" onclick=\"eatCookie('userpref')\">Reset All</a></p>"+
		
		/*
		" <label for='fontsize'>Font Size:</label>"+
		"<select name='fontsize' id='fontsize' onchange='addstyle(\"body\",this.options[this.selectedIndex].value, this.id+\"_\"+this.selectedIndex)'>"+
		"<option value='font-size:clear' >Default</option>"+
		"<option value= 'font-size:xx-small'>xx-small</option>"+
		"<option value= 'font-size:x-small'>x-small</option>"+
		"<option value= 'font-size:small'>small</option>"+
		"<option value= 'font-size:medium'>medium</option>"+
		"<option value= 'font-size:large'>large</option>"+
		"<option value= 'font-size:x-large'>x-large</option>"+
		"<option value= 'font-size:xx-large'>xx-large</option>"+
		"</select>"+
		" <label for='fontfamily'>Font:</label>"+
		"<select name='fontfamily' id='font-family' onchange='addstyle(\"body\",this.options[this.selectedIndex].value, this.id+\"_\"+this.selectedIndex)'>"+
		"<option value='font-family:clear' >Default</option>"+
		"<option value= 'font-family:serif'>serif</option>"+
		"<option value= 'font-family:sans-serif'>sans-serif</option>"+
		"<option value= 'font-family:cursive'>cursive</option>"+
		"<option value= 'font-family:monospace'>monospace</option>"+
		"</select>"+	
		*/
		
		// "</fieldset><br />"+
				"</form>"
	
		
		);
	}else{
		/* if their browser supports JavaScript but not some of the functions or cookies are disabled then you can output alternative content here.*/
		// document.write('This should be user preference controls, but unfortunately your browser cannot understand the required functions');
	}
}	

/* sets the selected value of each form element */
function setFormSelected(frmid, cookiename){
	var cookie=getCookie(cookiename); 						/* get existing cookie */
	var cookies=cookieCutter(cookie, "|"); 

	var frm=document.getElementById(frmid);
	if(testVar(frm)){
		var selects=frm.getElementsByTagName("SELECT");
		if(testVar(selects)){
			for(var sl=0; sl < selects.length; sl++){
			
				var opts=selects[sl].getElementsByTagName("OPTION");
				if(testVar(opts)){
					var oidx=findCookie(cookies, selects[sl].id);
					if(oidx){
						opts[oidx].selected="selected";
					}
						
				}
			}
		}
	}
}


function findCookie(cookies, fid){
	
	var found = false;	
	if(testVar(cookies)){
		for(var i=0; i < cookies.length; i++){
			var cookiecrumbs=cookies[i].split('[');
			if(testVar(cookiecrumbs[1])){
				chips=cookiecrumbs[1].split("_"); 
				if(testVar(chips[0])){
					if(fid == chips[0]){
						found=parseInt(chips[1]);					
					}
				}
				
			}

		}
	}
	return found;
}


/* Set the style now and add it to a cookie for later */
function addstyle(selector, rule, optidx){
	var name;
	var cookie;
	var expdate;
	var property;
	var valu;
	optidx= "["+optidx+"]";
	
	expdate=(24 * 60 * 60 * 1000 * 365);
	name='userpref';
	if(testVar(rule) && testVar(selector) ){
		valu=rule.split(":")[1];
		if(valu.indexOf("clear") >=0 ){
			property=rule.split(":")[0];
			cookie=biteCookie(name, selector, property, '|', optidx);
			if(testVar(cookie)){
				bakeCookie(name, cookie, expdate);
			}
			this.location.reload(false);	
		}else{
			setstyle(selector, rule); 
			addToCookieJar(name, selector, rule, '|', optidx);
		}
	}else{
		return false;
	}
}

/* removes one style from the cookie */
function biteCookie(name, selector, property, seperator, optidx){
	var sone;
	var stwo;
	var cookie;
	var cookies;
	var found;
	if(getCookie(name)){
		cookie=getCookie(name); 						/* get existing cookie */
		cookies=cookieCutter(cookie, seperator); 		/* get the cookies as an array */
		if(testVar(cookies)){
			for(var i=0; i < cookies.length; i++){
				cookiecrumbs=cookies[i].split('?');			/* split cookie into selector and rule */	
				if(testVar(cookiecrumbs[1])){
					chips=cookiecrumbs[1].split(":");  			/* split rule into property and value */
					if(chips[0]== property && cookiecrumbs[0] == selector){			
						found=i; 							/* Selector and property already exist */	
						cookies.splice( found, 1);
						cookie=cookies.join(seperator);	
						return cookie;						
					}
				}
			}
		}
		
		return cookie;
	}
	return false;
}

/* Set the style now and add it to a cookie for later of a full rule entered by user */
function anyRule(userRule){
	if(testVar(userRule)){
		userRule.slice(0,userRule.indexOf("}"));
		tokens=userRule.split("{");
		setstyle(tokens[0], tokens[1]); 
		addToCookieJar('userpref', tokens[0], tokens[1], '|', "[]"  );
	}
}

/* Dynamically sets the selected style */
function setstyle(selector, rule){
	var rulecount;
	var fullrule;
	var ssheet;
	ssheet=(document.styleSheets.length==0)? document.createStyleSheet(): document.styleSheets[0];
	if( testVar(selector)  && testVar(rule) && rule.indexOf(":")  ){		
		if(ssheet.insertRule){	/* DOM */
			rulecount=ssheet.cssRules.length;
			fullrule=selector +"{"+ rule +"}";	
			ssheet.insertRule(fullrule, rulecount++ );
		}else if(document.styleSheets[0].addRule){ /* IE */
			rulecount=ssheet.rules.length;
			if(selector.indexOf(",") >0){
				selectors=selector.split(",");
				for(var s=0; s< selectors.length; s++){
					ssheet.addRule(selectors[s], rule, rulecount++);
				}
			}else{
				ssheet.addRule(selector, rule, rulecount++);	
			}
		}
		return true;
	}else{
		return false;
	}
}
/* test to see if a varable has an assigned value */
function testVar(objToTest) {
	return (objToTest == null || objToTest == undefined || objToTest == false)? false : true;
}

/* Store Cookie */
function bakeCookie(name, data, usebydate){
	var today=new Date();
	today.setTime(today.getTime() +usebydate);  
	usebydate=today.toGMTString();	
	document.cookie = name + "=" + escape(data)+ "; expires=" + usebydate +  "; path=/";
    //alert("Cookie length: "+data.length);
}

/* get the cookie and add style */
function iceCookie(name, seperator){
	if(navigator.cookieEnabled && document.styleSheets && (document.styleSheets[0].addRule || document.styleSheets[0].insertRule)){
		var vanilla;
		var crumbs;
		var opti;
		vanilla=getCookie(name);
		if(testVar(vanilla)){
			crumbs=cookieCutter(vanilla, seperator);
			for(var x=0; x< crumbs.length; x++){
				opti=crumbs[x].split("[");
				chips=opti[0].split("?");
				setstyle(chips[0],chips[1]);			
			}
		}
	}else{
		return false;
	}
}

/* get the full Cookie from the cookie jar*/
function getCookie(name) {
	var start;
	start=0;
	thisCookie = document.cookie.split("; ")
	for (i = 0; i < thisCookie.length; i++) {
		if (name == thisCookie[i].split("=")[0]) {
			chocchip=unescape(thisCookie[i].split("=")[1]);		
			return chocchip;
		}
	}
	return false;
}

/* break up the cookies */
function cookieCutter(cookie, seperator){
	return (testVar(cookie) && cookie.length >1 && cookie.indexOf(seperator) >0)? cookie.split(seperator): false;
}

function addToCookieJar(name, selector, rule, seperator, optidx){
	var found;
	var cookie;
	var cookies;
	var mix;
	var expdate;
	expdate=(24 * 60 * 60 * 1000 * 365);
	if(testVar(name) && testVar(selector) && testVar(rule) && testVar(seperator)){
		if(!getCookie(name)){
			bakeCookie(name, selector +"?"+rule, expdate); 	/* new cookie */
		}else{			
			cookie=biteCookie(name, selector, rule.split(":")[0], seperator);
			if(testVar(cookie)){
				mix=cookie+seperator+selector+"?"+rule+optidx;			
			}
			bakeCookie(name, mix, expdate); 				/*rewrite cookie */
		}
	}else{
		return false;
	}
}

/*Remove Cookies and refresh to clear styles */
function eatCookie(name){
	var yesterday=0-(24 * 60 * 60 * 1000)	
	bakeCookie(name, "", yesterday); 					/*remove cookie */
	this.location.reload(false);								/* reload to clear styles */
}

/* on page load read and set the cookie styles */
window.onload=function(){
	iceCookie('userpref', '|');
	setFormSelected('userpref', 'userpref'); 
}