/**
 * Configuracion del reCaptcha.
 * Doc. http://wiki.recaptcha.net/index.php/
 * Los estilos estan en _estilos.css.
 **/
var RecaptchaOptions = {
    custom_translations : {
    	instructions_visual :  'Escriba las dos palabras:',
    	instructions_audio :   'Escribir lo que escucha:',
    	play_again :           'Volver a reproducir el audio.',
    	cant_hear_this :       'Descarga el audio en formato MP3.',
    	visual_challenge :     'Modo Visual',
    	audio_challenge :      'Escuchar la clave de seguridad.',
    	refresh_btn :          'Volver a generar una clave de seguridad.',
    	help_btn :             'Ayuda',
    	incorrect_try_again :  'Incorrecto. Por favor, int�ntelo de nuevo.',
	},
    theme : 'clean',    // [ red, white, blackglass, clean, custom ]
    lang: 'es'          // Idioma.
};

//////////////////////////////////////////////////
//IMPLEMENTACION DE NUEVOS OBJETOS
Element.implement({
	getText: function(){
		return this.get('text');
	},
	setText: function(text){
		return this.set('text', text);
	},
	setHTML: function(){
		return this.set('html', arguments);
	},
	getHTML: function(){
		return this.get('html');
	},
	getTag: function(){
		return this.get('tag');
	},
	opacity: function(de, a, du, fu) {
		var el = this;
		var st = (typeof(de) != "undefined")?de:0;
		var ed = (typeof(a) != "undefined")?a:1;
		var du = (typeof(du) != "undefined")?du:500;
		if (el) {
			if (el.getStyle('display') == "none")
				el.setStyle('display', 'block');
			
			var myFx = new Fx.Tween(el, {
				property: 'opacity',
				duration: du,
				onComplete: function() {
					var tipo = typeof(fu);
					if ( tipo != "undefined" ) {
						if (tipo == "function") {
							fu();
						} else if (tipo == "string") {
							eval(fu);
						}
					}
				}
			}).set('opacity', st).start(st, ed);
		}
	},
	comboAnidado: function (hijo, url, defaultSelected) {
		var padre = this;
		var hijo = $(hijo);
		
		if (!hijo)
			return false;
		if (typeof(url) != "string")
			return false;
			
		var optSirst = hijo.getFirst();
		var valFirst = optFirst.value;
		var txtFirst = optFirst.text;
		hijo.empty();
		var id = padre.get('value');
		
		var opt = new Element('option');
		
		if (id > 0 || id.trim() != "") {
			opt.value = '';
			opt.text = 'Cargando...';
			hijo.options.add(opt);
			url += ( url.contains('?') )?'&id=' + id + '&cache=' + $time():'?id=' + id + '&cache=' + $time();
			var newajax = new Ajax(url,{
				method: 'get',
				onComplete:function(response){
					hijo.empty();
					defaultSelected = ( typeof(defaultSelected) != 'undefined' )?defaultSelected:0;
					var optSelDefault = 0;
					Json.evaluate(response).each(function(obj, index){
						var opt = new Element('option');
						opt.setProperty("value", obj.value);
				      	opt.setHTML(obj.text); 
				      	hijo.adopt(opt);
				      	if (obj.value == defaultSelected) {
							optSelDefault = index;
						}
						
					}.bind(this));
					if (optSelDefault > 0) {
						hijo.options[optSelDefault].selected = true;
					}
				},
				onFailure: function(response){
					opt.value = '';
					opt.text = 'Fallo conexion.';
					hijo.options.add(opt);
				}
			}).request();
			
		} else {
			opt.value = valFirst;
			opt.text = txtFirst;
			hijo.options.add(opt);
		}
	},
	showMSG: function () {
		var el = $(this);
		if (el) {
			if (el.getStyle('display') == "none") {
				el.opacity(0, 1, 500);
			}
		}
	},
	hideMSG: function () {
		var el = $(this);
		if (el)
			if (el.getStyle('display') == "block" && el.getStyle('opacity') == 1 )
				el.opacity(1, 0, 300, function(){ el.setStyle('display', 'none'); });
	},
	sendForm: function (update) {
		//update => (opcional) Es el id del elemento donde se desea cargar la respuesta.
		var el = $(this);
		var tag = el.get('tag');//retrae la etiqueta del elemento recibido (this)
		if (tag == "form") { //verfica si realmente es un formulario
			$(document.body).setStyle('cursor', 'wait');
			if (typeof(update) != 'undefined') {
				//Vaciar el elemento y mostrar el indicador cargando.
				var log = $('log_res').empty().addClass('ajax-loading');
			}
			//Establecer las opciones del formulario de Solicitud
			el.set('send', {
				onComplete: function(response) {
					if (typeof(update) != 'undefined') {
						log.removeClass('ajax-loading');
						log.set('html', response);
					}
					$(document.body).setStyle('cursor', 'default');
				}
			});
			//Enviar el form
			el.send();
		}
	},
	toInputText: function(opt) {
		var obj = this;
		var value = obj.getText();
		var options = {
			'name': 'input_default',
			'id': 'input_default',
			'size': '',
			'maxlength': '100',
		    'class': '',
		    'style': ''
		};
		if ($type(opt) == 'object')
			$extend(options, opt);
		var myInput = new Element('input', $extend(options, {'type': 'text', 'value':value}) );
		obj.empty();
		myInput.inject(obj);
	},
	toText: function(idElement) {
		var el = $(idElement);
		if ( !el )
			return false;
		var obj = this;
		var value = this.get('value');
		el.setText(value);
	},
	center: function() {
		var el = this;
		var se = el.getSize();
		var sw = window.getSize();
		el.setStyles({
			top: ( (sw.y / 2) - (se.y / 2) )+'px',
			left: ( (sw.x / 2) - (se.x / 2) )+'px'
		});
	}
	
});
//////////////////////////////////////////////////
//IMPLEMENTAR UN STRING PARA CREAR FUNCIONES
String.implement({
	isMail: function() {
		var txt = this.trim();
		var regex = "^[\_]*([a-z0-9]+(\.|\_*)?)+@([a-z][a-z0-9\-]+(\.|\-*\.))+\.[a-z]{2,6}$";
		var regexp = new RegExp(regex, 'i');
		return regexp.test(txt);
	},
	isDate: function () {
		
		var dateStr = this.trim();
				
		if ( typeof(dateStr) == 'undefined' ) return false;
		
		var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
		var matchArray = dateStr.match(datePat); // is the format ok?
		
		var und = "undefined";
		
		if ( matchArray == null ) return false;
		
		if ( matchArray.length < 6 ) return false;
			
		var day = parseInt(matchArray[1]);
		var month = parseInt(matchArray[3]);
		var year = parseInt(matchArray[5]);
		
		if ( day < 1 || day > 31 ) {
			//dia inválido
			return false
		}
		
		if ( month < 1 || month > 12 ) { // check month range
			//mes inválido
			return false;
		}
		
		if ( (month==4 || month==6 || month==9 || month==11) && day==31) {
			//el mes no tiene 31 dias
			return false;
		}
		
		if (month == 2) { // check for february 29th
			var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
			if (day > 29 || (day==29 && !isleap)) {
				//febrero no tiene n dias
				return false;
			}
		}
		//
		return true;
	}
});

