/**
 * Styleswitch Stylesheet Switcher jQuery Plugin 2008.05.18 
 * A simple jQuery Plugin to switch the stylesheet.
 * 
 * This is based upon Kelvin Luck's ( http://www.kelvinluck.com/ )
 * "Styleswitch stylesheet switcher built on jQuery"
 * Under an Attribution, Share Alike License
 * Original by Kelvin Luck ( http://www.kelvinluck.com/ )
 * By Seamus P. H. Leahy ( http://moronicbajebus.com/ )
 *
 * 
 * This plugin gives you a simple way to turn on and off stylesheets. It will also store 
 * the current stylesheets state in a user cookie so they can be restored when they come 
 * to the page the next time. This is good if you want to switch the theme via stylesheet
 * or make the text bigger by turning on an additional stylesheet.
 *
 * To utilize the storing the user's settings in a cookie, you will need to also use the 
 * jQuery cookie plugin: http://plugins.jquery.com/project/cookie
 *
 * 
 * Interface:
 *
 * jQuery.styleswitch
 *  This is the namespace and object for Styleswitch.
 *
 * jQuery.styleswitch.disable(title, [cookie])
 *  Disable the stylesheets (via the link element) with the title attr matching the title param.
 *  @param title string - the title attr on the link elements you will be disabling
 *  @param cookie object optional - the cookie options to save it (see Cookie Options below)
 *  @return jQuery global object
 *
 * jQuery.styleswitch.enable(title, [cookie])
 *  Enable the stylesheets (via the link element) with the title attr matching the title param.
 *  @param title string - the title attr on the link elements you will be enabling
 *  @param cookie object optional - the cookie options to save it (see Cookie Options below)
 *  @return jQuery global object
 *
 * jQuery.styleswitch.toggle(title, [cookie])
 *  Toggles the stylesheets (via the link element) with the title attr matching the title param.
 *  If the stylesheets have different disabled states, then all of them will be set to match the
 *  toggle state of the first match.
 *  @param title string - the title attr on the link elements you will be toggling
 *  @param cookie object optional - the cookie options to save it (see Cookie Options below)
 *  @return jQuery global object
 *
 * jQuery.styleswitch.isDisabled(title)
 *  Checks if the stylesheet with the title attr matching the param title is disabled.
 *  If the stylesheets have different disabled states, then the disabled state of the first
 *  matched element is checked.
 *  @param title string - the title attr on the link elements you want to check
 *  @return boolean - true if is disabled, false if enabled
 *
 * jQuery.styleswitch.load([cookie])
 *  Loads the stylesheet disabled settings from the cookie (if set).
 *  If cookie is not passed in, then the default cookie will be used.
 *  Because of how cookies are handled with Javascript, only the cookie name is used for retrieving
 *  cookies instead of the cookie ID triple of name, domain, and path. 
 *  @param cookie object optional - the cookie options of the cookie to load.
 *
 * jQuery.styleswitch.reset([cookie])
 *  Resets the stylesheet disabled state to their states before this plugin changed the
 *  disabled state for a stylesheet.
 *  
 *  If you want to reset the states without clearing out the cookie, pass false for the cookie.
 *  @param cookie object optional - the cookie settings to save it (see Cookie Settings below)
 *
 * 
 * jQuery.styleswitch.removeCookie([cookie])
 *  This will remove the cookie used to save the users settings. This is for advance users.
 *  @param cookie object optional - removes the particular cookie
 *
 * 
 * setCookie
 *  This is for moderate to advance users. This sets the default cookie
 *  options to be used.
 * @param object cookieOptions - the options to change with the cookie 
 *
 * getCookie
 * This returns the default cookie options.
 * @return object cookieOptions
 *
 * The default default cookie options are the following:
 *    name: 'StyleSwitch',
 *    expires: 14, 
 *    path: '/', 
 *    domain:  window.location.hostname, 
 *    secure: window.location.protocol == 'https'
 *
 * 
 * Cookie Options
 * 1. If nothing is passed in, then the default cookie options from getCookie are used
 * 2. If false is passed for the cookie, then no cookie will be used
 * 3. If an object is passed with options, then those options will be 
 *    used and override the default options
 *
 * Settings:
 *   name string - the name of the cookie (this is not from jQuery.cookie plugin)
 *   expires number - the number of days until the cookie is expired
 *   path string - the path which the cookie will use for
 *   domain string - the domain the cookie will be valid for
 *   secure boolean - is this a secure cookie
 *
 *   For more information about the settings, visit http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/
 *
 *
 * Event
 * The Styleswitch plugin has a custom event that is triggered when the styleswitch plugin is updated.
 * Whenever the disabled state is updated (even to the same state), the event "styleswitch" is acted 
 * upon for the document. Three additional parameters are passed to the event function: 
 * title string, disabled boolean, and prevDisabled boolean.
 * 
 * The Event Function
 * function myStyleswitchEventFunc(event, title, disabled, prevDisabled){
 * 	alert("The stylesheet "+title+" disabled state has been updated from "+prevDisabled+" to "+disabled);
 * 	// ...
 * }
 *
 * How to Bind Event Function
 * jQuery(document).bind('styleswitch', myStyleswitchEventFunc);
 *
 **/



