<?php
/*********************************************
Desciption: Categorias
File: /bsk/categorias/index.php
Project: Basikus.Net
Developers: João Vieira	
Start Date: 2009/05/25
*********************************************/

//configuração principal
require_once($_SERVER['DOCUMENT_ROOT'] . "/bsk/includes/configuracao.default.php");
//funções de tratamento de textos
include($_SERVER['DOCUMENT_ROOT'] . '/bsk/includes/funcoes.default.php'); 
include($_SERVER['DOCUMENT_ROOT'] . "/bsk/includes/classe.bd.listas.php");

$ondeTou    = 'categorias';

$metaTitle  = $bngCategorias;

if ( isset($_GET['id']) ) {
    if ( (int)$_GET['id'] > 0 ) {
	if ( isset($_GET['faz']) ) {
	    if ( $_GET['faz'] == 'del' ) header('Location: /bsk/' . $ondeTou . '/?' . (int)$_GET['id'] . '/apagar/');
	}else header('Location: /bsk/' . $ondeTou . '/?' . (int)$_GET['id'] . '/alterar/#formPos');
    }
}

if (isset($_SERVER['QUERY_STRING'])) {
    $dBToDo = explode("/", $_SERVER['QUERY_STRING']);
    $dBToDo[0] = (int) $dBToDo[0];
    if (!isset($dBToDo[1])) $dBToDo[1] = "";
    $dBToDo[1] = addslashes($dBToDo[1]);
    if (!isset($dBToDo[2])) $dBToDo[2] = "";    
}

$fieldId                = 0;
$fieldCategoria         = 0;
$fieldNome              = '';
$erro                   = false;
$jsValidacoesRules      = '';
$jsValidacoesMessages   = '';
$jsValidaCategoria      = 'true';

/* remover conteudo */
if ($dBToDo[1] == 'apagar') {
    $serUsado = False;
    $sqlStmt = "SELECT categorias.id FROM categorias
		WHERE categorias.pai = '" . $dBToDo[0] . "'";
    $resultDb = $connectDb->pedido($sqlStmt);
    if ( $resultDb->rowCount() > 0 ) {
        $serUsado = True;
    } 
    $sqlStmt = "SELECT id FROM conteudos
		WHERE categorias_id = '" . $dBToDo[0] . "'";
    $resultDb = $connectDb->pedido($sqlStmt);
    if ( $resultDb->rowCount() > 0 ) {
        $serUsado = True;
    } 
    if ($serUsado) {}
    else {
        $sqlStmt = "DELETE FROM categorias
		WHERE categorias.id = '" . $dBToDo[0] . "' AND categorias.id > 100";
	$resultDb = $connectDb->pedido($sqlStmt);
	header('Location: /bsk/categorias/?/adicionar/dok');
    }
    
}
/* /remover conteudo */

/* tratamento de form comin' */
if (isset($_POST['btProcessar'])) {

    #id
    $_POST['bxId']  = (int) $_POST['bxId'];

    #categoria
    $fieldCategoria = (int)$_POST['bxCategoria'];
    #if ( (int)$fieldCategoria < 1 ) $erro = true;

    #nome
    for ($i = 0; $i < count($arrLinguas); $i++) {
        $var1 = stripslashes($_POST['bxNome' . $arrLinguas[$i][0]]);
        if ( strlen($var1) > 0 ) { 
            $fieldNome .= "[" . $arrLinguas[$i][0] . "]" . ereg_replace("<br />", "", $var1) . "[/" . $arrLinguas[$i][0] . "]\n"; 
        }else $erro = true;
    }	
    
    if ( $_POST['bxId'] > 0 && !($erro) ) { # ou altera
        $sqlStmt = "UPDATE categorias 
                SET 
                pai = '" . $fieldCategoria . "',
                nome = '" . safe($fieldNome) . "'
                WHERE id = '" . $_POST['bxId'] . "'";
        $fieldId    = $_POST['bxId'];
        $resultDb   = $connectDb->pedido($sqlStmt);
        $fieldId    = 0;
    }elseif ( !$erro ) { # ou insere
        $sqlStmt = "INSERT INTO categorias (
                            pai, 
                            nome
                    ) 
                    VALUES (
                            '" . $fieldCategoria . "', 
                            '" . safe($fieldNome) . "'
                    )";
        $resultDb       = $connectDb->pedido($sqlStmt);
        #$fieldId        = $connectDb->registosUltimo();
    }
}    
/* /tratamento de form comin' */