//////////////////////////////////////////////////
//EXTENDER NUMBER PARA AGREGAR EL NUMBER FORMAT
Number.extend({
 
	/*
	Property: numberFormat
		Format a number with grouped thousands.

	Arguments:
		decimals, optional - integer, number of decimal percision; default, 2
		dec_point, optional - string, decimal point notation; default, '.'
		thousands_sep, optional - string, grouped thousands notation; default, ','

	Returns:
		a formatted version of number.

	Example:
		(36432.556).numberFormat()  // returns 36,432.56
		(36432.556).numberFormat(2, '.', ',')  // returns 36,432.56
	*/

	numberFormat : function(decimals, dec_point, thousands_sep) {
		decimals = Math.abs(decimals) + 1 ? decimals : 2;
		dec_point = dec_point || '.';
		thousands_sep = thousands_sep || ',';

		var matches = /(-)?(\d+)(\.\d+)?/.exec((isNaN(this) ? 0 : this) + ''); // returns matches[1] as sign, matches[2] as numbers and matches[2] as decimals
		var remainder = matches[2].length > 3 ? matches[2].length % 3 : 0;
		return (matches[1] ? matches[1] : '') + (remainder ? matches[2].substr(0, remainder) + thousands_sep : '') + matches[2].substr(remainder).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep) + 
				(decimals ? dec_point + (+matches[3] || 0).toFixed(decimals).substr(2) : '');
	}

});