(function(){ // Keeping the namespace tidy
	
	jQuery.styleswitch = {
		disable: 		function(title, cookie){
								setStyleSheetState(title, true);
								setStyleSheetCookiesState(cookie, title, true);
								getStyleSheets(title).each(function(){
									this.disabled = true;
								});
								setCookie(cookie);
								return this;
							},
		enable:			function(title, cookie){
								
								setStyleSheetState(title, false);
								setStyleSheetCookiesState(cookie, title, false);
								getStyleSheets(title).each(function(){
									this.disabled = false;
								});
								setCookie(cookie);
								return this;
							},
		toggle:			function(title, cookie){
								var s = getStyleSheets(title);
								
								// this is to sync all of them to be in the same state
								if(!s.get(0)){
									return this;
								}
								if(s.get(0).disabled === true) {
									jQuery.styleswitch.enable(title, cookie);
								} else {
									jQuery.styleswitch.disable(title, cookie);
								}
								return this;
							},
		load:				function(cookie){
								cookie = cookieSettings(cookie);
								
								var states = unserializeCookie(cookie.name);
								
								applyStylesheetStates(states, cookie);
								return this;
							},
		reset:			function(cookie){
								applyStylesheetStates(originalState, cookie);
							},
		removeCookie:	function(cookie){
								removeTheCookie(cookie);
							},
	/**
	 * isDisabled
	 *
	 * @param title string - the title attr for the link elements
	 * @return true if it is disabled, false if it is enabled
	 */
		isDisabled:		function(title){
								if(stylesheetState[title] !== undefined){
									return stylesheetState[title];
								} else if(!getStyleSheets(title).get(0)){
									return undefined;
								} else {
									stylesheetState[title] = getStyleSheets(title).get(0).disabled === true;
									return stylesheetState[title];
								}
							},
		setCookie:		function(options){
								defaultCookie = cookieSettings(options);
							},
		getCookie:		function(){
								return defaultCookie;
							}
	};
	
	
	// Consts
	var EVENT_NAME = 'styleswitch';
	
	
	// Internal
	
	
	var defaultCookie = {name: 'StyleSwitch', expires: 14, path: '/', domain:  window.location.hostname , secure: window.location.protocol == 'https'}
	
	
	// 
	// Returns the jQuery set for the stylesheets with the given title
	// @title string = the title attr on the link elements
	var getStyleSheets = function(title){
		return jQuery('link[@rel*=style][@title='+title+']');
	};
	
	
	var setStyleSheetState = function(title, disabled){
		if(originalState[title] === undefined){
			originalState[title] = jQuery.styleswitch.isDisabled(title);
		}
		
		var prev = stylesheetState[title];
		stylesheetState[title] = disabled;
		// trigger event
		jQuery(document).trigger(EVENT_NAME, [title, disabled, prev]);
	};
	
	// Cookie stuff
	
	// The cached states for the stylesheets
	var stylesheetState = {};
	
	// The states for the cookies
	var cookieStylesheetState = {};
	
	// The original values
	var originalState = {};
	
	
	// Converts stylesheetState into a string form to save in the cookie
	// @returns string - the serialized version
	var serializeCookie = function(states){
		var a = [];
		// create an array of the title=bool
		for(var b in states){
			if(states[b]){
				a.push(b+'=1');
			} else {
				a.push(b+'=0');
			}
		}
		
		// insert & between pairs and return
		return a.join('&');
	};
	
	
	// Converts the serialized cookie into the stylesheetState variable
	var unserializeCookie = function(cookieName){
		if(!jQuery.cookie){ // without jQuery.cookie we cannot load cookie
			return this;
		}
		var s = {};
		var v = jQuery.cookie(cookieName);
		if(v){
			// split in title=bool
			var a = v.split('&');
			for(var i=0; i<a.length; i++){
				
				var b = a[i].split('=');
				
				s[b[0]] = b[1] == '1';
			}
		}
		
		return s;
	};
	
	// This sets the users cookie for the stylesheet information.
	var setCookie = function(cookie){
		if(cookie === false || !jQuery.cookie){
			return;
		}
		
		cookie = cookieSettings(cookie);
		
		// Update the cookie state to match the DOM state
		jQuery.cookie(cookie.name, serializeCookie(getStyleSheetCookieStates(cookie)), cookie);
	};
	
	
	var removeTheCookie = function(cookie){
		if(cookie === false || !jQuery.cookie){
			return;
		}
		cookie = cookieSettings(cookie);
		jQuery.cookie(cookie.name, null, cookie);
	};
	
	
	var applyStylesheetStates = function(s, cookie){
		
		for(var c in s){
			if(s[c]){
				jQuery.styleswitch.disable(c, cookie);
			} else {
				
				jQuery.styleswitch.enable(c, cookie);
			}
		}
	};
	
	
	// Set the stylesheet state for a particular cookie
	var setStyleSheetCookiesState = function(cookie, title, disabled){
		cookie = cookieSettings(cookie);
		
		if(!cookieStylesheetState[cookie.name]){
			cookieStylesheetState[cookie.name] = {};
		}
		
		cookieStylesheetState[cookie.name][title] = disabled;
		
	};
	
	
	// Get all the titles and disabled states for a cookie triple (name, domain, path)
	var getStyleSheetCookieStates = function(cookie){
		cookie = cookieSettings(cookie);
		
		if(!cookieStylesheetState[cookie.name]){
			return {};
		}
		return cookieStylesheetState[cookie.name];
	}
	
	
	var cookieSettings = function(cookie){
		var v = {}; 
		jQuery.extend(v, defaultCookie, cookie);
		return v;
	};
	
})();
