<?
//error_reporting(E_ALL);

require_once('class.stdModule.php');

define('VWK_LINK_TYPE_PAG', 1);
define('VWK_LINK_TYPE_ORG', 2);

define('VWK_BINARY_TYPE_ATT', 1);
define('VWK_BINARY_TYPE_LINK', 2);

// Errors
define('VWK_ERROR_INACTIVE_ORG', 100);
define('VWK_ERROR_INACTIVE_CTR', 101);
define('VWK_ERROR_INVALID_PAGE', 102);

define('MAX_RESULT', 10);

class verwijskompas extends stdModule {

	function verwijskompas() {
		$this->stdModule('cvwk0100');

		$this->_settings->assignTemplateFunction		= '$this->_assignGlobals();';

        $this->_settings->templates->login				= "login.tpl";
        $this->_settings->templates->home				= "home.tpl";
        $this->_settings->templates->medewerker_beheer	= "medewerker_beheer.tpl";
        $this->_settings->templates->pagina_beheer		= "pagina_beheer.tpl";
        $this->_settings->templates->brievenbus_beheer	= "brievenbus_beheer.tpl";
        $this->_settings->templates->brievenbus_detail	= "brievenbus_detail.tpl";

        $this->_settings->templates->pagina_detail		= "pagina_detail.tpl";
        $this->_settings->templates->mijn_vwk			= "mijn_vwk.tpl";

        $this->_settings->templates->license_check		= "license_check.tpl";

		$this->_settings->templates->search				= "zoeken.tpl";
		$this->_settings->templates->search_locations	= "zoek_locaties.tpl";
		$this->_settings->templates->search_result		= "zoek_resultaat.tpl";

		$this->_settings->templates->search_kwd_popoup	= "search_kwd_popoup.tpl";
		$this->_settings->templates->search_loc_popoup	= "search_loc_popoup.tpl";
		$this->_settings->templates->search_loc_popoup_edit	= "search_loc_popoup_edit.tpl";


		$this->_init_ctrl();

		$this->_smrt->register_modifier('make_clickable', 'tpl_make_clickable');
	}

	function _init_ctrl() {
		if (!is_object ($GLOBALS['g_obj_ctrl'])) {
			include_once('htmlcontrols-1.0/class.htmlcontrols.php');
			$GLOBALS['g_obj_ctrl'] = new htmlControls ($this->_settings->general->project->languageCode, $this->_settings->general->paths->virtual->style.'controls.css');
			$GLOBALS['g_obj_ctrl']->_initialized = 1;
			$GLOBALS['g_obj_ctrl']->_init_status['main'] = 1;
		}


		$this->_ctrl =& $GLOBALS['g_obj_ctrl'];

	}

	/*
	 * Callback function used by stdModule.
	 */
	function _assignGlobals() {
		$usr_row = null;
		$this->_variables->template->global['usrinfo']		= null;
		$this->_variables->template->global['orginfo']		= null;

		if (isset($_SESSION['session_usr_id']) && is_numeric($_SESSION['session_usr_id'])) {

			if (!is_array($_SESSION['usrinfo']) || count($_SESSION['usrinfo']) < 1 || ($_SESSION['session_usr_id'] != $_SESSION['usrinfo']['USR_ID'])) {
				$_SESSION['usrinfo']	= $this->_get_user_info($_SESSION['session_usr_id']);
			}

			$this->_variables->template->global['usrinfo']		= $_SESSION['usrinfo'];

			if (isset($_SESSION['session_org_id']) && is_numeric($_SESSION['session_org_id'])) {

				if (!is_array($_SESSION['orginfo']) || count($_SESSION['orginfo']) < 1 || $_SESSION['session_org_id'] != $_SESSION['orginfo']['ORG_ID']) {
					$_SESSION['orginfo']	= $this->_get_org_info($_SESSION['session_org_id']);
				}

				$this->_variables->template->global['orginfo']		= $_SESSION['orginfo'];

				$this->_variables->template->global['ctrinfo']		= $this->_get_contract();

			}
		}
	}

	function _check_contract() {

		if (isset($_SESSION['session_usr_id']) && is_numeric($_SESSION['session_usr_id'])) {
			if (isset($_SESSION['session_usr_def_code']) && $_SESSION['session_usr_def_code'] == 'MAT') {
				if (isset($_SESSION['session_org_id']) && is_numeric($_SESSION['session_org_id'])) {
					if (isset($_SESSION['session_org_def_code']) && $_SESSION['session_org_def_code'] == 'MAT') {

						//--- current user is org-user, usr-def = maatschap, org-def = maatschap

						$contract = $this->_get_contract();
						if (!$contract['ctr_org_state']) {
							$this->triggerError(VWK_ERROR_INACTIVE_ORG);
							return false;
						}
						if (!$contract['ctr_contract_state']) {
							$this->triggerError(VWK_ERROR_INACTIVE_CTR);
							return false;
						}
					}
				}
			}
		}


		return true;
	}

	function _get_contract() {
		if (!is_numeric($_SESSION['session_org_id'])) return;

		if (!isset($this->_contract_cache)) {
			/* MAIN CONTRACT INFO */
				$sql = "SELECT
							ctr_org_id
						,	ctr_org_state
						,	ctr_enddate
						,	ctr_startdate
						,	ctr_brievenbus
						,	((ctr_enddate IS NULL) OR (ctr_enddate > CURDATE()) AND (ctr_startdate IS NULL OR ctr_startdate <= NOW())) as ctr_contract_state
						FROM vwk_contract WHERE ctr_org_id = ". $_SESSION['session_org_id'];
				$rs = $this->_db->query($sql);

				$main_ctr_info = $rs->Row();

			/* SET CONTRACT INFO */
				$main_ctr_info['sets'] = array();
				$main_ctr_info['defs'] = array();
				$valid_sets = array();

				$sql = "SELECT	cds_set_code
						,		cds_max_pages 
						,		set_name
						FROM	vwk_contract
						INNER JOIN vwk_ctr_set_connection ON cds_ctr_id = ctr_id 
						INNER JOIN vwk_definition_sets ON set_code = cds_set_code
						WHERE ctr_org_id = ". $_SESSION['session_org_id'];

				$rs = $this->_db->query($sql);
				while ($r = $rs->row()) {
					$main_ctr_info['sets'][$r['cds_set_code']]['label'] = $r['set_name'];
					$main_ctr_info['sets'][$r['cds_set_code']]['max_pages'] = $r['cds_max_pages'];
					$valid_sets[] = $r['cds_set_code'];
					$rs->moveNext();
				}
				$rs->Close();

			/* DEF CONTRACT INFO */
				$sql = "SELECT	cpd_def_code
						,		cpd_max_keywords
						,		def_set_code
						,		def_name
						FROM	vwk_contract
						INNER JOIN vwk_ctr_def_connection ON cpd_ctr_id = ctr_id 
						INNER JOIN vwk_pag_definitions ON def_code = cpd_def_code
						WHERE ctr_org_id = ". $_SESSION['session_org_id'] ."
						ORDER BY def_order";
				$rs = $this->_db->query($sql);
				while ($r = $rs->row()) {
					$main_ctr_info['sets'][$r['def_set_code']]['defs'][$r['cpd_def_code']]['label'] = $r['def_name'];
					$main_ctr_info['sets'][$r['def_set_code']]['defs'][$r['cpd_def_code']]['max_keywords'] = $r['cpd_max_keywords'];
					$main_ctr_info['defs'][$r['cpd_def_code']]['max_keywords'] = $r['cpd_max_keywords'];
					$rs->moveNext();
				}
				$rs->Close();

				$this->_contract_cache = $main_ctr_info;			
		}

		return $this->_contract_cache;


	}

	function _check_contract_pages($only_active = false) {
		$sql = "SELECT ctr_org_id, ctr_max_pages, count(pag_id) pages
				FROM vwk_contract
				LEFT JOIN vwk_pages ON pag_org_id = ctr_org_id ".($only_active?"AND pag_active = 1":"")."
				WHERE ctr_org_id = ".$_SESSION['session_org_id']."
				GROUP BY ctr_org_id,ctr_max_pages";

		$rs = $this->_db->query($sql);
		return ($rs->Row('pages') <= $rs->Row('ctr_max_pages'));
	}

	function _get_user_info($usr_id, $return_one_field=false) {
		global $g_obj_i3a;

		$g_obj_i3a->getUsers($usr_row, array(array('usr_id','='.$usr_id), 'tbl_i3a_users.*,get_user_greeting(usr_id,0) as usr_greeting,get_user_greeting(usr_id,1) as usr_salutation'), array('GATT_VWK_IS_MANAGER'));
		$usr_row = current($usr_row);

		if ($return_one_field) {
			return $usr_row[$return_one_field];
		} else {
			return $usr_row;
		}
	}
	function _get_org_users($org_id, $return_one_field=false, $gatt_vwk_is_manager=false) {
		global $g_obj_i3a;

		if ($gatt_vwk_is_manager == 'Y') {
			$atts = array(array('GATT_VWK_IS_MANAGER',"='Y'"));
		} elseif ($gatt_vwk_is_manager == 'N') {
			$atts = array(array('GATT_VWK_IS_MANAGER',"='N'"));
		} elseif ($gatt_vwk_is_manager == 'both') {
			$atts = array('GATT_VWK_IS_MANAGER');
		} else {
			$atts = false;
		}

		$g_obj_i3a->getUsers($usr_row, array(array('USR_ORG_ID','='.$org_id), 'tbl_i3a_users.*,get_user_greeting(usr_id,0) as usr_greeting,get_user_greeting(usr_id,1) as usr_salutation'), $atts);


//		if ($return_one_field) {
			$new_usr_row = array();
			foreach ((array)$usr_row as $usr) {
				$new_usr_row[$usr['USR_ID']] = $return_one_field?$usr[$return_one_field]:$usr;
			}

			return $new_usr_row;
//		} else {
//			return $usr_row;
//		}

	}
	function _get_org_info($org_id) {
		$this->_tcc->doCall('ORG_LIST', array($org_id), $org_row);
		return $org_row;
	}
	function _get_member_status($org_id, $usr_id) {
		if (!is_numeric($org_id) || $org_id < 1) {
//			$org_id = $this->_settings->general->project->mainOrganizationID;
			$org_id = $_SESSION['arr_cur_org']['ORG_ID'];

			if (!is_numeric($org_id) || $org_id < 1) {
				return false;
			}
		}
		$err = $this->_tcc->doCall('MEMBER_STATUS', array($org_id, $usr_id), $usr_status);
		return $usr_status;
	}

	function _get_page_info($pag_id) {
		if (!is_numeric($pag_id)) return;

		$sql = "SELECT 
					vwk_pages.*
				".($_SESSION['session_usr_id'] ? ",	myp_usr_id" : '')."
				,	ctr_brievenbus as org_has_brievenbus
				,	ctr_org_name as org_name
				FROM vwk_pages
				INNER JOIN vwk_contract ON ctr_org_id = pag_org_id
				".($_SESSION['session_usr_id'] ? "LEFT JOIN vwk_my_pages ON myp_pag_id = pag_id AND myp_usr_id = ".$_SESSION['session_usr_id'] : '')."
				WHERE pag_id = ".$pag_id;
		$rs = $this->_db->query($sql);
		$page = $rs->Row();

		$page['fields']		= $this->_get_page_fields($pag_id);
		$page['pag_rights']	= $this->_get_page_rights($pag_id);
		$page['page_kwds']		= $this->get_page_kwds($pag_id);

//		$connected_kwds = $this->_get_pag_kwd_connections($pag_id);
//		if (count($connected_kwds) > 0) {
//			$page['pag_spe_id'] = $this->_get_spe_id_by_kwd_id($connected_kwds[0]);
//			$page['keywords'] = $this->_get_keywords($page['pag_spe_id']);

//			$nr=1;
//			foreach ($connected_kwds as $kwd_id) {
//				$page['pag_kwd_id'][$nr++] = $kwd_id;
//			}
//		}

		$sql = "UPDATE vwk_pages SET pag_lastviewdate = NOW(), pag_views = pag_views+1 WHERE pag_id = ".$pag_id;
		$this->_db->execute($sql);

		return $page;

	}

