// common.js by mr.xkr v2 rev.4

// pequeas funciones para reducir cdigo
function gid(id) {
	try {
		if (typeof(id)=="object") return id;
		else return document.getElementById(id);
	} catch(e) {
		return(null);
	}
}
function gidget(id) { return(gid(id).innerHTML); }
function gidset(id,html) { gid(id).innerHTML=html; }
function gidval(id,data) { if (typeof(data)!="undefined") gid(id).value=data; else return(gid(id).value); }
function gidvals(idsdata) { for (var i in idsdata) gidval(i,idsdata[i]); }
function giddel(id) { var d=gid(id); d.parentNode.removeChild(d); }
function gidmove(id_org,id_dst) { gid(id_dst).innerHTML=gid(id_org).innerHTML; gid(id_org).innerHTML=""; }
function show(id) { gid(id).style.display="block"; }
function hide(id) { gid(id).style.display="none"; }
function cell(id) { gid(id).style.display="table-cell"; }
function visible(id) { gid(id).style.visibility="visible"; }
function hidden(id) { gid(id).style.visibility="hidden"; }
function isShow(id) { return(gid(id).style.display=="block"?true:false); }
function isVisible(id) { return(gid(id).style.display!="none"?true:false); }
function showSwitch(id) { gid(id).style.display=(gid(id).style.display=="block"?"none":"block"); }

// obtener todos los datos de campos segn su ID prefijados y/o sufijados
function gpreids(prefix,ids,sufix) {
	var ids=ids.split(" ");
	var a={};
	for (var i in ids)
		if (gid((prefix?prefix+"_":"")+ids[i]+(sufix?"_"+sufix:"")))
			a[ids[i]]=gidval((prefix?prefix+"_":"")+ids[i]+(sufix?"_"+sufix:""));
	return a;
}

// establecer todos los datos de campos segn su ID prefijados y/o sufijados
function spreids(prefix,ids,values,sufix) {
	var ids=ids.split(" ");
	for (var i in ids)
		if (gid((prefix?prefix+"_":"")+ids[i]+(sufix?"_"+sufix:"")))
			gidval((prefix?prefix+"_":"")+ids[i]+(sufix?"_"+sufix:""),values[ids[i]]);
}

