<?php

if (has_filter('the_editor', 'qtrans_modifyRichEditor')) {
	/*Fix for qtranslate*/
	remove_filter('the_editor', 'qtrans_modifyRichEditor');
}

$wcttab2 = $_GET['wcttab2'];

if ($_POST['saveit'] == $tableid AND $_POST['saveit'] != '')
{
	if ($_GET['wcttab2'] == 'eview') { $sql = "e_setup"; }
	elseif ($_GET['wcttab2'] == 'oview') { $sql = "o_setup"; }
	elseif ($_GET['wcttab2'] == 'tview') { $sql = "t_setup"; $zusatz = ", `vortext`='".mres($_POST['wctvortext'])."', `nachtext`='".mres($_POST['wctnachtext'])."'"; }
	elseif ($_GET['wcttab2'] == 'theader') {
		foreach($_POST['wctheader'] as $var) { $header .= $var.","; }
		foreach($_POST['wctsort'] as $var) { $sort .= $var.","; }
		$zusatz = "`header`='".mres(substr($header,0,strlen($header)-1))."', `headersort`='".mres(substr($sort,0,strlen($sort)-1))."'";
		$wpdb->get_row("UPDATE `".$wpdb->prefix."wct_list` SET ".$zusatz." WHERE `id`='".$tableid."' LIMIT 1;");
	}

	if ($sql != '') {
		$table = $wpdb->get_row("UPDATE `".$wpdb->prefix."wct_list` SET `".$sql."`='".mres($_POST['content'])."'".$zusatz." WHERE `id`='".$tableid."' LIMIT 1;");
	}
}

