/**
 * 
 * 
 * ---------------------------------------------------------------------------
 * 
 * Copyright (C) 2009 Omnium Research Group
 * 
 * ---------------------------------------------------------------------------
 * 
 * LICENSE:
 * 
 * This file is part of Omnium(R) Software.
 * 
 * Omnium(R) Software 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.
 * 
 * Omnium(R) Software 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.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Omnium(R) Software; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 * 
 * ---------------------------------------------------------------------------
 * 
 * @author    Tim Neill <tim@omnium.net.au>
 * @copyright 2009 Omnium Research Group
 * @license   http://www.gnu.org/licenses/gpl.txt GNU GPL v2
 * @link      http://open.omnium.net.au Omnium Open
 **/


/**
 * omTheme doesn't rely on themeList per se, but the theme selector
 * won't operate properly without it
 * 
 *		Structure:
 * 		themeList => $H({ index: 'name', ... })
 *		PROTIP: http://www.prototypejs.org/api/utility/dollar-h
**/

var omTheme = Class.create();
omTheme.prototype = {
	initialize: function(cookieName, themeList)
	{
		// themeList should be set to something if there is a need for loading multiple themes, otherwise many methods will fail
		if (themeList) {
			this.availableThemes = $H(themeList);
		} else {
			this.availableThemes = $H();
		}
		
		// A custom cookieName should most definitely be set. This is here to protect against exceptions
		if (!cookieName) {
			cookieName = 'omTheme';
		}
		
		this.activeTheme 	= '';
		this.cookieName		= cookieName;
	},
	
	// Switches the site theme using alternate stylesheets and saves a cookie
	change: function(name)
	{
		// Wrapped in a try/catch to bypass Prototype errors in the event that there are
		// no themes available. [Used to prevent IE from terminating ALL execution on exception]
		try {
			if (this.activeTheme != name) {
				$$('link[rel="alternate stylesheet"]').each( function(linkObj) {
					linkObj.disabled = true;
				});
				
				var activeSheet = $$('link[title="' + name + '"]');
				
				if (activeSheet[0] !== undefined) {
					activeSheet[0].disabled = false;
				}
			
				this.activeTheme = name;
				this.save(name);
			}
		} catch(e) {}
	},
	
	// Clears the current themeList and re-adds the themes
	refresh: function(themeList)
	{
		if (themeList) {
			this.availableThemes.each( function(pair) {
				this.availableThemes.unset(pair.key);
			});
			
			this.availableThemes = $H(themeList);
			
		}
	},
	
	// Searches availableThemes for 'name', and returns the index of the first instance if true, -1 if false
	// PROTIP: Ensure that all names are unique. This isn't exclusively checked, but it is good practice
	lookup: function(name)
	{
		// Default the name parameter to the currently active theme
		if (name === undefined || name == '') {
			name = this.activeTheme;
		}
		
		// Initialise our return value to protect against null returns
		var matchIndex = -1;
		
		this.availableThemes.each( function(pair) {
			// If we have a match, set it to the corresponding hash value and break from our loop function
			if (pair.value == name) {
				matchIndex = pair.key;
				return true;
			}
		});
		
		// Return the index if successful, or -1 on fail
		return matchIndex;
	},
	
	
	// Utility function to check if a theme is active in the class. Requires availableThemes to be set
	verify: function(name)
	{
		return (this.lookup(name) == -1 ? false : true);
	},
	
	// Saves a cookie containing the name of the site theme if available
	save: function(name)
	{
		if(this.verify(name)) {
			Cookie.set(this.cookieName, name, 7);
		}
	},
	
	// Loads and activates a site theme from the cookie if available
	load: function()
	{
		if (name = Cookie.get(this.cookieName)) {
			this.change(name);
		}
	},
	
	// Performs a quick check to see if a theme exists in the cookie and returns it if true and it is available
	peek: function()
	{
		var _theme = Cookie.get(this.cookieName);
		return (this.verify(_theme) ? _theme : null);
	}
}


/**
 *   Cookie
 *   @author Carlos Reche
 **/
var Cookie = {
	
	// Sets a cookie with a value and expiration time
	set: function(name, value, daysToExpire) {
		
		var expire = '';
		if (daysToExpire != undefined) {
			var d = new Date();
			d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
			expire = '; expires=' + d.toGMTString();
		}
		return (document.cookie = escape(name) + '=' + escape(value || '') + expire + '; path=/');
	},
	
	// Gets a cookie based on its name
	get: function(name) {
		var cookie = document.cookie.match('\s*' + name + '=([^;]*)');
		return (cookie ? unescape(cookie[1]) : null);
	},
	
	// Erases a cookie
	erase: function(name) {
		var cookie = Cookie.get(name) || true;
		Cookie.set(name, '', -1);
		return cookie;
	},
	
	// Find out if the browser has cookies enable
	accept: function() {
		if (typeof navigator.cookieEnabled == 'boolean') {
			return navigator.cookieEnabled;
		}
		Cookie.set('_test', '1');
		return (Cookie.erase('_test') === '1');
	}
};
