<?php

	global $base_url;
	$urlxmls = $base_url."/";

    drupal_add_css("formularios/dhtmlx/dhtmlx.css");	  
    drupal_add_js("formularios/dhtmlx/dhtmlx.js");
    drupal_add_js("formularios/dhtmlx/dhtmlxgrid_group.js");
    drupal_add_css("formularios/dhtmlx/dhtmlxvault.css");	  
    drupal_add_js("formularios/dhtmlx/dhtmlxvault.js");
    drupal_add_css("formularios/dhtmlx/dhtmlxdataview.css");	  
    drupal_add_js("formularios/dhtmlx/dhtmlxdataview.js");
?>

<div id="form_container" style="width:1000px;"></div>
<script type="text/javascript">

var grid1, grid2, grid3, grid4, view;

function limpiar(f)
{
	f.clear();
	grid1.clearAll();
	grid2.clearAll();
}

function doGrid(name, value) {	
	var f = this.getForm();
	//if (value==1)
	//	myHeight = 497;
	//else
		myHeight = 300;

	if (value==3)
		myWidth = 480;
	else if(value==4)
		myWidth = 360;
	else
		myWidth = 390;

	return '<div id="grid_container' + value + '" style="width:'+myWidth+'px;height:'+myHeight+'px;"></div>';
}

function doImage(name, value) {	
	var f = this.getForm();
	if (value) {
		return '<img src="<?php echo $urlxmls; ?>formularios/logos/' + value + '" width="100" />';
	}
}

function doVault(name,value){
	return '<div id="view_container" style="width:430px;height:300px;border:1px solid #A4BED4;"></div><div id="vault" style="width:430px;"></div>';
}

function doImgManager()
{
	var cbs = "<?php echo $urlxmls; ?>formularios/dhtmlx/";
	view = new dhtmlXDataView({
		container:"view_container",
		type:{
			template:"<img src='#Image#' width='80' />",
			width:80,
			height:60
		}
	});
	view.load("<?php echo $urlxmls; ?>formularios/data/estructura.php?op=files", "xml");
	
	var hdlr = cbs + "handlers/";
	var vault = new dhtmlXVaultObject();
	with(vault)
	{
		setImagePath(cbs + "imgs/");
		setServerHandlers(hdlr + "UploadHandler.php", hdlr + "GetInfoHandler.php", hdlr + "GetIdHandler.php"); 
		
		onAddFile = function(fileName){
			var ext = this.getFileExtension(fileName);
			var fn = fileName.substring(0,lastIndexOf('.'));
			if (ext  == 'jpg' || ext == 'png' || ext == 'bmp' || ext == 'gif')
			{
				if(fn.indexOf('.') < 0 && fn.indexOf('/') < 0)
					return true;
				else
					alert("No se puede subir archivos con caracteres especiales en el nombre"); 
			}
			else
				alert("Sólo se permite subir ficheros de imágenes (jpg, png, bmp, gif)"); 
        	return false; 
   		};
		
		onFileUploaded = function(file) { 
			view.load("<?php echo $urlxmls; ?>formularios/data/estructura.php?op=files", "xml");
   		};
	
		strings.remove = "Eliminar"; 
	    	strings.done = "Finalizado";        // Error

		strings.btnAdd = "<?php echo t('Agregar'); ?>";
        	strings.btnUpload = "<?php echo t('Subir'); ?>";
        	strings.btnClean = "<?php echo t('Limpiar'); ?>";

		create("vault");
	}
}

function elimina()
{
	if(confirm ("Esta seguro que desea eliminar el elemento seleccionado?"))
	{
		
		var item = folders.getItem(folders._activeItemId);
	    	var xmlNode = item.data.dataObj;
		var fname = xmlNode.getAttribute('name');
		var loader = dhtmlxAjax.getSync("<?php echo $urlxmls; ?>formularios/data/estructura.php?op=delfiles&name="+fname);
		var msg = loader.xmlDoc.responseText;
		if(msg)
			alert(msg);
		folders.clearAll();
		folders.loadXML("<?php echo $urlxmls; ?>formularios/data/estructura.php?op=files", cbs + "types/ficon.xsl");
	}
}


