<?
////////////////////////////////////////////////////
// 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 getHeaders($conf){
	global $permissions;
	$cadena='<td class="barra_nombres_columnas" align="left">';
	if(((string)$conf->layout->btn_check=="true" && $permissions[3]==1) || $_SESSION[session_id()]['level']==1){
		$cadena.='<input class="checks" name="checkAll" type="checkbox" id="checkAll" onclick="toggleAllChecked()" />';
	}
	$cadena.='</td>';
	return $cadena;
}

function getTableRow($f,$fila,$conf){
	global $permissions;
	$nombre=$f[(string)$conf->column_model->title['boundTo']];
	$url=(string)$conf->column_model->image->prefix_thumb . $f[(string)$conf->column_model->image['boundTo']];
	$holder='';
	if(isset($conf->data->field_sort)) $holder="<div style='width:20px; height:22px; float:left; line-height:22px; overflow:hidden;'><img src='../resources/themes/default/icon_move_2.gif' alt='mover' class='sorter' style='line-height:22px; margin-top:1px; background:none !important;' id='hsorter_{$f['id']}' /></div>";
	
	$tamano='';
	if($conf->column_model->image->prefix_big!=NULL){
		$a1='<a target="_blank" rel="gallery" class="diap_thumb" href="' . $conf->column_model->image->prefix_big . $f[(string)$conf->column_model->image['boundTo']] . '">';	$a2='</a>';
		if($conf->layout->tip_filesize=="true") $tamano="<span class='sizetip'>".formatbytes($conf->column_model->image->prefix_big . $f[(string)$conf->column_model->image['boundTo']],"KB")."</span>";
	}else{
		$a1='';	$a2='';
	}	
	
	if(((string)$conf->layout->btn_check=="true" && $permissions[3]==1) || $_SESSION[session_id()]['level']==1){
		if(isset($conf->data->field_lock_del) && $f[(string)$conf->data->field_lock_del]==1){
			$check='<img style="border:0; margin-top:1px; margin-left:2px; vertical-align:top;" src="../resources/themes/default/forbidden.png" alt="'.TABLE_DEL_FORBIDDEN.'" />';
		}else{
			$check='<input class="checks" style="margin-top:-1px; vertical-align:bottom" type="checkbox" name="checkRow[' . $f[(string)$conf->data->field_key] . ']" id="checkRow[' . $f[(string)$conf->data->field_key] . ']" value="' . $f[(string)$conf->data->field_key] . '" />';
		}
	}
	if((string)$conf->layout->btn_edit=="true"){
		$accion=$permissions[2]==1 || $_SESSION[session_id()]['level']==1 ? 'edit' : 'view';
		$ed='<a href="template_detail_1.php?_action=' . $accion . '&resId=' . $_GET['resId'] . '&id=' . $f['id'] . '&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; margin-top:1px; vertical-align:top;"  /></a>';
	}else{
		$ed='';
	}
	if((string)$conf->layout->btn_details=="true"){
		$urled=changeUrlParam('id',$f['id']).'&amp;mymasterpage='.urlencode($_SERVER['REQUEST_URI']);
		$edt='<a href="template_detail_9.php?'.$urled.'" title="'.TABLE_TEXT_EDIT.'"><img class="icon_edit" src="../resources/themes/default/view_icon.png" alt="'. TABLE_TEXT_EDIT .'" style="border:0; margin-top:1px; vertical-align:top"  /></a>';
	}else{
		$edt='';
	}
	$statuscolors=array('', '#FF4200', '#FFD100', '#81EF4A', '#999');	// Array con los colores correspondientes a los diversos estados
	$estado='';
	if($conf->layout->tip_status=="true" && isset($conf->data->field_status)){
		$estado="<span class='statustip' style='background-color:".$statuscolors[$f[(string)$conf->data->field_status]]."'><img src='../resources/themes/default/pixeltrans.gif' width='12' height='10' /></span>";
	}
	
	
	$cadena=<<<EOT
		<div class="diap_outer roundcorners sombra">
			<div class="diap_top">{$holder}<span title="{$nombre}">{$nombre}</span></div>
			<div class="diap_middle">
				<div class="diap_inner">{$a1}<img src="{$url}" title="{$nombre}" border="0" />{$a2}</div>
			</div>
			<div class="diap_bottom">
				{$check} {$ed} {$edt} {$estado} {$tamano}
			</div>
		</div>
EOT;
	return $cadena;
}


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;


