
var Validator = {
	
	/*
		Cada vez que creamos una regla de validacion con la clase ValidationRule indicamos el formulario al que pertenece el campo.
		Este id de formulario lo usamos para agrupar los campos en formularios y poder llamar al metodo validateAll desde cualquiera
		de las reglas de validacion creadas.
	*/
	_forms: new Array(),
	
	/*
		Privado
		
		Realiza una validacion sobre un campo solicitado.
		Recibe tres parametros (elemento,tipo de validacion,[bool]obligatoriedad)
	*/
	_doValidation: function(e,type,obligatory)
	{
		
		//Validacion de longitud del campo
		if(typeof type == 'number')
			return (e.value.length >= type);
			
		//Si el tipo es una exprecion regular comprobamos el campo con esta expresion
		if(type instanceof RegExp)
			return type.test(e.value);
		
		// la cadena comienza con uno de estos caracteres comparamos el valor del campo
		// con eval.
		switch(type[0]){
			case '<':
			case '>':
			case '!':
			case '=':
				return (eval(e.value +' '+ type));
				break;
		}
		
		var expre = new RegExp();
		
		if(!obligatory)
			type = '@'+ type;
		
		//Campos obligatorios
		switch(type)
		{
			case 'text':	//TEXTO
				expre = /^[a-zA-Z\.\,\s\Ã¡Ã©Ã­Ã³Ãº\Ã±]+$/;
				break;
			case 'phone':	//TELEFONO
				expre = /^([0-9\s\+\-])+$/;
				break;
			case 'email':	//E-MAIL
				expre = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
				break;
			case 'number':	//NUMERICO
				expre = /^([0-9])+(\.?[0-9])+$/;
				break;
			case 'dni':		//DNI
				expre = /^([0-9]{8})(\-*)([a-zA-Z]{1})+$/;
				break;
			case 'content':	//CONTENIDO
				expre = /^[\w\s\\\/\Âº\Âª]+$/;
				break;
			
			//Campos no obligatorios
			case '@text':	//TEXTO
				expre = /^[a-zA-Z\.\,\s\Ã¡Ã©Ã­Ã³Ãº\Ã±]*$/;
				break;
			case '@phone':	//TELEFONO
				expre = /^([0-9\s\+\-])*$/;
				break;
			case '@email':	//E-MAIL
				expre = /^(\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4}))*$/;
				break;
			case '@number':	//NUMERICO
				expre = /^([0-9])+(\.?[0-9])*$/;
				break;
			case '@dni':	//DNI
				expre = /^(([0-9]{8})(\-*)([a-zA-Z]{1}))*$/;
				break;
			case '@content':		//CONTENIDO
				expre = /^[\w\s\\\/\Âº\Âª]*$/;
				break;
		}
		
		// comprobamos la validez del campo solicitado
		return expre.test(e.value);
	},
	
	/*
		AÃ±ade una regla de validacion
	*/
	_addRule: function(rule)
	{
		if(!(this._forms[rule._form] instanceof Array))
			this._forms[rule._form] = new Array();
		
		this._forms[rule._form].push(rule);
	},
	
	/*
		Valida una regla
	*/
	validate: function(rule)
	{
		if(this._doValidation(rule._field,rule._type,rule._obligatory))
		{
			if(rule._invalid_css_class)
				rule._field.removeClassName(rule._invalid_css_class);
			
			if(rule._showOnInvalid)
				$(rule._showOnInvalid).hide();
			
			if(rule._funcOnValid)
				rule._funcOnValid();
			
			return true;
		}
		else
		{
			if(rule._invalid_css_class)
				rule._field.addClassName(rule._invalid_css_class);
			
			if(rule._showOnInvalid)
				$(rule._showOnInvalid).show();
			
			if(rule._funcOnInvalid)
				rule._funcOnInvalid();
			
			return false;
		}
	},
	
	/*
		Valida todas las reglas de un formulario
	*/
	validateAll: function(rule){
		if(!rule._form)
			return this.validate(rule);
		
		var formArray = this._forms[rule._form];
		var valid = true;
		
		//Buscamos una regla para este campo
		for(var f=(formArray.length - 1);f>=0;f--){
			if(!this.validate(formArray[f]))
				valid = false;
		}
		
		return valid;
	}
};

//	Modelo de regla de validacion
//
//	var rule = {
//		field: 'id',
//		type: 'tipo',
//	
//		//Opcinales
//		obligatory: bool //false por defecto
//		classOnInvalid: 'class_css',
//		showOnInvalid: 'id/element'
//	};

function ValidationRule(p)
{
	if(!(p instanceof Object))
		return;
	
	//Comprobamos las variables
	if(!p.field)
		return;
		
	if(!p.type)
		return;
	
	//Campo que se validarÃ¡
	this._field = $(p.field);
	
	//Tipo de validacion para el campo
	this._type = p.type;
	
	//Agrupa las reglas en formualrios
	if(p.form)
		this._form = p.form;
	
	//Almacena la clase CSS que se plicara al campo si este es invalido
	if(p.classOnInvalid)
		this._invalid_css_class = p.classOnInvalid;
	
	//Establece si el campo es obligatorio o no. False por defecto.
	this._obligatory = (p.obligatory === true);
	
	//Establece si se mostrarÃ¡ un elemento cuando el campo sea invÃ¡lido
	if(p.showOnInvalid)
		this._showOnInvalid = $(p.showOnInvalid);
	
	//Establece si se ejecutarÃ¡ una funcion al aceptar
	if(p.funcOnValid)
		this._funcOnValid = p.funcOnValid;
	
	//Establece si se ejecutarÃ¡ una funcion al cancelar
	if(p.funcOnInvalid)
		this._funcOnInvalid = p.funcOnInvalid;
	
	Validator._addRule(this);
	/*
		metodos
	*/
	//Realiza una validacion 
	this.validate = function()
	{
		return Validator.validate(this);
	};
	
	//Valida todas las raglas que esten contenidas en el mismo formulario
	this.validateAll = function()
	{
		return Validator.validateAll(this);
	};
};


