/*
	Contains:
		* Animated style switch
		* Window resize style switcher
		* Text resize detector
*/














/* ANIMATED STYLE SWITCHER */	
	/*
		FIXME: IE giving me error: "object doesn't support property or method"
		Must install MS Script debugger to debug.
	*/
	var themeMenuContainer = themeMenuContainer||'#themes';
	var innerLayer = innerLayer||'#banner';
	var templatePath = templatePath||'';
	var themesLabel = 'Theme me: ';
	var cookieRef = 'theme';
	var buttonPrefix = '-button';
	
	
	var themeConfig = {
		tornbase: {
			ttitle: 'Torn Base',
			bheight: '135px',
			bgimg: ''
		},
		spring: {
			ttitle: 'Spring',
			bheight: '150px',
			bgimg: 'assets/template/spring/bg.png'
		},
		ice: {
			ttitle: 'Ice',
			bheight: '175px',
			bgimg: 'assets/template/ice/bg.png'
		}
		/*,
		night: {
			ttitle: 'Night',
			bheight: '200px',
			bgimg: 'assets/template/night/bg.jpg'
		}*/
	};
	
	var themeConfig = themeConfig || new Object();
	var menuConfigXML = null;
	
	$(document).ready(function() {
		//alert('test');
		// create theme menu
		if (themesLabel!=='') {
			$(themeMenuContainer).append($('<p class="label">'+themesLabel+'</p>'));
		}
		$(themeMenuContainer).append($('<ul></ul>'));
		// get config XML
		/*HTTPResponse = $.ajax({
			url: templatePath+'config.xml',
			ifModified: true,
			processData: false,
			success: addXML
		});*/
		if (typeof themeConfig === 'undefined') { return; }
		for (key in themeConfig) { if ( typeof themeConfig[key] !== 'undefined' ) {
			addThemeMenuItem(key, themeConfig[key]);
		}}
		// Set current theme
		// is theme set in cookie, if not set default
			var linkId = readCookie(cookieRef);
			if (linkId) {
				$('#'+linkId+buttonPrefix).each(setTheme);
			} else {
				//$('#'+$('entry:lt(1)',menuConfigXML).attr('id')+buttonPrefix).each(setTheme);
				for (id in themeConfig) { if (typeof themeConfig[id] !== 'undefined') {
						
					//alert('#'+id+buttonPrefix);
					$('#'+id+buttonPrefix).each(setTheme);
					break; // first entry only
				}}
			}
		return;
	});
	function addXML (configXML) {
		$('entry', configXML).each(addXMLEntry);
	};
	function addXMLEntry () {
		//alert($(this).attr('id'));
		temp = {
			ttitle: $(this).find('title').text(),
			bheight: $(this).find('height').text(),
			bgimg: $(this).find('bgimg').text()
		};
		eval ("themeConfig."+$(this).attr('id')+"=temp;");
	};
	function addThemeMenuItem (themeConfigEntryId, themeConfigEntry) {
		
		$(themeMenuContainer+' > ul').append($('<li><a href="#" id="'+themeConfigEntryId+buttonPrefix+'">'+themeConfigEntry.ttitle+'</a></li>'));
		$(themeMenuContainer+' > ul #'+themeConfigEntryId+buttonPrefix).click(setTheme);
		
		// preload bg image
			$("<img>").attr("src", themeConfigEntry.bgimg);
	};
	function switchStylesheet(linkId)
	{
		$('link[rel*=style]').filter('link[title]').each(function(i) 
		{
			this.disabled = true;
			if (this.getAttribute('id') === linkId) {
				this.disabled = false;
			}
		});
		
		createCookie(cookieRef, linkId, 365);
	};
	function setTheme () {
		if (typeof themeConfig == 'undefined') { return; }
		
		// get id by removing buttonPrefix
			id = $(this).attr('id').replace(buttonPrefix,'');
		
		if (typeof themeConfig[id] === 'undefined') { return; }
		theme = themeConfig[id];
		
		
		$(themeMenuContainer+' a').css('text-decoration','none');
		$(this).css('text-decoration','underline');
		
		switchStylesheet(id);
		
		
		
		$(innerLayer).animate({
			height:theme.bheight
		}, 'slow');
		
		return false;
	};
	// cookie functions http://www.quirksmode.org/js/cookies.html
	function createCookie(name,value,days)
	{
		var expires = "";
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			expires = "; expires="+date.toGMTString();
		}
		document.cookie = name+"="+value+expires+"; path=/";
	};
	function readCookie(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)
	{
		createCookie(name,"",-1);
	};
	// /cookie functions














