	function _allowed_to_view_page($pag_id) {
		$sql = "SELECT pag_active, pag_admin_active, ctr_org_state, ctr_org_id
				FROM vwk_pages
				INNER JOIN vwk_contract ON ctr_org_id = pag_org_id
				WHERE pag_id = ".$pag_id;

		$rs = $this->_db->query($sql);


		if ($rs->Row('pag_active') && $rs->Row('pag_admin_active') && $rs->Row('ctr_org_state')) {
			return true;
		} else {
			if (isset($_SESSION['session_usr_def_code']) && $_SESSION['session_usr_def_code'] == 'MAT') {
				if (isset($_SESSION['session_org_id']) && is_numeric($_SESSION['session_org_id'])) {
					if (isset($_SESSION['session_org_def_code']) && $_SESSION['session_org_def_code'] == 'MAT') {

						//--- current user is an org-user
						if ($_SESSION['session_org_id'] == $rs->Row('ctr_org_id')) {
							if ($rs->Row('ctr_org_state')) {
								return true;
							}
						}
					}
				}
			}
		}

		return false;
	}

	function _allowed_to_edit_page($usr_id, $pag_id) {
		if (!is_numeric($usr_id)) return;
		if (!is_numeric($pag_id)) return;

		if ($this->_get_page_rights($pag_id, $usr_id)) {
			return true;
		}

		$user_info 	= $this->_get_user_info($usr_id);

		if ($user_info['GATT_VWK_IS_MANAGER'] == 'Y') {

			$rs = $this->_db->query("SELECT pag_org_id FROM vwk_pages WHERE pag_id = ".$pag_id);
			if ($user_info['USR_ORG_ID'] == $rs->Row('pag_org_id')) {

				return true;

			}
		}
		return false;

	}

/*	function _get_pag_kwd_connections($pag_id) {
		if (!is_numeric($pag_id)) return;
		$sql = "SELECT pkc_kwd_id FROM vwk_pag_kwd_connection WHERE pkc_pag_id = ".$pag_id;
		$rs = $this->_db->query($sql);

		$kwd_ids = array();
		while ($r = $rs->Row()) {
			$kwd_ids[] = $r['pkc_kwd_id'];
			$rs->moveNext();
		}
		$rs->Close();

		return $kwd_ids;
	}
*/
	function &_get_keyword_tree($pag_id=0) {

		$sql = "SELECT	kwd_id, kwd_parent_id, kwd_name ".($pag_id?(", pkc_pag_id"):'')."
				FROM vwk_keywords
				".($pag_id?("LEFT JOIN vwk_pag_kwd_connection ON pkc_kwd_id = kwd_id AND pkc_pag_id = ".$pag_id):'')."
				WHERE kwd_single_page = 0 and kwd_state = 1
				ORDER BY kwd_name";

		$rs = $this->_db->query($sql);

		$nodes = array();

		while ($r = $rs->Row()) {
//			if (!$r['kwd_is_spec']) {
//				$name = '<span style="color: #FF0000">'. $r['kwd_name'] .'</span>';
//			} else {
				$name = $r['kwd_name'];
//			}

			$nodes['c'.$r['kwd_id']]->label		= addslashes($name);
			$nodes['c'.$r['kwd_id']]->name		= 'kwd'.$r['kwd_id'];
			$nodes['c'.$r['kwd_id']]->parent	= (is_numeric($r['kwd_parent_id']) ? 'c'.$r['kwd_parent_id'] : 1);
			$nodes['c'.$r['kwd_id']]->checked	= is_numeric($r['pkc_pag_id'])?true:false;

			if (is_numeric($r['pkc_pag_id'])) $n_checked++;

			$rs->moveNext();
		}

		$rs->close();

		$nodes[1]->label = '<b>Trefwoorden</b>';
		$nodes[1]->name = 'root';
		$nodes[1]->parent = 0;


		$tree = new stdClass();
		$tree->indent = 15;
		$tree->checkable = true;
		$tree->autoselect = true;
		$tree->autoexpand = false;
		$tree->checkvalues[0] = 'N';
		$tree->checkvalues[1] = 'Y';

		$tree->nodes = $nodes;

		return $tree;
	}

/*	function _get_keyword_list_options() {
		$sql = "SELECT if (kwd_level = 0, kwd_id, kwd_parent_id) root_id, kwd_level as level, kwd_id as id, kwd_name as name
				FROM vwk_keywords
				WHERE kwd_level IN (0,1)
				ORDER BY root_id, kwd_level, kwd_name";
		$rs = $this->query($sql);

		$options = array();
		while ($r = $rs->Row()) {

			$options[] = $r;

			$rs->moveNext();
		}

		return $options;
	}
*/
/*	function _get_keywords($parent_id, $filter_on_spec=null, $return_connected_only=false) {
		if (!is_numeric($parent_id)) return;

		$sql = "SELECT kwd_id, kwd_name, count(pkc_pag_id) as kwd_count, count(pag_id) as pag_count
				FROM vwk_keywords 
				LEFT JOIN vwk_pag_kwd_connection ON pkc_kwd_id = kwd_id 
				LEFT JOIN vwk_pages ON pkc_pag_id = pag_id AND pag_active = 1
				WHERE kwd_parent_id = ".$parent_id." 
				AND kwd_single_page = 0
				".(isset($filter_on_spec) ? (' AND kwd_is_spec = '.$filter_on_spec) : '')."
				GROUP BY kwd_id, kwd_name
				ORDER BY LOWER(kwd_name)";

		$rs = $this->_db->query($sql);

		$kwds = array();
		while ($r = $rs->Row()) {
			if (!$return_connected_only || $r['pag_count']) {
				$kwds[$r['kwd_id']] = $r['kwd_name'];
			}
			$rs->moveNext();
		}
		$rs->Close();

		return $kwds;
	}
*/
	function _get_keywords_by_id($kwd_ids) {
		if (!is_array($kwd_ids) && is_numeric($kwd_ids)) {
			$sql = "SELECT * FROM vwk_keywords WHERE kwd_id = ".$kwd_ids;
		} else {
			$sql = "SELECT * FROM vwk_keywords WHERE kwd_id IN (".implode(',',$kwd_ids).")";
		}

		$rs = $this->_db->query($sql);

		if (!is_array($kwd_ids) && is_numeric($kwd_ids)) {
			return $rs->Row();
		} else {
		
			$return = array();
			while ($r = $rs->Row()) {
				$return[] = $r;

				$rs->moveNext();
			}

			return $return;		
		}
	}

/*	function _get_spe_id_by_kwd_id($kwd_id) {
		if (!is_numeric($kwd_id)) return;
		$rs = $this->_db->query("SELECT kwd_spe_id FROM vwk_keywords WHERE kwd_id = ".$kwd_id);
		return $rs->Row('kwd_spe_id');
	}
*/
/*
	function _get_specialismen() {
		$sql = "SELECT spe_id, spe_name FROM vwk_keyword_spec ORDER BY lower(spe_name)";
		$rs = $this->_db->query($sql);
		$specs = array();
		while ($r = $rs->Row()) {
			$specs[$r['spe_id']] = $r['spe_name'];
			$rs->moveNext();
		}
		$rs->Close();

		return $specs;
	}
*/
	function _get_location($loc_id, $return_extended=false){
		if (!is_numeric($loc_id)) return;
		$sql = "SELECT * FROM vwk_locations WHERE loc_id = ".$loc_id;
		$rs = $this->_db->query($sql);
		if ($return_extended) {
			return $rs->Row();
		} else {
			return $rs->Row('loc_name');
		}

	}

	function _get_locations($return_array = false, $force_order=false, $code_as_index = false) {
		$sql = "SELECT loc_id, loc_code, loc_name, loc_coords FROM vwk_locations ORDER BY ".($force_order?$force_order:"loc_order, loc_name");
		$rs = $this->_db->query($sql);
		$locs = array();
		while ($r = $rs->Row()) {
			$index = $code_as_index ? $r['loc_code'] : $r['loc_id'];

			if ($return_array) {
				$locs[$index] = array (	'code' => $r['loc_code'],
												'name' => $r['loc_name'],
												'coords' => $r['loc_coords']
										);
			} else {
				$locs[$index] = $r['loc_name'];
			}


			$rs->moveNext();
		}
		$rs->Close();

		return $locs;
	}

	function _get_page_rights($pag_id, $usr_id = null) {
		if (!is_numeric($pag_id)) return;

		$sql = "SELECT pri_usr_id FROM vwk_page_rights WHERE pri_pag_id = ".$pag_id;
		$rs = $this->_db->query($sql);
		$usrs = array();
		while ($r = $rs->Row()) {
			$usrs[] = $r['pri_usr_id'];

			$rs->moveNext();
		}
		$rs->Close();

		if (is_numeric($usr_id)) {
			return in_array($usr_id, $usrs);
		} else {
			return $usrs;
		}
	}

	function _get_page_def_code($pag_id) {
		if (!is_numeric($pag_id)) return;

		$sql = "SELECT pag_def_code FROM vwk_pages WHERE pag_id = ".$pag_id;
		$rs = $this->_db->query($sql);
		return $rs->Row('pag_def_code');
	}

	function _get_page_fields($pag_id=0, $hide_values=false) {
		if ($hide_values) {
			$sql = "SELECT fld_code, fld_type, fld_label, fld_required, fld_maxsize, fld_help
					FROM vwk_pages
					INNER JOIN vwk_pag_fields ON fld_def_code = pag_def_code AND fld_active = 1
					WHERE pag_id = ". $pag_id ."
					ORDER BY fld_order";

		} else {
			$sql = "SELECT fld_code, fld_type, fld_label, fld_required, fld_maxsize, val_value, fld_def_code, fld_help
					FROM vwk_pages
					INNER JOIN vwk_pag_fields ON fld_def_code = pag_def_code AND fld_active = 1
					LEFT JOIN vwk_pag_values ON fld_code = val_fld_code AND val_pag_id = ".$pag_id ."
					WHERE pag_id = ".$pag_id ."
					ORDER BY fld_order";
		}

		$rs = $this->_db->query($sql);
		$fields = array();
		while ($r = $rs->Row()) {

			if ($r['fld_type'] == 'bin') {
				$r['binary'] = $this->get_binary_meta(VWK_BINARY_TYPE_ATT, null, $pag_id, $r['fld_code'], $r['fld_def_code']);
			}

			$fields[] = $r;


			$rs->moveNext();
		}
		$rs->Close();

		return $fields;

	}

	function _set_page_state($pag_id, $state) {
		if (!is_numeric($pag_id)) return;

		$sql = "SELECT count( p2.pag_id ) active_pages, cds_max_pages
				FROM vwk_pages p1
				INNER JOIN vwk_pag_definitions d1 ON d1.def_code = p1.pag_def_code
				INNER JOIN vwk_contract ON ctr_org_id = ".$_SESSION['session_org_id']."
				INNER JOIN vwk_ctr_set_connection ON cds_ctr_id = ctr_id AND cds_set_code = d1.def_set_code
				LEFT JOIN vwk_pag_definitions d2 ON d2.def_set_code = d1.def_set_code
				LEFT JOIN vwk_pages p2 ON p2.pag_def_code = d2.def_code AND p2.pag_active =1 AND p2.pag_org_id = ".$_SESSION['session_org_id']."
				WHERE p1.pag_id = ".$pag_id."
				GROUP BY cds_max_pages";

		$rs = $this->_db->query($sql);


		if (!$state || $rs->row('active_pages')+1 <= $rs->row('cds_max_pages')) {

			$sql = "UPDATE vwk_pages SET pag_active = ".($state?'1':'0')." ".($state ? ", pag_up2date_state = 'OK', pag_changedate = NOW()" : '')."
					WHERE	pag_org_id = ".$_SESSION['session_org_id']."
					AND		pag_admin_active = 1
					AND		pag_id = ". $pag_id;
			$this->_db->execute($sql);
			
			if ($state) {
				$this->_db->execute("UPDATE vwk_pages SET pag_active_since = NOW() WHERE pag_id = ".$pag_id." AND pag_active_since IS NULL ");
			}

			return true;

		} else {
			
			return false;
		}
	}