//////////////////////////////////////////////////
//OBJETO PARA CREAR TOOLTIPS
var tips = {
	options:{
		x: 0,
		y: 0,
		atb: 'rel',
		showTime: 500,
		hideTime: 400,
		effects: true,
		offsets: {'x': 20, 'y': 20},
		opacity: 0.9
	},
	initialize: function() {
		this.toolTip = new Element('div', {
			'class': 'tool-tip',
			'id': 'tool-tip',
			'styles': {
				'position': 'absolute',
				'top': '0',
				'left': '0',
				'visibility': 'hidden'
			},
			'events': {
				'click': function() {
					tips.hide();
				}
			}
		});
		
		this.toolTipContent = new Element('div', {'class': 'tool-content', 'id': 'tool-content'}).inject(this.toolTip);
		this.toolTip.inject(document.body)
	},
	position: function(){
		if (!this.existe)
			return false;
		var pos = $(this.el).getPosition();
		this.toolTip.setStyles({
			'left': pos.x + this.options.offsets.x,
			'top': pos.y + this.options.offsets.y
		});
	},
	createContent: function(txt) {
		if (typeof(txt) != 'undefined') {
			var cont = txt;
		} else {	
			var cont = this.el.getAttribute(this.options.atb);
			if (cont.trim() == "") {
				this.existe = false;
				return false;
			}
		}
		
		var dual = cont.split('::');
			
		if (dual.length > 1){
			this.title = new Element('div', {'class': 'tool-title'}).inject(this.toolTipContent).setHTML(dual[0].trim());
			this.text = new Element('div', {'class': 'tool-text'}).inject(this.toolTipContent).setHTML(dual[1].trim());
		} else {
			this.text = new Element('div', {'class': 'tool-text'}).inject(this.toolTipContent).setHTML(dual[0].trim());
		}
		this.existe = true;
		
	},
	assignSize: function() {
		var s = this.toolTipContent.getSize();
		this.toolTipContent.setStyles({'width': s.x+'px', 'height': s.y+'px'});
	},
	build: function(txt) {
		if ( $('tool-tip') ) {
			this.toolTipContent.empty();
			this.toolTipContent.setStyles({'width':'auto', 'height':'auto'});
			this.toolTip.setStyles({'width':'auto', 'height':'auto'});
		} else {
			this.initialize();
		}
		this.createContent(txt);
		this.position();
		this.assignSize();
	},
	show: function(el, txt) {
		this.el = el;
		this.build(txt);
		if ( !this.existe )
			return false;
		
		if (this.options.effects) {
			var size = this.toolTip.getSize();
			this.options.x = size.x;
			this.options.y = size.y;
			this.fxShow = new Fx.Morph(this.toolTip, {duration: this.options.showTime, wait: false});
			this.fxShow.start({
				'width':[0, size.x],
				'height':[0, size.y],
				'opacity':[0, this.options.opacity]
			});
		} else {
			this.toolTip.setStyle('visibility', 'visible');
		}
		
	},
	hide: function(){
		if (this.existe) {
			if (this.fxShow)
				this.fxShow.cancel();
			this.existe = false;
			
			if (this.options.effects) {
				var fxHide = new Fx.Morph(this.toolTip, {duration: this.options.hideTime, wait: false});
				fxHide.start({
					'width':[this.options.x, 0],
					'height':[this.options.y, 0],
					'opacity':[this.options.opacity, 0]
				});
			} else {
				this.toolTip.setStyle('visibility', 'hidden');
			}
		}
	}
};

