/**
	Dependencias:
		- mootools-1.2.1-core.js
		- mootools-1.2-more.js
*/
var InputHelp = {
	actions: {actIn: 0, actOut:1, actClear:2},
	init: function() {
		var inputs = $$('.inputHelp');
		inputs.each(function(input, index){
			InputHelp.initInput(input);
		});
	},

	/**
	* Inicializa el valor, estilo y comportamiento para el elemento.
	*/
	initInput: function(input) {
		InputHelp.setValue(input);
		input.addEvent('change', function() {
			InputHelp.testDefaultValue(this, InputHelp.actions.actOut);
		});
		input.addEvent('focus', function() {
			InputHelp.testDefaultValue(this, InputHelp.actions.actIn);
		});
		input.addEvent('blur', function() {
			InputHelp.testDefaultValue(this, InputHelp.actions.actOut);
		});
	},
    testDefaultValue: function (input, action) {
    		if(action == this.actions.actOut) {
    			if(
    				input.get('value').trim() == ''
    				|| input.get('value').toLowerCase() == input.get('alt').toLowerCase()
    			) {
    				input.setStyle('color', '#999999');
    				input.set('value', input.get('alt'));
    			} else {
    				input.setStyle('color', '#000000');
    			}
    		} else if(
    			action == this.actions.actIn
    			|| action == this.actions.actClear
    		) {
    			if(
    				input.get('value').trim() == ''
    				|| input.get('value').toLowerCase() == input.get('alt').toLowerCase()
    			) {
    				input.setStyle('color', '#000000');
    				input.set('value', '');
    			}
    		}
    	},
    setValue: function(input) {
		if(
			input.get('value').trim() == ''
			|| input.get('value').toLowerCase() == input.get('alt').toLowerCase()
		) {
			input.set('value', input.get('alt'));
			input.setStyle('color', '#999999');
		} else {
			input.setStyle('color', '#000000');
		}
	},
    setValues: function() {
    	var inputs = $$('.inputHelp');
		inputs.each(function(input, index){
			InputHelp.setValue(input);
		});
    },
	clearValues: function() {
		var inputs = $$('.inputHelp');
		inputs.each(function(input, index){
			InputHelp.testDefaultValue(input, InputHelp.actions.actClear);
		});
	}
};

var HelpHelp = {
	init: function() {
		var helpLinks = $$('.helpPopup');
		helpLinks.each(function(link, index) {

			link.addEvent('click', function(event){
				event.stop();
				event = new Event(event);
				var initFnt = function () {
					$$('input.close').each( function(elem){
						elem.addEvent('click', function(event) {
							$('helpDiv').setStyle('visibility', 'hidden');
							$('helpDiv').set('text', '');
							FormHelp.hideShadow();
						});
					});
				};

				FormHelp.showPopUp(
					link.get('href'),
					'helpDiv',
					'helpDiv',
					true,
					null,
					null,
					initFnt
				);
			});
		});
	}
};