function getResizedSrc(path)
{
	if(typeof(path) != 'string')
		path = $(path).src;
	
	if(path.indexOf('i=') > -1)
	{
		path = path.substring((path.indexOf('i=') + 2));
		
		var ampIndx = path.indexOf('&');
		if(ampIndx > 0)
			path = path.substring(0,ampIndx);
	}
	
	if(path.indexOf('/thumbs/') > -1)
		path = path.replace('/thumbs/','/');

	return path;
}

function thumbnailAddToVisor(t)
{
	Event.observe(t,'click',function(){
		visor.View(getVisorPath(getResizedSrc(this)));
	});
}

function getVisorPath(p)
{
	return 'resizetomax.php?i='+ p +'&anchomax='+ WDimForVisor.maxWidth +'&altomax='+ WDimForVisor.maxHeight;
}


/*
	jsViewer
	
	Crea un visor de imagenes para las paginas.
	
	Metodos:
	
	View(Ruta de la imagen);
		- Recibe como parametro la ruta de la imagen que se va a mostrar
*/
function jsViewer()
{
	this.IE = (window.attachEvent && navigator.userAgent.indexOf('Opera') === -1);
	this._div = getElement('div');
	this._imageDiv = getElement('div');
	this._cargandoDiv = getElement('div');
	var cargandoImg = getElement('img');
	var cerrarDiv = getElement('div');
	var arribaIzquierdaDiv = getElement('div');
	var arribaDiv = getElement('div');
	var arribaDerechaDiv = getElement('div');
	var derechaDiv = getElement('div');
	var abajoDerechaDiv = getElement('div');
	var abajoDiv = getElement('div');
	var abajoIzquierdaDiv = getElement('div');
	var izquierdaDiv = getElement('div');
	
	this._div.setStyle({
		position: 'fixed',
		top: '0px',
		right: '0px',
		bottom: '0px',
		left: '0px',
		background: 'url(imagenes/componentes/visor-fondo-transparente.png)',
		display: 'none',
		zIndex: 1000
	});
	
	this._imageDiv.setStyle({
		position: 'absolute',
		width: '400px',
		height: '300px',
		background: '#FFF'
	});
	
	this._cargandoDiv.setStyle({
		position: 'relative',
		margin: 'auto',
		top: '45%',
		width: '31px',
		height: '31px'
	});
	
	cargandoImg.src = 'imagenes/componentes/ajax-loader.gif';
	
	cerrarDiv.setStyle({
		position: 'absolute',
		top: '-29px',
		right: '0px',
		width: '62px',
		height: '15px',
		cursor: 'pointer',
		background: 'url(imagenes/componentes/visor-cerrar.png) no-repeat'
	});
	
	arribaIzquierdaDiv.setStyle({
		position: 'absolute',
		top: '-14px',
		left: '-14px',
		width: '14px',
		height: '14px',
		background: 'url(imagenes/componentes/visor-esquina-arriba-izquierda.png) no-repeat'
	});
	
	arribaDiv.setStyle({
		position: 'absolute',
		top: '-14px',
		left: '0px',
		right: '0px',
		height: '14px',
		background: '#FFF'
	});
	
	arribaDerechaDiv.setStyle({
		position: 'absolute',
		top: '-14px',
		right: '-14px',
		width: '14px',
		height: '14px',
		background: 'url(imagenes/componentes/visor-esquina-arriba-derecha.png) no-repeat'
	});
	
	derechaDiv.setStyle({
		position: 'absolute',
		top: '0px',
		bottom: '0px',
		right: '-14px',
		width: '14px',
		background: '#FFF'
	});
	
	abajoDerechaDiv.setStyle({
		position: 'absolute',
		bottom: '-14px',
		right: '-14px',
		width: '14px',
		height: '14px',
		background: 'url(imagenes/componentes/visor-esquina-abajo-derecha.png) no-repeat'
	});
	
	abajoDiv.setStyle({
		position: 'absolute',
		bottom: '-14px',
		left: '0px',
		right: '0px',
		height: '14px',
		background: '#FFF'
	});
	
	abajoIzquierdaDiv.setStyle({
		position: 'absolute',
		bottom: '-14px',
		left: '-14px',
		width: '14px',
		height: '14px',
		background: 'url(imagenes/componentes/visor-esquina-abajo-izquierda.png) no-repeat'
	});
	
	izquierdaDiv.setStyle({
		position: 'absolute',
		top: '0px',
		bottom: '0px',
		left: '-14px',
		width: '14px',
		background: '#FFF'
	});
	
	/*
		Metodos
	*/
	this.goToScreenCenter = function()
	{
		this._imageDiv.setStyle({
			width: '400px',
			height: '300px'
		});
		
		this._imageDiv.setStyle({
			top: ((screen.availHeight / 2) - 220) +'px',
			left: ((screen.availWidth / 2) - 200) +'px'
		});
	}
	
	this.setSize = function(width,height)
	{	
		var pX = width / 4;
		var pY = height / 3;
		
		new Effect.Parallel([
			new Effect.Scale(this._imageDiv,pX,{scaleY:false,scaleContent:false,scaleFromCenter:true}),
			new Effect.Scale(this._imageDiv,pY,{scaleX:false,scaleContent:false,scaleFromCenter:true})
		],{
			duration: 0.5
		});
	}
	
	this.View = function(path)
	{
		this.goToScreenCenter();
		this.createViewerImage();
		this._cargandoDiv.show();
		this.Show();
		path += (path.indexOf('?') > 0 ? '&v=' : '?v=') + Math.random();
		this._viewerImg.src = path;
	}
	
	this.Show = function()
	{
		this._div.appear({
			duration: 0.5
		});
	}
	
	this.Hide = function()
	{
		this._div.fade({
			duration: 0.5
		});
	}
	
	this.createViewerImage = function()
	{
		if(this._viewerImg)
			this._viewerImg.remove();
		
		this._viewerImg = getElement('img');
		this._viewerImg.style.visibility = 'hidden';
		this._viewerImgID = this._viewerImg.identify();
		Event.observe(this._viewerImg,'load',function(){
			viewer.showImage();
		});
		this._imageDiv.appendChild(this._viewerImg);
	}
	
	this.showImage = function()
	{
		this._cargandoDiv.hide();
		this.setSize(this._viewerImg.getWidth(),this._viewerImg.getHeight());
		this._viewerImg.hide();
		this._viewerImg.style.visibility = 'visible';
		setTimeout("$('"+ this._viewerImgID +"').appear({duration:0.4})",500);
	}
	
	/*
		Registro de eventos
	*/
	var viewer = this;
	Event.observe(cerrarDiv,'click',function(){
		viewer.Hide();
	});
	
	/*
		Agregamos los elementos a DOM
	*/
	this._cargandoDiv.appendChild(cargandoImg);
	this._imageDiv.appendChild(this._cargandoDiv);
	this._imageDiv.appendChild(cerrarDiv);
	this._imageDiv.appendChild(arribaIzquierdaDiv);
	this._imageDiv.appendChild(arribaDiv);
	this._imageDiv.appendChild(arribaDerechaDiv);
	this._imageDiv.appendChild(derechaDiv);
	this._imageDiv.appendChild(abajoDerechaDiv);
	this._imageDiv.appendChild(abajoDiv);
	this._imageDiv.appendChild(abajoIzquierdaDiv);
	this._imageDiv.appendChild(izquierdaDiv);
	
	this._div.appendChild(this._imageDiv);
	document.body.appendChild(this._div);
}

