<?php 
include("include/dbcommon.php");

@ini_set("display_errors","1");
@ini_set("display_startup_errors","1");

add_nocache_headers();
include("include/senuc_score_variables.php");
include('include/xtempl.php');
include('classes/addpage.php');

global $globalEvents;

//	check if logged in
if(@$_SESSION["UserID"] && IsAdmin() && !CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Add"))
{
	echo "<p>"."Você não tem permissão para acessar esta tabela"."<br>Proceed to <a href=\"admin.php\">Admin Area</a> to set up user permissions</p>";
	return;
}
if(!isLogged() || CheckPermissionsEvent($strTableName, 'A') && !CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Add"))
{ 
	$_SESSION["MyURL"]=$_SERVER["SCRIPT_NAME"]."?".$_SERVER["QUERY_STRING"];
	
	header("Location: login.php?message=expired"); 
	return;
}

if ((sizeof($_POST)==0) && (postvalue('ferror'))){
	if (postvalue("inline")){
		$returnJSON['success'] = false;
		$returnJSON['message'] = "Ocorreu um erro!";
		$returnJSON['fatalError'] = true;
		echo "<textarea>".htmlspecialchars(my_json_encode($returnJSON))."</textarea>";
		exit();
	}
	else if (postvalue("fly")){
		echo -1;
		exit();
	}
	else {
		$_SESSION["message_add"] = "<< "."Error occurred"." >>";
	}
}

$layout = new TLayout("add2","BreezeAqua1","MobileAqua1");
$layout->blocks["top"] = array();
$layout->containers["add"] = array();

$layout->containers["add"][] = array("name"=>"addheader","block"=>"","substyle"=>2);


$layout->containers["add"][] = array("name"=>"message","block"=>"message_block","substyle"=>1);


$layout->containers["add"][] = array("name"=>"wrapper","block"=>"","substyle"=>1, "container"=>"fields");


$layout->containers["fields"] = array();

$layout->containers["fields"][] = array("name"=>"addfields","block"=>"","substyle"=>1);


$layout->containers["fields"][] = array("name"=>"legend","block"=>"legend","substyle"=>3);


$layout->containers["fields"][] = array("name"=>"addbuttons","block"=>"","substyle"=>2);


$layout->skins["fields"] = "fields";

$layout->skins["add"] = "1";
$layout->blocks["top"][] = "add";
$layout->skins["details"] = "empty";
$layout->blocks["top"][] = "details";$page_layouts["senuc_score_add"] = $layout;



$filename = "";
$status = "";
$message = "";
$mesClass = "";
$usermessage = "";
$error_happened = false;
$readavalues = false;

$keys = array();
$showValues = array();
$showRawValues = array();
$showFields = array();
$showDetailKeys = array();
$IsSaved = false;
$HaveData = true;
$popUpSave = false;

$sessionPrefix = $strTableName;

$onFly = false;
if(postvalue("onFly"))
	$onFly = true;

if(@$_REQUEST["editType"]=="inline")
	$inlineadd = ADD_INLINE;
elseif(@$_REQUEST["editType"]==ADD_POPUP)
{
	$inlineadd = ADD_POPUP;
	if(@$_POST["a"]=="added" && postvalue("field")=="" && postvalue("category")=="")
		$popUpSave = true;	
}
elseif(@$_REQUEST["editType"]==ADD_MASTER)
	$inlineadd = ADD_MASTER;
elseif($onFly)
{
	$inlineadd = ADD_ONTHEFLY;
	$sessionPrefix = $strTableName."_add";
}
else
	$inlineadd = ADD_SIMPLE;

if($inlineadd == ADD_INLINE)
	$templatefile = "senuc_score_inline_add.htm";
else
	$templatefile = "senuc_score_add.htm";

$id = postvalue("id");
if(intval($id)==0)
	$id = 1;

//If undefined session value for mastet table, but exist post value master table, than take second
//It may be happen only when use dpInline mode on page add
if(!@$_SESSION[$sessionPrefix."_mastertable"] && postvalue("mastertable"))
	$_SESSION[$sessionPrefix."_mastertable"] = postvalue("mastertable");
	
$xt = new Xtempl();
	
// assign an id
$xt->assign("id",$id);
	
$auditObj = GetAuditObject($strTableName);

//array of params for classes
$params = array("pageType" => PAGE_ADD,"id" => $id,"mode" => $inlineadd);


$params['xt'] = &$xt;
$params['tName'] = $strTableName;
$params['includes_js'] = $includes_js;
$params['locale_info'] = $locale_info;
$params['includes_css'] = $includes_css;
$params['useTabsOnAdd'] = $gSettings->useTabsOnAdd();
$params['templatefile'] = $templatefile;
$params['includes_jsreq'] = $includes_jsreq;
$params['pageAddLikeInline'] = ($inlineadd==ADD_INLINE);
$params['needSearchClauseObj'] = false;
$params['strOriginalTableName'] = $strOriginalTableName;

if($params['useTabsOnAdd'])
	$params['arrAddTabs'] = $gSettings->getAddTabs();
	
$pageObject = new AddPage($params);

if(isset($_REQUEST['afteradd'])){
		header('Location: senuc_score_add.php');
	if($eventObj->exists("AfterAdd") && isset($_SESSION['after_add_data'][$_REQUEST['afteradd']])){
	
		$data = $_SESSION['after_add_data'][$_REQUEST['afteradd']];
		$eventObj->AfterAdd($data['avalues'], $data['keys'],$data['inlineadd'], $pageObject);
	
	}
	unset($_SESSION['after_add_data'][$_REQUEST['afteradd']]);
	
	foreach (is_array($_SESSION['after_add_data']) ? $_SESSION['after_add_data'] : array() as $k=>$v){
		if (!is_array($v) or !array_key_exists('time',$v)) {
			unset($_SESSION['after_add_data'][$k]);
			continue;
		}
		if ($v['time'] < time() - 3600){
			unset($_SESSION['after_add_data'][$k]);
		}
	}
		exit;
}

//Get detail table keys	
$detailKeys = $pageObject->detailKeysByM;

//Array of fields, which appear on add page
$addFields = $pageObject->getFieldsByPageType();

// add button events if exist
if ($inlineadd==ADD_SIMPLE)
	$pageObject->addButtonHandlers();

$url_page=substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1,12);

//For show detail tables on master page add
if($inlineadd==ADD_SIMPLE || $inlineadd==ADD_MASTER || $inlineadd==ADD_POPUP)
{
	$dpParams = array();
	if($pageObject->isShowDetailTables  && !isMobile())
	{
		$ids = $id;
		$countDetailsIsShow = 0;
		$pageObject->jsSettings['tableSettings'][$strTableName]['isShowDetails'] = $countDetailsIsShow > 0 ? true : false;
		$pageObject->jsSettings['tableSettings'][$strTableName]['dpParams'] = array('tableNames'=>$dpParams['strTableNames'], 'ids'=>$dpParams['ids']);
	}
}

//	Before Process event
if($eventObj->exists("BeforeProcessAdd"))
	$eventObj->BeforeProcessAdd($conn, $pageObject);

// proccess captcha
if ($inlineadd==ADD_SIMPLE || $inlineadd==ADD_MASTER || $inlineadd==ADD_POPUP)
	if($pageObject->captchaExists())
		$pageObject->doCaptchaCode();
	
// insert new record if we have to
if(@$_POST["a"]=="added")
{
	$afilename_values=array();
	$avalues=array();
	$blobfields=array();
//	processing tipo_nucleo - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_tipo_nucleo = $pageObject->getControl("tipo_nucleo", $id);
		$control_tipo_nucleo->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing tipo_nucleo - end
//	processing ano - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_ano = $pageObject->getControl("ano", $id);
		$control_ano->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing ano - end
//	processing mes - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_mes = $pageObject->getControl("mes", $id);
		$control_mes->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing mes - end
//	processing coordenadores - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_coordenadores = $pageObject->getControl("coordenadores", $id);
		$control_coordenadores->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing coordenadores - end
//	processing professores - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_professores = $pageObject->getControl("professores", $id);
		$control_professores->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing professores - end
//	processing alunos - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_alunos = $pageObject->getControl("alunos", $id);
		$control_alunos->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing alunos - end
//	processing meta_alunos - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_meta_alunos = $pageObject->getControl("meta_alunos", $id);
		$control_meta_alunos->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing meta_alunos - end
//	processing dias_funcionamento - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_dias_funcionamento = $pageObject->getControl("dias_funcionamento", $id);
		$control_dias_funcionamento->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing dias_funcionamento - end
//	processing meta_funcionamento - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_meta_funcionamento = $pageObject->getControl("meta_funcionamento", $id);
		$control_meta_funcionamento->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing meta_funcionamento - end
//	processing alunos_por_coordenador - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_alunos_por_coordenador = $pageObject->getControl("alunos_por_coordenador", $id);
		$control_alunos_por_coordenador->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing alunos_por_coordenador - end
//	processing meta_alunos_por_coordenador - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_meta_alunos_por_coordenador = $pageObject->getControl("meta_alunos_por_coordenador", $id);
		$control_meta_alunos_por_coordenador->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing meta_alunos_por_coordenador - end
//	processing freq_media_coordenador - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_freq_media_coordenador = $pageObject->getControl("freq_media_coordenador", $id);
		$control_freq_media_coordenador->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing freq_media_coordenador - end
//	processing min_freq_coordenador - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_min_freq_coordenador = $pageObject->getControl("min_freq_coordenador", $id);
		$control_min_freq_coordenador->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing min_freq_coordenador - end
//	processing freq_media_aluno - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_freq_media_aluno = $pageObject->getControl("freq_media_aluno", $id);
		$control_freq_media_aluno->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing freq_media_aluno - end
//	processing min_freq_aluno - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_min_freq_aluno = $pageObject->getControl("min_freq_aluno", $id);
		$control_min_freq_aluno->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing min_freq_aluno - end
//	processing freq_media_professor - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_freq_media_professor = $pageObject->getControl("freq_media_professor", $id);
		$control_freq_media_professor->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing freq_media_professor - end
//	processing min_freq_professor - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_min_freq_professor = $pageObject->getControl("min_freq_professor", $id);
		$control_min_freq_professor->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing min_freq_professor - end
//	processing meta_atividades - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_meta_atividades = $pageObject->getControl("meta_atividades", $id);
		$control_meta_atividades->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing meta_atividades - end
//	processing atividades_elaboradas - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_atividades_elaboradas = $pageObject->getControl("atividades_elaboradas", $id);
		$control_atividades_elaboradas->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing atividades_elaboradas - end
//	processing atividades_realizadas - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_atividades_realizadas = $pageObject->getControl("atividades_realizadas", $id);
		$control_atividades_realizadas->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing atividades_realizadas - end
//	processing score - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_score = $pageObject->getControl("score", $id);
		$control_score->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing score - end
//	processing operador - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_operador = $pageObject->getControl("operador", $id);
		$control_operador->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing operador - end
//	processing data_insercao - start
	$inlineAddOption = true;
	if($inlineAddOption)
	{
		$control_data_insercao = $pageObject->getControl("data_insercao", $id);
		$control_data_insercao->readWebValue($avalues, $blobfields, "", false, $afilename_values);
	}
//	processing data_insercao - end

//	insert ownerid value if exists
	if($strOriginalTableName == $pageObject->pSet->getOwnerTable("idnucleo"))
		$avalues["idnucleo"] = prepare_for_db("idnucleo",$_SESSION["_".$strTableName."_OwnerID"]);

//	insert masterkey value if exists and if not specified
	if(@$_SESSION[$sessionPrefix."_mastertable"]=="senuc_nucleo")
	{
		if(postvalue("masterkey1"))
			$_SESSION[$sessionPrefix."_masterkey1"] = postvalue("masterkey1");
		
		if($avalues["idnucleo"]==""){
			$avalues["idnucleo"] = prepare_for_db("idnucleo",$_SESSION[$sessionPrefix."_masterkey1"]);
		}
			
	}


	$failed_inline_add=false;
//	add filenames to values
	foreach($afilename_values as $akey=>$value)
		$avalues[$akey]=$value;
	
//	before Add event
	$retval = true;
	if($eventObj->exists("BeforeAdd"))
		$retval = $eventObj->BeforeAdd($avalues,$usermessage,(bool)$inlineadd, $pageObject);
	if($retval && $pageObject->isCaptchaOk)
	{
		//add or set updated lat-lng values for all map fileds with 'UpdateLatLng' ticked
		setUpdatedLatLng($avalues, $pageObject->cipherer->pSet);
		
		$_SESSION[$strTableName."_count_captcha"] = $_SESSION[$strTableName."_count_captcha"]+1;
		if(DoInsertRecord($strOriginalTableName,$avalues,$blobfields,$id,$pageObject, $pageObject->cipherer))
		{
			$IsSaved=true;
//	after edit event
			if($auditObj || $eventObj->exists("AfterAdd"))
			{
				foreach($keys as $idx=>$val)
					$avalues[$idx]=$val;
			}
			
			if($auditObj)
				$auditObj->LogAdd($strTableName,$avalues,$keys);
				
// Give possibility to all edit controls to clean their data				
//	processing tipo_nucleo - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_tipo_nucleo->afterSuccessfulSave();
			}
//	processing tipo_nucleo - end
//	processing ano - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_ano->afterSuccessfulSave();
			}
//	processing ano - end
//	processing mes - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_mes->afterSuccessfulSave();
			}
//	processing mes - end
//	processing coordenadores - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_coordenadores->afterSuccessfulSave();
			}