$table=array();										
unset($_SESSION['uploads'][$resId]);				
$errores=array();									
$cols=0;											
$_SESSION['current_master_page']=$_SERVER['REQUEST_URI'];
$page=isset($_GET['page']) ? $_GET['page'] : 0;										
$pagesize=(isset($_GET['pagesize']) && $_GET['pagesize']!="0") ? $_GET['pagesize'] : $conf->data->pagesize;		
$orderby=isset($_GET['orderby']) ? $_GET['orderby'] : $conf->data->orderby;			
$sortby=isset($_GET['sortby']) ? $_GET['sortby'] : $conf->data->sortby;				

$consulta=(string)$conf->data->sql;
$filtros=isset($conf->filters) ? FilterProcess::getQuery($consulta,$conf->filters) : '';	
$consulta=str_replace("{@filters}",$filtros,$consulta);
$consulta=Content::parse($consulta);														
$consulta=exclContent($consulta);															


$q=mysql_query($consulta . " ORDER BY " . $orderby) or die(mysql_error()."<br>" . $consulta);
$totalrows=mysql_num_rows($q);
$pages=ceil($totalrows/$pagesize);
if((int)$page>=$pages-1 || (string)$page=='last') $page=$pages-1;
if((int)$page<0 || (string)$page=='first') $page=0;
$qlimit=((int)$pagesize>0) ? " LIMIT " . ($pagesize*$page) . "," . $pagesize : "";
$q=mysql_query($consulta . " ORDER BY " . $orderby . " " . $sortby . " " . $qlimit) or die(mysql_error());
$currows=mysql_num_rows($q);		

