/*
 * xenonLayout (http://www.marciobarrios.com/new-xenon-layout)
 * (c) 2005 Marcio Barrios <marciobarrios@gmail.com>
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the Creative Commons License (Attribution-ShareAlike 2.5) 
 * as published by the Creative Commons Organization; either version 2.5
 * of the License, or (at your option) any later version.
 *
 * For the full copyright and license information, please view the LICENSE
 * text in the url http://creativecommons.org/licenses/by-sa/2.5/es/deed.en
 * or http://creativecommons.org/licenses/by-sa/2.5/es/ (spanish)
 */

var xenonLayout = {
	changeStructure: false,
	minWidth: null,
	maxWidth: null,
	thinWidth: null,
	wideWidth: null,
	titleNormalCss: null,
	titleThinCss: null,
	titleWideCss: null,
   /*
	*	función que inicializa el script
	*	parámetros:
	*			thinWidth: (opcional) límite en píxeles para cambiar de documento CSS para resoluciones pequeñas, solo utilizado si se define titleThinCss
	*			wideWidth: (opcional) límite en píxeles para cambiar de documento CSS para resoluciones grandes, solo utilizado si se define titleWideCss
	*			titleNormalCss: (requerido) atributo 'title' de la etiqueta link que enlaza el CSS por defecto
	*			titleThinCss: (opcional) atributo 'title' de la etiqueta link que enlaza el CSS para resoluciones pequeñas, necesario para cambiar de Css
	*			titleWideCss: (opcional) atributo 'title' de la etiqueta link que enlaza el CSS para resoluciones grandes, necesario para cambiar de Css
	*/
	init: function(thinWidth, wideWidth, titleNormalCss, titleThinCss, titleWideCss){
		this.minWidth = this.ruleValue('min-width');
		this.maxWidth = this.ruleValue('max-width');
		/*params*/
		this.thinWidth = thinWidth;
		this.wideWidth = wideWidth;
		this.titleNormalCss = titleNormalCss;
		this.titleThinCss = titleThinCss;
		this.titleWideCss = titleWideCss;
		/*end params*/
		
		this.check();
	},
	//funcion que comprueba la resolución de pantalla y cambia de CSS, además emula el min-width y max-width para IE
	check: function(){
		var rule,newWidth,newRule;
		
		var browserWidth = this.getBrowserWidth();
		
		if (navigator.userAgent.toLowerCase().indexOf("msie") + 1){
			if (this.minWidth != -1 && browserWidth <= this.minWidth) {
					newWidth = this.minWidth + "px";
					this.changeStructure = true;
				}
				else if (browserWidth > this.minWidth && browserWidth < this.maxWidth) {
					newWidth = "auto";
					this.changeStructure = true;
				}
				else if (this.maxWidth != -1 &&  browserWidth >= this.maxWidth) {
						newWidth = this.maxWidth + "px";
						this.changeStructure = true;
				}
		}
		
		if (this.validCss(this.titleThinCss) && browserWidth <= this.thinWidth) {
			this.changeLayout(this.titleThinCss); this.changeStructure = false;
		}
		else if (this.validCss(this.titleWideCss) && browserWidth >= this.wideWidth) {
			this.changeLayout(this.titleWideCss); this.changeStructure = false;
		}
		else this.changeLayout(this.titleNormalCss);
		
		if (this.changeStructure) {
			rule = this.ruleText(0);
			newRule = rule.replace(/(width|WIDTH) *: *[0-9]* *[a-z]+;/,"width:"+newWidth+";");
			if (document.styleSheets[0].cssRules) document.styleSheets[0].cssRules[0].style.cssText = newRule;
			else document.styleSheets[0].rules[0].style.cssText = newRule;
		}
		return true;
	},
	//funcion para comprobar que existe un CSS con un título concreto
	validCss: function(titleCss){
		var currTag;
		if (document.getElementsByTagName){
			for (var i = 0; (currTag = document.getElementsByTagName("link")[i]); i++){
				if (currTag.getAttribute("rel").indexOf("style") + 1 && currTag.getAttribute("title")){
					if (currTag.getAttribute("title") == titleCss) return true;
				}
			}
		}
		return false;
	},
	// getBrowserWidth is taken from The Man in Blue Resolution Dependent Layout Script
	// http://www.themaninblue.com/experiment/ResolutionLayout/
	getBrowserWidth: function(){
		if (window.innerWidth) return window.innerWidth;
		else if (document.documentElement && document.documentElement.clientWidth != 0) return document.documentElement.clientWidth;	
		else if (document.body) return document.body.clientWidth;
		return 0;
	},
	// changeLayout is adapted from The Man in Blue Resolution Dependent Layout Script
	// http://www.themaninblue.com/experiment/ResolutionLayout/
	changeLayout: function(styleTitle){
		var currTag;
		if (document.getElementsByTagName){
			for (var i = 0; (currTag = document.getElementsByTagName("link")[i]); i++){
				if (currTag.getAttribute("rel").indexOf("style") + 1 && currTag.getAttribute("title")){
					currTag.disabled = true;
					if(currTag.getAttribute("title") == styleTitle) currTag.disabled = false;
				}
			}
		}
		return true;
	},
	// funcion que extrae el valor de la primera regla de la primera CSS dependiendo del atributo
	// ruleValue by Marcio Barrios
	ruleValue: function(attr){
		var text, cssText;
		if (document.styleSheets) {
			text = this.ruleText(0);
			if (text != -1){
				switch (attr) {
					case 'min-width': cssText = /min-width *: *[0-9]{3,4}px/.exec(text); break;
					case 'max-width': cssText = /max-width *: *[0-9]{3,4}px/.exec(text); break;
				}
				if (cssText != null){
					var valueTmp = cssText[0].split(':');
					var valueInt = valueTmp[1].replace(/([0-9]+)[a-zA-Z]+/gi,"$1");
					return parseInt(valueInt);
				}
				else return -1;
			}
			else return -1;
		}
		else return -1;
	},
	// funcion que devuelve el texto de una regla determinada de la primera css
	// ruleText by Marcio Barrios
	ruleText: function(num){
		if (document.styleSheets) {
			if (document.styleSheets[0].cssRules) return document.styleSheets[0].cssRules[num].style.cssText;
			else if (document.styleSheets[0].rules) return document.styleSheets[0].rules[num].style.cssText;
			else return -1;
		}
		else return -1;
	}
};

/*
 * Utilización:
 * xenonLayout.init(thinWidth,wideWidth,titleNormalCss,titlethinCss,titleWideCss); 
 * los parámetros están explicados en la declaración de la función xenonLayout.init
 */

// addEvent() by John Resig
function addEvent( obj, type, fn ){ 
	if (obj.addEventListener){ 
	  obj.addEventListener( type, fn, false );
	}
	else if (obj.attachEvent){ 
	  obj["e"+type+fn] = fn; 
	  obj[type+fn] = function(){ obj["e"+type+fn]( window.event ); };
	  obj.attachEvent( "on"+type, obj[type+fn] ); 
	} 
};

// añadimos al manejador de eventos la funcion cuando se cargue la pagina y cuando se redimensione
addEvent(window, 'load', function(){
	xenonLayout.init(700,0,'normal','thin','');
});

addEvent(window, 'resize', function(){
	xenonLayout.init(700,0,'normal','thin','');
});