var FormHelp = {
	shadowId: 'shadow',
	windowStyles: {
		iframe: 0,
		popup: 1
	},
	init: function() {
		setTimeout(this.initFocus, 100);
	},
	initFocus: function() {
		var isMakeFocus = false
		$$('.initFocus').each(function(element, index) {
			if(isMakeFocus)return;
			try {
				element.focus();
				element.fireEvent('focus');
				isMakeFocus = true;
			} catch(e) {}
		});
	},
	/**
	* Posiciona un elemento y le asigna un tamaño en función de la ventana actual y del objeto dimensions recibido en
	* el siguiente formato:
	*	{
	*		center: true/false, //hace que se ignoren los valores left, right, top y bottom
	*		left:   valor,
	*		right:  valor,
	*		top:    valor,
	*		bottom: valor,
	*		height: valor,
	*		width:  valor
	*	}
	* Cualquier valor no indicado en dimensions es calculado por el método.
	* El orden de prioridad en caso de colisión dentro de los valores de dimensions es
	*	center
	*	width
	*	height
	*	left
	*	top
	*	right
	*	bottom
	* Ej: Para centrar un elemento basta con indicar el valor center a true.
	*/
	posicionar: function(element, dimensions) {
        if(!$chk(dimensions.width))dimensions.width = element.getSize().x;
        if(!$chk(dimensions.height))dimensions.height = element.getSize().y;
        element.setStyles({
			height: dimensions.height,
			width:  dimensions.width
		});
        if($chk(dimensions.center)) {
        	if(window.getSize().y >= element.getSize().y) {
				dimensions.top = ( (window.getSize().y - element.getSize().y) / 2) + window.getScroll().y;
			} else dimensions.top = window.getScroll().y;

			dimensions.bottom = window.getScrollSize().y - dimensions.top - element.getSize().y;

			if(window.getSize().x >= element.getSize().x) {
				dimensions.left = ( (window.getSize().x - element.getSize().x) / 2) + window.getScroll().x;
			} else dimensions.left = window.getScroll().x;

			dimensions.right = window.getScrollSize().x - dimensions.left - element.getSize().x;
		}

        if(!$chk(dimensions.top))dimensions.top = 0;
        if(!$chk(dimensions.bottom))dimensions.bottom = window.getScrollSize().y - dimensions.top - element.getSize().y;
        if(!$chk(dimensions.left))dimensions.left = 0;
        if(!$chk(dimensions.right))dimensions.right = window.getScrollSize().x - dimensions.left - element.getSize().x;

		element.setStyles({
			left:   dimensions.left,
			right:  dimensions.right,
			top:    dimensions.top,
			bottom: dimensions.bottom,
			height: dimensions.height,
			width:  dimensions.width
		});

	},
    showShadow: function() {
    	var divShadow = $(this.shadowId);
		if(!$chk(divShadow)) {
			divShadow = new Element('div', {'id': this.shadowId});
			document.body.adopt(divShadow);
		} else {
			divShadow.setStyle('visibility','visible');
		}
		divShadow.addClass('shadow');

		divShadow.setStyles({
			left: 0,
			top: 0,
			height: window.getScrollSize().y,
			width: window.getScrollSize().x
		});
    },
	hideShadow: function() {
    	var divShadow = $(this.shadowId);
		if($chk(divShadow)) {
			divShadow.dispose();
		}
    },
	showPopUp: function(path, containerId, style, modal, cssAux, jsAux, fntInit) {

		//Comprobamos si está inicializado de forma previa el script solicitado
		if(
			$chk(jsAux) &&
			!$chk(eval('window.' + jsAux.id))
		) {
			var JS = new Asset.javascript(jsAux.path, {
				id: jsAux.id,
				onload: function() {
					eval('window.' + jsAux.id + ' = JS');
					//Una vez tenemos cargado el js necesario, pasamos a la carga del resto de la página.
					FormHelp.showPopUp(path, containerId, style, modal, cssAux, null, fntInit);
				}
			});
			eval('window.' + jsAux.id + ' = JS');
			return;
		}

		if($chk(cssAux)) {
			new Asset.css(cssAux, {});
		}
        if($chk(modal)) {
        	this.showShadow();
        }
		var mensaje = 'Espere un momento, por favor.';
		var divLoanding = this.showLoanding(mensaje);
		//Realizamos la llamada para cargar el contenido de la página de compra.
		var req = new Request.HTML({
			url:path,
			evalScripts: true,
			onSuccess: function(html) {
				setTimeout(function () {
					var left = window.getScroll().x + (window.getWidth() - 600) / 2;
					var top = window.getScroll().y + (window.getHeight() - 400) / 2;
					if (left < 0) left = 10;
					if (top < 0) top = 10;
					FormHelp.hideLoanding();
					var div = $(containerId);
					if(!$chk(div)) {
						div = new Element('div', {'id': containerId}
						);
						document.body.adopt(div);
					}
					div.setStyles({
						position: 'absolute',
						opacity: 0,
						width: 600,
						height: 400,
						left: left,
						top: top
					});
					if($chk(style)) {
						div.addClass(style);
					}
					div.setStyle('visibility','visible');
					div.set('text', '');
					div.adopt(html);

					div.set('morph', {
						duration: 'normal',
						transition: 'linear'
					});
					div.get('morph').start({
						opacity: 1
					});
					if($chk(fntInit)) {
						if(typeof fntInit == 'function') {
							fntInit();
						} else if(typeof fntInit == 'string') {
							eval(fntInit + '()');
						}
					}
				}, 500);
			},
			//Our request will most likely succeed, but just in case, we'll add an
			//onFailure method which will let the user know what happened.
			onFailure: function() {
				$(containerId).set('text', 'The request failed.');
			}
		});
		req.send();
	},

	closePopUpExt: function(popUpExt) {
		if($chk(popUpExt.controls)) {
			popUpExt.controls.dispose();
		}
		popUpExt.dispose();
		this.hideShadow();
	},
	showPopUpExt: function(windowStyle, path, id, containerId, modal, onload, onclosing, ondispose, showControls) {

		if($chk(modal)) {
			this.showShadow();
		}

		var mensaje = 'Espere un momento, por favor.';
		var divLoanding = this.showLoanding(mensaje);
		var container = $chk(containerId)? $(containerId): document.body;
		if(!$chk(container)) container = document.body;

		var width = container.getScrollSize().x -20;
		var height = container.getScrollSize().y -20;
		var top = container.getCoordinates().top + 10;
		var left = container.getCoordinates().left + 10;

		var makeControls = function () {
			var topControls = top + 5;
			var leftControls = left + width - 100;
			var imgClose = new Element('img', {
				id: id + 'Control',
				src: '/restyling/img/obj/closeTxt.gif',
				alt: 'Cerrar',
				'class': 'zUpper',
				width: 75,
				height: 20,
				styles: {
					position: 'absolute',
					display: 'inline',
					position: 'absolute',
					left: leftControls,
					top: topControls,
					cursor: 'pointer'
				}
			});
			imgClose.addEvent('click', function(event){
				var continueClosing = true;
				if($chk(onclosing)) continueClosing = onclosing();
				if(!continueClosing) return;
				iframe.dispose();
				this.hideShadow();
				event.target.dispose();
				ondispose();
			}.bind(this));
			iframe.cotrols = imgClose;
			document.body.adopt(imgClose);
        }.bind(this);
        var iframe = new Element('iframe', {
			id: id,
			name: id,
			src: $chk(path)? path:'',
			opacity: 0,
			'class': 'zUpper',
			styles:	{
				'visibility': 'hidden',
				'background': '#fff',
				'position': 'absolute',
				'top': top+'px',
				'left': left+'px',
				'width': width+'px',
				'height': height+'px',
				'border-left': '2px solid',
				'border-bottom': '2px solid'
			}
		});
		(function() {
			iframe.inject(container);
			FormHelp.hideLoanding();
			iframe.setStyle('visibility','visible');
			iframe.set('morph', {
				duration: 'long',
				transition: 'linear'
			});
			iframe.get('morph').start({
				opacity: 1
			}).chain(function(){makeControls();});
			if($chk(onload)) onload();
		}).bind(this).delay(500);

		/*
		if (windowStyle == this.windowStyles.popup) {
			var opciones = 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left;
			iframe =
			window.open(($chk(path)? path:''), id, opciones);
		}
		*/
		return iframe;
	},

	showLoanding: function (message) {
		message += '<div class="waitDiv"></div>';
		var divLoanding = $('loanding');
		if(!$chk(divLoanding)) {
			divLoanding = new Element('div', {
				'id': 'loanding',
				'html': message,
				'styles': {
					'z-index': '999'
				}
			}).injectInside($$('body')[0]);
			divLoanding.addClass('loanding');
		} else {
			divLoanding.set('html', message);
			divLoanding.setStyle('visibility', 'visible');
		}
		FormHelp.posicionar(divLoanding, {
			center: true,
			width: 270,
			height: 170
		});
		return divLoanding;
	},

	hideLoanding: function(message, time) {
		var divLoanding = $('loanding');
		if(!$chk(divLoanding)) return false;

		if(!$chk(time)) {
			divLoanding.dispose();
			/*
			divLoanding.setStyle('visibility', 'hidden');
			divLoanding = null;
			*/
			return true;
		} else {
			divLoanding.set('html', message);
			setTimeout(function(){
				divLoanding.dispose();
				/*
				divLoanding.setStyle('visibility', 'hidden');
				divLoanding = null;
				*/
				return true;
			}, time);
		}
	},
	getPosition: function(element) {
		if (!Browser.Engine.trident) return element.getPosition();
		var b = element.getBoundingClientRect(), html = element.getDocument().documentElement;
		return {
			x: b.left + html.scrollLeft - html.clientLeft,
			y: b.top + html.scrollTop - html.clientTop
		};
	}
};