function isNumber(n)
{
	if (!isNaN(parseFloat(n)) && isFinite(n))
  	{
  		if(n.indexOf(',')!=-1 || n.indexOf(',')!=-1)
  		{
			alert('Ingrese un número sin decimales');
			return false;
  		}
  		return true;
  	}
	alert('El valor ingresado debe ser un número');
	return false;
}

var struc = [
	{type:"block", width: 902, list:[
		{type:"fieldset", name:"frdepartamentos", width:440, list:[
			{type:"label", label:"<?php echo t('Departamentos'); ?>", labelWidth:390},
			{type: "template", name: "departamentos", label: "", value:"1", format: "doGrid", inputWidth:390},
			{type:"block", width: 390, list:[
					{type:"button", name:"deptoagregar", value:"<?php echo t('Agregar'); ?>", offsetLeft:10, offsetTop:10},
					{type:"newcolumn"},
					{type:"button", name:"deptoeditar", value:"<?php echo t('Editar'); ?>", offsetLeft:10, offsetTop:10},
					{type:"newcolumn"},
					{type:"button", name:"deptoeliminar", value:"<?php echo t('Eliminar'); ?>", offsetLeft:20, offsetTop:10}
			]}  
		]},
		{type:"fieldset", name:"detadepartamentos", width:440,list:[
			{type:"settings", labelWidth:80},
			{type:"label", label:"<?php echo t('Detalle del Departamento'); ?>", labelWidth:390},
			{type:"input", name:"deptocodigo", label:"<?php echo t('C&oacute;digo'); ?>:", inputWidth:60},
			{type:"input", name:"deptonombre", label:"<?php echo t('Nombre'); ?>:", inputWidth:300},
			{type:"input", name:"deptoabrev", label:"<?php echo t('Abreviatura'); ?>:", inputWidth:100},
			{type:"input", name:"deptoorden", label:"<?php echo t('Orden'); ?>:", inputWidth:60},
			{type:"input", name:"deptoresponsable", label:"<?php echo t('Responsable'); ?>:", inputWidth:300},
			{type:"block", width: 390, list:[
					{type:"button", name:"deptoguardar", value:"<?php echo t('Guardar'); ?>", offsetLeft:10, offsetTop:10},
					{type:"newcolumn"},
					{type:"button", name:"deptocancelar", value:"<?php echo t('Cancelar'); ?>", offsetLeft:10, offsetTop:10}
			]}  
		]},
		{type:"fieldset", name:"detaentidades", width:440,list:[
			{type:"settings", labelWidth:85},
			{type:"label", label:"<?php echo t('Detalle de la Entidad'); ?>", labelWidth:390},
			{type:"input", name:"entedepto", label:"<?php echo t('Departamento'); ?>:", inputWidth:300, readonly:true, style:"border:none;"},
			{type:"input", name:"entecodigo", label:"<?php echo t('C&oacute;digo'); ?>:", inputWidth:60},
			{type:"input", name:"entenombre", label:"<?php echo t('Nombre'); ?>:", inputWidth:300},
			{type: "template", name: "enteimagen", label: "<?php echo t('Imagen'); ?>:", value:"", format: "doImage", inputWidth:150},
			{type:"block", width: 390, list:[
					{type:"button", name:"entecambiar", value:"<?php echo t('Cambiar Imagen'); ?>", offsetLeft:10, offsetTop:10},
					{type:"newcolumn"},
					{type:"button", name:"enteguardar", value:"<?php echo t('Guardar'); ?>", offsetLeft:10, offsetTop:10},
					{type:"newcolumn"},
					{type:"button", name:"entecancelar", value:"<?php echo t('Cancelar'); ?>", offsetLeft:10, offsetTop:10}
			]}
		]},
		{type:"fieldset", name:"imgentidades", width:440,list:[
			{type:"settings", labelWidth:85},
			{type:"label", label:"<?php echo t('Im&aacute;gen de la Entidad'); ?>", labelWidth:390},
			{type: "template", name: "imgmanager", label: "", value:"1", format: "doVault", inputWidth:440},
			{type:"block", width: 390, list:[
					{type:"button", name:"imgaceptar", value:"<?php echo t('Aceptar'); ?>", offsetLeft:10, offsetTop:10},
					{type:"newcolumn"},
					{type:"button", name:"imgcancelar", value:"<?php echo t('Cancelar'); ?>", offsetLeft:10, offsetTop:10}
			]}
		]},
		{type:"fieldset", name:"detausuarios", width:850,list:[
			{type:"settings", labelWidth:120},
			{type:"label", label:"<?php echo t('Detalle del Usuario'); ?>", labelWidth:390},
			{type:"hidden", name:"usercodigo"},
			{type:"input", name:"usercompleto", label:"<?php echo t('Nombre y Apellido'); ?>:", inputWidth:200},
			{type:"input", name:"usernombre", label:"<?php echo t('C&oacute;digo Usuario'); ?>:", inputWidth:200},
			{type:"input", name:"usermail", label:"<?php echo t('Correo'); ?>:", inputWidth:200},
			{type:"password", name:"userpass", label:"<?php echo t('Clave'); ?>:", inputWidth:200},
			{type:"hidden", name:"userpermisosdeta"},
			{type:"label", label:"<?php echo t('*Deje en blanco la clave si no desea modificarla*'); ?>", labelWidth:400, style:"font-weight:normal !important;"},
			{type:"block", width: 390, list:[
					{type:"button", name:"userguardar", value:"<?php echo t('Guardar'); ?>", offsetLeft:10, offsetTop:10},
					{type:"newcolumn"},
					{type:"button", name:"usercancelar", value:"<?php echo t('Cancelar'); ?>", offsetLeft:10, offsetTop:10}
			]},
			{type:"newcolumn"},
			{type: "template", name: "permisosdeta", label: "", value:"5", format: "doGrid", inputWidth:390}
		]},
		{type:"newcolumn"},
		{type:"fieldset", name:"frentidades", width:420, list:[
			{type:"label", label:"<?php echo t('Entidades'); ?>", labelWidth:390},
			{type: "template", name: "entidades", label: "", value:"2", format: "doGrid", inputWidth:390},
			{type:"block", width: 390, list:[
					{type:"button", name:"enteagregar", value:"<?php echo t('Agregar'); ?>", offsetLeft:10, offsetTop:10},
					{type:"newcolumn"},
					{type:"button", name:"enteeditar", value:"<?php echo t('Editar'); ?>", offsetLeft:10, offsetTop:10},
					{type:"newcolumn"},
					{type:"button", name:"enteeliminar", value:"<?php echo t('Eliminar'); ?>", offsetLeft:20, offsetTop:10}
			]}
		]}
	]},
	{type:"fieldset", name:"frusuarios", width:892, list:[
		{type:"label", label:"<?php echo t('Usuarios'); ?>", labelWidth:480},
		{type: "template", name: "usuarios", label: "", value:"3", format: "doGrid", inputWidth:480},
		{type:"block", width: 480, list:[
				{type:"button", name:"useragregar", value:"<?php echo t('Agregar'); ?>", offsetLeft:10, offsetTop:10},
				{type:"newcolumn"},
				{type:"button", name:"usereditar", value:"<?php echo t('Editar'); ?>", offsetLeft:10, offsetTop:10},
				{type:"newcolumn"},
				{type:"button", name:"usereliminar", value:"<?php echo t('Eliminar'); ?>", offsetLeft:20, offsetTop:10}
		]},
		{type:"newcolumn"},
		{type:"label", label:"<?php echo t('Permisos'); ?>", labelWidth:360},
		{type: "template", name: "permisos", label: "", value:"4", format: "doGrid", inputWidth:360}
	]},
	{type:"hidden", name:"op"},
	{type:"hidden", name:"cod"}
];

