/**
 * Parenchym's Toolkit Library
 */

/**
 * Builds an absolute URL for use in Parenchym
 *
 * It automatically detects protocol, host, port and base URL.
 * Base URL is current pathname up to and including `main.php'.
 * The new URI is appended to this base.
 * Search and hash are treated as usual.
 *
 * We use protocol and port of the main page. If the main page goes over
 * a secure line, so does the AJAX call.
 *
 * @param string URI     The new URI
 * @param string search  Optional parameters
 * @param string hash    Optional anchor inside a page
 * @return string        The absolute URL
 */
function pym_url(URI, search, hash)
{
    var l = window.location;
    var URL = l.protocol + '//' + l.host;
    // Hack for (at least) IE7: remove port number from host. IE SUCKS!!!
    var host = l.host.replace(/:\d+$/, '');
    var URL = l.protocol + '//' + host;
    if (l.port != '') {
        URL += ':' + l.port;
    }
	if (l.pathname.match(/main\.php/)) {
		var pn = l.pathname.split('main.php')[0];
		URL += pn + 'main.php/' + URI;
	}
	else {
		var pn = l.pathname.split('index.php')[0];
		URL += pn + 'index.php/' + URI;
	}
    if (search !== undefined) {
        URL += '?' + search;
    }
    if (hash !== undefined) {
        URL += '#' + hash;
    }
    return URL;
}

function pym_datatable_change_order(tbl_id, field)
{
	var f = document.pageForm.elements[tbl_id + '_order_field'];
	f.value = field;
	document.pageForm.submit();
}

function pym_datatable_goto_page(tbl_id, page_num)
{
	var f = document.pageForm.elements[tbl_id + '_cur_page'];
	f.value = page_num;
	document.pageForm.submit();
}

function pym_datatable_enable_rowselect(tbl_id)
{
	var tbl = document.getElementById(tbl_id);
	var rows = tbl.getElementsByTagName('tr');
	for (var i=0; i<rows.length; i++) {
		rows[i].addEventListener('click', pym_datatable_select_row, false);
	}
}

//var pym_datatable_selected_rows = new Array();
// Using prototype:
var pym_datatable_selected_rows = new Hash();


function pym_datatable_select_row(evt)
{
	var row = evt.currentTarget;
//	var markerId = row.id.replace(/Row/, 'Marker');
//	var marker = document.getElementById(markerId);
	var cn = row.className;
	if (pym_datatable_selected_rows.get(row.id)) {
		cn = pym_datatable_selected_rows.get(row.id);
		//pym_datatable_selected_rows[row.id] = undefined;
		pym_datatable_selected_rows.unset(row.id);
//		if (marker)	marker.checked = false;
	}
	else {
		pym_datatable_selected_rows.set(row.id, cn);
		cn = 'selectedRow';
//		if (marker) marker.checked = true;
	}
	row.className = cn;
}


function pym_selectoption_hint(list, hint_id, hint_attr)
{
	var h = document.getElementById(hint_id);
	var v = (list.value) ? list.value : v = list.options[0].value;
	var m = '';
	for (var i=0; i<list.options.length; i++) {
		if (v == list.options[i].value) {
			m = list.options[i].getAttribute(hint_attr);
			break;
		}
	}
	if (m != '') {
		h.firstChild.nodeValue = m;
	}
}


function pym_select_all_list_items(frm_name, list_name)
{
	var l = document.forms[frm_name][list_name];
	// grmpf!! PHP arrays
	if (! l) l = document.forms[frm_name][list_name+'[]'];
	for (var i=0; i<l.options.length;i++) l.options[i].selected = true;
}
 
/**
 * Compares two strings or numbers.
 *
 * TODO: sort_mode is not implemented yet.
 *
 * @param s1 mixed     String/number 1
 * @param s2 mixed     String/number 2
 * @param sort_mode string    (optional) Sort alphanumerically (alnum, default) or numerically (num)
 * @return int         -1 if s1<s2; 0 if s1==s2; +1 if s1>s2
 */
function pym_compare(s1, s2, sort_mode)
{
	if (s1 < s2) return -1;
	if (s1 == s2) return 0;
	return +1;
}

/**
 * Moves items from one list to another.
 *
 * TODO: sort_mode is not implemented yet.
 *
 * @param frm_name string     Name of the form the two lists belong to
 * @param list_name1 string   Name of the first list
 * @param list_name2 string   Name of the second list
 * @param sort string         (optional) Direction of sorting (ASC, DESC or none (default))
 * @param sort_mode string    (optional) Sort alphanumerically (alnum, default) or numerically (num)
 */
function pym_move_list_items(frm_name, list_name1, list_name2, sort, sort_mode)
{
	var l1 = document.forms[frm_name][list_name1];
	// grmpf!! PHP arrays
	if (! l1) l1 = document.forms[frm_name][list_name1+'[]'];
	var l2 = document.forms[frm_name][list_name2];
	// grmpf!! PHP arrays
	if (! l2) l2 = document.forms[frm_name][list_name2+'[]'];
	var ds;

	if (! sort) sort = '';
	switch (sort.toLowerCase())
	{
		case 'asc':
			ds = 1;
			break;
		case 'desc':
			ds = -1;
			break;
		default:
			ds = 0;
	}

	// unselect all items in list 2
	for (var i=0; i<l2.options.length; i++) l2.options[i].selected = false;

	// TODO    implement binary search
	for (var i=l1.options.length-1; i>=0; i--) {
		if (l1.options[i].selected) {
			// select new items in list 2 for better visibility
			var o = new Option(l1.options[i].text, l1.options[i].value, false, true);

			// no sorting required
			if (ds == 0) {
				l2.options[l2.options.length] = o;
			}
			// do sort
			else {
				// crawl upward in list to find our position
				if (l2.options.length == 0) {
					l2.options[0] = o;
				}
				else {
					for (i2=l2.options.length-1; i2>=0; i2--) {
						var sr = ds * pym_compare(l2.options[i2].text, o.text);
						
						// if current item is above or equal to us, put us below it
						if (sr == -1 || sr == 0) {
							l2.options[i2+1] = o;
							break;
						}
						// else move current item one position lower
						else {
							var o_tmp = new Option(
									l2.options[i2].text,
									l2.options[i2].value,
									l2.options[i2].defaultSelected,
									l2.options[i2].selected
								);
							l2.options[i2+1] = o_tmp;
						}
						// at least we come to an end :)
						if (i2 == 0) {
							l2.options[i2] = o;
						}
					}
				}
			}
			
			// remove item from list 1
			l1.options[i] = null;
		}
	}
}