/**
* Comprueba el tamaño máximo en caracteres del valor de un campo y notifica el número de caracteres restantes.
* param field: String. Id del campo a controlor
* param maxSize: int. Número máximo de caracteres
* param notifArea: String. Id del area en la que se escribe el html de notificación.
*/
var TexAreaMaxLength = new Class ({
    initialize: function(field, maxSize, notifArea){
		field = field;
		field.maxSize = maxSize;
		field.notifArea = notifArea;

		field.comprobarTamanio = function(field, maxSize, notifArea) {
			var actSize = field.get('value').length;
			if(actSize > maxSize) {
				field.set('value', field.get('prevValue').substring(0, maxSize));
				actSize = maxSize;
			}
			if($chk(notifArea)) {
				if(actSize > (maxSize * 0.8)) notifArea.setStyle('color', 'red');
				else if(actSize > (maxSize * 0.6)) notifArea.setStyle('color', 'orange');
				else notifArea.setStyle('color', '#939598');
				notifArea.set('html', ('<span class="flr">' + (maxSize-actSize) + '</span>'));
			}
		};

		field.addEvent('keyup', function() {
			this.comprobarTamanio(this, this.maxSize, this.notifArea);
		});

		field.addEvent('keydown', function() {
			this.set('prevValue', this.get('value'));
		});
		field.fireEvent('keydown');
		field.fireEvent('keyup');
    }
});