//////////////////////////////////////////////////
//LOADING
var hs = {
	options: {
		createFinish: false,
		opacity: true,
		className: 'hs-loading',
		loadingText: 'Cargando...',
		loadingOpacity: 0.7
	},
	show: function(ref) {  
		var ref = $(ref);
		if (!ref) return;
		hs.createElement();
		var pos = ref.getPosition();
		var size = ref.getSize();
		var size_hsl = hs.loading.getSize();
		var xc = (size.x - size_hsl.x) / 2;
		var yc = (size.y - size_hsl.y) / 2;
		hs.loading.setStyles({
			'left': pos.x + xc,
			'top': pos.y + yc
		});
	},
	hide: function (){
		if (hs.options.createFinish)
		hs.loading.setStyle('left', '-9999px');
	},
	createElement: function() {
		if (hs.options.createFinish) return;
		
		hs.loading = new Element('div', {
			'class': hs.options.className,
			'id': hs.options.className,
			'html': hs.options.loadingText,
			'styles': {
				'position': 'absolute',
				'top': '-9999px',
				'opacity': hs.options.loadingOpacity,
				'zIndex': '1'
			}
		}).inject(document.body);
		hs.options.createFinish = true;
	}
};

//////////////////////////////////////////////////
//VERIFICA SI EL VALOR ENVIADO ES UN NUMERO
function isNumber(value) {
    return Number(value).toString() != 'NaN';
}

//////////////////////////////////////////////////
//FUNCION SOLAMENTE ACEPTA NUMEROS
// return acceptNum(event);
function acceptNum(evt){
	// NOTE: Backspace = 8, Enter = 13, '0' = 48, '9' = 57, 'up' = 38, 'down' = 40, 'left' = 37, 'right' = 39
	var key = evt.which || evt.keyCode;
	return (key <= 13 || (key >= 48 && key <= 57) || key == 37 || key == 39 );
}

//////////////////////////////////////////////////
//FUNCION SOLAMENTE ACEPTA NUMEROS Y PUNTO
function acceptNumPoint(evt){
	// NOTE: Backspace = 8, Enter = 13, '0' = 48, '9' = 57, 'up' = 38, 'down' = 40, 'left' = 37, 'right' = 39, '.' = 46
	var key = evt.which || evt.keyCode;
	return (key <= 13 || (key >= 48 && key <= 57) || key == 46 || key == 37 || key == 39 );
}

//////////////////////////////////////////////////
//ENVIAR AJAX POR GET (default) o POST
function ajax(path, el, fun, methodgp, dataSend) {
	
	if (typeof(path) == 'undefined')
		return false;
	
	if ( path.trim() == "" )
		return false;
	
	path += ( path.contains('?') )?'&cache=' + $time():'?cache=' + $time();
	
	var upd = ( typeof(el) != 'undefined')?(( $(el) )?$(el):false):false;
	
	var methodgp = ( typeof(methodgp) != 'undefined' )?(( methodgp.toLowerCase() == 'post' )?'post':'get'):'get';
	
	var dataSend = ( typeof(dataSend) != 'undefined')?dataSend:'';
	
	var newajax = new Request({
		url: path,
		method: methodgp,
		data: dataSend,
		evalScripts: true,
		onSuccess: function(response) {
			if ( upd )
				upd.set('html', response);
		},
		onComplete:function(response){
			var tipo = typeof(fun);
			if ( tipo != "undefined" ) {
				if (tipo == "function") {
					fun(response);
				} else if (tipo == "string" && fun.trim() != "" ) {
					eval(fun);
				}
			}
			$(document.body).setStyle('cursor', 'default');
		},
		onRequest:function(){
			//enviando
			$(document.body).setStyle('cursor', 'wait');
		},
		onFailure: function(response){
			$(document.body).setStyle('cursor', 'default');
			//alert('Error de conexion.');
		}
	}).send();
}
//////////////////////////////////////////////////
//RETRAE ELEMENTOS DE UN FORMULARIO
function toQueryStringForm(id_frm){
	var frm = $(id_frm);
	var queryString = [];
	if ( frm ) {
		var tag = frm.getTag();
		if (tag == "form") {
			frm.getElements('input, select, textarea').each(function(el){
				var name = el.name;
				var value = (el.tagName.toLowerCase() == 'select') ? el.options[el.selectedIndex].value : ((el.type == 'radio' || el.type == 'checkbox') && !el.checked) ? null : el.value;
				
				if (value === false || !name) return;
				var qs = function(val){
					queryString.push(name + '=' + encodeURIComponent(val));
				};
				if ($type(value) == 'array') value.each(qs);
				else qs(value);
			});
		}
	}
	return queryString.join('&');
}