//	processing coordenadores - end
//	processing professores - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_professores->afterSuccessfulSave();
			}
//	processing professores - end
//	processing alunos - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_alunos->afterSuccessfulSave();
			}
//	processing alunos - end
//	processing meta_alunos - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_meta_alunos->afterSuccessfulSave();
			}
//	processing meta_alunos - end
//	processing dias_funcionamento - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_dias_funcionamento->afterSuccessfulSave();
			}
//	processing dias_funcionamento - end
//	processing meta_funcionamento - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_meta_funcionamento->afterSuccessfulSave();
			}
//	processing meta_funcionamento - end
//	processing alunos_por_coordenador - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_alunos_por_coordenador->afterSuccessfulSave();
			}
//	processing alunos_por_coordenador - end
//	processing meta_alunos_por_coordenador - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_meta_alunos_por_coordenador->afterSuccessfulSave();
			}
//	processing meta_alunos_por_coordenador - end
//	processing freq_media_coordenador - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_freq_media_coordenador->afterSuccessfulSave();
			}
//	processing freq_media_coordenador - end
//	processing min_freq_coordenador - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_min_freq_coordenador->afterSuccessfulSave();
			}
//	processing min_freq_coordenador - end
//	processing freq_media_aluno - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_freq_media_aluno->afterSuccessfulSave();
			}
