/**
 * 
 * @author Jorge Aldana
 */

var isExplorer = navigator.appVersion.match(/MSIE/) == "MSIE";


// LTrim(string) : Regresa una copia de la cadena sin espacios en blanco a la izquierda.
function ltrim(str)
{
   var whitespace = new String(" \t\n\r");
   var s = new String(str);
   if (whitespace.indexOf(s.charAt(0)) != -1) {
      var j=0, i = s.length;
      while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
         j++;
      s = s.substring(j, i);
   }
   return s;
}

//RTrim(string) : Regresa una copia de la cadena sin espacios en blanco a la derecha.
function rtrim(str)
{
   var whitespace = new String(" \t\n\r");
   var s = new String(str);
   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      var i = s.length - 1;       // Obtiene el largo de la cadena
      while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
         i--;
      s = s.substring(0, i+1);
   }
   return s;
}

// Trim(string) : Devuelve una cadena sin espacios en blanco a la izquierda y derecha
function trim(str) {
   return rtrim(ltrim(str));
}

/**
 * @author frogx3
 */


function eliminar(id, opt){
	var x=window.confirm("Esta seguro que desea eliminar este registro?");
	if (x) {
	
		if (opt == null) 
			opt = {};
		if (trim(opt.prefix) == "undefined") {
			opt.prefix = "";
		}
		else {
			opt.prefix += "-";
		}
		if (trim(opt.url) == "undefined") {
			showMsg('Debes especificar una URL para efectuar esta accion.');
			return false;
		}
		
		new Ajax(opt.url, {
			evalScripts: true,
			method: 'post',
			data: {
				'id': id,
				'no_header': 1
			},
			onFailure: function(){
				showMsg('La informacion no pudo ser enviada por favor intente mas tarde.');
			},
			onComplete: function(){
				if (this.response.text == 1) {
					hide(opt.prefix + id);
					if (opt.nomsg === false) {
						showMsg('Registro(s) eliminado correctamente.');
					}
				}
				else {
					if (opt.nomsg === false) {
						showMsg('El registro no se pudo eliminar.');
					}
				}
			}
		}).request();
	}
	
}

function hacer(url, opt){

	/*
	 * Opciones posibles:
	 * 	nomsg: true | default:false / Especifica si se muestra un mensaje de respuesta.
	 *  form: Id del formulario del cual se enviaran sus valores.
	 * 	contenedor: string / Especifica el ID del contenedor donde se imprimira la respuesta.
	 * 	after: string / Especifica el nombre de la funcion (JS) que se ejecutara si la accion es satisfactoria.
	 * 	newmsg: string / Es el texto que se mostrara como respuesta si nomsg es true.
	 * 	parametros: string / Es una cadena de texto con parametros ej: get=rules&post=problems&print=ok
	 * 	reload: URI / es la url donde se redireccionaria el sitio.
	 *  getreturn: true | default:false
	 *  timeHide: int | default:0 Oculta el contenedor de la respuesta despues del tiempo establecido en el parametro como entero.
	 */

	if(opt==null) opt = {};

	if(typeof url == "undefined"){
		showMsg('Debes especificar una URL para efectuar esta accion.');
		return false;
	}
	
	if(opt.form){
		var parametros = $(opt.form).toQueryString();
	}else if(opt.parametros){
		var parametros = opt.parametros;
	}
	
		new Ajax(
			url + "&no_header=1",
			{evalScripts:false,
				method: 'post',
				data: parametros,
				onFailure: function(){
					showMsg('La informacion no pudo ser enviada por favor intente mas tarde.');
				},
				onComplete: function(){
					if(this.response.text >= 1 || this.response.text && this.response.text != 0){
						if (!opt.nomsg) {
							if (!opt.newmsg) {
								showMsg('Accion realizada con extio.');
							}else{
								showMsg(opt.newmsg);
							}
						}

						if(opt.contenedor){
								show(opt.contenedor);							
							if (opt.response) {
								$(opt.contenedor).innerHTML = opt.response;
							}else {
								$(opt.contenedor).innerHTML = this.response.text;
							}
						}
	
						if(opt.after){
							eval(opt.after);
						}

						if(opt.reload){
							window.location = opt.reload;
						}
						
						if(opt.getreturn){
							return this.response.text;
						}
						
						if (opt.contenedor && opt.timeHide) {
							setTimeout('hide("'+opt.contenedor+'")', opt.timeHide+'000');
						}
						
					}else{
						showMsg('Hubo un problema al intentar realizar la accion, intente mas tarde.');
					}
				}
			}).request();	
	
}

function invertir(url, unik, tag){


	if(typeof url == "undefined"){
		showMsg('Debes especificar una URL para efectuar esta accion.');
		return false;
	}
	
		new Ajax(
			url + "&no_header=1",
			{	method: 'post',
				data: {id: unik },
				onFailure: function(){
					showMsg('La informacion no pudo ser enviada por favor intente mas tarde.');
				},
				onComplete: function(){
					if(this.response.text){
						$(tag).innerHTML = this.response.text;
					}else{
						showMsg('Hubo un problema al intentar realizar la accion, intente mas tarde.');
					}
				}
			}).request();	
}

