<?php
/******************************************************************************

	Copyright (C) 2005-2007  John Ha

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License along
	with this program; if not, write to the Free Software Foundation, Inc.,
	51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

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

if ($user_level >= 8) :
?>
function kca_dump(i) {
	var data = kca_parse_data();
	if (data) {
		data = data.split('<?= $this->kca_sep ?>');
		for (var j = i; j < i + <?= $this->kca_num_opts ?>; j++) {
			if (data[j - i + 1] != undefined) {
				var dataRef = document.getElementById('kca_' + j);
				if (dataRef.type == 'checkbox') {
					if (data[j - i + 1] == 'true') {
						dataRef.checked = true;
					} else {
						dataRef.checked = false;
					}
				} else {
					dataRef.value = data[j - i + 1];
				}
			}
		}
	}
}

function kca_save(set) {
	if (kca_submitted()) return false;
	i = (set - 1) * <?= $this->kca_num_opts ?> + 1;
	for (var j = i; j < i + <?= $this->kca_num_opts ?>; j++) {
		var dataRef = document.getElementById('kca_' + j);
		if (dataRef.type != 'checkbox' && dataRef.type != 'select-one') {
			if (dataRef.value != '') {
				if (confirm('Save [Record Set #' + set + '] to database?\n  \'OK\' to save, \'Cancel\' to abort.')) {
					kca_submit_flag = 1;
					return true;
				} else {
					return false;
				}
			}
		}
	}
	alert('Nothing to save!');
	return false;
}

// The little parsing engine that could
function kca_parse_data() {
	if (!document.getElementById('kca_scratch').value) return false;
	// Filter out crap lines first
	var s = document.getElementById('kca_scratch').value.match(/^([\t ]*\+.+|.*\=.*)$/gm);
	if (!s) return false;
	// Fill array with description names
	var desc = new Array(<?php
	for ($i = 0; $i < $this->kca_num_opts; $i++) {
		?>'<?= $this->kca_keys[$i] ?>'<?php
		echo $i < $this->kca_num_opts - 1 ? ', ' : '';
	}
	?>);
	var data = '';
	j = 0;
	c = 0;
	// Save all lines match description names or start with a (+)
	for (var i = 0; i < s.length; i++) {
		if (new RegExp('[\\t ]*' + desc[j] + '[\\t ]*\\=.*', 'i').test(s[i])) {
			data += s[i] + '\n';
			if (j < desc.length - 1) {
				j++;
			} else {
				j = 0;
				c++;
			}
		} else if (new RegExp('[\\t ]*\\+.+').test(s[i])) {
			data += s[i] + '\n';
		} else {
			break;
		}
	}
	// Description name is out of sync
	if (j || !j && !c) {
		var msg = '[Record Set #' + (c + 1) + '] in Scratch-Pad incomplete.\n';
		msg += '[' + desc[j] + '] is missing from this record set.\n';
		msg += 'Please make corrections, then try again.';
		alert(msg);
		return false;
	}
	// split up data values with $this->kca_sep
	data = data.replace(/^\w+[\t ]*\= ?/gm, '<?= $this->kca_sep ?>');
	// leading +'s
	data = data.replace(/^[\t ]*\+ ?/gm, '');
	// remove whitespace on either side of $this->kca_sep
	data = data.replace(/\s*<?= $this->kca_sep ?>\s*/gm, '<?= $this->kca_sep ?>');
	// remove trailing whitespace
	data = data.replace(/\s*$/g, '');
	return data;
}

function kca_clear(i) {
	for (var j = i; j < i + <?= $this->kca_num_opts ?>; j++) {
		var dataRef = document.getElementById('kca_' + j);
		if (dataRef.type == 'checkbox') {
			dataRef.checked = false;
		} else if (dataRef.type == 'select-one') {
			dataRef.selectedIndex = '0';
		} else {
			dataRef.value = '';
		}
	}
}

function kca_import() {
	if (document.getElementById('kca_scratch').value) {
		var data = kca_parse_data();
		if (data) {
			if (confirm('You are about to import data to the database.\n  \'OK\' to continue, \'Cancel\' to stop.')) {
				document.getElementById('import_all').value = data;
				return true;
			}
		} else {
			alert('Nothing to import! Scratch-Pad needs to contain appropriate data.');
		}
	} else {
		alert('Nothing to import! Scratch-Pad needs to contain appropriate data.');
	}
	return false;
}