/********************************************************************
|
|	Componentes
|
********************************************************************/

//dimenciones disponibles
WDimForVisor = {
	maxWidth: (screen.availWidth - 100),
	maxHeight: (screen.availHeight - 250)
};

//Dias de la semana
var semana = new Array();
semana.push('domingo');
semana.push('lunes');
semana.push('martes');
semana.push('miercoles');
semana.push('jueves');
semana.push('viernes');
semana.push('sÃ¡bado');

//Meses
var meses = new Array();
meses.push('enero');
meses.push('febrero');
meses.push('marzo');
meses.push('abril');
meses.push('mayo');
meses.push('junio');
meses.push('julio');
meses.push('agosto');
meses.push('septiembre');
meses.push('octubre');
meses.push('noviembre');
meses.push('diciembre');

function isObject(v){
	return (v instanceof Object);
}

function thumbnail(src,size)
{
	var img = getElement('img');
	img.src = 'thumb.php?i='+ src +'&s='+ (size || 50);
	return img;
}

function imageGetResized_URL(src,width,height)
{
	return 'resizetomax.php?i='+ src +'&anchomax='+ width +'&altomax='+ height;
}

function imageGetResized(src,width,height)
{
	var img = getElement('img');
	img.src = imageGetResized_URL(src,width,height);
	return img;
}

function coverDiv()
{
	var div = getElement('div');
	
	div.setStyle({
		position: 'absolute',
		background: '#000',
		top: '0px',
		right: '0px',
		bottom: '0px',
		left: '0px'
	});
	
	div.setOpacity(0.6);
	
	return div;
}

//Quita de un input la clase error
function removeErrorClass(){
	this.removeClassName('error');
};

function getCargandoSpan()
{
	var span = getElement('span');
	var image =  getImage('imagenes/web/ajax-loader.gif');
	var loadingText = getText(' Cargando...');
	
	span.appendChild(image);
	span.appendChild(loadingText);
	
	return span;
}

var Interfaces = {
	
	/*
		
	*/
	appendToDOM: function(e)
	{
		e = $(e);
		if(this._div)
		{
			e.appendChild(this._div);
			return this;
		}
		
		if(this._root)
		{
			e.appendChild(this._root);
			return this;
		}
	},
	
	del: function()
	{
		if(this._div)
			this._div.appendChild(coverDiv());
		
		if(this._root)
			this._root.appendChild(coverDiv());
		
		var pBody = 'id='+ this._id +'&tipo='+ this._tipo;
		
		if(this._tipo == 'img')
			pBody += '&img_path='+ this._imgSource;
		
		var comp = this;
		new Ajax.Request('admin/delete.php',{
			method: 'post',
			postBody: pBody,
			onComplete: function(response){ comp._onDel(); }
		});
	},
	
	fetch: function(entry,callback)
	{
		new Ajax.Request('admin/puente.php',{
			method: 'post',
			postBody: 'tipo='+ entry.tipo +'&id='+ entry.id,
			onComplete: callback
		});
	},
	
	/*
		Interpreta una capa a un componente de tipo ImageControl
	*/
	getImageControlDOM: function(div)
	{
		this._div =  $(div);
		this._status = 'loading';
		this._loadingImg = this._div.firstDescendant();
		this._img = this._loadingImg.next();
		this._img._control = this;
		this._imgSource = this._img.src;
		this._allowVisor = this._img.hasClassName('AddToVisor');
		var size = this._div.getDimensions();
		this._width = size.width;
		this._height = size.height;
		
		//Interfaces
		this.appendToDOM = Interfaces.appendToDOM;
	}
};

var DataBank = {
	_data: new Array(),
	
	add: function(data)
	{
		this._data.push(data);
		return (this._data.length - 1);
	},
	
	update: function(index,data)
	{
		this._data[index] = data;
		return this._data[index];
	},
	
	del: function(index)
	{
		this._data[index] = null;
	},
	
	get: function(index)
	{
		return this._data[index];
	}
};

