// Variables globales
// Incluir en la plantilla variable: var full_url = '{full_url}';

// Texto por default para mostrar en contenedores actualizados mediante AJAX
var loading_text = 'Cargando... por favor espera';

// Variables para ventanas de diálogo
var dbxTIMER = 5;	// Tiempo para ejecutar la transición
var dbxSPEED = 10;	// Velocidad de transición

// ******************** FUNCIONES GENERALES ******************

// Simplifica obtener elemento por ID
function $(id) {
	return document.getElementById(id);
}

// Cambia el estilo display de "block" a "none" y viceversa
function showHide(divToHide) {
	var elem, vis;
	elem = $(divToHide);
	if(elem == null) {
		return;
	}
	vis = elem.style;
	if(vis.display == 'block' || vis.display == null || vis.display == '') {
		vis.display = 'none';
	} else {
		vis.display = 'block';
	} 
}

// Mostrar/ocultar varias capas, solo hay que separar con +: 'capa1+capa2+capa3'
function multiShowHide(divs) {
	var adivs = divs.split('+');
	for(i = 0; i < adivs.length; i++) {
		showHide(adivs[i]);
	}
}

// Notificar al usuario si tiene mensajes nuevos
// Tal vez esta opción no la usemos, será preferible usar la ventana modal
function private_alert(msg, url) {
	bt = '<p class="centered"><br /><br />Ver mensajes en:</p><p class="centered"><a href="' + url + '" class="button">Esta ventana</a>';
	bt += ' <a href="#new" onclick="hideDialog(); window.open(\'' + url + '\'); return false;" class="button">Ventana nueva</a>';
	bt += ' <a href="#close" onclick="hideDialog(); return false;" class="button">Cancelar</a></p>';
	txt = '<p class="centered">' + msg.replace('\n', '<br />') + '</p>' + bt;
	showDialog('Notificación', txt, 'prompt', false, 400, 300);
	return;
}

// Agregar elemento en el contenedor indicado
function addElement(target, element, eid, eclass, html) {
	var elem = document.createElement(element);
	if(eid)
		elem.id = eid;
	if(eclass)
		elem.className = eclass;
	if(html)
		elem.innerHTML = html;
	document.getElementById(target).appendChild(elem);
}

// ******************** FUNCIONES AJAX ******************

// Ejecutar llamada AJAX
// url		= Dirección absoluta del script a ejecutar
// target	= Contenedor HTML donde se desplegará el resultado
// ffields	= null para método GET
//		  "campo1+campo2+...+campoN" para método POST
//		  Todos los campos serán obtenidos por su ID: document.getElementById()
function load_content(url, target, ffields) {
	// Crear el objeto XML
	var o_xml = false;
	var method = false;
	var post_fields = false;
	if (window.XMLHttpRequest) { // Funciona con mozilla, safari, etc.
		o_xml = new XMLHttpRequest();
	} else if (window.ActiveXObject){ // Debería funcionar con IExplorer
		try {
			o_xml = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {  // Para versiones antiguas
				o_xml = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){ alert(e); }
		}
	}
	if(o_xml === false) {
		return false;	// El navegador no soporta AJAX o el método no es correcto
	}
	if(!ffields) {
		// No necesitamos obtener mayor info
		method = 'GET';
		post_fields = null;
	} else {
		method = 'POST';
		// En algún navegador había error, por eso este IF cuando sólo se procesa 1 campo
		if(ffields.indexOf('+')) {
			fields = ffields.split('+');
		} else {
			fields = new Array(ffields);
		}
		post_fields = '';
		sep = '';
		// Analizamos los campos, no se pueden procesar campos tipo radio
		for(i = 0; i < fields.length; i++) {
			curfield = document.getElementById(fields[i]);
			if(curfield == null) {
				continue;
			}
			if(curfield.type == 'select') {
				selIndex = curfield.selectedIndex;
				curvalue = curfield.options[selIndex].value;
			} else if(curfield.type == 'checkbox') {
				curvalue = (curfield.checked == true) ? curfield.value : '';
			} else {
				curvalue = curfield.value;
			}
			post_fields += sep + fields[i] + "=" + encodeURIComponent(curvalue);
			sep = '&';
		}
		// Send fields by post
	}
	if(loading_text != '' && target != '') {
		// Actualizamos sólo cuando sea necesario
		if(!document.getElementById(target)) {
			alert('El contenedor ' + target + ' no existe');
			return;
		}
		document.getElementById(target).innerHTML = loading_text;
	}
	o_xml.onreadystatechange=function(){
		load_response(o_xml, target);
	}
	o_xml.open(method, url, true) // Asignamos los métodos open y send
	o_xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	o_xml.send(post_fields);
}