//////////////////////////////////////////////////
//RECARGAR LA PAGINA
function recargaPagina() {
	if ( document ) {
		document.location.reload();
	} else if ( window ) {
		window.location.reload();
	} else {
		history.go(0);
	}
}

//////////////////////////////////////////////////
//REDIRECCIONAR A UNA URL DADA
function redireccionar(url) {
	if ( typeof(url) == 'undefined' )
		return false;
		 
	if ( document ){
		document.location = url;
	} else if ( window ) {
		window.location = url;
	} else {
		location.href = url;
	}
}

//////////////////////////////////////////////////
//CLASSE PARA EL MENU
var Menu = new Class({
	Implements: [Events],
	options: {
		liElements:[],
		ulHeight:[],
		idMenu: 'menu',
		hoverClass: 'sfHover',
		showDuration: 400,
		hideDuration: 250
	},

	initialize: function(options){
		$extend(this.options, options);
		this.element = $(this.options.idMenu);
		if (!this.element)
			return false;
		this.element.getElements('li').each( function( li ){
			var firstUl = li.getFirst('ul');
			if ( firstUl ) {
				this.options.liElements.include(li);
				this.options.ulHeight.include(firstUl.getHeight());
				var num = (this.options.liElements.length - 1);
				li.addEvent('mouseenter', function(e){
					new Event(e).stop();
					this.enter(num);
				}.bind(this));
				
				li.addEvent('mouseleave', function(e){
					new Event(e).stop();
					this.leave(num);
				}.bind(this));
				firstUl.setStyles({visibility:'hidden'});
			}
		}.bind(this));
	},

	enter: function(n){
		var el = this.options.liElements[n];
		el.addClass(this.options.hoverClass);
		var ul = el.getFirst('ul');
		if ( this.hide )
			this.hide.cancel();
		this.show = new Fx.Morph(ul, {duration: this.options.showDuration, wait: false});
		var h = this.options.ulHeight[n];
		this.show.start({
			'opacity':[0, 1],
			'height':[0, h]
		});
	},
	leave: function(n) {
		var el = this.options.liElements[n];
		if ( this.show )
			this.show.cancel();
		var ul = el.getFirst('ul');
		this.hide = new Fx.Morph(ul, {duration: this.options.hideDuration, wait: false});
		var h = this.options.ulHeight[n];
		this.hide.start({
			'opacity':[1, 0]
		});
		
	}
});

window.addEvent('domready', function() {
	/*new Menu({
		idMenu: 'menu'
	});*/
});

//////////////////////////////////////////////////
//VALIDA ELEMENTOS DE UN FORMULARIO CON EL ATRIBUTO REL
function validateForm(id_frm){
	var frm = $(id_frm);
	if ( frm ) {
		var tag = frm.getTag();
		if (tag == "form") {
			var e=0;
			frm.getElements('input, select, textarea').each(function(el){
				var rel = el.getAttribute("rel");
				if ( typeof(rel) != "undefined" && rel != null && rel != "" && e==0){
					var value = (el.tagName.toLowerCase() == 'select') ? el.options[el.selectedIndex].value : ((el.type == 'radio' || el.type == 'checkbox') && !el.checked) ? null : el.value;
					if ( value === false || value.trim() == "") {
						el.focus();
						tips.show(el);
						e++;
					}
				}
			});
			return ( e == 0 );
		}
		return false;
	}
	return false;
}