//	processing freq_media_aluno - end
//	processing min_freq_aluno - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_min_freq_aluno->afterSuccessfulSave();
			}
//	processing min_freq_aluno - end
//	processing freq_media_professor - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_freq_media_professor->afterSuccessfulSave();
			}
//	processing freq_media_professor - end
//	processing min_freq_professor - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_min_freq_professor->afterSuccessfulSave();
			}
//	processing min_freq_professor - end
//	processing meta_atividades - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_meta_atividades->afterSuccessfulSave();
			}
//	processing meta_atividades - end
//	processing atividades_elaboradas - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_atividades_elaboradas->afterSuccessfulSave();
			}
//	processing atividades_elaboradas - end
//	processing atividades_realizadas - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_atividades_realizadas->afterSuccessfulSave();
			}
//	processing atividades_realizadas - end
//	processing score - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_score->afterSuccessfulSave();
			}
//	processing score - end
//	processing operador - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_operador->afterSuccessfulSave();
			}
//	processing operador - end
//	processing data_insercao - start
			$inlineAddOption = true;
			if($inlineAddOption)
			{
				$control_data_insercao->afterSuccessfulSave();
			}
//	processing data_insercao - end

			$afterAdd_id = '';	
			if($eventObj->exists("AfterAdd") && $inlineadd!=ADD_MASTER){
				$eventObj->AfterAdd($avalues,$keys,(bool)$inlineadd, $pageObject);
			} else if ($eventObj->exists("AfterAdd") && $inlineadd==ADD_MASTER){
				if($onFly)
					$eventObj->AfterAdd($avalues,$keys,(bool)$inlineadd, $pageObject);
				else{
					$afterAdd_id = generatePassword(20);	
				
					$_SESSION['after_add_data'][$afterAdd_id] = array(
						'avalues'=>$avalues,
						'keys'=>$keys,
						'inlineadd'=>(bool)$inlineadd,
						'time' => time()
					);	
				}
			}
				
			if($inlineadd==ADD_SIMPLE || $inlineadd==ADD_MASTER)
			{
				$permis = array();
				$keylink = "";$k = 0;
				foreach($keys as $idx=>$val)
				{
					if($k!=0)
						$keylink .="&";
					$keylink .="editid".(++$k)."=".htmlspecialchars(rawurlencode(@$val));
				}
				$permis = $pageObject->getPermissions();				
				if (count($keys))
				{
					$message .="</br>";
					if($pageObject->pSet->hasEditPage() && $permis['edit'])
						$message .='&nbsp;<a href=\'senuc_score_edit.php?'.$keylink.'\'>'."Editar".'</a>&nbsp;';
					if($pageObject->pSet->hasViewPage() && $permis['search'])
						$message .='&nbsp;<a href=\'senuc_score_view.php?'.$keylink.'\'>'."Exibir".'</a>&nbsp;';
				}
				$mesClass = "mes_ok";	
			}
		}
		elseif($inlineadd!=ADD_INLINE)
			$mesClass = "mes_not";	
	}
	else
	{
		$message = $usermessage;
		$status = "DECLINED";
		$readavalues = true;
	}
}
if($message)
	$message = "<div class='message ".$mesClass."'>".$message."</div>";

// PRG rule, to avoid POSTDATA resend
if (no_output_done() && $inlineadd==ADD_SIMPLE && $IsSaved)
{
	// saving message
	$_SESSION["message_add"] = ($message ? $message : "");
	// redirect
	header("Location: senuc_score_".$pageObject->getPageType().".php");
	// turned on output buffering, so we need to stop script
	exit();
}

if($inlineadd==ADD_MASTER && $IsSaved)
	$_SESSION["message_add"] = ($message ? $message : "");
	
// for PRG rule, to avoid POSTDATA resend. Saving mess in session
if($inlineadd==ADD_SIMPLE && isset($_SESSION["message_add"]))
{
	$message = $_SESSION["message_add"];
	unset($_SESSION["message_add"]);
}

$defvalues=array();

//	copy record
if(array_key_exists("copyid1",$_REQUEST) || array_key_exists("editid1",$_REQUEST))
{
	$copykeys=array();
	if(array_key_exists("copyid1",$_REQUEST))
	{
		$copykeys["id"]=postvalue("copyid1");
	}
	else
	{
		$copykeys["id"]=postvalue("editid1");
	}
	$strWhere=KeyWhere($copykeys);
	$strWhere=whereAdd($strWhere,SecuritySQL("Search"));
	$strSQL = $gQuery->gSQLWhere($strWhere);

	LogInfo($strSQL);
	$rs = db_query($strSQL,$conn);
	$defvalues = $pageObject->cipherer->DecryptFetchedArray($rs);
	if(!$defvalues)
		$defvalues=array();
//	clear key fields
	$defvalues["id"]="";
//call CopyOnLoad event
	if($eventObj->exists("CopyOnLoad"))
		$eventObj->CopyOnLoad($defvalues,$strWhere, $pageObject);
}
else
{
}

//	insert default ownerid value if exists
	if($strOriginalTableName == $pageObject->pSet->getOwnerTable("idnucleo"))
		$defvalues["idnucleo"] = prepare_for_db("idnucleo",$_SESSION["_".$strTableName."_OwnerID"]);

//	set default values for the foreign keys

if(@$_SESSION[$sessionPrefix."_mastertable"]=="senuc_nucleo")
{
	if(postvalue("masterkey1"))
		$_SESSION[$sessionPrefix."_masterkey1"] = postvalue("masterkey1");

	if(postvalue("mainMPageType")<>"add")
		$defvalues["idnucleo"] = @$_SESSION[$sessionPrefix."_masterkey1"];	
	
}

if($readavalues)
{
	$defvalues["tipo_nucleo"]=@$avalues["tipo_nucleo"];
	$defvalues["ano"]=@$avalues["ano"];
	$defvalues["mes"]=@$avalues["mes"];
	$defvalues["coordenadores"]=@$avalues["coordenadores"];
	$defvalues["professores"]=@$avalues["professores"];
	$defvalues["alunos"]=@$avalues["alunos"];
	$defvalues["meta_alunos"]=@$avalues["meta_alunos"];
	$defvalues["dias_funcionamento"]=@$avalues["dias_funcionamento"];
	$defvalues["meta_funcionamento"]=@$avalues["meta_funcionamento"];
	$defvalues["alunos_por_coordenador"]=@$avalues["alunos_por_coordenador"];
	$defvalues["meta_alunos_por_coordenador"]=@$avalues["meta_alunos_por_coordenador"];
	$defvalues["freq_media_coordenador"]=@$avalues["freq_media_coordenador"];
	$defvalues["min_freq_coordenador"]=@$avalues["min_freq_coordenador"];
	$defvalues["freq_media_aluno"]=@$avalues["freq_media_aluno"];
	$defvalues["min_freq_aluno"]=@$avalues["min_freq_aluno"];
	$defvalues["freq_media_professor"]=@$avalues["freq_media_professor"];
	$defvalues["min_freq_professor"]=@$avalues["min_freq_professor"];
	$defvalues["meta_atividades"]=@$avalues["meta_atividades"];
	$defvalues["atividades_elaboradas"]=@$avalues["atividades_elaboradas"];
	$defvalues["atividades_realizadas"]=@$avalues["atividades_realizadas"];
	$defvalues["score"]=@$avalues["score"];
	$defvalues["operador"]=@$avalues["operador"];
	$defvalues["data_insercao"]=@$avalues["data_insercao"];
}