echo "<style type=\"text/css\">
.theEditor { color: black !important; }
#editorcontainer, #quicktags { width: 720px; }
#edButtonHTML { visibility:hidden !important; }
#edButtonPreview { visibility:hidden !important; }
.ed_button2 { background-image: url(\"".plugins_url('custom-tables/img/fade-butt.png')."\") !important; }
.ed_button3 { background-image: url(\"".plugins_url('custom-tables/img/fade-butt2.png')."\") !important; }
</style>";

add_filter('admin_head','ShowTinyMCE');
function ShowTinyMCE() {
	wp_enqueue_script( 'common' );
	wp_enqueue_script( 'jquery-color' );
	wp_print_scripts('editor');
	if (function_exists('add_thickbox')) add_thickbox();
	wp_print_scripts('media-upload');
	if (function_exists('wp_tiny_mce')) wp_tiny_mce();
	wp_admin_css();
	wp_enqueue_script('utils');
	do_action("admin_print_styles-post-php");
	do_action('admin_print_styles');
}

echo "<div><h2>".__('View Setup','wct')."</h2><table vspace=\"0\" hspace=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"background-image:url(" . plugins_url('custom-tables/img/tab.png') . ");height:30px;\" ><tr>";
$table = $wpdb->get_row("SELECT * FROM `".$wpdb->prefix."wct_list` WHERE `id`='".$tableid."' LIMIT 1;");

echo $this->tab_link($wcttab,'Table Setup','setup','tview');
if ($table->headerline == '1') { echo $this->tab_link($wcttab,'Headerline Setup','setup','theader'); }
if ($tableid != '0') { echo $this->tab_link($wcttab,'Entry Setup','setup','eview'); }
echo $this->tab_link($wcttab,'Overlay Setup','setup','oview');

echo "</tr></table>
<table vspace=\"0\" hspace=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr>
<td width=\"780\" valign=\"top\"><form action=\"admin.php?page=".$_GET['page']."&wcttab=".$_GET['wcttab']."&wcttab2=".$_GET['wcttab2']."\" method=\"POST\">
<input type=\"hidden\" name=\"saveit\" value=\"".$tableid."\" />";


switch($_GET['wcttab2']) {
	case 'eview':
		echo "<h3>".__('Entry Setup', 'wct')."</h3>";
		the_editor(stripslashes($table->e_setup), $id = 'content', $prev_id = 'title', $media_buttons = false);
		$help = "<a href=\"".plugins_url('custom-tables/img/tutorial/Ansicht3.jpg')."\"><img src=\"".plugins_url('custom-tables/img/tutorial/Ansicht3_small.jpg')."\"  alt=\"Tutorial Picture\"></a><br/><br/>".
			 __('All users which will be redirected from Table Setup over the [LINK] will come to this view. You can create here your Page which will be autogenerated.<br/><br/>The <b>blue Fields</b> stays for the availalble fields in the database which you can use. You dont need to use all fields, but its recommented. Fields which are not used in this view, have proberly no usage!', 'wct')."<br/><br/><a href=\"admin.php?page=".$_GET['page']."&wcttab=setup&wcttab2=hints\">".__('More Hints', 'wct')."</a>";
		echo "<input type=\"submit\" name=\"submit\" value=\"". __('Save all Changes', 'wct') ."\">";
	break;

	case 'tview':
		echo "<h3>".__('Table Setup', 'wct')."</h3>";
		echo "<textarea name=\"wctvortext\" style=\"width:720px;\">".stripslashes($table->vortext)."</textarea>";
		if ($table->t_setup == '') { $table->t_setup = "<td></td>"; }
		the_editor(stripslashes($table->t_setup), $id = 'content', $prev_id = 'title', $media_buttons = false);
		echo "<textarea name=\"wctnachtext\" style=\"width:720px;\">".stripslashes($table->nachtext)."</textarea><br/>";
		$help = "<a href=\"".plugins_url('custom-tables/img/tutorial/Ansicht1.jpg')."\"><img src=\"".plugins_url('custom-tables/img/tutorial/Ansicht1_small.jpg')."\"  alt=\"Tutorial Picture\"></a><br/><br/>".
		__('The <b>Red TABLE</b> field need to be used for the Table definition for each line which will show the list to filter and search on the mainpage.<br/><br/>The <b>Red LINK</b> field will redirect the user on the Entry Page with can be setupd on the own configuration.<br/>If you dont link it manually, the link will be placed under the complete table line automatically.<br/><br/>The <b>blue Fields</b> stays for the availalble fields in the database. You dont need to use all fields.<br/><br/>The <b>Custom Headline</b> can be left blank if you wish, otherwise please define Name for all Cols with Comma separated.<br/><br/>The <b>Search Form</b> will search on default ot all fields, which can generate a high load on the Database. You can restrict the search to specific fields (Comma separated). Wrong written fields or not existing one will be iognored.<br/><b>*</b> Will search for all fields, possible high load on the database<br/><b>sss</b> This option will use the Search Tag from the choosed language.', 'wct')."<br/><br/><a href=\"admin.php?page=".$_GET['page']."&wcttab=setup&wcttab2=hints\">".__('More Hints', 'wct')."</a>";
		echo "<input type=\"submit\" name=\"submit\" value=\"". __('Save all Changes', 'wct') ."\"><br/><br/>";
		if ($tableid != '1') { $g = " id=\"".$tableid."\""; $l ='16'; } else { $l = '8'; }
		printf( __('This Table can be added with %s or %s to the page.', 'wct')."</br>", '<input type=\'text\' value=\'[wctable id="'.$tableid.'" limit="50"]\' size=\'27\' readonly/>', '<input type=\'text\' value=\'[wctable'.$g.']\' size=\''.$l.'\' readonly/>');
		printf( __('This Searchform for this table with %s or %s to the page.', 'wct')."<br/>", '<input type=\'text\' value=\'[wctsearch felder="*" text="sss"]\' size=\'34\' readonly/>', '<input type=\'text\' value=\'[wctsearch]\' size=\'11\' readonly/>');
		printf( __('Dropdown Menus for filtering on Categories can be add with %s or %s to the page.', 'wct'), '<input type=\'text\' value=\'[wctselect id="1" field="???" limit="20" maintext="title"]\' size=\'56\' readonly/>', '<input type=\'text\' value=\'[wctselect field="???"]\' size=\'22\' readonly/>');

	break;

	case 'theader':
		echo "<h3>".__('Headerline Setup', 'wct')."</h3><table><tr><td><b>".__('Your Content','wct')."</b></td><td><b>".__('Field Name','wct')."</b></td><td>&nbsp;</td><td><b>".__('Sort field','wct')."</b></td></tr>";

		$inhalt = stripslashes($table->t_setup);
		if (preg_match('/.*-->(.*?)<!--:--.*/',$inhalt)) {
			preg_match('/.*-->(.*?)<!--:--.*/',$inhalt, $treffer);
			$inhalt = $treffer[1];
		}

		if ($tableid != '0') {
			$tablet = $wpdb->get_row("SHOW CREATE TABLE `".$wpdb->prefix."wct".$tableid."`;");
			$array=array(); foreach($tablet as $member=>$data) { $array[$member]=$data; }
			$felder = explode("PRIMARY KEY",$array['Create Table']);
			$felder = array_slice(explode("`",$felder[0]),5);
			for ($x=0;$felder[$x] !='';$x++) {
				$f[] = $felder[$x];
				$x++;
			}
		}
		else {
			$f = array('author','date','title','kategory','comment_count');
		}

		$headerfields = explode(",",$table->header);
		$headerfieldss = explode(",",$table->headersort);

		$y = '0';
		$felderm = array_slice(explode("<td>",$inhalt),1);
		foreach ($felderm as $feld) {
			echo "<tr><td>".str_replace("</td>","",$feld)."</td><td><input name=\"wctheader[]\" type=\"text\" value=\"".htmlentities(stripslashes($headerfields[$y]), ENT_QUOTES)."\" size=\"72\"></td>";
			echo "<td>&nbsp;</td><td><select name=\"wctsort[]\"><option value=\"\">-- ".__('none','wct')." --</option>";
			foreach ($f as $var) {
				echo "<option value=\"".$var."\"";
				if ($headerfieldss[$y] == $var) { echo " selected"; }
				echo ">".$var."</option>";
			}
			echo "</select></td></tr>";
			$y++;
		}

		echo "</table><br/><input type=\"submit\" name=\"submit\" value=\"". __('Save all Changes', 'wct') ."\"><br/><br/>";
		printf( __('Dropdown Menus for filtering on Categories can be add with %s or %s to the page.', 'wct'), '<input type=\'text\' value=\'[wctselect id="1" field="???" limit="20" maintext="title"]\' size=\'56\' readonly/>', '<input type=\'text\' value=\'[wctselect field="???"]\' size=\'22\' readonly/>');

		$help = "<a href=\"".plugins_url('custom-tables/img/tutorial/Ansicht2.jpg')."\"><img src=\"".plugins_url('custom-tables/img/tutorial/Ansicht2_small.jpg')."\"  alt=\"Tutorial Picture\"></a><br/><br/>".
		        "* ".__('<b>Attention:</b> This Option should only be activated on Categories (Bar, Restaurant) or Selectionsfields (City, Country) and not FreeText fields with many diffrent Entries, or Performance and Usability are very bad! Don\'t select if you don\'t know what you are doing.','wct');
	break;

	case 'oview':
		echo "<h3>".__('Overlay Setup', 'wct')."</h3>";

		the_editor(stripslashes($table->o_setup), $id = 'content', $prev_id = 'title', $media_buttons = false);
		$help = "<a href=\"".plugins_url('custom-tables/img/tutorial/Ansicht4.jpg')."\"><img src=\"".plugins_url('custom-tables/img/tutorial/Ansicht4_small.jpg')."\"  alt=\"Tutorial Picture\"></a><br/><br/>".
			 __('This View will be shown, if a user get with the mousecurser over an entry of the Table. With a click, the user gets redirected to the Entry Page.', 'wct')."<br/><br/><a href=\"admin.php?page=".$_GET['page']."&wcttab=setup&wcttab2=hints\">".__('More Hints', 'wct')."</a>";

		if ($table->overlay != '1') {
			echo "<font color=\"#FF0000\"><strong>".__('Overlay not activated for this table, this setup will have no effect! Please use \'Table Setup\' to activate it.', 'wct')."</strong></font><br/>";
		}
		echo "<input type=\"submit\" name=\"submit\" value=\"". __('Save all Changes', 'wct') ."\">";
	break;

	case 'hints':
		echo "<h3>".__('Setup Hints', 'wct')."</h3>";
		echo __('You can customize the all Views with HTML to everything you want. There are no limitations, except your own HTML knowledge. Down here are 2 simple Examples.<br/><br/><b>To add a picture</b><LU><li>Create e.g. a field with the name \'img\' as varchar(64)</li><li>Create e.g. a field with the name \'imgtitle\' as varchar(32)</li><li>Upload the images for all entrys to the Mediathek</li><li>Copy of each image from the Mediathek the Link e.g. http://yourdomain.com/wp-uploads/image-lkd.jpg</li><li>Past this URL to the corresponging \'img\' field</li><li>Define \'imgtitle\' field of all entries</li><li>Use code at the setup page:', 'wct');
		echo '<input type=\'text\' value=\'&lt;img src="[img]" border="0" alt="[imgtitle]" /&gt;\' size=\'50\'></li></LU><br/>';
		echo __('<b>To add a custom link</b><LU><li>Create a DB field e.g. \'link\' as varchar(64)<br/><font color="red">'.__('Please notice, if you call a field \'link\' it will replace the internal page creation functionality and if you click on the table line, it will redirect the user on the new link.!', 'wct').'</font></li><li>Create a DB field e.g. \'linkdescription\' as varchar(32)</li><li>Use code at the setup page:', 'wct');
		echo '<input type=\'text\' value=\'&lt;a href="[links]"&gt;[linkdescription]&lt;/a&gt;\' size=\'40\'></li></LU><br/><b>'.__('Sample what is possible' ,'wct').'</b><br/>';
	 	echo "<a href=\"".plugins_url('custom-tables/img/tutorial/DemoHausDB.jpg')."\"><img src=\"".plugins_url('custom-tables/img/tutorial/DemoHausDB_small.jpg')."\"  alt=\"Demo DB View\"></a>";
	break;

	default:
		echo "<table><tr><td><img src=\"".plugins_url('custom-tables/img/tutorial/pfeil.png')."\" alt=\"\"></td><td>&nbsp;<br/>".__('You can define here which fields are shown and how. Also the Overlay can be defined and the Entry pages.','wct').".<br/>".
		     __('Please check the submenu for more information and detailed instructions.', 'wct')."<br/>".
		     __('For more details as example how to add HTML code, please have a look on','wct').": <a href=\"admin.php?page=".$_GET['page']."&wcttab=setup&wcttab2=hints\">".__('More Hints', 'wct')."</a></td><tr></table>".
		     "<br/><h3>".__('Instructions','wct')."</h3><img src=\"".plugins_url('custom-tables/img/tutorial/Overview.jpg')."\" alt=\"\">";
	break;
}

echo "</form></td><td valign=\"top\">";
if ($help != '') { echo "<h3>" . __('Instructions', 'wct') . "</h3>".$help; }
echo "</td></table></div>";

function wct_quicktag_button() {
	global $wpdb;
	$tableid = str_replace("wct_table_","",$_GET['page']);
	echo "<script type=\"text/javascript\">
	var wct_toolbar = document.getElementById(\"ed_toolbar\");";

	if ($_GET['wcttab2'] == 'tview') {
		echo "var theButtontd = document.createElement('input');
		theButtontd.type = 'button';
		theButtontd.value = 'TABLE';
		theButtontd.onclick = cp_myentryB;
		theButtontd.className = 'ed_button3';
		theButtontd.title = 'TABLE';
		theButtontd.id = 'cp_td';
		wct_toolbar.appendChild(theButtontd);

		var theButtonlink = document.createElement('input');
		theButtonlink.type = 'button';
		theButtonlink.value = 'LINK';
		theButtonlink.onclick = cp_myentry;
		theButtonlink.className = 'ed_button3';
		theButtonlink.title = 'LINK';
		theButtonlink.id = 'cp_link';
		wct_toolbar.appendChild(theButtonlink);";
	}

	if ($_GET['wcttab2'] == 'eview') {
		echo "var theButtonlink = document.createElement('input');
		theButtonlink.type = 'button';
		theButtonlink.value = 'BACK';
		theButtonlink.onclick = cp_myentry;
		theButtonlink.className = 'ed_button3';
		theButtonlink.title = 'BACK';
		theButtonlink.id = 'cp_link';
		wct_toolbar.appendChild(theButtonlink);";
	}

	if ($tableid != '0')	{

		echo "var theButton = document.createElement('input');
		theButton.type = 'button';
		theButton.value = 'id';
		theButton.onclick = cp_myentry;
		theButton.className = 'ed_button2';
		theButton.title = 'id';
		theButton.id = 'cp_id';
		wct_toolbar.appendChild(theButton);\n";

		$table = $wpdb->get_row("SHOW CREATE TABLE `".$wpdb->prefix."wct".$tableid."`;");
		$array=array(); foreach($table as $member=>$data) { $array[$member]=$data; }
		$felder = explode(",",str_replace(array(",","8 ,2"),array(" ,","8.2"),$array['Create Table']));

		for ($i=2;$felder[$i] != '';$i++) {
			$feldoutput .= preg_replace("/`(.*)`\s.*/","var theButton$1 = document.createElement('input');\ntheButton$1.type = 'button';\ntheButton$1.value = '$1';\ntheButton$1.onclick = cp_myentry;\ntheButton$1.className = 'ed_button2';\ntheButton$1.title = '$1';\ntheButton$1.id = 'cp_$1';\nwct_toolbar.appendChild(theButton$1);\n",$felder[$i-1]);
		}
	}
	else {
		$felder = array('author','date','title','content','comment_count');
		foreach ($felder as $feld) {
			$feldoutput .= "var theButton".$feld." = document.createElement('input');\ntheButton".$feld.".type = 'button';\ntheButton".$feld.".value = '".$feld."';\ntheButton".$feld.".onclick = cp_myentry;\ntheButton".$feld.".className = 'ed_button2';\ntheButton".$feld.".title = '".$feld."';\ntheButton".$feld.".id = 'cp_".$feld."';\nwct_toolbar.appendChild(theButton".$feld.");\n";
		}
	}

	echo $feldoutput." function cp_myentry(querystr) {
		var myField = document.getElementById(\"content\");
		var myInhalt = this.value;

		if (document.selection) {
			myField.focus();
			var sel = document.selection.createRange();
			sel.text +=  \"[\" + myInhalt + \"]\";
			myField.focus();
		}
		else if (myField.selectionStart || myField.selectionStart == '0') {
			var startPos = myField.selectionStart, endPos = myField.selectionEnd, cursorPos = endPos, scrollTop = myField.scrollTop;

			if (startPos != endPos) {
				myField.value = myField.value.substring(0, startPos)
			              + myField.value.substring(startPos, endPos)
			              + \"[\" + myInhalt + \"]\"
			              + myField.value.substring(endPos, myField.value.length);
				cursorPos += edButtons[i].tagStart.length + edButtons[i].tagEnd.length;
			}
			else {

				myField.value = myField.value.substring(0, startPos)
			              + \"[\" + myInhalt + \"]\"
				       + myField.value.substring(endPos, myField.value.length);
				cursorPos = startPos + edButtons[i].tagStart.length;
			}
			myField.focus();
			myField.selectionStart = cursorPos;
			myField.selectionEnd = cursorPos;
			myField.scrollTop = scrollTop;
		}
		else {
			myField.value += \"[\" + myInhalt + \"]\";
			myField.focus();
		}
	}
	function cp_myentryB(querystr) {
		var myField = document.getElementById(\"content\");
		var myInhalt = this.value;

		if (document.selection) {
			myField.focus();
			var sel = document.selection.createRange();
			sel.text +=  \"<td></td>\";
			myField.focus();
		}
		else if (myField.selectionStart || myField.selectionStart == '0') {
			var startPos = myField.selectionStart, endPos = myField.selectionEnd, cursorPos = endPos, scrollTop = myField.scrollTop;

			if (startPos != endPos) {
				myField.value = myField.value.substring(0, startPos)
			              + myField.value.substring(startPos, endPos)
			              + \"<td></td>\"
			              + myField.value.substring(endPos, myField.value.length);
				cursorPos += edButtons[i].tagStart.length + edButtons[i].tagEnd.length;
			}
			else {

				myField.value = myField.value.substring(0, startPos)
			              + \"<td></td>\"
				       + myField.value.substring(endPos, myField.value.length);
				cursorPos = startPos + edButtons[i].tagStart.length;
			}
			myField.focus();
			myField.selectionStart = cursorPos;
			myField.selectionEnd = cursorPos;
			myField.scrollTop = scrollTop;
		}
		else {
			myField.value += \"<td></td>\";
			myField.focus();
		}
	}
	</script>";
}
add_filter('admin_footer', 'wct_quicktag_button');

?>