function kca_load_ini() {
	var kca_ajax = new sack();
 	kca_ajax.onLoading = function () { kca_spin_wheel(1); };
	kca_ajax.onLoaded = function () { kca_spin_wheel(-1); }; 
	kca_ajax.onError = function () { kca_spin_wheel('!'); }; 
	kca_ajax.requestFile = '<?= core::urlname(dirname(__FILE__) . '/../addons/default.ini') ?>';
	kca_ajax.method = 'GET';
	kca_ajax.element = 'kca_scratch';
	kca_ajax.runAJAX();
	return false;
}

function kca_save_ini() {
	if (kca_submitted()) return false;
	var scratch_value = document.getElementById('kca_scratch').value;
	if (scratch_value) {
		var data = kca_parse_data();
		if (data) {
			if (confirm('You are about to overwrite default.ini with Scratch-Pad data.\n\'OK\' to overwrite, \'Cancel\' to stop.')) {
				kca_submit_flag = 1;
				var dataStr = 'kca-save-ini=' + encodeURIComponent(scratch_value);
				var kca_ajax = new sack();
				kca_ajax.onLoading = function () { kca_spin_wheel(1); };
				kca_ajax.onLoaded = function () { kca_spin_wheel(-1); };
				kca_ajax.onError = function () { kca_spin_wheel('!'); };
				kca_ajax.requestFile = '<?= core::urlname(dirname(__FILE__)) . '/../kca.php' ?>';
				kca_ajax.method = 'POST';
				kca_ajax.onCompletion = function () {
					if (kca_msg_flag < 1) kca_msg_flag = 1;
					kca_submit_flag = 0;
					var msg = document.getElementById('kca_msg_text');
					msg.innerHTML += this.response;
					msg.lastChild.id = khanh.core.randomString();
					Fat.fade_element(msg.lastChild.id, 33, 3000, '#' + khanh.core.randomString(6, 'abcdef'), '#ffffff');
				};
				kca_ajax.runAJAX(dataStr + '&xmlhttp=1');
			}
			return false;
		} else {
			alert('Nothing to save! Scratch-Pad needs to contain appropriate data.');
		}
	} else {
		alert('Nothing to save! Scratch-Pad needs to contain appropriate data.');
	}
}

function kca_extract_all() {
	var str = '';
	for (var i = 0; i < <?= $this->kca_tot_sets ?>; i++) {
		str += kca_extract(i);
	}
	document.getElementById('kca_scratch').value = str;
}

function kca_extract(i) {
	var desc = new Array(<?php
	$desc_maxlen = 0;
	for ($i = 0; $i < $this->kca_num_opts; $i++) {
		strlen($this->kca_keys[$i]) > $desc_maxlen ? $desc_maxlen = strlen($this->kca_keys[$i]) : '';
	}
	// Work out # of tab to insert for each description, depending on description length
	for ($i = 0; $i < $this->kca_num_opts; $i++) {
		echo "'" . $this->kca_keys[$i] . sprintf("%'\t-" . (ceil($desc_maxlen / 8) - floor(strlen($this->kca_keys[$i]) / 8)) . "s" , "") . "'";
		echo $i < $this->kca_num_opts - 1 ? ', ' : '';
	}
	?>);
	// Save tab stop count for client side
	tabs = '<?= sprintf("%'\t-" . ceil($desc_maxlen / 8) . "s" , "") ?>';
	str = '[Record Set #' + (i + 1) + ']\n';
	for (var j = 0; j < <?= $this->kca_num_opts ?>; j++) {
		str += desc[j] + '= ';
		dataRef = document.getElementById('kca_' + (i * <?= $this->kca_num_opts ?> + j + 1));
		if (dataRef.type == 'checkbox') {
			str += dataRef.checked;
		} else if (typeof dataRef.value == 'boolean') {
			str += dataRef.value;
		} else if (isNaN(dataRef.value)) {
			// Insert correct # of tabs, remove \r's
			str += dataRef.value.replace(/\r?(\n)/g, '$1' + tabs + '+ ');
		} else {
			str += dataRef.value;
		}
		str += '\n';
	}
	return str += '\n';
}

function kca_upgrade_all() {
	if (!confirm('You are about to upgrade the KCA database.\n  \'OK\' to upgrade, \'Cancel\' to cancel.')) {
		return false;
	}
}

function kca_help(file) {
	var kca_ajax = new sack();
 	kca_ajax.onLoading = function () { kca_spin_wheel(1); };
	kca_ajax.onLoaded = function () { kca_spin_wheel(-1); }; 
	kca_ajax.onError = function () { kca_spin_wheel('!'); }; 
	kca_ajax.requestFile = file;
	kca_ajax.method = 'GET';
	kca_ajax.element = 'kca_help_text';
	kca_ajax.runAJAX();
}

