/**
 * jquery.template-tags.js
 * @author Zenobius Jiricek
 * @version 1.0
 *
 * stores html elements as template tags for re-use later in the document
 *
 *
 */

(function($) {
	PLUGINNAME = "jquery.styleSheetSwitcher";
	LOG_PREFIX = PLUGINNAME+" : "
	$.log(LOG_PREFIX,"loading")
	// Local vars for toggle
	var availableStylesheets = [];
	var activeStylesheetIndex = 0;


	//
	//Private Functions
	//

	// To initialise the stylesheet with it's
	var init = function(options) {
		$.log(LOG_PREFIX, "Initialising")
		if(!options.stylesheets){
			$('link[rel*=style][title]').each(function(index, item){
				$.log(LOG_PREFIX, "Found stylesheet", index, $(item).attr("href") )
				availableStylesheets.push(this.getAttribute('title'));
			});
		}
		if(!cookie){
			$.log(LOG_PREFIX, "Cookie not found")
			var cookie = readCookie('style');
		}
		enableSheet(cookie);

	};

	// cookie functions http://www.quirksmode.org/js/cookies.html
	function createCookie(name, value, days){
		$.log(LOG_PREFIX, "Creating cookie")
		if (days){
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}else{
			var expires = "";
		}
		$.log(LOG_PREFIX, "Cookie : ", value, expires)
		document.cookie = name+"="+value+expires+"; path=/";
	}

	function readCookie(name){
		$.log(LOG_PREFIX, "Reading cookie : ", name)
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++){
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}

	function eraseCookie(name){
		$.log(LOG_PREFIX, "Erasing cookie")
		createCookie(name,"",-1);
	}

	var toggle = function(){
		$.log(LOG_PREFIX, "Toggling stylesheet")
		activeStylesheetIndex ++;
		activeStylesheetIndex %= availableStylesheets.length;
		$.stylesheetSwitch(availableStylesheets[activeStylesheetIndex]);
	};

	// To switch to a specific named stylesheet
	var enableSheet = function(styleName) {
		$.log(LOG_PREFIX, "Attempting to activate stylesheet :", styleName)

		$('link[@rel*=style][title]').each( function(index, item){
			$(item).attr('disabled', true);
			$.log(index, $(item).attr('title') )
				if ($(item).attr('title') == styleName) {
					$.log(LOG_PREFIX, "stylesheet found :", index, styleName)
					$(item).attr('disabled', false);
					activeStylesheetIndex = index;
				}
			}
		);
		$.log(LOG_PREFIX, "Recording stylesheet in cookie :", styleName)
		createCookie('style', styleName, 365);
	};


/*
 *
 */
	$.fn.styleSheetSwitcher = function(options) {
		$.log(LOG_PREFIX, "Called")
		// PLUGIN OPTIONS
		var opts = $.extend({}, $.fn.styleSheetSwitcher.defaults, options);
		init(opts)

		return {
			init: init,
			toggle: toggle,
			enableSheet: enableSheet
		}
	};


	//
	// plugin defaults
	//
	$.fn.styleSheetSwitcher.defaults = {

	};

	//
	// end of closure
	//
	$.log(LOG_PREFIX, "loaded")

})(jQuery);


