<?php

// anti hack
defined('unified_panel') or exit;

// what to do
switch (@$_GET['sa'])
{
	// show list of stuff to do
	default:
		show_main_list(); // done
	break;
	
	// add a language 
	case 'add_lang':
		add_lang(); // done
	break;
	
	// ... remove one?
	case 'remove_lang':
		remove_lang(); // should I even bother?
	break;

	// add a country
	case 'add_country':
		add_country(); // done
	break;

	// remove one..
	case 'remove_country':
		remove_country(); // wont
	break;

	// Add translation for soldat.pl
	case 'add_trans':
		load_trans_fields();
		add_trans();
	break;

	// Edit translation for soldat.pl
	case 'edit_trans':
		load_trans_fields();
		edit_trans();
	break;

	// Remove translation for soldat.pl?
	case 'del_trans':
		del_trans();
	break;

	// Add an allowed action on soldat.pl
	case 'add_action':
		add_action();
	break;
	
	// Remove an allowed action on soldat.pl
	case 'del_action':
		del_action();
	break;

	// Change a menu item
	case 'menu_mod':
		menu_mod();
	break;

	// Add a menu item
	case 'menu_add':
		menu_add();
	break;

	// JSON - get list of static pages for a site
	case 'menu_get_sp':
		menu_get_sp();
	break;
}


// defs for above