function kca_update_all() {
	if (kca_submitted()) return false;
	if (confirm('You are about to do a global update to the database.\n  \'OK\' to continue, \'Cancel\' to stop.')) {
		kca_submit_flag = 1;
		var dataStr = 'kca-update-all=1';
		for (var i = 0; i < <?= $this->kca_tot_sets ?>; i++) {
			for (var j = 0; j < <?= $this->kca_num_opts ?>; j++) {
				dataRef = document.getElementById('kca_' + (i * <?= $this->kca_num_opts ?> + j + 1));
				if (dataRef.type == 'checkbox') {
					controlValue = dataRef.checked;
				} else {
					controlValue = URLEncode(dataRef.value);
				}
				controlName = 'kca_' + (i * <?= $this->kca_num_opts ?> + j + 1);

				dataStr += '&' + (controlName + "=" + controlValue);
			}
		}
		var kca_ajax = new sack();
		kca_ajax.onLoading = function () { kca_spin_wheel(1); };
		kca_ajax.onLoaded = function () { kca_spin_wheel(-1); }; 
		kca_ajax.onError = function () { kca_spin_wheel('!'); }; 
		kca_ajax.requestFile = '<?= core::urlname(dirname(__FILE__)) . '/../kca.php' ?>';
		kca_ajax.method = 'POST';
		kca_ajax.onCompletion = function () {
			kca_msg_flag = 2;
			kca_submit_flag = 0;
			var msg = document.getElementById('kca_msg_text');
			msg.innerHTML += this.response;
			msg.lastChild.id = khanh.core.randomString();
			Fat.fade_element(msg.lastChild.id, 33, 3000, '#' + khanh.core.randomString(6, 'abcdef'), '#ffffff');
		};
		kca_ajax.runAJAX(dataStr + '&xmlhttp=1');
	}
	return false;
}

function kca_update(i) {
	if (kca_submitted()) return false;
	if (confirm('You are about to update [Record Set #' + i + '].\n  \'OK\' to update, \'Cancel\' to stop.')) {
		kca_submit_flag = 1;
		var dataStr = 'kca-update=1&set=' + i;
		for (var j = 0; j < <?= $this->kca_num_opts ?>; j++) {
			dataRef = document.getElementById('kca_' + ((i - 1)* <?= $this->kca_num_opts ?> + j + 1));
			if (dataRef.type == 'checkbox') {
				controlValue = dataRef.checked;
			} else {
				controlValue = URLEncode(dataRef.value);
			}
			controlName = 'kca_' + ((i - 1) * <?= $this->kca_num_opts ?> + j + 1);

			dataStr += '&' + (controlName + "=" + controlValue);
		}
		var kca_ajax = new sack();
		kca_ajax.onLoading = function () { kca_spin_wheel(1); };
		kca_ajax.onLoaded = function () { kca_spin_wheel(-1); }; 
		kca_ajax.onError = function () { kca_spin_wheel('!'); }; 
		kca_ajax.requestFile = '<?= core::urlname(dirname(__FILE__)) . '/../kca.php' ?>';
		kca_ajax.method = 'POST';
		kca_ajax.onCompletion = function () {
			if (kca_msg_flag < 1) kca_msg_flag = 1;
			kca_submit_flag = 0;
			var msg = document.getElementById('kca_msg_text');
			msg.innerHTML += this.response;
			msg.lastChild.id = khanh.core.randomString();
			Fat.fade_element(msg.lastChild.id, 33, 3000, '#' + khanh.core.randomString(6, 'abcdef'), '#ffffff');
		};
		kca_ajax.runAJAX(dataStr + '&xmlhttp=1');
	}
	return false;
}

function kca_delete(set) {
	if (kca_submitted()) return false;
	if (confirm('You are about to delete [Record Set #' + set + ']!\n  \'OK\' to delete, \'Cancel\' to stop.')) {
		kca_submit_flag = 1;
		return true;
	} else {
		return false;
	}
}

function kca_purge_all() {
	if (kca_submitted()) return false;
	if (confirm('You are about to purge the KCA database of all data.\n  \'OK\' to purge, \'Cancel\' to cancel.')) {
		kca_submit_flag = 1;
		return true;
	} else {
		return false;
	}
}

