//////////////////////////////////////////////////
//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);
		}
	}
});


//////////////////////////////////////////////////
//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': -50},
		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 (typeof(cont) == "undefined" || cont == null ||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');
			}
		}
	}
};

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

//////////////////////////////////////////////////
//FUNCION SOLAMENTE ACEPTA NUMEROS
//example: onkeypress="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
//example: onkeypress="return acceptNumPoint(event);"
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 );
}

//////////////////////////////////////////////////
//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;
	}
}
//////////////////////////////////////////////////
//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;
}