/* busca de conteudo a gerir */
if ($dBToDo[1] == 'alterar') {
    $sqlStmt = "SELECT 
		pai, 
		nome
            FROM categorias
            WHERE id = '" . $dBToDo[0] . "'";
    $resultDb       = $connectDb->pedido($sqlStmt);
    if ( $rowResultDb = $resultDb->fetch(PDO::FETCH_ASSOC) ) {
        $fieldId            = $dBToDo[0];
        $fieldCategoria     = $rowResultDb['pai'];
        for ($i = 0; $i < count($arrLinguas); $i++){
            ${"fieldNome" . $arrLinguas[$i][0]} = trd($rowResultDb['nome'], $arrLinguas[$i][0]);
        }
    }else exit();
}
/* /busca de conteudo a gerir */

for ($i = 0; $i < count($arrLinguas); $i++){
    $jsValidacoesRules      .= "\n bxNome" . $arrLinguas[$i][0] . ": {required: true, minlength: 4},";
    $jsValidacoesMessages   .= "\n bxNome" . $arrLinguas[$i][0] . ": {required: \"" . $bngCampoInvalido . "\",minlength: jQuery.format(\"" . $bngCampoMinimode . " {0} " . $bngCcaracteres . "\")},";
}
$jsValidacoesRules      = substr($jsValidacoesRules, 0, strlen($jsValidacoesRules)-1);
$jsValidacoesMessages   = substr($jsValidacoesMessages, 0, strlen($jsValidacoesMessages)-1);

if ($dBToDo[1] == 'alterar') {
    if ( $fieldId < 100 ) $jsValidaCategoria = 'false';
}