function showMsg(msg){
	if (document.all) {
		var top = window.document.documentElement.scrollTop;
	}else {
		var top = window.pageYOffset;
	}  
	
	if($('msgAlert') != null){
		$('msgAlert').style.top = top + 100 + "px";
		$('msgAlert').innerHTML = msg;
		show('msgAlert');
		setTimeout("hide('msgAlert');", 2000);
	}else{
		alert(msg);
	}
	
}


function show(elm){
	$(elm).setStyles({
		display: 'block'
		});
	return;
}

function hide(elm){
	$(elm).setStyles({
		display: 'none'
		});
	return;
}

function toggle(elm){
	var estatus = $(elm).getStyle('display');
	if(estatus == "block"){
		hide(elm);
	}else{
		show(elm);	
	}
	return;
}


function abrirPopup(uri, w, h){
	window.open (uri, "mywindow","menubar=0,resizable=1,scrollbars=1,width="+w+",height="+h); 
}

function openModal(uri, opt){
	if(opt==null) opt = {};

	var relativo = document.body;
	var caja = document.createElement('div');
	caja.setStyles({position: 'absolute',zIndex: '999'});
	caja.className = "caja_modal";
	caja.id = "caja_modal";
	if(opt.width){
		caja.setStyles({width: opt.width+'px'});
	}
	if (opt.height) {
		caja.setStyles({height: opt.height+'px'});
	}
	relativo.appendChild(caja);


	var contenedor = document.createElement('div');
	contenedor.setStyles({position: 'absolute',zIndex: '9999', overflow: 'auto'});
	contenedor.className = "contenido";
	contenedor.id = "contenedor_modal";
	relativo.appendChild(contenedor);	
	
	var cerrar = document.createElement('span');
	cerrar.setStyles({position: 'absolute',zIndex: '99999'});	
	cerrar.className = "cerrar_modal";
	cerrar.id = "cerrar_modal";
	relativo.appendChild(cerrar);	
	
	var anchor = document.createElement('a');
	anchor.href = "javascript:void(0);";
	anchor.innerHTML = "Cerrar";
	anchor.title = "Cerrar";
	anchor.id = "anchor_modal";
	anchor.addEvent('click', cerrarModal);
	cerrar.appendChild(anchor);
	
	if (opt.iframe === true) {
		var frame = document.createElement('iframe');
		frame.style.width = "100%";
		frame.style.height = "100%";
		frame.style.backgroundColor = "#fff";
		frame.style.border = 0;
		frame.id = "_frameContenedor";
		frame.src = uri+"&no_header=1";
		contenedor.appendChild(frame);
	}
	else {
		hacer(uri, {
			contenedor: 'contenedor_modal',
			nomsg: true,
			after: opt.exec
		});
	}


	posicionModal();
	
}

function cerrarModal(){
	var relativo = document.body;
	$('contenedor_modal').innerHTML = "";
	$('contenedor_modal').remove();
	$('caja_modal').remove();
	$('anchor_modal').remove();	
	$('cerrar_modal').remove();
}

function posicionModal(){
	var ancho = $('caja_modal').getStyle('width').toInt();
	var alto = $('caja_modal').getStyle('height').toInt();

	var arrayPageScroll = document.body.getPosition();
	var someArea = document.body.getCoordinates();

	var mTop = arrayPageScroll.y + someArea.height / 12;
	var mLeft = (someArea.width / 2) - (ancho / 2);	
	
	$('caja_modal').setStyles({
		top: mTop+"px",
		left: mLeft+"px"
	});	

	
	$('contenedor_modal').setStyles({
		width: (ancho - 10)+"px",
		height: (alto - 32)+"px",
		marginTop: "23px",
		top: (mTop + 5)+"px",
		left: (mLeft + 5)+"px"
	});		

	$('cerrar_modal').setStyles({
		width: (ancho - 10)+"px",
		top: (mTop + 5)+"px",
		left: (mLeft + 5)+"px"
	});		
}

/*
 * Validamos formularios ;)
 */

window.addEvent('domready', function(){
  //new Tips($$('a'));
  var doc = document.body;
  var forms = doc.getElementsByTagName('form');
  if(forms.length > 0) prepararFormularios(forms);

});

function prepararFormularios(forms){

	for(i=0;i<forms.length;i++){
		if(forms[i].getAttribute('id') === null){
			forms[i].setAttribute('id', 'formulario'+i);
		}

		var identificador = $(forms[i].getAttribute('id'));

		identificador.addEvent('submit', function(event){
				event = new Event(event).stop();
				var x = verificarFormulario(this);
				if(x == 1){
					this.submit();
				}
		});

	}
}

function verificarFormulario(k){
	var result = 1;

	if (typeof k == 'string') {
		var idform = $(k);
	}else{
		var idform = $(k.id);
	}

	var elms = idform.getElements('input[type=text]');

	for(i=0;i<elms.length;i++){
		var attr = elms[i].getAttribute('ref');
		//checa si esta vacio
		if(attr == 1 && elms[i].value == ""){
			showMsg('Olvidaste llenar algun campo.');
			result = 0;
		}
	}

	var elmsSelect = idform.getElementsByTagName('select');

	if (elmsSelect.length > 0) {
		for (i = 0; i < elmsSelect.length; i++) {
			var attr = elmsSelect[i].getAttribute('ref');
			//checa si esta vacio
			if (attr == 1 && elmsSelect[i].value == "") {
				showMsg('Olvidaste llenar algun campo.');
				result = 0;
			}
		}
	}

	return result;
}