/**
 * This source file is is part of Saurus CMS content management software.
 * It is licensed under MPL 1.1 (http://www.opensource.org/licenses/mozilla1.1.php).
 * Copyright (C) 2000-2010 Saurused Ltd (http://www.saurus.info/).
 * Redistribution of this file must retain the above copyright notice.
 * 
 * Please note that the original authors never thought this would turn out
 * such a great piece of software when the work started using Perl in year 2000.
 * Due to organic growth, you may find parts of the software being
 * a bit (well maybe more than a bit) old fashioned and here's where you can help.
 * Good luck and keep your open source minds open!
 * 
 * @package		SaurusCMS
 * @copyright	2000-2010 Saurused Ltd (http://www.saurus.info/)
 * @license		Mozilla Public License 1.1 (http://www.opensource.org/licenses/mozilla1.1.php)
 * 
 */
function edit_objekt()
{
    global $site;
    global $objekt;
    global $keel;
    global $class_path;
    global $tyyp;
    // refreshing (fdat['refresh'] = 1) looses object data, I don't know why and because it's done in edit_object.php, I'm not going to fix it, lord knows what it'll screw up
    if ($site->fdat['refresh'] && $site->fdat['id']) {
        $obj = new Objekt(array('objekt_id' => $site->fdat['id']));
        $objekt->objekt_id = $obj->objekt_id;
        $objekt->parent_id = $obj->parent_id;
    }
    if ($objekt->parent_id || $site->fdat['op'] == 'new') {
        $parent = new Objekt(array('objekt_id' => $objekt->objekt_id ? $objekt->parent_id : $site->fdat['parent_id']));
        $pearubriik = $parent->all['sys_alias'] == 'home' ? 1 : 0;
    } else {
        $pearubriik = 0;
    }
    $content_templates = get_templates('CONTENT', $objekt->all['ttyyp_id']);
    if ($content_templates['template_variable_html']) {
        $template_variable_html = $content_templates['template_variable_html'];
        unset($content_templates['template_variable_html']);
    }
    $page_templates = get_templates('PAGE', $objekt->all['page_ttyyp_id']);
    $sql = $site->db->prepare('select ttyyp_id, page_ttyyp_id from keel where keel_id = ' . $keel);
    $default_templates = new SQL($sql);
    $default_templates = $default_templates->fetch('ASSOC');
    foreach ($page_templates as $name => $group) {
        if ($group[$default_templates['page_ttyyp_id']]) {
            $default_page_template = array('id' => $default_templates['page_ttyyp_id'], 'group' => $name, 'name' => $group[$default_templates['page_ttyyp_id']]['nimi']);
        }
    }
    foreach ($content_templates as $name => $group) {
        if ($group[$default_templates['ttyyp_id']]) {
            $default_content_template = array('id' => $default_templates['ttyyp_id'], 'group' => $name, 'name' => $group[$default_templates['ttyyp_id']]['nimi']);
        }
    }
    // parent path
    if ($objekt->all['sys_alias'] == '' && $site->fdat['sys_alias'] == '') {
        // this needs serious rethink and optmisation: there's no need to get the entire tree, parent object's path to top is only needed
        include_once $class_path . 'rubloetelu.class.php';
        $rubs = new RubLoetelu(array('keel' => $keel, 'required_perm' => 'C', 'ignore_perm_for_obj' => $parent ? $parent->objekt_id : 0));
        #$rubs->debug->print_msg();
        $topparents = $rubs->get_loetelu();
        if (is_array($topparents)) {
            asort($topparents);
        }
        foreach ($topparents as $k => $v) {
            if ($parent->objekt_id == $k) {
                $section_name = $v;
                break;
            }
        }
    }
    // setup for section selection
    $_SESSION['parent_selection']['callback'] = 'window.opener.updateSection';
    $_SESSION['parent_selection']['selectable'] = 1;
    $_SESSION['parent_selection']['hide_language_selection'] = '1';
    $_SESSION['parent_selection']['mem_classes'] = array('rubriik');
    //this sucks, really
    $_SESSION['parent_selection']['db_fields'] = array('select_checkbox', 'objekt_id', 'pealkiri');
    $_SESSION['parent_selection']['display_fields'] = array('select_checkbox', 'pealkiri');
    $publish_start = $objekt->all['avaldamisaeg_algus'] > 0 ? $site->db->MySQL_ee_long($objekt->all['avaldamisaeg_algus']) : '';
    /* Don't print out time which is 00:00:00 */
    if (preg_match("/(\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d?\\d\\d)\\s(\\d?\\d)[\\:\\\\.\\/\\-](\\d?\\d)/", $publish_start, $aa_reg)) {
        $publish_start = $aa_reg[2] == "00" && $aa_reg[3] == "00" ? $aa_reg[1] : $publish_start;
    }
    $publish_end = $objekt->all['avaldamisaeg_lopp'] > 0 ? $site->db->MySQL_ee_long($objekt->all['avaldamisaeg_lopp']) : '';
    /* Don't print out time which is 23:59 */
    if (preg_match("/(\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d?\\d\\d)\\s(\\d?\\d)[\\:\\\\.\\/\\-](\\d?\\d)/", $publish_end, $la_reg)) {
        $publish_end = $la_reg[2] == "23" && $la_reg[3] == "59" ? $la_reg[1] : $publish_end;
    }
    // to get the correct path to parent objects set use_alises on
    $site->CONF['use_aliases'] = 1;
    if ($parent) {
        $parent_href = $parent->get_object_href();
    } else {
        $alias = '';
        if ($site->CONF['alias_language_format']) {
            $languages = $site->cash(array('klass' => 'GET_LANGUAGES', 'kood' => 'ALL_LANGUAGE_INFO'));
            if (empty($languages)) {
                $sql = "select keel_id, extension, on_default from keel where on_kasutusel = 1";
                $result = new SQL($sql);
                while ($row = $result->fetch('ASSOC')) {
                    $languages[$row['keel_id']] = $row;
                }
                $site->cash(array('klass' => 'GET_LANGUAGES', 'kood' => 'ALL_LANGUAGE_INFO', 'sisu' => $languages));
            }
        }
        // add languge alias - alias language format 0: none, 1: always, 2: for non-default lang objs
        if ($site->CONF['alias_language_format'] == 1) {
            $alias .= $languages[$objekt->all['keel']]['extension'] . '/';
        } elseif ($site->CONF['alias_language_format'] == 2) {
            if (!$languages[$objekt->all['keel']]['on_default']) {
                $alias .= $languages[$objekt->all['keel']]['extension'] . '/';
            }
        }
        $parent_href = '/' . $alias;
    }
    if ($parent_href && $parent_href != '/' && ($site->CONF['alias_trail_format'] == 0 || $parent->all['sys_alias'] == 'home' || $parent->all['sys_alias'] == 'trash' || $parent->all['sys_alias'] == 'system' || $parent->all['sys_alias'] == 'gallup_arhiiv')) {
        $parent_href = preg_replace('#' . preg_quote('/' . ($parent->all['friendly_url'] ? $parent->all['friendly_url'] : $parent->objekt_id), '#') . '/$#', '/', $parent_href);
    }
    $parent_href = $site->CONF['hostname'] . $parent_href;
    ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
	<head> 	
		<title><?php 
    echo $site->title;
    ?>
 <?php 
    echo $site->cms_version;
    ?>
</title>
		
		<meta http-equiv="Content-Type" content="text/html; charset=<?php 
    echo $encoding ? $encoding : $site->encoding;
    ?>
" />
		<meta http-equiv="Cache-Control" content="no-cache" />
		
		<link rel="stylesheet" href="<?php 
    echo $site->CONF['wwwroot'] . $site->CONF['styles_path'];
    ?>
/datepicker.css" />
		<link rel="stylesheet" href="<?php 
    echo $site->CONF['wwwroot'] . $site->CONF['styles_path'];
    ?>
/section_editor.css" />
		
		<script type="text/javascript" src="<?php 
    echo $site->CONF['wwwroot'] . $site->CONF['js_path'];
    ?>
/yld.js"></script>
		<script type="text/javascript" src="<?php 
    echo $site->CONF['wwwroot'] . $site->CONF['js_path'];
    ?>
/edit_popup.js"></script>
		<script type="text/javascript" src="<?php 
    echo $site->CONF['wwwroot'] . $site->CONF['js_path'];
    ?>
/jquery.js"></script>
		<script type="text/javascript" src="<?php 
    echo $site->CONF['wwwroot'] . $site->CONF['js_path'];
    ?>
/datepicker.js"></script>
		<script type="text/javascript" src="<?php 
    echo $site->CONF['wwwroot'];
    ?>
/common.js.php"></script>
		
		<script type="text/javascript">
			var isIE = navigator.appVersion.match(/MSIE/); // assume gecko on false
			
			window.onload = function ()
			{
				var title = document.getElementById('pealkiri');
				
				resizeWindow();
				
				var advanced_panel_state = document.getElementById('advanced_panel_state');
				if(advanced_panel_state.value == 1)
				{
					togglePanel('advanced');
				}
				
				this.focus();
				title.focus();
			}
			
			function resizeWindow()
			{
				resizeWindowTo($('#size_wrapper').width(), $('#size_wrapper').height());
			}
			
			
			function chooseSection()
			{
				explorer_window = openpopup('explorer.php?objekt_id=home&editor=1&swk_setup=parent_selection&remove_objects=<?php 
    echo $site->fdat['id'];
    ?>
&pre_selected=' + document.getElementById('rubriik').value, 'cms_explorer', '800','600');
			}
			
			function updateSection(sections)
			{
				explorer_window.close();
				var section_name = document.getElementById('section_name');
				var section_id = document.getElementById('rubriik');
				var trail_path= new Array();

					for(var j = 0; j < sections[0].trail.length; j++){
						trail_path[j] = sections[0].trail[j].pealkiri;
					}

				section_name.innerHTML = '<a href="javascript:chooseSection();">' + trail_path.join("->") + '</a>';
				section_id.value = sections[0].objekt_id;
			}

			function editAlias()
			{
				var alias_placeholder = document.getElementById('alias_placeholder');
				var alias_value = document.getElementById('alias_value');
				
				alias_placeholder.innerHTML = '<input type="text" id="alias" value="' + alias_value.value + '" onblur="saveAlias();">';
				
		    	resizeWindow();
		    	
				var alias = document.getElementById('alias');
				alias.focus();
			}
			
			function saveAlias()
			{
				var alias_placeholder = document.getElementById('alias_placeholder');
				var alias_value = document.getElementById('alias_value');
				var alias = document.getElementById('alias');
				
				if(alias_value.value != alias.value)
				{
					$.ajax({
					    url: 'ajax_response.php?rand=' + Math.random(9999),
					    data: {op: 'generate_alias', string: alias.value, language_id: '<?php 
    echo $keel;
    ?>
'},
					    type: 'POST',
					    dataType: 'json',
					    timeout: 1000,
					    error: function()
					    {
							alias_placeholder.innerHTML = '<a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + (alias_value.value.length > 30 ? alias_value.value.substring(0, 30) + '...' : alias_value.value) + '</a>';
					    },
					    success: function(response)
					    {
					    	if(response.alias)
					    	{
								alias_value.value = response.alias;
								alias_placeholder.innerHTML = '<a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + (alias_value.value.length > 30 ? alias_value.value.substring(0, 30) + '...' : alias_value.value) + '</a>';
					    	}
					    	else
					    	{
								alias_value.value = '';
								<?php 
    if ($objekt->objekt_id) {
        ?>
								alias_placeholder.innerHTML = '<a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + '<?php 
        echo $objekt->objekt_id;
        ?>
' + '</a>';
								<?php 
    } else {
        ?>
						    	alias_placeholder.innerHTML = '<input type="text" id="alias" value="" onblur="saveAlias();">';
								<?php 
    }
    ?>
					    	}
							
					    	resizeWindow();
					    }
					});
				}
				else
				{
					if(!alias.value)
					{
						alias_value.value = '';
						<?php 
    if ($objekt->objekt_id) {
        ?>
						alias_placeholder.innerHTML = '<a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + '<?php 
        echo $objekt->objekt_id;
        ?>
' + '</a>';
						<?php 
    } else {
        ?>
				    	alias_placeholder.innerHTML = '<input type="text" id="alias" value="" onblur="saveAlias();">';
						<?php 
    }
    ?>
					}
					else
					{
						alias_placeholder.innerHTML = '<a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + (alias_value.value.length > 30 ? alias_value.value.substring(0, 30) + '...' : alias_value.value) + '</a>';
					}
			    	
					resizeWindow();
				}
			}
			
			function createAlias()
			{
				var alias_value = document.getElementById('alias_value');
				var title = document.getElementById('pealkiri')
				
				if(0 || (!alias_value && title.value))
				{
					$.ajax({
					    url: 'ajax_response.php?rand=' + Math.random(9999),
					    data: {op: 'generate_alias', string: title.value, language_id: '<?php 
    echo $keel;
    ?>
'},
					    type: 'POST',
					    dataType: 'json',
					    timeout: 1000,
					    error: function()
					    {
					    },
					    success: function(response)
					    {
					    	var alias_cell = document.getElementById('alias_cell');
					    	alias_cell.className = 'alias';
					    	if(response.alias)
					    	{
						    	alias_cell.innerHTML = '<input type="hidden" name="friendly_url" id="alias_value" value="' + response.alias + '"><?php 
    echo $parent_href;
    ?>
<span id="alias_placeholder"><a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + (response.alias.length > 30 ? response.alias.substring(0, 30) + '...' : response.alias) + '</a></span>';
					    	}
					    	else
					    	{
						    	alias_cell.innerHTML = '<input type="hidden" name="friendly_url" id="alias_value" value=""><?php 
    echo $parent_href;
    ?>
<span id="alias_placeholder"><input type="text" id="alias" value="" onblur="saveAlias();"></span>';
					    	}
					    	
					    	var alias_row = document.getElementById('alias_row');
					    	alias_row.style.display = (isIE ? 'block' : 'table-row');

					    	resizeWindow();
					    }
					});			
				}
			}
			
			function saveForm(op2)
			{
				var form = document.getElementById('editForm');
				
				var title = document.getElementById('pealkiri');
				
				if(title.value.length == 0)
				{
					alert('<?php 
    echo $site->sys_sona(array('sona' => 'please_fill_in_the_title!', 'tyyp' => 'admin'));
    ?>
');
					return;
				}
				
				var alias_value = document.getElementById('alias_value');
				var alias = document.getElementById('alias');
				
				if((title.value && !alias_value) || (alias && alias_value && alias.value != alias_value.value))
				{
					$.ajax({
					    url: 'ajax_response.php?rand=' + Math.random(9999),
					    data: {op: 'generate_alias', string: title.value, language_id: '<?php 
    echo $keel;
    ?>
'},
					    type: 'POST',
					    dataType: 'json',
					    timeout: 1000,
					    error: function()
					    {
					    	var form = document.getElementById('editForm');
			 				
					    	form.op2.value = op2;
			 				form.submit();
					    },
					    success: function(response)
					    {
					    	var alias_value = document.getElementById('alias_value');
					    	
					    	if(!alias_value && response.alias)
					    	{
						    	var alias_cell = document.getElementById('alias_cell');
						    	alias_cell.innerHTML = '<input type="hidden" name="friendly_url" id="alias_value" value="' + response.alias + '"><?php 
    echo $parent_href;
    ?>
<span id="alias_placeholder"><a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + (response.alias.length > 30 ? response.alias.substring(0, 30) + '...' : response.alias) + '</a></span>';
					    	}
							
					    	var form = document.getElementById('editForm');
			 				
					    	form.op2.value = op2;
			 				form.submit();
					    }
					});
				}
				else
				{
	 				form.op2.value = op2;
	 				form.submit();
				}
			}
		</script>
	</head>
	
	<body>
		
		<? if ($site->fdat['op']=='edit') {?>
			<iframe src="checkin.php?objekt_id=<?php 
    echo $objekt->objekt_id;
    ?>
" style="width: 0; height: 0; display: none; visibility: hidden;"></iframe>
		<? } ?>
		
		<form action="edit.php" name="editForm" id="editForm" method="POST"  enctype="multipart/form-data">
		
		<input type="hidden" name="tab" value="<?php 
    echo $site->fdat['tab'];
    ?>
" />
		<input type="hidden" id="op" name="op" value="<?php 
    echo htmlspecialchars($site->fdat['op']);
    ?>
" />
		<input type="hidden" id="op2" name="op2" value="" />
		<input type="hidden" id="refresh" name="refresh" value="0" />
		
		<input type="hidden" name="tyyp_id" value="<?php 
    echo $tyyp['tyyp_id'];
    ?>
" />
		<input type="hidden" name="tyyp" value="<?php 
    echo $tyyp['klass'];
    ?>
" />
		
		<input type="hidden" name="pearubriik" value="<?php 
    echo $pearubriik;
    ?>
" />
		<input type="hidden" name="id" value="<?php 
    echo $site->fdat['id'];
    ?>
" />
		<input type="hidden" name="parent_id" value="<?php 
    echo $site->fdat['parent_id'];
    ?>
" />
		<input type="hidden" name="previous_id" value="<?php 
    echo $site->fdat['previous_id'];
    ?>
" />
		<input type="hidden" name="keel" value="<?php 
    echo $keel;
    ?>
" />
		<input type="hidden" name="on_pealkiri" value="1" />
		
        <input type="hidden" name="sorting" value="<?php 
    echo $site->fdat['sorting'];
    ?>
">

        <input type="hidden" name="extension_path" value="<?php 
    echo $site->fdat['extension_path'];
    ?>
" />
		
		<input type="hidden" name="opener_location" value="" />
		<input type="hidden" name="publish" value="<?php 
    echo $site->fdat['publish'] ? $site->fdat['publish'] : $objekt->all['on_avaldatud'];
    ?>
" />

		<input name="permanent_parent_id" type="hidden" value="<?php 
    echo $objekt->parent_id;
    ?>
" />
		<input name="sys_alias" type="hidden" value="<?php 
    echo $site->fdat['sys_alias'] ? $site->fdat['sys_alias'] : $objekt->all['sys_alias'];
    ?>
" />
		
		<input name="advanced_panel_state" id="advanced_panel_state" type="hidden" value="<?php 
    echo $site->fdat['advanced_panel_state'] ? htmlspecialchars($site->fdat['advanced_panel_state']) : 0;
    ?>
" />
		
		<div id="size_wrapper" class="section_editor">
		
		<div id="main_container">
			<?php 
    ########### Tabs  ########
    ?>
			<div id="tab_container">
				<a href="javascript:void(0);" class="selected"><?php 
    echo $site->sys_sona(array('sona' => 'tyyp_rubriik', 'tyyp' => 'System'));
    ?>
</a>
				<?php 
    if ($objekt->objekt_id) {
        ?>
					<a href="<?php 
        echo $site->self . '?tab=seo&id=' . $site->fdat['id'] . '&keel=' . $keel . '&op=' . $site->fdat['op'];
        ?>
" onclick="resizeDocumentHeightTo(430);"><?php 
        echo $site->sys_sona(array('sona' => 'meta-info', 'tyyp' => 'admin'));
        ?>
</a>
					<?php 
    } else {
        ?>
					<a href="javascript:void(0);"><?php 
        echo $site->sys_sona(array('sona' => 'meta-info', 'tyyp' => 'admin'));
        ?>
</a>
				<?php 
    }
    ?>
				<?php 
    if ($objekt->objekt_id) {
        ?>
					<a href="<?php 
        echo $site->self . '?tab=permissions&id=' . $site->fdat['id'] . '&keel=' . $keel . '&op=' . $site->fdat['op'];
        ?>
" onclick="resizeDocumentHeightTo(430);"><?php 
        echo $site->sys_sona(array('sona' => 'permissions', 'tyyp' => 'admin'));
        ?>
</a>
					<?php 
    } else {
        ?>
					<a href="javascript:void(0);"><?php 
        echo $site->sys_sona(array('sona' => 'permissions', 'tyyp' => 'admin'));
        ?>
</a>
				<?php 
    }
    ?>
			</div>
			
			<div id="content_container">
		
				<table cellpadding="0" cellspacing="0" class="form_row">
					<tr>
						<td class="label"><label><?php 
    echo $site->sys_sona(array('sona' => 'Pealkiri', 'tyyp' => 'editor'));
    ?>
:</label></td>
						<td class="input"><input type="text" class="text" name="pealkiri" id="pealkiri" value="<?php 
    echo htmlspecialchars($objekt->all['pealkiri']);
    ?>
" onblur="createAlias();" /></td>
					</tr>
					<?php 
    if (($objekt->objekt_id || isset($objekt->all['friendly_url'])) && !($objekt->all['sys_alias'] == 'trash' || $objekt->all['sys_alias'] == 'system' || $objekt->all['sys_alias'] == 'gallup_arhiiv')) {
        ?>
					<tr>
						<td class="label">&nbsp;</td>
						<td class="input"><input type="hidden" id="alias_value" name="friendly_url" name="friendly_url" value="<?php 
        echo htmlspecialchars($objekt->all['friendly_url']);
        ?>
" /><?php 
        echo $parent_href;
        ?>
<span id="alias_placeholder"><a href="javascript:void(0);" onclick="editAlias();" id="alias_link"><?php 
        echo $objekt->all['friendly_url'] ? strlen(htmlspecialchars($objekt->all['friendly_url'])) > 30 ? substr(htmlspecialchars($objekt->all['friendly_url']), 0, 30) . '...' : htmlspecialchars($objekt->all['friendly_url']) : $objekt->objekt_id;
        ?>
</a></span></td>
					</tr>
					<?php 
    } else {
        ?>
					<tr id="alias_row">
						<td class="label">&nbsp;</td>
						<td class="input" id="alias_cell"></td>
					</tr>
					<?php 
    }
    ?>
					<tr>
						<td class="label"><label><?php 
    echo $site->sys_sona(array('sona' => 'content template', 'tyyp' => 'editor'));
    ?>
:</label></td>
						<td class="input"><select class="select" id="template_select" name="ttyyp_id" onchange="refreshForm();"><option value="0"><?php 
    echo $site->sys_sona(array('sona' => 'default', 'tyyp' => 'admin'));
    ?>
 (<?php 
    echo $default_content_template['name'];
    ?>
)</option>
						<?php 
    foreach ($content_templates as $template_group_name => $templates_group) {
        ?>
							<optgroup label="<?php 
        echo $template_group_name;
        ?>
">
						<?php 
        foreach ($templates_group as $template_id => $template) {
            ?>
						<?php 
            if ($objekt->all['ttyyp_id'] == $template_id) {
                $ttyyp = $template;
            }
            ?>
								<option value="<?php 
            echo $template_id;
            ?>
"<?php 
            echo $objekt->all['ttyyp_id'] == $template_id ? ' selected="selected" style="color: #a7a6aa;"' : '';
            ?>
><?php 
            echo $template['nimi'];
            ?>
</option>
						<?php 
        }
        ?>
							</optgroup>
						<?php 
    }
    ?>
						</select></td>
					</tr>
					<?php 
    ########### publishing  ########
    ?>
					<tr>
						<td class="label"><?php 
    echo $site->sys_sona(array('sona' => 'visible_to_visitors', 'tyyp' => 'editor'));
    ?>
</td>
						<td><input type="radio" name="publish" id="object_published" value="1"<?php 
    echo $site->fdat['publish'] || $objekt->all['on_avaldatud'] ? ' checked' : '';
    ?>
> <label for="object_published"><?php 
    echo $site->sys_sona(array('sona' => 'published', 'tyyp' => 'editor'));
    ?>
</label>	<input type="radio" name="publish" id="object_unpublished" value="0"<?php 
    echo $site->fdat['publish'] == 0 && $objekt->all['on_avaldatud'] == 0 ? ' checked' : '';
    ?>
> <label for="object_unpublished"><?php 
    echo $site->sys_sona(array('sona' => 'unpublished', 'tyyp' => 'editor'));
    ?>
</label></td>
					</tr>
				</table>
				
				<br />
				
				<?php 
    ########### advanced  ########
    ?>
				<div class="panel_toggler" onclick="togglePanel('advanced');">
					<a href="javascript:void(0);"><?php 
    echo $site->sys_sona(array('sona' => 'Advanced', 'tyyp' => 'editor'));
    ?>
 <span id="advanced_panel_link_state">&raquo;</span></a>
				</div>
				
				<div id="advanced_panel" class="panel">
					
					<?php 
    ########### parent section  ########
    ?>
					<?php 
    if ($section_name) {
        ?>
					<table cellpadding="0" cellspacing="0" class="form_row">
						<tr>
							<td class="label"><label><?php 
        echo $site->sys_sona(array('sona' => 'Rubriigid', 'tyyp' => 'editor'));
        ?>
:</label></td>
							<td class="input">
								<table cellpadding="0" cellspacing="0" class="cf_container">
									<tr>
										<th><input type="hidden" name="rubriik[]" id="rubriik" value="<?php 
        echo $parent ? $parent->objekt_id : 0;
        ?>
"><span id="section_name"><a href="javascript:chooseSection();"><?php 
        echo $section_name;
        ?>
</a></span></th>
										<td><a href="javascript:chooseSection();">..</a></td>
									</tr>
								</table>
							</td>
						</tr>
					</table>
					<?php 
    }
    ?>
					
					<?php 
    ########### page template  ########
    ?>
					<table cellpadding="0" cellspacing="0" class="form_row">
						<tr>
							<td class="label"><label><?php 
    echo $site->sys_sona(array('sona' => 'page template', 'tyyp' => 'editor'));
    ?>
:</label></td>
							<td class="input"><select class="select" name="page_ttyyp_id"><option value="0"><?php 
    echo $site->sys_sona(array('sona' => 'default', 'tyyp' => 'admin'));
    ?>
 (<?php 
    echo $default_page_template['name'];
    ?>
)</option>
							<?php 
    foreach ($page_templates as $template_group_name => $templates_group) {
        ?>
								<optgroup label="<?php 
        echo $template_group_name;
        ?>
">
							<?php 
        foreach ($templates_group as $template_id => $template) {
            ?>
									<option value="<?php 
            echo $template_id;
            ?>
"<?php 
            echo $objekt->all['page_ttyyp_id'] == $template_id ? ' selected="selected" style="color: #a7a6aa;"' : '';
            ?>
><?php 
            echo $template['nimi'];
            ?>
</option>
							<?php 
        }
        ?>
								</optgroup>
							<?php 
    }
    ?>
							</select></td>
						</tr>
					</table>
					
					<?php 
    ########### hiding in menu and mailinglist  ########
    ?>
					<table cellpadding="0" cellspacing="0" class="form_row">
						<tr>
							<td class="label">&nbsp;</td>
							<td><input type="checkbox" class="checkbox" id="hide_in" name="is_hided_in_menu" value="1"<?php 
    echo $objekt->all['is_hided_in_menu'] ? ' checked="checked"' : '';
    ?>
 /></td>
							<td width="145"><label for="hide_in"><?php 
    echo $site->sys_sona(array('sona' => 'Hide in menu', 'tyyp' => 'editor'));
    ?>
</label></td>
							<td><input type="checkbox" class="checkbox" id="add_mailinglist" name="on_meilinglist" value="1"<?php 
    echo $objekt->all['on_meilinglist'] ? ' checked="checked"' : '';
    ?>
 /></td>
							<td><label for="add_mailinglist"><?php 
    echo $site->sys_sona(array('sona' => 'On meilinglist', 'tyyp' => 'editor'));
    ?>
</label></td>
						</tr>
					</table>
					
					<table cellpadding="0" cellspacing="0" class="form_row">
						<tr>
							<td class="label">&nbsp;</td>
							<td><label><?php 
    echo $site->sys_sona(array('sona' => 'Avaldatud', 'tyyp' => 'editor'));
    ?>
:</label></td>
							<td><input type="text" id="publish_start" name="avaldamise_algus" maxlength="16" class="text_date" value="<?php 
    echo $publish_start;
    ?>
" /></td>
							<td><a href="javascript:init_datepicker('publish_start', 'publish_start', 'publish_end');"><img src="<?php 
    echo $site->CONF['wwwroot'] . $site->CONF['styles_path'];
    ?>
/gfx/calendar/cal.gif" width="16" height="15" title="Choose from calendar" alt="Choose from calendar" /></a></td>
							<td><label><?php 
    echo $site->sys_sona(array('sona' => 'Kuni', 'tyyp' => 'editor'));
    ?>
:</label></td>
							<td><input type="text" id="publish_end" name="avaldamise_lopp" maxlength="16" class="text_date" value="<?php 
    echo $publish_end;
    ?>
" /></td>
							<td><a href="javascript:init_datepicker('publish_end', 'publish_start', 'publish_end');"><img src="<?php 
    echo $site->CONF['wwwroot'] . $site->CONF['styles_path'];
    ?>
/gfx/calendar/cal.gif" width="16" height="15" title="Choose from calendar" alt="Choose from calendar" /></a></td>
						</tr>
					</table>
					
					<?########### ONLY FOR SAURUS 3 BUILT-IN TEMPLATES: subarticles +  Add print icon  ########?>
					<?if(($objekt || $site->fdat['refresh']) && $ttyyp['ttyyp_id'] > 0 && $ttyyp['ttyyp_id'] < 1000) { # if ver3 content template?>
					<table cellpadding="0" cellspacing="0" class="form_row">
			              <tr> 
							<td class="label">&nbsp;</td>
			
							<?########### subarticles  ########?>
			                <td><input type="checkbox" id="on_alamartiklid" name="on_alamartiklid"<?php 
    echo $objekt->all['on_alamartiklid'] ? ' checked="checked"' : '';
    ?>
 /></td>
			                <td width="145"><label for="on_alamartiklid"><?php 
    echo $site->sys_sona(array('sona' => 'Naita alamartiklid', 'tyyp' => 'editor'));
    ?>
</label></td>
			
							<?########### Add print icon  ########?>
			                <td><input type="checkbox" id="on_printlink" name="on_printlink"  value="1" <?php 
    echo $objekt->all['on_printlink'] ? ' checked="checked"' : '';
    ?>
 /></td>
			                <td><label for="on_printlink"><?php 
    echo $site->sys_sona(array('sona' => 'Naita prindi ikoon', 'tyyp' => 'editor'));
    ?>
</label></td>
			
						  </tr>
					</table>
					<?} # if ver3 content template?>
					<?php 
    if ($template_variable_html) {
        ?>
					<table cellpadding="0" cellspacing="0" class="form_row">
						<?php 
        echo $template_variable_html;
        ?>
					</table>
					<?php 
    }
    ?>
					
					<?php 
    ########### position  ########
    ?>
					<?php 
    if ($site->CONF['allow_change_position']) {
        ?>
					<table cellpadding="0" cellspacing="0" class="form_row">
						<tr>
							<td class="label"><label><?php 
        echo $site->sys_sona(array('sona' => 'Position', 'tyyp' => 'editor'));
        ?>
:</label></td>
							<td><input type="text" maxlength="5" class="text_position" name="kesk" value="<?php 
        echo $site->fdat['op'] == 'edit' ? $objekt->all['kesk'] : $site->fdat['kesk'];
        ?>
" /></td>
						</tr>
					</table>
					<?php 
    } else {
        ?>
						<input type="hidden" name="kesk" value="<?php 
        echo $site->fdat['op'] == 'edit' ? $objekt->all['kesk'] : $site->fdat['kesk'];
        ?>
" />
					<?php 
    }
    ?>
					
				</div>
			</div>
			
		</div>
		
		<div id="button_container">
			
			<table width="100%" cellspacing="0" cellpadding="0">
				<tbody>
					<tr>
						<td align="left">
							<input type="button" class="button" value="<?php 
    echo $site->sys_sona(array('sona' => 'Apply', 'tyyp' => 'editor'));
    ?>
" onclick="saveForm('save');" />
						</td>
						<td align="right">
							<input type="button" class="button" value="&nbsp;&nbsp;&nbsp;&nbsp;<?php 
    echo $site->sys_sona(array('sona' => 'save_and_close', 'tyyp' => 'editor'));
    ?>
&nbsp;&nbsp;&nbsp;&nbsp;" onclick="saveForm('saveclose');" />
							<input type="button" class="button" value="<?php 
    echo $site->sys_sona(array('sona' => 'Close', 'tyyp' => 'editor'));
    ?>
" onclick="window.close();" />		
						</td>
					</tr>
				</tr>
				</tbody>
			</table>
			
			
			
			
		</div>
		
		</div> <!-- / size_wrapper -->
		
		</form>
	</body>
</html>

<?php 
}
/**
 * edit_artikkel.php
 *
 */

function edit_objekt()
{
	function print_profiles()
	{
		global $site, $objekt;

		$sql = $site->db->prepare("SELECT profile_id AS id, source_table AS parent, name FROM object_profiles WHERE source_table=? ORDER BY name",'obj_artikkel');
		$sth = new SQL($sql);

		# get object profile
		if($objekt->all['profile_id']) {
			$profile_def = $site->get_profile(array("id"=>$objekt->all['profile_id']));
			$site->fdat['profile_id'] = $profile_def['profile_id'];
		}
		# if still not found then use default profile for this class
		if(!$profile_def['profile_id'] && !$site->fdat['profile_id']) {

			$site->fdat['profile_id'] = $site->get_default_profile_id(array("source_table" => 'obj_artikkel'));
			$profile_def = $site->get_profile(array("id"=>$site->fdat['profile_id']));
		}
		?>

<fieldset>
	<legend>
		<select onchange="changeProfile(this)" name="profile_id">
		<?php
		$all_profiles_hash = array();
		while ($profile_data = $sth->fetch()){
			$all_profiles_hash[] = $profile_data['id'];
			print "<option value='".$profile_data['id']."' ".($profile_data['id']==$site->fdat['profile_id'] ? '  selected':'').">".$site->sys_sona(array(sona => $profile_data['name'], tyyp=>"custom"))."</option>";
		} ?>
		</select>
	</legend>

	<?php foreach($all_profiles_hash as $profile_id) {	?>

	<div id="profile_<?= $profile_id ?>" style="display: <?=($site->fdat['profile_id'] == $profile_id ? 'block' : 'none');?>;">
		<table cellpadding="0" cellspacing="0">
	<?php
		$profile_def = $site->get_profile(array("id"=>$profile_id));
		$profile_fields = unserialize($profile_def['data']);

		# if profile fields exist
		if(is_array($profile_fields) && sizeof($profile_fields)>0){

			## add suffix for each field, to get unique id-s
			foreach($profile_fields as $key=>$tmp_prof){
				$profile_fields[$key]['html_fieldname'] = $profile_fields[$key]['name']."_".$profile_id;

				# field can be INPUT or READ-ONLY value - this info may be passed from triggers file "actions.inc.php", using "$site->fdat" array
				$profile_fields[$key]['is_readonly'] = $site->fdat['is_readonly_'.$key];
			}
			#printr($profile_fields);

			###################
			# print profile fields rows
			print_profile_fields(array(
				'profile_fields' => $profile_fields,
				'field_values' => $objekt->all,
			));

		} # if profile fields exist

	?>
		</table>
	</div>

	<?php } //foreach ?>

</fieldset>

<fieldset>
	<legend><?=$site->sys_sona(array('sona' => 'visible_to_visitors', 'tyyp' => 'editor'))?></legend>
	<input type="radio" name="publish" id="object_published" value="1"<?=($site->fdat['publish'] || $objekt->all['on_avaldatud'] ? ' checked' : '')?>> <label for="object_published"><?=$site->sys_sona(array('sona' => 'published', 'tyyp' => 'editor'))?></label><br>
	<input type="radio" name="publish" id="object_unpublished" value="0"<?=($site->fdat['publish'] == 0 && $objekt->all['on_avaldatud'] == 0 ? ' checked' : '')?>> <label for="object_unpublished"><?=$site->sys_sona(array('sona' => 'unpublished', 'tyyp' => 'editor'))?></label><br>
</fieldset>

<fieldset>
	<?php ####### dont show checkbox "Headline is visible" if config variable "killheadlineisvisible" is true in file config.php
	if($site->CONF['killheadlineisvisible']) { ?>

	<input type="hidden" id="on_pealkiri" name="on_pealkiri" value="<?=($site->fdat['op'] == 'new' ? 1 : $objekt->all['on_pealkiri'])?>">

	<?php } else { # by default: show it ?>
	<div>
		<input type="checkbox" id="on_pealkiri" name="on_pealkiri" value="1" <?=($site->fdat['op'] == 'new') ? 'checked' : ($objekt->all['on_pealkiri'] ? 'checked' : null)?>>
		<label for="on_pealkiri"><?=$site->sys_sona(array(sona => 'Pealkiri on nahtav', tyyp => 'editor'));?></label>
	</div>
	<?php } ?>
	<div>
		<input type="checkbox" name="on_foorum" id="on_foorum" value="1" <?=($objekt->all['on_foorum'] || ($site->fdat['op'] == 'new' && ($site->CONF['default_comments'] || $site->fdat['allow_comments'])) ? 'checked' : null)?>>
		<label for="on_foorum"><?=$site->sys_sona(array(sona => "Foorum lubatud", tyyp=>"editor"))?></label>
	</div>

	<?php if ($site->CONF['enable_mailing_list']) {  ## Bug #2590
	## fuzzy logic: if editor checks here checkbox "is mailinglist",
	# then field "on_saadetud" is set to "0" and that means article is included in next mailinglist routine.
	?>
	<div>
		  <input type="checkbox" name="on_saadetud" id="on_saadetud" value="1" <?=($objekt->all['on_saadetud'] ? null : "checked");?>>
		  <label for="on_saadetud"><?=$site->sys_sona(array(sona => 'On meilinglist', tyyp=>'editor'));?></label>
	</div>
	<?php } ?>

</fieldset>

<fieldset>
	<table cellpadding="1" cellspacing="1" border="0"  style="color: #999;">
		<?php if ($objekt->all['created_user_name']) { ?>
		<?php if ($site->CONF['allow_change_position']) { ?>
		<tr>
			<td><?=$site->sys_sona(array('sona' => 'position', 'tyyp' => 'Editor'));?>:</td>
			<td>
				<input type="text" name="kesk" value="<?=$objekt->all['kesk']?>" style="width: 40px; text-align: right;">
			</td>
		</tr>
		<?php } ?>
		<tr>
			<td><?=$site->sys_sona(array('sona' => 'object_created', 'tyyp' => 'Editor'));?>:</td>
			<td><?=date('d.m.Y H:i', strtotime($objekt->all['created_time']));?></td>
		</tr>
		<tr>
			<td></td>
			<td><?=$objekt->all['created_user_name'];?></td>
		</tr>
		<?php } ?>
		<?php if ($objekt->all['changed_user_name']) { ?>
		<tr>
			<td><?=$site->sys_sona(array('sona' => 'object_changed', 'tyyp' => 'Editor'));?>:</td>
			<td><?=date('d.m.Y H:i', strtotime($objekt->all['changed_time']));?></td>
		</tr>
		<tr>
			<td></td>
			<td><?=$objekt->all['changed_user_name'];?></td>
		</tr>
		<?php } ?>
	</table>
</fieldset>




	<?php
	} // end function print_profile()

	function print_sections()
	{
		global $site, $objekt, $class_path, $keel;

		$tmpkeel = $keel;
		if (!is_numeric($tmpkeel)){
			$sql = $site->db->prepare("SELECT keel FROM objekt WHERE objekt_id=?",  $site->fdat['parent_id']);
			$sth = new SQL($sql);
			$site->debug->msg($sth->debug->get_msgs());
			$tmpkeel = $sth->fetchsingle();
		}

	$sections = array($site->fdat['parent_id']);

	if ($objekt->objekt_id) {

		$sql = $site->db->prepare("SELECT parent_id FROM objekt_objekt WHERE objekt_id=?", $objekt->objekt_id);
		$result = new SQL ($sql);

		while ($data = $result->fetch('ASSOC'))
		{
			$sections[] = $data['parent_id'];
		}
	}

	if ($site->fdat['permanent_parent_id'] == '')
	{
		include_once($class_path.'rubloetelu.class.php');

		$all_sections = new RubLoetelu(array('keel' => $keel));
		$all_sections = $all_sections->get_loetelu();

		asort($all_sections);
	}
?>
<script type="text/javascript">
// the sections list
var all_sections = Array();

// for Mozilla the section list doesn't stretch dynamically so add this increment value to the containing elements height
var heightIncrement = 10;

function createSectionNodeSet(sectionNode, section_id, section_name)
{
	var input = document.createElement('input');
	input.type = 'hidden';
	input.name = 'rubriik[]';
	input.value = section_id;

	sectionNode.appendChild(input);

	var buttons = document.createElement('div');
	buttons.id='button_' + section_id;

	if(sectionNode.parentNode)
	{
		for(var i = 0; i < sectionNode.parentNode.childNodes.length; i++) if(sectionNode.parentNode.childNodes[i].tagName == 'LI') break;

		if(sectionNode.id != sectionNode.parentNode.childNodes[i].id)
		{
			var del_button = document.createElement('a');
			del_button.href = "javascript:deleteSection('" + section_id +"');";
			del_button.innerHTML = '<img src="<?=$site->CONF['wwwroot'].$site->CONF['styles_path'];?>/gfx/editor/delete.gif">';
			buttons.appendChild(del_button);
		}
	}

	sectionNode.appendChild(buttons);

	var link = document.createElement('a');
	link.href = "javascript:opopup('"+ section_id +"');";
	link.innerHTML = section_name;

	sectionNode.appendChild(link);

	return sectionNode;
}
// add a new item to the section list

function opopup(section_id){
var pre_selected='';

if(section_id !=''){
	pre_selected = '&pre_selected=' + section_id;
	explorer_window = openpopup('explorer.php?objekt_id=home&editor=1&swk_setup=current_article_parent_selection' + pre_selected, 'cms_explorer', '800','600', 'auto');
}else{
	explorer_window = openpopup('explorer.php?objekt_id=home&editor=1&swk_setup=article_parent_selection', 'cms_explorer', '800','600', 'auto');
}


}


function addNewSection(node)
{

	explorer_window.close();
		for(var j = 0; j < node.length; j++){

			var error = false;
			for(var i = 0; i < all_sections.length; i++){
			/* no duplicates */
				if (all_sections[i] == node[j].objekt_id){
					//return;
					error = true;
				}else{

				}
			}
			if(!error){

				var trail_path= new Array();

					for(var z = 0; z < node[j].trail.length; z++){
						trail_path[z] = node[j].trail[z].pealkiri;
					}

				var sections = document.getElementById('sections');

				var item = document.createElement('li');
				item.id = 'section_' + node[j].objekt_id;
				sections.appendChild(item);
				item = createSectionNodeSet(item, node[j].objekt_id, trail_path.join("->"));
				var container = document.getElementById('sections_container');
				container.height = Number(container.height) + heightIncrement;

				all_sections[all_sections.length] = node[j].objekt_id;
				}




				for(var b = 0; b < all_sections.length; b++){
					var c = all_sections[b];
					var x = document.getElementById("button_" + c);

					x.style.visibility = "visible";

				}


		}


	return;

}
// /function addNewSection

function deleteSection(section_id)
{
	var section = document.getElementById('section_' + section_id);

	section.parentNode.removeChild(section);

	var container = document.getElementById('sections_container');
	//container.height = Number(container.height) - heightIncrement;

	// delete from duplicate checklist
	var new_all_sections =new Array();

	for(var i = 0; i < all_sections.length; i++){
		if (all_sections[i] == section_id){
			all_sections[i] = null;
		}else{

			new_all_sections.push(all_sections[i]);
		}
	}
all_sections=new_all_sections;

	var c = 0;
	var d = '';

	for(var b = 0; b < all_sections.length; b++){
		if (all_sections[b] != null){
			c++;
			d=all_sections[b];
		}
	}

	if(c == 1){
		document.getElementById('button_' + d).style.visibility = 'hidden';
	}

	return;
}
// /function deleteSection

function modifySection(node,section_id)
{

	explorer_window.close();
		for(var j = 0; j < node.length; j++){

			var error = false;
			for(var i = 0; i < all_sections.length; i++){
			/* no duplicates */
				if (all_sections[i] == node[j].objekt_id){
					//return;
					error = true;
				}else{

				}
			}
			if(!error){

				var trail_path= new Array();

					for(var z = 0; z < node[j].trail.length; z++){
						trail_path[z] = node[j].trail[z].pealkiri;
					}

				var section = document.getElementById('section_' + section_id);
				section.innerHTML = '';

				section = createSectionNodeSet(section, node[j].objekt_id, trail_path.join("->"));
				section.id = 'section_' + node[j].objekt_id;

					/* delete from duplicate checklist */
						for(var i = 0; i < all_sections.length; i++) if (all_sections[i] == section_id) all_sections[i] = null;
						all_sections[all_sections.length] = node[j].objekt_id;


				}




		}


	return;
}

// /function modifySection
</script>
<?
// setup for new section selection
$_SESSION['article_parent_selection']['callback'] = 'window.opener.addNewSection';
$_SESSION['article_parent_selection']['selectable'] = 2;
$_SESSION['article_parent_selection']['hide_language_selection'] = '1';
$_SESSION['article_parent_selection']['mem_classes'] = array('rubriik', ); //this sucks, really
$_SESSION['article_parent_selection']['db_fields'] = array('select_checkbox', 'objekt_id', 'pealkiri', );
$_SESSION['article_parent_selection']['display_fields'] = array('select_checkbox', 'pealkiri', );

// setup for current section change
$_SESSION['current_article_parent_selection']['callback'] = 'window.opener.modifySection';
$_SESSION['current_article_parent_selection']['selectable'] = 1;
$_SESSION['current_article_parent_selection']['hide_language_selection'] = '1';
$_SESSION['current_article_parent_selection']['mem_classes'] = array('rubriik', ); //this sucks, really
$_SESSION['current_article_parent_selection']['db_fields'] = array('select_checkbox', 'objekt_id', 'pealkiri', );
$_SESSION['current_article_parent_selection']['display_fields'] = array('select_checkbox', 'pealkiri', );
?>
		<div class="sections_header">
			<div>
				<a href="#" id="new_section" onClick="opopup(''); return false;"><?=$site->sys_sona(array(sona => "New", tyyp=>"editor"))?></a>
			</div>
			<?=$site->sys_sona(array(sona => "Rubriigid", tyyp=>"editor"))?>
		</div>
		<ul id="sections" class="sections">
		<?php

		$home_section = $site->alias(array('key'=>'rub_home_id', 'keel'=>$tmpkeel));
		$i = 0;
		foreach ($all_sections as $section_id => $section_name)
		{
			# Bug #2264: Uuele artiklile KAKS v�i rohkem eeldefineeritud parentit (triggers)
			if ($section_id != $home_section &&

			(in_array($section_id, $sections) || (is_array($site->fdat['parents_arr']) && in_array($section_id,$site->fdat['parents_arr'])))

			)
			{
			?>
			<script type="text/javascript">
				all_sections[all_sections.length] = <?=$section_id?>;
			</script>
<?if($i==0){$first_section=$section_id;}?>
			<li id="section_<?=$section_id;?>">
				<input type="hidden" name="rubriik[]" value="<?=$section_id;?>">
				<div id="button_<?=$section_id;?>"><a href="javascript:deleteSection('<?=$section_id;?>');"><img src="<?=$site->CONF['wwwroot'].$site->CONF['styles_path'];?>/gfx/editor/delete.gif"></a></div>
				<a href="javascript:opopup('<?=$section_id;?>');"><?=$section_name;?></a>
			</li>
			<?php
				$i++;
			}
		}
?>
		</ul>
		<?php if($i == 1){?>

			<script type="text/javascript">
					document.getElementById('button_<?=$first_section;?>').style.visibility = 'hidden';
			</script>
		<?}?>

	  <!-- /rubriigid -->
	  <?php
	} /* end function print_sections2() */


	global $site, $class_path, $objekt, $tyyp, $keel;

	include_once($class_path.'adminpage.inc.php');
	include_once($class_path.'SCMSEditor.php');
	include_once($class_path.'extension.class.php');

	$editor = new SCMSEditor('scms_article_editor') ;

	if($site->fdat['op'] == 'new')
	{
		$editor->Value = '';
	}
	else
	{
		$editor->Value = ($objekt->lyhi->get_text() ? $objekt->lyhi->get_text().'<hr class="scms_lead_body_separator" />' : '').($objekt->sisu->get_text() ? $objekt->sisu->get_text() : '');

		// bug #2388  Tagaside vormist eemaldada e-maili aadress, tagasiasendus
		if(preg_match_all('/<input(.*?)>/', $editor->Value, $matches))
		{
			$systemfields = array();
			foreach ($matches[0] as $match)
			{
				if(strpos($match,'type="hidden"') && strpos($match,'name="systemfield"')) $systemfields[] = $match;
			}
			foreach ($systemfields as $systemfield)
			{
				if(preg_match('/value="(.*?)\|\|\|(.*?)\|\|\|(.*?)\|\|\|/', $systemfield, $matches))
				{
					$sql = $site->db->prepare('select mail from allowed_mails where id = ?;', $matches[1]);
					$result = new SQL($sql);
					$mail = $result->fetchsingle();

					$editor->Value = str_replace('value="'.$matches[1].'|||', 'value="'.$mail.'|||', $editor->Value);
				}
			}
		}
		// /form allowed mails check/insert
	}

	$editor->Height = '100%';
	$editor->Width = '100%';
	$editor->ToolbarSet = '';

	$editor->BasePath = (empty($_SERVER['HTTPS']) ? 'http://': 'https://').$site->CONF['hostname'].$site->CONF['wwwroot'].$site->CONF['js_path'].'/fckeditor/';

	// create config array
	$Config['CustomConfigurationsPath'] = $editor->BasePath.'scms_config.js';
	$Config['SkinPath'] = $editor->BasePath.'editor/skins/scms/';
	$Config['ToolbarCanCollapse'] = false;

	$Config['SCMSFormName'] = $site->CONF['feedbackform_form_name'];
	$Config['SCMSFormAction'] = $site->CONF['feedbackform_action'];
	$Config['SCMSFormMethod'] = $site->CONF['feedbackform_method'];

	$Config['SCMSFormHiddenName'] = 'systemfield';
	$Config['SCMSFormHiddenString'] = $site->CONF["default_mail"].'|||index.php?id='.$site->alias(array('key'=>"error_page", 'keel'=>$keel )).'|||index.php?id='.$site->alias(array('key'=>"ok_page", 'keel'=>$keel )).'|||'.$site->CONF["subject"];

	$default_toolbar = 'SCMS_simple';
	if($_COOKIE['scms_toolbar'])
	{
		$default_toolbar = $_COOKIE['scms_toolbar'];
	}

	// load custom values for FCKeditor config
	foreach (get_extensions('DB', true) as $act_ext)
	{
		if(file_exists($act_ext['fullpath'].'/extension.config.php')) // assume this is the right one
		{
			$EXTENSION =& load_extension_config($act_ext);

			// set the toolbar, later TODO user based toolbars
			if($site->user->is_superuser)
			{
				if($EXTENSION['wysiwyg_config']['SuperUserToolbarSet'])
				{
					$editor->ToolbarSet = $EXTENSION['wysiwyg_config']['SuperUserToolbarSet'];
				}
				elseif($EXTENSION['wysiwyg_config']['DefaultToolbarSet'])
				{
					$editor->ToolbarSet = $EXTENSION['wysiwyg_config']['DefaultToolbarSet'];
				}
				else
				{
					$editor->ToolbarSet = $default_toolbar;
				}
			}
			else
			{
				$roles = array();
				$sql = 'select role_id, name from roles;';
				$result = new SQL($sql);
				while($row = $result->fetch('ASSOC')) {	$roles[$row[role_id]] = $row['name']; }

				foreach((array)$EXTENSION['wysiwyg_config']['ToolbarSets'] as $role => $set)
				{
					if($role)
					{
						$key = array_search($role, $roles);
						if($key !== null && in_array($key, $site->user->roles))
						{
							$editor->ToolbarSet = $set;
							break;
						}
					}
				}

				if(!$editor->ToolbarSet)
				{
					($EXTENSION['wysiwyg_config']['DefaultToolbarSet'] ? $editor->ToolbarSet = $EXTENSION['wysiwyg_config']['DefaultToolbarSet'] : $editor->ToolbarSet = $default_toolbar);
				}
			}
			// set the config
			if(is_array($EXTENSION['wysiwyg_config']['Config'])) $Config = array_merge($Config, $EXTENSION['wysiwyg_config']['Config']);
			break; // get only the first
		}
	}
	if(!$editor->ToolbarSet) $editor->ToolbarSet = $default_toolbar;

	$editor->Config = $Config;
	// somethings are not allowed to be overwritten
	$editor->Config['PluginsPath'] = $editor->BasePath.'editor/plugins/';
	$editor->Config['EditorAreaCSS'] = (empty($_SERVER['HTTPS']) ? 'http://' : 'https://').$site->CONF['hostname'].$site->CONF['wwwroot'].'/styles.php?with_wysiwyg=1';
	$editor->Config['CustomStyles'] = '';
	$editor->Config['StylesXmlPath'] = (empty($_SERVER['HTTPS']) ? 'http://' : 'https://').$site->CONF['hostname'].$site->CONF['wwwroot'].'/admin/fckstyles.php';

	$editor->Config['FormatOutput'] = false;
	$editor->Config['AutoDetectLanguage'] = false;
	$editor->Config['DefaultLanguage'] = substr($_SESSION['keel_admin']['locale'], 0, 2);
	$editor->Config['ProcessHTMLEntities'] = false;
	$editor->Config['Debug'] = false;
	//$editor->Config['FitWindow_autoFitToResize'] = true;
	$editor->Config['CurrentToolbar'] = $editor->ToolbarSet;

	//printr($editor->Config);
	//printr($editor->ToolbarSet);

	// setup for site linking
	$_SESSION['site_linking']['callback'] = 'window.opener.frames[0].site_linking';
	$_SESSION['site_linking']['selectable'] = 1;
	$_SESSION['site_linking']['mem_classes'] = array('rubriik', 'artikkel', ); //this sucks, really
	$_SESSION['site_linking']['db_fields'] = array('select_checkbox', 'objekt_id', 'pealkiri', 'klass',);
	$_SESSION['site_linking']['display_fields'] = array('select_checkbox', 'pealkiri', 'klass',);
	// /setup for site linking

	$parent = new Objekt(array('objekt_id' => $site->fdat['parent_id']));
	// to get the correct path to parent objects set use_alises on
	$site->CONF['use_aliases'] = 1;
	$parent_href = $parent->get_object_href();

	if($site->CONF['alias_trail_format'] == 0 || $parent->all['sys_alias'] == 'home' || $parent->all['sys_alias'] == 'trash' || $parent->all['sys_alias'] == 'system' || $parent->all['sys_alias'] == 'gallup_arhiiv') $parent_href = preg_replace('#'.preg_quote('/'.($parent->all['friendly_url'] ? $parent->all['friendly_url'] : $parent->objekt_id), '#').'/$#', '/', $parent_href);

	$parent_href = $site->CONF['hostname'].$parent_href;

	// setup file insert
	$_SESSION['scms_filemanager_settings']['scms_wysiwyg_insert_file'] = array(
		'select_mode' => 1, // 1 - select single file
		'action_text' => $site->sys_sona(array('sona' => 'fm_choose_file_into_article', 'tyyp' => 'editor')),
		'action_trigger' => $site->sys_sona(array('sona' => 'fm_insert_file_into_article', 'tyyp' => 'editor')),
		'callback' => 'window.opener.frames[0].SCMSImageFileInsert',
	);
?>
<html>

<head>

	<title><?=$site->title;?> <?=$site->cms_version;?></title>

	<meta http-equiv="Content-Type" content="text/html; charset=<?=($encoding ? $encoding : $site->encoding);?>">
	<meta http-equiv="Cache-Control" content="no-cache">
	<link rel="stylesheet" href="<?=$site->CONF['wwwroot'].$site->CONF['styles_path'].'/article_editor.css';?>" media="screen">

	<script type="text/javascript" src="<?=$site->CONF['wwwroot'].$site->CONF['js_path'];?>/yld.js"></script>
	<script type="text/javascript" src="<?=$site->CONF['wwwroot'].$site->CONF['js_path']?>/edit_popup.js"></script>
	<link rel="stylesheet" href="<?=$site->CONF['wwwroot'].$site->CONF['styles_path']?>/datepicker.css">
	<script type="text/javascript" src="<?=$site->CONF['wwwroot'].$site->CONF['js_path'] ?>/jquery.js"></script>
	<script type="text/javascript" src="<?=$site->CONF['wwwroot'].$site->CONF['js_path'] ?>/datepicker.js"></script>
	<script type="text/javascript" src="<?=$site->CONF['wwwroot'];?>/common.js.php"></script>

	<script type="text/javascript">
	function FCKeditor_OnComplete( editorInstance )
	{
		<?php if($objekt->objekt_id) { ?>
		var oSCMSEditor = FCKeditorAPI.GetInstance('scms_article_editor') ;
		oSCMSEditor.Focus();
		<?php } else { ?>
		document.frmEdit.pealkiri.focus();
		<?php } ?>
		window.moveTo((screen.width - 880) / 2, (screen.height - 660) / 2);
		window.resizeTo(880, 660);
	}

	function editAlias()
	{
		var alias_placeholder = document.getElementById('alias_placeholder');
		var alias_value = document.getElementById('alias_value');

		alias_placeholder.innerHTML = '<input type="text" id="alias" value="' + alias_value.value + '" onblur="saveAlias();">';

		var alias = document.getElementById('alias');
		alias.focus();
	}

	function saveAlias()
	{
		var alias_placeholder = document.getElementById('alias_placeholder');
		var alias_value = document.getElementById('alias_value');
		var alias = document.getElementById('alias');

		if(alias_value.value != alias.value)
		{
			$.ajax({
			    url: 'ajax_response.php?rand=' + Math.random(9999),
			    data: {op: 'generate_alias', string: alias.value, language_id: '<?=$keel;?>'},
			    type: 'POST',
			    dataType: 'json',
			    timeout: 1000,
			    error: function()
			    {
					alias_placeholder.innerHTML = '<a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + (alias_value.value.length > 30 ? alias_value.value.substring(0, 30) + '...' : alias_value.value) + '</a>';
			    },
			    success: function(response)
			    {
			    	if(response.alias)
			    	{
						alias_value.value = response.alias;
						alias_placeholder.innerHTML = '<a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + (alias_value.value.length > 30 ? alias_value.value.substring(0, 30) + '...' : alias_value.value) + '</a>';
			    	}
			    	else
			    	{
						alias_value.value = '';
						<?php if($objekt->objekt_id) { ?>
						alias_placeholder.innerHTML = '<a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + '<?=$objekt->objekt_id;?>' + '</a>';
						<?php } else { ?>
				    	alias_placeholder.innerHTML = '<input type="text" id="alias" value="" onblur="saveAlias();">';
						<?php } ?>
			    	}
			    }
			});
		}
		else
		{
			if(!alias.value)
			{
				alias_value.value = '';
				<?php if($objekt->objekt_id) { ?>
				alias_placeholder.innerHTML = '<a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + '<?=$objekt->objekt_id;?>' + '</a>';
				<?php } else { ?>
		    	alias_placeholder.innerHTML = '<input type="text" id="alias" value="" onblur="saveAlias();">';
				<?php } ?>
			}
			else
			{
				alias_placeholder.innerHTML = '<a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + (alias_value.value.length > 30 ? alias_value.value.substring(0, 30) + '...' : alias_value.value) + '</a>';
			}
		}

	}

	function createAlias()
	{
		var alias_value = document.getElementById('alias_value');
		var title = document.getElementById('pealkiri')

		if(0 || (!alias_value && title.value))
		{
			$.ajax({
			    url: 'ajax_response.php?rand=' + Math.random(9999),
			    data: {op: 'generate_alias', string: title.value, language_id: '<?=$keel;?>'},
			    type: 'POST',
			    dataType: 'json',
			    timeout: 1000,
			    error: function()
			    {
			    },
			    success: function(response)
			    {

			    	var alias_cell = document.getElementById('alias_cell');
			    	alias_cell.className = 'alias';
			    	if(response.alias)
			    	{
				    	alias_cell.innerHTML = '<input type="hidden" name="friendly_url" id="alias_value" value="' + response.alias + '"><?=$parent_href;?><span id="alias_placeholder"><a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + (response.alias.length > 30 ? response.alias.substring(0, 30) + '...' : response.alias) + '</a></span>';
			    	}
			    	else
			    	{
				    	alias_cell.innerHTML = '<input type="hidden" name="friendly_url" id="alias_value" value=""><?=$parent_href;?><span id="alias_placeholder"><input type="text" id="alias" value="" onblur="saveAlias();"></span>';
			    	}
			    }
			});
		}
	}

	function saveForm(op2)
	{
		var form = document.getElementById('frmEdit');

		var title = document.getElementById('pealkiri')
		var alias_value = document.getElementById('alias_value');
		var alias = document.getElementById('alias');

		if((title.value && !alias_value) || (alias && alias_value && alias.value != alias_value.value))
		{
			$.ajax({
			    url: 'ajax_response.php?rand=' + Math.random(9999),
			    data: {op: 'generate_alias', string: title.value, language_id: '<?=$keel;?>'},
			    type: 'POST',
			    dataType: 'json',
			    timeout: 1000,
			    error: function()
			    {
			    	var form = document.getElementById('frmEdit');

			    	form.op2.value = op2;
	 				form.submit();
			    },
			    success: function(response)
			    {
			    	var alias_value = document.getElementById('alias_value');

			    	if(!alias_value && response.alias)
			    	{
				    	var alias_cell = document.getElementById('alias_cell');
				    	alias_cell.className = 'alias';
				    	alias_cell.innerHTML = '<input type="hidden" name="friendly_url" id="alias_value" value="' + response.alias + '"><?=$parent_href;?><span id="alias_placeholder"><a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + (response.alias.length > 30 ? response.alias.substring(0, 30) + '...' : response.alias) + '</a></span>';
			    	}

			    	var form = document.getElementById('frmEdit');

			    	form.op2.value = op2;
	 				form.submit();
			    }
			});
		}
		else
		{
				form.op2.value = op2;
				form.submit();
		}
	}
	</script>

	<?php if ($editor->browser() == 'Gecko') { ?>
	<style type="text/css">
		table.layout td.editor div {
			height: 100%;
		}
	</style>
	<?php } ?>

</head>

<body id="scms_editor_popup">

	<form action="edit.php" method="POST" name="frmEdit" id="frmEdit" class="article_submit_form">
		<?php /* hidden form stuff */ ?>
				<input type=hidden name="op" value="<?=$site->fdat['op'];?>">
				<input type=hidden name="op2" id="op2" value="saveclose">
				<input type=hidden name="refresh" value="0">

				<input type="hidden" name="tyyp_id" value="<?=$tyyp['tyyp_id'];?>">
				<input type="hidden" name="tyyp" value="<?=$tyyp['klass'];?>">
				<input type="hidden" name="sys_alias" value="<?=$site->fdat['sys_alias'];?>">

				<input type="hidden" name="id" value="<?=$site->fdat['id'];?>">
				<input type="hidden" name="kesk" value="<?=$site->fdat['kesk'];?>">
				<input type="hidden" name="parent_id" value="<?=$site->fdat['parent_id'];?>">
				<input type="hidden" name="previous_id" value="<?=$site->fdat['previous_id'];?>">
				<input type="hidden" name="keel" value="<?=$keel;?>">
				<input type="hidden" name="baseurl" value="<?=(empty($_SERVER['HTTPS']) ? 'http://': 'https://').$site->CONF['hostname'].$site->CONF['wwwroot'];?>/">
				<input type="hidden" name="wwwroot" value="<?=$site->CONF['wwwroot'];?>/">

                <input type="hidden" name="sorting" value="<?=$site->fdat['sorting'];?>">

				<input type="hidden" name="extension_path" value="<?=$site->fdat['extension_path'];?>">
		<?php /* /hidden form stuff */ ?>

	<table cellpadding="0" cellspacing="0" class="layout" border="0">
		<tr>
			<td>
				<table cellpadding="0" cellspacing="0" class="layout" border="0">
					<tr>
						<td class="header">
							<table cellpadding="0" cellspacing="0" border="0">
								<tr>
									<td style="	font-size: 12px;font-weight: bold;"><label for="pealkiri"><?=$site->sys_sona(array('sona' => 'Pealkiri', 'tyyp' => 'editor'))?>:&nbsp;</label></td>
									<td width="100%"><input type="text" tabindex="1" id="pealkiri" name="pealkiri" value="<?=htmlspecialchars($objekt->pealkiri);?>" onblur="createAlias();"></td>
								</tr>
							</table>
						</td>
					</tr>
					<?php if($objekt->objekt_id) { ?>
					<tr>
						<td class="alias"><input type="hidden" name="friendly_url" id="alias_value" value="<?=htmlspecialchars($objekt->all['friendly_url']);?>"><?=$parent_href;?><span id="alias_placeholder"><a href="javascript:void(0);" onclick="editAlias();" id="alias_link"><?=($objekt->all['friendly_url'] ? (strlen(htmlspecialchars($objekt->all['friendly_url'])) > 30 ? substr(htmlspecialchars($objekt->all['friendly_url']), 0, 30).'...' : htmlspecialchars($objekt->all['friendly_url'])) : $objekt->objekt_id);?></a></span></td>
					</tr>
					<?php } else { ?>
					<tr>
						<td id="alias_cell" class="alias">&nbsp;</td>
					</tr>
					<?php } ?>
					<tr>
						<td class="editor">
							<?=$editor->Create();?>
						</td>
					</tr>
					<tr>
						<td id="sections_container" class="sections">
							<?=print_sections();?>
						</td>
					</tr>
				</table>
			</td>
			<td class="profiles">
				<?=print_profiles();?>
			</td>
		</tr>
	</table>


	</form>
	<? if ($site->fdat['op']=='edit') {?>
		<iframe src="checkin.php?objekt_id=<?=$objekt->objekt_id ?>" style="width: 0; height: 0; display: none; visibility: hidden;"></iframe>
	<? } ?>

</body>

</html>

<?php

}
/**
 * convert local link to alias,
 * if given link is not local, returns the link unchanged
 *
 * @param string $bytes
 * @return string
 */
function convert_local_link_to_alias($link)
{
    global $site;
    $objektUrl = $link;
    $queryArray = array();
    $idValue = '';
    # bug #2882
    if (preg_match("/^(.*:+(\\/*))\$/i", $objektUrl)) {
        # in case of invalid url, the url is returned unchanged
        return $objektUrl;
    }
    $urlArray = parse_url($objektUrl);
    $separator = strpos($urlArray['query'], '&amp;') !== false ? '&amp;' : '&';
    foreach (explode($separator, $urlArray['query']) as $value) {
        $query = explode('=', $value);
        if ($query[0] != 'id') {
            $queryArray[] = $value;
        } else {
            $idValue = $query[1];
        }
    }
    if (count($queryArray) > 0) {
        $param = '?' . implode('&amp;', $queryArray);
    } else {
        $param = '';
    }
    // check if link is local and id parameter was given
    if (($urlArray['host'] == $_SERVER['SERVER_NAME'] || $urlArray['host'] == '') && ($urlArray['path'] == $site->wwwroot . '/' || $urlArray['path'] == '') && is_numeric($idValue)) {
        $linkObj = new Objekt(array(objekt_id => $idValue));
        // if http missing, add it
        if (!$urlArray['scheme']) {
            $urlArray['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
        }
        // replace link
        $objektUrl = $urlArray['scheme'] . '://' . $_SERVER['SERVER_NAME'] . $linkObj->get_object_href() . $param;
    }
    return $objektUrl;
}
function smarty_function_init_object($params, &$smarty)
{
    global $site, $leht, $template, $class_path;
    $content_template =& $leht->content_template;
    ##############
    # default values
    extract($params);
    if (!isset($id)) {
        $id = $leht->id;
    }
    if (!isset($name)) {
        $name = "object";
    }
    ###############
    # action-buttons
    # by default show all
    if (!isset($buttons)) {
        $buttons = array("new", "edit", "hide", "move", "delete");
    } else {
        $buttons = split(",", $buttons);
    }
    ##############
    # luua objekt & load sisu
    $obj = new Objekt(array(objekt_id => $id));
    $obj->load_sisu();
    ################
    # object GENERAL parameters
    $obj->id = $obj->objekt_id;
    $obj->class = translate_en($obj->all[klass]);
    # translate it to english
    # kui link
    if ($obj->all[klass] == "link") {
        $objektUrl = $obj->all['url'];
        // replace index.php?id=xxx or ?id=xxx style local url with its alias
        if (!$site->in_editor && $site->CONF['use_aliases'] && $site->CONF['replace_links_with_alias']) {
            $objektUrl = convert_local_link_to_alias($objektUrl);
        }
        $objektUrl && $obj->all['on_uusaken'] ? $obj->href = $objektUrl . '" target="_blank' : ($obj->href = $objektUrl);
    } else {
        $obj->get_object_href();
    }
    $obj->title = $obj->pealkiri;
    $obj->buttons = $obj->get_edit_buttons(array(nupud => $buttons, tyyp_idlist => $obj->all['tyyp_id'], publish => $publish));
    $obj->fdate = $obj->all[aeg];
    $obj->last_modified = date('Y', $obj->all['last_modified']) > 1970 ? date('d.m.Y H:i', $obj->all['last_modified']) : '';
    ## crap data
    $obj->flast_modified = $obj->all['last_modified'];
    $obj->details_link = $obj->href;
    $obj->details_title = $site->sys_sona(array(sona => "loe edasi", tyyp => "kujundus"));
    $obj->printgif = '<a href="' . $obj->href . '&op=print" onClick="avaprintaken(this.href, 600, 400, \'print\'); return false;" target=_blank><img src="' . $site->img_path . '/print_it.gif" border=0 width=19 height=18></a>';
    $obj->printlink = $site->self . '?id=' . $obj->objekt_id . '&op=print';
    $obj->created_user_id = $obj->all['created_user_id'];
    $obj->created_user_name = $obj->all['created_user_name'];
    $obj->changed_user_id = $obj->all['changed_user_id'];
    $obj->changed_user_name = $obj->all['changed_user_name'];
    $obj->created_time = $site->db->MySQL_ee($obj->all['created_time']);
    $obj->fcreated_time = $obj->all['created_time'];
    $obj->changed_time = $site->db->MySQL_ee($obj->all['changed_time']);
    $obj->fchanged_time = $obj->all['changed_time'];
    $obj->last_commented_time = $site->db->MySQL_ee($obj->all['last_commented_time']);
    $obj->comment_count = $obj->all['comment_count'];
    ################
    # ALL values, set as attributes
    foreach ($obj->all as $fieldname => $value) {
        $obj->{$fieldname} = $value;
    }
    ###############
    # profile values, set as attributes
    $profile_def = $site->get_profile(array(id => $obj->all['profile_id']));
    if ($profile_def[profile_id]) {
        include_once $class_path . 'profile.class.php';
        $obj_profile = new Profile(array("id" => $obj->all['profile_id']));
        #### 1. set profile fields as object attributes
        $obj_profile->set_obj_general_fields(array("obj" => &$obj, "get_object_fields" => $get_object_fields));
        ###################
        # get selectlist values - 1 extra sql per function; sql is fast
        if (is_array($obj_profile->selectlist)) {
            $obj_profile->selectlist = array_unique($obj_profile->selectlist);
            #printr($obj_profile->selectlist);
        }
        # go on if object values needs changing:
        if (sizeof($obj_profile->selectlist) > 0) {
            #### 2. save array "->asset_names"  human readable NAME-s:
            $obj_profile->get_asset_names(array("selectlist" => $obj_profile->selectlist));
            #printr($obj_profile->asset_names);
            #printr($obj_profile->change_fields);
            ### 3. save object rest of attributes
            #print "<br>muuta ID: ".$obj->id;
            $obj_profile->set_obj_selectlist_fields(array("obj" => &$obj, "change_fields" => $obj_profile->change_fields));
        }
        # if any selectvalue exist & need to change
        # / get selectlist values
        ###################
    }
    ################
    # object CLASS specific parameters
    ########## ARTICLE
    if ($obj->class == 'article') {
        //$obj = init_article(array("id"=>$obj->id), &$smarty);
        if (!function_exists('smarty_function_init_article')) {
            require_once $smarty->_get_plugin_filepath('function', 'init_article');
        }
        smarty_function_init_article(array("id" => $obj->id, 'name' => $name), $smarty);
        return;
    } elseif ($obj->class == 'document') {
        if (!function_exists('smarty_function_init_document')) {
            require_once $smarty->_get_plugin_filepath('function', 'init_document');
        }
        $obj = smarty_function_init_document(array("id" => $obj->id, 'name' => $name), $smarty);
        return;
    } elseif ($obj->class == 'image') {
        if (!function_exists('smarty_function_init_picture')) {
            require_once $smarty->_get_plugin_filepath('function', 'init_picture');
        }
        $obj = smarty_function_init_picture(array("id" => $obj->id, 'name' => $name), $smarty);
        return;
    } elseif ($obj->class == 'section') {
        $obj->show_toolicons = $obj->all['on_printlink'];
        $obj->is_mailinglist = $obj->all['on_meilinglist'];
        $obj->show_subarticles = $obj->all['on_alamartiklid'];
        $obj->hide_in_menu = $obj->all['on_peida_vmenyy'];
        $obj->show_date = $obj->all['on_kp_nahtav'];
    } elseif ($obj->class == 'poll') {
        $obj->is_open = $obj->all['on_avatud'];
        $obj->expires = $obj->all['expires'] ? $site->db->MySQL_ee($obj->all['expires']) : '';
        $obj->fexpires = $obj->all['expires'] ? $obj->all['expires'] : '';
        $obj->is_expired = $obj->all['expires'] && (strtotime($obj->all['expires']) > 0 && strtotime($obj->all['expires']) < time()) ? 1 : 0;
        #printr(strtotime($obj->all['expires']));
        ######### CHECK voting
        # 1) IP-based gallup
        if ($site->CONF[gallup_ip_check] == 1) {
            $sql = $site->db->prepare("SELECT COUNT(gi_id) FROM gallup_ip WHERE objekt_id=? AND ip LIKE ?", $obj->id, $_SERVER["REMOTE_ADDR"]);
            $sth = new SQL($sql);
            $count = $sth->fetchsingle();
        } else {
            if ($site->CONF[gallup_ip_check] == 2 && $site->cookie["gallup"][$obj->id] == 1) {
                $count = 1;
            } else {
                if ($site->CONF[gallup_ip_check] == 3) {
                    $sql = $site->db->prepare("SELECT COUNT(gi_id) FROM gallup_ip WHERE objekt_id=? AND user_id=?", $obj->id, $site->user->user_id);
                    $sth = new SQL($sql);
                    # count=1: not logged in users are not allowed to vote:
                    $count = $site->user->user_id ? $sth->fetchsingle() : 1;
                } else {
                    $count = 0;
                }
            }
        }
        ######### / CHECK voting
        ### is_voted: if user is voted this poll or not, 1/0
        $obj->is_voted = $count;
        # not voted
        ### answers
        $sql = $site->db->prepare("SELECT * FROM gallup_vastus WHERE objekt_id=?", $obj->id);
        $sth = new SQL($sql);
        $site->debug->msg($sth->debug->get_msgs());
        $obj->answers = array();
        $obj->answers_count = 0;
        while ($vastus = $sth->fetch()) {
            unset($tmp);
            $tmp = new stdClass();
            $tmp->id = $vastus[gv_id];
            $tmp->answer = $vastus[vastus];
            $tmp->title = $vastus[vastus];
            $tmp->count = $vastus[count];
            $obj->answers[$vastus[gv_id]] = $tmp;
            $obj->answers_count += $vastus[count];
        }
        ### / answers
        ### voters (if not anonymous poll)
        if (!$obj->is_anonymous) {
            $sql = $site->db->prepare("SELECT gallup_ip.*, users.firstname, users.lastname\r\n\t\t\t\tFROM gallup_ip\r\n\t\t\t\t\tLEFT JOIN users ON users.user_id = gallup_ip.user_id\r\n\t\t\t\tWHERE objekt_id=?", $obj->id);
            $sth = new SQL($sql);
            $site->debug->msg($sth->debug->get_msgs());
            $obj->voters = array();
            while ($vastus = $sth->fetch()) {
                unset($tmp);
                $tmp->id = $vastus[gi_id];
                $tmp->answer_id = $vastus[gv_id];
                $tmp->ip = $vastus[ip];
                $tmp->user_id = $vastus[user_id];
                $tmp->user_firstname = $vastus[firstname];
                $tmp->user_lastname = $vastus[lastname];
                $tmp->time = $site->db->MySQL_ee($vastus[vote_time]);
                $tmp->ftime = $vastus[vote_time];
                $obj->voters[$vastus[gi_id]] = $tmp;
            }
        }
        # if not anonymous poll
        ### / voters
    } elseif ($obj->class == 'album') {
        // add album config atributes
        $conf = new CONFIG($obj->all['ttyyp_params']);
        $obj->description = $conf->get('desc');
        $obj->thumbnail_size = $conf->get('tn_size');
        # in pixels
        $obj->image_size = $conf->get('pic_size');
        # in pixels
        $obj->folder_id = $conf->get('folder_id');
        # source folder ID
        $obj->folder_path = $conf->get('path');
        # source folder path, eg "public/images"
    }
    ########## / ALBUM
    ##############
    # assign to template variables
    $smarty->assign($name, $obj);
}
/**
 * This source file is is part of Saurus CMS content management software.
 * It is licensed under MPL 1.1 (http://www.opensource.org/licenses/mozilla1.1.php).
 * Copyright (C) 2000-2010 Saurused Ltd (http://www.saurus.info/).
 * Redistribution of this file must retain the above copyright notice.
 * 
 * Please note that the original authors never thought this would turn out
 * such a great piece of software when the work started using Perl in year 2000.
 * Due to organic growth, you may find parts of the software being
 * a bit (well maybe more than a bit) old fashioned and here's where you can help.
 * Good luck and keep your open source minds open!
 * 
 * @package		SaurusCMS
 * @copyright	2000-2010 Saurused Ltd (http://www.saurus.info/)
 * @license		Mozilla Public License 1.1 (http://www.opensource.org/licenses/mozilla1.1.php)
 * 
 */
function edit_objekt()
{
    global $site;
    global $objekt;
    global $keel;
    global $class_path;
    global $tyyp;
    // refreshing (fdat['refresh'] = 1) looses object data, I don't know why and because it's done in edit_object.php, I'm not going to fix it, lord knows what it'll screw up
    if ($site->fdat['refresh'] && $site->fdat['id']) {
        $obj = new Objekt(array('objekt_id' => $site->fdat['id']));
        $objekt->objekt_id = $obj->objekt_id;
        $objekt->parent_id = $obj->parent_id;
    }
    $parent = new Objekt(array('objekt_id' => $objekt->objekt_id ? $objekt->parent_id : $site->fdat['parent_id']));
    $pearubriik = $parent->all['sys_alias'] == 'home' ? 1 : 0;
    // parent path
    if ($objekt->all['sys_alias'] == '' && $site->fdat['sys_alias'] == '') {
        // this needs serious rethink and optmisation: there's no need to get the entire tree, parent object's path to top is only needed
        include_once $class_path . 'rubloetelu.class.php';
        $rubs = new RubLoetelu(array('keel' => $keel, 'required_perm' => 'C', 'ignore_perm_for_obj' => $parent->objekt_id));
        #$rubs->debug->print_msg();
        $topparents = $rubs->get_loetelu();
        if (is_array($topparents)) {
            asort($topparents);
        }
        foreach ($topparents as $k => $v) {
            if ($parent->objekt_id == $k) {
                $section_name = $v;
                break;
            }
        }
    }
    // publishing
    $publish_start = $objekt->all['avaldamisaeg_algus'] > 0 ? $site->db->MySQL_ee_long($objekt->all['avaldamisaeg_algus']) : '';
    /* Don't print out time which is 00:00:00 */
    if (preg_match("/(\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d?\\d\\d)\\s(\\d?\\d)[\\:\\\\.\\/\\-](\\d?\\d)/", $publish_start, $aa_reg)) {
        $publish_start = $aa_reg[2] == "00" && $aa_reg[3] == "00" ? $aa_reg[1] : $publish_start;
    }
    $publish_end = $objekt->all['avaldamisaeg_lopp'] > 0 ? $site->db->MySQL_ee_long($objekt->all['avaldamisaeg_lopp']) : '';
    /* Don't print out time which is 23:59 */
    if (preg_match("/(\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d?\\d\\d)\\s(\\d?\\d)[\\:\\\\.\\/\\-](\\d?\\d)/", $publish_end, $la_reg)) {
        $publish_end = $la_reg[2] == "23" && $la_reg[3] == "59" ? $la_reg[1] : $publish_end;
    }
    // to get the correct path to parent objects set use_alises on
    $site->CONF['use_aliases'] = 1;
    $parent_href = $parent->get_object_href();
    if ($site->CONF['alias_trail_format'] == 0 || $parent->all['sys_alias'] == 'home' || $parent->all['sys_alias'] == 'trash' || $parent->all['sys_alias'] == 'system' || $parent->all['sys_alias'] == 'gallup_arhiiv') {
        $parent_href = preg_replace('#' . preg_quote('/' . ($parent->all['friendly_url'] ? $parent->all['friendly_url'] : $parent->objekt_id), '#') . '/$#', '/', $parent_href);
    }
    $parent_href = $site->CONF['hostname'] . $parent_href;
    // setup for section selection
    $_SESSION['parent_selection']['callback'] = 'window.opener.updateSection';
    $_SESSION['parent_selection']['selectable'] = 1;
    $_SESSION['parent_selection']['hide_language_selection'] = '1';
    $_SESSION['parent_selection']['mem_classes'] = array('rubriik');
    //this sucks, really
    $_SESSION['parent_selection']['db_fields'] = array('select_checkbox', 'objekt_id', 'pealkiri');
    $_SESSION['parent_selection']['display_fields'] = array('select_checkbox', 'pealkiri');
    // setup folder select
    $_SESSION['scms_filemanager_settings']['scms_select_album_folder'] = array('select_mode' => 2, 'action_text' => $site->sys_sona(array('sona' => 'use_this_folder_for_album', 'tyyp' => 'editor')), 'action_trigger' => $site->sys_sona(array('sona' => 'use_this_folder_for_album', 'tyyp' => 'editor')), 'callback' => 'window.opener.setFolder');
    $conf = new CONFIG($objekt->all['ttyyp_params']);
    $args['cols'] = $conf->get('cols');
    $args['rows'] = $conf->get('rows');
    $args['path'] = $conf->get('path');
    //$args['path'] = 1;
    $args['tn_size'] = $conf->get('tn_size');
    $args['desc'] = $conf->get('desc');
    $args['pic_size'] = $conf->get('pic_size');
    $args['folder_id'] = $conf->get('folder_id');
    if (!$args['path']) {
        if ($objekt->all['pealkiri']) {
            $album_folder_path = $clean_path = create_alias_from_string($objekt->all['pealkiri']);
        } else {
            $result = new SQL('select max(objekt_id) + 1 from objekt');
            $album_folder_path = $clean_path = $result->fetchsingle();
        }
        $supplement = 2;
        // unlikely to happen
        if ($album_folder_path === '') {
            $album_folder_path = $clean_path = rand(10000, 20000);
        }
        while (file_exists($site->absolute_path . '/public/galleries/' . $album_folder_path)) {
            $album_folder_path = create_alias_from_string($clean_path . '-' . $supplement);
            $supplement++;
            // guard, also unlikely
            if ($supplement > 1000) {
                exit;
            }
        }
        $album_folder_path = 'public/galleries/' . $album_folder_path;
    }
    //printr($album_folder_path);
    ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
	<head> 	
		<title><?php 
    echo $site->title;
    ?>
 <?php 
    echo $site->cms_version;
    ?>
</title>
		
		<meta http-equiv="Content-Type" content="text/html; charset=<?php 
    echo $encoding ? $encoding : $site->encoding;
    ?>
" />
		<meta http-equiv="Cache-Control" content="no-cache" />
		
		<link rel="stylesheet" href="<?php 
    echo $site->CONF['wwwroot'] . $site->CONF['styles_path'];
    ?>
/datepicker.css" />
		<link rel="stylesheet" href="<?php 
    echo $site->CONF['wwwroot'] . $site->CONF['styles_path'];
    ?>
/album_editor.css" />
		<!--[if IE 6]>
			<style type="text/css">
				input.inline_button {
					padding: 0px 0px 0px 0px;
					height: 21px;
				}
			</style>
		<![endif]-->
		<!--[if IE 7]>
			<style type="text/css">
				input.inline_button {
					padding: 0px 0px 0px 0px;
					height: 21px;
				}
			</style>
		<![endif]-->
		
		<script type="text/javascript" src="<?php 
    echo $site->CONF['wwwroot'] . $site->CONF['js_path'];
    ?>
/yld.js"></script>
		<script type="text/javascript" src="<?php 
    echo $site->CONF['wwwroot'] . $site->CONF['js_path'];
    ?>
/edit_popup.js"></script>
		<script type="text/javascript" src="<?php 
    echo $site->CONF['wwwroot'] . $site->CONF['js_path'];
    ?>
/jquery.js"></script>
		<script type="text/javascript" src="<?php 
    echo $site->CONF['wwwroot'] . $site->CONF['js_path'];
    ?>
/datepicker.js"></script>
		<script type="text/javascript" src="<?php 
    echo $site->CONF['wwwroot'];
    ?>
/common.js.php"></script>
		<?php 
    if ($site->CONF['fm_allow_multiple_upload'] && $parent->all['ttyyp_id'] != 39) {
        ?>
		<script type="text/javascript" src="<?php 
        echo $site->CONF['wwwroot'] . $site->CONF['js_path'];
        ?>
/swfupload/swfupload.js"></script>
		<script type="text/javascript" src="<?php 
        echo $site->CONF['wwwroot'] . $site->CONF['js_path'];
        ?>
/swfupload/swfupload.queue.js"></script>
		<?php 
    }
    ?>
		
		<script type="text/javascript">
			var isIE = navigator.appVersion.match(/MSIE/); // assume gecko on false
			
			var folder_path = '<?php 
    echo $album_folder_path;
    ?>
';
			
			var ajax_token = <?php 
    echo create_form_token_json('edit-album-ajax');
    ?>
;
			
			var swfu;
			
			window.onload = function ()
			{
				var title = document.getElementById('pealkiri');
				
				var advanced_panel_state = document.getElementById('advanced_panel_state');
				if(advanced_panel_state.value == 1)
				{
					togglePanel('advanced');
				}
				
				this.focus();
				title.focus();
				
				resizeWindow();
				
				<?php 
    if ($site->CONF['fm_allow_multiple_upload'] && $parent->all['ttyyp_id'] != 39) {
        ?>
				
				var post_params = {'<?php 
        echo session_name();
        ?>
' : '<?php 
        echo session_id();
        ?>
', 'op': 'add_image_to_album'};
				$.extend(post_params, ajax_token);
				
				swfu = new SWFUpload({
					flash_url : '<?php 
        echo $site->CONF['wwwroot'] . $site->CONF['js_path'];
        ?>
/swfupload/swfupload.swf',
					upload_url: '<?php 
        echo $site->CONF['wwwroot'];
        ?>
/admin/ajax_response.php',
					post_params: post_params,
					file_size_limit : '<?php 
        echo is_int(ini_get('upload_max_filesize')) ? round(ini_get('upload_max_filesize') / 1024) : ini_get('upload_max_filesize') . 'B';
        ?>
',
					file_types : '*.gif;*.png;*.jpeg;*.jpg',
					file_types_description : 'Images',
					file_upload_limit : 0,
					file_queue_limit : 100,
					custom_settings : {
						cancelButtonId : 'cancel_file_upload_button'
					},
					debug: false,
			
					// Button settings
					button_image_url: '<?php 
        echo $site->CONF['wwwroot'] . $site->CONF['styles_path'];
        ?>
/gfx/general/album_upload_button_bg.gif',	// Relative to the Flash file
					button_width: '95',
					button_height: '21',
					button_placeholder_id: 'span_upload_button_place_holder',
					button_text: '<?php 
        echo $site->sys_sona(array('sona' => 'add_images', 'tyyp' => 'editor'));
        ?>
',
					button_text_left_padding: 8,
					button_text_top_padding: 1,
					button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT,
					
					// The event handler functions
					swfupload_loaded_handler: swfuLoaded,
					file_queued_handler : fileQueued,
					file_queue_error_handler : fileQueueError,
					file_dialog_complete_handler : fileDialogComplete,
					upload_start_handler : uploadStart,
					upload_progress_handler : uploadProgress,
					upload_error_handler : uploadError,
					upload_success_handler : uploadSuccess,
					upload_complete_handler : uploadComplete
					//queue_complete_handler : queueComplete	// Queue plugin event
				});
				<?php 
    }
    ?>
				}
			
			function resizeWindow()
			{
        if(jQuery.browser.webkit)
        {
          window.resizeTo(580, 380);
        }
        else
        {
          resizeWindowTo($('#size_wrapper').width(), $('#size_wrapper').height());
        }
			}
			
			var filemanager_window;
			var uploadFolderPathSet = false;

			function chooseFolder()
			{
				filemanager_window = openpopup('filemanager.php?setup=scms_select_album_folder', 'filemanager', 980, 600);
			}
			
			function setFolder(data)
			{
				filemanager_window.close();
				uploadFolderPathSet = true;
				
				$('input#path').attr('value', data.folders[0].relative_path.replace(/^\//, ''));
				$('a#images_folder_path_link').text(data.folders[0].relative_path.replace(/^\//, ''));
				
				$('td#images_folder_cf_container_cell').removeClass('hidden');
				$('td#images_choose_folder_button_cell').addClass('hidden');
			}
			
			
			function clearFolder()
			{
				$('input#path').attr('value', '');
				
				$('td#images_folder_cf_container_cell').addClass('hidden');
				$('td#images_choose_folder_button_cell').removeClass('hidden');
				
				resizeWindow();
			}
			
			function chooseSection()
			{
				explorer_window = openpopup('explorer.php?objekt_id=home&editor=1&swk_setup=parent_selection&remove_objects=<?php 
    echo $site->fdat['id'];
    ?>
&pre_selected=' + document.getElementById('rubriik').value, 'cms_explorer', '800','600');
			}
			
			function updateSection(sections)
			{
				explorer_window.close();
				var section_name = document.getElementById('section_name');
				var section_id = document.getElementById('rubriik');
				var trail_path= new Array();

					for(var j = 0; j < sections[0].trail.length; j++){
						trail_path[j] = sections[0].trail[j].pealkiri;
					}

				section_name.innerHTML = '<a href="javascript:chooseSection();">' + trail_path.join("->") + '</a>';
				section_id.value = sections[0].objekt_id;
			}

			function editAlias()
			{
				var alias_placeholder = document.getElementById('alias_placeholder');
				var alias_value = document.getElementById('alias_value');
				
				alias_placeholder.innerHTML = '<input type="text" id="alias" value="' + alias_value.value + '" onblur="saveAlias();">';
				
		    	resizeWindow();
		    	
				var alias = document.getElementById('alias');
				alias.focus();
			}
			
			function saveAlias()
			{
				var alias_placeholder = document.getElementById('alias_placeholder');
				var alias_value = document.getElementById('alias_value');
				var alias = document.getElementById('alias');
				
				if(alias_value.value != alias.value)
				{
					$.ajax({
					    url: 'ajax_response.php?rand=' + Math.random(9999),
					    data: {op: 'generate_alias', string: alias.value, language_id: '<?php 
    echo $keel;
    ?>
'},
					    type: 'POST',
					    dataType: 'json',
					    timeout: 1000,
					    error: function()
					    {
							alias_placeholder.innerHTML = '<a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + (alias_value.value.length > 30 ? alias_value.value.substring(0, 30) + '...' : alias_value.value) + '</a>';
					    },
					    success: function(response)
					    {
					    	if(response.alias)
					    	{
								alias_value.value = response.alias;
								alias_placeholder.innerHTML = '<a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + (alias_value.value.length > 30 ? alias_value.value.substring(0, 30) + '...' : alias_value.value) + '</a>';
					    	}
					    	else
					    	{
								alias_value.value = '';
								<?php 
    if ($objekt->objekt_id) {
        ?>
								alias_placeholder.innerHTML = '<a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + '<?php 
        echo $objekt->objekt_id;
        ?>
' + '</a>';
								<?php 
    } else {
        ?>
						    	alias_placeholder.innerHTML = '<input type="text" id="alias" value="" onblur="saveAlias();">';
								<?php 
    }
    ?>
					    	}
							
					    	resizeWindow();
					    }
					});
				}
				else
				{
					if(!alias.value)
					{
						alias_value.value = '';
						<?php 
    if ($objekt->objekt_id) {
        ?>
						alias_placeholder.innerHTML = '<a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + '<?php 
        echo $objekt->objekt_id;
        ?>
' + '</a>';
						<?php 
    } else {
        ?>
				    	alias_placeholder.innerHTML = '<input type="text" id="alias" value="" onblur="saveAlias();">';
						<?php 
    }
    ?>
					}
					else
					{
						alias_placeholder.innerHTML = '<a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + (alias_value.value.length > 30 ? alias_value.value.substring(0, 30) + '...' : alias_value.value) + '</a>';
					}
			    	
					resizeWindow();
				}
			}
			
			function createAlias()
			{
				var alias_value = document.getElementById('alias_value');
				var title = document.getElementById('pealkiri')
				
				if(0 || (!alias_value && title.value))
				{
					$.ajax({
					    url: 'ajax_response.php?rand=' + Math.random(9999),
					    data: {op: 'generate_alias', string: title.value, language_id: '<?php 
    echo $keel;
    ?>
'},
					    type: 'POST',
					    dataType: 'json',
					    timeout: 1000,
					    error: function()
					    {
					    },
					    success: function(response)
					    {
					    	var alias_cell = document.getElementById('alias_cell');
					    	alias_cell.className = 'alias';
					    	if(response.alias)
					    	{
						    	alias_cell.innerHTML = '<input type="hidden" name="friendly_url" id="alias_value" value="' + response.alias + '"><?php 
    echo $parent_href;
    ?>
<span id="alias_placeholder"><a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + (response.alias.length > 30 ? response.alias.substring(0, 30) + '...' : response.alias) + '</a></span>';
						    	if(swfu && !swfu.uploadFolderPathSent && !uploadFolderPathSet) $('input#path').attr('value', 'public/galleries/' + response.alias);
					    	}
					    	else
					    	{
						    	alias_cell.innerHTML = '<input type="hidden" name="friendly_url" id="alias_value" value=""><?php 
    echo $parent_href;
    ?>
<span id="alias_placeholder"><input type="text" id="alias" value="" onblur="saveAlias();"></span>';
					    	}
					    	
					    	$('a#images_folder_path_link').text($('input#path').attr('value'));
					    	
					    	$('#alias_row').show();
					    	//var alias_row = document.getElementById('alias_row');
					    	//alias_row.style.display = (isIE ? 'block' : 'table-row');

	    					resizeWindow();
					    }
					});			
				}
			}
			
			function saveForm(op2)
			{
				var form = document.getElementById('editForm');
				
				var title = document.getElementById('pealkiri');
				
				if(title.value.length == 0)
				{
					alert('<?php 
    echo $site->sys_sona(array('sona' => 'please_fill_in_the_title!', 'tyyp' => 'admin'));
    ?>
');
					return;
				}
				
				var alias_value = document.getElementById('alias_value');
				var alias = document.getElementById('alias');
				
				if((title.value && !alias_value) || (alias && alias_value && alias.value != alias_value.value))
				{
					$.ajax({
					    url: 'ajax_response.php?rand=' + Math.random(9999),
					    data: {op: 'generate_alias', string: title.value, language_id: '<?php 
    echo $keel;
    ?>
'},
					    type: 'POST',
					    dataType: 'json',
					    timeout: 1000,
					    error: function()
					    {
					    	var form = document.getElementById('editForm');
			 				
					    	form.op2.value = op2;
			 				form.submit();
					    },
					    success: function(response)
					    {
					    	var alias_value = document.getElementById('alias_value');
					    	
					    	if(!alias_value && response.alias)
					    	{
						    	var alias_cell = document.getElementById('alias_cell');
						    	alias_cell.innerHTML = '<input type="hidden" name="friendly_url" id="alias_value" value="' + response.alias + '"><?php 
    echo $parent_href;
    ?>
<span id="alias_placeholder"><a href="javascript:void(0);" onclick="editAlias();" id="alias_link">' + (response.alias.length > 30 ? response.alias.substring(0, 30) + '...' : response.alias) + '</a></span>';
					    	}
							
					    	var form = document.getElementById('editForm');
			 				
					    	form.op2.value = op2;
			 				form.submit();
					    }
					});
				}
				else
				{
	 				form.op2.value = op2;
	 				form.submit();
				}
			}
			
			<?php 
    if ($site->CONF['fm_allow_multiple_upload'] && $parent->all['ttyyp_id'] != 39) {
        ?>
			// SWFupload handler functions
			function fileQueued(file) {
				try {
				} catch (ex) {
					this.debug(ex);
				}
			}
			

			function fileQueueError(file, errorCode, message) {
				try {
					
					if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
						alert('<?php 
        echo $site->sys_sona(array('sona' => 'upload_queue_limit', 'tyyp' => 'Files'));
        ?>
' + ': ' + this.settings.file_queue_limit);
						return;
					}
				
					if (errorCode === SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT) {
						alert(file.name + ' ' + '<?php 
        echo $site->sys_sona(array('sona' => 'upload_limit_size', 'tyyp' => 'Files'));
        ?>
' + ' ' + this.settings.file_size_limit);
						return;
					}
			
					switch (errorCode) {
					default:
						if (file !== null) {
							alert("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
						}
						this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
						break;
					}
				} catch (ex) {
			        this.debug(ex);
			    }
			}
			
			function fileDialogComplete(numFilesSelected, numFilesQueued) {
				try {
					
					if(numFilesQueued > 0)
					{
						$('td#images_folder_cf_container_cell').addClass('hidden');
						$('td#images_choose_folder_button_cell').addClass('hidden');
						$('table#form_submit_buttons_table').addClass('hidden');
						
						this.setButtonDisabled(true);
						this.setButtonDimensions(1, 1);
						
						$('td#upload_progress_cell').removeClass('hidden');
						$('td#upload_progress_text_cell').removeClass('hidden');
						$('table#upload_cancel_table').removeClass('hidden');
						
						$('div#upload_progress_grow').width(0);
						
						this.numFilesQueued = numFilesQueued;
						
						if(!$('input#path').attr('value')) $('input#path').attr('value', folder_path);
						
						this.addPostParam('folder_path', $('input#path').attr('value'));
						this.uploadFolderPathSent = true;
						this.startUpload();
					}
				} catch (ex)  {
			        this.debug(ex);
				}
			}
			
			function uploadStart(file) {
				try {
					
					$('td#upload_progress_text_cell').html(file.name + ' <span id="percent_placeholder">0</span>%');
					this.progressBarWidth = $('div#upload_progress_grow').width();
					
				} catch (ex)  {
			        this.debug(ex);
				}
				
				return true;
			}
			
			function uploadProgress(file, bytesLoaded, bytesTotal) {
				try {
					var percent = Math.round((bytesLoaded / bytesTotal) * 100);
					
					$('div#upload_progress_grow').width(this.progressBarWidth + Math.round(($('div#upload_progress_bar').width() / this.numFilesQueued * percent) / 100));
					
					$('span#percent_placeholder').html(percent);
					
				} catch (ex) {
					this.debug(ex);
				}
			}
			
			function uploadSuccess(file, serverData) {
				try {
				} catch (ex) {
					this.debug(ex);
				}
			}
			
			function uploadError(file, errorCode, message) {
				try {
					
					switch (errorCode) {
						case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
						case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
							// upload canceled
						break;
						
						case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
							alert('Error occured while trying to connect.');
						break;
						
						default:
							alert("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
						break;
					}
				} catch (ex) {
			        this.debug(ex);
			    }
			}
			
			function uploadComplete(file) {
				
				$('td#upload_progress_text_cell').empty();
				
				if (this.getStats().files_queued === 0) {
					
					// all files are finished
					$('td#upload_progress_cell').addClass('hidden');
					$('td#upload_progress_text_cell').addClass('hidden');
					$('table#upload_cancel_table').addClass('hidden');
						
					this.setButtonDisabled(false);
					this.setButtonDimensions(95, 21);
					
					$('a#images_folder_path_link').text($('input#path').attr('value'));
					
					$('table#form_submit_buttons_table').removeClass('hidden');
					$('td#images_folder_cf_container_cell').removeClass('hidden');
				}
			}
			
			function swfuLoaded()
			{
				$('input#add_images_button').addClass('hidden');
			}
			<?php 
    }
    ?>
			
		</script>
	</head>
	
	<body>
		
		<?php 
    if ($site->fdat['op'] == 'edit') {
        ?>
			<iframe src="checkin.php?objekt_id=<?php 
        echo $objekt->objekt_id;
        ?>
" style="width: 0; height: 0; display: none; visibility: hidden;"></iframe>
		<?php 
    }
    ?>
		
		<form action="edit.php" name="editForm" id="editForm" method="POST"  enctype="multipart/form-data">
		
		<?php 
    create_form_token('edit-album');
    ?>
		
		<input type="hidden" name="tab" value="<?php 
    echo $site->fdat['tab'];
    ?>
" />
		<input type="hidden" id="op" name="op" value="<?php 
    echo htmlspecialchars($site->fdat['op']);
    ?>
" />
		<input type="hidden" id="op2" name="op2" value="" />
		<input type="hidden" id="refresh" name="refresh" value="0" />
		
		<input type="hidden" name="tyyp_id" value="<?php 
    echo $tyyp['tyyp_id'];
    ?>
" />
		<input type="hidden" name="tyyp" value="<?php 
    echo $tyyp['klass'];
    ?>
" />
		
		<input type="hidden" name="pearubriik" value="<?php 
    echo $pearubriik;
    ?>
" />
		<input type="hidden" name="id" value="<?php 
    echo $site->fdat['id'];
    ?>
" />
		<input type="hidden" name="parent_id" value="<?php 
    echo $site->fdat['parent_id'];
    ?>
" />
		<input type="hidden" name="previous_id" value="<?php 
    echo $site->fdat['previous_id'];
    ?>
" />
		<input type="hidden" name="keel" value="<?php 
    echo $keel;
    ?>
" />
		<input type="hidden" name="on_pealkiri" value="1" />
		
        <input type="hidden" name="sorting" value="<?php 
    echo $site->fdat['sorting'];
    ?>
">

		<input type="hidden" name="opener_location" value="" />
		<input type="hidden" name="publish" value="<?php 
    echo $site->fdat['publish'] || $objekt->all['on_avaldatud'] ? 1 : 0;
    ?>
">

		<input name="permanent_parent_id" type="hidden" value="<?php 
    echo $objekt->parent_id;
    ?>
" />
		<input name="sys_alias" type="hidden" value="<?php 
    echo $site->fdat['sys_alias'] ? $site->fdat['sys_alias'] : $objekt->all['sys_alias'];
    ?>
" />
		
		<input name="advanced_panel_state" id="advanced_panel_state" type="hidden" value="<?php 
    echo $site->fdat['advanced_panel_state'] ? htmlspecialchars($site->fdat['advanced_panel_state']) : 0;
    ?>
" />
		
		<div id="size_wrapper" class="section_editor">
		
		<div id="main_container">
			<?php 
    ########### Tabs  ########
    ?>
			<div id="tab_container">
				<a href="javascript:void(0);" class="selected"><?php 
    echo $site->sys_sona(array('sona' => 'tyyp_album', 'tyyp' => 'System'));
    ?>
</a>
			</div>
			
			<div id="content_container">
		
				<table cellpadding="0" cellspacing="0" class="form_row">
					<tr>
						<td class="label"><label><?php 
    echo $site->sys_sona(array('sona' => 'Pealkiri', 'tyyp' => 'editor'));
    ?>
:</label></td>
						<td class="input"><input type="text" class="text" name="pealkiri" id="pealkiri" value="<?php 
    echo htmlspecialchars($objekt->all['pealkiri']);
    ?>
" onblur="createAlias();" /></td>
					</tr>
					<?php 
    if (($objekt->objekt_id || isset($objekt->all['friendly_url'])) && !($objekt->all['sys_alias'] == 'home' || $objekt->all['sys_alias'] == 'trash' || $objekt->all['sys_alias'] == 'system' || $objekt->all['sys_alias'] == 'gallup_arhiiv')) {
        ?>
					<tr>
						<td class="label">&nbsp;</td>
						<td class="input"><input type="hidden" id="alias_value" name="friendly_url" name="friendly_url" value="<?php 
        echo htmlspecialchars($objekt->all['friendly_url']);
        ?>
" /><?php 
        echo $parent_href;
        ?>
<span id="alias_placeholder"><a href="javascript:void(0);" onclick="editAlias();" id="alias_link"><?php 
        echo $objekt->all['friendly_url'] ? strlen(htmlspecialchars($objekt->all['friendly_url'])) > 30 ? substr(htmlspecialchars($objekt->all['friendly_url']), 0, 30) . '...' : htmlspecialchars($objekt->all['friendly_url']) : $objekt->objekt_id;
        ?>
</a></span></td>
					</tr>
					<?php 
    } else {
        ?>
					<tr id="alias_row">
						<td class="label">&nbsp;</td>
						<td class="input" id="alias_cell"></td>
					</tr>
					<?php 
    }
    ?>
					
					<?php 
    ########### images folder  ########
    ?>
					<?php 
    if ($parent->all['ttyyp_id'] != 39) {
        ?>
					<tr id="images_folder">
						<td class="label"><?php 
        echo $site->sys_sona(array('sona' => 'Image files directory', 'tyyp' => 'editor'));
        ?>
:</td>
						<td class="input">
							<table cellpadding="0" cellspacing="0" class="container" id="images_folder_cf_container_table">
								<tr>
									<?php 
        ########### images folder  ########
        ?>
									<td id="images_folder_cf_container_cell"<?php 
        echo $args['path'] ? '' : ' class="hidden"';
        ?>
>
										<table cellpadding="0" cellspacing="0" class="cf_container">
											<tr>
												<th><input type="hidden" name="path" id="path" value="<?php 
        echo $args['path'] ? $args['path'] : '';
        ?>
"><span id="images_folder_path"><a href="javascript:chooseFolder();" id="images_folder_path_link" title="<?php 
        echo $site->sys_sona(array('sona' => 'choose_a_folder', 'tyyp' => 'editor'));
        ?>
"><?php 
        echo $args['path'];
        ?>
</a></span></th>
												<td><a href="javascript:chooseFolder();" title="<?php 
        echo $site->sys_sona(array('sona' => 'choose_a_folder', 'tyyp' => 'editor'));
        ?>
">..</a></td>
												<td><a href="javascript:clearFolder();">X</a></td>
											</tr>
										</table>
									</td>
									
									<?php 
        ########### add images  ########
        ?>
									<?php 
        if ($site->CONF['fm_allow_multiple_upload']) {
            ?>
									<td id="images_add_button_cell">
										<span id="span_upload_button_place_holder"></span>
									</td>
									
									<?php 
            ########### upload progress  ########
            ?>
									<td id="upload_progress_cell" class="hidden"><div id="upload_progress_bar"><div id="upload_progress_grow"></div></div></td><!-- / scms_upload_progress -->
									<td id="upload_progress_text_cell" class="hidden"></td><!-- / scms_upload_text -->
									<?php 
        }
        ?>
									
									<?php 
        ########### choose_a_folder  ########
        ?>
									<td id="images_choose_folder_button_cell"<?php 
        echo $args['path'] ? ' class="hidden"' : '';
        ?>
>
										<?php 
        if ($site->CONF['fm_allow_multiple_upload']) {
            ?>
&nbsp;<?php 
            echo $site->sys_sona(array('sona' => 'or', 'tyyp' => 'editor'));
        }
        ?>
										<input type="button" value="<?php 
        echo $site->sys_sona(array('sona' => 'choose_a_folder', 'tyyp' => 'editor'));
        ?>
" class="inline_button" onclick="chooseFolder();" />
									</td>
								</tr>
							</table>
						</td>
					</tr>
					<?php 
    }
    ?>
					
					<?php 
    ########### description  ########
    ?>
					<tr>
						<td class="label"><?php 
    echo $site->sys_sona(array('sona' => 'Kirjeldus', 'tyyp' => 'editor'));
    ?>
:</td>
						<td class="input"><textarea name="desc"><?php 
    echo $args['desc'] ? $args['desc'] : "";
    ?>
</textarea></td>
					</tr>
					
					<?php 
    ########### publishing  ########
    ?>
					<tr>
						<td class="label"><?php 
    echo $site->sys_sona(array('sona' => 'visible_to_visitors', 'tyyp' => 'editor'));
    ?>
:</td>
						<td><input type="radio" name="publish" id="object_published" value="1"<?php 
    echo $site->fdat['publish'] || $objekt->all['on_avaldatud'] ? ' checked' : '';
    echo $objekt->permission && !$objekt->permission['P'] || !$objekt->permission && !$parent->permission['P'] ? ' disabled="disabled"' : NULL;
    ?>
> <label for="object_published"><?php 
    echo $site->sys_sona(array('sona' => 'published', 'tyyp' => 'editor'));
    ?>
</label>	<input type="radio" name="publish" id="object_unpublished" value="0"<?php 
    echo $site->fdat['publish'] == 0 && $objekt->all['on_avaldatud'] == 0 ? ' checked' : '';
    echo $objekt->permission && !$objekt->permission['P'] || !$objekt->permission && !$parent->permission['P'] ? ' disabled="disabled"' : NULL;
    ?>
> <label for="object_unpublished"><?php 
    echo $site->sys_sona(array('sona' => 'unpublished', 'tyyp' => 'editor'));
    ?>
</label></td>
					</tr>
				</table>
				
				<br />
				
				<?php 
    ########### advanced  ########
    ?>
				<div class="panel_toggler" onclick="togglePanel('advanced');">
					<a href="javascript:void(0);"><?php 
    echo $site->sys_sona(array('sona' => 'Advanced', 'tyyp' => 'editor'));
    ?>
 <span id="advanced_panel_link_state">&raquo;</span></a>
				</div>
				
				<div id="advanced_panel" class="panel">
					
					<?php 
    ########### image sizes  ########
    ?>
					<table cellpadding="0" cellspacing="0" class="form_row">
						<tr>
							<td class="label">Image sizes:</td>
							<td><?php 
    echo $site->sys_sona(array('sona' => 'Image size', 'tyyp' => 'editor'));
    ?>
:</td>
							<td>
								<input name="pic_size" class="text_number" value="<?php 
    echo $args['pic_size'] ? $args['pic_size'] : $site->CONF['image_width'];
    ?>
" />
								<input name="old_pic_size" type="hidden" value="<?php 
    echo $args['pic_size'] ? $args['pic_size'] : $site->CONF['image_width'];
    ?>
" />
							</td>
							<td>px&nbsp;</td>
							<td><?php 
    echo $site->sys_sona(array('sona' => 'Thumbnail size', 'tyyp' => 'editor'));
    ?>
:</td>
							<td>
								<input name="tn_size" class="text_number" value="<?php 
    echo $args['tn_size'] ? $args['tn_size'] : $site->CONF['thumb_width'];
    ?>
" />
								<input name="old_tn_size" type="hidden" value="<?php 
    echo $args['tn_size'] ? $args['tn_size'] : $site->CONF['thumb_width'];
    ?>
" />
							</td>
							<td>px</td>
						</tr>
					</table>
					
					<?php 
    ########### parent section  ########
    ?>
					<?php 
    if ($section_name) {
        ?>
					<table cellpadding="0" cellspacing="0" class="form_row">
						<tr>
							<td class="label"><label><?php 
        echo $site->sys_sona(array('sona' => 'Rubriigid', 'tyyp' => 'editor'));
        ?>
:</label></td>
							<td class="input">
								<table cellpadding="0" cellspacing="0" class="cf_container">
									<tr>
										<th><input type="hidden" name="rubriik[]" id="rubriik" value="<?php 
        echo $parent->objekt_id;
        ?>
"><span id="section_name"><a href="javascript:chooseSection();"><?php 
        echo $section_name;
        ?>
</a></span></th>
										<td><a href="javascript:chooseSection();">..</a></td>
									</tr>
								</table>
							</td>
						</tr>
					</table>
					<?php 
    }
    ?>
					
					<table cellpadding="0" cellspacing="0" class="form_row">
						<tr>
							<td class="label">&nbsp;</td>
							<td><label><?php 
    echo $site->sys_sona(array('sona' => 'Avaldatud', 'tyyp' => 'editor'));
    ?>
:</label></td>
							<td><input type="text" id="publish_start" name="avaldamise_algus" maxlength="16" class="text_date" value="<?php 
    echo $publish_start;
    ?>
" /></td>
							<td><a href="javascript:init_datepicker('publish_start', 'publish_start', 'publish_end');"><img src="<?php 
    echo $site->CONF['wwwroot'] . $site->CONF['styles_path'];
    ?>
/gfx/calendar/cal.gif" width="16" height="15" title="Choose from calendar" alt="Choose from calendar" /></a></td>
							<td><label><?php 
    echo $site->sys_sona(array('sona' => 'Kuni', 'tyyp' => 'editor'));
    ?>
:</label></td>
							<td><input type="text" id="publish_end" name="avaldamise_lopp" maxlength="16" class="text_date" value="<?php 
    echo $publish_end;
    ?>
" /></td>
							<td><a href="javascript:init_datepicker('publish_end', 'publish_start', 'publish_end');"><img src="<?php 
    echo $site->CONF['wwwroot'] . $site->CONF['styles_path'];
    ?>
/gfx/calendar/cal.gif" width="16" height="15" title="Choose from calendar" alt="Choose from calendar" /></a></td>
						</tr>
					</table>
					
					<?php 
    ########### position  ########
    ?>
					<?php 
    if ($site->CONF['allow_change_position']) {
        ?>
					<table cellpadding="0" cellspacing="0" class="form_row">
						<tr>
							<td class="label"><label><?php 
        echo $site->sys_sona(array('sona' => 'Position', 'tyyp' => 'editor'));
        ?>
:</label></td>
							<td><input type="text" maxlength="5" class="text_position" name="kesk" value="<?php 
        echo $site->fdat['op'] == 'edit' ? $objekt->all['kesk'] : $site->fdat['kesk'];
        ?>
" /></td>
						</tr>
					</table>
					<?php 
    } else {
        ?>
						<input type="hidden" name="kesk" value="<?php 
        echo $site->fdat['op'] == 'edit' ? $objekt->all['kesk'] : $site->fdat['kesk'];
        ?>
" />
					<?php 
    }
    ?>
					
				</div>
			</div>
			
		</div>
		
		<div id="button_container">
			
			<table cellspacing="0" cellpadding="0" id="form_submit_buttons_table">
				<tr>
					<td id="apply_button_cell">
						<input type="button" class="button" value="<?php 
    echo $site->sys_sona(array('sona' => 'Apply', 'tyyp' => 'editor'));
    ?>
" onclick="saveForm('save');" />
					</td>
					<td id="save_close_button_cell">
						<input type="button" class="button" value="&nbsp;&nbsp;&nbsp;&nbsp;<?php 
    echo $site->sys_sona(array('sona' => 'save_and_close', 'tyyp' => 'editor'));
    ?>
&nbsp;&nbsp;&nbsp;&nbsp;" onclick="saveForm('saveclose');" />
						<input type="button" class="button" value="<?php 
    echo $site->sys_sona(array('sona' => 'Close', 'tyyp' => 'editor'));
    ?>
" onclick="window.close();" />		
					</td>
				</tr>
			</table>
			
			<table cellspacing="0" cellpadding="0" class="hidden" id="upload_cancel_table">
				<tr>
					<td id="cancel_button_cell">
						<input type="button" class="button" value="<?php 
    echo $site->sys_sona(array('sona' => 'katkesta', 'tyyp' => 'editor'));
    ?>
" onclick="swfu.cancelQueue();" />		
					</td>
				</tr>
			</table>
			
		</div> <!-- / button_container -->
		
		</div> <!-- / size_wrapper -->
		
		</form>
	</body>
</html>

<?php 
}
function smarty_function_init_article($params, &$smarty)
{
    global $site, $leht, $template, $class_path;
    $content_template =& $leht->content_template;
    ##############
    # default values
    extract($params);
    if (!isset($id)) {
        $id = $leht->id;
    }
    if ($system_message || $system_alias) {
        $system_message = $system_alias ? $system_alias : $system_message;
        $id = $site->alias(array('key' => translate_ee($system_message), 'keel' => $site->keel));
    }
    if (!isset($name)) {
        $name = "article";
    }
    // on_create statements:
    $on_create = explode(',', $on_create);
    // default on_create statements:
    $publish = 0;
    $allow_comments = $site->CONF['default_comments'];
    // cycle statements
    foreach ($on_create as $on_create_statement) {
        $on_create_statement = trim($on_create_statement);
        switch ($on_create_statement) {
            case 'publish':
                $publish = 1;
                break;
            case 'hide':
                $publish = 0;
                break;
            case 'allow_comments':
                $allow_comments = 1;
                break;
        }
    }
    # if parameter "get_object_fields" is given (may be comma sep.list), then split it to array
    if (isset($get_object_fields)) {
        $get_object_fields_arr = split(",", $get_object_fields);
        $i = 0;
        foreach ($get_object_fields_arr as $tmp) {
            $get_object_fields_arr[$i] = trim($tmp);
            $i++;
        }
    }
    ###############
    # action-buttons
    # by default show all
    if (!isset($buttons)) {
        $buttons = array("new", "edit", "hide", "move", "delete");
    } else {
        $buttons = split(",", $buttons);
    }
    if (!isset($ttyyp_id)) {
        $ttyyp_id = 0;
    }
    // system alias given but no such article, can be created under system section
    if (!$id) {
        $parent_id = $site->alias('system');
        $alamlist = new Alamlist(array('parent' => $parent_id, 'klass' => 'artikkel', 'asukoht' => $position, 'start' => 0, 'limit' => 1));
        $new_button = $alamlist->get_edit_buttons(array('tyyp_idlist' => 2, 'publish' => $publish, 'allow_comments' => $allow_comments, 'sys_alias' => $system_message));
        $smarty->assign($name . '_newbutton', $new_button);
        return;
    }
    ##############
    # luua objekt
    $objSettings = array();
    $objSettings['objekt_id'] = $id;
    $obj = new Objekt($objSettings);
    $allObjParents = $obj->get_obj_all_parents($objSettings['objekt_id']);
    if (in_array($leht->parents->list[0]->parent_id, $allObjParents)) {
        $objSettings['parent_id'] = $leht->parents->list[0]->parent_id;
        $obj = new Objekt($objSettings);
    }
    ##############
    # minna edasi vaid siis kui tegemist on artikliga
    if (!$obj->all[klass] == "artikkel") {
        # error pealkirja or smth
        # assign
        # exit;
    }
    ##############
    # load variables
    #PREVIOUS ARTICLE
    $alamlistSQL = new AlamlistSQL(array(parent => $obj->parent_id, klass => "artikkel", asukoht => 0, order => "objekt_objekt.sorteering ASC"));
    $alamlistSQL->add_where("sorteering>'" . $obj->all['sorteering'] . "'");
    $alamlist = new Alamlist(array(alamlistSQL => $alamlistSQL, start => 0, limit => 1));
    #NEXT ARTICLE
    $alamlistSQL2 = new AlamlistSQL(array(parent => $obj->parent_id, klass => "artikkel", asukoht => 0));
    $alamlistSQL2->add_where("sorteering<'" . $obj->all['sorteering'] . "'");
    $alamlist2 = new Alamlist(array(alamlistSQL => $alamlistSQL2, start => 0, limit => 1));
    $prev_art = $alamlist->next();
    $next_art = $alamlist2->next();
    $obj->id = $obj->objekt_id;
    $obj->get_object_href();
    $obj->is_selected = $leht->parents->on_parent($obj->objekt_id);
    $obj->title = $obj->pealkiri;
    $obj->date = $site->db->MySQL_ee_short($obj->all['aeg']);
    $obj->datetime = $site->db->MySQL_ee($obj->all['aeg']);
    $obj->fdate = substr($obj->all['aeg'], 0, strpos($obj->all['aeg'], ' '));
    $obj->fdatetime = $obj->all['aeg'];
    $obj->show_headline = $obj->all['on_pealkiri'];
    $obj->details_link = $site->self . '?id=' . $obj->objekt_id;
    $obj->details_title = $site->sys_sona(array(sona => "loe edasi", tyyp => "kujundus"));
    $obj->printgif = '<a href="' . $obj->href . '&op=print" onClick="avaprintaken(this.href, 600, 400, \'print\'); return false;" target=_blank><img src="' . $site->img_path . '/print_it.gif" border=0 width=19 height=18></a>';
    $obj->printlink = $site->self . '?id=' . $obj->objekt_id . '&op=print';
    # added 08.11.2002:
    $obj->comment_link = $site->self . '?id=' . $obj->objekt_id . '#comm';
    $obj->comment_title = $site->sys_sona(array(sona => "Kommentaarid", tyyp => "kujundus"));
    $obj->add_comment_link = $site->self . '?id=' . $obj->objekt_id . '#cbox';
    $obj->add_comment_title = $site->sys_sona(array(sona => "Add", tyyp => "kujundus"));
    # existing already by default: $obj->comment_count
    $obj->forum_allowed = $obj->all[on_foorum];
    $obj->last_commented_time = $site->db->MySQL_ee($obj->all['last_commented_time']);
    $obj->comment_count = $obj->all['comment_count'];
    # added 21.01.2003:
    $obj->author = $obj->all[author];
    $obj->class = translate_en($obj->all[klass]);
    # translate it to english
    $obj->next_id = $next_art->objekt_id;
    $obj->prev_id = $prev_art->objekt_id;
    $obj->hit_count = $obj->all['count'];
    ##############
    # load sisu
    $obj->load_sisu();
    if (0 && $context_start) {
        $obj->lead = $context_start . $obj->lyhi->get_text() . '</editor:context>';
        $obj->body = $context_start . $obj->sisu->get_text() . '</editor:context>';
    } else {
        $obj->lead = $obj->lyhi->get_text();
        $obj->body = $obj->sisu->get_text();
    }
    if (!$site->in_editor && $site->CONF['use_aliases'] && $site->CONF['replace_links_with_alias']) {
        $hostUrl = (empty($_SERVER['HTTPS']) ? 'http://' : 'https://') . $_SERVER['SERVER_NAME'] . $site->wwwroot . '/';
        //body urls enclosed with "
        preg_match_all('{<a[^>]+href="((' . str_replace('.', '\\.', $hostUrl) . '[^>]*|/[^>]*|index.php|)\\?([^>]*id=([0-9]+)[^>0-9]*))"[^>]*>.+</a>}Ui', $obj->body, $searchResults, PREG_SET_ORDER);
        //body urls enclosed with '
        preg_match_all("{<a[^>]+href='((" . str_replace('.', '\\.', $hostUrl) . "[^>]*|/[^>]*|index.php|)\\?([^>]*id=([0-9]+)[^>0-9]*))'[^>]*>.+</a>}Ui", $obj->body, $searchResults2, PREG_SET_ORDER);
        $searchResults = array_merge($searchResults, $searchResults2);
        //non-enclosed body urls
        preg_match_all('{<a[^>]+href=((' . str_replace('.', '\\.', $hostUrl) . '[^>]*|/[^>]*|index.php|)\\?([^>]*id=([0-9]+)[^>\\s0-9]*))(\\s+[^>]*|)>.+</a>}Ui', $obj->body, $searchResults2, PREG_SET_ORDER);
        $searchResults = array_merge($searchResults, $searchResults2);
        //lead urls enclosed with "
        preg_match_all('{<a[^>]+href="((' . str_replace('.', '\\.', $hostUrl) . '[^>]*|/[^>]*|index.php|)\\?([^>]*id=([0-9]+)[^>0-9]*))"[^>]*>.+</a>}Ui', $obj->lead, $searchResults2, PREG_SET_ORDER);
        $searchResults = array_merge($searchResults, $searchResults2);
        //lead urls enclosed with '
        preg_match_all("{<a[^>]+href='((" . str_replace('.', '\\.', $hostUrl) . "[^>]*|/[^>]*|index.php|)\\?([^>]*id=([0-9]+)[^>0-9]*))'[^>]*>.+</a>}Ui", $obj->lead, $searchResults2, PREG_SET_ORDER);
        $searchResults = array_merge($searchResults, $searchResults2);
        //non-enclosed lead urls
        preg_match_all('{<a[^>]+href=((' . str_replace('.', '\\.', $hostUrl) . '[^>]*|/[^>]*|index.php|)\\?([^>]*id=([0-9]+)[^>\\s0-9]*))(\\s+[^>]*|)>.+</a>}Ui', $obj->lead, $searchResults2, PREG_SET_ORDER);
        $searchResults = array_merge($searchResults, $searchResults2);
        foreach ($searchResults as $key => $value) {
            //create an object with the id found in url
            $linkObj = new Objekt(array(objekt_id => $value[4]));
            $variables = array();
            $separator = strpos($value[3], '&amp;') !== false ? '&amp;' : '&';
            foreach (explode($separator, $value[3]) as $param) {
                $paramArray = explode('=', $param);
                if ($paramArray[0] != 'id') {
                    $variables[] = $param;
                }
            }
            if (count($variables) > 0) {
                $param = '?' . implode('&amp;', $variables);
            } else {
                $param = '';
            }
            $replaceValue = str_replace($value[1], (empty($_SERVER['HTTPS']) ? 'http://' : 'https://') . $_SERVER['SERVER_NAME'] . $linkObj->get_object_href() . $param, $value[0]);
            $obj->lead = str_replace($value[0], $replaceValue, $obj->lead);
            $obj->body = str_replace($value[0], $replaceValue, $obj->body);
        }
    }
    #############
    # buttons (must be after load_sisu(), Bug #1963)
    $obj->buttons = $obj->get_edit_buttons(array(tyyp_idlist => $obj->all['tyyp_id'], nupud => $buttons, ttyyp_id => $ttyyp_id, profile_id => $obj->all['profile_id'], publish => $publish, 'allow_comments' => $allow_comments));
    ########## KUI artiklil on Mļæ½ļæ½RATUD mļæ½ni PROFIIL, siis korja andmed "->" omadustena kokku
    if ($obj->all['profile_id']) {
        #printr($obj->objekt_id.' PROFILE_ID: '.$obj->all['profile_id']);
        include_once $class_path . 'profile.class.php';
        $obj_profile = new Profile(array("id" => $obj->all['profile_id']));
        #### 1. set profile fields as object attributes
        $obj_profile->set_obj_general_fields(array("obj" => &$obj, "get_object_fields" => $get_object_fields));
        ###################
        # get selectlist values - 1 extra sql per function; sql is fast
        if (is_array($obj_profile->selectlist)) {
            $obj_profile->selectlist = array_unique($obj_profile->selectlist);
            #printr($obj_profile->selectlist);
        }
        # go on if object values needs changing:
        if (sizeof($obj_profile->selectlist) > 0) {
            #### 2. save array "->asset_names"  human readable NAME-s:
            $obj_profile->get_asset_names(array("selectlist" => $obj_profile->selectlist));
            #printr($obj_profile->asset_names);
            #printr($obj_profile->change_fields);
            ### 3. save object rest of attributes
            #print "<br>muuta ID: ".$obj->id;
            $obj_profile->set_obj_selectlist_fields(array("obj" => &$obj, "change_fields" => $obj_profile->change_fields));
        }
        # if any selectvalue exist & need to change
        # / get selectlist values
        ###################
    }
    ####### / profile is set
    $obj->created_user_id = $obj->all['created_user_id'];
    $obj->created_user_name = $obj->all['created_user_name'];
    $obj->changed_user_id = $obj->all['changed_user_id'];
    $obj->changed_user_name = $obj->all['changed_user_name'];
    $obj->created_time = $site->db->MySQL_ee($obj->all['created_time']);
    $obj->fcreated_time = $obj->all['created_time'];
    $obj->changed_time = $site->db->MySQL_ee($obj->all['changed_time']);
    $obj->fchanged_time = $obj->all['changed_time'];
    ##############
    # assign to template variables
    $smarty->assign($name, $obj);
    //return $obj; # bug #1921 # for {init_object} tag
}