var form = new dhtmlXForm("form_container",struc);
with(form)
{
	attachEvent("onButtonClick", function(id){
	switch(id)
    	{
		case "deptoagregar":
			setItemValue("deptocodigo","");
			setItemValue("deptonombre","");
			setItemValue("deptoabrev","");
			setItemValue("deptoorden","");
			setItemValue("deptoresponsable","");
			setItemValue("op", "deptoadd");
			showItem("detadepartamentos");
		    	hideItem("frdepartamentos");
		    	hideItem("frentidades");
		    	hideItem("frusuarios");
	    	    	break;

		case "deptoeditar":
			elem = grid1.getSelectedRowId();
			if(elem)
			{
				setItemValue("deptocodigo", grid1.cells(elem,0).getValue());
				setItemValue("deptonombre", grid1.cells(elem,1).getValue());
				setItemValue("deptoabrev", grid1.cells(elem,2).getValue());
				setItemValue("deptoorden", grid1.cells(elem,3).getValue());
				setItemValue("deptoresponsable", grid1.cells(elem,4).getValue());
				setItemValue("op", "deptoedit");
				showItem("detadepartamentos");
			    	hideItem("frdepartamentos");
			    	hideItem("frentidades");
		    		hideItem("frusuarios");
			}
			else
				alert("Seleccione el departamento que desea editar");
	    	    	break;
	   	
	   	case "deptoeliminar":
			elem = grid1.getSelectedRowId();
			if(elem)
			{
				if(confirm("Esta seguro que desea eliminar el registro?"))
				{
					var xml = dhtmlxAjax.postSync("<?php echo $urlxmls; ?>formularios/data/estructura.php", "op=deptodel&id="+elem);
					alert(xml.xmlDoc.responseText);
					if(xml.xmlDoc.responseText.indexOf("correctamente")>0)
					{
						grid1.clearAndLoad("<?php echo $urlxmls; ?>formularios/data/estructura.php?op=cargadeptos");
						grid2.clearAll();
						grid3.clearAll();
					}
				}
		    	}
			else
				alert("Seleccione el departamento que desea eliminar");
	    	    	break;
	
		case "deptoguardar":
			form.send("<?php echo $urlxmls; ?>formularios/data/estructura.php","post",function(xml){
		    	    	alert(xml.xmlDoc.responseText);
		    	    	if(xml.xmlDoc.responseText.indexOf("correctamente")>0)
			    	{
					grid1.clearAndLoad("<?php echo $urlxmls; ?>formularios/data/estructura.php?op=cargadeptos");
					hideItem("detadepartamentos");
				    	showItem("frdepartamentos");
				    	showItem("frentidades");
				    	showItem("frusuarios");
				}
	            	});
	    	    	break;

		case "deptocancelar":
			hideItem("detadepartamentos");
		    	showItem("frdepartamentos");
		    	showItem("frentidades");
		    	showItem("frusuarios");
	    	    	break;

		case "enteagregar":
			el = grid1.getSelectedRowId();
			if(el)
			{
				setItemValue("entedepto",grid1.cells(el,1).getValue());
				setItemValue("entecodigo","");
				setItemValue("entenombre","");
				setItemValue("enteimagen","");
				setItemValue("op", "enteadd");
				setItemValue("cod", el);
				showItem("detaentidades");
			    	hideItem("frdepartamentos");
			    	hideItem("frentidades");
			    	hideItem("frusuarios");
			}
			else
				alert("Seleccione el departamento al que pertenece la entidad");
	    	    	break;

		case "enteeditar":
			el = grid1.getSelectedRowId();
			elem = grid2.getSelectedRowId();
			if(elem)
			{
				setItemValue("entedepto", grid1.cells(el,1).getValue());
				setItemValue("entecodigo", grid2.cells(elem,0).getValue());
				setItemValue("entenombre", grid2.cells(elem,1).getValue());
				setItemValue("enteimagen", grid2.cells(elem,2).getValue());
				setItemValue("op", "enteedit");
				setItemValue("cod", el);
				showItem("detaentidades");
			    	hideItem("frdepartamentos");
			    	hideItem("frentidades");
			    	hideItem("frusuarios");
			}
			else
				alert("Seleccione la entidad que desea editar");
	    	    	break;
		    	    	
	   	case "enteeliminar":
	   		el = grid1.getSelectedRowId();
			elem = grid2.getSelectedRowId();
			if(elem)
			{
				if(confirm("Esta seguro que desea eliminar el registro?"))
				{
					var xml = dhtmlxAjax.postSync("<?php echo $urlxmls; ?>formularios/data/estructura.php", "op=entedel&agencia="+el+"&id="+elem);
					alert(xml.xmlDoc.responseText);
					if(xml.xmlDoc.responseText.indexOf("correctamente")>0)
					{
						grid2.clearAndLoad("<?php echo $urlxmls; ?>formularios/data/estructura.php?op=cargaentes&agencia="+el);
					}
				}
		    	}
			else
				alert("Seleccione la entidad que desea eliminar");
	    	    	break;

		case "entecambiar":
			hideItem("detaentidades");
		    	showItem("imgentidades");
	    	    	break;
	    	    	
		case "imgaceptar":
			elem = view.getSelected();
			if(elem)
			{
				hideItem("imgentidades");
		    		showItem("detaentidades");
		    		setItemValue("enteimagen",elem);
	    	    	}
	    	    	break;

		case "imgcancelar":
			hideItem("imgentidades");
		    	showItem("detaentidades");
	    	    	break;

		case "enteguardar":
	   		el = grid1.getSelectedRowId();
			form.send("<?php echo $urlxmls; ?>formularios/data/estructura.php","post",function(xml){
		    	    	alert(xml.xmlDoc.responseText);
		    	    	if(xml.xmlDoc.responseText.indexOf("correctamente")>0)
			    	{
					grid2.clearAndLoad("<?php echo $urlxmls; ?>formularios/data/estructura.php?op=cargaentes&agencia="+el);
					hideItem("detaentidades");
				    	showItem("frdepartamentos");
				    	showItem("frentidades");
				    	showItem("frusuarios");
				}
	            	});
	    	    	break;

		case "entecancelar":
			hideItem("detaentidades");
			showItem("frdepartamentos");
			showItem("frentidades");
			showItem("frusuarios");
			break;

		case "useragregar":
			setItemValue("usercompleto","");
			setItemValue("usernombre","");
			setItemValue("usermail","");
			setItemValue("op", "useradd");
			grid5.clearAndLoad("<?php echo $urlxmls; ?>formularios/data/estructura.php?op=permisos&usuario=0");
			showItem("detausuarios");
			hideItem("frdepartamentos");
			hideItem("frentidades");
			hideItem("frusuarios");
	    	    	break;

		case "usereditar":
			elem = grid3.getSelectedRowId();
			if(elem)
			{
				setItemValue("usercodigo", elem);
				setItemValue("usercompleto", grid3.cells(elem,0).getValue());
				setItemValue("usernombre", grid3.cells(elem,1).getValue());
				setItemValue("usermail", grid3.cells(elem,2).getValue());
				setItemValue("userpass", "");
				setItemValue("op", "useredit");
				grid5.clearAndLoad("<?php echo $urlxmls; ?>formularios/data/estructura.php?op=permisos&usuario="+elem);
				grid4.clearAll();
				showItem("detausuarios");
				hideItem("frdepartamentos");
				hideItem("frentidades");
				hideItem("frusuarios");
			}
			else
				alert("Seleccione el usuario que desea editar");
	    	    	break;

	   	case "usereliminar":
			elem = grid3.getSelectedRowId();
			if(elem)
			{
				if(confirm("Esta seguro que desea eliminar el registro?"))
				{
					var xml = dhtmlxAjax.postSync("<?php echo $urlxmls; ?>formularios/data/estructura.php", "op=userdel&id="+elem);
					alert(xml.xmlDoc.responseText);
					if(xml.xmlDoc.responseText.indexOf("correctamente")>0)
					{
						grid3.clearAndLoad("<?php echo $urlxmls; ?>formularios/data/estructura.php?op=cargausers");
						grid4.clearAll();
					}
				}
	    	}
			else
				alert("Seleccione el usuario que desea eliminar");
	    	    	break;

		case "userguardar":
			var permisos = grid5.getCheckedRows(2);
			if(permisos)
			{
				form.setItemValue("userpermisosdeta",permisos);
				form.send("<?php echo $urlxmls; ?>formularios/data/estructura.php","post",function(xml){
					alert(xml.xmlDoc.responseText);
					if(xml.xmlDoc.responseText.indexOf("correctamente")>0)
					{
						grid3.clearAndLoad("<?php echo $urlxmls; ?>formularios/data/estructura.php?op=cargausers");
						hideItem("detausuarios");
						showItem("frdepartamentos");
						showItem("frentidades");
						showItem("frusuarios");
					}
				});
			}
			else
			{
				alert("Seleccione los permisos que desea para este usuario");
			}
   	    	break;

		case "usercancelar":
			hideItem("detausuarios");
	    	showItem("frdepartamentos");
	    	showItem("frentidades");
	    	showItem("frusuarios");
   	    	break;

		case "limpiar":
			limpiar(form);
			break;

	}
	});
	
	attachEvent("onValidateError", function (input, value, result){
		alert("Revise los datos del formulario. Existen campos sin rellenar.("+input+")");
	});
	
	hideItem("detadepartamentos");
	hideItem("detaentidades");
	hideItem("imgentidades");
	hideItem("detausuarios");
}