/*
	Comprueba respuestas estandar Ajax desde el servidor
*/
function ajaxCallBack(func)
{
	return function(response){
		if(response.getHeader('Content-type') != 'application/json')
			return false;
		
		if(typeof response.responseJSON != 'object'){
			alert('Ha ocurrido un error:\nEl servidor a devuelto un valor vacio.');
			return false;
		}
		
		if(response.responseJSON.action == 'error'){
			alert('Ha ocurrido un error:\n'+ response.responseJSON.message);
			return false;
		};
		
		if(typeof func == 'function')
			return func(response.responseJSON);
	}
};

/*
	Comprueba que un php_response tenga definida la propiedad status y que esta coincida con el valor pasaso
*/
function php_responseStatus(php_response,valor){
	return (typeof php_response.status != 'undefined' && php_response.status == valor);
};

//Retorna una fecha pasandole un timestamp php (*1000)
function fecha(timestamp){
	var f = new Date();
	f.setTime(timestamp);
	return semana[f.getDay()] +' '+ f.getDate() +' de '+ meses[f.getMonth()] +' de '+ f.getFullYear();
};

//Retorna una hora pasandole un timestamp phpp (*1000)
function hora(timestamp){
	var f = new Date();
	f.setTime(timestamp);
	return f.getHours() +':'+ f.getMinutes();
};

//Se le pasa dia,mes y aÃ±o y retorna el timestamp para esta fecha
function timestamp(dia,mes,year){
	var fecha_obj = new Date(year,mes,dia);
	return (fecha_obj.getTime() / 1000);
};

function ScreenOff()
{
	this._root = getElement('div');
	this._root.addClassName('comp-ScreenOff-rootDiv');
	
	//Interfaces
	this.appendToDOM = Interfaces.appendToDOM;
}

function ImageControl(p)
{
	if(!p instanceof Object)
		return;
	
	if(!p.src)
		return;
	
	//Propiedades
	this._status = 'loading';
	this._tipo = 'img';
	this._id = p.id;
	this._div = getElement('div');
	this._loadingImg = getImage('imagenes/web/ajax-loader.gif');
	this._img = getElement('img');
	this._img._control = this;
	this._imgSource = p.src;
	this._allowVisor = !(p.allowVisor === false);
	this._width = p.width || 130;
	this._height = p.height || 130;
	
	if(p.deletable)
	{
		this._delDiv = getElement('div');
		this._delImage = getImage('imagenes/web/cross.png');
		this._delSpan = getElement('span');
		this._delText = getText(' Eliminar');
		
		this._delImage.alt = '[x]';
		this._delImage.setStyle({ verticalAlign: 'middle' });
		this._delDiv.setStyle({ display: 'none' });
		this._delDiv.addClassName('delComponent');
		
		//Funcion que se ejecutarÃ¡ al eliminar
		this._onDel = function()
		{
			this._div.remove();
		};
		
		//Interfaces
		this.del = Interfaces.del;
		
		var imgComp = this;
		//Eventos
		this._div.observe('mouseover',function(){
			imgComp._delDiv.show();
		});
		this._div.observe('mouseout',function(){
			imgComp._delDiv.hide();
		});
		
		//Boton eliminar
		this._delDiv.observe('click',function(){
			var prmt = new Prompt({
				title: 'Â¿Seguro que desea eliminar esta imÃ¡gen?',
				onAccept: function(){ imgComp.del(); },
				onCancel: function(){}
			});
			
			var image_copy = new ImageControl({
				src: imgComp._imgSource,
				showOnVisor: false
			});
			
			prmt.appendContent(image_copy._div);
			//var clearDiv = getElement('div');
			//clearDiv = getElement('div');
			
			prmt.appendToDOM('components-div');
		});
		
		this._delSpan.appendChild(this._delText);
		this._delDiv.appendChild(this._delImage);
		this._delDiv.appendChild(this._delSpan);
		this._div.appendChild(this._delDiv);
	}
	
	//Configuracion y estilos
	this._img.setStyle({
		display: 'none'
	});
	
	this._loadingImg.setStyle({
		marginTop: '25%'
	});
	
	this._div.addClassName('thumb-div');
	
	var styles = new Object();
	if(p.width)
		styles.width = p.width +'px';
	if(p.height)
		styles.height = p.height +'px';
	
	this._div.setStyle(styles);
	
	//DOM
	this._div.appendChild(this._loadingImg);
	this._div.appendChild(this._img);
	
	//Eventos
	this._img.observe('load',function(){ this._control._setLoadedStatus(); });
	if(p.showOnVisor !== false)
		this._img.observe('click',function(){ this._control._showOnVisor(); });
	
	//Metodos Privados
	this._setLoadedStatus = function(){
		this._loadingImg.hide();
		this._img.show();
		this._status = 'ready';
	}
	
	this._showOnVisor = function()
	{
		if(this._allowVisor)
			visor.View(getVisorPath(getResizedSrc(this._imgSource)));
	};
	
	//Metodos
	this.loadImage = function()
	{
		this._img.src = imageGetResized_URL(this._imgSource,(this._width - 4),(this._height - 4));
	};
	
	this.status = function()
	{
		return this._status;
	};
	
	this.id = function()
	{
		return this._id;
	};
	
	//Interfaces
	this.appendToDOM = Interfaces.appendToDOM;
	
	//Llamada automatica a metodos
	if(p.loadImage !== false)
		this.loadImage();
}

function FormItem(p)
{
	if(typeof p != 'object')
		return;
	
	var edit_type = (p.textarea ? 'textarea' : 'input');
	this._root = getElement('p');
	this._text = getText(p.text);
	this._spanText = getElement('span');
	this._input = getElement(edit_type);
	
	this._spanText.appendChild(this._text);
	this._root.appendChild(this._spanText);
	this._root.appendChild(getElement('br'));
	this._root.appendChild(this._input);
	
	//Configuracion
	if(edit_type == 'input')
		this._input.type = p.type || 'text';
	
	//Metodos
	this.value = function(txt){
		if(typeof(txt) != 'undefined')
			this._input.value = txt;
		
		return this._input.value;
	};
	
	this.input = function(){ return this._input; };
	
	//Interfaces
	this.appendToDOM = Interfaces.appendToDOM;
	
	if(p.value)
		this.value(p.value);
}

