/*
Libreria de funciones generales de JavaScript
Version: $Id: common.js,v 1.4 2005/07/12 17:33:24 dgobera Exp $
*/

// Abrir una ventana para seleccionar registros
function l_select(script, returnFunc, l_baseurl, extra){
	var url="";
	if(l_baseurl!=undefined && l_baseurl.length>0) url=l_baseurl;
	url+="l_"+script+".php?ret="+returnFunc;
	if(extra!=undefined && extra.length>0) url+="&"+extra;
	ventana = window.open(url, "Select", "width=550,height=590,status=yes,resizable=yes,scrollbars=yes");
	ventana.focus();
}

// Abrir una ventana con el calendario para elegir una fecha
function calendario(forma, prefijoCampos) {
	dia = eval("document." + forma + "." + prefijoCampos + "_d.value");
	mes = eval("document." + forma + "." + prefijoCampos + "_m.value");
	anio = eval("document." + forma + "." + prefijoCampos + "_a.value");
    dateField = eval("document." + forma + "." + prefijoCampos);
    dateField.value = anio+"-"+mes+"-"+dia;
    dateType="date";
	window.open(baseurl+"l_calendario.php?form="+forma+"&field="+prefijoCampos, "Calendario", "width=400,height=200,status=yes");
}

// Confirmar eliminar un registro
function confEliminar(){
	if(window.confirm(deleteWarning)){
		document.forma.eliminar.value=1;
		document.forma.submit();
	}
}

// Presentar el cuadro de dialogo de imprimir
function printDoc(){
	window.focus();
	if(window.print){
		window.print();
	}
}


// Cargar un documento XML asincronamente del servidor via GET
var req;
function sendGetXML(url) {
	// Si soporta XMLHttpRequest nativamente
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		req.onreadystatechange = processReqChange;
		req.open("GET", url, true);
		req.send(null);
	// Si es IE/Windows ActiveX
	} else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange = processReqChange;
			req.open("GET", url, true);
			req.send();
		}
	}
}

// Enviar datos al servidor via POST y recibir la respuesta en XML
function sendPostXML(url, postData) {
	// Si soporta XMLHttpRequest nativamente
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		req.onreadystatechange = processReqChange;
		req.open("POST", url, true);
		req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		req.send(postData);
	// Si es IE/Windows ActiveX
	} else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange = processReqChange;
			req.open("POST", url, true);
			req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			req.send(postData);
		}
	}
}

// Procesar la respuesta del servidor en XML
function processReqChange(){
	// verificar que estemos en status "complete"
	if (req.readyState == 4) {
		// verificar que la respuesta sea status OK
		if (req.status == 200) {
			// objeto XML
			response  = req.responseXML.documentElement;
			// llamar al metodo que pidio el servidor
			method    = response.getElementsByTagName('method')[0].firstChild.data;
			eval(method + '(response)');
		}
	}
}   


// Abrir o cerrar una seccion plegable
// Recibe el nombre de la seccion
// En el documento debe existir un elemento fieldset con id=fieldset_"seccion"
// y una imagen con id=fieldset_arrow_"seccion"
function toggleSection(seccion, sufijo){
	// imagenes de flechas
	var imgPath=baseurl+iconsdir;
	var flechas= new Array("closedArrow"+sufijo+".gif", "openedArrow"+sufijo+".gif");
	// mostrar/ocultar el fieldset
	toggleDisplay("fieldset_"+seccion);
	// cambiar la imagen de la flecha
	img=getElement("fieldset_arrow_"+seccion);
	if(img.src.indexOf(flechas[0])>-1) img.src=imgPath+flechas[1];
	else img.src=imgPath+flechas[0];
}

// Mostrar u ocultar un elemento
function toggleDisplay(elementName){
	var object=getElement(elementName);
	if(object.style.display != 'none') object.style.display = 'none';
	else object.style.display = '';
}

// Obtener la referencia de un objeto a traves de su nombre
function getElement(e,f){
    if(document.layers){
        f=(f)?f:self;
        if(f.document.layers[e]) return f.document.layers[e];
        for(W=0;i<f.document.layers.length;W++) return(getElement(e,fdocument.layers[W]));
    }
    if(document.all) return document.all[e];
    return document.getElementById(e);
}

// Formatear un numero con separadores de miles
function format_number(num,decimalNum, twoDecimals){ 
	// configure
	bolLeadingZero=true;
	bolParens=false;
	bolCommas=true;

	if (isNaN(parseInt(num))) return "NaN";

	var tmpNum = num;
	var iSign = !(num >= 0) ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	if(twoDecimals) tmpNum = (tmpNum == Math.floor(tmpNum)) ? tmpNum + '.00' : (  (tmpNum*10 == Math.floor(tmpNum*10)) ? tmpNum + '0' : tmpNum);
	
	
	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}

	// See if we need to use parenthesis
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

	return tmpNumStr;		// Return our formatted string!
}


// ----------------------------
// Funciones basicas JavaScript
// ----------------------------

function isArray(a) {
    return isObject(a) && a.constructor == Array;
}

function isBoolean(a) {
    return typeof a == 'boolean';
}

function isEmpty(o) {
    var i, v;
    if (isObject(o)) {
        for (i in o) {
            v = o[i];
            if (isUndefined(v) && isFunction(v)) {
                return false;
            }
        }
    }
    return true;
}

function isFunction(a) {
    return typeof a == 'function';
}

function isNull(a) {
    return typeof a == 'object' && !a;
}

function isNumber(a) {
    return typeof a == 'number' && isFinite(a);
}

function isObject(a) {
    return (a && typeof a == 'object') || isFunction(a);
}

function isString(a) {
    return typeof a == 'string';
}

function isUndefined(a) {
    return typeof a == 'undefined';
} 