function kca_restore_all() {
	if (kca_submitted()) return false;
	var origNode = document.getElementById('import_all');
	// If no value then must be first pass
	if (origNode.value) {
		kca_submit_flag = 1;
	} else {
		if (confirm('You are about to restore to defaults!\n  \'OK\' to continue, \'Cancel\' to stop.')) {
			kca_submit_flag = 1;
			if (confirm('Reset panel settings?\n  \'OK\' to reset, \'Cancel\' to keep settings.')) {
				khanh.core.setCookie('kca_last_loc', '', 0);
				khanh.core.setCookie('kca_info_state', '', 0);
				khanh.core.setCookie('kca_sets_state', '', 0);
				khanh.core.setCookie('kca_forms_state', '', 0);
			}
			// Move import node to global form...
			var dataNode = origNode.cloneNode(true);
			document.getElementById('kca_form_<?= $this->kca_tot_sets + 3 ?>').appendChild(dataNode);
			origNode.id = '';

			// ...then read INI file to copied node...
			var kca_ajax = new sack();
			kca_ajax.onLoading = function () { kca_spin_wheel(1); };
			kca_ajax.onLoaded = function () { kca_spin_wheel(-1); }; 
			kca_ajax.onError = function () { kca_spin_wheel('!'); }; 
			kca_ajax.requestFile = '<?= core::urlname(dirname(__FILE__)) . '/../addons/default.ini' ?>';
			kca_ajax.method = 'GET';
			kca_ajax.element = 'kca_scratch';
			kca_ajax.onCompletion = function () {
				kca_submit_flag = 0;
				// ...parse the data that will be submitted
				if (document.getElementById('import_all').value = kca_parse_data()) {
					document.getElementById('kca_restore').click();
				} else {
					document.getElementById('import_all').value = '';
				}
			};
			kca_ajax.runAJAX();
		}
		return false;
	}
}

/***************
 Navigation Bar
****************/

function kca_go_to(loc) {
	var set = kca_loc_cookie();
	if (loc != set) {
		kca_toggle_set(loc, 'block');
	} else {
		kca_toggle_set(loc);
	}
	kca_do_info()[4] != 'block' ? kca_jump_to(loc) : kca_scroll_to(loc);
	return false;
}

function kca_jump_to(loc) {
	var set = kca_loc_cookie();
	loc != set ? document.getElementById('kca_set_' + set).style.display = 'none' : 0;
}

function kca_scroll_to(loc) {
	var pY = findPosY(document.getElementById('kca_set_' + loc)) - document.getElementById('kca-nav').offsetHeight - 14;
	scrollTo(0, pY);
}

function kca_go_to_next() {
	if (<?= $this->kca_tot_sets ?>) {
		var loc = kca_loc_cookie();
		if (loc < <?= $this->kca_tot_sets ?>) {
			loc++;
			kca_go_to(loc);
		} else if (loc != 1) {
			loc = 1;
			kca_go_to(loc);
		}
	}
	return false;
}

function kca_go_to_prev() {
	if (<?= $this->kca_tot_sets ?>) {
		var loc = kca_loc_cookie();
		if (loc > 1) {
			if (loc > <?= $this->kca_tot_sets ?>) {
				loc = <?= $this->kca_tot_sets ?>;
			} else {
				loc--;
			}
			kca_go_to(loc);
		} else if (loc != <?= $this->kca_tot_sets ?>) {
			loc = <?= $this->kca_tot_sets ?>;
			kca_go_to(loc);
		}
	}
	return false;
}

function kca_go_to_first() {
	if (<?= $this->kca_tot_sets ?>) {
		kca_loc_cookie() != 1 ? kca_go_to(1) : 0;
	}
	return false;
}

function kca_go_to_last() {
	if (<?= $this->kca_tot_sets ?>) {
		kca_loc_cookie() != <?= $this->kca_tot_sets ?> ? kca_go_to(<?= $this->kca_tot_sets ?>) : 0;
	}
	return false;
}

function kca_go_to_top() {
	document.getElementById('nav_tab_' + kca_loc_cookie()).className = 'normal';
	document.getElementById('nav_tab_' + kca_loc_cookie(1)).className = 'current';
	scrollTo(0, 0);
	return false;
}

function kca_go_to_bottom() {
	document.getElementById('nav_tab_' + kca_loc_cookie()).className = 'normal';
	document.getElementById('nav_tab_' + kca_loc_cookie(<?= $this->kca_tot_sets + 3 ?>)).className = 'current';
	scrollTo(0, document.body.offsetHeight);
	return false;
}