/* TEXT RESIZE DETECTOR */
	/** 
	 *  @fileoverview TextResizeDetector
	 * 
	 *  Detects changes to font sizes when user changes browser settings
	 *  <br>Fires a custom event with the following data:<br><br>
	 * 	iBase  : base font size  	
	 *	iDelta : difference in pixels from previous setting<br>
	 *  	iSize  : size in pixel of text<br>
	 *  
	 *  * @author Lawrence Carvalho carvalho@uk.yahoo-inc.com
	 * @version 1.0
	 */
	
	/**
	 * @constructor
	 */
	TextResizeDetector = function() { 
		var el  = null;
		var iIntervalDelay  = 200;
		var iInterval = null;
		var iCurrSize = -1;
		var iCurrWidth = -1;
		var iBase = -1;
		var aListeners = [];
		var createControlElement = function() {
			el = document.createElement('span');
			el.id='textResizeControl';
			el.innerHTML='&nbsp;';
			el.style.position="absolute";
			el.style.left="-9999px";
			var elC = document.getElementById(TextResizeDetector.TARGET_ELEMENT_ID);
			// insert before firstChild
			if (elC) {
				elC.insertBefore(el,elC.firstChild);
			}
			iBase = iCurrSize = TextResizeDetector.getSize();
		};
	
		function _stopDetector() {
			window.clearInterval(iInterval);
			iInterval=null;
		};
		function _startDetector() {
			if (!iInterval) {
				iInterval = window.setInterval('TextResizeDetector.detect()',iIntervalDelay);
			}
		};
		
		 function _detect() {
			var iNewSize = TextResizeDetector.getSize();
			
			if (typeof document.body.clientWidth != 'undefined') {
				var iNewWidth = document.body.clientWidth;
			} else {
				var iNewWidth = window.innerWidth;
			}
			
			if(iNewSize!== iCurrSize || iNewWidth !== iCurrWidth) {
				for (var i=0;i <aListeners.length;i++) {
					aListnr = aListeners[i];
					var oArgs = {  iBase: iBase,iDelta:((iCurrSize!=-1) ? iNewSize - iCurrSize + 'px' : "0px"),iSize:iCurrSize = iNewSize};
					if (!aListnr.obj) {
						aListnr.fn('textSizeChanged',[oArgs]);
					}
					else  {
						aListnr.fn.apply(aListnr.obj,['textSizeChanged',[oArgs]]);
					}
				}
	
			}
			iCurrWidth = iNewWidth;
			return iCurrSize;
		};
		var onAvailable = function() {
			
			if (!TextResizeDetector.onAvailableCount_i ) {
				TextResizeDetector.onAvailableCount_i =0;
			}
	
			if (document.getElementById(TextResizeDetector.TARGET_ELEMENT_ID)) {
				TextResizeDetector.init();
				if (TextResizeDetector.USER_INIT_FUNC){
					TextResizeDetector.USER_INIT_FUNC();
				}
				TextResizeDetector.onAvailableCount_i = null;
			}
			else {
				if (TextResizeDetector.onAvailableCount_i<600) {
					TextResizeDetector.onAvailableCount_i++;
					setTimeout(onAvailable,10); // 200
				}
			}
		};
		setTimeout(onAvailable, 0); // 100
	
		return {
				/*
				 * Initializes the detector
				 * 
				 * @param {String} sId The id of the element in which to create the control element
				 */
				init: function() {
					
					createControlElement();		
					_startDetector();
				},
				/**
				 * Adds listeners to the ontextsizechange event. 
				 * Returns the base font size
				 * 
				 */
				addEventListener:function(fn,obj,bScope) {
					aListeners[aListeners.length] = {
						fn: fn,
						obj: obj
					}
					return iBase;
				},
				/**
				 * performs the detection and fires textSizeChanged event
				 * @return the current font size
				 * @type {integer}
				 */
				detect:function() {
					return _detect();
				},
				/**
				 * Returns the height of the control element
				 * 
				 * @return the current height of control element
				 * @type {integer}
				 */
				getSize:function() {
						var iSize;
						return el.offsetHeight;
					
					
				},
				/**
				 * Stops the detector
				 */
				stopDetector:function() {
					return _stopDetector();
				},
				/*
				 * Starts the detector
				 */
				startDetector:function() {
					return _startDetector();
				}
		}
	 }();
	
	TextResizeDetector.TARGET_ELEMENT_ID = 'doc';
	TextResizeDetector.USER_INIT_FUNC = null;











































/* WINDOW RESIZE STYLE SWITCHER */
	function init()  {
		var iBase = TextResizeDetector.addEventListener(onFontResize,null);
	};
	//id of element to check for and insert control
	TextResizeDetector.TARGET_ELEMENT_ID = 'footer';
	//function to call once TextResizeDetector has init'd
	TextResizeDetector.USER_INIT_FUNC = init;
	
	rConfig = {
		narrowMulti : 45, // 38 ems - 835 default
		mediumMulti : 62, // 56 ems - 1130 default
		wideMulti   : 78, // 76 ems - 1420 default
		widerMulti  : 90, // 96 ems - 1720 default
		deaultClass : 'layout-narrow',
		narrowClass : 'layout-narrow',
		mediumClass : 'layout-medium',
		wideClass   : 'layout-wide',
		widerClass  : 'layout-wider',
		widestClass : 'layout-widest'
	};
	
	function onFontResize(e,args) {
		adjustLayout(args[0].iSize);
	};
	function adjustLayout (emPixels) {
		if (typeof emPixels == 'undefined') return;
		
		bodyEl = document.getElementsByTagName('body')[0];
		
		narrowLimit = emPixels * rConfig.narrowMulti;
		mediumLimit = emPixels * rConfig.mediumMulti;
		wideLimit   = emPixels * rConfig.wideMulti;
		widerLimit  = emPixels * rConfig.widerMulti;
		//widestLimit = emPixels * rConfig.widestMulti; // 106 ems
		
		if (typeof currentClass != 'undefined') {
			previousClass = currentClass;
		} else {
			previousClass = rConfig.defaultClass;
		}
		currentClass = rConfig.defaultClass;
		if (typeof document.body.clientWidth != 'undefined') {
			pageWidth = document.body.clientWidth;
		} else {
			pageWidth = window.innerWidth;
		}
		if (pageWidth <= narrowLimit) {
			currentClass = rConfig.narrowClass;
		} else if (pageWidth <= mediumLimit) {
			currentClass = rConfig.mediumClass;
		} else if (pageWidth <= wideLimit) {
			currentClass = rConfig.wideClass;
		} else if (pageWidth <= widerLimit) {
			currentClass = rConfig.widerClass;
		} else {
			currentClass = rConfig.widestClass;
		}
		
		$(bodyEl).removeClass(previousClass);
		$(bodyEl).addClass(currentClass);
		//mainEL.style.display = 'block';
	};

