﻿// Escalar una imagen <objIMG> guardando corréctamente la proporción
function imgScale(objIMG, pxMaxWidth, pxMaxHeight) {
	
	if(objIMG!=undefined && objIMG!=null) {
		
		var imgw = parseInt(objIMG.width);
		var imgh = parseInt(objIMG.height);
		
		if(imgw * pxMaxHeight > imgh * pxMaxWidth ) {
			
			if(imgw>=1)
				objIMG.style.height=parseInt( (pxMaxWidth * imgh)/imgw).toString() + 'px';
			else
				objIMG.style.height='1px';
				
			objIMG.style.width= pxMaxWidth.toString() + 'px';
			
		} else {
			
			if(imgh>=1)
				objIMG.style.width=parseInt( ( pxMaxHeight * imgw )/imgh).toString() + 'px';
			else
				objIMG.style.width='1px';
				
			objIMG.style.height=pxMaxHeight.toString() + 'px';
		}
		
	}	
	//Informa tamaño si es necesario.
	if (componentActId != undefined && componentActId != null) {      
        SendInfo2IFrameCtrl(componentActId);
    }
}

// Verificar que los INPUT hijos de un elemento verifican las restricciones impuestas (Obligatoriedad, Numérico)
// Devuelve FALSE si algun elemento no verifica las restricciones.
// Devuelve TRUE si todo está ok.
function _DataRangeVerify(objRoot, errMsg, errMsgButtonValue) {
	objRoot = $(objRoot);
	if( typeof(objRoot)!='undefined' && objRoot!=null) {
		var errorFound = false;
		
		var childs = Form.getElements(objRoot);
		for(var ix=0; ix<childs.length; ix++) {
			var fldError = false;
			var ctrl = childs[ix];
			if( typeof(ctrl.attributes["required"])!='undefined' ) {
				if(ctrl.tagName=='INPUT' || ctrl.tagName=='SELECT' || ctrl.tagName=='TEXTAREA') {
					fldError |= ctrl.value == undefined || ctrl.value==null || ctrl.value=='';
				}
			}
			if( typeof(ctrl.attributes["numeric"])!='undefined' ) {
				fldError |= 
					ctrl.value!=undefined && ctrl.value!=null && ctrl.value!='' 
					&& isNaN( parseFloat( ctrl.value) );
			}
			if( typeof(ctrl.attributes["email"])!='undefined' ) {
				fldError |= 
					ctrl.value!=undefined && ctrl.value!=null && ctrl.value!='' 
						&& !isMail( ctrl.value );
			}
			if( typeof(ctrl.attributes["date"])!='undefined') {
				fldError |= 
					ctrl.value!=undefined && ctrl.value!=null && ctrl.value!='' 
						&& !esFecha(ctrl.value);
			}
			// El elemento a resaltar puede no ser el elemento que contiene el valor			
			if(ctrl.tagName=='TEXTAREA' && typeof(ctrl.attributes["richtext"])!='undefined' ) {
				ctrl=ctrl.nextSibling; // Div visible.
			} else {
			}
		
			if(fldError) {
				ctrl.style.backgroundColor='#FF8080';
				ctrl.style.color='Black';
				ctrl.style.borderColor='Red';
			} else {
				ctrl.style.backgroundColor='';
				ctrl.style.color='';
				ctrl.style.borderColor='';
			}
			errorFound|=fldError;
		}
		if(errorFound)
		    if (errMsg!=null && errMsg!='undefined'){
		     if (errMsgButtonValue!=null && errMsgButtonValue!='undefined'){
		         Dialog.alert(errMsg, {windowParameters: {className:"floatwindow", width:300, height:80}, okLabel: errMsgButtonValue}	);
		     }else{
		         Dialog.alert(errMsg, {windowParameters: {className:"floatwindow", width:300, height:80}, okLabel: "Ok"}	);
		     }   
		    }else{
			Dialog.alert("Revise los campos resaltados en rojo", {windowParameters: {className:"floatwindow", width:300, height:80}, okLabel: "Aceptar"}	);
			}
		return !errorFound;
	}
}
function isMail(Cadena) {
	Punto = Cadena.substring(Cadena.lastIndexOf('.') + 1, Cadena.length)	;		// Cadena del .com
	Dominio = Cadena.substring(Cadena.lastIndexOf('@') + 1, Cadena.lastIndexOf('.')); 	// Dominio @lala.com
	Usuario = Cadena.substring(0, Cadena.lastIndexOf('@'));					// Cadena lalala@
	Reserv = "@/º\"'+*{}\\<>?¿[]áéíóú#·¡!^*;,:";						// Letras Reservadas
	// Añadida por El Codigo para poder emitir un alert en funcion de si email valido o no
	valido = true;
	// verifica qie el Usuario no tenga un caracter especial
	for (var Cont=0; Cont<Usuario.length; Cont++) {
		X = Usuario.substring(Cont,Cont+1);
		if (Reserv.indexOf(X)!=-1)	return false;
	}
	// verifica qie el Punto no tenga un caracter especial
	for (var Cont=0; Cont<Punto.length; Cont++) {
		X=Punto.substring(Cont,Cont+1);
		if (Reserv.indexOf(X)!=-1) return false;
	}
	// verifica qie el Dominio no tenga un caracter especial
	for (var Cont=0; Cont<Dominio.length; Cont++) {
		X=Dominio.substring(Cont,Cont+1);
		if (Reserv.indexOf(X)!=-1) return false;
	}
	// Verifica la sintaxis básica.....
	if (Punto.length<2 || Dominio <1 || Cadena.lastIndexOf('.')<0 || Cadena.lastIndexOf('@')<0 || Usuario<1) {
		return false;
	}

	return true;
}
  