function kca_toggle_font(state) {
	state = state ? state : kca_do_info(7)[6];
	if (state != 'none') {
		document.getElementById('kca-nav').style.fontSize = '12px';
	} else {
		document.getElementById('kca-nav').style.fontSize = '16px';
	}
	return false;
}

function kca_toggle_msg(state) {
	state = state ? state : kca_do_info(3)[2];
	document.getElementById('kca_msg_panel').style.display = state;
	return false;
}

function kca_toggle_help(state) {
	state = state ? state : kca_do_info(4)[3];
	if (state != 'none') kca_help('<?= $this->kca_docs ?>/readme.txt');
	document.getElementById('kca_help_panel').style.display = state;
	return false;
}

function kca_toggle_set(loc, state) {
	state = state ? kca_do_sets('kca_set', loc, state)[loc - 1] : kca_do_sets('kca_set', loc)[loc - 1];
	document.getElementById('kca_set_' + loc).style.display = state;
	return false;
}

function kca_toggle_nav() {
	kca_do_info(6);
	return false;
}

function kca_toggle_display(state) {
	state = state ? state : kca_do_info(5)[4];
	var loc = kca_loc_cookie();
	var sets = kca_do_sets('kca_set');
	var panels = kca_do_sets('kca_form');
	if (state != 'block') {
		for (var i = 1; i <= <?= $this->kca_tot_sets + 3 ?>; i++) {
			if (loc != i) {
				document.getElementById('kca_set_' + i).style.display = state;
			} else if (sets[i - 1] != 'none') {
				document.getElementById('kca_set_' + i).style.display = 'block';
				document.getElementById('kca_form_' + i).style.display = panels[i - 1];
			}
		}
		sets[loc -1] != 'none' ? scrollTo(0, 0) : 0;
	} else {
		for (var i = 1; i <= <?= $this->kca_tot_sets + 3 ?>; i++) {
			document.getElementById('kca_set_' + i).style.display = sets[i - 1];
			document.getElementById('kca_form_' + i).style.display = panels[i - 1];
		}
		sets[loc -1] != 'none' ?  kca_scroll_to(loc) : 0;
	}
	return false;
}

function kca_rollup_info(loc, state) {
	state = state ? state : kca_do_info(loc)[loc - 1];
	document.getElementById('kca_info_' + loc).style.display = state;
	kca_toggle_button('kca_info', loc, state);
	return false;
}

function kca_rollup_set(loc, state) {
	state = state ? state : kca_do_sets('kca_form', loc)[loc - 1];
	document.getElementById('kca_form_' + loc).style.display = state;
	kca_toggle_button('kca_form', loc, state);
	return false;
}

function kca_toggle_button(prefix, loc, state) {
	var button = document.getElementById(prefix + '_' + loc + '_');
	button.color = '#fff';
	if (state != 'none') {
		button.innerHTML = '&ndash;';
		if (typeof(khanh.dtt) != 'undefined') {
			var tipText = khanh.dtt.getTipText(button);
			if (tipText) khanh.dtt.changeTip(button, tipText.replace(/Rolldown/, 'Rollup'));
		} else
			button.title = button.title.replace(/Rolldown/, 'Rollup');
	} else {
		button.innerHTML = '+';
		// If khanh.dtt is present, then update tooltips
		if (typeof(khanh.dtt) != 'undefined') {
			var tipText = khanh.dtt.getTipText(button);
			if (tipText) khanh.dtt.changeTip(button, tipText.replace(/Rollup/, 'Rolldown'));
		} else
			button.title = button.title.replace(/Rollup/, 'Rolldown');
	}
}

function kca_do_info(loc) {
	var info_cookie = khanh.core.getCookie('kca_info_state');
	var info = info_cookie.split('|');
	if (info.length != 7 || loc) {
		if (info.length != 7) {
			info = new Array();
			info[0] = 'block'; // msg rollup state
			info[1] = 'block'; // help rollup state
			info[2] = 'block'; // msg panel state
			info[3] = 'block'; // help panel state
			info[4] = 'block'; // display mode
			info[5] = 'block'; // nav-bar mode
			info[6] = 'block'; // font size
		} else if (loc) {
			if (info[loc - 1] != 'none') {
				info[loc - 1] = 'none';
			} else {
				info[loc - 1] = 'block';
			}
		}
		info_cookie = '';
		for (var i = 0; i < info.length; i++) {
			info_cookie += info[i] + (i < info.length - 1 ? '|' : '');
		}
		khanh.core.setCookie('kca_info_state', info_cookie, <?= $this->kca_days ?>);
	}
	return info;
}