function DinamicValueChange(p){
	if(typeof p == 'undefined')
		p = new Object();
	
	//Propiedades
	this.changed = false;
	
	//Elementos
	this._div = getElement('div');
	this._input = getElement('input');
	
	//Configuracion de elementos
	this._input.type = 'text';
	this._input.value = p.value || '';
	this._input.addClassName('small');
	
	//Metodos
	this.value = function(val){
		if(typeof val != 'undefined')
			this._input.value = val;
		return this._input.value;
	};
	this.focus = function(){
		this._input.focus();
	};
	this.observe = function(evType,func){
		this._input.observe(evType,func);
	};
	this.setStyle = function(style){
		this._div.setStyle(style);
	};
	
	//DOM
	this._div.appendChild(this._input);
	
	//Llamadas a metodos
	if(typeof p.value != 'undefined')
		this.value(p.value);
	
	//Interfaces
	this.appendToDOM = Interfaces.appendToDOM;
};

function Prompt(p)
{
	//Elementos necesarios
	this._root = getElement('div');
	this._contentDiv = getElement('div');
	this._titleDiv = getElement('div');
	this._textDiv = getElement('div');
	this._buttonsDiv = getElement('div');
	this._closeImage = getImage(siteRoot +'imagenes/componentes/x.png');
	var closeDiv = getElement('div');
	this._acceptButton = getElement('input');
	this._cancelButton = getElement('input');
	
	//Acciones
	this._onAccept = p.onAccept;
	this._onCancel = p.onCancel;
	
	//Estilos
	this._acceptButton.type = 'button';
	this._cancelButton.type = 'button';
	this._acceptButton.value = 'Aceptar';
	this._cancelButton.value = 'Cancelar';
	
	
	this._root.addClassName('comp-promp-rootDiv');
	this._root.setStyle({
		top: ((WDimForVisor.maxHeight / 2) - 135) +'px',
		left: ((WDimForVisor.maxWidth / 2) - 240) +'px'
	});
	
	this._contentDiv.setStyle({
		paddingTop: '12px',
		marginLeft: '16px',
		marginRight: '16px'
	});
	
	closeDiv.setStyle({
		float: 'right',
		marginTop: '4px',
		marginRight: '13px',
		cursor: 'pointer'
	});
	
	this._titleDiv.addClassName('comp-titulo');
	this._titleDiv.setStyle({
		marginBottom: '12px',
		cursor: 'move'
	});
	
	this._textDiv.setStyle({
		height: '180px'
	});
	
	this._buttonsDiv.setStyle({
		position: 'absolute',
		bottom: '20px',
		left: '20px',
		right: '20px',
		textAlign: 'right'
	});
	
	new Draggable(this._root,{
		handle: this._titleDiv,
		starteffect: false,
		endeffect: false
	});
	
	//Eventos
	var comp = this;
	this._closeImage.observe('click',function(){
		if(comp._onCancel)
		{
			if(comp._onCancel() === false)
				return false;
		}
		
		comp.Close();
	});
	
	//Accion para el boton aceptar
	this._acceptButton.observe('click',function(){
		if(comp._onAccept)
		{
			if(comp._onAccept() === false)
				return false;
		}
		
		comp.Close();
	});
	
	//Accion para el boton cancelar
	this._cancelButton.observe('click',function(){
		if(comp._onCancel)
			comp._onCancel();
		
		comp.Close();
	});
	
	//Interfaces
	this.appendToDOM = Interfaces.appendToDOM;
	
	//Metodos
	this.Close = function()
	{
		comp._root.remove();	
	}
	
	this.title = function(title)
	{
		if(title)
			this._titleDiv.update(title);
		
		return this._titleDiv.innerHTML;
	}
	
	//AÃ±ade texto a la capa de contenido
	this.text = function(text)
	{
		if(text)
			this._textDiv.update(text);
		
		return this._textDiv.innerHTML;
	}
	
	//AÃ±ade nodos DOM a la capa de contenido
	this.appendContent = function(cont)
	{
		this._textDiv.appendChild(cont);
	}
	
	this.onAccept = function(f)
	{
		this._onAccept = f;
	}
	
	this.onCancel = function(f)
	{
		this._onCancel = f;
	}
	
	//DOM
	closeDiv.appendChild(this._closeImage);
	this._buttonsDiv.appendChild(this._acceptButton);
	this._buttonsDiv.appendChild(this._cancelButton);
	this._root.appendChild(closeDiv);
	this._contentDiv.appendChild(this._titleDiv);
	this._contentDiv.appendChild(this._textDiv);
	this._contentDiv.appendChild(this._buttonsDiv);
	this._root.appendChild(this._contentDiv);
	
	//Llamadas a metodos
	if(p.title)
		this.title(p.title);
	
	if(p.text)
		this.text(p.text);
};

/*
	Crea una sentencia SQL condificada para enviar al servidor
*/
function SQLCommand(p)
{
	return p.command +'.'+ p.table +'('+ p.data.toString() +')';
};

