<?
////////////////////////////////////////////////////
// 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");

function getVarTable($conf){
	$arr=array();
	$arr['tabla']=(string)$conf->data->table;
	$arr['id']=(string)$conf->data->field_key;
	$arr['nombre']=(string)$conf->data->field_name;
	$arr['descripcion']=(string)$conf->data->field_desc;
	$arr['valor']=(string)$conf->data->field_value;
	$arr['tipodatos']=(string)$conf->data->field_datatype;
	$arr['control']=(string)$conf->data->field_control;
	$arr['multilang']=(string)$conf->data->field_multilang;
	$arr['lockdel']=(string)$conf->data->field_lock_del;
	$arr['lockedit']=(string)$conf->data->field_lock_edit;
	$arr['tab']=(string)$conf->data->field_tab;
	$arr['grupo']=(string)$conf->data->field_group;
	$arr['estado']=(string)$conf->data->field_status;
	return $arr;
}

function getTableRow($f,$fila,$master){
	global $permissions; global $widget; global $master;
	$userprocess=new UserProcessing();	$process=new Process(); $cadena='';
	extract(getVarTable($master));
	$cadena.="<tr id='row_{$f[id]}'>";
	
	$cadena.="<td class='cell_main' width='300'>".$f[$descripcion]."<br/><img src='../resources/themes/default/pixeltrans.gif' height='1' width='300'></td>";
	$cadena.="<td class='cell_main' width='100%'>";
	$c=simplexml_load_string($f[$control]);
	$cadena.=$widget->getControl($c,$f[$valor],"edit",$_GET['resId']);
	$cadena.="</td>";

	if($master->layout->col_edit=="true"){
		$cadena.='<td class="cell_main" width="20" >';
		if($f[$lockedit]==1){
			$cadena.='<img src="../resources/themes/default/forbidden.png" alt="'.TABLE_DEL_FORBIDDEN.'" />';
		}else{
			$cadena.='<a href="template_detail_1.php?_action=edit&amp;resId=' . $_GET['resId'] . '&amp;id=' . $f[$id] . '&amp;mymasterpage=' . urlencode($_SERVER['REQUEST_URI']) . '" title="'.TABLE_TEXT_EDIT.'"><img class="icon_edit" src="../resources/themes/default/edit_icon.gif" alt="'. TABLE_TEXT_EDIT .'" style="border:0;" /></a>';
		}
		$cadena.='</td>';
	}
	
	if($master->layout->col_del=="true"){
		$cadena.='<td class="cell_main" width="20" >';
		if(($f[$lockdel]==1 && $permissions[3]==1) || $_SESSION[session_id()]['level']==1){
			$cadena.='<img src="../resources/themes/default/forbidden.png" alt="'.TABLE_DEL_FORBIDDEN.'" />';
		}else{
			$cadena.="<a href='#' onclick='deleteProperty(".$f[$id].");return false;'><img src='../resources/themes/default/icono_borrar.png' style='border:none' /></a>";
		}
		$cadena.='</td>';
	}
	
	if($master->layout->col_save=="true"){
		$cadena.='<td class="cell_main" width="20" >';
		$cadena.="<a href='#' onclick='saveProperty(".$f[$id].", \"".$f[$nombre]."\"); return false;'><img src='../resources/themes/default/save_icon.gif' style='border:none' /></a>";
		$cadena.='</td>';
	}
	$cadena.='</tr>';
	return $cadena;
}


$widget=new Controls();
$process=new UserProcessing();

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


$table=array();										
unset($_SESSION['uploads'][$resId]);				
$errores=array();									
$_SESSION['current_master_page']=$_SERVER['REQUEST_URI'];

$sql=(string)$master->data->sql;
$filtros=isset($master->filters) ? FilterProcess::getQuery($sql,$master->filters) : '';	
$sql=str_replace("{@filters}",$filtros,$sql);
$sql=Content::parse($sql);
$sql=exclContent($sql);
$q=mysql_query($sql) or die(mysql_error()."<br>" . $sql);
$conjunto=array();
$seccion='';$fsec='';
$subseccion='';$fsubsec='';
while($f=mysql_fetch_assoc($q)){
	$fsec=$f[(string)$master->data->field_tab];
	$fsubsec=$f[(string)$master->data->field_group];
	if(!array_key_exists($fsec,$conjunto)){
		$seccion=$fsec;
		$conjunto[$seccion]=array();
	}
	if(!array_key_exists($fsubsec,$conjunto[$seccion])){
		$subseccion=$fsubsec;
		$conjunto[$seccion][$subseccion]=array();
	}
	$conjunto[$seccion][$subseccion][]=$f;
}
$qsecciones=array_keys($conjunto); $cadenatabs=''; $tabs=0;
foreach($qsecciones as $tab){
	if($tabs==0){
		$cadenatabs.='<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#section'.$tabs.'">' . $tab . '</a></li>';
	}else{
		$cadenatabs.='<li class="ui-state-default ui-corner-top"><a href="#section'.$tabs.'">' . $tab . '</a></li>';
	}
	$tabs++;
}