if($eventObj->exists("ProcessValuesAdd"))
	$eventObj->ProcessValuesAdd($defvalues, $pageObject);


//for basic files
$includes="";

if($inlineadd!=ADD_INLINE)
{
	if($inlineadd!=ADD_ONTHEFLY && $inlineadd!=ADD_POPUP)
	{
		$includes .="<script language=\"JavaScript\" src=\"include/loadfirst.js\"></script>\r\n";
				$includes.="<script type=\"text/javascript\" src=\"include/lang/".getLangFileName(mlang_getcurrentlang()).".js\"></script>";
		if (!isMobile())
			$includes.="<div id=\"search_suggest\"></div>\r\n";
	}
	
	if(!$pageObject->isAppearOnTabs("tipo_nucleo"))
		$xt->assign("tipo_nucleo_fieldblock",true);
	else
		$xt->assign("tipo_nucleo_tabfieldblock",true);
	$xt->assign("tipo_nucleo_label",true);
	if(isEnableSection508())
		$xt->assign_section("tipo_nucleo_label","<label for=\"".GetInputElementId("tipo_nucleo", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("ano"))
		$xt->assign("ano_fieldblock",true);
	else
		$xt->assign("ano_tabfieldblock",true);
	$xt->assign("ano_label",true);
	if(isEnableSection508())
		$xt->assign_section("ano_label","<label for=\"".GetInputElementId("ano", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("mes"))
		$xt->assign("mes_fieldblock",true);
	else
		$xt->assign("mes_tabfieldblock",true);
	$xt->assign("mes_label",true);
	if(isEnableSection508())
		$xt->assign_section("mes_label","<label for=\"".GetInputElementId("mes", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("coordenadores"))
		$xt->assign("coordenadores_fieldblock",true);
	else
		$xt->assign("coordenadores_tabfieldblock",true);
	$xt->assign("coordenadores_label",true);
	if(isEnableSection508())
		$xt->assign_section("coordenadores_label","<label for=\"".GetInputElementId("coordenadores", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("professores"))
		$xt->assign("professores_fieldblock",true);
	else
		$xt->assign("professores_tabfieldblock",true);
	$xt->assign("professores_label",true);
	if(isEnableSection508())
		$xt->assign_section("professores_label","<label for=\"".GetInputElementId("professores", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("alunos"))
		$xt->assign("alunos_fieldblock",true);
	else
		$xt->assign("alunos_tabfieldblock",true);
	$xt->assign("alunos_label",true);
	if(isEnableSection508())
		$xt->assign_section("alunos_label","<label for=\"".GetInputElementId("alunos", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("meta_alunos"))
		$xt->assign("meta_alunos_fieldblock",true);
	else
		$xt->assign("meta_alunos_tabfieldblock",true);
	$xt->assign("meta_alunos_label",true);
	if(isEnableSection508())
		$xt->assign_section("meta_alunos_label","<label for=\"".GetInputElementId("meta_alunos", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("dias_funcionamento"))
		$xt->assign("dias_funcionamento_fieldblock",true);
	else
		$xt->assign("dias_funcionamento_tabfieldblock",true);
	$xt->assign("dias_funcionamento_label",true);
	if(isEnableSection508())
		$xt->assign_section("dias_funcionamento_label","<label for=\"".GetInputElementId("dias_funcionamento", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("meta_funcionamento"))
		$xt->assign("meta_funcionamento_fieldblock",true);
	else
		$xt->assign("meta_funcionamento_tabfieldblock",true);
	$xt->assign("meta_funcionamento_label",true);
	if(isEnableSection508())
		$xt->assign_section("meta_funcionamento_label","<label for=\"".GetInputElementId("meta_funcionamento", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("alunos_por_coordenador"))
		$xt->assign("alunos_por_coordenador_fieldblock",true);
	else
		$xt->assign("alunos_por_coordenador_tabfieldblock",true);
	$xt->assign("alunos_por_coordenador_label",true);
	if(isEnableSection508())
		$xt->assign_section("alunos_por_coordenador_label","<label for=\"".GetInputElementId("alunos_por_coordenador", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("meta_alunos_por_coordenador"))
		$xt->assign("meta_alunos_por_coordenador_fieldblock",true);
	else
		$xt->assign("meta_alunos_por_coordenador_tabfieldblock",true);
	$xt->assign("meta_alunos_por_coordenador_label",true);
	if(isEnableSection508())
		$xt->assign_section("meta_alunos_por_coordenador_label","<label for=\"".GetInputElementId("meta_alunos_por_coordenador", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("freq_media_coordenador"))
		$xt->assign("freq_media_coordenador_fieldblock",true);
	else
		$xt->assign("freq_media_coordenador_tabfieldblock",true);
	$xt->assign("freq_media_coordenador_label",true);
	if(isEnableSection508())
		$xt->assign_section("freq_media_coordenador_label","<label for=\"".GetInputElementId("freq_media_coordenador", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("min_freq_coordenador"))
		$xt->assign("min_freq_coordenador_fieldblock",true);
	else
		$xt->assign("min_freq_coordenador_tabfieldblock",true);
	$xt->assign("min_freq_coordenador_label",true);
	if(isEnableSection508())
		$xt->assign_section("min_freq_coordenador_label","<label for=\"".GetInputElementId("min_freq_coordenador", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("freq_media_aluno"))
		$xt->assign("freq_media_aluno_fieldblock",true);
	else
		$xt->assign("freq_media_aluno_tabfieldblock",true);
	$xt->assign("freq_media_aluno_label",true);
	if(isEnableSection508())
		$xt->assign_section("freq_media_aluno_label","<label for=\"".GetInputElementId("freq_media_aluno", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("min_freq_aluno"))
		$xt->assign("min_freq_aluno_fieldblock",true);
	else
		$xt->assign("min_freq_aluno_tabfieldblock",true);
	$xt->assign("min_freq_aluno_label",true);
	if(isEnableSection508())
		$xt->assign_section("min_freq_aluno_label","<label for=\"".GetInputElementId("min_freq_aluno", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("freq_media_professor"))
		$xt->assign("freq_media_professor_fieldblock",true);
	else
		$xt->assign("freq_media_professor_tabfieldblock",true);
	$xt->assign("freq_media_professor_label",true);
	if(isEnableSection508())
		$xt->assign_section("freq_media_professor_label","<label for=\"".GetInputElementId("freq_media_professor", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("min_freq_professor"))
		$xt->assign("min_freq_professor_fieldblock",true);
	else
		$xt->assign("min_freq_professor_tabfieldblock",true);
	$xt->assign("min_freq_professor_label",true);
	if(isEnableSection508())
		$xt->assign_section("min_freq_professor_label","<label for=\"".GetInputElementId("min_freq_professor", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("meta_atividades"))
		$xt->assign("meta_atividades_fieldblock",true);
	else
		$xt->assign("meta_atividades_tabfieldblock",true);
	$xt->assign("meta_atividades_label",true);
	if(isEnableSection508())
		$xt->assign_section("meta_atividades_label","<label for=\"".GetInputElementId("meta_atividades", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("atividades_elaboradas"))
		$xt->assign("atividades_elaboradas_fieldblock",true);
	else
		$xt->assign("atividades_elaboradas_tabfieldblock",true);
	$xt->assign("atividades_elaboradas_label",true);
	if(isEnableSection508())
		$xt->assign_section("atividades_elaboradas_label","<label for=\"".GetInputElementId("atividades_elaboradas", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("atividades_realizadas"))
		$xt->assign("atividades_realizadas_fieldblock",true);
	else
		$xt->assign("atividades_realizadas_tabfieldblock",true);
	$xt->assign("atividades_realizadas_label",true);
	if(isEnableSection508())
		$xt->assign_section("atividades_realizadas_label","<label for=\"".GetInputElementId("atividades_realizadas", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("score"))
		$xt->assign("score_fieldblock",true);
	else
		$xt->assign("score_tabfieldblock",true);
	$xt->assign("score_label",true);
	if(isEnableSection508())
		$xt->assign_section("score_label","<label for=\"".GetInputElementId("score", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("operador"))
		$xt->assign("operador_fieldblock",true);
	else
		$xt->assign("operador_tabfieldblock",true);
	$xt->assign("operador_label",true);
	if(isEnableSection508())
		$xt->assign_section("operador_label","<label for=\"".GetInputElementId("operador", $id, PAGE_ADD)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("data_insercao"))
		$xt->assign("data_insercao_fieldblock",true);
	else
		$xt->assign("data_insercao_tabfieldblock",true);
	$xt->assign("data_insercao_label",true);
	if(isEnableSection508())
		$xt->assign_section("data_insercao_label","<label for=\"".GetInputElementId("data_insercao", $id, PAGE_ADD)."\">","</label>");
	
	
	
	if($inlineadd!=ADD_ONTHEFLY && $inlineadd!=ADD_POPUP)
	{
		$pageObject->body["begin"] .= $includes;
				$xt->assign("backbutton_attrs","id=\"backButton".$id."\"");
		$xt->assign("back_button",true);
	}
	else
	{		
		$xt->assign("cancelbutton_attrs", "id=\"cancelButton".$id."\"");
		$xt->assign("cancel_button",true);
		$xt->assign("header","");
	}
	$xt->assign("save_button",true);
}
$xt->assign("savebutton_attrs","id=\"saveButton".$id."\"");
$xt->assign("message_block",true);
$xt->assign("message",$message);
if(!strlen($message))
{
	$xt->displayBrickHidden("message");
}

//	show readonly fields
$linkdata="";

$i = 0;
$jsKeys = array();
$keyFields = array();
foreach($keys as $field=>$value)
{
	$keyFields[$i] = $field;
	$jsKeys[$i++] = $value;
}

if(@$_POST["a"]=="added" && $inlineadd==ADD_ONTHEFLY)
{
	if( !$error_happened && $status!="DECLINED")
	{
		$addedData = GetAddedDataLookupQuery($pageObject, $keys, false);
		$data =& $addedData[0];	
		
		if($data)
		{
			$respData = array($addedData[1]["linkField"] => @$data[$addedData[1]["linkFieldIndex"]], $addedData[1]["displayField"] => @$data[$addedData[1]["displayFieldIndex"]]);
		}
		else
		{
			$respData = array($addedData[1]["linkField"] => @$avalues[$addedData[1]["linkField"]], $addedData[1]["displayField"] => @$avalues[$addedData[1]["displayField"]]);
		}		
		$returnJSON['success'] = true;
		$returnJSON['keys'] = $jsKeys;
		$returnJSON['keyFields'] = $keyFields;
		$returnJSON['vals'] = $respData;
		$returnJSON['fields'] = $showFields;
	}
	else
	{
		$returnJSON['success'] = false;
		$returnJSON['message'] = $message;
	}
	echo "<textarea>".htmlspecialchars(my_json_encode($returnJSON))."</textarea>";
	exit();
}

if(@$_POST["a"]=="added" && ($inlineadd == ADD_INLINE || $inlineadd == ADD_MASTER || $inlineadd==ADD_POPUP)) 
{
	//Preparation   view values
	//	get current values and show edit controls
	$dispFieldAlias = "";
	$data=0;
	$linkAndDispVals = array();
	if(count($keys))
	{
		$where=KeyWhere($keys);
		//	select only owned records
		$where=whereAdd($where,SecuritySQL("Search"));
		
		$forLookup = postvalue('forLookup');
		if ($forLookup)
		{
			$addedData = GetAddedDataLookupQuery($pageObject, $keys, true);
			$data =& $addedData[0];
			$linkAndDispVals = array('linkField' => $addedData[0][$addedData[1]["linkField"]], 'displayField' => $addedData[0][$addedData[1]["displayField"]]);
		}
		else
		{
			$strSQL = $gQuery->gSQLWhere_having_fromQuery('', $where, '');		
		
			LogInfo($strSQL);
			$rs=db_query($strSQL,$conn);
			$data = $pageObject->cipherer->DecryptFetchedArray($rs);
		}
	}
	if(!$data)
	{
		$data=$avalues;
		$HaveData=false;
	}
	//check if correct values added

	$keylink="";
	$keylink.="&key1=".htmlspecialchars(rawurlencode(@$data["id"]));
	
////////////////////////////////////////////
//	tipo_nucleo
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("tipo_nucleo", $data, $keylink);
		$showValues["tipo_nucleo"] = $value;
		$showFields[] = "tipo_nucleo";
	}	
//	ano
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("ano", $data, $keylink);
		$showValues["ano"] = $value;
		$showFields[] = "ano";
	}	
//	mes
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("mes", $data, $keylink);
		$showValues["mes"] = $value;
		$showFields[] = "mes";
	}	
//	coordenadores
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("coordenadores", $data, $keylink);
		$showValues["coordenadores"] = $value;
		$showFields[] = "coordenadores";
	}	
//	professores
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("professores", $data, $keylink);
		$showValues["professores"] = $value;
		$showFields[] = "professores";
	}	
//	alunos
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("alunos", $data, $keylink);
		$showValues["alunos"] = $value;
		$showFields[] = "alunos";
	}	
//	meta_alunos
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("meta_alunos", $data, $keylink);
		$showValues["meta_alunos"] = $value;
		$showFields[] = "meta_alunos";
	}	
//	dias_funcionamento
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("dias_funcionamento", $data, $keylink);
		$showValues["dias_funcionamento"] = $value;
		$showFields[] = "dias_funcionamento";
	}	
//	meta_funcionamento
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("meta_funcionamento", $data, $keylink);
		$showValues["meta_funcionamento"] = $value;
		$showFields[] = "meta_funcionamento";
	}	
//	alunos_por_coordenador
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("alunos_por_coordenador", $data, $keylink);
		$showValues["alunos_por_coordenador"] = $value;
		$showFields[] = "alunos_por_coordenador";
	}	
//	meta_alunos_por_coordenador
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("meta_alunos_por_coordenador", $data, $keylink);
		$showValues["meta_alunos_por_coordenador"] = $value;
		$showFields[] = "meta_alunos_por_coordenador";
	}	
//	freq_media_coordenador
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("freq_media_coordenador", $data, $keylink);
		$showValues["freq_media_coordenador"] = $value;
		$showFields[] = "freq_media_coordenador";
	}	
//	min_freq_coordenador
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("min_freq_coordenador", $data, $keylink);
		$showValues["min_freq_coordenador"] = $value;
		$showFields[] = "min_freq_coordenador";
	}	
//	freq_media_aluno
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("freq_media_aluno", $data, $keylink);
		$showValues["freq_media_aluno"] = $value;
		$showFields[] = "freq_media_aluno";
	}	
//	min_freq_aluno
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("min_freq_aluno", $data, $keylink);
		$showValues["min_freq_aluno"] = $value;
		$showFields[] = "min_freq_aluno";
	}	
//	freq_media_professor
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("freq_media_professor", $data, $keylink);
		$showValues["freq_media_professor"] = $value;
		$showFields[] = "freq_media_professor";
	}	
//	min_freq_professor
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("min_freq_professor", $data, $keylink);
		$showValues["min_freq_professor"] = $value;
		$showFields[] = "min_freq_professor";
	}	
//	meta_atividades
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("meta_atividades", $data, $keylink);
		$showValues["meta_atividades"] = $value;
		$showFields[] = "meta_atividades";
	}	
//	atividades_elaboradas
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("atividades_elaboradas", $data, $keylink);
		$showValues["atividades_elaboradas"] = $value;
		$showFields[] = "atividades_elaboradas";
	}	
//	atividades_realizadas
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("atividades_realizadas", $data, $keylink);
		$showValues["atividades_realizadas"] = $value;
		$showFields[] = "atividades_realizadas";
	}	
//	score
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("score", $data, $keylink);
		$showValues["score"] = $value;
		$showFields[] = "score";
	}	
//	operador
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("operador", $data, $keylink);
		$showValues["operador"] = $value;
		$showFields[] = "operador";
	}	