function FileUploadIframe()
{
	this._root		= getElement('div');
	this._iframe	= getElement('iframe');
	
	//Estilos
	if(Prototype.Browser.IE)
		this._iframe.frameBorder = '0';
	
	this._iframe.observe('load',function(){
		var _win = this.contentWindow;
		var _doc = this.contentWindow.document;
		var _body = this.contentWindow.document.body;
		
		//Creamos los elementos
		this._form = _doc.createElement('form');
		this._fileField = _doc.createElement('input');
		_win._fileField = this._fileField;
		_win._loadingImage = getImage('../imagenes/web/ajax-loader-formdiv.gif');
		
		//Configuracion
		this._fileField.type = 'file';
		this._form.method = 'post';
		this._form.action = 'save.php';
		this._form.enctype = 'multipart/form-data';
		
		//Estilos
		_body.style.background					= '#EAEFF7';
		_body.style.margin						= '0px';
		_body.style.padding						= '0px';
		_body.style.overflow					= 'hidden';
		_win._loadingImage.style.display		= 'none';
		_win._loadingImage.style.verticalAlign	= 'top';
		
		//Eventos
		var changeFunction = function()
		{
			//Validacion de tipo de archivo seleccionado
			
			_win._fileField.style.display = 'none';
			_win._loadingImage.style.display = '';
			
			
		};
		
		if(Prototype.Browser.IE)
			this._fileField.attachEvent('onchange',changeFunction);
		else
			this._fileField.addEventListener('change',changeFunction,false);
		
		//DOM
		this._form.appendChild(this._fileField);
		_body.appendChild(_win._loadingImage);
		_body.appendChild(this._form);
	});
	
	//DOM
	this._root.appendChild(this._iframe);
	
	//Metodos en el iframe
	this.addField = function(name,value)
	{
		var field = getElement('input');
		
		field.type = 'hidden';
		field.name = name;
		field.value = value;
		
		this._iframe._form.appendChild(field);
		
		return field;
	};
	
	this.$ = function(id)
	{
		return this._iframe.contentWindow.document.getElementById(id);
	};
	
	//Envia el formaulario al archivo save.php
	this.send = function()
	{
		this._iframe._form.submit();
	};
	
	//Interfaces
	this.appendToDOM = Interfaces.appendToDOM;
};

//Genera un numero aleratorio entre un minimo y un maximo pasado como parametro
function aleatorio(inferior,superior)
{
	var numPosibilidades = superior - inferior;
	var aleat = Math.random() * numPosibilidades;
	aleat = Math.round(aleat);
	return parseInt(inferior) + aleat;
}

//Apila imagenes para una galeria tipo caos
function apilar(apilamientoArr,div)
{
	var temp_apilamiento = [];
	var top_div;
	var i;
	for(i=0;i<apilamientoArr.length;i++)
	{
		if(apilamientoArr[i].id == div.id)
		{
			top_div = apilamientoArr[i];
			continue;
		}
		else
		{
			temp_apilamiento.push(apilamientoArr[i]);
		}
	}
	
	temp_apilamiento.push(top_div);
	
	for(i=0;i<temp_apilamiento.length;i++)
	{
		temp_apilamiento[i].setStyle({
			zIndex: i
		});
	}
	
	return temp_apilamiento;
}

//AÃ±ade sombras a una capa
function shadows(e)
{
	if(typeof e == 'string')
		e = $(e);
	
	var arriba = getElement('div');
	var derecha = getElement('div');
	var abajo = getElement('div');
	var izquierda = getElement('div');
	var arriba_derecha =  getElement('div');
	var abajo_derecha =  getElement('div');
	var abajo_izquierda =  getElement('div');
	var arriba_izquierda =  getElement('div');
	
	arriba.addClassName('sombra_arriba');
	derecha.addClassName('sombra_derecha');
	abajo.addClassName('sombra_abajo');
	izquierda.addClassName('sombra_izquierda');
	arriba_derecha.addClassName('sombra_arriba_derecha');
	abajo_derecha.addClassName('sombra_abajo_derecha');
	abajo_izquierda.addClassName('sombra_abajo_izquierda');
	arriba_izquierda.addClassName('sombra_arriba_izquierda');
	
	e.appendChild(arriba);
	e.appendChild(derecha);
	e.appendChild(abajo);
	e.appendChild(izquierda);
	e.appendChild(arriba_derecha);
	e.appendChild(abajo_derecha);
	e.appendChild(abajo_izquierda);
	e.appendChild(arriba_izquierda);
}

/*
	Ingredient
*/
function IngredientControl(ingredient){
	//Elementos
	this._div = getElement('div');
	this._delImage = getImage('../imagenes/web/close-azul-mini.png');
	this._nombreText = getText(ingredient.nombre);
	
	//Configuracion de elementos
	this._div.addClassName('ingredientControl');
	this._delImage.addClassName('button');
	this._delImage.setStyle({
		marginLeft: '5px',
		verticalAlign: 'text-bottom'
	});
	
	//Eventos
	if(typeof ingredient.onClose == 'function')
		this._delImage.observe('click',ingredient.onClose);
	
	//DOM
	this._div.appendChild(this._nombreText);
	this._div.appendChild(this._delImage);
	
	//Interfaces
	this.appendToDOM = Interfaces.appendToDOM;
};