function kca_do_sets(prefix, loc, state) {
	var sets_cookie = khanh.core.getCookie(prefix + 's_state');
	var sets = sets_cookie.split('|');
	if (sets.length != <?= $this->kca_tot_sets + 3 ?> || loc) {
		if (sets.length != <?= $this->kca_tot_sets + 3 ?>) {
			sets = new Array();
			for (var i = 0; i < <?= $this->kca_tot_sets + 3 ?>; i++) {
				sets[i] = 'block';
			}
		} else if (loc) {
			if (state) {
				sets[loc - 1] = state;
			} else if (sets[loc - 1] != 'none') {
				sets[loc - 1] = 'none';
			} else {
				sets[loc - 1] = 'block';
			}
		}
		sets_cookie = '';
		for (var i = 0; i < sets.length; i++) {
			sets_cookie += sets[i] + (i < sets.length - 1 ? '|' : '');
		}
		khanh.core.setCookie(prefix + 's_state', sets_cookie, <?= $this->kca_days ?>);
	}
	return sets;
}

function kca_loc_cookie(crumb) {
	var loc = khanh.core.getCookie('kca_last_loc');
	if (loc > <?= $this->kca_tot_sets + 3 ?> && <?= $this->kca_tot_sets ?> > 0) {
		crumb = <?= $this->kca_tot_sets ?>;
	} else if (loc > 3 && <?= $this->kca_tot_sets ?> < 1) {
		crumb = 1;
	} else if (crumb < 1) {
		crumb = 1;
	}
	if (crumb) {
		if (isNaN(loc)) {
			khanh.core.setCookie('kca_last_loc', crumb, <?= $this->kca_days ?>);
		} else {
			if (parseInt(loc) != crumb) {
				khanh.core.setCookie('kca_last_loc', crumb, <?= $this->kca_days ?>);
			}
		}
	} else {
		if (isNaN(loc) || !loc || loc == 'undefined') {
			crumb = 1;
			khanh.core.setCookie('kca_last_loc', crumb, <?= $this->kca_days ?>);
		} else {
			crumb = loc;
		}
	}
	return crumb;
}

function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	} else if (obj.y) curtop += obj.y;
	return curtop;
}

function print(s) {
	document.getElementById('kca-show-info').innerHTML = '[' + s + ']';
}

function write(s) {
	if (typeof(debug) == 'undefined') {
		debug = window.open('about:blank','debugWindow','width=800,height=580,scrollbars=yes');
	}
	debug.document.write('<pre>'+s+'<br /></pre>');
}