function load_response(o_xml, target) {
	if (o_xml.readyState == 4) {	// Proceso completo
		if(o_xml.status >= 200 ||  o_xml.status <= 300) {	// 200 a 300 son valores correctos
			// Obtenemos nuevo contenido y javascript a ejecutar
			var newScript = false;
			var txtSplit = o_xml.responseText.split('<!-- V8L-AJAX-SCRIPT -->');
			var newContent = txtSplit[0];
			if(txtSplit[1] != null) {
				newScript = txtSplit[1];
			}

			if(newContent != '' && target != '') {
				// Actualizamos sólo cuando sea necesario
				var mainTarget = document.getElementById(target);
				try { // Esto funciona perfecto con los navegadores reales
					mainTarget.innerHTML = newContent;
				} catch (e) { // Solución para IExplorer
					var wrapDiv = document.createElement('div');
					mainTarget.innerHTML = '';
					wrapDiv.innerHTML = newContent;
					mainTarget.appendChild(wrapDiv);
				}
			}
			// Ejecutar javascript adicional
			if(newScript != false) {
				var toEval = newScript.split('<!-- V8L-NEWLINE -->');
				for(i = 0; i < toEval.length; i++) {
					if(toEval[i] == '') {
						continue;
					}
					eval(toEval[i]);
				}
			}
		} else {
			if(target != '') {
				document.getElementById(target).innerHTML = 'Error #' + o_xml.status + '; por favor intenta nuevamente';
			} else {
				alert('Error #' + o_xml.status + '; por favor intenta nuevamente');
			}
		}
	}
}

// ******************** FUNCIONES PARA VENTANAS DE DIALOGO ******************

// Obtener ancho actual de la ventana
function pageWidth() {
	return window.innerWidth != null ? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
}

// Obtener altura actual de la ventana
function pageHeight() {
	return window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
}

// Calcular posición vertical
function topPosition() {
	return typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
}

// Calcular posición horizontal
function leftPosition() {
	return typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
}

// Crear la caja de diálogo con un texto inicial
function showDialog(title,message,type,autohide,sdw,sdh) {
	if(!type) {
		type = 'error';
	}
	var dialog;
	var dialogheader;
	var dialogclose;
	var dialogtitle;
	var dialogcontent;
	var dialogmask;
	if(!document.getElementById('dialog')) {
		// Crear la ventana si no existe
		dialog = document.createElement('div');
		dialog.id = 'dialog';
		dialogheader = document.createElement('div');
		dialogheader.id = 'dialog-header';
		dialogtitle = document.createElement('div');
		dialogtitle.id = 'dialog-title';
		dialogclose = document.createElement('div');
		dialogclose.id = 'dialog-close'
		dialogcontent = document.createElement('div');
		dialogcontent.id = 'dialog-content';
		dialogmask = document.createElement('div');
		dialogmask.id = 'dialog-mask';
		dialogmask.setAttribute('onclick','hideDialog()');
		document.body.appendChild(dialogmask);
		document.body.appendChild(dialog);
		dialog.appendChild(dialogheader);
		dialogheader.appendChild(dialogtitle);
		dialogheader.appendChild(dialogclose);
		dialog.appendChild(dialogcontent);;
		dialogclose.setAttribute('onclick','hideDialog()');
		dialogclose.setAttribute('title','Click para cerrar');
		dialogclose.setAttribute('alt','Click para cerrar');
		dialogclose.onclick = hideDialog;
	} else {
		// Creamos las variables necesarias para modificar la ventana
		dialog = document.getElementById('dialog');
		dialogheader = document.getElementById('dialog-header');
		dialogtitle = document.getElementById('dialog-title');
		dialogclose = document.getElementById('dialog-close');
		dialogcontent = document.getElementById('dialog-content');
		dialogmask = document.getElementById('dialog-mask');
		dialogmask.style.visibility = "visible";
		dialog.style.visibility = "visible";
	}
	dialog.style.opacity = .00;
	dialog.style.filter = 'alpha(opacity=0)';
	dialog.alpha = 0;
	var width = pageWidth();
	var height = pageHeight();
	var left = leftPosition();
	var top = topPosition();
	// Tamaño por default de la ventana
	if(sdw == null)
		sdw = 400;
	if(sdh == null)
		sdh = 160;
	if(sdw > (width - 100))
		sdw = width - 100;
	//if(sdh > (height - 100))
	//	sdh = height - 100;

	dialog.style.width = sdw + 'px';
	dialogcontent.style.height = sdh + 'px';

	var dialogwidth = dialog.offsetWidth;
	var dialogheight = dialog.offsetHeight;
	var topposition = top + (height / 2) - (dialogheight / 2);
	if(topposition < 50)
		topposition = 50;
	var leftposition = left + (width / 2) - (dialogwidth / 2);

	dialog.style.top = topposition + "px";
	dialog.style.left = leftposition + "px";
	dialogheader.className = 'dbx' + type + "header";

	dialogtitle.innerHTML = title;
	dialogcontent.className = 'dbx' + type;
	if(message != false)
		dialogcontent.innerHTML = message;

	dialogmask.style.height = document.body.offsetHeight + 'px';

	// Desactivamos la barra de desplazamiento
	// document.body.style.overflow = 'hidden';
	dialog.timer = setInterval("fadeDialog(1)", dbxTIMER);
	if(autohide) {
		dialogclose.style.visibility = "hidden";
		window.setTimeout("hideDialog()", (autohide * 1000));
	} else {
		dialogclose.style.visibility = "visible";
	}
}