$metaJS     = '	
jQuery(document).ready(function(){ 

	jQuery("#listaG").jqGrid({ 
		treeGrid: true,
		treeGridModel : "adjacency", 
		ExpandColumn : "nome",
		url: "/bsk/categorias/registos/lista/", 
		datatype: "xml", 
		mtype: "POST", 
		colNames:["id","nome","Activo", "", ""], 
		colModel:[ 
			{name:"id",index:"id", width:1,hidden:true,key:true}, 
			{name:"nome",index:"name", width:400}, 
			{name:"activo", index:"activo", width:100, align:"center", editable: true, sortable: false, edittype:"select", editoptions:{value:"0:Ambos;SIM:Sim;NAO:Não"}},
			{name:"editar", index:"editar", width:80, align:"center", editable: false, sortable: false, formatter: "showlink",  formatoptions: {baseLinkUrl: "/bsk/categorias", showAction: "", addParam:""} },
			{name:"remover", index:"remover", width:100, align:"right", editable: false, sortable: false, formatter: "showlink",  formatoptions: {baseLinkUrl: "/bsk/categorias", showAction: "", addParam:"&faz=del"} }
		], 
		height:"auto", 
		pager : jQuery("#listaP"), 
		onSelectRow: function(id){ 
		    if(id && id!==lastsel){ 
			 jQuery("#listaG").restoreRow(lastsel); 
			 jQuery("#listaG").editRow(id,true); 
			 lastsel=id; 
		    }
		}, 
		editurl: "/bsk/categorias/registos/editar/?' . md5($pwdWord . Date('Ymd')) . '",
        loadError : function(xhr,st,err) { 
            jQuery("#listaErr").html("Type: "+st+"; Response: "+ xhr.status + " "+xhr.statusText); 
        },	
		caption: "Lista de registos",
		edit: {reloadAfterSubmit: true}
		
	}); 
    jQuery("#listaG").navGrid("#listaP",{edit:false,add:false,del:false,search:false,refresh:true});



	$("#formConteudos").validate({
	    rules: {
		bxCategoria: {required: ' . $jsValidaCategoria . '},
		' . $jsValidacoesRules . '
	    },
	    messages: {
		bxCategoria: {required: "' . $bngTemEscolherOpcao . '"},
		' . $jsValidacoesMessages . '
	    },
	    errorPlacement: function(error, element) {
	        var errEl = \'#erR\' + element.attr("name");
                $(errEl).css({\'color\' : \'red\', \'width\' : \'520px\', \'padding-left\' : \'10px\'});
	        error.appendTo(errEl);
	    },
	    submitHandler: function(form) {
		form.submit();
	    },
	    success: function(label) {
		//label.html("&nbsp;").addClass("checked");
	    }
	});

});';

include($_SERVER['DOCUMENT_ROOT'] . '/bsk/includes/md.topo.php');

$dbListCategorias = New DB_List($connectDb);
$dbListCategorias->designList['name']    =   "bxCategoria";
$dbListCategorias->designList['css']    =   "element select medium";
$dbListCategorias->sqlStmt("SELECT id, pai, nome FROM categorias");
$dbListCategorias->showLikeTree(True);
$dbListCategorias->recordSelected($fieldCategoria);


?>

	<div id="middle">
		
		<div id="center-column">
			<div class="top-bar">
				<h1><?php print $bngCategorias;?></h1>
				<div class="breadcrumbs"><a href="/bsk/"><?php print $bngInicial;?></a> / <a href="/bsk/categorias/?/adicionar"><b>+</b><?php print $bngCategorias;?>&nbsp;<?php print $bngCategorias;?></a></div>
			</div>
			<br />
		  <div class="select-bar">
		    &nbsp;
		  </div>
		
		
	<a name="formPos"></a> 
	<!-- form -->
	<div id="form_container" >
	   
	    <form id="formConteudos" class="appnitro"  method="post" action="">
		<ul >				
		    <li id="liCategoria" >
			<label class="description" for="cbxCategoria"><?php print $bngCategoria;?> </label>
			<div>
			<?php $dbListCategorias->Make();    ?>
			</div> <span id="erRbxCategoria"></span>
		    </li>		
		</ul>
		<div id="tabs" style="margin-top:10px;width:100%;"><!-- main div tabs -->
		
<?php			
	for ($i = 0; $i < count($arrLinguas); $i++){
	   if ( !isset(${"fieldNome" . $arrLinguas[$i][0]}) ) ${"fieldNome" . $arrLinguas[$i][0]} = '';
?>		
                <div id="tabs-<?php print $arrLinguas[$i][0];?>" style="margin-bottom:10px;"><!-- div tab -->
                <ul>
		    <li id="liNome<?php print $arrLinguas[$i][0];?>" >
		    <label class="description" for="cbxNome<?php print $arrLinguas[$i][0];?>"><img src="/bsk/media/img/icon.bandeira.<?php print $arrLinguas[$i][0];?>.png" align="left" border="0"/>&nbsp;<?php print $bngTitulo;?>    </label>
		    <div>
		    <input id="cbxNome<?php print $arrLinguas[$i][0];?>" name="bxNome<?php print $arrLinguas[$i][0];?>" class="element text medium" type="text" maxlength="80" value="<?php print (${"fieldNome" . $arrLinguas[$i][0]});?>"/> 
		    </div> <span id="erRbxNome<?php print $arrLinguas[$i][0];?>"  ></span> 
		    </li>	
		</ul>
		</div><!-- div tab -->
<?php
	}
?> 		
                </div><!-- /main div tabs -->
                <ul>
			
		<li class="buttons">
		    <input type="hidden" id="cbxId" name="bxId" value="<?php print $fieldId;?>" />
		    <input type="hidden" id="cbtProcessar" name="btProcessar" value="<?php print $bngProcessar;?>" />
		    <input id="cbtProcessarB" class="button_text" type="submit" name="btProcessarB" value="<?php print $bngProcessar;?>" />
		</li>
		</ul>
		</form>	
	</div>
	<!-- /form -->
		
	<br/>
	<br/>
	
	<table id="listaG" class="scroll"></table> 
	<div id="listaP" class="scroll" style="text-align:center;"></div> 
	<span id="listaErr" style="color:red"></span>  		
		
		
	<br/>	
	<br/>

		</div>
		
<?php include( $_SERVER['DOCUMENT_ROOT'] . "/bsk/includes/md.direita.php" );?>

	</div>
<?php
include($_SERVER['DOCUMENT_ROOT'] . '/bsk/includes/md.fundo.php');	
?>