//	data_insercao
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value = $pageObject->showDBValue("data_insercao", $data, $keylink);
		$showValues["data_insercao"] = $value;
		$showFields[] = "data_insercao";
	}	
		$showRawValues["id"] = substr($data["id"],0,100);
		$showRawValues["idnucleo"] = substr($data["idnucleo"],0,100);
		$showRawValues["idregional"] = substr($data["idregional"],0,100);
		$showRawValues["tipo_nucleo"] = substr($data["tipo_nucleo"],0,100);
		$showRawValues["ano"] = substr($data["ano"],0,100);
		$showRawValues["mes"] = substr($data["mes"],0,100);
		$showRawValues["coordenadores"] = substr($data["coordenadores"],0,100);
		$showRawValues["professores"] = substr($data["professores"],0,100);
		$showRawValues["alunos"] = substr($data["alunos"],0,100);
		$showRawValues["meta_alunos"] = substr($data["meta_alunos"],0,100);
		$showRawValues["dias_funcionamento"] = substr($data["dias_funcionamento"],0,100);
		$showRawValues["meta_funcionamento"] = substr($data["meta_funcionamento"],0,100);
		$showRawValues["alunos_por_coordenador"] = substr($data["alunos_por_coordenador"],0,100);
		$showRawValues["meta_alunos_por_coordenador"] = substr($data["meta_alunos_por_coordenador"],0,100);
		$showRawValues["freq_media_coordenador"] = substr($data["freq_media_coordenador"],0,100);
		$showRawValues["min_freq_coordenador"] = substr($data["min_freq_coordenador"],0,100);
		$showRawValues["freq_media_aluno"] = substr($data["freq_media_aluno"],0,100);
		$showRawValues["min_freq_aluno"] = substr($data["min_freq_aluno"],0,100);
		$showRawValues["freq_media_professor"] = substr($data["freq_media_professor"],0,100);
		$showRawValues["min_freq_professor"] = substr($data["min_freq_professor"],0,100);
		$showRawValues["meta_atividades"] = substr($data["meta_atividades"],0,100);
		$showRawValues["atividades_elaboradas"] = substr($data["atividades_elaboradas"],0,100);
		$showRawValues["atividades_realizadas"] = substr($data["atividades_realizadas"],0,100);
		$showRawValues["score"] = substr($data["score"],0,100);
		$showRawValues["operador"] = substr($data["operador"],0,100);
		$showRawValues["data_insercao"] = substr($data["data_insercao"],0,100);
	
	// for custom expression for display field
	if ($dispFieldAlias)
	{
		$showValues[] = $data[$dispFieldAlias];	
		$showFields[] = $dispFieldAlias;
		$showRawValues[] = substr($data[$dispFieldAlias],0,100);
	}
	
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_POPUP)
	{	
		if($IsSaved && count($showValues))
		{
			$returnJSON['success'] = true;
			if($HaveData){
				$returnJSON['noKeys'] = false;
			}else{
				$returnJSON['noKeys'] = true;
			}
			
			$returnJSON['keys'] = $jsKeys;
			$returnJSON['keyFields'] = $keyFields;
			$returnJSON['vals'] = $showValues;
			$returnJSON['fields'] = $showFields;
			$returnJSON['rawVals'] = $showRawValues;
			$returnJSON['detKeys'] = $showDetailKeys;
			$returnJSON['userMess'] = $usermessage;
			$returnJSON['hrefs'] = $pageObject->buildDetailGridLinks($showDetailKeys);
			// add link and display value if list page is lookup with search
			if(array_key_exists('linkField', $linkAndDispVals))
			{
				$returnJSON['linkValue'] = $linkAndDispVals['linkField'];
				$returnJSON['displayValue'] = $linkAndDispVals['displayField'];
			}
			if($globalEvents->exists("IsRecordEditable", $strTableName))
			{ 
				if(!$globalEvents->IsRecordEditable($showRawValues, true, $strTableName))
					$returnJSON['nonEditable'] = true;
			}
			
			if($inlineadd==ADD_POPUP && isset($_SESSION[$strTableName."_count_captcha"]) || $_SESSION[$strTableName."_count_captcha"]>0 || $_SESSION[$strTableName."_count_captcha"]<5)
				$returnJSON['hideCaptcha'] = true;
		}
		else
		{
			$returnJSON['success'] = false;
			$returnJSON['message'] = $message;
			if(!$pageObject->isCaptchaOk)
				$returnJSON['captcha'] = false;
		}
		echo "<textarea>".htmlspecialchars(my_json_encode($returnJSON))."</textarea>";
		exit();
	}
} 

