i_xbd_nVersion=0.209;
/*
	intelygenz  - www.intelygenz.com

	[DOC]	 M:\ig_intelygenz\ig05_intranet\desarrollo\areas\dev\docs\i_xbd.txt
	[UPDATE] M:\ig_intelygenz\ig05_intranet\desarrollo\areas\dev\libs\js\i_xbd.js

		open -> i_core.js, i_igz.js [, i_gfx.js] 		( i_xjs.js )

*/

oIGZ.f_loadLib("i_xbd", i_xbd_nVersion);
oIGZ.f_require("i_igz", 0.722);

oXBD =  new function (){
	this.m_sObj 	= "oXBD";
	this.m_nVersion = i_xbd_nVersion;
	this.m_sKey 	= "[i_xbd v"+i_xbd_nVersion+"]";

	this.m_nTimeoutMSG 	 = 1000;
	this.m_a_sDefaultMSG = ["cargando datos..."
						   ,"datos guardados correctamente"
						   ,"ocurrió un error al intentar guardar los datos"
						   ];

	// Manager de objetos XMLHttpRequest
	//
	this.m_maHttpReq = [["nReqId", "oHttpReq", "sSRC"], []];
	this.f_addHttpReq = function (sSRC){
		var nReqId = Date.UTC;
		var oHttpReq = new Object();
		oHttpReq.m_nReqId  = nReqId;
		oHttpReq.m_oXMLReq = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
		this.m_maHttpReq.f_maNewRow([nReqId, oHttpReq, sSRC]);
		return (oHttpReq);
	}
	this.f_delHttpReq = function (oHttpReq){
		var nReqId = oHttpReq.m_nReqId;
		var nReg = this.m_maHttpReq.f_maGetReg("nReqId", nReqId);
		this.m_maHttpReq.f_maDeleteRow(nReg);
	}

	this.f_openInNewWin = function (sSRC, oForm){
		if ( !IsNull(oForm) ) {
			sSRC = sSRC.f_replace("xjs=1&", "");	// RETROCOMPATIBILIDAD!!!
			sSRC = sSRC.f_replace("xjs=1", "");		// RETROCOMPATIBILIDAD!!!
			oForm.action = sSRC;
			oForm.target = "_blank";
			oForm.submit();
		}
		else {
			sSRC = sSRC.f_replace("xjs=1&", "");	// RETROCOMPATIBILIDAD!!!
			sSRC = sSRC.f_replace("xjs=1", "");		// RETROCOMPATIBILIDAD!!!
			NewWin("wXBD", sSRC);
		}
	}


	this.m_maTypes = [["sSendType", "nSendType"]
				  	 ,["DEFAULT"	, 0				// Tipo de Envio normal con todos los mensajes
				   	  ,"SHOWERRORS"	, 1			// Solo se muestran mensajes de error
				   	  ,"NOMSGS"		, 2				// No se muesta ningún mensaje
				   	  ,"USERMSGS"	, 3				// Solo se muestran mensajes si se le ha pasado sMSG_Element
				   	  ]
				  	 ];
	this.f_submitType = function (sSendType, vFormOrSRC, f_call, sMSG_Element, a_sMSGs, nSendMode) {
		var nSendType = this.m_maTypes.f_maGetValIf("nSendType", "sSendType", sSendType.toUpperCase(), 0);
		this.f_submit(vFormOrSRC, f_call, sMSG_Element, a_sMSGs, nSendMode, nSendType);
	}

	// Carga el retorno de una URL que tiene que devolver código JavaScript
	//
	this.f_submit = function (vFormOrSRC, f_call, sMSG_Element, a_sMSGs, nSendMode, nSendType) {
		var oMSG_Element = null;
		var sSRC = vFormOrSRC;
		var oForm = null;
		// Verifica si vFormOrSRC es un Objeto FORM o un URL
		if ( GetType(vFormOrSRC) != String && vFormOrSRC.action ) {
			oForm = vFormOrSRC
			sSRC  = oForm.action;
		}
		sSRC = sSRC.f_replace("xjs=1", "xjs=0");	// RETROCOMPATIBILIDAD!!!

		if ( sSRC ) {
			// Hace submit clásico en una ventana nueva, solo para DEBUG !
			if (nSendMode==2) {
				this.f_openInNewWin(sSRC, oForm);
			}
			else {
				// Verifica si se ha especificado id de un elemento DOM donde cargar los mensajes automáticos
				if ( sMSG_Element ) {
					oMSG_Element = GetElement(sMSG_Element);
					// Verifica si existe el elemento DOM sMSG_Element en la página
					if ( oMSG_Element==null ) {
						ErrorJS("No existe el elemento '"+sMSG_Element+"' en la página '"+document.location.href+"'","",1);
					}
				}
				else {
					// nSendType=3 -> No muestra mensajes si el usuario no ha mandado sMSG_Element
					if ( nSendType != 3 ) {
						this.f_createElementMSG();
						oMSG_Element = this.m_oMSG;
						if ( oMSG_Element.id == this.m_sIdMSG ) {
							this.f_rePositionAutoMSG();
						}
					}
				}

				if ( !a_sMSGs || IsNull(a_sMSGs) || !IsArray(a_sMSGs) ) a_sMSGs = this.m_a_sDefaultMSG;
				else {
					for ( var f = 0, F = this.m_a_sDefaultMSG.length; f<F; f++ ) {
						if ( f>=a_sMSGs.length || IsNull(a_sMSGs[f]) ) a_sMSGs[f] = this.m_a_sDefaultMSG[f];
					}
				}

				// Si el envío es multipart se hace por IFrame oculto
				if (!IsNull(oForm) && oForm.enctype.toUpperCase().indexOf("MULTIPART")!=-1 ) {
					oForm.method = "POST";
					this.f_submitIFrame(sSRC, oForm, f_call, oMSG_Element, a_sMSGs, nSendType);
				}
				else {
					this.f_submitXMLHttpRequest(sSRC, oForm, f_call, oMSG_Element, a_sMSGs, nSendType);
				}
			}
		}
	}

	this.f_submitXMLHttpRequest = function (sSRC, oForm, f_call, oMSG_Element, a_sMSGs, nSendType) {
		// Crea objeto XmlHttpRequest
		var oHttpReq = this.f_addHttpReq(sSRC);
		var oXMLReq  = oHttpReq.m_oXMLReq;

		// Espera Respuesta del servidor
		oXMLReq.onreadystatechange = function (){
			// readyState=4 Indica que el fichero de vuelta ya ha sido descargado completamente
			if (oXMLReq.readyState == 4) {
				// status=200 Indica que el fichero existe y que no ha dado errores 500 en el servidor
		        if (oXMLReq.status == 200 ) {
		        	// Carga todo el contenido del fichero devuelto
		        	var sResponse = oXMLReq.responseText;
		        	// try Comprueba que sResponse es código JavaScript válido
					try {
						eval( sResponse );	// carga todo el codigo javascript en la página
					}
					catch(e){
						// en desarrollo automáticamente abre una ventana con el error											
						if (oCore.m_sServer=="DEV") {
							oXBD.f_openInNewWin(sSRC, oForm);
						}
						// muestra mensaje de error si el contenido del fichero no es código JavaScript válido
						oXBD.f_error ("\nERROR EN EL JAVASCRIPT DEVUELTO\n\n"+ErrorEx(e)+"\n\n"+sResponse, sSRC, "JS", oMSG_Element, a_sMSGs[2], nSendType)
					}
					// el servidor puede mandar errores controlados al cliente para lo cual xbd_error debe existir y ser distinto de 0 o false
					if ( GetType("xbd_error", 1) && xbd_error!="" && xbd_error!=0 ) {
						// muestra mensaje de error controlado
						oXBD.f_error ("", sSRC, "XBD", oMSG_Element, xbd_error, nSendType);
					}
					else if ( GetType("xjs_error", 1) && xjs_error!="" && xjs_error!=0 )	{ // RETROCOMPATIBILIDAD!!!
						// muestra mensaje de error controlado
						oXBD.f_error ("", sSRC, "XJS", oMSG_Element, xjs_error, nSendType);
					}
					else if ( GetType("xbd_warning", 1) && xbd_warning!="" && xbd_warning!=0 ) {
						// muestra mensaje de aviso controlado
						oXBD.f_warning (oMSG_Element, xbd_warning, nSendType);
					}
					else {
						// si hay funcion de retorno se ejecuta
						try {
							if (f_call) f_call();
							// muestra mensaje de que todo ha ido bien
							if ( !IsNull(oMSG_Element) ) oXBD.f_message( oMSG_Element, a_sMSGs[1], "OK", oXBD.m_nTimeoutMSG, nSendType);
						}
						catch (e) {
							// muestra mensaje de error en la función
							oXBD.f_error ("\nERROR EN LA FUNCIÓN DE RETORNO.\n\n"+f_call+"\n\n"+ErrorEx(e), sSRC, "JS", oMSG_Element, a_sMSGs[2], nSendType);							
						}
					}
				}
				else if(oXMLReq.status==500) { 		// Error 500 de servidor 
					// en desarrollo automáticamente abre una ventana con el error
					if (oCore.m_sServer=="DEV") {
								oXBD.f_openInNewWin(sSRC, oForm);
					}
					// mensaje de error de servidor
					oXBD.f_error ("\nERROR EN LA RESPUESTA DEL SERVIDOR\n\n"+oXMLReq.responseText, sSRC, oXMLReq.status, oMSG_Element, a_sMSGs[2], nSendType);
				}
				else if(oXMLReq.status==404) {		// Error 404 de que no existe la página
					// mensaje de error de que la url no existe
					oXBD.f_error ("\nNO SE HA ENCONTRADO LA PÁGINA\n", sSRC, oXMLReq.status, oMSG_Element, a_sMSGs[2], nSendType)
				}
				else {
					// mensaje de error no controlado
					oXBD.f_error ("\nERROR NO CONTROLADO EN EL RETORNO DEL FICHERO "+sSRC+"\n\n"+oXMLReq.getAllResponseHeaders()+"\n\nCONTENT:\n"+oXMLReq.responseText, sSRC, "ERROR!",oMSG_Element, a_sMSGs[2], nSendType);
				}
			}
		}

		// El método de envío es siempre GET cuando se envía una URL
		// y POST cuando se envía un FORM
		var sMethod = "GET";
		if (!IsNull(oForm)) sMethod = "POST";

		// mensaje de carga, aparece mientras se espera a la respuesta del servidor
		if ( !IsNull(oMSG_Element) ) oXBD.f_message( oMSG_Element, a_sMSGs[0], "MSG", 0, nSendType);

		// Timeout de 1ms es necesario para que se muestra el mensaje de carga
		setTimeout( function () {
						// Abre conexión con la URL, se pasa siempre true para que la conexión se asíncrona
						oXMLReq.open( sMethod, sSRC, true );

						// Se especifica el content type como FORM asi se pueden hacer multipart
						oXMLReq.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded;" );
				
						// Se envía el formulario en formato urlencoded
//alert( oXBD.f_form2String( oForm ) )
						oXMLReq.send( oXBD.f_form2String( oForm ) );
// oXBD.f_delHttpReq( oHttpReq );
					}
				, 1
				);
	}

	this.m_nIF = 0;
	this.f_submitIFrame = function (sSRC, oForm, f_call, oMSG_Element, a_sMSGs, nSendType) {
		// El método de envío es siempre POST y Multipart
		this.m_nIF++;
		// mensaje de carga, aparece mientras se espera a la respuesta del servidor
		if ( oMSG_Element !=null ) oXBD.f_message( oMSG_Element, a_sMSGs[0], "MSG", 0, nSendType);
		var oIFrame = oIFRAME.f_create(document.getElementsByTagName("BODY")[0]
									  ,"IFRAME_XBD_Multipart_"+this.m_nIF
									  ,""
									  ,0, 0, 0, 0, "style='display: none;'"
									  , function (){
									  		oIFrame.f_onload = function (){
												var sResponse = oIFrame.contentWindow.document.body.innerHTML;
												try {
													eval( sResponse );	// carga todo el codigo javascript en la página												
												}
												catch(e){
													// en desarrollo automáticamente abre una ventana con el error											
													if (oCore.m_sServer=="DEV") {
														oXBD.f_openInNewWin(sSRC, oForm);
													}
													// muestra mensaje de error si el contenido del fichero no es código JavaScript válido
													oXBD.f_error ("\nERROR EN EL JAVASCRIPT DEVUELTO AL ENVIAR MULTIPART.\n\n"+ErrorEx(e)+"\nVerifique si la ruta es correcta: "+sSRC+"\nVerifique si la respuesta es código JavaScript correcto "+sResponse, sSRC, "MULTIPART", oMSG_Element, a_sMSGs[2], nSendType)
												}
												// el servidor puede mandar errores controlados al cliente para lo cual xbd_error debe existir y ser distinto de 0 o false
												if ( GetType("xbd_error", 1) && xbd_error!="" && xbd_error!=0 ) {
													// muestra mensaje de error controlado
													oXBD.f_error ("", sSRC, "XBD", oMSG_Element, xbd_error, nSendType);
												}
												else if ( GetType("xjs_error", 1) && xjs_error!="" && xjs_error!=0 ) {	// RETORCOMPATIBILIDAD!!!
													// muestra mensaje de error controlado
													oXBD.f_error ("", sSRC, "XJS", oMSG_Element, xjs_error, nSendType);
												}
												else if ( GetType("xbd_warning", 1) && xbd_warning!="" && xbd_warning!=0 ) {
													// muestra mensaje de aviso controlado
													oXBD.f_warning (oMSG_Element, xbd_warning, nSendType);
												}
												else {
													// si hay funcion de retorno se ejecuta
													try {
														if (f_call) f_call();
														// muestra mensaje de que todo ha ido bien
														oXBD.f_message( oMSG_Element, a_sMSGs[1], "OK", oXBD.m_nTimeoutMSG, nSendType);
													}
													catch (e) {
														// muestra mensaje de error en la función
														oXBD.f_error ("\nERROR EN LA FUNCIÓN DE RETORNO.\n\n"+f_call+"\n\n"+ErrorEx(e), sSRC, "JS", oMSG_Element, a_sMSGs[2], nSendType);
													}
												}
									  		}
									  		oForm.target = oIFrame.name;
									  		oForm.submit();
									  	}
									  );

	}

	// RETROCOMPATIBILIDAD!!!
	// DEPRECATED !!!  Llama a this.f_submit 
	this.f_load = function (vFormOrSRC, f_call, oForm, nSendMode, sMSG_Element, a_sMSGs){
		if ( oForm ) {
			if ( vFormOrSRC != oForm ) oForm.action = vFormOrSRC;
			vFormOrSRC = oForm;
		}
		this.f_submit (vFormOrSRC, f_call, sMSG_Element, a_sMSGs, nSendMode) 
	}
	// RETROCOMPATIBILIDAD!!!
	// DEPRECATED!!! Llama a this.f_load
	this.f_reloadXJS = function (sSRC, f_call, oForm){ this.f_load (sSRC, f_call, oForm); }

	// Convierte objeto FORM en WWW-FORM-URLENCODED
	this.f_form2String = function (oForm){
		if ( !g_a_vFixAtSubmit ) ErrorJS("ATENCION! Si utilizas XBD sin i_form algunos campos podrían enviarse en el formato correcto");
		var oInput, sType, sName, a_vValues = [], a_sStringForm = [];
		if (!IsNull(oForm) && oForm.length>0) {
			var g, G;
			var f=-1, K = oForm.length;
			while ( ++f < K ) {
				oInput = oForm[f];
				sName  = oInput.name;
				if (sName) {
					sType = String(oInput.type).toUpperCase();
					sIFormType = sName.substring(0, 1);
					if (sType.indexOf("SELECT")!=-1){
						if (sType.indexOf("MULTIPLE")!=-1){
							if (sIFormType.toUpperCase() == "Y") {
								for ( g=0, G=oInput.options.length; g<G; g++ ) {
									a_vValues.push( oInput.options[g].value );
								}
							}
							else {
								for ( g=0, G=oInput.options.length; g<G; g++ ) {
									if ( oInput.options[g].selected ) {
										a_vValues.push( oInput.options[g].value );
									}
								}
							}
						}
						else {
							if (oInput.selectedIndex!=-1 && oInput[oInput.selectedIndex].value) {
								a_vValues.push( oInput[oInput.selectedIndex].value );
							}
						}
					}
					else if ( sType=="CHECKBOX" && sIFormType == "K"){
						if ( !oInput.checked ) a_vValues.push( 0 );
						else a_vValues.push( oInput.value );
					}
					else if ( (sType!="CHECKBOX" && sType!="RADIO") || oInput.checked) {
						a_vValues.push( oInput.value );
					}
					if ( a_vValues.length > 0 ) {
						for ( g = 0, G = a_vValues.length; g<G; g++ ) {
							vValue = escape( this.f_fixValue(sName, a_vValues[g]) );
							vValue = vValue.f_replace("+", encodeURIComponent("+"));
							a_sStringForm.push(sName+"="+vValue+"&");
						}
						a_vValues = [];
					}
				}
			}
		}
		return (a_sStringForm.join(""));
	}

	this.f_fixValue = function (sName, vValue) {
		if ( g_a_vFixAtSubmit ) {
			var nIdx = g_a_vFixAtSubmit.f_indexOf(sName);
			if ( nIdx!=-1 ) vValue = g_a_vFixAtSubmit[nIdx+1];
		}
		return (vValue);
	}
	
	// Mensajes de error para el cliente
	this.f_error = function ( sError, sSRC, nError, oMSG_Element, sErrorMSG, nSendType ) {	
		// sError = "" cuando son errores controlados de servidor (xbd_error)
		var nModo=4;
		if ( oMSG_Element !=null ) {
			sColor    = "ERROR";
			if ( sError ) sErrorMSG ="<DIV onclick='ErrorJS()' style='cursor:pointer' title='Pulsa para ver la descripción del error'><B><U>[ERROR "+nError+"]</U></B> " + sErrorMSG + "</DIV>"
			else sErrorMSG = "<DIV onclick='oIGZ.f_closeMSG(this)' style='cursor:pointer' title='Ocultar Aviso'>" +sErrorMSG+ "</DIV>"
			oXBD.f_message( oMSG_Element, sErrorMSG, sColor, 0, nSendType);
			if (oCore.m_sServer!="DEV") nModo=0
		}
		if (sError) ErrorJS(oXBD.m_sKey+" ("+sSRC+")\n"+sError,"",nModo);
	}

	// Mensajes de aviso para el cliente
	this.f_warning = function ( oMSG_Element, sWarningMSG, nSendType ) {
		if ( oMSG_Element !=null ) {
			sColor    = "WARNING";
			sWarningMSG = "<DIV onclick='oIGZ.f_closeMSG(this)' style='cursor:pointer' title='Ocultar Aviso'>" +sWarningMSG+ "</DIV>"
			oXBD.f_message( oMSG_Element, sWarningMSG, sColor, 0, nSendType);
		}
	}

	// Colores de DrawMSG
	// 	0 :	Error (Rojo) ,  1 : OK (Verde) , 2 : Aviso (Amarillo) , por defecto Mensaje (Azul)
	this.f_message =  function (oMSG_Element, sMsg, sType, nTimeOut, nSendType) {

		var nMSGColor;
		switch ( sType ) {
			case "OK" :
				nMSGColor = 1;
				break;
			case "ERROR" :
				nMSGColor = 0;
				nTimeOut  = 0;
				break;
			case "WARNING" :
				nMSGColor = 2;
				nTimeOut  = 0;
				break;
		}

		if ( nSendType==1 && nMSGColor!=0 && nMSGColor!=2 ) {	// nSendType=1 -> Solo mostrar mensajes de error
			nSendType = 2;						// Si nMSGColor!=0 es que no es un error
		}

		if ( nSendType!=2 ) {	// nSendType=2 -> No mostrar nunca ningún mensaje
			oMSG_Element.innerHTML = oIGZ.f_drawMSG(sMsg, nMSGColor);
	
			if ( nTimeOut > 0 ) {
				if ( GetType("oGFX", 1) && sType!="ERROR") {
					oGFX.f_fade (oMSG_Element, 100, 0, nTimeOut/10, 10, function (){ if (sType!="ERROR") { oMSG_Element.innerHTML = ""; } } );
				}
				else {
					oMSG_Element.stMessage = setTimeout( function () { if (sType!="ERROR") { oMSG_Element.innerHTML = ""; } }, nTimeOut );
				}
			}
			else if ( GetType("oGFX", 1) ) {
				if ( oMSG_Element.stMessage ) clearTimeout(oMSG_Element.stMessage);
				oGFX.f_fadeStop(oMSG_Element);
				oGFX.f_opacity (oMSG_Element, 100);
			}
		}
	}

	this.m_sIdMSG = "DIV_XBD_AutoMSG";
	this.m_oMSG = null;
	this.f_createElementMSG = function () {
		if ( IsNull(this.m_oMSG) ) {
			this.m_oMSG = document.createElement("DIV");
			this.m_oMSG.setAttribute("id", this.m_sIdMSG);
			this.m_oMSG.style.position = "absolute";
			this.m_oMSG.style.left = 0;
			this.m_oMSG.style.top  = 0;
			document.getElementsByTagName("BODY")[0].appendChild( this.m_oMSG );
		}
	}
	this.f_rePositionAutoMSG = function (){
		this.m_oMSG.style.left = oIGZ.m_nMouseX;
		this.m_oMSG.style.top  = oIGZ.m_nMouseY;
	}
}

oIGZ.f_mouseMoveOn();

// RETROCOMPATIBILIDAD!!!
oXJS = oXBD; 
oIGZ.m_a_sStartDraws.push("<FUN>oXJS=oXBD;");