$cols=2+((string)$master->layout->col_del=="true") + ((string)$master->layout->col_edit=="true") + ((string)$master->layout->col_save=="true");
while($f=mysql_fetch_assoc($q)){ $tabla[]=$f; Content::$data['main']=$f; }
if(isset($master->data->aux_datasets)){
	foreach($master->data->aux_datasets->dataset as $aux){
		$sql=Content::parse((string)$aux);
		$qq=mysql_query($sql) or print($sql);
		if(mysql_num_rows($qq)>1){
			Content::$data[(string)$aux['name']]=array();
			while($ff=mysql_fetch_assoc($qq)){
				Content::$data[(string)$aux['name']][]=$ff;
			}
		}else if(mysql_num_rows($qq)==1){
			$ff=mysql_fetch_assoc($qq);
			Content::$data[(string)$aux['name']]=$ff;
		}
	}
}
?>
<!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" />
	<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/ui/jquery.ui.selectmenu.js" ></script>
	<script type="text/javascript" src = "../jslib/jq/jquery.textarea.min.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/fancybox/jquery.fancybox-1.3.4.pack.js" ></script>
	<link rel="stylesheet" href="../jslib/jq/fancybox/jquery.fancybox-1.3.4.css" type="text/css" media="screen" />

	<script type="text/javascript" src="../jslib/utils.js"></script>
	<script src="../jslib/swfobject2.js" type="text/javascript"></script>
	<script type="text/javascript" src="../jslib/controls.js"></script>
	<script type="text/javascript">
	var cal_date_format="<? echo CAL_DATE_FORMAT ?>";
	var cal_invalid_date="<? echo CAL_INVALID_DATE ?>";
	var selectedTab=0;
	<?
	$tmplngs=array();
	foreach($lngs as $key=>$cont){$tmplngs[]=$key;}
	?>
	var langs=new Array("<? echo implode('","',$tmplngs) ?>")
	</script>
	<script type="text/javascript">
	$(document).ready(function(){
		$('#tabla').tabs();
		$('#tipo').focus();
		$('select:not(.select_multiple), select:not(.select_editable)').selectmenu();
		$('button, input:submit, input:button, input:reset, .button, .link_button').button();
		$('.button-disabled').button({disabled: true});
	});
	</script>
</head>