/**
* Indica al fieldset cuando uno de sus componentes tiene el foco para establecer un estilo concreto.
* param fieldsetName: String. Id del fieldset al que queremos aplicar el comportamiento.
*					  En caso de nulo, se aplica a todos los fieldset contenidos en el formulario formName
* param formName: String. Id del formulario a cuyos fieldset queremos aplicar el comportamiento.
*					  En caso de nulo, se aplica a todos los fieldset de la página
* param styleClass: String. Nombre del estilo a aplicar al fieldset cuando uno de sus componentes toma el foco.
*/
var FielsetUtility = new Class ({
    initialize: function(fieldsetName, formName, styleClass){
    	var filedsets = null;
    	if(fieldsetName) {
    		fieldsets = $$('#' + fieldsetName);
    	} else if(formName) {
    		fieldsets = $$('#' + formName + ' fieldset');
    	} else {
    		fieldsets = $$('fieldset');
    	}
    	if(!styleClass) styleClass = 'selected';
    	fieldsets.each(function(fieldset) {
    		if(!fieldset.hasClass('noeffect')) {
				var fields = fieldset.getElements('input').combine(fieldset.getElements('textarea')).combine(fieldset.getElements('select'));
				var onFocus = function () {
					this.addClass(styleClass);
				}.bind(fieldset);
				var onBlur = function () {
					this.removeClass(styleClass);
				}.bind(fieldset);
				fields.each(function(field){
					field.addEvent('focus', onFocus);
					field.addEvent('blur', onBlur);
				});
			}
    	});
    }
});

window.addEvent('domready', function() {
	FormHelp.init();
	InputHelp.init();
	HelpHelp.init();
});