function esFecha(value) {
	
  if (typeof value == 'string') 
		value = value.split('/').reverse();  

  var d = parseInt(value.pop(), 10);
  var m = parseInt(value.pop(), 10) - 1;
  var y = parseInt(value.pop());
  var date = new Date(y, m, d);
  return (
    (date.getFullYear() == y)
    &&
    (date.getMonth() == m)
    &&
    (date.getDate() == d) 
  );
} 
function tvnClick(evt,nodeId,nwValue){
	nodeId = $(nodeId);	
	
	if(nwValue==undefined) nwValue='';
	nodeId.value=nwValue;
	if(!evt) evt=window.event;
	evt.cancelBubble = true;
	if(nodeId.onchange!=undefined) nodeId.onchange.call(evt);
}
function lvrwClick(element,evt,nodeId,nwValue){
	// Cambiar estilo:seleccionado deja de serlo
	var parent = element.parentNode;
	if(parent) {	
		var children = parent.childNodes;
		for (var i = 0; i < children.length; i++) 
		{
			if(children[i].className=="lvw_rs") children[i].className="lvw_r";
		};
	}	
	// Nuevo seleccionado
	element.className="lvw_rs";
	// Cambiar valor
	nodeId = $(nodeId);
	if(nwValue==undefined) nwValue='';
	nodeId.value=nwValue;
	// No propagar el evento 
	if(!evt) evt=window.event;
	evt.cancelBubble = true;
	//Si nodoId tiene un "onchange", lanzarlo
	if(nodeId.onchange!=undefined) nodeId.onchange.call(evt);
}

