<?
////////////////////////////////////////////////////
// Conciliación: gestión de conciliación de activos
// Version: 1.0
//
// Copyright (C) 2014  Eustotem Multimedia, S.L.
//
// License: MIT, see LICENSE
////////////////////////////////////////////////////


include("../conf/preferences.php");
session_name(SYS_APP_SESSNAME);
session_start();
include("../conf/langs/".$langs[$_SESSION['userlang']][0]."/MAIN.php");
include("../conf/connections.php");
include("../phplib/auth.php");
require_once("../phplib/utils.php");
require_once("../core/plugins.php");

if(!isset($_GET['resId'])) header("Location:error.php");
$resId=$_GET['resId'];
if(isset($_GET['parentId'])) $parentId=$_GET['parentId'];
$conf=simplexml_load_file("../conf/resources/".$langs[$_SESSION['userlang']][0]."/".$_SESSION['conf'][$resId]->masterview);
$titulogeneral=$conf->title!=NULL ? $conf->title : $_SESSION['conf'][$resId]->title;

$config_columns_array2=array();
$tmp=$conf->xpath('//column[client_config]');
foreach($tmp as $padre){
	$tmp_client=$padre->xpath('client_config');
	$tmp_datasource=$padre->xpath('datasource');
	if(count($tmp_datasource)==0){
		$config_columns_array2[]=(string)$tmp_client[0];
	}else{
		$arrcadena=array();
		foreach($tmp_datasource[0]->option as $option){
			$arrcadena[]='"' . addslashes($option['value']) . '":"' . addslashes((string)$option) . '"';
		}
		if(isset($tmp_datasource[0]->sql)){
			$qq=mysql_query((string)$tmp_datasource[0]->sql);
			while($ff=mysql_fetch_array($qq)){
				$arrcadena[]='"' . addslashes($ff[0]) . '":"' . addslashes($ff[1]) . '"';
			}
		}
		$cadena='"options":{' . implode(",",$arrcadena) . "},";
		$tmp_client[0]=str_replace("{{options}}",$cadena,$tmp_client[0]);
		$config_columns_array2[]=$tmp_client[0];
	}
}