// Precargar imagen y cambiar tamaño de ventana
function dialogImg(imgsrc) {
	objImg = new Image();
	objImg.onload = function() {
		dw = objImg.width + 100;
		dh = objImg.height + 70;
		objImg.onload = function(){}; // IE se comporta raro (que raro!!) con gifs animados
		dialogDim(dw, dh);
	};
	objImg.src = imgsrc;
}

// Abrir imagen en ventana de diálogo
function imageOpen(file) {
	content = 'Leyendo archivo, por favor espera...';
	var dw = 900;
	var dh = 450;

	title = 'Imagen ampliada';
	// Precargar imagen y cambiar tamaño de ventana
	dialogImg(file);
	content = '<img src="' + file + '" alt="Imagen ampliada" style="display:block; margin:1em auto; cursor:pointer;" onclick="hideDialog();" />';
	content = content + '<p class="centered"><input type="button" class="dialog-button" name="dcclose" value="Cerrar ventana" onclick="hideDialog();" /></p>';

	showDialog(title, content, 'prompt', false, dw, dh);
	return;
}


// Cambiar tamaño de la ventana
function dialogDim(dw, dh) {
	var dialog = document.getElementById('dialog');
	var dialogcontent = document.getElementById('dialog-content');
	if(dw < 450)
		dw = 450;
	else if(dw > 900)
		dw = 900;

	var topposition = topPosition() + (pageHeight() / 3) - (dh / 3);
	if(topposition < 50)
		topposition = 50;
	var leftposition = leftPosition() + (pageWidth() / 2) - (dw / 2);

	dialog.style.top = topposition + "px";
	dialog.style.left = leftposition + "px";
	dialog.style.width = dw + 'px';
	dialogcontent.style.height = dh + 'px';
}

// Ocultar la ventana
function hideDialog() {
	var dialog = document.getElementById('dialog');
	// Reactivamos la barra de desplazamiento
	// document.body.style.overflow = 'auto';
	clearInterval(dialog.timer);
	dialog.timer = setInterval("fadeDialog(0)", dbxTIMER);
}

// Mostrar la ventana con transición
function fadeDialog(flag) {
	if(flag == null) {
		flag = 1;
	}
	var dialog = document.getElementById('dialog');
	var value;
	if(flag == 1) {
		value = dialog.alpha + dbxSPEED;
	} else {
		value = dialog.alpha - dbxSPEED;
	}
	dialog.alpha = value;
	dialog.style.opacity = (value / 100);
	dialog.style.filter = 'alpha(opacity=' + value + ')';
	if(value >= 99) {
		clearInterval(dialog.timer);
		dialog.timer = null;
	} else if(value <= 1) {
		dialog.style.visibility = "hidden";
		document.getElementById('dialog-mask').style.visibility = "hidden";
		clearInterval(dialog.timer);
	}
}

// *************** Asignar imagen al campo seleccionado *****************
// image	Ruta de la imagen
// target	Campo de texto donde se asignará el valor
function image2field(image, target) {
	if($('actimg')) {
		if($('imagethumb')) {
			$('actimg').src = image.replace('.jpg', '.th.jpg');
		} else {
			$('actimg').src = image;
		}
	}
	trash = image.split('/');
	image = trash[trash.length - 1];
	$(target).value = image;
	// Cerrar contenedores
	multiShowHide('js-white+js-black');
}

// ********** Mostrar imagen seleccionada ***********
// div		Contenedor para mostrar la imagen
// image	Imagen a mostrar
// target	Campo donde de asignará el valor
function showImage(div, image, target) {
	showHide(div);
	var jsbuttons = '<div class="centered">';
	jsbuttons += '<input type="button" name="js-btimg" value="Asignar imagen" class="button" onclick="showHide(' + "'" + div + "'" + '); image2field(' + "'" + image + "','" + target + "'" + ');" /> ';
	jsbuttons += '<input type="button" name="js-close" value="Cerrar imagen" class="button" onclick="showHide(' + "'" + div + "'" + ');" /></div>';
	var newContent = jsbuttons + '<p class="centered"><img src="' + image + '" alt="Vista previa" /></div>' + jsbuttons;
	try {
		$(div).innerHTML = newContent;
	} catch (e) {
		// IE a veces falla con esto, a menos que hagamos un nuevo elemento
		var wrapper = document.createElement(div);
		$(div).innerHTML = '';
		wrapper.innerHTML = newContent;
		$(div).appendChild(wrapper);
	}
}