// Llamada cuando un objeto Pagina se crea.  Puede ser usado para revisar
// el contenido de controles.
function _ConstruirControles(oContainer) {

}
// Upload de un fichero.
// sid: Identificador de la sesión de trabajo del usuario.
// fld: Campo al que se vincula el upload.  Si el upload tiene éxito, se asignará en este campo la "clave" del fichero.
// onlyimage:  Solo se desean imágenes, los otros ficheros deben descartarse. Soportados .gif.jpg.jpeg.bmp.png
function pupFileUpload(sid, fld, onlyimage) {
	if($('fUploadWindow'))	return; // Solo una Vtn de upload a la vez
	if($(fld)) {
		var fldId=$(fld).id;
		var surl = "Pups/UploadFichero.aspx?SID=" + sid;
		var stitulo = "Subir ";
		if(typeof(onlyimage)!='undefined' && onlyimage) {
			surl+="&IMAGEN=1";
			stitulo = "imagen";
		} else 
			stitulo = "fichero";
			 
		var win = new Window('fUploadWindow', 
			{
				className: "floatwindow", 
				title: stitulo, 
				width:300, height:200, 
				resizable: false, maximizable:false, minimizable:false, draggable:true,
				closable: true,
				url: surl, 
				showEffectOptions: {duration:1},
				hideEffectOptions: {duration:1}
			}
		);
		win.setDestroyOnClose();
		win.setZIndex(1000);
		win.showCenter(true,null,null);
		$('fUploadWindow').onOk = function(ServerFileKey, ServerFileName) {
			
			if(typeof(ServerFileKey)!='undefined' && ServerFileKey!='') {
				if( $(fldId) ) {
				 $(fldId).value = ServerFileKey;
				 if(typeof(ServerFileName)!='undefined') 
					$(fldId).nextSibling.innerHTML = ServerFileName; // Div con el nombre visible del fichero.

				}
			}
			$('fUploadWindow').onOk = null;
			Windows.close('fUploadWindow');
		}
	}
}
var nvid=0;
function newWinId(sPrefix) {
	nvid++;
	return sPrefix + nvid;
}
// Editar mediante editor de texto rico el contenido de un campo.
// fld: Campo al que se vincula el editor.
// title: título a mostrar en la ventan.
function pupEditorHTML(fld, title) {
	
	if($('fRichTextEditor'))	return; // Solo una Vtn de upload a la vez
	if($(fld)) {
		var fldId = $(fld).id;
		var surl = "Pups/EditorHtml.aspx";
		var win = new Window('fRichTextEditor' , 
			{
				className: "floatwindow", 
				title: (typeof(title)!='undefined')?title:"Editor de textos", 
				url: surl,
				width: 500,
				height: 500,
				centered: true,
				resizable: false, maximizable:false, minimizable:false, draggable:true,
				closable: true,
				showEffectOptions: {duration:0},
				hideEffectOptions: {duration:0}			
			}
		);
		win.setDestroyOnClose();
		win.setZIndex(1000);
		win.showCenter(true);
		
		$('fRichTextEditor').onOk = function(nwValue) {
			try {
				if(typeof(nwValue)!='undefined' && nwValue!=null) {
					if($(fldId)) {
						$(fldId).value = nwValue; // Campo oculto.
						$(fldId).nextSibling.innerHTML = nwValue; // Div con el texto visible
					}
				}
			} catch(e) {}
			Windows.close('fRichTextEditor');
		}
		
		$('fRichTextEditor').onValueRequest = function() {
			if($(fldId)) 	
				return $(fldId).value;
			else
				return "";
		}
		// Falta anular las funciones onValueRequest y onOk
	}
}
// Abrir Fichero en Vtn Nueva
function pupFileOpen(surl) { 
	window.open(surl, '', '')
}
// Abrir (ver) una imagen
function pupImageOpen(surl, stitulo) {
	var win = new Window(newWinId('fShowWindow'), {
			className: "floatwindow", 
			title: (typeof(stitulo)=='undefined')?"Ver Imagen":stitulo, 
			width:'600px', height:'500px', 
			resizable: true, maximizable:true, minimizable:true, draggable:true,
			closable: true,
			showEffectOptions: {duration:1},
			hideEffectOptions: {duration:1}		
		}
	);
	win.setDestroyOnClose();
	win.setZIndex(1000);
	win.getContent().innerHTML = "<img src=\"" + surl+ "\" />";
	win.showCenter(false,null,null);
}

// Editar color mediate ventana PickColor.
// fld: Campo al que se vincula al PickColor.
// title: título a mostrar en la ventan.
function pickColor(fld, title) {
	if($('fPickColor'))	return; // Solo una Vtn de upload a la vez
	if($(fld)) {
		var fldId = $(fld).id;
		var surl = "Pups/ColorPicker.html";
		var win = new Window('fPickColor' , 
			{
				className: "floatwindow", 
				title: (typeof(title)!='undefined')?title:"Selector de color", 
				url: surl,
				width: 500,
				height: 300,
				centered: true,
				resizable: false, maximizable:false, minimizable:false, draggable:true,
				closable: true,
				showEffectOptions: {duration:1},
				hideEffectOptions: {duration:1}			
			}
		);
		win.setDestroyOnClose();
		win.setZIndex(1000);
		win.showCenter(true);
		
		$('fPickColor').onOk = function(nwValue) {
			try {
				if(typeof(nwValue)!='undefined' && nwValue!=null) {
					if($(fldId)) {
						$(fldId).value = nwValue; 						
					}
				}
			} catch(e) {}
			Windows.close('fPickColor');
		}
		
		$('fPickColor').onValueRequest = function() {
			if($(fldId)) 				    
				return $(fldId).value;
			else
				return "";
		}
		$('fPickColor').finalizar = function() {
		    $('fPickColor').onValueRequest = null;
		    $('fPickColor').onOk = null;
		}
		// Falta anular las funciones onValueRequest y onOk
	}
}