while($f=mysql_fetch_assoc($q)){ $tabla[]=$f; Content::$data['main']=$f; }
if(isset($conf->data->aux_datasets)){
	foreach($conf->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" />
	<?
	$diapow=isset($conf->layout->slide_width) ? (int)$conf->layout->slide_width : 100;
	$diapoh=isset($conf->layout->slide_height) ? (int)$conf->layout->slide_height : 100;
	?>
	<style type="text/css" media="all">
	.diap_outer{
		width:<? echo $diapow ?>px; height:<? echo $diapoh ?>px; border:1px solid #999999; background-color:#EEEEEE; float:left; margin:8px; overflow:hidden; position:relative;
	}
	.diap_top{position:absolute; height:18px; background-color:#CCC; text-align:center; overflow:hidden; width:100%; border-bottom:1px solid #999; line-height:18px;}
	
	.diap_middle{position:absolute; height:100%; text-align:center; padding:0; width:100%; display: table; }
	
	.diap_inner{display: table-cell; vertical-align: middle; }
	.diap_inner a{position:relative;}
	.diap_inner img{border:1px solid #666;}
	.sizetip{position:absolute; background-color:none; color:#444; font-size:9px; line-height:18px; padding:0 2px; right:0; zoom:1}
	.statustip{border:1px solid #666; font-size:10px; line-height:18px; padding:0; margin:0; }
	.diap_bottom{position:absolute; background-color:#CCCCCC; overflow:hidden; padding:0; bottom:0; height:18px; border-top:1px solid #999999; width:100%;}
	</style>
	<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>
	<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">
	
	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;	?>
	(function($){var a=$.ui.mouse.prototype._mouseMove;$.ui.mouse.prototype._mouseMove=function(b){if($.browser.msie&&document.documentMode>=9){b.button=1};a.apply(this,[b]);}}(jQuery));
	$(document).ready(function(){
		$("a.diap_thumb").fancybox({overlayColor:'#000'});
		<? if(isset($conf->data->field_sort)){ ?>
		$("#cell_body").sortable({		
			containment: 'parent', cursor:'move',
			update: function(event, ui){
				var yuyu = $(".sorter[id]").map(function() { return this.id.split("hsorter_").join(""); }).get();
				$.blockUI({ message: null }); 
				$.post("XHR.master.php",{"action":"reorder", "resId":"<? echo $_GET['resId'] ?>", "items":yuyu.toString()},
					function(data){
						if(data.result=="KO"){
							alert("Error de base de datos. Por favor, inténtalo de nuevo más tarde.");
						}else{
						}
						$.unblockUI(); 
					},"json"
				);
			}
		}).disableSelection();
		<? } ?>
		$(".diap_outer").mouseenter(function(){
			$(this).removeClass("sombra").addClass("glow_red");
		}).mouseleave(function(){
			$(this).removeClass("glow_red").addClass("sombra");
		});
	});
	<? if(isset($conf->data->field_sort)){ ?>
	
	<? } ?>
	</script>

	<script type="text/javascript">
	$(document).ready(function(){
		$('#tabla').tabs();
		$('#tipo').focus();
		$('select').selectmenu();
		$('button, input:submit, input:button, input:reset, .button, .link_button').button();
		$('.button-disabled').button({disabled: true});
	});
	</script>
	<? 
	foreach($conf->user_scripts as $script)	echo '<script type="text/javascript" src="../userlib/'.$script.'?'.microtime().'"></script>';
	?>
</head>

<body id="cuerpo" class="<? echo isset($conf->layout->class)? $conf->layout->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%" >
<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'] ?>">
	<? if(isset($conf->intro)) echo "<div class='introbox sombra roundcorners bkg_icon_info'>" . Content::parse($conf->intro) . "</div>" ?>
	<? $anchura=$conf->layout->width!=NULL ? (string)$conf->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 class="header_caption header_caption_bkg ui-corner-top"><? echo getRecordCount($page,$pagesize,$totalrows,$currows); ?></td>
		</tr>
		<tr>
		<? echo getHeaders($conf); ?>
		</tr>
		</thead>
		<tbody id="table_body">
			<tr><td id="cell_body">
			<? for($i=0;$i<count($tabla);$i++){ echo getTableRow($tabla[$i],$i,$conf); } ?>
			</td></tr>
		</tbody>
		<tfoot id="table_foot">
		<? if((string)$conf->layout->paginator=="true"){ ?>
		<tr>
			<td colspan="<? echo $cols ?>" class="barra_paginator"><? echo getPaginator($page,$pages,7) ?></td>
		</tr>
		</tfoot>
		<? } ?>
	</table>
	</form>
</td>
<td id="panel_lateral" valign="top">
	<? if(isset($conf->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 $conf->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($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"><? echo isset($conf->layout->but_insert['label']) ? $conf->layout->but_insert['label'] : PANEL_BTN_NEW ?></a>
		<?
		}
		if($conf->layout->but_delete=="true" && $permissions[3]==1){
		?>
			<a href="javascript:submitTo('template_delete.php','')" class="link_button"><? echo PANEL_BTN_DELETE ?></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" onclick="toggleVis('secc4')">&nbsp;<? echo PANEL_SECC_4 ?></div>
		<div class="secc_content" id="secc4" style="display:inherit">
			<form name="frmOpciones" id="frmOpciones" method="post" action="#" enctype="application/x-www-form-urlencoded" >
			<? echo PANEL_OPCS_ROWSPERPAGE ?><br />
			<select name="opsRegistros" id="opsRegistros" onchange="javascript:changeURL(this.options[this.selectedIndex].value)" class="select_large">
				<option value="<? echo changeUrlParam('pagesize','0') ?>"><? echo PANEL_OPCS_DEFAULT ?></option>
				<option value="<? echo changeUrlParam('pagesize','15') ?>" <? if($pagesize=="15") echo 'selected="selected"' ?>>15</option>
				<option value="<? echo changeUrlParam('pagesize','25') ?>" <? if($pagesize=="25") echo 'selected="selected"' ?>>25</option>
				<option value="<? echo changeUrlParam('pagesize','50') ?>" <? if($pagesize=="50") echo 'selected="selected"' ?>>50</option>
				<option value="<? echo changeUrlParam('pagesize','100') ?>" <? if($pagesize=="100") echo 'selected="selected"' ?>>100</option>
				<option value="<? echo changeUrlParam('pagesize','-1') ?>" <? if($pagesize=="-1") echo 'selected="selected"' ?>><? echo PANEL_OPCS_ALL ?></option>
			</select>
			</form>
			<?
			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>