// carga el contenido HTML de una capa y realiza reemplazos para usarla como template para ventanas o bsquedas AJAX
// por defecto, los reemplazos que hace son automticamente de id y name con prefijo $
function gtemplate(id,replaces) {
	var s=gidget("template:"+id);
	s=s.replace(/ id=\$/gi," id=");
	s=s.replace(/ id=\'\$/gi," id='");
	s=s.replace(/ id=\"\$/gi,' id="');
	s=s.replace(/ name=\$/gi," name=");
	s=s.replace(/ name=\'\$/gi," name='");
	s=s.replace(/ name=\"\$/gi,' name="');
	if (replaces)
		for (var i in replaces)
			s=s.replace(new RegExp(i.replace(/([.?*+^$[\]\\(){}-])/g, "\\$1"),'g'),replaces[i]);
	return s;
}

// funciones auxiliares
function getTop(id) { var o=gid(id); var p=0; do { p+=o.offsetTop; } while (o=o.offsetParent); return(p); }
function getLeft(id) { var o=gid(id); var p=0; do { p+=o.offsetLeft; } while (o=o.offsetParent); return(p); }
function getWidth(id) { return gid(id).offsetWidth; }
function getHeight(id) { return gid(id).offsetHeight; }
function style(id,styles) { var o=gid(id); for (var i in styles) o.style[i]=styles[i]; }

// propiedades del documento y ventana
function ieTrueBody() { return((document.compatMode && document.compatMode!="BackCompat")?document.documentElement:document.body); }
function scrollLeft() { return(ieTrueBody().scrollLeft); }
function scrollTop() { return(ieTrueBody().scrollTop); }
function windowWidth() { return(document.documentElement.clientWidth?document.documentElement.clientWidth:(window.innerWidth?window.innerWidth:document.body.clientWidth)); }
function windowHeight() { return(document.documentElement.clientHeight?document.documentElement.clientHeight:(window.innerHeight?window.innerHeight:document.body.clientHeight)); }
function documentWidth() { return(document.body.clientWidth); }
function documentHeight() { return(document.body.clientHeight); }

// establecer cursor
function setCursor(cursor) { document.body.style.cursor=(cursor?cursor:"auto"); }

// obtiene el ancho del borde (horizontal)
function getBorderWidth(id) {
	var wext=(parseInt(getStyle(id,"border-left-width"))+parseInt(getStyle(id,"border-right-width")));
	return (!isNaN(wext)?wext:0);
}

// obtiene el alto del borde (vertical)
function getBorderHeight(id) {
	var wext=(parseInt(getStyle(id,"border-top-width"))+parseInt(getStyle(id,"border-bottom-width")));
	return (!isNaN(wext)?wext:0);
}

// obtiene el alto del borde superior
function getBorderTopHeight(id) {
	var wext=parseInt(parseInt(getStyle(id,"border-top-width")));
	return (!isNaN(wext)?wext:0);
}

// obtiene el alto del borde inferior
function getBorderBottomHeight(id) {
	var wext=parseInt(parseInt(getStyle(id,"border-bottom-width")));
	return (!isNaN(wext)?wext:0);
}

// obtiene el ancho del padding (horizontal)
function getPaddingWidth(id) {
	var wext=(parseInt(getStyle(id,"padding-left"))+parseInt(getStyle(id,"padding-right")));
	return (!isNaN(wext)?wext:0);
}

// obtiene el alto del padding (vertical)
function getPaddingHeight(id) {
	var wext=(parseInt(getStyle(id,"padding-top"))+parseInt(getStyle(id,"padding-bottom")));
	return (!isNaN(wext)?wext:0);
}

// obtiene el estilo final computado de un elemento
function getStyle(id,styleProp) {
	var x=gid(id);
	if (x.currentStyle) { return x.currentStyle[styleProp]; }
	else if (window.getComputedStyle) { return document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp); }
	return null;
}

// ancho interno (sin mrgenes/paddings/bordes)
function crossInnerWidth(id) {
	var element=gid(id);
	try {
		if (window.getComputedStyle(element,""))
			return(element.clientWidth-parseInt(window.getComputedStyle(element,"").getPropertyValue("padding-left"))-parseInt(window.getComputedStyle(element,"").getPropertyValue("padding-right")));
	} catch(e) {
		return(element.clientWidth-parseInt(element.currentStyle.paddingLeft)-parseInt(element.currentStyle.paddingRight));
	}
}

// alto interno (sin mrgenes/paddings/bordes)
function crossInnerHeight(id) {
	var element=gid(id);
	try {
		if (window.getComputedStyle(element,""))
			return(element.clientHeight-parseInt(window.getComputedStyle(element,"").getPropertyValue("padding-top"))-parseInt(window.getComputedStyle(element,"").getPropertyValue("padding-bottom")));
	} catch(e) {
		return(element.clientHeight-parseInt(element.currentStyle.paddingTop)-parseInt(element.currentStyle.paddingBottom));
	}
}

// precarga de imgenes
var imagePreloadList=new Object();
function imagePreload(imageorlist) {
	var image_list=(typeof image=="string"?[imageorlist]:imageorlist);
	for (var i in image_list) {
		var image=image_list[i];
		imagePreloadList[image]={"loaded":false,"img":new Image()};
		imagePreloadList[image].img.src=image;
		imagePreloadList[image].img.onload=function(){imagePreloadList[image].loaded=true;};
	}
}

// ancho del scroll vertical
// thanks to Alexandre Gomes (Portugal)
// http://www.alexandre-gomes.com/?p=115
function scrollWidth() {

	var inner=document.createElement('p');
	inner.style.width='100%';
	inner.style.height='200px';

	var outer=document.createElement('div');
	outer.style.position='absolute';
	outer.style.top='0px';
	outer.style.left='0px';
	outer.style.visibility='hidden';
	outer.style.width='200px';
	outer.style.height='150px';
	outer.style.overflow='hidden';

	outer.appendChild(inner);
	document.body.appendChild(outer);

	var w1=inner.offsetWidth;
	outer.style.overflow='scroll';
	var w2=inner.offsetWidth;
	if (w1==w2) w2=outer.clientWidth;

	document.body.removeChild(outer);
	return(w1-w2);
}

// almacenar cookie
function setCookie(name,value,days) {
	var expires="";
	value=""+value;
	if (days) {
		var date=new Date();
		date.setTime(date.getTime()+(days*86400000));
		expires="; expires="+date.toGMTString();
	}
	document.cookie=name+"="+value.replace(/\\/gi,"\\\\").replace(/\n/gi,"\\n").replace(/;/gi,"\\,")+expires+"; path=/";
}

// obtener cookie
function getCookie(name) {
	var nameEQ=name+"=";
	var ca=document.cookie.split(';');
	for (i=0;i<ca.length;i++) {
		var c=ca[i];
		while (c.charAt(0)==' ')
			c=c.substring(1,c.length);
		if (c.indexOf(nameEQ)==0)
			return(c.substring(nameEQ.length,c.length).replace(/\\\\/gi,"\\").replace(/\\n/gi,"\n").replace(/\\,/gi,";"));
	}
	return("");
}

// borrar cookie
function delCookie(name) {
	setCookie(name,"",-1);
}

// comprobacin de navegadores
function isie() { return (navigator.userAgent.indexOf("MSIE")!=-1); }
function ismoz() { return (navigator.userAgent.indexOf("Firefox")!=-1 || navigator.userAgent.indexOf("Iceweasel")!=-1); }

// oculta todos los selects de la pgina si es IE
function hideSelects(hidden) {
	if (!isie()) return;
	selects=document.getElementsByTagName("select");
	for (i=0;i<selects.length;i++)
		selects[i].style.visibility=(hidden?"hidden":"visible");
}

// buscar y ejecutar tags <script> embebidos
function getrunjs(data) {
	runjs(getjs(data));
}

// buscar tags <script> embebidos
function getjs(data) {
	scode="";
	while (true) {
		ss=data.toLowerCase().indexOf("<script>"); if (ss<0) break;
		es=data.toLowerCase().indexOf("<\/script>",ss+2); if (es<0) break;
		scode=scode+data.substring(ss+8,es);
		data=data.substring(0,ss)+data.substring(es+9);
	}
	return(scode);
}

// ejecutar cadena de javascript (mucho mejor que eval)
function runjs(data) {
	if (!data) return;
	var escode=document.createElement("script");
	escode.setAttribute("type","text/javascript");
	escode.text=data;
	document.getElementsByTagName("body").item(0).appendChild(escode);
}

// convertir retornos de carro en nuevas lineas HTML
function nl2br(t) {
	try { var e=/\n/gi; t=t.replace(e,"<br />"); } catch(e) {}
	return(t);
}

// id/object merge: de una lista de identificadores separadas por comas,
// mezclar sus datos con objetos JavaScript previamente existentes
function ioMerge(ids,root,obj) {
	ids=ids.split(",");
	for (i=0;i<ids.length;i++)
		if (gid(root+ids[i]))
			obj[ids[i]]=gidval(root+ids[i]);
	return(obj);
}

// object/object merge: de una lista de objetos separados por comas,
// copia los los datos del primero objeto en el segundo y devuelve este
function ooMerge(ids,obj1,obj2) {
	ids=ids.split(",");
	for (i=0;i<ids.length;i++)
		obj2[ids[i]]=obj1[ids[i]];
	return(obj2);
}

// aade CSS al documento (no funciona bien en IE6)
function cssAdd(css) {
  var style=document.createElement("style");
  style.type="text/css";
  if (style.styleSheet) style.styleSheet.cssText=css;
  else style.appendChild(document.createTextNode(css));
  document.getElementsByTagName("head")[0].appendChild(style);
}

// array_merge: mezcla arrays puros o asociativos
// es equivalente a la funcion de PHP
function array_merge(a1,a2) {
	for (var i in a2) a1[i]=a2[i];
	return a1;
}

// array_remove: elimina claves de un array asociativo
function array_remove(a1,a2) {
	var a=new Object();
	var clone;
	for (var i in a1) {
		clone=true;
		for (var j in a2)
			if (i==a2[j]) {
				clone=false;
				break;
			}
		if (clone)
		a[i]=a1[i];
	}
	return a;
}

// elimina un elemento en la posicin del indice de un array
function array_delete(a,index) {
	var n=Array();
	for (var i in a)
		if (i!=index)
			n[n.length]=a[i];
	return n;
}

// array_get: devuelve las claves de un array dada una lista de ellas
function array_get(a,list) {
	var o=new Object();
	for (var i in list)
		o[list[i]]=a[list[i]];
	return o;
}

// array_save: busca las claves de la lista en el segundo array y los mezcla con el primero
function array_save(a1,a2,list) {
	for (var i in list)
		a1[list[i]]=a2[list[i]];
	return a1;
}

// copia en profundidad de un objeto
function array_copy(o) {
	if (typeof o != "object" || o === null) return o;
	var r = o.constructor == Array ? [] : {};
	for (var i in o) r[i] = array_copy(o[i]);
	return r;
}

// aade un objeto a un array plano
function array_push(a,o) {
	a.push(o);
}

// control de impresin, sobrecargar este mtodo
function doprint() { window.print(); }

// init_fast
var init_fast_func=new Array();
function init_fast(add) {
	if (add) init_fast_func[init_fast_func.length]=add;
	else { for (var i in init_fast_func) { try { init_fast_func[i](); } catch(e) {} } }
}

// onload
var init_func=new Array();
var init_func_last=window.onload;
function init(add) {
	if (add) init_func[init_func.length]=add;
	else { for (var i in init_func) { try { init_func[i](); } catch(e) {} } }
}
window.onload=function(){
	try { init_func_last(); } catch(e) {}
	try { init(); } catch(e) {}
}

// onunload
var unload_func=new Array();
var unload_func_last=window.onunload;
function unload(add) {
	if (add) unload_func[unload_func.length]=add;
	else { for (var i in unload_func) { try { unload_func[i](); } catch(e) {} } }
}
window.onunload=function(){
	try { unload_func_last(); } catch(e) {}
	try { unload(); } catch(e) {}
}

// onresize
var resize_func=new Array();
var resize_func_last=window.onresize;
function resize(add) {
	if (add) resize_func[resize_func.length]=add;
	else { for (var i in resize_func) { try { resize_func[i](); } catch(e) {} } }
}
window.onresize=function(){
	try { resize_func_last(); } catch(e) {}
	try { resize(); } catch(e) {}
}

// onkeydown
var keydown_func=new Array();
var keydown_func_last=document.onkeydown;
function keydown(p) {
	if (typeof(p)=="function") keydown_func[keydown_func.length]=p;
	else { for (var i in keydown_func) { try { keydown_func[i](p); } catch(e) {} } }
}
document.onkeydown=function(we){
	try { keydown_func_last(we); } catch(e) {}
	try { keydown(we); } catch(e) {}
}

// onkeyup
var keyup_func=new Array();
var keyup_func_last=document.onkeyup;
function keyup(p) {
	if (typeof(p)=="function") keyup_func[keyup_func.length]=p;
	else { for (var i in keyup_func) { try { keyup_func[i](p); } catch(e) {} } }
}
document.onkeyup=function(we){
	try { keyup_func_last(we); } catch(e) {}
	try { keyup(we); } catch(e) {}
}

// onscroll
var scroll_func=new Array();
var scroll_func_last=document.onscroll;
function scroll(p) {
	if (typeof(p)=="function") scroll_func[scroll_func.length]=p;
	else { for (var i in scroll_func) { try { scroll_func[i](p); } catch(e) {} } }
}
document.onscroll=function(we){
	try { scroll_func_last(we); } catch(e) {}
	try { scroll(we); } catch(e) {}
}

// onmouseup
var mouseup_func=new Array();
var mouseup_func_last=document.onmouseup;
function mouseup(p) {
	if (typeof(p)=="function") mouseup_func[mouseup_func.length]=p;
	else { for (var i in mouseup_func) { try { mouseup_func[i](p); } catch(e) {} } }
}
document.onmouseup=function(we){
	if (!we) we=window.event;
	try { mouseup_func_last(we); } catch(e) {}
	try { mouseup(we); } catch(e) {}
}

// onmousedown
var mousedown_func=new Array();
var mousedown_func_last=document.onmousedown;
function mousedown(p) {
	var ret=null;
	if (typeof(p)=="function") mousedown_func[mousedown_func.length]=p;
	else {
		for (var i in mousedown_func) { try { ret=mousedown_func[i](p); } catch(e) {} }
		if (typeof(ret)!="undefined" && typeof(ret)!="null") return(ret);
	}
}
document.onmousedown=function(we){
	var ret=null;
	if (!we) we=window.event;
	try { ret=mousedown_func_last(we); } catch(e) {}
	try { ret=mousedown(we); } catch(e) {}
	if (typeof(ret)!="undefined" && typeof(ret)!="null") return(ret);
}

// onmousemove
var mousemove_func=new Array();
var mousemove_func_last=document.onmousemove;
function mousemove(p) {
	if (typeof(p)=="function") mousemove_func[mousemove_func.length]=p;
	else { for (var i in mousemove_func) { try { mousemove_func[i](p); } catch(e) {} } }
}
document.onmousemove=function(we){
	if (!we) we=window.event;
	try { mousemove_func_last(we); } catch(e) {}
	try { mousemove(we); } catch(e) {}
}

// mouse delta
var mousewheel_func=new Array();
function mousewheel(p) {
	if (typeof(p)=="function") mousewheel_func[mousewheel_func.length]=p;
	else { for (var i in mousewheel_func) { try { mousewheel_func[i](p); } catch(e) {} } }
}
function mousewheel_eventhandler(event) {
	var delta=0;
	if (!event) event=window.event; // IE
	if (event.wheelDelta) { // IE/Opera
		delta=event.wheelDelta/120;
		// In Opera 9, delta differs in sign as compared to IE.
		if (window.opera) delta=-delta;
	} else if (event.detail) { // Mozilla
		// In Mozilla, sign of delta is different than in IE. Also, delta is multiple of 3.
		delta=-event.detail/3;
	}
	// If delta is nonzero, handle it. Basically, delta is now positive
	// if wheel was scrolled up, and negative, if wheel was scrolled down.
	if (delta) {
		//handle(delta);
		var cancel=false;
		for (var i in mousewheel_func) { try { if (mousewheel_func[i](delta,event)) cancel=true; } catch(e) {} }
	}
	// Prevent default actions caused by mouse wheel. That might be ugly,
	// but we handle scrolls somehow anyway, so don't bother here..
	if (cancel) {
		if (event.preventDefault)
			event.preventDefault();
		event.returnValue=false;
	}
}
if (window.addEventListener) window.addEventListener('DOMMouseScroll', mousewheel_eventhandler, false); // DOMMouseScroll for Mozilla
window.onmousewheel=document.onmousewheel=mousewheel_eventhandler; // IE/Opera

// habilitar/deshabilitar seleccionar texto en un elemento
function selectionEnabled(o,enable) {
	var o=gid(o);
	if (typeof o.onselectstart!="undefined") { if (enable) o.onselectstart=null; else { o.onselectstart=function(){ return false; } } } // IE
	else if (typeof o.style.MozUserSelect!="undefined") { o.style.MozUserSelect=(enable?"":"none"); } //Firefox
	else { if (enable) o.onmousedown=null; else { o.onmousedown=function(){ return false; } } } // all other navs
	o.style.cursor="default";
}

// entrada slo numrica entera
function gInputInt(id,negatives,floating) {
	var input=gid(id);
	input.style.textAlign="right";
	input.onkeydown=function(e){
		var c=e.keyCode;
		if (c>=35 && c<=39) return true;
		if (c==8) return true;
		if (c==46) return true;
		if (c==116) return true;
		if (c==9) return true;
		if (c==13) return true;
		if (c==15) return true;
		if (floating)
			if (c==110 || c==190)
				return (this.value.indexOf(".")==-1?true:false);
		if (negatives)
			if (c==109)
				return (this.value.indexOf("-")==-1?true:false);
		if (c>=48 && c<=57) return true;
		return false;
	}
	input.onblur=function(e){
		var v=parseFloat(this.value);
		this.value=(isNaN(v)?"":v);
	}
}

// entrada slo numrica floatante
function gInputFloat(id,negatives) {
	gInputInt(id,negatives,true);
}

// eliminar espacios de una cadena
function trim(str) {
	return (""+str).replace(/^\s*|\s*$/g,"");
}

// elimina la ruta de un nombre de fichero completo,
// y tambin su sufijo, si se especifica y coincide
function basename(path, suffix) {
	var b=path.replace(/^.*[\/\\]/g, '');
	if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix)
		b=b.substr(0, b.length-suffix.length);
	return b;
}

// equivalente a br2nl en php
function br2nl(s) {
	return s.replace(/<br\s*\/?>/mg,"\n");
}

// mostrar un nmero en formato X.XXX,XX
function spf(n) {
	var n=Math.round(n*100)/100;
	var d=Math.round((n-parseInt(n))*100);
	var x=""+parseInt(n);
	var rgx=/(\d+)(\d{3})/;
	while (rgx.test(x))
		x=x.replace(rgx,'$1'+'.'+'$2');
	return x+","+d;
}

// convierte una cadena YYYY-MM-DD HH:II:SS a DD/MM/YYYY HH:II:SS
function sqlDateSP(d) {
	if (d.length!=10 && d.length!=19) return "";
	return d.substring(8,10)+"/"+d.substring(5,7)+"/"+d.substring(0,4)+d.substring(10);
}

// convierte una cadena DD/MM/YYYY HH:II:SS a YYYY-MM-DD HH:II:SS
function spDateSQL(d) {
	if (d.length!=10 && d.length!=19) return "";
	return d.substring(6,10)+"-"+d.substring(3,5)+"-"+d.substring(0,2)+d.substring(10);
}