function kca_do_nav(startY, el) {
	function ml(el)	{
		el.sP = function(y, pos) { pos ? this.style.position = pos : 0; this.style.top = y + 'px'; };
		el.y = startY;
		return el;
	}
	window.stayTop = function() {
		// Get the page top value
		if (window.pageYOffset) pY = window.pageYOffset;
		else if (document.documentElement && document.documentElement.scrollTop) pY = document.documentElement.scrollTop;
		else if (document.body) pY = document.body.scrollTop;

		var info = kca_do_info();
		if (info[5] != 'none') {
			// Move nav-bar to correct position
			if (pY > startY) ftlObj.y += (pY - ftlObj.y) / 5;
			else if (ftlObj.y > startY) ftlObj.y += (startY - ftlObj.y) / 5;
		<?php if ($is_IE) { ?>
		} else {
			if (pY > startY) ftlObj.y += pY - ftlObj.y;
			else if (ftlObj.y > startY) ftlObj.y += startY - ftlObj.y;
		}
		<?php } else { ?>
		} else {
			if (pY > startY) {
				ftlObj.y = 0;
				ftlObj.pos = 'fixed';
			} else {
				ftlObj.y = startY;
				ftlObj.pos = 'absolute';
			}
		}
		<?php } ?>

		ftlObj.sP(ftlObj.y, ftlObj.pos);
		// Update data to the nav-bar
		document.getElementById('kca-show-loc').innerHTML = pY + ':' + parseInt(ftlObj.y + 0.5);

		var y = parseInt(ftlObj.y + 0.5);
		if (y == pY || y == startY || info[5] != 'block') {
			document.getElementById('kca_msg_button').style.color = info[0] == 'none' || info[2] == 'none' ? kca_msg_flag == 2 ? '#ff3300' : kca_msg_flag == 1 ? '#ffcc00' : '' : '';
			document.getElementById('kca-disp-mode').lastChild.nodeValue = info[4] != 'none' ? String.fromCharCode(8734) : String.fromCharCode(8733);
			document.getElementById('kca-nav-mode').lastChild.nodeValue = info[5] != 'none' ? String.fromCharCode(8225) : String.fromCharCode(8224);
			var sets = kca_do_sets('kca_set');
			var min = '';
			for (var i = 0; i < <?= $this->kca_tot_sets + 3 ?>; i++) {
				min += i == <?= $this->kca_tot_sets + 2 ?> && sets[i] == 'none' ? '&Theta;:' :
					i == <?= $this->kca_tot_sets + 1 ?> && sets[i] == 'none' ? '#:' :
					i == <?= $this->kca_tot_sets ?> && sets[i] == 'none' ? '+:' :
					sets[i] != 'block' ? (i + 1) + ':' : '';
			}
			min += info[2] == 'none' ? '&Xi;:' : '';
			min += info[3] == 'none' ? '?:' : '';
			min ? min = min.substring(0, (min.length - 1)) : min = '&ndash;';
			document.getElementById('kca-show-closed').innerHTML = min;
			for (var i = 1; i <= <?= $this->kca_tot_sets + 3 ?>; i++) {
				rY = findPosY(document.getElementById('kca_set_' + i));
				if (rY <= pY + 36 && rY > 0) {
					var r = i;
				} else if (rY > pY + 36) {
					if (isNaN(r)) r = i;
					break;
				}
			}
			var loc = kca_loc_cookie();
			if (r != loc) {
				if (!isNaN(r)) document.getElementById('nav_tab_' + loc).className = 'normal';
				document.getElementById('nav_tab_' + kca_loc_cookie(r)).className = 'current';
			}
			setTimeout('stayTop()', 100);
		} else setTimeout('stayTop()', 10);

	};
	ftlObj = ml(el);
	stayTop();
}

function kca_now() {
	var now = new Date();
	return (now.getHours() < 10 ? '0' : '') + now.getHours() + ':' +
	(now.getMinutes() < 10 ? '0' : '') + now.getMinutes() + ':' +
	(now.getSeconds() < 10 ? '0' : '') + now.getSeconds();
}

function kca_check_ver() {
<?php $your = core::version(dirname(__FILE__) . '/../kca.php') ?>
	var kca_ajax = new sack();
 	kca_ajax.onLoading = function () { kca_spin_wheel(1); };
	kca_ajax.onLoaded = function () { kca_spin_wheel(-1); }; 
	kca_ajax.onError = function () { kca_spin_wheel('!'); }; 
	kca_ajax.requestFile = '<?= core::urlname(dirname(__FILE__)) . '/get-version.php' ?>';
	kca_ajax.onCompletion = function () {
		var ref = document.getElementById('kca_msg_text');

		var version_num = this.response.replace(/[\.a-z-,]/g,'');
		var version_text = this.response.replace(/[a-z-,]/g,'');
		var name = this.response.replace(/[\.\d-]/g,'').split(',');
		var current_name = name[0];
		var previous_name = (typeof(name[1]) != 'undefined' ? name[1] : '');
		if (msg = version_num > '<?= preg_replace('/\./', '', $your['version']) ?>' ? '<li>[' + kca_now() + ']<ul class="kca_msg_ul"><li class="kca_msg_li">' + current_name.toUpperCase() + version_text + (previous_name ? ' (was ' + previous_name.toUpperCase() + ') ' : ' ') + ' is now available. (<a href="http://ink.bur.st/?dl=' + current_name + '-' + version_text + '.zip">Download <img src="<?= core::urlname(dirname(__FILE__)) . '/dlicon.gif' ?>" /></a>)</li></ul></li>' : '') {
			kca_msg_flag = 2;
			ref.innerHTML += msg;
			ref.lastChild.id = khanh.core.randomString();
			Fat.fade_element(ref.lastChild.id, 33, 3000, '#' + khanh.core.randomString(6, 'abcdef'), '#' + khanh.core.randomString(6, 'abcdef'));
		}
	};
	kca_ajax.runAJAX();
}

function URLEncode(str) {
	if( typeof encodeURIComponent != 'undefined' &&
		typeof encodeURIComponent !=  undefined ) {
	 code = encodeURIComponent(str);
	 code = code.replace( /%20/g , "+" );
	 return code;
	}
	else {
	 return null;
	}
}

