/**
 * Switch theme
 *
 * @author Alec Hill
 */
(function(){

	if(window['com'] == undefined){ 
		window.com = { alechill: {} }; 
	}else{
		if(com['alechill'] == undefined){
			com.alechill = {};
		}
	}
	
	if(window['theme'] == undefined){ 
		window.theme = {}; 
	}
	
	
	com.alechill.Theme = new Class({
		
		name: null,
		
		images: [],
		
		preloaded: [],
		
		initialize: function(){
			console.log('Instantiating ' + this.name);
			this.preloaded = [];
			this.preloadImages();
		},
		
		/**
		 * Preloads images for css so switch happens fast
		 */
		preloadImages: function(){
			this.images.each(function(src, i){
				var source = 'themes/' + this.name + '/' + src;
				console.log('Preloading: "' + source + '"');
				this.preloaded[i] = new Image(source);
			});
		},
		
		/**
		 * Perform anything needed to destroy theme
		 */
		destroy: function(){
			console.log('Destroying ' + this.name);
		}
		
	});
	
	
	/**
	 * Static var for storing the current theme object
	 */
	com.alechill.Theme.current_theme = null;
	
	/**
	 * The name of the current theme
	 */
	com.alechill.Theme.current_theme_name = null;
	
	/**
	 * Static reference to a function that will set up the new theme when dom is ready
	 * Done this way so can be cancelled 
	 */
	com.alechill.Theme.new_theme_setup = null;
	
	/**
	 * static method to parse page for external links and set them up for you
	 */
	com.alechill.Theme.switchTo = function( theme_name ){
		
		$$('link.theme').each(function(link){
			if(!link.get('title')) return;
			link.set('disabled', link.get('title') != theme_name);
		});
		
		com.alechill.Theme.current_theme_name = theme_name;
		
		com.alechill.Theme.new_theme_setup = function(){
			// destroy the current theme js object
			if(com.alechill.Theme.current_theme){
				com.alechill.Theme.current_theme.destroy();
				delete com.alechill.Theme.current_theme;
				com.alechill.Theme.current_theme = null;
			};
			// attempt instantiation of the theme js object 
			if(theme[theme_name]){
				com.alechill.Theme.current_theme = new theme[theme_name].Theme();
			}else{
				// no theme js
				delete com.alechill.Theme.current_theme;
				com.alechill.Theme.current_theme = null;
			}
		}
		
		window.addEvent('domready', function(){
			console.log('domready')
			// call inside this anonymous function so it is not directly referenced as an event handler
			com.alechill.Theme.new_theme_setup();
		});
	}

})();