<body id="cuerpo" <? echo isset($master->layout->class)? 'class="'.$master->layout->class.'"' : 'bkg-master-1' ?>>
<div id="pageBar">
	<h1><? echo $titulogeneral ?></h1>
	<div style="position:absolute; right:5px; top:3px;">
	<? if($master->layout->help_topic!="" && $master->layout->help_topic!=NULL){ ?><a href="#" onclick="javascript:openPopupWindow('../help/loader.php?topic=<? echo $master->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%" >
<tr>
<td id="panel_central" valign="top">
	<form name="dataform" id="dataform" method="post" enctype="application/x-www-form-urlencoded" action="<? echo $_SERVER['REQUEST_URI'] ?>" class="ui-form">
	<? if(isset($master->intro)) echo "<div class='introbox sombra roundcorners bkg_icon_info'>" . Content::parse($master->intro) . "</div>" ?>
	<? $anchura=$master->layout->width!=NULL ? (string)$master->layout->width : "100%" ?>
	<table width="<? echo $anchura  ?>" border="0" align="center" cellspacing="0" cellpadding="0" id="tabla" class="sombra tablaformulario ui-corner-top">
		<thead>
		<tr>
			<td colspan="<? echo $cols ?>"  class="header_caption header_caption_bkg ui-corner-top"><? echo $master->title ?></td>
		</tr>
		<tr>
			<td class="ui-tabs ui-widget ui-widget-content ui-corner-all header_tabbar" colspan="<? echo $cols ?>" id="tabscell">
				<ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" id="tabs">
					<? echo $cadenatabs ?>
				</ul>
			</td>
		</tr>
		</thead>
		<? 
		$cuenta=0;
		foreach($qsecciones as $tab){ ?>
		<tbody id="section<? echo $cuenta ?>" class="innertbody">
			<?
			$curtab=$conjunto[$tab];
			foreach(array_keys($curtab) as $group){
				$curgrp=$curtab[$group];
				$cadena="<tr><td colspan='$cols' class='grad_orange' id='group_{$group}' style='height:30px; padding-left:6px !important'><strong>{$group}</strong></td></tr>";
				echo $cadena;
				foreach($curgrp as $item){
					echo getTableRow($item,$cuenta,$master);
				}
			}
			$cuenta++;
			?>
		</tbody>
		<? } ?>
		<tfoot id="table_foot">
		<tr>
			<td colspan="<? echo $cols ?>" class="ui-state-default footer">&nbsp;</td>
		</tr>
		</tfoot>
	</table>
	</form>
</td>
<td id="panel_lateral" valign="top">
	<? if(isset($master->desc)){ ?>
	<div class="secc_container" >
		<div class="secc_title" onclick="toggleVis('secc1')">&nbsp;<? echo PANEL_SECC_1 ?></div>
		<div class="secc_content" id="secc1"><? echo $master->desc ?></div>
	</div>
	<? } ?>
	<div class="secc_container" >
		<div class="secc_title" onclick="toggleVis('secc2')">&nbsp;<? echo PANEL_SECC_2 ?></div>
		<div class="secc_content" id="secc2">
		<?
		if($master->layout->but_insert=="true" && $permissions[1]==1){
		?>
			<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"><? echo isset($master->layout->but_insert['label']) ? $master->layout->but_insert['label'] : PANEL_BTN_NEW ?></a>
		<?
		}
		if($master->layout->but_delete=="true" && $permissions[3]==1){
		?>
			<a href="javascript:submitTo('template_delete.php','')" class="link_button"><? echo PANEL_BTN_DELETE ?></a>
		<?
		}
		if(isset($conf->layout->but_special)) echo getSpecialButtons($conf->layout->but_special);
		?>
		</div>
	</div>
	<div class="secc_container" >
		<div class="secc_title" onclick="toggleVis('secc4')">&nbsp;<? echo PANEL_SECC_4 ?></div>
		<div class="secc_content" id="secc4" style="display:inherit">
			<?
			if(isset($master->filters)){
				echo FilterProcess::getValidationScript($master->filters);
				echo FilterProcess::getResetScript($master->filters);
			?>
			<form name="frmFiltros" id="frmFiltros" method="GET" action="#" class="ui-form ">
				<strong><? echo $master->filters['title'] ?></strong><br />
				<?
				foreach($master->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 $master->filters['btn_submit'] ?>" onclick="validaFiltros(); return false;" />
				<input type="button" name="fil_btn_reset" class="but_default grad_orange" value="<? echo $master->filters['btn_reset'] ?>" onclick="javascript:resetFiltros()" />
			</form>
			<? } ?>			
		</div>
	</div>
</td>
</tr>
</table>
<script type="text/javascript">

<? if(isset($master->inline_scripts)) echo $master->inline_scripts;	?>
$(document).ready(function(){
	initTableRows();				
});
function changeTab(param){
	if(param==selectedTab) return;
	selectedTab=param;
	for(i=0;i<<? echo $tabs ?>;i++){
		$('#tablink'+i).removeClass('active');
		$('#section'+i).css("display","none");
	}
	$('#tablink'+param).addClass('active');
	$('#section'+param).css("display","");
	return false;
}
function initTableRows(){
	$("#tabla tbody tr:odd").removeClass("row1 row2").addClass("row1");
	$("#tabla tbody tr:even").removeClass("row1 row2").addClass("row2");
	return;		
	$("#tabla tbody tr").hover(
		function(){$(this).addClass("row_hover")}, 
		function(){$(this).removeClass("row_hover")}
	);
}

function deleteProperty(param){
	var x=confirm("¿Estás seguro de que quieres eliminar esta propiedad?\nSu eliminación podría hacer que dejen de funcionar algunas o todas las páginas de la web pública.");
	if(x){
		$.ajax({
			type: "POST",
			url: "../core/XHR.master7.php",
			data: {action:'delete', resId:'<? echo $resId ?>', id:param},
			success: function(msg){
				if(msg=="OK"){
					window.location.reload(true);
				}else{
					alert("Ha habido un problema en la operación.");
				}
			}
		});		
	}
}
function saveProperty(id, valor){
	var control=$("#"+valor); var valor;
	var obj={action:'save', id:id, resId:'<? echo $resId ?>'};
	switch(control.attr("type")){
		case "checkbox":
			obj.value=control.attr("checked") ? 1 : 0;
			break;
		default:
			var controles=$(':input[id^="'+valor+'"]');
			if(controles.length>1){		
				var ultimo=controles[controles.length-1].id;
				obj.multilang=true;
				obj.nombre=ultimo;
				for(i=0; i<controles.length-1; i++){
					var temp=controles[i].id.split(ultimo+"_h").join("");
					obj["value"+temp]=controles[i].value;
				}
			}else{
				obj.value=control.val();
			}
	}
	$.blockUI({ message: null }); 
	$.ajax({
		type: "POST",
		url: "../core/XHR.master7.php",
		data: obj,
		success: function(msg){
			$.unblockUI(); 
			if(msg=="OK"){
			}else{
				alert(msg);
			}
		}
	});		
}
<?
$tmplngs=array();
foreach($lngs as $key=>$cont){$tmplngs[]=$key;}
?>
</script>
<? 
foreach($master->user_scripts as $script) echo '<script type="text/javascript" src="../userlib/'.$script.'?'.microtime().'"></script>';
?>
</body>
</html>