/////////////////////////////////////////////////////////////
if($inlineadd==ADD_MASTER)
{
	$respJSON = array();
	if(($_POST["a"]=="added" && $IsSaved))
	{
		$respJSON['afterAddId'] = $afterAdd_id;
		$respJSON['success'] = true;
		$respJSON['fields'] = $showFields;
		$respJSON['vals'] = $showValues;
		if($onFly){
			if($HaveData)
				$respJSON['noKeys'] = false;
			else
				$respJSON['noKeys'] = true;
			$respJSON['keys'] = $jsKeys;
			$respJSON['keyFields'] = $keyFields;
			$respJSON['rawVals'] = $showRawValues;
			$respJSON['detKeys'] = $showDetailKeys;
			$respJSON['userMess'] = $usermessage;
			$respJSON['hrefs'] = $pageObject->buildDetailGridLinks($showDetailKeys);
			if($globalEvents->exists("IsRecordEditable", $strTableName))
			{
				if(!$globalEvents->IsRecordEditable($showRawValues, true, $strTableName))
					$respJSON['nonEditable'] = true;
			}
		}
		$respJSON['mKeys'] = array();
		for($i=0;$i<count($dpParams['ids']);$i++)
		{
			$data=0;
			if(count($keys))
			{
				$where=KeyWhere($keys);
							//	select only owned records
				$where=whereAdd($where,SecuritySQL("Search"));
				$strSQL = $gQuery->gSQLWhere($where);
				LogInfo($strSQL);
				$rs = db_query($strSQL,$conn);
				$data = $pageObject->cipherer->DecryptFetchedArray($rs);
			}
			if(!$data)
				$data=$avalues;
			
			$mKeyId = 1;
			foreach($mKeys[$dpParams['strTableNames'][$i]] as $mk)
			{
				if($data[$mk])
					$respJSON['mKeys'][$dpParams['strTableNames'][$i]]['masterkey'.$mKeyId++] = $data[$mk];
				else
					$respJSON['mKeys'][$dpParams['strTableNames'][$i]]['masterkey'.$mKeyId++] = '';
			}
		}
		if(isset($_SESSION[$strTableName."_count_captcha"]) || $_SESSION[$strTableName."_count_captcha"]>0 || $_SESSION[$strTableName."_count_captcha"]<5)
			$respJSON['hidecaptcha'] = true;
	}
	else{
			$respJSON['success'] = false;
			if(!$pageObject->isCaptchaOk)
				$respJSON['captcha'] = false;
			else
				$respJSON['error'] = $message;
			if($onFly)
				$respJSON['message'] = $message;
		}
	echo "<textarea>".htmlspecialchars(my_json_encode($respJSON))."</textarea>";
	exit();
}