function kca_spin_wheel(state) {
	var ops = document.getElementById('kca-ajax-ops').innerHTML;
	if (state < 0) ops--;
	else if (state > 0) ops++;
	if (state) document.getElementById('kca-ajax-ops').innerHTML = ops;

	var spinner = document.getElementById('kca-spinner');
	var ani = String.fromCharCode(8211) + '/|\\';
	var i = ani.indexOf(spinner.innerHTML);

	if (state && i > -1) {
		return false;
	}

	if (ops > 0) {
		spinner.innerHTML = ani.charAt(i < ani.length - 1 ? i + 1 : 0);
		setTimeout('kca_spin_wheel()', 30);
	} else spinner.innerHTML = '-';
}

function kca_submitted() {
	if (kca_submit_flag) {
		alert('Process already initiated, please be patient.');
		return true;
	} else {
		return false;
	}
}

<?php
if ($is_IE) {
?>

function CopyToClipboard() {
	CopiedTxt = document.selection.createRange();
	CopiedTxt.execCommand('Copy');
}

function PasteFromClipboard() {
	document.kca_scratch_pad.kca_scratch.focus();
	PastedText = document.kca_scratch_pad.kca_scratch.createTextRange();
	PastedText.execCommand('Paste');
}
<?php } ?>

function kca_set_textarea() {
	/* The following is to make textareas fixed width,
		since IE stuffs up the width when colspans is
		mixed with textarea or input fields that
		contain long unbroken strings.
	*/
 	// get panel width from msg panel
	var w = parseInt(document.getElementById('kca_msg_text').offsetWidth / 2) - <?= $is_IE ? '8' : '16' ?>;
	var z = parseInt(w / 5 * 4);
	z += 'px';
	for (var i = 1; i <= <?= $this->kca_tot_sets + 1 ?>; i++) {
		var tNode = document.getElementById('kca_set_' + i).getElementsByTagName('textarea');
		for (var j = 0; j < tNode.length; j++) {
			tNode[j].style.width = w + 'px';
		}
		var tNode = document.getElementById('kca_set_' + i).getElementsByTagName('input');
		for (var j = 0; j < tNode.length; j++) {
			if (tNode[j].className == 'kca-field') {
				tNode[0].style.width = w<?= $is_IE ? ' + 8' : '' ?> + 'px';
				tNode[1].style.width = tNode[3].style.width = z;
			}
		}
	}
}


function kca_init() {
	// Remove Holly hack coz it stuffs up navigation
	if (document.styleSheets[0].cssText) document.styleSheets[0].cssText = document.styleSheets[0].cssText.replace(/\.wrap \{\s*height: ?1\%\;?\s*\}/i, '');

	// Check if latest version
	kca_check_ver();

	var info = kca_do_info();

	// do nav-bar font-size,
	kca_toggle_font(info[6]);

	// then do nav-bar
	var nav_bar = document.getElementById('kca-nav');
	kca_do_nav(findPosY(nav_bar), nav_bar);

	// set size of textareas if IE (must go before msg rollup)
	kca_set_textarea();

	// msg & help rollup states
	kca_rollup_info(1, info[0]);
	kca_rollup_info(2, info[1]);

	// record set rollup states
	var forms = kca_do_sets('kca_form');
	for (var i = 1; i <= <?= $this->kca_tot_sets + 3 ?>; i++) {
		kca_rollup_set(i, forms[i - 1]);
	}

	// help panel state
	kca_toggle_help(info[3]);

	// msg panel state
	var msg = document.getElementById('kca_msg_text');
	msg.innerHTML += '<?= preg_replace("[\r|\n|\t]", '', $this->kca_msg) ?><li>[' + kca_now() + ']<ul class="kca_msg_ul"><li class="kca_msg_li">...complete!</li></ul></li>';
	var li_list = msg.childNodes;
	var i = 0;
	do {
		li_list[i].id = khanh.core.randomString();
		Fat.fade_element(li_list[i].id, 33, 3000, '#' + khanh.core.randomString(6, 'abcdef'), '#ffffff');
		i++;
	} while (i < li_list.length);

	kca_toggle_msg(info[2]);

	// display mode: single or multi
	kca_toggle_display(info[4]);

	if (typeof(textarea_init) != 'undefined' && khanh.core.browser('msie')) textarea_init();
	if (typeof(khanh.dtt) != 'undefined') khanh.dtt.scanTags();
}

var kca_msg_flag = <?= $this->kca_msg_flag ?>;
var kca_submit_flag = 0;
khanh.event.add(window, 'load', kca_init);
<?php endif; ?>