$config_columns_array=$config_columns_array2;
$config_columns=implode(",",$config_columns_array);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title><? echo $_SESSION['application']['title'] ?></title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link href="../resources/themes/default/common.css" rel="stylesheet" type="text/css" media="screen" />
	<link href="../resources/themes/default/main.css" rel="stylesheet" type="text/css" media="screen" />
	<link href="../resources/themes/default/form_screen.css" rel="stylesheet" type="text/css" media="screen" />
	<?
	$styles=(string)$conf->layout->styles;
	if($styles!=NULL && $styles!='' && $styles!='main.css'){
	?>
	<link href="../resources/themes/default/<? echo $styles ?>" rel="stylesheet" type="text/css" media="screen" />
	<? } ?>
	<link type="text/css" href="../jslib/jq/ui/css/<? echo UI_THEME ?>/jquery-ui.custom.css" rel="stylesheet" />
	<link type="text/css" href="../jslib/jq/ui/css/<? echo UI_THEME ?>/jquery-ui.ekain.css" rel="stylesheet" />
	<script type="text/javascript" src = "../jslib/jq/jquery-1.7.2.min.js" ></script>
	<script type="text/javascript" src = "../jslib/jq/jquery.blockUI.js" ></script>
	<script type="text/javascript" src = "../jslib/jq/ui/js/jquery-ui-1.8.21.custom.min.js" ></script>
	<script type="text/javascript" src = "../jslib/jq/jquery.event.drag-2.0.min.js"></script>
	<script type="text/javascript" src = "../jslib/jq/ui/jquery.ui.selectmenu.js" ></script>
	<link type="text/css" href="../jslib/jq/ui/css/<? echo UI_THEME ?>/jquery.ui.selectmenu.css" rel="stylesheet" />
	<script type="text/javascript" src = "../jslib/jq/ui/i18n/jquery.ui.datepicker-<? echo $langs[$_SESSION['userlang']][0] ?>.js" ></script>
	
	<script type="text/javascript" src="../jslib/utils.js"></script>
	<script src="../jslib/swfobject2.js" type="text/javascript"></script>
	
	<link rel="stylesheet" href="../jslib/jq/slickgrid/slick.grid.css" type="text/css"/>
	<script src="../jslib/jq/slickgrid/slick.core.js"></script>
	<script src="../jslib/jq/slickgrid/plugins/slick.cellrangedecorator.js"></script>
	<script src="../jslib/jq/slickgrid/plugins/slick.cellrangeselector.js"></script>
	<script src="../jslib/jq/slickgrid/plugins/slick.cellselectionmodel.js"></script>
	<script src="../jslib/jq/slickgrid/slick.formatters.js"></script>
	<script src="../jslib/jq/slickgrid/slick.editors.js"></script>
	<script src="../jslib/jq/slickgrid/slick.grid.js"></script>
	<script src="../jslib/jq/slickgrid/controls/slick.pager.js"></script>
	
	<script type="text/javascript">
	
	var cal_date_format="<? echo CAL_DATE_FORMAT ?>";
	var cal_invalid_date="<? echo CAL_INVALID_DATE ?>";
	function toggleAllChecked(){
		var el=document.getElementById("checkAll");
		valor=el.checked;
		var frm=document.getElementById("dataform");
		for(i=0;i<frm.elements.length;i++){
			if(frm.elements[i].name.substr(0,8)=="checkRow"){
				frm.elements[i].checked=valor;
			}
		}
	}
	
	function submitTo(dir,targ){
		if(targ=='') targ="_self";
		var f=document.getElementById("dataform");
		var direccion=dir+"?resId=<? echo $_GET['resId'] ?>\&mymasterpage=<? echo urlencode($_SERVER['REQUEST_URI']) ?>";
		f.target=targ;
		f.action=direccion;
		f.submit();
	}
	
	<? if(isset($conf->inline_scripts)) echo $conf->inline_scripts;	?>
	
	var grid, options, columns, datos;		
	var commandQueue = [];					
	var page=0, pagesize=25, pages=0;		
	var iSelPolicy=1;						
	function customButtonFormatter(row, cell, value, columnDef, dataContext){
		var cadena="";
		<?
		if($conf->layout->col_edit=="true"){
			$accion=$permissions[2]==1 || $_SESSION[session_id()]['level']==1 ? 'edit' : 'view';
		?>
		cadena+='<a href="#" onclick="location.href=\'template_detail_1.php?_action=<? echo $accion ?>&amp;resId=<? echo $resId ?>&amp;id=' + value + '&amp;mymasterpage=<? echo urlencode($_SERVER['REQUEST_URI']) ?>\'" id="btnRowEdit_' + row + '" title="Editar este registro" class="button icon_button ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only"><span class="ui-button-text"><img class="icon_edit" src="../resources/themes/default/edit_icon.gif" alt="Editar este registro" style="border:0;"></span></a>';
		<? } ?>
		
		<? 
		if($conf->layout->col_details=="true"){ 
			$pos=$fila+($page*$pagesize);
			$url=changeUrlParam('pos',$pos).'&amp;mymasterpage='.urlencode($_SERVER['REQUEST_URI']);
		?>
		cadena+='<a href="#" onclick="location.href=\'template_detail_9.php?id=' + value + '&amp;<? echo $url ?>\'" id="btnDetails_' + row + '" title="Ver detalles de este registro" class="button icon_button ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only"><span class="ui-button-text"><img class="icon_edit" src="../resources/themes/default/view_icon.png" alt="Ver detalles de este registro" style="border:0;"></span></a>';
		<? } ?>
		
		<? if(($conf->layout->but_delete=="true" && $permissions[3]==1) || $_SESSION[session_id()]['level']==1){ ?>
		cadena+='<a href="#" id="btnRowDel_' + row + '" onclick="confirmDeletion(\'' + value + '\', ' + row + '); return false;" title="Borrar este registro" class="button icon_button ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only"><span class="ui-button-text"><img class="icon_edit" src="../resources/themes/default/icono_borrar.png" alt="Borrar este registro" style="border:0;"></span></a>';
		<? } ?>
		return cadena;
	}
	function selectFormatter(row, cell, value, columnDef, dataContext){
		var cadena=value;
		try{
			var o=columnDef.options;
			cadena=o[""+value];
		}catch(e){
			cadena="";
		}
		return cadena;
	}
	function queueAndExecuteCommand(item, column, editCommand) {
		commandQueue.push(editCommand);
		editCommand.execute();
	}
	function confirmDeletion(param, row){
		var x=confirm("¿Estás seguro de que quieres eliminar este registro?\nLa acción no se podrá deshacer");
		if(x==true){
			$.blockUI({message:"Cargando datos..."});
			$.post("XHR.master9.php", { "action":"deleteRecord", "resId":'<? echo $resId ?>', "key":param },
				function(data){
					$.unblockUI();
					if(data.result=="ko"){
						alert(data.data);
						undo();
					}else{
						var data = grid.getData(); 
						data.splice(row, 1);
						grid.setData(data);
						grid.render();
					}
				}, "json"
			);
		}
	}
	function undo() {
		var command = commandQueue.pop();
		if (command && Slick.GlobalEditorLock.cancelCurrentEdit()) {
			command.undo();
			grid.gotoCell(command.row, command.cell, false);
		}
	}
	$(document).ready(function(){
		$('select').selectmenu();
		$('button, input:submit, input:button, input:reset, .button, .link_button').button();
		$('.button-disabled').button({disabled: true});
		columns=[<? echo $config_columns ?>];
		var colextra={id: "acciones", name: "Acciones", field: "id", maxWidth: 80, formatter: customButtonFormatter};
		columns.push(colextra);
		options = {
			editable: true,
			enableAddRow: false,
			enableCellNavigation: true,
			asyncEditorLoading: false,
			autoEdit: false,
			forceFitColumns: true,
			editCommandHandler: queueAndExecuteCommand
		};
		<?
		$params=NULL;
		foreach($_REQUEST as $clave=>$valor) $params->$clave=$valor;
		$params->action='getData';
		?>
		$.post("XHR.master9.php", <? echo json_encode($params) ?>,
			function(data){
				datos=data.data;
				datos.getItemMetadata =function(row){
					var item=datos[row];
					if(item.af_id_activo==undefined) return;		
					if(item.xdenom=="Activo desglosado"){
					}
				}
				grid = new Slick.Grid("#tabla", datos, columns, options);
				grid.setSelectionModel(new Slick.CellSelectionModel());
				if(data.paginator!=null){	
					$("#paginator_container").html(data.paginator);
					$('.paginator button, .paginator input:submit, .paginator input:button, .paginator input:reset, .paginator .button, .paginator .link_button').button();
					$('.paginator .button-disabled').button({disabled: true});
				}
				
				grid.onSelectedRowsChanged.subscribe(function (e, args) {
				});
				grid.onCellChange.subscribe(function (e, args) {
					$.blockUI({message:"Cargando datos..."});
					$.post("XHR.master9.php", { "action":"updateRecord", "resId":'<? echo $resId ?>', "params":args.item },
						function(data){
							$.unblockUI();
							if(data.result=="ko"){
								alert(data.data);
								undo();
							}else{
								if(data.extra!=undefined) alert(data.extra);
							}
						}, "json"
					);
				});
				grid.onKeyDown.subscribe(function(e) {
					var row=grid.getSelectedRows();
					var editando=grid.getEditorLock().isActive();	
					if(row.length!=1 || grid.getOptions().autoEdit==true) return;
					switch(e.which){
						case 46:	
							if(!editando) $("#btnRowDel_"+row).click();
							break;
						case 68:	
							if(!editando) $("#btnDetails_"+row).click();
							break;
						case 69:	
							if(!editando) $("#btnRowEdit_"+row).click();
							break;
						case 17:	
							break;
					}
				});
			}, "json"
		);
		
		$("#btn_autoedit").click(function(){
			var estado=$(this).text();
			if(estado=="Autoedit: OFF"){
				$(this).text("Autoedit: ON");
				grid.setOptions({autoEdit:true})
			}else{
				$(this).text("Autoedit: OFF");
				grid.setOptions({autoEdit:false})
			}
		});
		$("#selPolicy").change(function(){
			iSelPolicy=$(this).val();
		});
		
	});
	</script>

	<? if(isset($conf->client_code)) echo Content::parse($conf->client_code); ?>
	<style type="text/css">
	input.editor-text {	width: 100%;height: 100%;border: 0px none;margin: 0px;background: none repeat scroll 0% 0% transparent;outline: 0px none;padding: 0px;}
	select.editor-select{width: 100%;height: 100%;border: 0px none;margin: 0px;background: none repeat scroll 0% 0% transparent;outline: 0px none;padding: 0px;}
	.slick-cell-checkboxsel {background: #f0f0f0;border-right-color: silver;border-right-style: solid;}
	.slick-headerrow {  background: #fafafa;}
	.slick-headerrow-column {  background: #fafafa;  border-bottom: 0;  height: 100%;}
	.slick-row.ui-state-active {  background: #F5F7D7;}
	.slick-row {  position: absolute;  background: white;  border: 0px;  line-height: 20px;}
	.slick-row.selected {  z-index: 10;  background: #DFE8F6;}
	.slick-cell {  padding-left: 4px;  padding-right: 4px;}
	.slick-group {  border-bottom: 2px solid silver;}
	.slick-group-toggle {  width: 9px;  height: 9px;  margin-right: 5px;}
	.slick-group-toggle.expanded {  background: url(../images/collapse.gif) no-repeat center center;}
	.slick-group-toggle.collapsed {  background: url(../images/expand.gif) no-repeat center center;}
	.slick-group-totals {  color: gray;  background: white;}
	.slick-cell.selected {  background-color: beige;}
	.slick-cell.active {  border-color: gray;  border-style: solid;}
	.slick-sortable-placeholder {  background: silver !important;}
	.slick-row.odd {  background: #fafafa;}
	.slick-row.ui-state-active {  background: #F5F7D7;}
	.slick-row.loading {  opacity: 0.5;  filter: alpha(opacity = 50);}
	.slick-cell.invalid {  border-color: red;}
	.slick-column-non-editable{color:#999;}
	#panel_central{padding:0;}
	.test_row{background-color:#DBEAF9;}
	</style>
</head>

<body id="cuerpo" <? echo isset($conf->layout->class)? 'class="'.$conf->layout->class.'"' : 'class="bkg-master-1"' ?>>
<div id="pageBar">
	<h1><? echo $titulogeneral ?></h1>
	<div style="position:absolute; right:5px; top:3px;">
	<? if($conf->layout->help_topic!="" && $conf->layout->help_topic!=NULL){ ?><a href="#" onclick="javascript:openPopupWindow('../help/loader.php?topic=<? echo $conf->layout->help_topic ?>','helpWindow',500,500,true,'scrollbars')"><img src="../resources/themes/default/icon_help.png" style="border:0" /></a><? } ?>
	<? include("../jslib/layoutBtns.htm") ?>
	</div>
</div>
<table cellpadding="0" cellspacing="0" style="width: 100%; height: 100%; position: absolute; top: 0px; padding-top: 22px;" >
<tr>
<td id="panel_central" valign="top">
<?
$posbottom=(string)$conf->layout->paginator=="true" ? "36px;" : "0";	
?>
	<div id="tabla" style="position:absolute;top:22px;right:155px;left:0;bottom:<? echo $posbottom ?>;"></div>
	<? if((string)$conf->layout->paginator=="true"){ ?>
	<div class="ui-state-default footer" style="position:absolute; bottom:0; right:155px; left:0;" id="paginator_container"><? echo getPaginator($page,$pages,7) ?></div>
	<? } ?>
</td>
<td id="panel_lateral" valign="top">
	<? if(isset($conf->desc)){ ?>
	<div class="secc_container" >
		<div class="secc_title header_caption_bkg" onclick="toggleVis('secc1')">&nbsp;<? echo PANEL_SECC_1 ?></div>
		<div class="secc_content" id="secc1"><? echo $conf->desc ?></div>
	</div>
	<? } ?>
	<div class="secc_container" >
		<div class="secc_title header_caption_bkg" onclick="toggleVis('secc2')">&nbsp;<? echo PANEL_SECC_2 ?></div>
		<div class="secc_content" id="secc2">
		<?
		if($conf->layout->but_insert=="true" && $permissions[1]==1 && ($conf->data->maxrecords==0 || $totalrows<$conf->data->maxrecords)){
		?>
			<a href="template_detail_1.php?_action=insert&amp;resId=<? echo $_GET['resId'] ?>&amp;parentId=<? echo $_GET['parentId'] ?>&amp;mymasterpage=<? echo urlencode($_SERVER['REQUEST_URI']) ?>" class="link_button grad_blue"><? echo isset($conf->layout->but_insert['label']) ? $conf->layout->but_insert['label'] : PANEL_BTN_NEW ?></a>
		<?
		}?>
			<a href="template_master_1.php?<? echo $_SERVER['QUERY_STRING'] ?>" class="link_button grad_green">Listado normal</a>
		<?
		if($conf->layout->but_print=="true"){
		?>
			<a href="javascript:window.print()" class="link_button"><? echo PANEL_BTN_PRINT ?></a>
		<?
		}
		if($conf->layout->but_export_csv=="true"){
		?>
			<a href="../phplib/export_csv.php?<? echo $_SERVER['QUERY_STRING']; ?>" class="link_button"><? echo PANEL_BTN_EXPORT_CSV ?></a>
		<?
		}
		if($conf->layout->but_export_pdf=="true"){
		?>
			<a href="../phplib/export_pdf.php?<? echo $_SERVER['QUERY_STRING']; ?>" class="link_button" target="_blank"><? echo PANEL_BTN_EXPORT_PDF ?></a>
		<?
		}
		if(isset($conf->layout->but_special)) echo getSpecialButtons($conf->layout->but_special);
		?>
		</div>
	</div>
	<div class="secc_container" >
		<div class="secc_title header_caption_bkg" onclick="toggleVis('secc4')">&nbsp;<? echo PANEL_SECC_4 ?></div>
		<div class="secc_content" id="secc4" style="display:inherit">
			<a href="#" class="link_button grad_orange" id="btn_autoedit">Autoedit: OFF</a>
			Al editar un campo:
			<select id="selPolicy" class="select_large grad_orange">
				<option value="1">Seleccionar todo</option>
				<option value="2">Poner el cursor al final</option>
			</select>
			<?
			if(isset($conf->filters)){
				echo FilterProcess::getValidationScript($conf->filters);
				echo FilterProcess::getResetScript($conf->filters);
			?>
			<form name="frmFiltros" id="frmFiltros" method="GET" action="#" class="ui-form ">
				<strong><? echo $conf->filters['title'] ?></strong><br />
				<?
				foreach($conf->filters->filter as $filtro){
				?>
				<fieldset title="<? echo $filtro['title'] ?>">
					<legend ><? echo $filtro['title'] ?></legend>
					<? echo FilterProcess::getFilter($filtro); ?>
				</fieldset>
				<? } ?>
				<input type="submit" name="fil_btn_filter" class="but_default grad_orange" value="<? echo $conf->filters['btn_submit'] ?>" onclick="validaFiltros(); return false;" />
				<input type="button" name="fil_btn_reset" class="but_default grad_orange" value="<? echo $conf->filters['btn_reset'] ?>" onclick="javascript:resetFiltros()" />
			</form>
			<? } ?>			
		</div>
	</div>
</td>
</tr>
</table>
</body>
</html>