/*
	Checkbox javascript
*/
function jsCheckbox(p)
{
	this._markedPath = p.markedImg || '../imagenes/componentes/thumb_up.png';
	this._unmarkedPath = p.unmarkedImg || '../imagenes/componentes/thumb_down.png';
	this._changeFunc = p.changeFunc;
	this._markedFunc = p.markedFunc;
	this._unmarkedFunc = p.unmarkedFunc;
	this._status = (p.status == false) ? false : true;
	this._active = p.active || true;
	
	//Elementos
	this._root			= getElement('div');
	this._markedImg		= getImage(this._markedPath);
	this._unmarkedImg	= getImage(this._unmarkedPath);
	
	//Configuracion de elementos
	this._root.setStyle({
		position: 'absolute',
		width: '16px',
		height: '16px',
		cursor: 'pointer',
		overflow: 'hidden'
	});
	
	this._markedImg.setStyle({
		position: 'absolute',
		top: '0px',
		left: '0px'
	});
	
	this._unmarkedImg.setStyle({
		position: 'absolute',
		top: '0px',
		left: '0px',
		display: 'none'
	});
	
	//DOM
	this._root.appendChild(this._markedImg);
	this._root.appendChild(this._unmarkedImg);
	
	//Interfaces
	this.appendToDOM = Interfaces.appendToDOM;
	
	//Metodos
	this.setStyle = function(style)
	{
		this._root.setStyle(style);
	};
	
	//Pone el checkbox en estado marcado
	this.setMarked = function(no_exe)
	{
		if(!this._active)
			return false;
		
		this._unmarkedImg.hide();
		this._markedImg.show();
		this._status = true;
		
		if(!(no_exe === false) && typeof this._markedFunc == 'function')
			this._markedFunc(this);
	};
	
	//Pone el checkbox en estado desmarcado
	this.setUnmarked = function(no_exe)
	{
		if(!this._active)
			return false;
		
		this._markedImg.hide();
		this._unmarkedImg.show();
		this._status = false;
		
		if(!(no_exe === true) && typeof this._unmarkedFunc == 'function')
			this._unmarkedFunc(this);
	};
	
	//Cambia el estado del checbox
	this.change = function(no_exe)
	{
		if(this._status)
			this.setUnmarked(no_exe);
		else
			this.setMarked(no_exe);
		
		if(!(no_exe === true) && typeof this._changeFunc == 'function')
			this._changeFunc(this);
		
		return this._status;
	};
	
	//Eventos
	var chkbox = this;
	this._root.observe('click',function(){ chkbox.change(); });

	if(p.setStyle)
		this.setStyle(p.setStyle);
	
	if(!this._status)
		this.setUnmarked(true);
	
	if(p.appendTo)
		this.appendToDOM(p.appendTo);
};

/*
	Formulario
*/
function HiddenForm(action,p){
	if(!p)
		p = new Object();
	
	//Miembros
	this._fields = new Array();
	
	//Elementos
	this._form = getElement('form');
	
	/*****************************
		Configuracion
	*****************************/
	this._form.hide();
	
	/*****************************
		Metodos publicos
	*****************************/
	//AÃ±ade un campo al formulario
	this.addField = function(name,value,type){
		if(typeof name == 'object' && /^input$/i.test(name.tagName)){
			//Se ha pasado un elemento input que se incluirÃ¡ directamente
			this._form.appendChild(name);
			this._fields.push(name);
			return name;
		}
		
		var f = this.field(name);
		if(f){
			f.value = value;
		}else{
			f = getElement('input');
			f.setAttribute('type',(type || 'hidden'));
			f.setAttribute('name',name);
			f.setAttribute('value',value);
			this._form.appendChild(f);
			this._fields.push(f);
		}
		
		return f;
	};
	
	//Retorna un campo del formulario si existe o false si no
	this.field = function(name){		
		//Buscamos el campo
		for(var i=(this._fields.length-1);i>-1;i--){
			if(this._fields[i].name == name)
				return this._fields[i];
		}
		
		return false;
	};
	
	//Establece el metodo de envio
	this.method = function(method){
		if(!method)
			return this._form.method;
		
		this._form.method = method;
	};
	
	//Establece el atributo action
	this.action = function(action){
		if(!action)
			return this._form.action;
		
		this._form.action = action;
	};
	
	//Establece el enctype
	this.enctype = function(enctype){
		if(!enctype)
			return this._form.enctype;
		
		this._form.enctype = enctype;
	};
	
	//Envia el formulario
	this.submit = function(){
		this._form.submit();
	};
	
	//Elimina el formulario
	this.remove = function(){
		this._form.remove();
	};
	
	/*****************************
		DOM
	*****************************/
	document.body.appendChild(this._form);
	
	/*****************************
		Configuracion en construccion
	*****************************/
	this.action(action);
	this.method((p.method || 'post'));
	
	if(p.enctype)
		this.enctype(p.enctype);
	
	if(p.id)
		this._form.id = p.id;
};

/********************************************************************
|
|	Common Effects
|
********************************************************************/

function Tabs()
{
	this._tabs = [];
	this._cTab = null;
	
	this.addTab = function(p)
	{
		p.control = $(p.control);
		p.tab = $(p.tab);
		
		var tabControl = this;
		Event.observe(p.control,'click',function(){
			tabControl.showTab(this);
		});
		
		this._tabs.push(p);
	}
	
	this.showTab = function(tab)
	{
		tab = $(tab);
		
		//Comprobamos que el control pulsado este registrado en este control de tabs
		for(var i = (this._tabs.length - 1); i >= 0; i--)
		{
			if(this._tabs[i].control.id == tab.id)
			{
				//Ocultamos el tab anterior
				if(this._cTab)
					switchElement(this._cTab.tab);
					
				//Mostramos el nuevo tab
				this._cTab = this._tabs[i];
				switchElement(this._tabs[i].tab);
				
				return this._cTab;
			}
		}
	}
	
	this.closeTab = function(tab)
	{
		//Ocultamos el tab actual
		if(this._cTab)
			switchElement(this._cTab.tab);
		
		this._cTab = null;
	}
};

function switchElement(e)
{
	e = $(e);
	
	if(e.getStyle('display') == 'none')
		e.show();
	else
		e.hide();
};

function smoothSwitchElement(e,param)
{
	e = $(e);
	
	if(!param)
		param = new Object();
	
	if(!param.duration)
		param.duration = 0.5;
	
	if(e.getStyle('display') == 'none')
		Effect.Appear(e,param);
	else
		Effect.Fade(e,param);
};

/********************************************************************
|
|	Events
|
********************************************************************/

var onReady = {
	functions: [],
	
	exeAll: function()
	{
		for(var i=0;i<onReady.functions.length;i++)
			onReady.functions[i]();
	},
	
	exe: function(f)
	{
		this.functions.push(f);
	}
};

Event.observe(window,'load',function(){
	
	if(typeof jsMonitor != 'undefined')
		m = new jsMonitor();
	
	if(typeof jsViewer != 'undefined')
		visor = new jsViewer();
	
	onReady.exeAll();
});

/********************************************************************
|
|	Elements
|
********************************************************************/