	function _delete_page($pag_id) {
		if (!is_numeric($pag_id)) return;

		$sql = "DELETE FROM vwk_pages WHERE pag_id = ".$pag_id." AND pag_org_id = ".$_SESSION['session_org_id'];
		$this->_db->execute($sql);

	}

	function _save_page($page_data) {
		/*	Steps for saving a page:
				1. save main data & location
				2. save page fields
				3. save keywords
				4. save rights
		*/

		if (isset($page_data['pag_id']) && is_numeric($page_data['pag_id'])) {
			//--- update page

			$pag_loc_id = is_numeric($page_data['pag_loc_id']) ? $page_data['pag_loc_id'] :'NULL';

			$sql = "UPDATE vwk_pages SET
						pag_name			= '".mysql_escape_string($page_data['pag_name'])."'
					,	pag_loc_id			= ".$pag_loc_id."
					,	pag_editted			= 1
					,	pag_admin_checked	= 0
					,	pag_changedate		= NOW()
					,	pag_usr_change		= ".$_SESSION['session_usr_id']."
					,	pag_up2date_state	= 'OK'
					WHERE pag_id = ".$page_data['pag_id'];

			$this->_db->execute($sql);
			$pag_id = $page_data['pag_id'];


			$valid_page_fields = $this->_get_page_fields($pag_id);

			foreach ($valid_page_fields as $fld) {
	
				if ($fld['fld_type'] == 'bin') {
					
					//--- delete
					if (isset($_REQUEST['chk_del_PAG_'.$fld['fld_code']]) && $_REQUEST['chk_del_PAG_'.$fld['fld_code']] == 'on') {
						$this->delete_binary(VWK_BINARY_TYPE_ATT, null, $pag_id, $fld['fld_code'], $page_data['pag_def_code']);
					}

					if (is_uploaded_file($_FILES['PAG_'.$fld['fld_code']]['tmp_name'])) {

						if (isset($fld['fld_maxsize']) && $fld['fld_maxsize'] > 0 && $_FILES['PAG_'.$fld['fld_code']]['size'] > $fld['fld_maxsize']) {
							$this->error_message = "Bestand '".$fld['fld_label']."' is te groter dan toegestaan. Maximaal toegestane grootte: ".($fld['fld_maxsize']/1024)."kB";
						} else {
							$this->save_binary(VWK_BINARY_TYPE_ATT, $_FILES['PAG_'.$fld['fld_code']], null, $pag_id, $fld['fld_code'], $page_data['pag_def_code']);
						}
					}

				} else {

					if (!isset($page_data['PAG_'.$fld['fld_code']]) || ($page_data['PAG_'.$fld['fld_code']] != $fld['val_value'])) {

						//--- update / create value
						$value = $page_data['PAG_'.$fld['fld_code']];
						if (is_numeric($fld['fld_maxsize'])) {
							$value = substr($value, 0, $fld['fld_maxsize']);
						}

						$sql = "REPLACE INTO vwk_pag_values SET
									val_pag_id		= ".$pag_id."
								,	val_fld_code	= '".$fld['fld_code']."'
								,	val_fld_def_code= '".$page_data['pag_def_code']."'
								,	val_value		= '".mysql_escape_string($value)."'
								,	val_createdate	= NOW()";
						$this->_db->execute($sql);
					}
				}
			}


			if (isset($page_data['kwd_tree']) && is_array($page_data['kwd_tree'])) {

				//-- delete connections
				$this->_db->execute("DELETE vwk_pag_kwd_connection.* 
									FROM vwk_pag_kwd_connection 
									INNER JOIN vwk_keywords ON kwd_id = pkc_kwd_id AND kwd_single_page = 0 
									WHERE pkc_pag_id = ".$pag_id);

/*				$kwd_ids = array();
				foreach ($page_data['kwd_tree'] as $node_id => $node_value) {
					if ($node_id != '1' && $node_id{0} == 'c') {
						if ($node_value == 'Y') {
							$kwd_ids[] = substr($node_id,1);
						}
					}
				}
*/


				if (isset($page_data['kwd_tree_selected_ids']) && strlen($page_data['kwd_tree_selected_ids']) > 0) {

					$org_contract = $this->_get_contract();

					$sql = "INSERT INTO vwk_pag_kwd_connection (pkc_pag_id, pkc_kwd_id) 
							SELECT $pag_id, kwd_id FROM vwk_keywords WHERE kwd_id in (".str_replace(':',',',$page_data['kwd_tree_selected_ids']).")
							LIMIT ". $org_contract['defs'][$page_data['pag_def_code']]['max_keywords'];
					$this->_db->execute($sql);

				}

				//-- 
				$this->_add_parent_kwd_connection($pag_id, null, true);
			}

		} else {
			//--- create new page
			$sql = "INSERT INTO vwk_pages SET
						pag_name		= '".mysql_escape_string($page_data['pag_name'])."'
					,	pag_def_code	= '".mysql_escape_string($page_data['pag_def_code'])."'
					,	pag_org_id		= ".$_SESSION['session_org_id']."
					,	pag_active		= 0
					,	pag_editted		= 0
					,	pag_createdate	= NOW()
					,	pag_changedate	= NOW()
					,	pag_usr_create	= ".$_SESSION['session_usr_id'];

			$this->_db->execute($sql);
			$pag_id = mysql_insert_id($this->_db->Connection);
		}


//		if ($this->_get_user_info($_SESSION['session_usr_id'], 'GATT_VWK_IS_MANAGER') == 'Y') {
			//-- delete rights
			$this->_db->execute("DELETE FROM vwk_page_rights WHERE pri_pag_id = ".$pag_id);


			foreach ((array)$page_data['pag_rights'] as $usr_id => $state) {
				if (is_numeric($usr_id) && $state == 'on') {
					$this->_db->execute("INSERT INTO vwk_page_rights (pri_usr_id, pri_pag_id) VALUES (".$usr_id.", ".$pag_id .")");
				}
			}
//		}
		return $pag_id;
	}

	function _add_parent_kwd_connection($pag_id, $kwd_ids, $first_time=false) {
		if (!is_numeric($pag_id)) return false;

		if (count($kwd_ids) || $first_time) {
			
			//--- insert kwd-connections
			if (count($kwd_ids)) {
				foreach ($kwd_ids as $kwd_id) {
					if (is_numeric($kwd_id)) $this->_db->Execute("REPLACE INTO vwk_pag_kwd_connection (pkc_pag_id, pkc_kwd_id) VALUES (".$pag_id.",".$kwd_id.")");
				}
			}
			
			if ($first_time) {
				//--- get kwd's from page
				$sql = "SELECT DISTINCT kwd_parent_id FROM vwk_pag_kwd_connection 
						INNER JOIN vwk_keywords ON kwd_id = pkc_kwd_id
						WHERE kwd_parent_id IS NOT NULL AND pkc_pag_id =". $pag_id;
			} else {
				//--- get parent-kwd's from given kwd-ids
				$sql = "SELECT DISTINCT kwd_parent_id FROM vwk_keywords 
						WHERE kwd_parent_id IS NOT NULL AND kwd_id IN (".implode(',',$kwd_ids).")";
			}

			$rs = $this->_db->query($sql);

			$new_kwd_ids = array();
			while ($r = $rs->row()) {
				$new_kwd_ids[] = $r['kwd_parent_id'];
				$rs->moveNext();
			}
			$rs->Close();

			if ($new_kwd_ids) {
				$this->_add_parent_kwd_connection($pag_id, $new_kwd_ids);
			}
		}
	}


	function delete_binary($bin_type, $lnk_id=null, $pag_id=null, $fld_code=null, $fld_def_code=null) {

		switch ($bin_type) {
			
			case VWK_BINARY_TYPE_ATT:
				if (is_numeric($pag_id)) {
					$sql = "DELETE FROM vwk_binaries WHERE 
								bin_pag_id			= ".$pag_id."
							AND	bin_fld_code		= '". $fld_code . "'
							AND	bin_fld_def_code	= '". $fld_def_code . "'";
					$this->_db->execute($sql);
				}
				break;

			case VWK_BINARY_TYPE_LINK:
				if (is_numeric($lnk_id)) {
					$sql = "DELETE FROM vwk_binaries WHERE 
								bin_lnk_id			= ".$lnk_id;
					$this->_db->execute($sql);
				}
				break;

		}				
	
	}

	function save_binary($bin_type, $binary, $lnk_id=null, $pag_id=null, $fld_code=null, $fld_def_code=null) {
	
		switch ($bin_type) {
			
			case VWK_BINARY_TYPE_ATT:
				
				$this->delete_binary($bin_type, null, $pag_id, $fld_code, $fld_def_code);

				$bin_data = array();
				$bin_data['bin_lnk_id']			= 'NULL';
				$bin_data['bin_pag_id']			= $pag_id;
				$bin_data['bin_fld_code']		= "'". $fld_code . "'";
				$bin_data['bin_fld_def_code']	= "'". $fld_def_code . "'";
				$bin_data['bin_data']			= "'". addslashes(file_get_contents($binary['tmp_name'])) . "'";
				$bin_data['bin_filename']		= "'". mysql_escape_string($binary['name']) . "'";
				$bin_data['bin_mimetype']		= "'". mysql_escape_string($binary['type']) . "'";
				$bin_data['bin_size']			= $binary['size'];

				break;

			case VWK_BINARY_TYPE_LINK:

				$this->delete_binary($bin_type, $lnk_id);

				$bin_data = array();
				$bin_data['bin_lnk_id']			= $lnk_id;
				$bin_data['bin_pag_id']			= 'NULL';
				$bin_data['bin_fld_code']		= 'NULL';
				$bin_data['bin_fld_def_code']	= 'NULL';
				$bin_data['bin_data']			= "'". addslashes(file_get_contents($binary['tmp_name'])) . "'";
				$bin_data['bin_filename']		= "'". mysql_escape_string($binary['name']) . "'";
				$bin_data['bin_mimetype']		= "'". mysql_escape_string($binary['type']) . "'";
				$bin_data['bin_size']			= $binary['size'];

				break;

		}

		if (is_array($bin_data) && count($bin_data)) {
			$sql = "INSERT INTO vwk_binaries (".implode(',',array_keys($bin_data)).") VALUES (".implode(',',array_values($bin_data)).")";
			$this->_db->execute($sql);
		}

	}
	function get_binary_meta($bin_type, $lnk_id=null, $pag_id=null, $fld_code=null, $fld_def_code=null) {
		switch ($bin_type) {
			
			case VWK_BINARY_TYPE_ATT:
				$sql = "SELECT bin_id, bin_filename, bin_mimetype, bin_size FROM vwk_binaries WHERE 
							bin_pag_id			= ".$pag_id."
						AND	bin_fld_code		= '". $fld_code . "'
						AND	bin_fld_def_code	= '". $fld_def_code . "'";
				$rs = $this->_db->query($sql);
				return $rs->Row();
				break;

			case VWK_BINARY_TYPE_LINK:
				$sql = "SELECT bin_id, bin_filename, bin_mimetype, bin_size FROM vwk_binaries WHERE 
							bin_lnk_id			= ".$lnk_id;
				$rs = $this->_db->query($sql);
				return $rs->Row();
				break;		
		}
		
	}

	function get_binary($bin_type, $id) {


		if (!is_numeric($id)) return;

		if ($bin_type == VWK_BINARY_TYPE_ATT) {
			$sql_where = "bin_id = ". $id;
		} elseif ($bin_type == VWK_BINARY_TYPE_LINK) {
			$sql_where = "bin_lnk_id = ". $id;
		}

		$sql = "SELECT bin_filename, bin_mimetype, bin_size, bin_data
				FROM vwk_binaries
				WHERE ". $sql_where;

		$rs = $this->_db->query($sql);

		if ($rs->RowCount && $rs->Row('bin_data') && $rs->Row('bin_mimetype')) {

			Header("Content-type: ".str_replace('-','/',$rs->Row('bin_mimetype')).", Expires: ".gmdate("D, d M Y H:i:s", time() + 3600));
			header("Content-Length: ".$rs->Row('bin_size'));
			header("Content-Disposition: attachment; filename=".$rs->Row('bin_filename'));
			Header("Cache-Control: max-age=3600, must-revalidate, pre-check=0, post-check=0");
			echo $rs->Row('bin_data');
			die();

		}
	
	}

	function _make_copy($pag_id) {
		if (!is_numeric($pag_id)) return;

		$source_page = $this->_get_page_info($pag_id);
		unset($source_page['pag_id']);

		//--- setting page rights
		foreach ($source_page['pag_rights'] as $index => $usr_id) {
			$source_page['pag_rights'][$usr_id] = 'on';
			unset($source_page['pag_rights'][$index]);
		}

		//--- rename title
		$source_page['pag_name'] .= ' (kopie)';
		
		//--- saving page (first time)
		$new_id = $this->_save_page($source_page);
		if (is_numeric($new_id)) {
			//--- de-activate
			$this->_set_page_state($new_id, 0);

			//--- settinge page fields
			foreach ($source_page['fields'] as $fld) {
				$source_page['PAG_'.$fld['fld_code']] = $fld['val_value'];
			}
			unset($source_page['fields']);

			$source_page['pag_id'] = $new_id;

			//--- saving page (second time)
			$this->_save_page($source_page);

			//--- copying keyword connections
			$sql = "INSERT INTO vwk_pag_kwd_connection (pkc_pag_id, pkc_kwd_id)
					SELECT ".$new_id.", pkc_kwd_id FROM vwk_pag_kwd_connection WHERE pkc_pag_id = ".$pag_id;
			$this->_db->execute($sql);
			
			return $new_id;

		}

	}

	function _get_links($lnk_type, $id, $active_pages_only=false, $single_link=false) {
		if (!is_numeric($id)) return;


		if ($lnk_type == VWK_LINK_TYPE_PAG) {
		
			$sql_where = "lnk_from_pag_id = ".$id;

		} elseif ($lnk_type == VWK_LINK_TYPE_ORG) {

			$sql_where = "lnk_org_id = ".$id;
		
		} else {
			return; # impossible
		}

		$sql = "SELECT 
					lnk_id
				,	lnk_from_pag_id
				,	lnk_to_pag_id
				,	lnk_url
				,	lnk_title
				,	lnk_desc
				,	lnk_file_mime
				,	lnk_file_size
				,	lnk_file_name
				,	vwk_pages.pag_name
				,	vwk_pages.pag_def_code
				FROM vwk_pag_links 
				LEFT JOIN vwk_pages ON pag_id = lnk_to_pag_id 
				WHERE 
				".$sql_where."
				".($single_link ? (' AND lnk_id = '.$single_link) : '')."
				".($active_pages_only ? ' AND (lnk_to_pag_id IS NULL OR pag_active=1)' :'');

		$links = array();
		$rs = $this->_db->query($sql);
		while ($r = $rs->Row()) {
			$r['binary'] = $this->get_binary_meta(VWK_BINARY_TYPE_LINK, $r['lnk_id']);		

			$links[] = $r;
			$rs->moveNext();
		}
		$rs->Close();

		return $single_link ? $links[0] : $links;
	}

	function _delete_link($lnk_type, $id, $lnk_id) {

		if ($lnk_type == VWK_LINK_TYPE_PAG) {

			$sql = "DELETE vwk_pag_links.*
					FROM vwk_pag_links
					INNER JOIN vwk_pages ON pag_id = lnk_from_pag_id
					WHERE lnk_id = ".$lnk_id."
					AND	lnk_from_pag_id = ".$id."
					AND pag_org_id = ".$_SESSION['session_org_id'];

		} elseif ($lnk_type == VWK_LINK_TYPE_ORG) {

			$sql = "DELETE vwk_pag_links
					FROM vwk_pag_links
					WHERE lnk_id = ".$lnk_id."
					AND	lnk_org_id = ".$_SESSION['session_org_id'];
		}


		$this->_db->execute($sql);

		$this->delete_binary(VWK_BINARY_TYPE_LINK, $lnk_id);

	}

	function _save_link($lnk_type, $id, $type, $title, $desc, $url=null, $lnk_id=null) {
		if (!is_numeric($id)) return;

		$lnk_data = array();
		if ($lnk_type == VWK_LINK_TYPE_PAG) {
			$lnk_data['lnk_from_pag_id']	= $id;
			$lnk_data['lnk_org_id']			= 'NULL';
		} elseif ($lnk_type == VWK_LINK_TYPE_ORG) {
			$lnk_data['lnk_from_pag_id']	= 'NULL';
			$lnk_data['lnk_org_id']			= $id;
		}

		if ($type == 'URL') {
			if (is_numeric($lnk_id)) {
			
				$sql = "UPDATE vwk_pag_links SET
							lnk_url				= '".mysql_escape_string($url)."'
						,	lnk_title			= '".mysql_escape_string($title)."'
						,	lnk_desc			= '".mysql_escape_string($desc)."'
						WHERE lnk_id = ".$lnk_id;
				$this->_db->execute($sql);
			} else {
				
				if (strpos($url,'http://') === false) $url = 'http://'.$url;

				$sql = "INSERT INTO vwk_pag_links SET
							lnk_from_pag_id		= ".$lnk_data['lnk_from_pag_id']."
						,	lnk_org_id			= ".$lnk_data['lnk_org_id']."
						,	lnk_url				= '".mysql_escape_string($url)."'
						,	lnk_title			= '".mysql_escape_string($title)."'
						,	lnk_desc			= '".mysql_escape_string($desc)."'";
				$this->_db->execute($sql);
			}
		} elseif ($type == 'FILE') {
			if (is_uploaded_file($_FILES['new_link_file']['tmp_name'])) {

				if (!is_numeric($lnk_id)) {

					$sql = "INSERT INTO vwk_pag_links SET
								lnk_from_pag_id		= ".$lnk_data['lnk_from_pag_id']."
							,	lnk_org_id			= ".$lnk_data['lnk_org_id']."
							,	lnk_title			= '".mysql_escape_string($title)."'
							,	lnk_desc			= '".mysql_escape_string($desc)."'";
					$this->_db->execute($sql);
					$new_lnk_id = $this->_db->lastInsertID();
					$this->save_binary(VWK_BINARY_TYPE_LINK, $_FILES['new_link_file'], $new_lnk_id);

				} else {
					$this->save_binary(VWK_BINARY_TYPE_LINK, $_FILES['new_link_file'], $lnk_id);
				}
			} elseif (is_numeric($lnk_id)) {
			
				$sql = "UPDATE vwk_pag_links SET
							lnk_title			= '".mysql_escape_string($title)."'
						,	lnk_desc			= '".mysql_escape_string($desc)."'
						WHERE lnk_id = ".$lnk_id;
				$this->_db->execute($sql);

				if (isset($_REQUEST['chk_del_new_link_file']) && $_REQUEST['chk_del_new_link_file'] == 'on') {
					$this->delete_binary(VWK_BINARY_TYPE_LINK, $lnk_id);
				}
			}
		}
	}

	function show_bin($lnk_id) {
		if (!is_numeric($lnk_id)) return;

		$sql = "SELECT lnk_file_data, lnk_file_mime, lnk_file_size, lnk_file_name
				FROM vwk_pag_links 
				WHERE lnk_id = ".$lnk_id;

		$rs = $this->_db->query($sql);

		if ($rs->RowCount && $rs->Row('lnk_file_data') && $rs->Row('lnk_file_mime')) {

			header("Content-type: ".str_replace('-','/',$rs->Row('lnk_file_mime')).", Expires: ".gmdate("D, d M Y H:i:s", time() + 3600));
			header("Content-Length: ".$rs->Row('lnk_file_size'));
			header("Content-Disposition: attachment; filename=".$rs->Row('lnk_file_name'));
			header("Cache-Control: max-age=3600, must-revalidate, pre-check=0, post-check=0");
			echo $rs->Row('lnk_file_data');
			die();

		}
	
	}

	function _save_page_links($pag_id, $pag_links) {
		$this->_db->execute("DELETE FROM vwk_pag_links WHERE lnk_from_pag_id = ".$pag_id ." AND lnk_to_pag_id IS NOT NULL");
		$new_pag_link_ids = array();
		foreach ($pag_links as $to_pag_id => $state) {
			if ($state == 'on') {
				$new_pag_link_ids[] = $to_pag_id;
			}
		}
		
		if (count($new_pag_link_ids)) {
			$sql = "INSERT INTO vwk_pag_links (lnk_from_pag_id, lnk_to_pag_id)
					SELECT ".$pag_id.", pag_id FROM vwk_pages WHERE pag_id IN (".implode(',',$new_pag_link_ids).")";
			$this->_db->execute($sql);
	
		}
	
	}

	function get_page_kwds($pag_id) {
		if (!is_numeric($pag_id)) return;

		$kwds = array();

		$sql = "SELECT kwd_id, kwd_name FROM vwk_keywords 
				INNER JOIN vwk_pag_kwd_connection ON pkc_pag_id = ".$pag_id." AND pkc_kwd_id = kwd_id
				WHERE kwd_single_page = 1 
				ORDER BY kwd_name";
		$rs = $this->_db->query($sql);
		while ($r = $rs->row()) {
			$kwds[$r['kwd_id']] = $r['kwd_name'];
			
			$rs->moveNext();
		}
		$rs->Close();

		return $kwds;
	}

	function set_page_kwd($pag_id, $action, $kwd_id, $kwd_value='') {
		if (!is_numeric($pag_id)) return;

		switch ($action) {
		
			case 'delete':

				if (is_numeric($kwd_id)) {
					$sql = "DELETE vwk_keywords.*
							FROM vwk_keywords
							INNER JOIN vwk_pag_kwd_connection ON pkc_pag_id = ".$pag_id." AND pkc_kwd_id = kwd_id
							WHERE kwd_id = ".$kwd_id;
					$this->_db->execute($sql);
				} else {
					$sql = "DELETE vwk_keywords.*
							FROM vwk_keywords
							INNER JOIN vwk_pag_kwd_connection ON pkc_pag_id = ".$pag_id." AND pkc_kwd_id = kwd_id
							WHERE kwd_name = '".mysql_escape_string($kwd_value) ."'";

					$this->_db->execute($sql);
				}

				break;

			case 'edit':

				if (is_numeric($kwd_id)) {
					
					$sql = "UPDATE vwk_keywords 
							INNER JOIN vwk_pag_kwd_connection ON pkc_pag_id = ".$pag_id." AND pkc_kwd_id = kwd_id
							SET kwd_name = '".mysql_escape_string($kwd_value) ."'
							WHERE kwd_id = ".$kwd_id;

					$this->_db->execute($sql);
				} else {

					$sql = "UPDATE vwk_keywords 
							INNER JOIN vwk_pag_kwd_connection ON pkc_pag_id = ".$pag_id." AND pkc_kwd_id = kwd_id
							SET kwd_name = '".mysql_escape_string($kwd_value) ."'
							WHERE kwd_name = '".mysql_escape_string($kwd_id) ."'";

					$this->_db->execute($sql);
				}

				break;
			
			case 'new':

				$sql = "INSERT INTO vwk_keywords SET 
							kwd_parent_id	= NULL
						,	kwd_name		= '".mysql_escape_string($kwd_value) ."'
						,	kwd_level		= 1
						,	kwd_order		= NULL
						,	kwd_end_node	= 1
						,	kwd_single_page	= 1
						,	kwd_bread_crumb	= '".mysql_escape_string($kwd_value) ."'
						,	kwd_createdate	= NOW()
						,	kwd_changedate	= NOW()";
				$this->_db->execute($sql);

				$new_kwd_id = mysql_insert_id($this->_db->Connection);

				$this->_db->execute("INSERT INTO vwk_pag_kwd_connection VALUES (".$pag_id.", ".$new_kwd_id.")");

				break;

		}
	}

/***************************************************************************************************************************/
/***************************************************************************************************************************/

	function brievenbus_beheer() {
		if (!$this->_check_contract()) {
			return;
		}

		$ctr_info = $this->_get_contract();
		if (!$ctr_info['ctr_brievenbus']) {
			return;			
		}

		if (isset($_REQUEST['new_link_title']) && strlen(trim($_REQUEST)) > 0 && isset($_REQUEST['new_link_type'])) {
		
			$this->_save_link(VWK_LINK_TYPE_ORG, $_SESSION['session_org_id'], $_REQUEST['new_link_type'], $_REQUEST['new_link_title'], $_REQUEST['new_link_desc'], $_REQUEST['new_link_url'], $_REQUEST['new_link_lnk_id']);
		}

		if (isset($_REQUEST['link_delete']) && is_numeric($_REQUEST['link_delete'])) {

			$this->_delete_link(VWK_LINK_TYPE_ORG, $_SESSION['session_org_id'], $_REQUEST['link_delete']);

		} elseif (isset($_REQUEST['link_edit']) && is_numeric($_REQUEST['link_edit'])) {

			$this->_smrt->assign('link_edit', $this->_get_links(VWK_LINK_TYPE_ORG, $_SESSION['session_org_id'], false, $_REQUEST['link_edit']));
		}


		$this->_smrt->assign('links', $this->_get_links(VWK_LINK_TYPE_ORG, $_SESSION['session_org_id']));


	//--------------------------------------------
	//--- SHOW TEMPLATE

		// Assign globals to template
		$this->assignTemplateGlobals();

		// Partse template
		$this->_smrt->display($this->_settings->templates->brievenbus_beheer);
		
	}

	function brievenbus_show($org_id) {
		if (!is_numeric($org_id)) return;

		$this->_smrt->assign('links', $this->_get_links(VWK_LINK_TYPE_ORG, $org_id));
		$this->_smrt->assign('organization', $this->_get_org_info($org_id));



		// Assign globals to template
		$this->assignTemplateGlobals();

		// Partse template
		$this->_smrt->display($this->_settings->templates->brievenbus_detail);
	}

	function pagina_beheer() {
		if (!$this->_check_contract()) {
			return;
		}


		$show_new_user_form = false;
		if (isset($_REQUEST['new'])) {
			$show_new_page_form = true;
		}

		$usrinfo = $this->_get_user_info($_SESSION['session_usr_id']);

	//--------------------------------------------
	//--- EDIT PAGE LINKS
		if (isset($_REQUEST['edit-links']) && is_numeric($_REQUEST['edit-links'])) {
			
			if (isset($_REQUEST['link_delete']) && is_numeric($_REQUEST['link_delete'])) {

				$this->_delete_link(VWK_LINK_TYPE_PAG, $_REQUEST['edit-links'], $_REQUEST['link_delete']);

			} elseif (isset($_REQUEST['link_edit']) && is_numeric($_REQUEST['link_edit'])) {

				$this->_smrt->assign('link_edit', $this->_get_links(VWK_LINK_TYPE_PAG, $_REQUEST['edit-links'], false, $_REQUEST['link_edit']));
			}



			if (isset($_REQUEST['pag_links'])) {
				
				$this->_save_page_links($_REQUEST['edit-links'], $_REQUEST['pag_links']);
			}

			if (isset($_REQUEST['new_link_title']) && strlen($_REQUEST['new_link_title']) > 0) {
				

				$this->_save_link(VWK_LINK_TYPE_PAG, $_REQUEST['edit-links'], $_REQUEST['new_link_type'], $_REQUEST['new_link_title'], $_REQUEST['new_link_desc'], $_REQUEST['new_link_url'], $_REQUEST['new_link_lnk_id']);


			}
			$rs_tmp = $this->_db->query("SELECT pag_name FROM vwk_pages WHERE pag_id = ".$_REQUEST['edit-links']);
			$link_pag_name = $rs_tmp->Row('pag_name');
			$rs_tmp->Close();

			$link_info = $this->_get_links(VWK_LINK_TYPE_PAG, $_REQUEST['edit-links']);
			$linked_pag_ids = array_demulti($link_info, 'lnk_to_pag_id');
			$this->_smrt->assign('mode', 'edit-links');
			$this->_smrt->assign('link_pag_id', $_REQUEST['edit-links']);
			$this->_smrt->assign('link_pag_name', $link_pag_name);
			$this->_smrt->assign('link_info', $link_info);
			$this->_smrt->assign('linked_pag_ids', $linked_pag_ids);
		}


	//--------------------------------------------
	//--- DELETE PAGE
		if (isset($_REQUEST['delete']) && is_numeric($_REQUEST['delete'])) {
			//--- delete a page
			/* active user must be a manager */

			if ($usrinfo['GATT_VWK_IS_MANAGER'] == 'Y') {
				//--- user is manager
				$this->_delete_page($_REQUEST['delete']);
			}
		}

	//--------------------------------------------
	//--- (DE)ACTIVATE PAGE

		if (isset($_REQUEST['activate']) && is_numeric($_REQUEST['activate']) && $usrinfo['GATT_VWK_IS_MANAGER'] == 'Y') {
			$return = $this->_set_page_state($_REQUEST['activate'], 1);
			if ($return === false) {
				
				$this->_smrt->assign('error_message', 'Pagina is niet geactiveerd, maximum bereikt');
				
			}

		}
		if (isset($_REQUEST['deactivate']) && is_numeric($_REQUEST['deactivate']) && $usrinfo['GATT_VWK_IS_MANAGER'] == 'Y') {
			$this->_set_page_state($_REQUEST['deactivate'], 0);
		}


	//--------------------------------------------
	//--- COPY PAGE

		if (isset($_REQUEST['copy']) && is_numeric($_REQUEST['copy'])) {
			$new_id = $this->_make_copy($_REQUEST['copy']);
			Header('Location: /vwk/pagina-beheer/edit='.$new_id);exit();

		}

	//--------------------------------------------
	//--- SAVE & CREATE PAGE

		if (isset($_REQUEST['save']) && $_REQUEST['save'] == '1') {
			$save_data = $_REQUEST;
			$save_data['pag_id'] = $_REQUEST['pag_id'];

			$new_pag_id = $this->_save_page($save_data);



			if (is_numeric($new_pag_id)) {
				$err = '';
				if ($this->error_message) {
					$err = '&error_message='.urlencode($this->error_message);
				}
				Header('Location: /vwk/pagina-beheer/edit='.$new_pag_id.$err);exit();
			} else {

				$show_new_page_form = true;

			}

		}

	//--------------------------------------------
	//--- EDIT & NEW PAGE
		if ((isset($_REQUEST['edit']) && is_numeric($_REQUEST['edit'])) || $show_new_page_form) {

			$this->setTemplateVariable('checkpage',	$_REQUEST['cp']);
			$this->_smrt->assign('org_users',	$this->_get_org_users($_SESSION['session_org_id'], 'USR_GREETING', 'N'));

			if ($_SERVER['REQUEST_METHOD'] == 'POST') {
				//--- editting the page
				$page_info = $_REQUEST;
				$page_info['fields'] = $this->_get_page_fields($_REQUEST['edit'], true);

			} else {
				$page_info = array();
			}

			
			$page_kwd_tree = $this->_ctrl->olv('De Tree', 'kwd_tree', '', 255, $this->_get_keyword_tree($_REQUEST['edit']));

			if (isset($_REQUEST['edit']) && is_numeric($_REQUEST['edit'])) {


				//-- get pageinfo from db when: 1. page isn't submitted before when editting this page
				//--							2. when user comes from a login redirect

				if ($_SERVER['REQUEST_METHOD'] != 'POST' || isset($_REQUEST['redirect'])) {
					$page_info = $this->_get_page_info($_REQUEST['edit']);
				}

				$page_info['kwd_tree'] = $page_kwd_tree;
				$page_info['selected_location'] = $this->_get_location($page_info['pag_loc_id']);


				if (!$this->_allowed_to_edit_page($_SESSION['session_usr_id'], $_REQUEST['edit'])) {
					//--- USER IS NOT ALLOWED TO EDIT
					$this->triggerError(VWK_ERROR_INVALID_PAGE);
					return;
				}

				if (is_array($page_info)) {

					$this->_smrt->assign('edit_page', $page_info);

				} else {

					//-- invalid page / page not found
					$this->triggerError(VWK_ERROR_INVALID_PAGE);
					return;

				}
			} elseif ($show_new_page_form) {
				//--- new page
				$page_info['kwd_tree'] = $page_kwd_tree;
				$this->_smrt->assign('edit_page', $page_info);
			}
		}


	//--------------------------------------------
	//--- PAGES OVERVIEW

		if ($usrinfo['GATT_VWK_IS_MANAGER'] == 'Y') {
			$sql = "SELECT pag_id, pag_def_code, pag_name, pag_active, pag_admin_active, pag_editted, count(pkc_kwd_id) as pag_keywords, DATE_FORMAT(pag_changedate, '%d-%m-%Y %H:%i') as pag_changedate, set_name, def_name
					FROM vwk_pages
					INNER JOIN vwk_pag_definitions ON def_code = pag_def_code
					INNER JOIN vwk_definition_sets ON set_code = def_set_code
					LEFT JOIN ( vwk_pag_kwd_connection 
							INNER JOIN vwk_keywords ON kwd_id = pkc_kwd_id AND kwd_end_node = 1 AND kwd_single_page = 0 AND kwd_state = 1
						)
						ON pkc_pag_id = pag_id

					WHERE pag_org_id = ".$_SESSION['session_org_id'] ."
					GROUP BY pag_id, pag_name, pag_active, pag_admin_active, pag_editted, pag_changedate
					ORDER BY set_code, def_code, def_order, pag_admin_active DESC, pag_changedate DESC";
		} else {
			$sql = "SELECT pag_id, pag_def_code, pag_name, pag_active, pag_admin_active, pag_editted, count(pkc_kwd_id) as pag_keywords, DATE_FORMAT(pag_changedate, '%d-%m-%Y %H:%i') as pag_changedate, set_name, def_name
					FROM vwk_pages
					INNER JOIN vwk_page_rights ON pri_pag_id = pag_id AND pri_usr_id = ".$_SESSION['session_usr_id']."
					INNER JOIN vwk_pag_definitions ON def_code = pag_def_code
					INNER JOIN vwk_definition_sets ON set_code = def_set_code
					LEFT JOIN (vwk_pag_kwd_connection 
							INNER JOIN vwk_keywords ON kwd_id = pkc_kwd_id AND kwd_end_node = 1 AND kwd_single_page = 0 AND kwd_state = 1
						) ON pkc_pag_id = pag_id
					
					WHERE pag_org_id = ".$_SESSION['session_org_id'] ."
					GROUP BY pag_id, pag_name, pag_active, pag_admin_active, pag_editted, pag_changedate
					ORDER BY set_code, def_code, def_order, pag_changedate DESC";
		}
		$rs = $this->_db->query($sql);

		while ($r = $rs->Row()) {
			$this->_smrt->append('paginas', $r);
			$rs->MoveNext();
		}

	//--------------------------------------------
	//--- SHOW TEMPLATE

		// Assign globals to template
		$this->assignTemplateGlobals();

		// Partse template
		$this->_smrt->display($this->_settings->templates->pagina_beheer);
	}


	function medewerker_beheer() {
		if (!$this->_check_contract()) {
			return;
		}

		global $g_obj_i3a;

		$show_new_user_form = false;
		if (isset($_REQUEST['new'])) {
			$show_new_user_form = true;
		}


	//--------------------------------------------
	//--- DELETE USER

		if (isset($_REQUEST['delete']) && is_numeric($_REQUEST['delete'])) {
			//--- delete a user
			/* active user must be a manager and the delete user must be an org-user of the current org */

			$usrinfo = $this->_get_user_info($_SESSION['session_usr_id']);
			if ($usrinfo['GATT_VWK_IS_MANAGER'] == 'Y') {
				//--- user is manager
				$org_users = $this->_get_org_users($_SESSION['session_org_id']);
				if (isset($org_users[$_REQUEST['delete']]) && is_array($org_users[$_REQUEST['delete']])) {
					//--- user is een medewerker van huidige org

					$g_obj_i3a->deleteUser($_REQUEST['delete']);

				}
			}
		}

	//--------------------------------------------
	//--- SAVE & CREATE USER

		if (isset($_REQUEST['save']) && $_REQUEST['save'] == '1') {
			$save_data = $_REQUEST;
			$save_data['usr_id'] = $_REQUEST['edit_usr_id'];
			$save_data['USR_ORG_ID'] = $_SESSION['session_org_id'];
			$save_data['USR_DEF_CODE'] = 'MAT';

			$g_obj_i3a->setVariable('email->profile_created', '');
			$new_usr_id = $g_obj_i3a->saveUser($save_data, false);

			if (is_numeric($new_usr_id)) {
				//-- disable email
				$g_obj_i3a->setVariable('email->member_activated', '');
				//-- update status
//				$g_obj_i3a->setMember($new_usr_id, $this->_settings->general->project->mainOrganizationID, ($_REQUEST['MBR_USR_STATUS']=='on'));
				$g_obj_i3a->setMember($new_usr_id, $org_id = $_SESSION['arr_cur_org']['ORG_ID'], ($_REQUEST['MBR_USR_STATUS']=='on'));
			} else {

				$this->_smrt->assign('i3a_error', $g_obj_i3a->_lastError);
				$show_new_user_form = true;


			}

		}

	//--------------------------------------------
	//--- EDIT & NEW USER

		if ((isset($_REQUEST['edit']) && is_numeric($_REQUEST['edit'])) || $show_new_user_form) {
			//--- edit or create an user
			/* active user must be a manager and the edit user must be an org-user of the current org */
			$usrinfo = $this->_get_user_info($_SESSION['session_usr_id']);
			if ($usrinfo['GATT_VWK_IS_MANAGER'] == 'Y') {
				//--- user is manager
				$org_users = $this->_get_org_users($_SESSION['session_org_id']);
				if (isset($org_users[$_REQUEST['edit']]) && is_array($org_users[$_REQUEST['edit']])) {
					//--- user is een medewerker van huidige org

					$edit_usr = $this->_get_user_info($_REQUEST['edit']);
					if (is_array($edit_usr)) {
						$edit_usr['MBR_USR_STATUS'] = ($this->_get_member_status(0, $_REQUEST['edit']) > 0);
						$this->_smrt->assign('edit_medewerker', $edit_usr);

					} else {
						//-- invalid user / user not found
					}
				} elseif ($show_new_user_form) {
					//--- new user
					$this->_smrt->assign('edit_medewerker', $_REQUEST);

				}
			}

		}

	//--------------------------------------------
	//--- USER OVERVIEW

		$usr_rows = $this->_get_org_users($_SESSION['session_org_id'], false, 'both');

		foreach ($usr_rows as $usr) {
//			$usr_status = $this->_get_member_status($this->_settings->general->project->mainOrganizationID, $usr['USR_ID']);
			$usr_status = $this->_get_member_status($org_id = $_SESSION['arr_cur_org']['ORG_ID'], $usr['USR_ID']);
			
			$usr['MBR_USR_STATUS'] = ($usr_status > 0);

			$this->_smrt->append('medewerkers', $usr);
		}


		// Assign globals to template
		$this->assignTemplateGlobals();

		// Partse template
		$this->_smrt->display($this->_settings->templates->medewerker_beheer);
	}

	function do_license_check() {
		global $g_obj_i3a;

		if (isset($_REQUEST['license_is_checked']) && $_REQUEST['license_is_checked']) {
		
			setcookie('cookie_vwk_license_ok', 1, time() + (3600*24*3600), '/', '.'.$this->_settings->general->project->hostname, 0);

			if (is_numeric($this->_settings->default_maillist_id)) {

				$this->add_user_to_mailinglist($_SESSION['session_usr_id']);
				$g_obj_i3a->setGroupMember($_SESSION['session_usr_id'], $_SESSION['arr_cur_org']['ORG_ID'], 'ACT');
				
			}

			if (isset($_REQUEST['redirect_url']) && $_REQUEST['redirect_url']) {
				//Header('Location: '.$_REQUEST['redirect_url']);exit();

				$this->_smrt->assign('license_ok', 1);
				$this->_smrt->assign('redirect_url', $_REQUEST['redirect_url']);
				$this->_smrt->assign('content', $this->_tdyp_get_article('PINTRO'));
			}

		} else {

			$this->_smrt->assign('content', $this->_tdyp_get_article('PLIC'));

		}


		// Assign globals to template
		$this->assignTemplateGlobals();

		// Partse template
		$this->_smrt->display($this->_settings->templates->license_check);

		

	}

	function add_user_to_mailinglist($usr_id) {

		global $globalSettings, $g_arr_cur_org;
		require_once $globalSettings->tmai0300->paths->ddi;
		$obj_tmai0300 = new TroyceMailing();
		$obj_tmai0300->setVariable('org_id',$g_arr_cur_org['ORG_ID']);
		
		$obj_tmai0300->setVariable('usr_id', $usr_id);
		$obj_tmai0300->saveLists($obj_tmai0300->saveUser(), array('tmai_lst' => array($this->_settings->default_maillist_id => 1)));

		$obj_tmai0300->execute("UPDATE tbl_tma_users SET usr_name = '".mysql_escape_string($_SESSION['session_usr_greeting']) ."', usr_email = '".$this->_get_user_info($usr_id, 'USR_EMAIL')."' WHERE usr_i3a_id = ".$usr_id);
	}
	

	function home() {

		$this->_smrt->assign('content', $this->_tdyp_get_article('OHOM'));

		// Assign globals to template
		$this->assignTemplateGlobals();

		// Partse template
		$this->_smrt->display($this->_settings->templates->home);
	}

	function _tdyp_get_article($code) {
		global $globalSettings;
		require_once $globalSettings->tdyp0207->paths->ddi;

		$pag = new dynamicPages();
		$pag->setVariable("org_id",$_SESSION['arr_cur_org']['ORG_ID']);
		$pag->setVariable("dateformat","d-m-Y");

		$page_contents = $pag->getArticle($code);
		$pag = null;


		return $page_contents;

	}

	function pagina_detail() {
		if (isset($_REQUEST['id']) && is_numeric($_REQUEST['id'])) {

			$page = $this->_get_page_info($_REQUEST['id']);

			// Assign globals to template
			$this->assignTemplateGlobals();

			if ($this->_allowed_to_view_page($_REQUEST['id'])) {



				foreach ($page['fields'] as $field) {
					$field['val_value'] = stripslashes($field['val_value']);
					$fields[$field['fld_code']] = $field;
				}
				$page['fields'] = $fields;

				$this->_smrt->assign('page', $page);


				// Assign to template
				
				$this->_smrt->assign('page_links', $this->_get_links(VWK_LINK_TYPE_PAG, $_REQUEST['id'], true));
				$this->_smrt->assign('controls', $this->_getSearchFields("result"));
				$this->_smrt->assign('form', $this->_get_template_forminfo());

				// Parse template
				$this->_smrt->display($this->_settings->templates->pagina_detail);

			} else {

				$this->triggerError(VWK_ERROR_INVALID_PAGE);

			}

		} else {

			$this->triggerError(VWK_ERROR_INVALID_PAGE);

		}
	}

	function _add_my_page($pag_id) {
		if (!is_numeric($pag_id)) return;

		$sql = "REPLACE INTO vwk_my_pages SET
					myp_usr_id		= ".$_SESSION['session_usr_id'].",
					myp_pag_id		= ". $pag_id.",
					myp_createdate	= NOW()";

		$this->_db->execute($sql);
	}

	function _delete_my_page($pag_id) {
		if (!is_numeric($pag_id)) return;

		$sql = "DELETE FROM vwk_my_pages
				WHERE	myp_usr_id		= ".$_SESSION['session_usr_id']."
				AND		myp_pag_id		= ". $pag_id;

		$this->_db->execute($sql);

	}


	function mijn_verwijskompas() {
		/*
			options:	- add a page
						- deletes a page
						- view list
		*/

		if (isset($_REQUEST['add']) && is_numeric($_REQUEST['add'])) {
			//--- ADD

			if ($this->_allowed_to_view_page($_REQUEST['add'])) {
				$this->_add_my_page($_REQUEST['add']);

			}

		}

		if (isset($_REQUEST['delete']) && is_numeric($_REQUEST['delete'])) {
			//--- DELETE
			$this->_delete_my_page($_REQUEST['delete']);

		}


		if (isset($_REQUEST['r'])) {
			if ($_REQUEST['r'] == 'ref') {
				Header('Location: '. $_SERVER['HTTP_REFERER']);exit();
			} else {
				Header('Location: '. $_REQUEST['r']);exit();
			}
		}

		$sql = "	SELECT
							DISTINCT vwk_pages.*
					,		loc_name
					,		ctr_org_name
					,		vwk_vals_city.val_value AS city
					,		vwk_vals_desc.val_value AS description
					,		vwk_vals_doc.val_value AS doctor
					,		vwk_vals_phone.val_value AS phone
					,		vwk_vals_zip.val_value as zipcode
					,		vwk_vals_address.val_value as address
					FROM	vwk_my_pages
					INNER JOIN vwk_pages ON pag_id = myp_pag_id AND pag_active = 1
					INNER JOIN vwk_locations ON loc_id = pag_loc_id
					INNER JOIN vwk_contract ON ctr_org_id = pag_org_id AND ctr_org_state = 1 AND (ctr_enddate IS NULL OR vwk_contract.ctr_enddate >= NOW())
					INNER JOIN vwk_pag_kwd_connection ON pkc_pag_id = pag_id

					LEFT JOIN vwk_pag_values AS vwk_vals_address ON vwk_vals_address.val_pag_id=pag_id AND vwk_vals_address.val_fld_code = 'ADRES'
					LEFT JOIN vwk_pag_values AS vwk_vals_zip ON vwk_vals_zip.val_pag_id=pag_id AND vwk_vals_zip.val_fld_code = 'POSTCODE'
					LEFT JOIN vwk_pag_values AS vwk_vals_city  ON vwk_vals_city.val_pag_id=pag_id  AND vwk_vals_city.val_fld_code  = 'WOONPLAATS'
					LEFT JOIN vwk_pag_values AS vwk_vals_desc ON vwk_vals_desc.val_pag_id=pag_id  AND vwk_vals_desc.val_fld_code  = 'ZOEK_BESCHRIJVING'
					LEFT JOIN vwk_pag_values AS vwk_vals_doc   ON vwk_vals_doc.val_pag_id=pag_id   AND vwk_vals_doc.val_fld_code   = 'NAAM_HOOFD'
					LEFT JOIN vwk_pag_values AS vwk_vals_phone ON vwk_vals_phone.val_pag_id=pag_id AND vwk_vals_phone.val_fld_code = 'ALGEMEEN_TELEFOON'
					WHERE	myp_usr_id = ".$_SESSION['session_usr_id'];

		$rs = $this->_db->query($sql);

		while ($r = &$rs->Row()) {
			$this->_smrt->append('my_pages', $r);
			$rs->moveNext();
		}

		$this->_smrt->assign('content', $this->_tdyp_get_article('PMVK'));


		// Assign globals to template
		$this->assignTemplateGlobals();

		$this->_smrt->assign('num_of_pages',$rs->RowCount	);

		// Partse template
		$this->_smrt->display($this->_settings->templates->mijn_vwk);
	}

	function login_page() {

		$this->_smrt->assign('content', $this->_tdyp_get_article('OHOM'));

		// Assign globals to template
		$this->assignTemplateGlobals();

		// Partse template
		$this->_smrt->display($this->_settings->templates->login);
	}


/* ZOEKEN */

		function _getSearchFields($screen) {

			// Include control class

			// NAMES
			if ($screen == "search") {

				$result['names']['alg']['ctrl']	= $this->_ctrl->txt("Algemeen", "name_alg", $_SESSION['session_vwk_src']['name_alg'], 50, array('style'=>'width:358px', 'javascript'=>'onkeyup="searchOnEnter(event);"'));

				$result['names']['usr']['ctrl']	= $this->_ctrl->txt("Naam arts", "name_usr", $_SESSION['session_vwk_src']['name_usr'], 50, array('style'=>'width:358px', 'javascript'=>'onkeyup="searchOnEnter(event);"'));
				$result['names']['org']['ctrl']	= $this->_ctrl->txt("Naam ziekenhuis", "name_org", $_SESSION['session_vwk_src']['name_org'], 50, array('style'=>'width:358px', 'javascript'=>'onkeyup="searchOnEnter(event);"'));

//				$result['keywords']['options'] = $this->_get_keyword_list_options();

			} else {

				$result['names']['usr']['name']	= $_SESSION['session_vwk_src']['name_usr'];
				$result['names']['org']['name']	= $_SESSION['session_vwk_src']['name_org'];
				$result['names']['alg']['name']	= $_SESSION['session_vwk_src']['name_alg'];

				$result['keyword']['id']	= $_SESSION['session_vwk_src']['search_kwd_id'];
				$result['keyword']['name']	= $_SESSION['session_vwk_src']['search_kwd_name'];


			}


			/* Keywords */

			//-- get parent_kwd info
			if (is_numeric($_SESSION['session_vwk_src']['kwd_id'])) {
				$result['keywords']['parent_name'] = $this->_get_keywords_by_id($_SESSION['session_vwk_src']['kwd_id']);

				if (isset($_SESSION['session_vwk_src']['sub_kwd_ids']) && strlen($_SESSION['session_vwk_src']['sub_kwd_ids']) > 0) {
					$kwds = $this->_get_keywords_by_id(explode(':', $_SESSION['session_vwk_src']['sub_kwd_ids']));
					$result['keywords']['items'] = $kwds;
				}
			}


			// LOCATIONS
			$locs = $this->_get_locations(false, false, true);
			if (isset($_SESSION['session_vwk_src']['loc_ids']) && strlen($_SESSION['session_vwk_src']['loc_ids']) > 0) {

				$loc_ids = explode(':',$_SESSION['session_vwk_src']['loc_ids']);

				foreach ((array)$loc_ids as $loc_code) {

					$result['locations']['names'][] = $locs[$loc_code];

				}
			}




			// Return the controls
			return $result;

		}


		function _setSessions($reset=false) {

			if ($reset) {

				$_SESSION['session_vwk_src'] = array();

				} else {


				if (!is_null($_REQUEST['name_usr'])) {

					$_SESSION['session_vwk_src']['name_alg']	= $_REQUEST['name_alg'];
					$_SESSION['session_vwk_src']['name_usr']	= $_REQUEST['name_usr'];
					$_SESSION['session_vwk_src']['name_org']	= $_REQUEST['name_org'];

					if (isset($_REQUEST['search_kwd_name']) && strlen(trim($_REQUEST['search_kwd_name'])) == 0) {
						$_SESSION['session_vwk_src']['search_kwd_id']	= '';
						$_SESSION['session_vwk_src']['search_kwd_name']	= '';
					} else {
						$_SESSION['session_vwk_src']['search_kwd_id']	= $_REQUEST['search_kwd_id'];
						$_SESSION['session_vwk_src']['search_kwd_name']	= $_REQUEST['search_kwd_name'];
					}
					


	//				$_SESSION['session_vwk_src']['kwd_id']		= $_REQUEST['vwk_kwd_selector'];
					$_SESSION['session_vwk_src']['sub_kwd_ids']	= $_REQUEST['checked_sub_kwd_ids'];
					$_SESSION['session_vwk_src']['sub_kwd_names']	= $_REQUEST['frm_checked_sub_kwd_names'];


					$_SESSION['session_vwk_src']['loc_ids']		= $_REQUEST['checked_loc_ids'];
					$_SESSION['session_vwk_src']['loc_names']	= stripslashes($_REQUEST['frm_checked_loc_names']);

					$koek = array();
					$koek['loc_ids'] = $_SESSION['session_vwk_src']['loc_ids'];
					$koek['loc_names'] = $_SESSION['session_vwk_src']['loc_names'];

					setcookie('cookie_vwk_search', serialize($koek), time() + (3600*24*3600), '/', '.'.$this->_settings->general->project->hostname, 0);
				}
			}

			if (isset($_COOKIE['cookie_vwk_search'])) {

				if (!isset($_REQUEST['checked_loc_ids'])) {

					$cookie_data = unserialize(stripslashes($_COOKIE['cookie_vwk_search']));

					$_SESSION['session_vwk_src']['loc_ids']		= $cookie_data['loc_ids'];
					$_SESSION['session_vwk_src']['loc_names']	= $cookie_data['loc_names'];
				}
			}

		}

		function _get_template_forminfo() {
			// ADD FORM TAGS, JAVASCRIPT AND BUTTONS
			$js_h =	"<script language=\"javascript\">";

			$js =	"function fSearch() {".
					"	document.getElementById('action').value = 'search';".
					"	document.forms['vwk_search'].submit();".
					"}".

					"function fLocation() {".
					"	document.getElementById('action').value = 'location';".
					"	document.forms['vwk_search'].submit();".
					"}".

					"function fMap(id) {".
					"	var chk = document.getElementById('chk_loc_id[' + id + ']');".
					"	chk.checked = !chk.checked;".
					"	fIsSet('loc');".
					"}".

					"function fSetRdo(type, choise) {".
					"	if (choise) {".
					"		document.getElementById('rdo_' + type + '2').checked = true;".
					"		document.getElementById('rdo_' + type).value = 'Y';".
					"	} else {".
					"		document.getElementById('rdo_' + type + '1').checked = true;".
					"		document.getElementById('rdo_' + type).value = 'N';".
					"	}".
					"}".

					"function fIsSet(type) {".
					"	var elm = document.vwk_search.elements;".
					"	var is_set = false;".
					"	for(id=0; id<elm.length; id++) {".
					"		if (elm[id].name.substr(0,10) == 'chk_' + type + '_id' && document.getElementById(elm[id].name).checked) {".
					"			is_set = true;".
					"			break;".
					"		}".
					"	}".
					"	fSetRdo(type, is_set);".
					"}".

					"function fReset(type) {".
					"	var elm = document.vwk_search.elements;".
					"	var count = 0;".
					"	for(id=0; id<elm.length; id++) {".
					"		if (elm[id].name.substr(0,10) == 'chk_' + type + '_id') {".
					"			document.getElementById(elm[id].name).checked = false;".
					"			count++;".
					"		}".
					"	}".
					"	if (count) fSetRdo(type, false);".
					"}".

					"function fBack() {".
					"	document.forms['vwk_search'].submit();".
					"}".

					"function fNew() {".
					"	document.getElementById('action').value = 'new';".
					"	document.forms['vwk_search'].submit();".
					"}";

			$js_f =	"</script>";

			$action = ''; #"<input type=\"hidden\" name=\"action\" id=\"action\">";

			$form['open']		= '<form method="post" name="vwk_search" id="vwk_search" action="/vwk/zoeken/">';
			$form['close']		= "</form>";
			$form['submit']		= "javascript:fSearch();";
			$form['back']		= "javascript:fBack();";
			$form['new']		= "javascript:fNew();";
			$form['locations']	= "javascript:fLocation();";
			$form['javascript']	= $js_h . $js . $js_f . $action;

			return $form;
		}

		function printSearch() {
			$this->_setSessions();

			// Assign globals to template
			$this->assignTemplateGlobals();
			$this->_smrt->assign('form', $this->_get_template_forminfo());

			switch($_REQUEST["action"]) {

				case "new":
					//setcookie('cookie_vwk_search', '', time() - 3600, '/', '.'.$this->_settings->general->project->hostname, 0);
//					$_SESSION['session_vwk_src'] = array();
					$this->_setSessions(true);

				case "search":
				default:



					// Check if search conditions are met
					if (
					    (
					        $_SESSION['session_vwk_src']['name_alg'] 
							|| 
					        $_SESSION['session_vwk_src']['name_usr'] 
							|| 
							$_SESSION['session_vwk_src']['name_org']
						    ||
							$_SESSION['session_vwk_src']['search_kwd_id']
							||
							(isset($_SESSION['session_vwk_src']['sub_kwd_ids']) && strlen($_SESSION['session_vwk_src']['sub_kwd_ids']) > 0)
							||
							(isset($_SESSION['session_vwk_src']['loc_ids']) && strlen($_SESSION['session_vwk_src']['loc_ids']) > 0)
					    )
					   && $_REQUEST["action"]=='search'
					 ) {


						// Assign to template
						$this->_smrt->assign('results', $this->_doSearch());
						$this->_smrt->assign('order', $_SESSION['session_vwk_src']['order']);

						// Get the controls
						$controls = $this->_getSearchFields("result");

						// Assign to template
						$this->_smrt->assign('controls', $controls);

						// Parse template
						$this->_smrt->display($this->_settings->templates->search_result);

					} else {

						if ($_REQUEST["action"] == 'search') {

							$this->_smrt->assign('message', "U moet de naam van de arts of ziekenhuis invullen of een trefwoord kiezen.<br>");

						}


						$this->_smrt->assign('content', $this->_tdyp_get_article('PTIP'));
						

						// Get the controls
						$controls = $this->_getSearchFields("search");

						// Assign to template
						$this->_smrt->assign('controls', $controls);

						// Parse template
						$this->_smrt->display($this->_settings->templates->search);

					}

					break;

			}

		}

		function _search_pages($search_term) {
			//-- searches in
			//	- page fields
			//	- locations
			//	- connected keywords

			$pag_ids = array();
			$s = strtolower(mysql_escape_string($search_term));

			$sql = "SELECT DISTINCT pag_id
					FROM vwk_pages
					INNER JOIN vwk_keywords, vwk_pag_kwd_connection ON kwd_id = pkc_kwd_id AND kwd_single_page = 0 AND pkc_pag_id = pag_id AND lower(kwd_name) LIKE '%".$s."%'
					WHERE pag_active = 1";
			$rs = $this->_db->query($sql);
			$pag_ids = array_merge($pag_ids, rs2arr($rs));

			$sql = "SELECT DISTINCT pag_id
					FROM vwk_pages
					INNER JOIN vwk_locations ON loc_id = pag_loc_id AND lower(loc_name) LIKE '%".$s."%'
					WHERE pag_active = 1";
			$rs = $this->_db->query($sql);
			$pag_ids = array_merge($pag_ids, rs2arr($rs));

			$sql = "SELECT DISTINCT pag_id
					FROM vwk_pages
					INNER JOIN vwk_pag_values, vwk_pag_fields ON fld_code = val_fld_code AND val_pag_id = pag_id AND fld_search IS NOT NULL AND lower(val_value) LIKE '%".$s."%'
					WHERE pag_active = 1";
			$rs = $this->_db->query($sql);
			$pag_ids = array_merge($pag_ids, rs2arr($rs));

			return $pag_ids;
		}


		function _doSearch() {
			
			$joins = '';
			$where = '';

			// Check is search should include medical staff

			if ($_SESSION['session_vwk_src']['name_alg']) {
				$search_terms = explode(' ',$_SESSION['session_vwk_src']['name_alg']);

				$matches = null;
				foreach ($search_terms as $term) {
					if (is_null($matches)) {
						$matches = $this->_search_pages($term);
					} else {
						$matches = array_intersect($matches, $this->_search_pages($term));
					}
					
				}
				if (count($matches)) {
					$where .= " AND pag_id in (".implode(',',$matches).") ";
				} else {
					$where .= " AND 1=0 ";
				}

				$joins .= '';

			}


			if ($_SESSION['session_vwk_src']['name_usr']) {

				$search_terms = explode(' ',$_SESSION['session_vwk_src']['name_usr']);
				$sql_like = array();
				foreach ($search_terms as $term) {
					$sql_like[] = "LOWER( usr_pag_values.val_value ) LIKE '%".strToLower(mysql_escape_string($term))."%'";
				}

				$joins .= " INNER JOIN vwk_pag_fields as usr_pag_fields ON
							usr_pag_fields.fld_def_code = pag_def_code
							AND	usr_pag_fields.fld_search IN ('ALG','USR')";
				$joins .= " INNER JOIN vwk_pag_values as usr_pag_values
							ON	usr_pag_fields.fld_code = usr_pag_values.val_fld_code
							AND	usr_pag_values.val_pag_id = pag_id
							AND ( ". implode(" AND ", $sql_like)." )";
			}

			// Check is search should include hospitals
			if ($_SESSION['session_vwk_src']['name_org']) {

				$search_terms = explode(' ',$_SESSION['session_vwk_src']['name_org']);
				$sql_like = array();
				foreach ($search_terms as $term) {
					$sql_like[] = "LOWER( org_pag_values.val_value ) LIKE '%".strToLower(mysql_escape_string($term))."%'";
				}

				/*$joins .= " INNER JOIN 
								vwk_pag_values as org_pag_values
							,	vwk_pag_fields as org_pag_fields
							ON	org_pag_fields.fld_code = org_pag_values.val_fld_code
							AND	org_pag_fields.fld_def_code = pag_def_code
							AND	org_pag_fields.fld_search IN ('ALG','ORG')
							AND	org_pag_values.val_pag_id = pag_id
							AND ( ". implode(" OR ", $sql_like)." )";
				*/
				$joins .= " INNER JOIN vwk_pag_fields as org_pag_fields 
								ON org_pag_fields.fld_def_code = pag_def_code 
								AND org_pag_fields.fld_search IN ('ALG','ORG')
							INNER JOIN vwk_pag_values as org_pag_values 
								ON org_pag_values.val_fld_code = org_pag_fields.fld_code
								AND	org_pag_values.val_pag_id = pag_id
								AND ( ". implode(" AND ", $sql_like)." )";

			}

			$loc_table = '';
			// Check if search should include locations
			if (isset($_SESSION['session_vwk_src']['loc_ids']) && strlen($_SESSION['session_vwk_src']['loc_ids']) > 0) {

				$joins .= " INNER JOIN vwk_locations ON pag_loc_id=loc_id AND pag_loc_id IN (".str_replace(':', ',', $_SESSION['session_vwk_src']['loc_ids']).") ";

			} else {
				//$loc_table = ', vwk_locations';
				$joins .= " INNER JOIN vwk_locations ON pag_loc_id = loc_id ";

			}


			// Check is search should include specialismes
			if (isset($_SESSION['session_vwk_src']['sub_kwd_ids']) && strlen($_SESSION['session_vwk_src']['sub_kwd_ids']) > 0) {

				$joins .= " INNER JOIN vwk_pag_kwd_connection ON pkc_pag_id=pag_id AND pkc_kwd_id IN (".str_replace(':', ',', $_SESSION['session_vwk_src']['sub_kwd_ids']).")";

			}

			if (isset($_SESSION['session_vwk_src']['search_kwd_id']) && is_numeric($_SESSION['session_vwk_src']['search_kwd_id'])) {

				$joins .= " INNER JOIN vwk_pag_kwd_connection ON pkc_pag_id=pag_id AND pkc_kwd_id = ".$_SESSION['session_vwk_src']['search_kwd_id'];

			}



			// Set order
			if ($_REQUEST['order'] != '') $_SESSION['session_vwk_src']['order'] = $_REQUEST['order'];
			$order = $_SESSION['session_vwk_src']['order'] == "CITY" ? "vwk_vals_city.val_value" : "ctr_org_name";

			$new_sql = "FROM vwk_pages
						INNER JOIN vwk_contract ON ctr_org_id = pag_org_id AND ctr_org_state = 1 AND (ctr_enddate IS NULL OR vwk_contract.ctr_enddate >= NOW()) 
						INNER JOIN vwk_pag_definitions ON def_code = pag_def_code
						LEFT JOIN vwk_pag_values AS vwk_vals_city ON vwk_vals_city.val_pag_id=pag_id AND vwk_vals_city.val_fld_code='WOONPLAATS'
						LEFT JOIN vwk_pag_values AS vwk_vals_desc ON vwk_vals_desc.val_pag_id=pag_id AND vwk_vals_desc.val_fld_code='ZOEK_BESCHRIJVING'
						LEFT JOIN vwk_pag_values AS vwk_vals_doc ON vwk_vals_doc.val_pag_id=pag_id AND vwk_vals_doc.val_fld_code='NAAM_HOOFD'
						LEFT JOIN vwk_pag_values AS vwk_vals_phone ON vwk_vals_phone.val_pag_id=pag_id AND vwk_vals_phone.val_fld_code='ALGEMEEN_TELEFOON'
						LEFT JOIN vwk_my_pages ON myp_pag_id=pag_id AND myp_usr_id=".$_SESSION['session_usr_id']."
						".$joins."
						WHERE pag_active = 1
						".$where." 
						ORDER BY def_order ASC, ".$order." ASC";

			// Count the pages
			$rs = $this->_db->Query("SELECT DISTINCT pag_id ".$new_sql);

			$_SESSION['session_vwk_src']['page_numbers'] = array();
			while(!$rs->EOF()) {

				$_SESSION['session_vwk_src']['page_numbers'][] = $rs->Row('pag_id');
				$rs->MoveNext();

			}
			$total_records = $rs->RowCount;
			$rs->Close();

			// Calculate pages
			$number_of_pages = ceil($total_records / MAX_RESULT);
			for($i=1; $i <= $number_of_pages; $i++) $index[] = $i;

			$offset = ($_REQUEST['offset'] ? $_REQUEST['offset'] : 0);
			$start = ($offset * MAX_RESULT) + 1;

			// Get the pages
			$rs = $this->_db->Query("SELECT DISTINCT vwk_pages.*, myp_usr_id, loc_name, ctr_org_name, vwk_vals_city.val_value AS city, vwk_vals_desc.val_value AS description, vwk_vals_doc.val_value AS doctor, vwk_vals_phone.val_value AS phone ".$new_sql, ($offset * MAX_RESULT), MAX_RESULT);

			$counter = 0;
			// Loop throug the pages
			while(!$rs->EOF()) {


				$result['pages'][$counter] = $rs->Row();
				$result['pages'][$counter]['index'] = $start + $counter;
				$counter++;
				$rs->MoveNext();

			}
			$rs->Close();

			// Page counter
			$result['counter']['total']		= $total_records;
			$result['counter']['pages']		= $number_of_pages;
			$result['counter']['index']		= $index;
			$result['counter']['offset']	= $offset;
			$result['counter']['current']	= $offset + 1;
			$result['counter']['start']		= $start;
			$result['counter']['end']		= $start + $counter - 1;

			// Return the result
			return $result;

		}

	
	function search_keywords($kwd_name, $p=1, $loc_ids='') {
		$max_keywords_per_page = 20;

		$js = "var result = [];\n";
		$sql_like = array();
		$search_terms = explode(' ',$kwd_name);
		foreach ($search_terms as $term) {
			$term = strtolower(mysql_escape_string($term));
			if (strlen(trim($term)) > 0) {
				$sql_like[] = "(lower(kwd_bread_crumb) LIKE '%".$term."%' OR lower(ksy_synonym) LIKE '%".$term."%')";

			}
		}

		if (count($sql_like)) {

			if ($p > 1) {
				$js .= "var prev_page = ".($p-1).";\n";
			}
			$limit_offset = ($p-1)*$max_keywords_per_page;
			$limit_count = $max_keywords_per_page+1;

			$sql_loc = '';
			if ($loc_ids) {
				$loc_ids = explode(':',$loc_ids);
				if (count($loc_ids) > 0) {
					$sql_loc = "AND pag_loc_id IN (".implode(',', $loc_ids).")";
				}
			}


			$sql = "SELECT kwd_id
					, kwd_bread_crumb
					, COUNT(DISTINCT(pag_id)) AS hits
					, REPLACE(kwd_bread_crumb, kwd_name, ksy_synonym) AS syno
					FROM vwk_keywords 
					LEFT JOIN vwk_kwd_synonym ON ksy_kwd_id = kwd_id
					INNER JOIN vwk_pag_kwd_connection ON pkc_kwd_id = kwd_id
					INNER JOIN vwk_pages ON pag_id = pkc_pag_id AND pag_active = 1
					INNER JOIN vwk_contract ON ctr_org_id = pag_org_id
					WHERE	kwd_state = 1
					AND		ctr_org_state = 1
					AND		(ctr_enddate IS NULL OR vwk_contract.ctr_enddate >= NOW()) 
					AND		( ".implode(' AND ', $sql_like).")
					". $sql_loc ."
					GROUP BY kwd_id
					HAVING hits > 0
					ORDER BY kwd_bread_crumb
					LIMIT ". $limit_offset .", ".$limit_count;


			$rs = $this->_db->query($sql);

			$i=0;
			while ($r = $rs->row()) {

				if ($r['syno'] && !str_match($r['kwd_bread_crumb'], $search_terms)) {
					$result_text = $r['syno'];
				} else {
					$result_text = $r['kwd_bread_crumb'];
				}

				if ($i == $max_keywords_per_page) {
					$js .= "var next_page = ".($p+1).";\n";
				} else {
					$js .= "result[".$i++."] = [".$r['kwd_id'].", '".js_escape($result_text)."', ".$r['hits']."];\n";
				}
				$rs->moveNext();
			}
			$rs->Close();
		}
		return $js;
	}


	function print_kwd_popup() {
		die(' NOT POSSIBLE' );
	}

	function print_loc_popup() {

		$vwk_template_vars = array();
		$vwk_template_vars['locations'] = $this->_get_locations(true);


		if (isset($_REQUEST['loc_selected']) && strlen($_REQUEST['loc_selected']) > 0) {
			$vwk_template_vars['loc_type_value'] = 'Y';
			$vwk_template_vars['selected_locs'] = array();
			foreach (explode(':', $_REQUEST['loc_selected']) as $id) {
				$vwk_template_vars['selected_locs'][$id] = 'on';
			}
		} else {
			$vwk_template_vars['loc_type_value'] = 'N';
		}
		
		$this->_smrt->assign('vwk', $vwk_template_vars);


		$this->assignTemplateGlobals();

		// Parse template
		$this->_smrt->display($this->_settings->templates->search_loc_popoup);
	}


	function print_loc_edit_popup() {

		$vwk_template_vars = array();
		$vwk_template_vars['locations'] = $this->_get_locations(true);
		
		$vwk_template_vars['locations_simple_list'] = $this->_get_locations(false, false, true);

		if (isset($_REQUEST['loc_selected']) && is_numeric($_REQUEST['loc_selected'])) {
			$vwk_template_vars['selected_loc'] = $_REQUEST['loc_selected'];
		}
		
		$this->_smrt->assign('vwk', $vwk_template_vars);


		$this->assignTemplateGlobals();

		// Parse template
		$this->_smrt->display($this->_settings->templates->search_loc_popoup_edit);
	}



}

//-- turns a multi dimensional array into 2d
function array_demulti(&$arr,$new_value_index) {

	$return = array();
	foreach ($arr as $index => $row) {
		$return[$index] = $row[$new_value_index];
	}
	return $return;
}

function tpl_make_clickable($text) {

	// pad it with a space so we can match things at the start of the 1st line.
	$ret = ' ' . $text;

	// matches an "xxxx://yyyy" URL at the start of a line, or after a space. 
	// xxxx can only be alpha characters. 
	// yyyy is anything up to the first space, newline, comma, double quote or < 
	$ret = preg_replace("#(^|[\n \(])([\w]+?://[^ \"\n\r\t<]*)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $ret); 

	// matches a "www|ftp.xxxx.yyyy[/zzzz]" kinda lazy URL thing 
	// Must contain at least 2 dots. xxxx contains either alphanum, or "-" 
	// zzzz is optional.. will contain everything up to the first space, newline, 
	// comma, double quote or <. 
	$ret = preg_replace("#(^|[\n \(])((www|ftp)\.[^ \"\t\n\r<]*)#is", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $ret); 

	// matches an email@domain type address at the start of a line, or after a space.
	// Note: Only the followed chars are valid; alphanums, "-", "_" and or ".".
	$ret = preg_replace("#(^|[\n \(])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret);

	// Remove our padding..
	$ret = substr($ret, 1);

	return($ret);
}

function rs2arr(&$rs, $key_as_index=false) {

	$new_arr = array();

	while ($r = $rs->Row()) {
		if (count($r) == 1) {
			$value = current($r);
		} elseif (count($r) == 2 && $key_as_index !== false) {
			$tmp_r = $r;
			unset($tmp_r[$key_as_index]);
			$value = current($tmp_r);
		} else {
			$value = $r;
			
		}
		if ($key_as_index && isset($r[$key_as_index])) {
			$new_arr[$r[$key_as_index]] = $value;
		} else {
			$new_arr[] = $value;
		}		

		$rs->moveNext();
	}
	$rs->Close();

	return $new_arr;

}

function js_escape($str) {
	return (strtr($str, array('\\'=>'\\\\',"'"=>"\\'",'"'=>'\\"',"\r"=>'\\r',"\n"=>'\\n','</'=>'<\/')));
}

function str_match($str, $arr) {
	foreach ($arr as $s) {
		if (stristr($str, $s) === false) {
			return false;			
		}
	}

	return true;
}

?>