/////////////////////////////////////////////////////////////
//	prepare Edit Controls
/////////////////////////////////////////////////////////////

//	validation stuff
$regex='';
$regexmessage='';
$regextype = '';
$control = array();

foreach($addFields as $fName)
{
	$gfName = GoodFieldName($fName);
	$controls = array('controls'=>array());
	if(!$detailKeys || !in_array($fName, $detailKeys) || $fName == postvalue("category"))
	{
		$control[$gfName] = array();
		$control[$gfName]["func"] = "xt_buildeditcontrol";
		$control[$gfName]["params"] = array();
		$control[$gfName]["params"]["id"] = $id;
		$control[$gfName]["params"]["ptype"] = PAGE_ADD;
		$control[$gfName]["params"]["field"] = $fName;
		$control[$gfName]["params"]["value"] = @$defvalues[$fName];
		$control[$gfName]["params"]["pageObj"] = $pageObject;
		if($pageObject->pSet->isUseRTE($fName))
			$_SESSION[$strTableName."_".$fName."_rte"] = @$defvalues[$fName];
		
		//	Begin Add validation
		$arrValidate = $pageObject->pSet->getValidation($fName);
		$control[$gfName]["params"]["validate"] = $arrValidate;
		//	End Add validation
	}
	$controls["controls"]['ctrlInd'] = 0;
	$controls["controls"]['id'] = $id;
	$controls["controls"]['fieldName'] = $fName;
	//if richEditor for field
	if($pageObject->pSet->isUseRTE($fName))
	{
		if(!$detailKeys || !in_array($fName, $detailKeys))
			$control[$gfName]["params"]["mode"]="add";
		$controls["controls"]['mode'] = "add";
	}
	else
	{
		if($inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		{
			if(!$detailKeys || !in_array($fName, $detailKeys) || $fName == postvalue("category"))	
				$control[$gfName]["params"]["mode"]="inline_add";
			$controls["controls"]['mode'] = "inline_add";
		}
		else
		{
			if(!$detailKeys || !in_array($fName, $detailKeys) || $fName == postvalue("category"))	
				$control[$gfName]["params"]["mode"]="add";
			$controls["controls"]['mode'] = "add";
		}
	}
	
	if(!$detailKeys || !in_array($fName, $detailKeys))
		$xt->assignbyref($gfName."_editcontrol",$control[$gfName]);
	elseif($detailKeys && in_array($fName, $detailKeys))
		$controls["controls"]['value'] = @$defvalues[$fName];
	
	// category control field
	$strCategoryControl = $pageObject->isDependOnField($fName);
	
	if($strCategoryControl!==false && in_array($strCategoryControl, $addFields))
		$vals = array($fName => @$defvalues[$fName], $strCategoryControl => @$defvalues[$strCategoryControl]);
	else
		$vals = array($fName => @$defvalues[$fName]);
	
	$preload = $pageObject->fillPreload($fName, $vals);
	if($preload!==false)
	{
		$controls["controls"]['preloadData'] = $preload;
		if(!@$defvalues[$fName] && count($preload["vals"])>0)
			$defvalues[$fName] = $preload["vals"][0];
	}
	$pageObject->fillControlsMap($controls);
	
	//fill field tool tips
	$pageObject->fillFieldToolTips($fName);
	
	// fill special settings for timepicker
	if($pageObject->pSet->getEditFormat($fName) == 'Time')
		$pageObject->fillTimePickSettings($fName, @$defvalues[$fName]);
	
	if((($detailKeys && in_array($fName, $detailKeys)) || $fName == postvalue("category")) && array_key_exists($fName, $defvalues))
	{
		$value = $pageObject->showDBValue($fName, $defvalues);
		
		$xt->assign($gfName."_editcontrol", $value);
	}
}

//fill tab groups name and sections name to controls
$pageObject->fillCntrlTabGroups();

/////////////////////////////////////////////////////////////
if($pageObject->isShowDetailTables && ($inlineadd==ADD_SIMPLE || $inlineadd==ADD_POPUP) && !isMobile())
{
	if(count($dpParams['ids']))
	{
		$xt->assign("detail_tables",true);
		include('classes/listpage.php');
		include('classes/listpage_embed.php');
		include('classes/listpage_dpinline.php');
		include("classes/searchclause.php");
	}
	
	$dControlsMap = array();
	$dViewControlsMap = array();
		
	$flyId = $ids+1;
	for($d=0;$d<count($dpParams['ids']);$d++)
	{
		$options = array();
		//array of params for classes
		$options["mode"] = LIST_DETAILS;
		$options["pageType"] = PAGE_LIST;
		$options["masterPageType"] = PAGE_ADD;
		$options["mainMasterPageType"] = PAGE_ADD;
		$options['masterTable'] = "senuc_score";
		$options['firstTime'] = 1;
		
		$strTableName = $dpParams['strTableNames'][$d];
		include_once("include/".GetTableURL($strTableName)."_settings.php");
		
		$layout = GetPageLayout(GoodFieldName($strTableName), PAGE_LIST);
		if($layout)
		{
			$rtl = $xt->getReadingOrder() == 'RTL' ? 'RTL' : '';
			$xt->cssFiles[] = array("stylepath" => "styles/".$layout->style.'/style'.$rtl.".css"
				, "pagestylepath" => "pagestyles/".$layout->name.$rtl.".css");
			$xt->IEcssFiles[] = array("stylepathIE" => "styles/".$layout->style.'/styleIE'.".css");
		}	
			
		$options['xt'] = new Xtempl();
		$options['id'] = $dpParams['ids'][$d];
		$options['flyId'] = $flyId++;
		$mkr = 1;
		
		foreach($mKeys[$strTableName] as $mk)
		{
			if($defvalues[$mk])
				$options['masterKeysReq'][$mkr++] = $defvalues[$mk];
			else
				$options['masterKeysReq'][$mkr++] = '';
		}
		$listPageObject = ListPage::createListPage($strTableName,$options);
		
		// prepare code
		$listPageObject->prepareForBuildPage();
		$flyId = $listPageObject->recId+1;
		
		//set page events
		foreach($listPageObject->eventsObject->events as $event => $name)
			$listPageObject->xt->assign_event($event, $listPageObject->eventsObject, $event, array());
		
		//add detail settings to master settings
		$listPageObject->addControlsJSAndCSS();
		$listPageObject->fillSetCntrlMaps();
		$pageObject->jsSettings['tableSettings'][$strTableName]	= $listPageObject->jsSettings['tableSettings'][$strTableName];

		$dControlsMap[$strTableName] = $listPageObject->controlsMap;
		$dViewControlsMap[$strTableName] = $listPageObject->viewControlsMap;
		
		foreach($listPageObject->jsSettings["global"]["shortTNames"] as $tName => $shortTName){
			$pageObject->settingsMap["globalSettings"]["shortTNames"][$tName] = $shortTName;
		}
		
		//Add detail's js files to master's files
		$pageObject->copyAllJSFiles($listPageObject->grabAllJSFiles());
		
		//Add detail's css files to master's files
		$pageObject->copyAllCSSFiles($listPageObject->grabAllCSSFiles());
		
		$xtParams = array("method"=>'showPage', "params"=> false);
		$xtParams['object'] = $listPageObject;
		$xt->assign("displayDetailTable_".GoodFieldName($listPageObject->tName), $xtParams);
		$pageObject->controlsMap['dpTablesParams'][] = array('tName'=>$strTableName, 'id'=>$options['id']);
	}
	$pageObject->controlsMap['dControlsMap'] = $dControlsMap;
	$pageObject->viewControlsMap['dViewControlsMap'] = $dViewControlsMap;
	$strTableName = "senuc_score";
}
/////////////////////////////////////////////////////////////
//fill jsSettings and ControlsHTMLMap
$pageObject->fillSetCntrlMaps();

$pageObject->addCommonJs();

//For mobile version in apple device

if($inlineadd == ADD_SIMPLE)
{
	$pageObject->body['end'] = array();
	$pageObject->body['end']["method"] = "assignBodyEnd";
	$pageObject->body['end']["object"] = &$pageObject;
	$xt->assign("body", $pageObject->body);
	$xt->assign("flybody",true);
}

if($inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_MASTER || $inlineadd==ADD_POPUP)
{ 
	$xt->assign("footer",false);
	$xt->assign("header",false);
	$xt->assign("flybody", $pageObject->body);
	$xt->assign("body",true);
}	

$xt->assign("style_block",true);
$pageObject->xt->assign("legend", true);

if($eventObj->exists("BeforeShowAdd"))
	$eventObj->BeforeShowAdd($xt, $templatefile, $pageObject);
	
if($inlineadd != ADD_SIMPLE)
{
	$returnJSON['controlsMap'] = $pageObject->controlsHTMLMap;
	$returnJSON['viewControlsMap'] = $pageObject->viewControlsHTMLMap;
	$returnJSON['settings'] = $pageObject->jsSettings;	
}

if($inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
{
	$xt->load_template($templatefile);
	$returnJSON['html'] = $xt->fetch_loaded('style_block').$xt->fetch_loaded('body');
	if(count($pageObject->includes_css))
		$returnJSON['CSSFiles'] = array_unique($pageObject->includes_css);
	if(count($pageObject->includes_cssIE))
		$returnJSON['CSSFilesIE'] = array_unique($pageObject->includes_cssIE);
	$returnJSON["additionalJS"] = $pageObject->grabAllJsFiles();
	$returnJSON['idStartFrom'] = $id+1;	
	echo (my_json_encode($returnJSON)); 
}
elseif ($inlineadd == ADD_INLINE)
{
	$xt->load_template($templatefile);
	$returnJSON["html"] = array();
	foreach($addFields as $fName)
	{
		$returnJSON["html"][$fName] = $xt->fetchVar(GoodFieldName($fName)."_editcontrol");	
	}	
	$returnJSON["additionalJS"] = $pageObject->grabAllJsFiles();
	$returnJSON["additionalCSS"] = $pageObject->grabAllCSSFiles();
	echo (my_json_encode($returnJSON)); 
}
else
	$xt->display($templatefile);

function GetAddedDataLookupQuery($pageObject, $keys, $forLookup)
{
	global $conn, $strTableName, $strOriginalTableName;
	
	$LookupSQL = "";
	$linkfield = "";
	$dispfield = "";
	$noBlobReplace = false;
	$lookupFieldName = "";
	
	if($LookupSQL && $nLookupType != LT_QUERY)
		$LookupSQL.=" from ".AddTableWrappers($strOriginalTableName);
		
	$data = 0;
	$lookupIndexes = array("linkFieldIndex" => 0, "displayFieldIndex" => 0);
	if(count($keys))
	{
		$where = KeyWhere($keys);
		if($nLookupType == LT_QUERY){
			$LookupSQL = $lookupQueryObj->toSql(whereAdd($lookupQueryObj->m_where->toSql($lookupQueryObj), $where));
		}else 
			$LookupSQL.=" where ".$where;
		$lookupIndexes = GetLookupFieldsIndexes($lookupPSet, $lookupFieldName);
		LogInfo($LookupSQL);
		if($forLookup){
			$rs=db_query($LookupSQL,$conn);
			$data = $pageObject->cipherer->DecryptFetchedArray($rs);
		}else if($LookupSQL)
		{
			$rs = db_query($LookupSQL,$conn);
			$data = db_fetch_numarray($rs);
			$data[$lookupIndexes["linkFieldIndex"]] = $pageObject->cipherer->DecryptField($linkFieldName, $data[$lookupIndexes["linkFieldIndex"]]);
			if($nLookupType == LT_QUERY)
				$data[$lookupIndexes["displayFieldIndex"]] = $pageObject->cipherer->DecryptField($dispfield, $data[$lookupIndexes["displayFieldIndex"]]);		
		}
	}

	return array($data, array("linkField" => $linkFieldName, "displayField" => $dispfield
		, "linkFieldIndex" => $lookupIndexes["linkFieldIndex"], "displayFieldIndex" => $lookupIndexes["displayFieldIndex"]));
}	
	
?>