// The menu of all menus
function show_main_list() {
	global $sql, $layout, $langpref2word, $url_path, $web_url;

	// For reference later on. A lot of it
	$get_sites = $sql->query("select `name`, `displayName` from `site` order by `displayName` asc");
	while (list($name, $displayName) = $sql->fetch_row($get_sites))
		$unified_sites[$name] = $displayName;
	$sql->free($get_sites);

	
	// We need tabs!
	$layout->add_dep('js', 'tab');

	// We need ajax for a few things here
	$layout->add_dep('js', 'ajax');

	// start off layout
	$layout->head('Locales');
	?>
	

	<div class="tabs_realm">
		<div class="tabs_list">
			<a id="link_languages" href="#languages" onclick="tabs.show_tab('languages', this);" class="tabs_link">Languages</a>			
			<a id="link_countries" href="#countries" onclick="tabs.show_tab('countries', this);" class="tabs_link">Countries</a>			
			<a id="link_translations" href="#translations" onclick="tabs.show_tab('translations', this);" class="tabs_link">Unified Translations</a>			
			<a id="link_core_actions" href="#core_actions" onclick="tabs.show_tab('core_actions', this);" class="tabs_link">Unified Core Actions</a>			
			<a id="link_unified_menu" href="#unified_menu" onclick="tabs.show_tab('unified_menu', this);" class="tabs_link">Unified Menu</a>			
		</div>
		<div class="tabs_pages">

			<div class="option_tab" id="languages">
				<h2>Languages</h2>

				<table>
					<colgroup>
						<col style="width: 50%;">
						<col style="width: 50%;">
					</colgroup>
					<tr>
						<th>Abbreviation</th>
						<th>Full Name</th>
					</tr>
				
				<?php
				
				$alt = false;
				
				foreach ($langpref2word as $k => $v)
				{
					?>
					
					<tr<?=( $alt ? ' class="alt"' : '' )?>>
						<td><?=$k?></td>
						<td><?=$v?></td>
					</tr>
					
					<?php
				
					$alt = !$alt;
				}
					
				?>
					
				</table>
				<form action="<?=$url_path.'?action='.SITE_ACTION?>;sa=add_lang" method="post">
					<div class="small_form">
						Add  &mdash; 
						<label for="abreve">Two letter abbreviation:</label>
						<input size="2" type="text" id="abreve" name="abreve" maxlength="2">
						<label for="lang_name">Full name. <span class="protip">(Eg: Russian)</span>:</label>
						<input type="text" id="lang_name" name="lang_name">
						<input type="submit" class="btn" value="Add">
					</div>
				</form>
			</div>
			<div class="option_tab" id="countries">
				<h2>Countries</h2>

				<table>
					<colgroup>
						<col style="width: 50%;">
						<col style="width: 50%;">
					</colgroup>
					<tr>
						<th>Abbreviation</th>
						<th>Full Name</th>
					</tr>
				
				<?php
				
				$get = $sql->query("select `code`, `name` from `country` order by `name` asc");	
				
				for ($i = 0; list($k, $v) = $sql->fetch_row($get); $i++):

				?>

				<tr<?=($i % 2 ? ' class="alt"' : '')?>>
					<td><?=$k?></td>
					<td><?=$v?></td>
				</tr>
					

				<?php endfor; $sql->freelast(); ?>

				</table>
				<form action="<?=$url_path.'?action='.SITE_ACTION?>;sa=add_country" method="post">
					<div class="small_form">
						Add  &mdash; 
						<label for="country_abreve">Two letter abbreviation:</label>
						<input size="2" type="text" id="country_abreve" name="country_abreve" maxlength="2">
						<label for="country_name">Full name. <span class="protip">(Eg: Italy)</span>:</label>
						<input type="text" id="country_name" name="country_name">
						<input type="submit" class="btn" value="Add">
					</div>
				</form>
			</div>
			<div class="option_tab" id="translations">

				<h2>Translations on unified sites</h2>
				
				<table>
					<colgroup>
						<col style="width: 45%;">
						<col style="width: 45%;">
						<col style="width: 10%; text-align: right;">
					</colgroup>
					<tr>
						<th>Site</th>
						<th>Language</th>
						<th>Manage</th>
					</tr>
				
				<?php
					$get = $sql->query("
						select distinct `site` , `language` from `trans`
						");

					for ($i = 0; list($site, $lang) = $sql->fetch_row($get); $i++):
				?>
					
					<tr<?=($i % 2 ? ' class="alt"' : '')?>>
						<td><?=stringprep($site)?></td>
						<td><?=stringprep($lang)?></td>
						<td><a href="<?=$url_path.'?action='.SITE_ACTION?>;sa=edit_trans;site=<?=$site?>;lang=<?=$lang?>">Edit</a></td>
					</tr>

				<?php endfor; $sql->freelast(); ?>

				</table>

				<form action="<?=$url_path.'?action='.SITE_ACTION?>;sa=add_trans" method="post">
					<div class="small_form">
						Add &mdash; 
						<label for="trans_site">Site:</label>
						<select id="trans_site" name="trans_site">
							<option value="">Choose</option>
							<?php
								$get = $sql->query("select `name`, `displayName` from `site` order by `displayName` asc");
								while (list($name, $displayName) = $sql->fetch_row($get)):
							?>
								<option value="<?=$name?>"><?=$displayName?></option>
							<?php endwhile; $sql->freelast(); ?>
						</select>
						<label for="trans_lang">Language:</label>
						<select id="trans_lang" name="trans_lang">
							<option value="">Choose</option>
							<?php
								$get = $sql->query("select `code`, `name` from `language` order by `name` asc");
								while (list($code, $name) = $sql->fetch_row($get)):
							?>
								<option value="<?=$code?>"><?=$name?></option>
							<?php endwhile; $sql->freelast(); ?>
						</select>
						<input type="submit" value="Add">
					</div>
				</form>
			</div>
			<div class="option_tab" id="core_actions">
				<h2>Unified Core Actions</h2>
				<p>
					Careful, editing/removing these will break things.
					And you cannot disallow/allow the global actions, like those used for logging in/out, registering, account management, etc.
					The 'home' action canot be removed, as it is the default.
				</p>

				<table>
					<colgroup>
						<col style="width: 45%;">
						<col style="width: 45%;">
						<col style="width: 10%;">
					</colgroup>
					<tr>
						<th>Site</th>
						<th>Action</th>
						<th>Manage</th>
					</tr>
				
				<?php
					$get = $sql->query("
						select
							sa.`action`,
							s.`displayName`
						from
							`site_actions` as sa
							join `site` as s on s.`name` = sa.`site`
					");

					for ($i = 0; list($act, $site) = $sql->fetch_row($get); $i++):
				?>
					
					<tr<?=($i % 2 ? ' class="alt"' : '')?>>
						<td><?=$site?></td>
						<td><?=$act?></td>
						<td><a href="<?=$web_url?>?action=<?=SITE_ACTION?>;sa=del_action;site=<?=$site?>;act=<?=$act?>;<?=URL_VERIFIER?>">Delete</a></td>
					</tr>

				<?php endfor; $sql->free($get); ?>

				</table>

				<form action="<?=$url_path.'?action='.SITE_ACTION?>;sa=add_action" method="post">
					<div class="small_form">
						Add &mdash; 
						<label for="act_site">Site:</label>
						<select id="act_site" name="act_site">
							<option value="">Choose</option>
							<?php
								foreach ($unified_sites as $name => $displayName):
							?>
								<option value="<?=$name?>"><?=$displayName?></option>
							<?php endforeach; ?>
						</select>
						<label for="act_act">Action:</label>
						<input type="text" id="act_act" name="act_act">
						<input type="submit" value="Add">
					</div>
				</form>
			</div>
			<div class="option_tab" id="unified_menu">
				<h2>Unified Menu</h2>
				<table>
					<tr>
						<th>Site</th>
						<th>Section</th>
						<th>Link</th>
						<th>Action</th>
						<th>URL</th>
						<th style="text-align: right;">Mod</th>
					</tr>
					<?php
						
						// get / display them
						$get = $sql->query("
							select
								m1.`site`,
								m1.`section_tranid`,
								m1.`title_tranid`,
								m1.`act`,
								m1.`url`,
								m1.`order`,
								(select max(`order`) from `menu` where `site` = m1.`site` and `section_tranid` = m1.`section_tranid`  group by `section_tranid`) as max_order,
								(select min(`order`) from `menu` where `site` = m1.`site` and `section_tranid` = m1.`section_tranid`  group by `section_tranid`) as min_order
							from
								`menu` as m1
							order by
								m1.`site` asc,
								m1.`section_tranid` desc,
								m1.`order` asc
						");
						
						$last_site = '';
						$last_sect = '';

						for ($i = false, $j = 0; $link = $sql->fetch_assoc($get); $i = !$i, $j++): 
							
							// Each new section or site send out a divider
							if ($j > 0 && ($link['site'] != $last_site || $link['section_tranid'] != $last_sect)) {
								echo '<tr><td colspan="6" style="text-align: center;">&mdash;</td></tr>';
								$i = true;
							}

							// Get the url to the mod part done here to preserve clarity later
							$mod_url = $web_url.'?action='.SITE_ACTION.';sa=menu_mod;'.URL_VERIFIER.';site='.$link['site'].';sect='.$link['section_tranid'].';title='.$link['title_tranid'].';area=';
							
							// Stuff between  brackets needs to be emphasized
							$url = preg_replace('/{([^}]+)}/', '<strong class="fade">{$1}</strong>', $link['url']);

						?>
					<tr<?=($i  ? ' class="alt"' : '')?>>
						<td><?=$link['site']?></td>
						<td><?=$link['section_tranid']?></td>
						<td><?=$link['title_tranid']?></td>
						<td><?=$link['act']?></td>
						<td><?=$url?></td>
						<td style="text-align: right;">
							<?=($link['order'] > $link['min_order'] ? '<a href="'.$mod_url.'mv_up" title="Move up">&uarr;</a>' : '<span class="fade">&uarr;</span>')?>	
							<?=($link['order'] < $link['max_order'] ? '<a href="'.$mod_url.'mv_down" title="Move down">&darr;</a>' : '<span class="fade">&darr;</span>')?>
							<a title="Remove" href="<?=$mod_url?>remove" onclick="return confirm('Are you sure?')">X</a>
						</td>
					</tr>

						<?php
						
							// For next time around
							$last_site = $link['site'];
							$last_sect = $link['section_tranid'];

						endfor;

					?>
				</table>
				<script type="text/javascript">
					function get_static_pages(site) {
						if (site == '') {
							document.getElementById('add_link_sp_pages').disabled = true;
							document.getElementById('add_link_sp_btn').disabled = true;
							return;
						}
						var url = '<?=$web_url?>?action=<?=SITE_ACTION?>;sa=menu_get_sp;site='+site+';<?=URL_VERIFIER?>';
						var ajax_handle = grab_ajax_handle();
						ajax_handle.open('GET', url, true);
						ajax_handle.onreadystatechange = function () {
							if (ajax_handle.readyState == 4 && ajax_handle.status == 200) {
								var results = JSON.parse(ajax_handle.responseText);
								if (results.length == 0) {
									document.getElementById('add_link_sp_pages').disabled = true;
									document.getElementById('add_link_sp_btn').disabled = true;
									alert('No static pages are currently in site '+site);
									return;
								}
								populate_select(document.getElementById('add_link_sp_pages'), results);
							}
						};
						ajax_handle.send(null);
					}

					function handle_link_sp_add(form) {
						return (form.add_link_sp_site.value != '' && form.add_link_sp_pages.value != '');
					}

					function add_link_sp_pages_change(field) {
						document.getElementById('add_link_sp_btn').disabled = (field.value == '');	
					}
				</script>
				<h3>Add Link</h3>
				<div style="overflow: hidden; margin: 0px 5px;">
					<div style="width: 50%; float: left;">
						<fieldset>
							<legend>To Static Page</legend>
							<form onsubmit="return handle_link_sp_add(this);" action="<?=$web_url?>?action=<?=SITE_ACTION?>;sa=menu_add;type=static_page" method="post">
								<select onchange="get_static_pages(this.value);" style="width: 40%;" name="add_link_sp_site" class="small">
									<option selected="selected" value="">Pick Site</option>
								<?php
									foreach ($unified_sites as $name => $displayName):
								?>
									<option value="<?=$name?>"><?=$displayName?></option>
								<?php endforeach; ?>
								</select>
								<select onchange="add_link_sp_pages_change(this);" class="small" style="width: 40%;" disabled="disabled"
									name="add_link_sp_pages"
										id="add_link_sp_pages">

									<option selected="selected" value="">Pick Page</option>
								</select><br>
								<label class="p_abs" for="add_link_sp_sect">Section: </label>
								<input class="p_rel" style="left: 40px;" type="text" id="add_link_sp_sect" name="add_link_sp_sect"><br>
								<label class="p_abs" for="add_link_sp_trans">Link: </label>
								<input class="p_rel" style="left: 40px;" type="text" id="add_link_sp_trans" name="add_link_sp_trans"><br>
								<input type="submit" value="Add Link" disabled="disabled" id="add_link_sp_btn">
							</form>
						</fieldset>
					</div>
					<div style="width: 50%; float: left;">
						<fieldset>
							<legend>To Somewhere Else</legend>
							<form action="<?=$web_url?>?action=<?=SITE_ACTION?>;sa=menu_add;type=manual" method="post">
								<label class="p_abs" for="add_link_m_site">Site:</label>
								<select class="p_rel small" style="left: 40px;" id="add_link_m_site" name="add_link_m_site">
									<option selected="selected" value="">Pick Site</option>
								<?php foreach ($unified_sites as $name => $displayName): ?>
									<option value="<?=$name?>"><?=$displayName?></option>
								<?php endforeach; ?>
								</select><br>
								<label class="p_abs" for="add_link_m_sect">Section:</label>
								<input class="p_rel" style="left: 40px;" type="text" id="add_link_m_sect" name="add_link_m_sect"><br>
								<label class="p_abs" for="add_link_m_trans">Link:</label>
								<input class="p_rel" style="left: 40px;" type="text" id="add_link_m_trans" name="add_link_m_trans"><br>
								<label class="p_abs" for="add_link_m_url">URL:</label>
								<input class="p_rel" style="left: 40px;" type="text" id="add_link_m_url" name="add_link_m_url"><br>
								<label class="p_abs fade" for="add_link_m_act">Action:</label>
								<input class="p_rel" style="left: 40px;" type="text" id="add_link_m_act" name="add_link_m_act"><br>
								<input type="submit" value="Add Link">
							</form>
						</fieldset>
					</div>
				</div>
				<h3>Notes</h3>
				<ul>
					<li>These are sortable and reside to the left of unified pages.</li>
					<li>The Site and Section names refer to keys in the translations for each language.</li>
					<li>The Link section and field refer to keys starting with 'menu.' for each language.</li>
					<li><em>{web_full_url}</em> is automatically replaced with the url to the site, including language section and trailing slash.</li>
					<li>
						Action refers to what state the site is in that enables the link to look active. Pipes give options; amperstands
						give requirments. Ones with equal signs mean that a certain key under $_REQUEST must equal a value.
						It's also optional, especially with the manually defined links. 
					</li>
				</ul>
			</div>
		</div>	
	</div>
	
	<script type="text/javascript">
		// Attempt to get current tab via url
		if (!tabs.url_tab()) {
			// If not, default to languages
			tabs.show_tab('languages', document.getElementById('link_languages'));
		}

	</script>

	<?php
	// end layout
	$layout->foot();
}

// add a language
function add_lang() {
	global $sql, $layout, $langpref2word, $url_path;

	// get stuff
	$lang_code = strtolower(trim($sql->prot($_POST['abreve'])));
	$lang_word = trim($sql->prot($_POST['lang_name']));
	
	// fields filled out
	if ($lang_code == '' || $lang_word == '')
		$layout->error_message('Fields not filled out');
	
	// validate the code
	if (!preg_match('/^[a-z]{2}$/i', $lang_code))
		$layout->error_message('Invalid two letter abbreviation. Must be two letters.');

	// see if we already have language word
	if (in_array($lang_word, $langpref2word))
		$layout->error_message('We already have a language with that name');
	
	// see if we already have language code
	if (array_key_exists($lang_code, $langpref2word))
		$layout->error_message('We already have a language with that abbreviation');

	// seems ok; add it
	$sql->query("insert into `language` set `code` = '$lang_code', `name` = '$lang_word'");

	// go back
	redirect($url_path.'?action='.SITE_ACTION.'#languages');
}

function add_country() {

	global $sql, $layout;

	// get stuff
	$country_code = strtolower(trim($sql->prot($_POST['country_abreve'])));
	$country_word = trim($sql->prot($_POST['country_name']));
	
	// fields filled out
	if ($country_code == '' || $country_word == '')
		$layout->error_message('Fields not filled out');
	
	// validate the code
	if (!preg_match('/^[a-z]{2}$/i', $country_code ))
		$layout->error_message('Invalid two letter abbreviation. Must be two letters.');

	// seems ok; add it
	$sql->query("insert into `country` set `code` = '$country_code', `name` = '$country_word'");

	// go back
	redirect($url_path.'?action='.SITE_ACTION.'#countries');

}

// will we ever?
function remove_lang() {
	echo 'deliberately not implemented';
}

// will we ever?
function remove_country() {
	echo 'also deliberately not implemented';
}

// Add translation to soldat.pl
function add_trans() {

	global $sql, $layout, $web_url, $translation_fields;

	// Get input
	$site = $sql->prot(trim($_POST['trans_site']));
	$language = $sql->prot(trim($_POST['trans_lang']));

	// Make sure both exist
	if (
		$sql->num($sql->query("select null from `site` where `name` = '$site' limit 1")) == 0 || 
		$sql->num($sql->query("select null from `language` where `code` = '$language' limit 1")) == 0) {
			$sql->freelast();
			$layout->error_message('Nonexistant lang or site.');
	}

	// They do. 

	// Do we already have this translation?
	if ($sql->num($sql->query("select null from `trans` where `language` = '$language' and `site` = '$site' limit 1")) == 1) {
		// If so, go to it
		$sql->freelast();
		redirect('?action='.SITE_ACTION.';sa=edit_trans;site='.$site.';lang='.$language);
	}

	// No, we don't.

	// Let's get pretty. Get full names for site and language we're dealing with
	list($site_, $language_) = $sql->fetch_row($sql->query("
		select
			(select `name` from `language` where `code` = '$language' limit 1),
			(select `displayName` from `site` where `name` = '$site' limit 1)
	"));
	$sql->freelast();

	// form not submitted? Show it
	if ($_POST['do_add'] != 'yes') {
		
		// Need some javascript here
		$layout->add_dep('js', 'dom');

		// Header part of layout
		$layout->head('Add '.$language_.' translation for '.$site_.'');
	
		// Show form
		echo '
		<form action="'.$web_url.'?action=locales;sa=add_trans" method="post">
			<div id="trans_holder">
				<div id="field_storm">
					<input type="hidden" name="do_add" value="yes">
					<input type="hidden" name="trans_site" id="trans_site" value="'.$site.'">
					<input type="hidden" name="trans_lang" id="trans_lang" value="'.$language.'">
				';

		// Fields
		$alt = true;
		foreach ($translation_fields as $k => $v) {
			$k = htmlentities($k);
			$v = htmlentities($v);
			echo '<div class="trans_txt',$alt ? ' alt' : '','">
						<label for="trans['.$k.']">'.$k.'</label>
						<input class="val" type="text" id="trans['.$k.']" name="trans['.$k.']">
						<div class="note">Info: '.$v.'</div>
					</div>
					';
			$alt = !$alt;
		}
	
		echo '
				</div>
				<script type="text/javascript">
					alt = ',$alt ? 'true' : 'false',';
					new_id = 0;
					function add_field() {
						// Snag box of fields
						fields = document.getElementById("field_storm");
						
						// Create row
						cur_box = create_element("div", "", [["class", "trans_txt"+(alt ? " alt" : "")]], "", fields);

						// Create inputs 
						create_element("input", "trans_new_k["+new_id+"]", [["class","fid"]], "", cur_box);
						create_element("input", "trans_new_v["+new_id+"]", [["class","val"]], "", cur_box);

						// Alterate bg color
						alt = !alt;

						// Get next key/val id ready
						new_id++;
					}
				</script>
				<input style="margin: 10px;" type="submit" value="Save Changes">
				<input style="margin: 10px; float: right;" type="button" value="Add Field" onclick="add_field();">
			</div>
		</form>';



		// End footer 
		$layout->foot();
		exit;
	}

	// Deal with values
	foreach ((array)$_POST['trans'] as $k => $v)  {

		// Disallow blanks completely
		$k = trim($k);
		$v = trim($v);
		
		// Save if it's not blank
		if ($v != '' && $k != '') {
			
			// Get them escaped for db
			$k_ = $sql->prot($k);
			$v_ = $sql->prot($v);

			// Insert
			$sql->query("insert ignore into `trans` set `site` = '$site', `language` = '$language', `key` = '$k_', `value` = '$v_'");
		}
	}

	// Custom ones
	foreach((array)$_POST['trans_new_k'] as $n => $rubbish) {

		// Disallow blanks completely
		$k = trim($_POST['trans_new_k'][$n]);
		$v = trim($_POST['trans_new_v'][$n]);

		// Update if it's not blank, is new, or is different than current version
		if ($v != '' && $k != '') {

			// Get them escaped for db
			$k_ = $sql->prot($k);
			$v_ = $sql->prot($v);

			// Insert
			$sql->query("insert ignore into `trans` set `site` = '$site', `language` = '$language', `key` = '$k_', `value` = '$v_'");
		}
	}

	// Done. Go back
	redirect($url_path.'?action='.SITE_ACTION.';sa=edit_trans;lang='.$language.';site='.$site.';upd=1');
}

// Edit translation for soldat.pl
function edit_trans() {

	global $sql, $layout, $translation_fields;

	// Need some javascript here
	$layout->add_dep('js', 'dom');

	// Get input
	$site = $sql->prot(trim($_GET['site']));
	$language = $sql->prot(trim($_GET['lang']));
	
	// Hold current values
	$current_values = array();

	// Get existing values. And check if it exists.
	$get = $sql->query("select `key`, `value` from `trans` where `language` = '$language' and `site` = '$site'");

	// See if it exists
	if ($sql->num($get) == 0)
		$layout->error_message('Does not exist');

	// do it
	while (list($k, $v) = $sql->fetch_row($get))
		$current_values[trim($k)] = trim($v);

	// Done
	$sql->free($get);

	// Form not submitted? Show it
	if ($_POST['do_update'] != 'yes') {

		// Header
		$layout->head('Editing lang '.$language.' for '.$site.'');
	
		// Updated successfully?
		if ($_GET['upd'] == 1)
			echo '<div class="notif_good">Updated Successfully</div>';

		// Show form
		echo '
		<form action="?action=locales;sa=edit_trans;lang='.$language.';site='.$site.'" method="post">
			<div id="trans_holder">
				<div id="field_storm">
					<input type="hidden" name="do_update" value="yes">
				';

		// Fields to edit
		$alt = true;
		foreach($current_values as $k => $v) {
			$k = htmlentities($k);
			$v = htmlentities($v);
			echo '<div class="trans_txt',$alt ? ' alt' : '','">
						<label for="trans['.$k.']">'.$k.'</label>
						<input class="val" type="text" id="trans['.$k.']" name="trans['.$k.']" value="'.$v.'">
						<div class="note"></div>
					</div>
					';
			$alt = !$alt;
		}

		echo '
				</div>
				<script type="text/javascript">
					alt = ',$alt ? 'true' : 'false',';
					new_id = 0;
					function add_field() {
						// Snag box of fields
						fields = document.getElementById("field_storm");
						
						// Create row
						cur_box = create_element("div", "", [["class", "trans_txt"+(alt ? " alt" : "")]], "", fields);

						// Create inputs 
						create_element("input", "trans_new_k["+new_id+"]", [["class","fid"]], "", cur_box);
						create_element("input", "trans_new_v["+new_id+"]", [["class","val"]], "", cur_box);

						// Alterate bg color
						alt = !alt;

						// Get next key/val id ready
						new_id++;
					}
				</script>
				<input style="margin: 10px;" type="submit" value="Save Changes">
				<input style="margin: 10px; float: right;" type="button" value="Add Field" onclick="add_field();">
			</div>
		</form>
		';
		
		// Footer
		$layout->foot();
		
		exit;
	}

	// Form submitted. 

	// Go through..
	foreach ((array)$_POST['trans'] as $k => $v)  {

		// Disallow blanks completely
		$k = trim($k);
		$v = trim($v);
		
		// Update if it's not blank, is new, or is different than current version
		if ($v != '' && $k != '' && (!array_key_exists($k, $current_values) || $v != $current_values[$k])) {
			
			// Get them escaped for db
			$k_ = $sql->prot($k);
			$v_ = $sql->prot($v);

			// Either update current or insert new
			if (array_key_exists($k, $current_values))
				$sql->query("update `trans` set `value` = '$v_' where `site` = '$site' and `language` = '$language' and `key` = '$k_'");
			else
				$sql->query("insert ignore into `trans` set `site` = '$site', `language` = '$language', `key` = '$k_', `value` = '$v_'");
		}
	}

	// Custom ones
	foreach((array)$_POST['trans_new_k'] as $n => $rubbish) {

		// Disallow blanks completely
		$k = trim($_POST['trans_new_k'][$n]);
		$v = trim($_POST['trans_new_v'][$n]);

		// Update if it's not blank, is new, or is different than current version
		if ($v != '' && $k != '' && (!array_key_exists($k, $current_values) || $v != $current_values[$k])) {

			// Get them escaped for db
			$k_ = $sql->prot($k);
			$v_ = $sql->prot($v);

			// Either update current or insert new
			if (array_key_exists($k, $current_values))
				$sql->query("update `trans` set `value` = '$v_' where `site` = '$site' and `language` = '$language' and `key` = '$k_'");
			else
				$sql->query("insert ignore into `trans` set `site` = '$site', `language` = '$language', `key` = '$k_', `value` = '$v_'");
		}
	}

	// Done. Go back
	redirect($url_path.'?action='.SITE_ACTION.';sa=edit_trans;lang='.$language.';site='.$site.';upd=1');

}

// Remove translation for soldat.pl
function del_trans() {}

// Get the giant list of translations fields..
function load_trans_fields() {

	// So we can get to it anywhere
	global $translation_fields, $sql;

	// Get english fields and default values
	$get = $sql->query("select `key`, `value` from `trans` where `language` = 'en' and `site` = 'soldat'");

	// do it
	while (list($k, $v) = $sql->fetch_row($get))
		$translation_fields[$k] = $v;

	// Done
	$sql->free($get);
}

// Add an allowed action for a site on soldat.pl
function add_action() {

	global $sql, $layout;

	// get them
	$site = $sql->prot(trim($_POST['act_site']));
	$act = $sql->prot(trim($_POST['act_act']));

	// Can't be blank
	if ($site == '' || $act == '')
		$layout->error_message('Cannot be blank.');

	// Make sure site exists
	if ($sql->num($sql->query("select null from `site` where `name` = '$site' limit 1")) == 0)
		$layout->error_message('That site does not exist.');

	// Anti hack
	if (!preg_match('/^[a-z0-9\-\_]+$/i', $act))
		$layout->error_message('Only numbers, letters, underscores, and dashes allowed.');

	// Retard check
	if ($act == 'home')
		$layout->error_message('`home` is non-negotiable and mandatory.');

	// pft
	$sql->query("insert ignore into `site_actions` set `site` = '$site', `action` = '$act'");

	// mk
	redirect($web_url.'?action='.SITE_ACTION.'#core_actions');

}

// Remove an allowed action for a site on soldat.pl
function del_action() {
	global $sql, $layout, $ui;

	// Must be a real valid request.
	$ui->require_verification();

	// get what to kill
	$site = $sql->prot(trim($_GET['site']));
	$action = $sql->prot(trim($_GET['act']));

	// kill it
	$sql->query("delete from `site_actions` where `site` = '$site' and `action` = '$action' limit 1");

	// mk
	redirect($web_url.'?action='.SITE_ACTION.'#core_actions');
}

// Change a menu item on soldat.pl
function menu_mod() {
	global $sql, $layout, $ui;

	// Must be a real valid request.
	$ui->require_verification();

	// Get what's needed to change a menu item
	$m_site = $sql->prot(trim($_GET['site']));
	$m_sect = $sql->prot(trim($_GET['sect']));
	$m_title = $sql->prot(trim($_GET['title']));

	// What do we want to do?
	$job = $_GET['area'];

	// Get whether or not it exists and its current order and the highest order
	$check = $sql->query("
			select
			`order`
			from
			`menu`
			where
			`site` = '$m_site' and
			`section_tranid` = '$m_sect' and
			`title_tranid` = '$m_title'
			limit 1
			");

	// Does not exist?
	if ($sql->num($check) == 0)
		$layout->error_message('Specified menu item does not exist.');

	// Get info
	list($current_order) = $sql->fetch_row($check);
	$sql->free($check);

	// If wanted, get highest order
	if ($job == 'mv_down' || $job == 'mv_up') {
		list($lowest_order, $highest_order) = $sql->fetch_row($sql->query("
					select
					(select `order` from `menu` order by `order` asc limit 1),
					(select `order` from `menu` order by `order` desc limit 1)
					"));
		$sql->freelast();
	}

	// Job?
	switch ($job) {

		// Move it up
		case 'mv_up':

			// Sanity check. Is it the lowest?
			if ($current_order <= $lowest_order)
				$layout->error_message('Cannot go any lowerr');

			// Make one below one higher
			$sql->query("update `menu` set `order` = '$current_order' where `site` = '$m_site' and `section_tranid` = '$m_sect' and `title_tranid` != '$m_title' and `order` < '$current_order' order by `order` desc limit 1");

			// Make this one one lower
			$sql->query("update `menu` set `order` = `order` - 1 where `site` = '$m_site' and `section_tranid` = '$m_sect' and `title_tranid` = '$m_title'  limit 1");

			break;

			// Move it down
		case 'mv_down':
			// Sanity check. Is it the highest?
			if ($current_order >= $highest_order)
				$layout->error_message('Cannot go any higher');

			// Make one above one lower
			$sql->query("update `menu` set `order`  = '$current_order' where `site` = '$m_site' and `section_tranid` = '$m_sect' and `title_tranid` != '$m_title' and `order` > '$current_order' order by `order` asc  limit 1");

			// Make this one one higher
			$sql->query("update `menu` set `order` = `order` + 1 where `site` = '$m_site' and `section_tranid` = '$m_sect' and `title_tranid` = '$m_title'  limit 1");

			break;

			// Kill it
		case 'remove':
			$sql->query("delete from `menu` where `site` = '$m_site' and `section_tranid` = '$m_sect' and `title_tranid` = '$m_title' limit 1");
			break;

			// Unknown?
		default:
			$layout->error_message('Unknown job');
			break;
	}

	// Done, Go back
	redirect($web_url.'?action='.SITE_ACTION.'#unified_menu');
}

// Fill static page dropdown
function menu_get_sp() {
	global $sql, $web_url, $layout, $ui;

	// Nothing fishy
	$ui->require_verification();

	// Get desired site
	$site = $sql->prot(trim($_GET['site']));

	// Get the pages
	$get = $sql->query("select replace(lower(`title`),' ', '-'), `title` from `static_pages` where `site` = '$site' order by `title` asc");

	// Hold them here
	$pages = array();

	// Stuff it
	while (list($sid, $st) = $sql->fetch_row($get))
		$pages[] = array('val' => trim(stripslashes($sid)), 'txt' => trim(stripslashes($st)));

	// Free ram that used
	$sql->free($get);

	// Send out the json encoded string with the pages for desired site
	echo json_encode($pages);
}

// Add a link to the menu
function menu_add() {
	global $sql, $web_url, $layout;

	// Which kind?
	switch ($_GET['type'])
	{
		// This is quick and easy. Just a static page. Like FAQ
		case 'static_page':

			// Get values
			$site = trim($sql->prot($_POST['add_link_sp_site']));
			$page = trim($sql->prot($_POST['add_link_sp_pages']));
			$sect = trim($sql->prot($_POST['add_link_sp_sect']));
			$trans = trim($sql->prot($_POST['add_link_sp_trans']));

			// These we auto gen
			$act = 'page&page='.$page;
			$url = '{web_full_url}page/'.$page;

			// Make sure we have what we need
			if ($site == '' || $page == '' || $sect == '' || $trans == '') 
				$layout->error_message('All fields are required for static page form.');

			// Get current highest order number for the current section/site
			$get_order = $sql->query("select `order` from `menu` where `site` = '$site' and `section_tranid` = '$sect' order by `order` desc limit 1");
			if ($sql->num($get_order) == 0) {
				// This is a new site/section, start it off as the first of its kind
				$order = 1;
			}
			else {
				list($current_order) = $sql->fetch_row($get_order);

				// One higher than current. Add it to the end. 
				$order = (int)$current_order + 1;
			}
			$sql->free($get_order);

			// Looks like it. Add it.
			$sql->query("
					insert ignore into `menu` set
					`site` = '$site',
					`section_tranid` = '$sect',
					`title_tranid` = '$trans',
					`act` = '$act',
					`url` = '$url',
					`order` = '$order'
					");

			// Go back.
			redirect($web_url.'?action='.SITE_ACTION.'#unified_menu');
			break;

			// For those who know what they're doing. Like linking to an action or an external link
		case 'manual':
			// Get values
			$site = trim($sql->prot($_POST['add_link_m_site']));
			$sect = trim($sql->prot($_POST['add_link_m_sect']));
			$trans = trim($sql->prot($_POST['add_link_m_trans']));
			$action = trim($sql->prot($_POST['add_link_m_act']));
			$url = trim($sql->prot($_POST['add_link_m_url']));

			// Must have lots
			if ($site == '' || $sect == '' || $trans == '' || $url == '')
				$layout->error_message('Missing fields');

			// Get current highest order number for the current section/site
			$get_order = $sql->query("select `order` from `menu` where `site` = '$site' and `section_tranid` = '$sect' order by `order` desc limit 1");
			if ($sql->num($get_order) == 0) {
				// This is a new site/section, start it off as the first of its kind
				$order = 1;
			}
			else {
				list($current_order) = $sql->fetch_row($get_order);

				// One higher than current. Add it to the end. 
				$order = (int)$current_order + 1;
			}
			$sql->free($get_order);

			// Looks like it. Add it.
			$sql->query("
					insert ignore into `menu` set
					`site` = '$site',
					`section_tranid` = '$sect',
					`title_tranid` = '$trans',
					`act` = '$action',
					`url` = '$url',
					`order` = '$order'
					");

			// Go back.
			redirect($web_url.'?action='.SITE_ACTION.'#unified_menu');


			break;

			// Unknown?
		default:
			$layout->error_message('Unknown job');
			break;
	}
}