/**
 * 
 * @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 mark_checkboxs(form, name){
	var idform = $(form);

	var elms = idform.getElements('input[type=checkbox]');
		for (i = 0; i < elms.length; i++) {
			var attr = elms[i].getAttribute('name');
			if(attr == 'pic[]'){
				if(elms[i].checked == true){
					elms[i].checked = false;
				}else{
					elms[i].checked = true;
				}
			}
		}
}

function multi_eliminar(form, plugin, new_action){
	
	var idform = $(form);

	idform.getElements('input[name=t]')[0].value = plugin;

	var elm = document.createElement('input');
	elm.type = "hidden";
	elm.name = "accion";
	elm.value = new_action;
	idform.appendChild(elm);
	idform.submit();

}

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 Request({
			url: 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.');
			},
			onSuccess: 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.');
					}
				}
			}
		}).send();
	}
	
}

function imprimir_rss(feed_url, idfeed, show, titulo){
	var url = "admin.php?t=opciones&accion=imprimir_rss";
	var params = "show="+show+"&titulo="+titulo+"&feedurl="+feed_url+"";
	
	var capa = document.createElement('div');
	capa.style.textAlign = "center";
	capa.style.marginTop = "10px";	
		var imagen = document.createElement('img');
		imagen.src = "template/images/loading.gif";
		capa.appendChild(imagen);
	
	$(idfeed).appendChild(capa);
	
	hacer(url, {nomsg: true, parametros: params, contenedor: idfeed});
	return true;
}

function hacer(valUrl, opt){

	/*
	 * Opciones posibles:
	 * 	nomsg: true | default:false / Especifica si se muestra un mensaje de respuesta, donde false mostrara el mensaje.
	 *  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 false.
	 * 	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.
	 *  contenedorInput: string / Especifica el ID del contenedor donde se imprimira la respuesta.
	 */

	if(opt==null) opt = {};

	if(typeof valUrl == "undefined"){
		showMsg('Debes especificar una URL para efectuar esta accion.');
		return false;
	}
	
	var parametros = "";
	if(opt.form)parametros += $(opt.form).toQueryString();
	
	if(opt.parametros){
		if(opt.form) parametros += "&";
		parametros += opt.parametros;
	}
	
	var rusticComplete = function(response){
		if(this.response.text >= 1 || this.response.text && this.response.text != 0){
		
			if (!opt.nomsg) {
				if (!opt.newmsg) {
					showMsg('Accion realizada con exito.');
				}else{
					showMsg(opt.newmsg);
				}
			}
			
			if(opt.contenedorInput){						
					$(opt.contenedorInput).value = "";
					if (opt.response) {
						$(opt.contenedorInput).value = opt.response;
					}else {
						$(opt.contenedorInput).value = this.response.text;
					}
			}
			
			if(opt.contenedor){
				if($(opt.contenedor).style.display == "none"){
					show(opt.contenedor);							
				}	
				$(opt.contenedor).innerHTML = "";
				
				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.contenedor && opt.timeHide) setTimeout('hide("'+opt.contenedor+'")', opt.timeHide+'000');

			
		}else{
			showMsg('Hubo un problema al intentar realizar la accion, intente mas tarde.');
		}
	}
	
	var rusticFailure = function(){
		showMsg('La informacion no pudo ser enviada por favor intente mas tarde.');
	}
	
	var opts = {
		url: valUrl + "&no_header=1", 
		method: opt.metodo?opt.metodo:'post',
		evalScripts: opt.Scripts?opt.Scripts:false,
		onRequest: opt.onRequest?onRequest:null,
		onComplete: opt.onComplete?opt.onComplete:rusticComplete,
		onSuccess: opt.onSuccess?opt.onSuccess:null,
		onFailure: opt.onFailure?opt.onFailure:rusticFailure,
	}
		

	var AjaxMoving = new Request(opts);
	AjaxMoving.send(parametros);
	
}

function invertir(gurl, unik, tag){


	if(typeof gurl == "undefined"){
		showMsg('Debes especificar una URL para efectuar esta accion.');
		return false;
	}
	
		new Request(
			{	
				url: gurl + "&no_header=1",
				method: 'post',
				data: {id: unik },
				onFailure: function(){
					showMsg('La informacion no pudo ser enviada por favor intente mas tarde.');
				},
				onSuccess: function(){
					if(this.response.text){
						$(tag).innerHTML = this.response.text;
					}else{
						showMsg('Hubo un problema al intentar realizar la accion, intente mas tarde.');
					}
				}
			}).send();	
}

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, tipo){
	var estatus = $(elm).getStyle('display');
	if(tipo){
		var myVerticalSlide = new Fx.Slide(elm);
		myVerticalSlide.toggle();
	}else{
		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); 
}

var modalOpened = 0;

function openModal(uri, opt){
	if(opt==null) opt = {};
	
	if(modalOpened == 1){
		cerrarModal();
	}
		modalOpened = 1;
	
	var relativo = $('main');
	var caja = document.createElement('div');
		caja.style.position = "absolute";
		caja.style.zIndex = "999";
	caja.className = "caja_modal";
	caja.id = "caja_modal";
	if(opt.width){
		caja.style.width = opt.width+'px';
	}
	if (opt.height) {
		caja.style.height = opt.height+'px';
	}
	relativo.appendChild(caja);


	var contenedor = document.createElement('div');
		contenedor.style.position = "absolute";
		contenedor.style.zIndex = "9999";
		contenedor.style.overflow = "auto";
	contenedor.className = "contenido";
	contenedor.id = "contenedor_modal";
	relativo.appendChild(contenedor);	
	
	var cerrar = document.createElement('span');
		cerrar.style.position = "absolute";
		cerrar.style.zIndex = "99999";
	cerrar.className = "cerrar_modal";
	cerrar.id = "cerrar_modal";
	relativo.appendChild(cerrar);	

	var anchor = document.createElement('a');
	anchor.href = "javascript:cerrarModal();";
	anchor.innerHTML = "Cerrar";
	anchor.title = "Cerrar";
	anchor.id = "anchor_modal";
	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.frameBorder = 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(){
	$('contenedor_modal').destroy();
	$('caja_modal').destroy();
	$('anchor_modal').destroy();	
	$('cerrar_modal').destroy();
	modalOpened = 0;
}

function posicionModal(){
	
	var ancho = $('caja_modal').getStyle('width').toInt();
	var alto = $('caja_modal').getStyle('height').toInt();

	var anchoMain = $('main').getStyle('width').toInt();
	var altoMain = $('main').getStyle('height').toInt();

	var mTop = (altoMain - alto) / 4;
	var mTop = $(window).getScroll().y + 50;
	var mLeft = (anchoMain - 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": "-60px"
	});		
	

	$('cerrar_modal').setStyles({
		"width": (ancho - 10)+"px",
		"top": (mTop + 5)+"px",
		"left": (mLeft + 5)+"px"
	});		
}

/*
 * Validamos formularios ;)
 */

window.addEvent('domready', function(){
  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') == "") || (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.');
			elms[i].className = "vacio";
			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.');
				elmsSelect[i].className = "vacio";
				result = 0;
			}
		}
	}

	return result;
}

function getLinks_editor(v, c){
	return hacer('../../../../../../administracion/admin.php?t=menus&accion=getLinks', {nomsg: true, contenedor: c, parametros: "tipo="+v+"&editor=1"});
}