doImgManager();
    
grid1 = new dhtmlXGridObject('grid_container1');
with(grid1)
{
	setImagePath("<?php echo $urlxmls; ?>formularios/dhtmlx/imgs/");
 	setHeader("<?php echo t('C&oacute;digo'); ?>,<?php echo t('Nombre'); ?>,<?php echo t('Abrev.'); ?>,<?php echo t('Orden'); ?>,<?php echo t('Responsable'); ?>");//set column names
	setInitWidths("50,150,50,50,150");//set column width in px
	setColAlign("center,left,center,center,left");//set column values align
	setColTypes("ed,ed,ed,ed,ed");//set column types
	enableMultiline(true);
	init();//initialize grid
	loadXML("<?php echo $urlxmls; ?>formularios/data/estructura.php?op=cargadeptos");
	attachEvent("onRowSelect", function(id,ind){
		grid2.clearAndLoad("<?php echo $urlxmls; ?>formularios/data/estructura.php?op=cargaentes&agencia="+id);
	});
}

grid2 = new dhtmlXGridObject('grid_container2');
with(grid2)
{
    setImagePath("<?php echo $urlxmls; ?>formularios/dhtmlx/imgs/");
	setHeader("<?php echo t('C&oacute;digo'); ?>,<?php echo t('Nombre'); ?>,");
	setInitWidths("50,*,0");//set column width in px
	setColAlign("center,left,center");//set column values align
	setColTypes("ro,ro,ro");//set column types
	enableMultiline(true);
	init();//initialize grid
}