function elementExtends(element){
	var metodos = new Object();
	if(element.tagName != 'img'){
		metodos.putIn = function(element){
			$(element).appendChild(this);
			return this;
		}
	}
	return  metodos;
};

function getElement(tagName,p)
{
	var element = $(document.createElement(tagName));
	if(isObject(p)){
			Object.extend(element,p);
	}else if(Object.isString(p)){
		element.addClassName(p);
	}
	Object.extend(element,elementExtends(element));
	return element;
}

function getImage(src,p)
{
	var element = getElement('img');
	element.src = src;
	if(isObject(p)){
			Object.extend(element,p);
	}else if(Object.isString(p)){
		element.addClassName(p);
	}
	Object.extend(element,elementExtends(element));
	return element;
}


function getText(text)
{
	return $(document.createTextNode(text));
}

/*
	clear
	
	Elimina todos los hijos de un elemento
*/
function clear(e)
{
	e = $(e);
	while(e.hasChildNodes())
		e.removeChild(e.firstChild);
}

/*
	devuelve el valor seleccionado de un campo select
*/
function selectVal(field)
{
	field = $(field);
	return field.options[field.selectedIndex].value;
}

/*
	Devuelve el estado de un checkbox como 1 o 0
*/
function checkboxStatus(chkbx)
{
	chkbx = $(chkbx);
	return (chkbx.checked) ? 1 : 0;
}

/*
	jsMonitor v1.4
	
	Parcheado!!!!!
	{
		Parche!!!!!
		
		El acceso a la propiedad "rangeParent" provoca un error.
		El metodo jsMonitor.printObject no accedera a esta propiedad.
		
		Firefox 3.5.3
		http://localhost/universalgym/login.php
		24/09/2009
	}
*/
function jsMonitor(p)
{
	if(!p)p = {};
	var div = document.createElement("div");
	var controlDiv = document.createElement("div");
	div.style.background = "#FFF";
	div.style.padding = "3px";
	div.style.display = "none";
	div.style.zIndex = '10000';
	
	this.counter = 0;
	if(p.inNode)
	{
		if(p.width)div.style.width = p.width;
		document.getElementById(p.inNode).appendChild(div);
	}
	else
	{
		div.style.border = "1px solid #000";
		div.style.width = (p.width)		? p.width	: "1000px";
		div.style.height = (p.height)	? p.height	: "350px";
		div.style.overflow = "auto";
		div.style.position = "fixed";
		div.style.bottom = "10px";
		div.style.right = "10px";
		document.body.appendChild(div);
	}
	this.monitor = div;
	/*
		Detecta internet explorer
	*/
	this.IE = (window.attachEvent && navigator.userAgent.indexOf('Opera') === -1);
	/*
		Imprime un separador
	*/
	this.printHr = function()
	{
		var hr = document.createElement("hr");
		this.monitor.appendChild(hr);
	}
	/*
		Vacia el monitor de todas las entradas
	*/
	this.clear = function()
	{
		while(this.monitor.hasChildNodes())this.monitor.removeChild(this.monitor.firstChild);
		this.monitor.style.display = "none";
		this.counter = 0;
	}
	/*
		devuelve un numero para indicar el objeto
	*/
	this.number = function()
	{
		var numberSpan = document.createElement("span");
		var number = document.createTextNode(this.counter++ + "  ");
		numberSpan.style.fontSize = "11px";
		numberSpan.style.color = "#C00";
		numberSpan.appendChild(number);
		return numberSpan;
	}
	/*
		Muestra un mensaje en el monitor pasado como primer parametro
		Si es segundo parametro es true eliminara todo el contenido previo
	*/
	this.printMessage = function(m,con)
	{
		if(con)this.clear()
		var div = document.createElement("div");
		var m = document.createTextNode(m);
		div.appendChild(m);
		if(this.monitor.hasChildNodes())this.printHr();
		this.monitor.appendChild(div);
		this.monitor.style.display = "";
	}
	this.printObject = function(o,title)
	{
		if(this.monitor.hasChildNodes())this.printHr();
		var rootDiv  = document.createElement("div");
		var oDiv = document.createElement("div");
		var tDiv = document.createElement("div");
		var bTitle = document.createElement("b");
		var subTitleSpan = document.createElement("span");
		var title = title ? document.createTextNode(title):document.createTextNode('Object');
		var subTitle = document.createTextNode("  "+o);
		subTitleSpan.style.fontSize = "11px";
		oDiv.style.background = "#FC6";
		oDiv.style.padding = "3px";
		tDiv.style.fontSize = "16px";
		tDiv.style.padding = "5px";
		bTitle.style.cursor = "pointer";
		oDiv.style.display = "none";
		subTitleSpan.appendChild(subTitle);
		bTitle.appendChild(title);
		tDiv.appendChild(this.number());
		tDiv.appendChild(bTitle);
		tDiv.appendChild(subTitleSpan);
		rootDiv.appendChild(tDiv);
		rootDiv.appendChild(oDiv);
		for(var p in o)
		{	
			try{
				var valor = document.createTextNode(eval('o.'+p));
			}catch(err){
				alert('Error al examinar el objeto:\n'+ err);
				continue;
			}
			
			var div = document.createElement("div");
			var b = document.createElement("b");
			var prop = document.createTextNode(p+' -> ');
			b.appendChild(prop);
			div.appendChild(b);
			div.appendChild(valor);
			oDiv.appendChild(div);
		}
		
		var showObjectProperties = function()
		{
			if(oDiv.style.display == "none")
				oDiv.style.display = "";
			else
				oDiv.style.display = "none";
		}
		
		/*
			Añadimos el evento que muestra las propiedades del objeto
			al hacer clic sobre su nombre
		*/
		if(this.IE)
			bTitle.attachEvent("onclick",showObjectProperties);
		else
			bTitle.addEventListener("click",showObjectProperties,false);
		
		this.monitor.appendChild(rootDiv);
		this.monitor.style.display = "";
	}
}