grid3 = new dhtmlXGridObject('grid_container3');
with(grid3)
{
    setImagePath("<?php echo $urlxmls; ?>formularios/dhtmlx/imgs/");
	setHeader("<?php echo t('Nombre Completo'); ?>,<?php echo t('C&oacute;digo Usuario'); ?>,<?php echo t('Email'); ?>");
	setInitWidths("170,100,170");//set column width in px
	setColAlign("left,center,left");//set column values align
	setColTypes("ro,ro,ro");//set column types
	enableMultiline(true);
	init();//initialize grid
	loadXML("<?php echo $urlxmls; ?>formularios/data/estructura.php?op=cargausers");
	attachEvent("onRowSelect", function(id,ind){
		grid4.clearAndLoad("<?php echo $urlxmls; ?>formularios/data/estructura.php?op=cargapermisos&usuario="+id);
	});
}

grid4 = new dhtmlXGridObject('grid_container4');
with(grid4)
{
    setImagePath("<?php echo $urlxmls; ?>formularios/dhtmlx/imgs/");
	setHeader("<?php echo t('Departamento'); ?>,<?php echo t('Entidad'); ?>");
	//attachHeader("#select_filter,#text_filter");
	setInitWidths("0,*");//set column width in px
	setColAlign("left,left");//set column values align
	setColTypes("ro,ro");//set column types
	enableMultiline(true);
	init();//initialize grid
	attachEvent("onXLE", function(grid_obj,count){
		groupBy(0);
	}); 
}

grid5 = new dhtmlXGridObject('grid_container5');
with(grid5)
{
    setImagePath("<?php echo $urlxmls; ?>formularios/dhtmlx/imgs/");
	setHeader("<?php echo t('Departamento'); ?>,<?php echo t('Entidad'); ?>,<?php echo t('Permiso'); ?>");
	setInitWidths("0,*,50");//set column width in px
	setColAlign("left,left,center");//set column values align
	setColTypes("ro,ro,ch");//set column types
	enableMultiline(true);
	init();//initialize grid
	attachEvent("onXLE", function(grid_obj,count){
		groupBy(0);
	}); 
}
</script>