var submit_ok = true;

function clean_edit(ed) {
	var o = gereg(ed);
	if(!o)
		return;
	o.value = '';
}

function follow_a(a) {
	var h = '' + a.href;
	if(h.indexOf('javascript:') == 0) {
		eval(h);
	}
	else {
		window.location = h;
	}
}

function follow_link(e) {
	if(!e) var e = window.event;
	var t = e.target ? e.target : e.srcElement;
	cancel_event(e);
	
	if(t.tagName == 'A') {
		follow_a(t);
	}
	else if(t.tagName == 'TD' || t.tagName == 'TABLE') {
		var aid = t.getAttribute('aid');
		var a = ge(aid);
		follow_a(a);
	}
	else {
		alert('error: unsupported link element: ' + (t.tagName ? t.tagName : t));
	}
}
	
function cancel_event(pE) {
	if(!pE) {
		if(window.event)
			pE = window.event;
		else
			return;
	}
	if(pE.cancelBubble != null)
		pE.cancelBubble = true;
	if(pE.stopPropagation)
		pE.stopPropagation();
	if(pE.preventDefault)
		pE.preventDefault();
	if(window.event)
		pE.returnValue = false;
	if(pE.cancel != null)
		pE.cancel = true;
}

function post(posterControlID, postControlID) {
	document.form.post_control.value = postControlID;
	document.form.poster_control.value = posterControlID;
	form_onsubmit();
	if(submit_ok)
		document.form.submit();
}

function select_state(url, controller_id, state_id) {
	document.form.action = url;
	post_value(controller_id + '_view_select', controller_id, state_id);
}

function post_value(posterControlID, postControlID, posterControlValue) {
	document.form.poster_control.value = posterControlID;
	document.form.poster_value.value = posterControlValue;
	if(new String(postControlID).indexOf('.') != -1)
		postControlID = get_reg_control(postControlID);
	document.form.post_control.value = postControlID;
	form_onsubmit();
	if(submit_ok)
		document.form.submit();
}

function show_popup2(e) {
	if(!e) var e = window.event;
	//alert(e.target);
	var targ = e.target ? e.target : e.srcElement;
	var text = targ ? targ.getAttribute("popup-text") : null;
	if(!text)
		return;
	var pop;
	pop = ge('popup');
	if(!pop)
		return;
	if(pop.innerHTML != text)
		pop.innerHTML = text;

	var posx = 0;
	var posy = 0;
	if (e.pageX || e.pageY) {
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) {
		posx = e.clientX + document.body.scrollLeft;
		posy = e.clientY + document.body.scrollTop;
	}
	pop.style.left = posx + 10;
	pop.style.top = posy + 10;
	pop.style.display = "block";
}

function hide_popup() {
	ge('popup').style.display = "none";
}

function move_sel_list_option(src_list, dst_list) {
	if(src_list.selectedIndex < 0)
		return;
	if(dst_list.selectedIndex != -1)
		dst_list.insertBefore(src_list.options[src_list.selectedIndex], dst_list.options[dst_list.selectedIndex]);
	else
		dst_list.appendChild(src_list.options[src_list.selectedIndex]);
}

function move_sel_list_option_up(the_list) {
	var idx = the_list.selectedIndex;
	if(idx < 1)
		return;
	var in_html = the_list.options[idx].innerHTML;
	var val = the_list.options[idx].value;
	the_list.options[idx].innerHTML = the_list.options[idx - 1].innerHTML;
	the_list.options[idx].value = the_list.options[idx - 1].value;
	the_list.options[idx - 1].innerHTML = in_html;
	the_list.options[idx - 1].value = val;
	the_list.selectedIndex = idx - 1;
}

function move_sel_list_option_down(the_list) {
	var idx = the_list.selectedIndex;
	if(idx == -1 || !the_list.options[idx + 1])
		return;
	var in_html = the_list.options[idx].innerHTML;
	var val = the_list.options[idx].value;
	the_list.options[idx].innerHTML = the_list.options[idx + 1].innerHTML;
	the_list.options[idx].value = the_list.options[idx + 1].value;
	the_list.options[idx + 1].innerHTML = in_html;
	the_list.options[idx + 1].value = val;
	the_list.selectedIndex = idx + 1;
}

function get_all_list_option_values(the_list) {
	var values = "";
	for(i = 0; i < the_list.options.length; i ++) {
		if(i > 0)
			values += ",";
		values += the_list.options[i].value;
	}
	return values;
}

function open_win(url, width, height, tgt) {
	return open_window(url, width, height, 0, null, null, tgt);
}

function open_window(url, win_width, win_height, menu, pos_left, pos_top, tgt, ret) {
	var scr_width = (screen.availWidth) ? screen.availWidth : 800;
	var scr_height = (screen.availHeight) ? screen.availHeight : 600;
	if((win_width == null) || (win_width <= 100) || (win_width > scr_width))
		win_width = scr_width - 100;
	if((win_height == null) || (win_height <= 100) || (win_height > scr_height - 75))
		win_height = scr_height - 75;
	if((pos_left == null) || (pos_left < 0) || (scr_width < pos_left + win_width))
		pos_left = (scr_width - win_width) / 2;
	if((pos_top == null) || (pos_top < 0) || (scr_height < pos_top + win_height))
		pos_top = ((scr_height - win_height) / 2) - 20;
	if(pos_top < 0)
		pos_top = 0;
	if(menu != 0 && menu != 1)
		menu = 0;
	var winpop;
	//if (winpop && (winpop.closed != true))
		//winpop.close();
	winpop = window.open(url, tgt, 'toolbar=0,location=0,directories=0,status=0,menubar=' + 
		menu + ',scrollbars=1,resizable=1,width=' + win_width + ',height=' + win_height + ',left=' + pos_left + ',top=' + pos_top);
	//winpop.focus();
	/*
	if(winpop.opener == null) {
		self.name = 'text';
		winpop.opener = self;
	}
	*/
	/*return true;*/
	if(ret)
		return winpop;
}

function repeatv(id) {
	repeat(id);
}

function repeat(id) {
	
	id = id + ':0';
	
	var o = document.getElementById(id);
	if(o == null)
		return;
		
	var h_id = id + '_repeat';
	var h = document.getElementById(h_id);
	if(h == null)
		return;

	var rpt = parseInt(h.getAttribute('value')) + 1;
	h.setAttribute('value', rpt);
	rpt--; //convert length to index

	var cloned = o.cloneNode(true);
	fix_repeated(cloned, rpt); //increment ids
	
	o.parentNode.appendChild(cloned);
	
	return cloned;
}


function fix_repeated(o, rpt) {
	
	for(var i = 0; i < o.childNodes.length; i++) {
		var x = o.childNodes[i];
		if(x.nodeName == "OPTION" || x.nodeType != 1) {
			continue;
		}
		if(x.nodeName == 'SELECT' || x.nodeName == 'INPUT' || x.nodeName == 'TEXTAREA') {
			var name = x.getAttribute('NAME');
			if(name != null) {
				var n = new String(name);
				var idx = n.lastIndexOf(':');
				if(idx != -1) {
					var name = n.substr(0, idx + 1) + rpt;
					x.setAttribute('NAME', name);
					if(name != x.getAttribute('NAME'))
						fix_name(x, name);
				}
			}
		}
		else if(x.hasChildNodes())
			fix_repeated(x, rpt);
	}
}

function fix_name(orig, name) { //for IE
	var es = '<' + orig.nodeName;
	if(orig.attributes) {
		for(i = 0, j = 0; i < orig.attributes.length; i++)
			if(orig.attributes[i].specified)
				if(orig.attributes[i].nodeName.toUpperCase() == 'NAME')
					es += ' ' + orig.attributes[i].nodeName + '="' + name + '"';
				else
					es += ' ' + orig.attributes[i].nodeName + '="' + orig.attributes[i].nodeValue + '"';
	}
	es += '>';
	
	if(orig.options) {
		var zz = new Array(orig.options.length);
		for(var i = 0; i < orig.options.length; i++)
			zz[i] = '<option value="' + orig.options[i].value + '">' + orig.options[i].text + '</option>';
		orig.parentNode.innerHTML = es + zz.join() + '</select>';
	}
	else {
		orig.parentNode.innerHTML = es;
	}
}

//1st version: just repeat and set
//2nd version: like v1 but search if the skill is already there, and change it if it is

function seek_and_set(p, arr) {
	if(arr.length == 0)
		return;
	for(var i = 0; i < p.childNodes.length; i++) {
		var x = p.childNodes[i];
		if(x.nodeName == 'SELECT') {
			//lookup the option
			var opt = arr.shift();
			for(var j = 0; j < x.options.length; j++) {
				if(x.options[j].value == opt) {
					x.selectedIndex = j;
					return;
				}
			}
		}
		else if(x.nodeName == 'INPUT') {
			x.value = arr.shift();
			return;
		}
		else if(x.hasChildNodes()) {
			seek_and_set(x, arr);
		}
	}		
}


function ge(id) {
	return document.getElementById(id);
}

function gen(id) {
	return document.getElementsByName(id);
}

function gens(id) {
	var col = document.getElementsByName(id);
	return col.length == 1 ? col.item(0) : null;
}

function get_reg_control(pid, variant) {
	if(control_reqister_arr == null)
		return null;
	if(!variant)
		variant = 0;
	for(var i = 0; i < control_reqister_arr.length; i += 2) {
		if(control_reqister_arr[i] == pid) {
			if(variant == 0) {
				return control_reqister_arr[i + 1];
			}
			else {
				variant--;
			}
		}
	}
	return null;
}

function gereg(pid, variant) {
	var id = get_reg_control(pid, variant);
	return id != null ? ge(id) : null;
}

function gereg_id(pid, variant) {
	return get_reg_control(pid, variant);
}

function geregx(fld, pcn, variant) {
	return gereg(processName + '_' + (pcn ? pcn : processClassName) + '.' + fld, variant); 
}

function geregx_id(fld, pcn, variant) {
	return gereg_id(processName + '_' + (pcn ? pcn : processClassName) + '.' + fld, variant); 
}


function check_with(orig_id, siva_id_with) {

	//var oval = ge(orig_id).value;
	var wth = gereg(siva_id_with).value;
	
	var hd = document.createElement('input');
	hd.setAttribute('type', 'hidden');
	hd.setAttribute('name', orig_id + '_check_with');
	hd.value = wth;
	ge('form').appendChild(hd);
}

var json;
function get_json() {
	if(json == null) {
		json = new JSONRpcClient(context_path + '/JSON-RPC');
	}
	return json;
}


function clear_select(select_id) {
	var s = document.getElementById(select_id);
	s.options.length = 0;
}

function find_option_idx(s, opt_id) {
	for(var i = 0; i < s.options.length; i++)
		if(s.options[i].value == opt_id)
			return i;
	return -1;
}

function select_select(select_id, option_id, no_fire) {
	var sel = ge(select_id);
	select_selecto(sel, option_id, no_fire); 
}

function select_selecto(sel, option_id, no_fire) {
	var prev = sel.selectedIndex;
	var opt_idx = find_option_idx(sel, option_id);
	sel.selectedIndex = -1; //IE NEEDS THIS
	sel.selectedIndex = opt_idx;
	if(!no_fire && prev != sel.selectedIndex)
		on_changeo(sel);
}

function on_change(select_id) {
	var s = document.getElementById(select_id);
	if(s.onchange != null && s.onchange != '')
		s.onchange();
}

function on_changeo(s) {
	if(s.onchange != null && s.onchange != '')
		s.onchange();
}

function set_value(input_id, val, a) {
	var s = document.getElementById(input_id);
	set_valueo(s, val, a);
}

function set_valueo(s, val, a) {
	if(val == null)
		val = '';
	if(s.tagName == 'SPAN' || s.tagName == 'DIV' || s.tagName == 'A') {
		var txt = s.firstChild;
		if(txt == null)
			s.appendChild(document.createTextNode(val));
		else if(txt.nodeType != 3)
			s.insertBefore(document.createTextNode(val), txt);
		else
			txt.nodeValue = val;
		if(a != null)
			s.href = a;
	}
	else
		s.value = val;
}

function get_select(select_id) {
	var s = document.getElementById(select_id);
	return s.selectedIndex == -1 ? null : s.options[s.selectedIndex].value;
}

function get_selecto(s) {
	return s.selectedIndex == -1 ? null : s.options[s.selectedIndex].value;
}

function get_multiselect(select_id) {
	var s = document.getElementById(select_id);
	return get_multiselecto(s);
}

function get_multiselecto(s) {
	var a = [];
	for(i = 0; i < s.options.length; i++) {
		if(s.options[i].selected) {
			a.push(s.options[i].value);
		}
	}
	return a;
}

function get_dynacheck_options(s) {
	var o = [];
	var cn = s.parentNode.childNodes;
	for(var i = 0; i < cn.length; i++) {
		var n = cn.item(i);
		if(n.nodeType == 1 && n.tagName == 'TABLE' && n.className == 'checkbox-div') {
			o.push(n);
		}
	}
	return o;
}

function is_dynacheck_option_checked(sel, opt) {
	return ge(opt.getAttribute('value') + '_' + sel.id).checked;
}

function check_dynacheck_option(sel, opt, to) {
	var o = ge(opt.getAttribute('value') + '_' + sel.id);
	if(!o)
		o = deep_find_first(opt, 'INPUT');
	o.checked = to;
}

function check_colacheck_option(sel, opt, to) {
	//dogz
	var o = ge(opt.getAttribute('value') + '_' + sel.id);
	if(!o)
		o = deep_find_first(opt, 'INPUT');
	o.checked = to;
}

function deep_find_first(o, tag) {
	var cn = o.childNodes;
	for(var i = 0; i < cn.length; i++) {
		var n = cn.item(i);
		if(n.nodeType == 1 && n.tagName == tag) {
			return n;
		}
		var r = deep_find_first(n, tag);
		if(r)
			return r;
	}
	return null;
}

function dynacheck_remove_option(sel, opt) {
	sel.parentNode.removeChild(opt);
}

function dynacheck_get_option_text(sel, opt) {
	return ge(opt.getAttribute('value') + '_' + sel.id + '_lb').firstChild.nodeValue; 
}

function dynacheck_set_option_text(sel, opt, text) {
	ge(opt.getAttribute('value') + '_' + sel.id + '_lb').firstChild.nodeValue = text;
}


/*
	<table class="checkbox-div" value="14">
	<tr>
		<td class="chk">
			<input type="checkbox" name="i75763" id="14_i75763" class="form-control form-control-wide checkbox" value="14">
		</td>
		<td class="lbl">
			<label for="14_i75763">Kraj Vysocina</label>
		</td>
	</tr>
	</table>
*/

function dynacheck_sel_create_option(sel, value, text) {

	var tb = document.createElement('TABLE');
	tb.className = 'checkbox-div';
	tb.setAttribute('value', value);
	tb.setAttribute('base-id', sel.id);
	
	var tr = tb.insertRow(tb.rows.length);
	
	var td1 = tr.insertCell(tr.cells.length);
	td1.className = 'chk';
	var td2 = tr.insertCell(tr.cells.length);
	td2.className = 'lbl';
	
	var ip = document.createElement('INPUT');
	ip.setAttribute('type', 'checkbox');
	ip.name = sel.id;
	var ipid = '' + value + '_' + sel.id;
	ip.id = ipid;
	ip.className = 'form-control form-control-wide checkbox';
	ip.value = value;
	ip.onclick = dynacheck_onchange;
	//ip.setAttribute('onchange', 'dynacheck_onchange(event)');
	td1.appendChild(ip);
	
	var lb = document.createElement('LABEL');
	lb.setAttribute('for', ipid);
	lb.id = value + '_' + sel.id + '_lb';
	lb.appendChild(document.createTextNode(text));
	td2.appendChild(lb);
	
	return tb;
}

function dynacheck_onchange(e) {
	if(!e) var e = window.event;
	var opt = e.target ? e.target : e.srcElement;
	var sel = ge(opt.name);
	if(sel.onchange)
		sel.onchange();
}

function set_selecto_colacheck(s, collection, key_id, name_id, filter, empty_option, specfunc, specfunc_args) {
	var tab = ge(ga(s, 'cola-id') + '_cola_tb');
	var sid = s.id;
	var opts = {};
	if(empty_option) {
		var o = { key: '', name: '' };
		opts[o.key] = o;
	}
	for(var d in collection) {
		if(filter != null && !filter(collection[d]))
			continue;
		var o = { key: collection[d][key_id], name: collection[d][name_id] };
		if(specfunc) {
			specfunc(o, collection[d], specfunc_args);
		}
		opts[o.key] = o;
	}
	//var ox = get_dynacheck_options(s);
	var ox = [];
	for(var i = 0; i < tab.rows.length; i++) {
		ox.push(tab.rows.item(i));
	}
	for(var i = 0; i < ox.length; i++) {
		var oxt = ox[i];
		var key = deep_find_first(oxt, 'INPUT').value;
		//var val = '' + oxt.getAttribute('value');
		var rot = opts[key];
		if(!rot) {
			//dynacheck_remove_option(s, oxt);
			tab.deleteRow(oxt.rowIndex);
		}
		else {
			var otxt = deep_find_first(oxt, 'LABEL').firstChild;
			var ot = '' + otxt.nodeValue; //dynacheck_get_option_text(s, oxt);
			var rt = rot.name; //dynacheck_get_option_text(s, rot);
			if(ot != rt) {
				//dynacheck_set_option_text(sel, oxt, rt);
				otxt.nodeValue = rt;
			}
		}
		delete opts[key];
	}
	for(var p in opts) {
		var opt = opts[p];
		//s.parentNode.appendChild(opt);
		var row = tab.insertRow(tab.rows.length);
		var c1 = row.insertCell(0);
		c1.className = 'cell1';
		var c2 = row.insertCell(1);
		c2.className = 'cell2';
		var inp = t('input', { type: 'checkbox', name: sid, id: opt.key + '_' + sid, value: opt.key });
		c1.appendChild(inp);
		c2.appendChild(t('label', { id: opt.key + '_' + sid + '_lb', $for: opt.key + '_' + sid, $text: opt.name }));
		if(opt.checked)
			inp.checked = true;
	}
}

function set_selecto_dynacheck(s, collection, key_id, name_id, filter, empty_option, specfunc, specfunc_args) {
	var opts = {};
	if(empty_option) {
		var o = dynacheck_sel_create_option(s, '', '');
		opts[o.getAttribute('value')] = o;
	}
	for(var d in collection) {
		if(filter != null && !filter(collection[d]))
			continue;
		var o = dynacheck_sel_create_option(s, collection[d][key_id], collection[d][name_id]);
		if(specfunc) {
			specfunc(o, collection[d], specfunc_args);
		}
		var val = '' + o.getAttribute('value');
		opts[val] = o;
	}
	var ox = get_dynacheck_options(s);
	for(var i = 0; i < ox.length; i++) {
		var oxt = ox[i];
		var val = '' + oxt.getAttribute('value');
		var rot = opts[val];
		if(!rot) {
			dynacheck_remove_option(s, oxt);
		}
		else {
			var ot = dynacheck_get_option_text(s, oxt);
			var rt = dynacheck_get_option_text(s, rot);
			if(ot != rt) {
				dynacheck_set_option_text(sel, oxt, rt);
			}
		}
		delete opts[val];
	}
	for(var p in opts) {
		var opt = opts[p];
		s.parentNode.appendChild(opt);
	}
}

function get_multiselecto_colacheck(s) {
	var a = [];
	/*
	var grp = document.getElementsByName(s.id); //IE7 returns element by ID here, if also defined, fuckers...
	for(var i = 0; i < grp.length; i++) {
		if(grp[i].checked == true) { //dogz
			a.push(grp[i].value);
		}
	}
	*/
	var tab = ge(ga(s, 'cola-id') + '_cola_tb');
	for(var i = 0; i < tab.rows.length; i++) {
		var cell = tab.rows.item(i).cells.item(0);
		var inp = cell.firstChild;
		if(inp.tagName != 'INPUT')
			inp = deep_find_first(cell, 'INPUT');
		if(inp.checked)
			a.push(inp.value);
	}
	return a;
}

function get_multiselecto_dynacheck(s) {
	var a = [];
	var opts = get_dynacheck_options(s);
	for(var i = 0; i < opts.length; i++) {
		if(is_dynacheck_option_checked(s, opts[i])) {
			a.push(opts[i].getAttribute('value'));
		}
	}
	return a;
}

function init_dynacheck_select(id) {
	var s = ge(id);
	//dogz
}

function get_select_text(select_id) {
	return get_select_texto(document.getElementById(select_id));
}

function get_select_texto(s) {
	if(s.selectedIndex == -1)
		return null;
	var n = s.options[s.selectedIndex];
	return n.firstChild != null ? n.firstChild.nodeValue : null;
}


function get_value(input_id) {
	var s = document.getElementById(input_id);
	var val = trim(s.value);
	if(val == '')
		return null;
	return val;
}

function trim(str) {
	return str == null ? null : str.replace(/^\s*|\s*$/g,"");
}

function toggle(d) {
	var dv = document.getElementById(d);
	if(dv == null)
		return;
	dv.style.display = dv.style.display == '' || dv.style.display == 'none' ? 'block' : 'none';
}

function hide(d) {
	var dv = document.getElementById(d);
	if(dv == null)
		return;
	dv.style.display = 'none';
}

function hideo(dv) {
	if(dv == null)
		return;
	dv.style.display = 'none';
}

function show(d) {
	var dv = document.getElementById(d);
	if(dv == null)
		return;
	dv.style.display = 'block';
}

function showo(dv) {
	if(dv == null)
		return;
	dv.style.display = 'block';
}


function check_box(box_id, check) {
	var chk = document.getElementById(box_id);
	if(chk)
		chk.checked = check;
}

function get_check_box(box_id) {
	var chk = document.getElementById(box_id);
	return chk.checked;
}

function search_col(col, prop, val) {
	for(var k in col) {
		if(col[k][prop] == val)
			return col[k];
	}
	return null;
}

function set_selecto_OFF(s, collection, key_id, name_id, filter, empty_option, specfunc, specfunc_args) {

	//clear & create
	s.selectedIndex = -1;
	s.options.length = 0;
	
	//if(collection.length == 0)
		//return;

	if(empty_option) {
		var o = document.createElement('option');
		o.value = '';
		o.innerHTML = '';
		s.appendChild(o);
	}
	
	for(var d in collection) {
		if(filter != null && !filter(collection[d]))
			continue;
		var o = document.createElement('option');
		o.value = collection[d][key_id];
		o.innerHTML = collection[d][name_id];
		if(specfunc) {
			specfunc(o, collection[d][key_id], collection[d][name_id], specfunc_args);
		}
		s.appendChild(o);
	}
}

function set_selecto(s, collection, key_id, name_id, filter, empty_option, specfunc, specfunc_args) {
	var opts = {};
	if(empty_option) {
		var o = document.createElement('option');
		o.value = '';
		o.innerHTML = '';
		opts[o.value] = o;
	}
	for(var d in collection) {
		if(filter != null && !filter(collection[d]))
			continue;
		var o = document.createElement('option');
		o.value = collection[d][key_id];
		o.innerHTML = collection[d][name_id];
		if(specfunc) {
			specfunc(o, collection[d][key_id], collection[d][name_id], specfunc_args);
		}
		opts[o.value] = o;
	}
	for(var i = 0; i < s.options.length;) {
		var opt = s.options[i];
		var rot = opts[opt.value];
		if(!rot) {
			s.remove(i);
		}
		else {
			if(opt.innerHTML != rot.innerHTML)
				opt.innerHTML = rot.innerHTML;
			i++;
		}
		delete opts[opt.value];
	}
	for(var p in opts) {
		var opt = opts[p];
		s.appendChild(opt);
	}
}

function add_selecto(s, value, name) {
	for(var i = 0; i < s.options.length; i++) {
		if(s.options[i].value == value)
			return;
	}
	var o = document.createElement('option');
	o.value = value;
	o.innerHTML = name;
	s.appendChild(o);
}

function create_row(parent_element, cells) {
	var tr = parent_element.insertRow(parent_element.rows.length);
	for(var c in cells) {
		var td = tr.insertCell(tr.cells.length);
		td.innerHTML = cells[c] == null ? '' : cells[c];
	}
	return tr;
}

function create_row2(parent_element, cells, clazzes) {
	var tr = parent_element.insertRow(parent_element.rows.length);
	for(var c in cells) {
		var td = tr.insertCell(tr.cells.length);
		td.innerHTML = cells[c] == null ? '' : cells[c];
		if(clazzes != null)
			td.className = clazzes[c];
	}
	return tr;
}

function create_row3(parent_element, cells, setfunc) {
	var tr = parent_element.insertRow(parent_element.rows.length);
	for(var c in cells) {
		var td = tr.insertCell(tr.cells.length);
		setfunc(td, cells[c], cells, c);
	}
	return tr;
}

function create_table(parent_element, clazz, headings, cellpadding, cellspacing) {
	var t = document.createElement('table');
	if(clazz != null)
		t.className = clazz;
	if(headings != null) {
		var th = t.createTHead();
		create_row(th, headings);
	}
	parent_element.appendChild(t);
	return t;
}


function init_lists_editor(editor_id) {
	var lists_editor_categories = ge('lists_editor_categories');
	if(!lists_editor_categories)
		return;

	get_json();
	var cats = json.DataTypesServer.listDataTypeCategories();
	
	set_selecto(lists_editor_categories, cats, 0, 1, null, true);
	on_changeo(lists_editor_categories);
}

function list_editor_row_creator(cell, data, alldata, iter) {
	if(iter == 0) {
		cell.innerHTML = data;
	}
	else {
		var f = document.createElement('input');
		f.setAttribute('type', 'text');
		f.className = 'form-control';
		//f.name = alldata[0] + '_' + iter;
		f.value = data;
		cell.origval = data;
		cell.appendChild(f);
	}
}

function lists_editor_categories_onchange() {
	var lists_editor_categories = ge('lists_editor_categories');
	if(!lists_editor_categories)
		return;
	var content = ge('list_editor_content');
	if(!content)
		return;
	//get rid of old table
	var table = ge('list_editor_table');
	if(table) {
		table.parentNode.removeChild(table);
		delete table;
	}
	
	var cat_id = get_selecto(lists_editor_categories);
	if(!cat_id)
		return;
	var cat_items = json.DataTypesServer.listDataTypeCategoryItems(cat_id);
	var cat_items_headers = cat_items.shift();
	
	//create new table
	table = document.createElement('table');
	table.id = 'list_editor_table';
	//table.setAttribute('style', 'width: 100%;');
	
	var th = table.createTHead();
	create_row(th, cat_items_headers);
	
	content.appendChild(table);

	for(var ci in cat_items) {
		create_row3(table, cat_items[ci], list_editor_row_creator);
	}
}

function lists_editor_add_item() {
	//just add new editors to the table (infer based on previous row)
	var table = ge('list_editor_table');
	if(!table)
		return;

	var data = [ '' ];
	var cnt = table.rows[table.rows.length - 1].cells.length;
	for(var i = 1; i < cnt; i++)
		data[i] = '';

	create_row3(table, data, list_editor_row_creator);
}

function lists_editor_commit_changes() {
	//go through the table and detect changed AND add ADDED items and update with server accordingly; then refresh by calling onchange
	var lists_editor_categories = ge('lists_editor_categories');
	if(!lists_editor_categories)
		return;
	var cat_id = get_selecto(lists_editor_categories);
	if(!cat_id)
		return;
	var table = ge('list_editor_table');
	if(!table)
		return;

	for(var rr = 1; rr < table.rows.length; rr++) {
		var cx = table.rows[rr].childNodes;
		var data = [];
		var changed = false;
		var del = true;
		for(var cc = 1; cc < cx.length; cc++) {
			var cell = cx[cc];
			var f = cell.firstChild;
			if(f.value != cell.origval)
				changed = true;
			if(f.value != '')
				del = false;
			data.push(f.value);
		}
		if(del) {
			try {
				var id = cx[0].innerHTML;
				if(id != '')
					json.DataTypesServer.deleteDataTypeItem(cat_id, id);
			}
			catch(e) {
				alert('Delete failed: ' + e);
			}
		}
		else if(changed) {
			var id = cx[0].innerHTML;
			if(id == '') { //add
				//alert('adding: ' + cat_id + ', [n/a] ' + data);
				try {
					json.DataTypesServer.addDataTypeItem(cat_id, data);
				}
				catch(e) {
					alert('Add failed: ' + e);
				}
			}
			else { //update
				//alert('updating: ' + cat_id + ', [' + id + '] ' + data);
				try {
					json.DataTypesServer.updateDataTypeItem(cat_id, id, data);
				}
				catch(e) {
					alert('Update failed: ' + e);
				}
			}
		}
	}

/*
	var rowcnt = 0;
	for(var rr in table.rows) {
		if(rowcnt == 0) {
			rowcnt++;
			continue;
		}
		var row = table.rows[rr];
		var changed = false;
		var data = [];
		var icnt = 0;
		var first_cell;
		for(var c in row.childNodes) {
			if(icnt == 0) {
				var cell = row.childNodes[c];
				if(!cell.tagName || cell.tagName != 'TD')
					continue;
				first_cell = cell;
				icnt++;
				continue;
			}
			var cell = row.childNodes[c];
			if(!cell.origval)
				continue;
			if(cell.origval != cell.innerHTML) {
				alert('change: ' + cell.origval + ' --> ' + cell.innerHTML);
				changed = true;
			}
			data.push(cell.innerHTML);
		}
		if(changed) {
			var id = first_cell.innerHTML;
			if(id && id.length > 0) { //update
				alert('updating: [' + id + ']');
				try {
					json.DataTypesServer.updateDataTypeItem(cat_id, id, data);
				}
				catch(e) {
					alert('Update failed: ' + e);
				}
			}
			else { //add
				try {
					json.DataTypesServer.addDataTypeItem(cat_id, data);
				}
				catch(e) {
					alert('Add failed: ' + e);
				}
			}
		}
	}
*/
	//call onchange
	on_changeo(lists_editor_categories);
}

function xml_action(act_id) {
	set_value('xml_config_edit_action', act_id);
	post('none', 'none');
}

function xml_action_zero(act_id) {
	set_value('__xml_version_id', '0');
	xml_action(act_id);
}

function xml_action_code(act_id, version_id, is_public) {
	set_value('__xml_version_id', version_id);
	set_value('__xml_public_mode', is_public);
	xml_action(act_id);
}

function check_tss_radio(ra_id) {
	var r = ge(ra_id);
	if(r == null || !r.checked)
		return;
	var group_id = r.name;
	//find the others in group
	var grp = document.getElementsByName(group_id);
	for(var i = 0; i < grp.length; i++) {
		if(grp[i].id != ra_id) {
			enable_tss(grp[i], false);
		}
	}
	enable_tss(r, true);
}

function enable_tss(radio, enable) {
	//radio --> input --> select --> select
	var x;
	for(x = radio.nextSibling; x && x.tagName != 'INPUT'; x = x.nextSibling);
	if(!x) return;
	x.disabled = !enable;
	for(x = x.nextSibling; x && x.tagName != 'SELECT'; x = x.nextSibling);
	if(!x) return;
	x.disabled = !enable;
	for(x = x.nextSibling; x && x.tagName != 'SELECT'; x = x.nextSibling);
	if(!x) return;
	x.disabled = !enable;
}

function show_gmap_pinpoint(id, api_code, lon, lat, search_hint, dflt_lat, dflt_lon, key) {
	var a = ge(id + '_a');
	var m = ge(id + '_map');
	var f = ge(id + '_frm');
	if(!a || !m || !f) return;
	if(!f.src) f.src = '/core/tools/gmaps-pinpoint.jsps?api-code=' + encodeURIComponent(api_code) 
		+ '&search-hint=' + encodeURIComponent(search_hint) + '&key=' + encodeURIComponent(key) 
		+ '&lon=' + encodeURIComponent(lon)
		+ '&lat=' + encodeURIComponent(lat)
		+ '&dflt-lat=' + encodeURIComponent(dflt_lat)
		+ '&dflt-lon=' + encodeURIComponent(dflt_lon);
	hideo(a);
	showo(m);
}

function show_gmap_view(id, api_code, lon, lat) {
	var a = ge(id + '_a');
	var m = ge(id + '_map');
	var f = ge(id + '_frm');
	if(!a || !m || !f) return;
	if(!f.src) f.src = '/core/tools/gmaps-view.jsps?api-code=' + encodeURIComponent(api_code) 
		+ '&lon=' + encodeURIComponent(lon)
		+ '&lat=' + encodeURIComponent(lat);
	hideo(a);
	showo(m);
}

var ch_radio_ids, ch_max_user, ch_list_ids;

function init_clearing_house(max_user, radio_ids, list_ids) {
	ch_radio_ids = radio_ids;
	ch_max_user = max_user;
	ch_list_ids = list_ids;
}

function ch_enable_all(uid, enable) {
	for(var i = 0; i < ch_radio_ids.length; i++) {
		var r = ge(ch_radio_ids[i] + ':' + uid);
		if(r != null)
			r.disabled = !enable;
	}
	for(var i = 0; i < ch_list_ids.length; i++) {
		var lid = ch_list_ids[i] + ':' + uid + '_';
		for(var j = 0; ; j++) {
			var lod = lid + j;
			var ch = ge(lod);
			if(ch == null)
				break;
			ch.disabled = !enable;
		}
	}
}

function ch_select_radios(uid) {
	for(var i = 0; i < ch_radio_ids.length; i++) {
		var r = ge(ch_radio_ids[i] + ':' + uid);
		if(r != null)
			r.checked = true;
	}
}

function ch_select_checkboxes(uid) {
	for(var i = 0; i < ch_list_ids.length; i++) {
		var lid = ch_list_ids[i] + ':' + uid + '_';
		for(var j = 0; ; j++) {
			var lod = lid + j;
			var ch = ge(lod);
			if(ch == null)
				break;
			ch.checked = true;
		}
	}
}

function ch_selector_onchange(sel) {
	var ar, val = get_selecto(sel), uid = /:(\d+)/.exec(sel.id)[1];
	if(val == 'master') {
		//only single master
		for(var i = 0; i < ch_max_user; i++) {
			var s = ge('ch-selector:' + i);
			var val = get_selecto(s);
			if(val == 'master' && s != sel) {
				if(!ar) {
					alert('There can be only one master - I\'m auto-resetting the other one, please review.');
					ar = true;
				}
				s.selectedIndex = -1;
				//no value -> disable all
				ch_enable_all(uid, false);
			}
		}
		//master -> enable all & select radios + checkboxes
		ch_enable_all(uid, true);
		ch_select_radios(uid);
		ch_select_checkboxes(uid);
		
	}
	else if(val == 'delete') {
		//merge -> enable all & select checkboxes
		ch_enable_all(uid, true);
		ch_select_checkboxes(uid);
	}
	else if(val == 'nodupe') {
		//nodupe -> disable all
		ch_enable_all(uid, false);
	}
	else if(val == 'leave' || val == '' || !val) {
		//leave -> disable all
		//no value -> disable all
		ch_enable_all(uid, false);
	}
}

function initDataFilterContextMenu(list_id, id) {
	var aItems = [
		{ text: "Today" },
		{ text: "This Week" },
		{ text: "Last Week" },
		{ text: "This Month" },
		{ text: "All" },
		{ text: "Custom" }
	];
	var menu = new YAHOO.widget.Menu("dataFilterMenu_" + id); //, { constraintoviewport: true, x: 100, y: 100, container: list_id });
	menu.addItems(aItems);
	var edit = ge(id);
	edit.dataFilterMenu = menu;
	menu.theEditField = edit;
	menu.theListID = list_id;
	menu.render(document.body); //ge(list_id));
	menu.hideEvent.subscribe(menuHidden, menu, true);
	menu.clickEvent.subscribe(menuClicked, menu, true);
	
	//rangePickerOverlay
	
	var ovr = new YAHOO.widget.Overlay("ovr_" + id, { context:[id,"tl","bl"], visible:false } );
	ovr.setBody('<table cellpadding="2" cellspacing="1" class="dateRangePicker">' +
		'<tr><td align="center">From</td><td align="center">To</td></tr>' +
		'<tr><td align="center"><div id="div_cal_from_' + id + '" style="padding: 0px;"></div></td><td align="center"><div id="div_cal_to_' + id + '" style="padding: 0px;"></div></td></tr>' +
		'<tr><td align="right"><button id="ok_cal_' + id + '">OK</button></td><td align="left"><button id="cancel_cal_' + id + '">Cancel</button></td></tr>' +
		'</table>');
	ovr.render(document.body); 
	var cal_from = new YAHOO.widget.Calendar("cal_from_" + id, "div_cal_from_" + id);
	cal_from.IMG_ROOT = '/core/yui/calendar/assets/';
	var cal_to = new YAHOO.widget.Calendar("cal_to_" + id, "div_cal_to_" + id);
	cal_from.render();
	cal_to.render();
	
	YAHOO.util.Event.addListener("ok_cal_" + id, "click", setCalRange, edit, true);
	YAHOO.util.Event.addListener("cancel_cal_" + id, "click", ovr.hide, ovr, true);
	
	edit.calendarsOverlay = ovr;
	edit.cal_from = cal_from;
	edit.cal_to = cal_to;
	edit.theListID = list_id;
}

function setCalRange(p_sType, p_aArgs, p_oBj) {
	var edit = p_aArgs;
	if(!edit)
		return;
	
	var from = getYMD(edit.cal_from);
	var to = getYMD(edit.cal_to);
	
	edit.calendarsOverlay.hide();
	
	if(from != null && to != null) {
		edit.value = 'between ' + from + ' -- ' + to;
		post(edit.id, edit.theListID);
	}
}

function getYMD(cal) {
	var d = cal.getSelectedDates();
	if(!d || d.length != 1)
		return null;
	return d[0].getFullYear() + '-' + (d[0].getMonth() + 1) + '-' + d[0].getDate();
}


function show_datefilter_menu(e) {
	if(!e) var e = window.event;
	var targ = e.target ? e.target : e.srcElement;
	if(!targ.dataFilterMenu)
		return;
	var menu = targ.dataFilterMenu;
	if(!menu)
		return;

	if(menu.theEditField.nofire && menu.theEditField.nofire == true) {
		menu.theEditField.nofire = false;
		return;
	}
	
	var xy = YAHOO.util.Dom.getXY(targ);
	var reg = YAHOO.util.Region.getRegion(targ);
	menu.moveTo(xy[0], reg.bottom);
	menu.show();
}

function menuHidden(p_sType, p_aArgs, p_oMenu) {
	p_oMenu.theEditField.nofire = true;
	p_oMenu.theEditField.focus();
}

function menuClicked(p_sType, p_aArgs, p_oMenu) {
	var oItem = p_aArgs[1];
	if(!oItem)
		return;
	var txt = oItem.cfg.getProperty("text");
	if(txt == 'All')
		txt = '';
	if(txt == 'Custom') {
	
		var xy = YAHOO.util.Dom.getXY(p_oMenu.theEditField);
		var reg = YAHOO.util.Region.getRegion(p_oMenu.theEditField);
		p_oMenu.theEditField.calendarsOverlay.moveTo(xy[0] - 100, reg.bottom);
		p_oMenu.theEditField.calendarsOverlay.show();
	}
	else {
		p_oMenu.theEditField.value = txt;
		post(p_oMenu.theEditField.id, p_oMenu.theListID);
	}
}

function checkListItem(list_id, item_id, val) {
	checkListItemPageF(list_id, item_id, val, false);
}

function checkListItemPage(list_id, item_id, val) {
	checkListItemPageF(list_id, item_id, val, true);
}

function checkListItemPageF(list_id, item_id, val, use_page) {
	try {
		var ret = get_json().ListCheckServer.checkItem(list_id, item_id, val, use_page);
		ge('chk_' + list_id + '_' + item_id).checked = val;
		var all = ge('chk_' + list_id);
		if(all)
			all.checked = ret;
	}
	catch(x) {
		alert('Error checking the checkbox, please reload the page. (' + x + ')');
	}
}

function jobEmailToFriend() {
	var a = ge('email-job-to-friend');
	if(!a)
		return;
		
	if(!get_json().PublicServer.isUserLoggedIn()) {
		alert("You have to be logged in to access this function.");
		return;
	}
	

	if(!a.ovr) {
		var ovr = new YAHOO.widget.Overlay("ovr-email-job-to-friend", { context:[a,"tl","bl"], visible:false } );
		ovr.setBody('<table cellpadding="2" cellspacing="1" style="background-color: white; border: 1px solid lightblue;">' +
			'<tr><td align="left">Email:</td><td align="right"><input type="text" id="ejtf_email" style="width: 150px;"/></td></tr>' +
			'<tr><td align="left" valign="top">Message:</td><td align="right"><textarea id="ejtf_msg" style="width: 150px;" rows="3"></textarea></td></tr>' +
			'<tr><td align="center" colspan="2"><button id="ok_ejtf">OK</button>&nbsp;&nbsp;<button id="cancel_ejtf">Cancel</button></td></tr>' +
			'</table>');
		ovr.render(document.body); 
		
		YAHOO.util.Event.addListener("ok_ejtf", "click", sendEmailEJTF, ovr, true);
		YAHOO.util.Event.addListener("cancel_ejtf", "click", ovr.hide, ovr, true);
		
		a.ovr = ovr;
	}
	
	var xy = YAHOO.util.Dom.getXY(a);
	var reg = YAHOO.util.Region.getRegion(a);
	a.ovr.moveTo(xy[0], reg.bottom);
	a.ovr.show();
	ge('ejtf_email').focus();
}

function sendEmailEJTF(p_sType, p_aArgs, p_oMenu) {
		
	var a = ge('email-job-to-friend');
	var email = get_value('ejtf_email');
	var msg = get_value('ejtf_msg');
	
	if(!email || email == '') {
		alert('Email must not be empty.');
		return;
	}
	
	ge('ok_ejtf').disabled = true;
	ge('ok_ejtf').value = 'Sending...';
	
	try {
		get_json().PublicServer.sendEmail(email, msg, ge('sjtf_jobid').value);
		alert('Email to ' + email + ' sent successfully.');
	}
	catch(e) {
		alert('Sending failed: ' + e);
	}
	
	ge('ok_ejtf').value = 'OK';
	ge('ok_ejtf').disabled = false;
	a.ovr.hide();
}

function sl(o, i) { o.style.left = i; o.left = i;  }
function st(o, i) { o.style.top = i; o.top = i;  }
function sw(o, i) { o.style.width = i; o.width = i;  }
function sh(o, i) { o.style.height = i; o.height = i;  }

function buildAjaxCalendar() {
	var base = ge('ajax-calendar');
	if(!base)
		return;
		
	//var om = new YAHOO.widget.OverlayManager();
	//base.om = om;
	var oreg = new Object();
	base.oreg = oreg;
	
	base.acal_date = new Date();
	var w = base.parentNode.clientWidth;
	var cw = Math.round(w / 7);
	base.cw = cw;

	var xy = YAHOO.util.Dom.getXY(base);
	var y = xy[1];
	var h = 81;
	var h2 = 20;
	var x = xy[0];
	var h3 = 21;
	var h4 = 21;
	var wtop = 150;
	var wtop2 = 200;
	
	var top = new YAHOO.widget.Overlay('accal_top', { x:x, y:y, height: h4 });
	top.setBody("<button id='ac_prev' class='ac_butt'>Prev</button>&nbsp;<button id='ac_next' class='ac_butt'>Next</button>&nbsp;<button id='ac_now' class='ac_butt'>Now</button>");
	top.render(document.body);
	YAHOO.util.Event.addListener("ac_prev", "click", acCalPrev, top, true);
	YAHOO.util.Event.addListener("ac_next", "click", acCalNext, top, true);
	YAHOO.util.Event.addListener("ac_now", "click", acCalNow, top, true);
	wtop = top.element.clientWidth + 14; //YAHOO.util.Dom.getXY(top.element)[0] + ;
	x += wtop;
	
	var top2 = new YAHOO.widget.Overlay('accal_top2', { x:x, y:y, width: wtop2, height: h4 });
	base.top2 = top2;
	base.top2.setBody('Loading...');
	top2.render(document.body);
	YAHOO.util.Dom.addClass(top2.element, 'ac-top2');
	x += wtop2;
	y += h4;
	
	var days = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ];
	x = xy[0];
	for(col = 0; col < 7; col++) {
		//var ovr = new YAHOO.widget.Overlay('hdays_' + col, { x:x, y:y, width: cw, height:h3 });
		//ovr.setBody(days[col]);
		//ovr.render(document.body);
		//if(col == 0)
		//	YAHOO.util.Dom.addClass(ovr.element, 'ac-firstcol-days');
		//YAHOO.util.Dom.addClass(ovr.element, 'ac-cell-days');
		
		var ovr = document.createElement('DIV');
		ovr.className = col == 0 ? 'ac-firstcol-days ac-cell-days' : 'ac-cell-days';
		sl(ovr, x);
		st(ovr, y);
		sw(ovr, cw);
		sh(ovr, h3);
		var at = document.createTextNode(days[col]);
		ovr.appendChild(at);
		document.body.appendChild(ovr);
		
		x += cw;
	}
	y += h3;

	for(row = 0; row < 5; row++) {
		x = xy[0];
		for(col = 0; col < 7; col++) {
			var xid = 'hday_' + row + '_' + col;
			/*var ovr = new YAHOO.widget.Overlay(xid, { x:x, y:y, width: cw, height:h2 });
			ovr.setBody('.');
			ovr.render(document.body);
			//om.register(ovr);
			oreg[xid] = ovr;
			if(col == 0)
				YAHOO.util.Dom.addClass(ovr.element, 'ac-firstcol-head');
			YAHOO.util.Dom.addClass(ovr.element, 'ac-cell-head');*/
			
			var ovr = document.createElement('DIV');
			ovr.className = col == 0 ? 'ac-firstcol-head ac-cell-head' : 'ac-cell-head';
			sl(ovr, x);
			st(ovr, y);
			sw(ovr, cw);
			sh(ovr, h2);
			var at = document.createTextNode('.');
			ovr.appendChild(at);
			document.body.appendChild(ovr);
			oreg[xid] = ovr;
			
			x += cw;
		}
		y += h2;
		
		x = xy[0];
		for(col = 0; col < 7; col++) {
			var xid = 'bday_' + row + '_' + col;
			/*var ovr = new YAHOO.widget.Overlay(xid, { x:x, y:y, width:cw, height:h });
			ovr.base_height = h;
			ovr.render(document.body);
			//om.register(ovr);
			oreg[xid] = ovr;
			if(col == 0)
				YAHOO.util.Dom.addClass(ovr.element, 'ac-firstcol');
			YAHOO.util.Dom.addClass(ovr.element, 'ac-cell');*/
			
			var ovr = document.createElement('DIV');
			ovr.className = col == 0 ? 'ac-firstcol ac-cell' : 'ac-cell';
			sl(ovr, x);
			st(ovr, y);
			sw(ovr, cw);
			sh(ovr, h);
			ovr.base_height = h;
			document.body.appendChild(ovr);
			oreg[xid] = ovr;
			
			x += cw;
		}
		y += h;
	}
	
	acalRefresh();
}

function acCalPrev(p_sType, p_aArgs, p_oMenu) {
	var dd = ge('ajax-calendar').acal_date;
	dd.setMonth(dd.getMonth() - 1);
	acalRefresh();
}

function acCalNext(p_sType, p_aArgs, p_oMenu) {
	var dd = ge('ajax-calendar').acal_date;
	dd.setMonth(dd.getMonth() + 1);
	acalRefresh();
}

function acCalNow(p_sType, p_aArgs, p_oMenu) {
	ge('ajax-calendar').acal_date = new Date();
	acalRefresh();
}

function acalRefresh() {
	var base = ge('ajax-calendar');
	var dd = base.acal_date;
	var maxy = 550;
	var ret;
	try {
		base.top2.setBody('Loading...');
		ret = get_json().AjaxCalendarServer.refresh(dd.getTime());
	}
	catch(e) {
		alert('Calendar refresh failed, please refresh the page. (' + e + ')');
		base.top2.setBody('Loading failed.');
		return;
	}
	
	if(base.zz) {
		for(i in base.zz)
			//base.zz[i].destroy();
			base.zz[i].parentNode.removeChild(base.zz[i]);
	}
	base.zz = new Array();
	
	/*if(!base.zz)
		base.zz = new Array(0);
	var zz2 = new Array(0);*/
	
	var event_height = 38;
	var event_space = 0;
	var ehs = event_height + event_space;
	
	var xstart = new Date().getTime();
	
	base.top2.setBody('' + ret.title);
	var data = ret.data;
	for(var row = 0; row < 5; row++) {
		for(var col = 0; col < 7; col++) {
			var d = data[row * 7 + col];
			var bday = base.oreg['bday_' + row + '_' + col];
			bday.className = (col == 0 ? 'ac-firstcol ac-cell' : 'ac-cell') + (d.thisDay ? ' ac-today' : '');
			
			if(col == 0) {
				var mh = 2 + (d.max_row_events * ehs);
				if(mh < bday.base_height)
					mh = bday.base_height;
				var dmh = mh - bday.height;// bday.cfg.getProperty('height');
				if(dmh != 0) {
					for(rx = row; rx < 5; rx++) {
						if(rx > row) {
							for(cx = 0; cx < 7; cx++) {
								var bx = base.oreg['hday_' + rx + '_' + cx];
								//bx.cfg.setProperty('y', bx.cfg.getProperty('y') + dmh, false);
								//bx.style.top = bx.style.top + dmh;
								st(bx, bx.top + dmh);
							}
						}
						for(cx = 0; cx < 7; cx++) {
							var bx = base.oreg['bday_' + rx + '_' + cx];
							if(rx == row)
								//bx.cfg.setProperty('height', mh, false);
								//bx.style.height = mh;
								sh(bx, mh);
							else
								//bx.cfg.setProperty('y', bx.cfg.getProperty('y') + dmh, false);
								//bx.style.top = bx.style.top + dmh;
								st(bx, bx.top + dmh);
						}
					}
				}
			}
			//var dr = new Date().getTime();
			for(k in d.items) {
				var x = d.items[k];
				if(x.orig != row * 7 + col)
					continue;
				var xx = bday.left + 1; //bday.cfg.getProperty('x');
				var yy = bday.top + 2 + (x.slot * ehs); //bday.cfg.getProperty('y') + 1;
				var ww = (base.cw * x.span) - 3;
				var hh = event_height - 2;
				/*var ovr;
				if(base.zz.length > 0) {
					ovr = base.zz.pop();
					//TODO: moveTo
					ovr.cfg.setProperty("x", xx);
					ovr.cfg.setProperty("y", yy + (x.slot * ehs));
					ovr.cfg.setProperty("width", ww);
					ovr.cfg.setProperty("height", hh);
					ovr.setBody('<a href="' + x.link + '">' + x.title + '</a>');
				}
				else {
					ovr = new YAHOO.widget.Overlay('act_' + dr + '_' + k, { x:xx, y:yy + (x.slot * ehs), width: ww, height: hh });
					YAHOO.util.Dom.addClass(ovr.element, 'ac-cell-evt');
					ovr.setBody('<a href="' + x.link + '">' + x.title + '</a>');
					ovr.render(document.body);
				}
				zz2.push(ovr);
				*/
				
				/*var ovr = new YAHOO.widget.Overlay('act_' + x.act_id, { x:xx, y:yy + (x.slot * ehs), width: ww, height: hh });
				ovr.setBody('<a href="' + x.link + '">' + x.title + '</a>');
				YAHOO.util.Dom.addClass(ovr.element, 'ac-cell-evt');
				ovr.render(document.body);
				base.zz.push(ovr);*/
				
				var ovr = document.createElement('DIV');
				ovr.className = 'ac-cell-evt';
				ovr.style.left = xx;
				ovr.style.top = yy;
				ovr.style.width = ww;
				ovr.style.height = hh;
				maxy = ww + hh;
				var a = document.createElement('A');
				a.setAttribute('href', x.link);
				var at = document.createTextNode(x.title);
				a.appendChild(at);
				ovr.appendChild(a);
				base.zz.push(ovr);
				document.body.appendChild(ovr);
				
				base.zz.push(wc(xx, yy));
				base.zz.push(wc(xx, yy + hh -1));
				base.zz.push(wc(xx + ww - 1, yy));
				base.zz.push(wc(xx + ww - 1, yy + hh -1));
				
			}
			var hday = base.oreg['hday_' + row + '_' + col];
			//hday.setBody('' + d.day);
			hday.firstChild.nodeValue = '' + d.day;
			hday.className = (col == 0 ? 'ac-firstcol-head ac-cell-head' : 'ac-cell-head') 
				+ (d.thisMonth == true ? '' : ' ac-othermonth');
		}
	}
	
	var xend = new Date().getTime();
	//alert('ms: ' + (xend - xstart));
	
	/*for(i in base.zz)
		base.zz[i].destroy();
	base.zz = zz2;*/
	
	base.style.height = (maxy + 50) + 'px';
}

function wc(x, y) {
	var wp = document.createElement('DIV');
	wp.className = 'wpic';
	wp.style.left = x;
	wp.style.top = y;
	wp.style.width = 1;
	wp.style.height = 1;
	document.body.appendChild(wp);
	return wp;
}

var tabs = {};

function register_tab(parent_id, tab_id) {
	var x = tabs[parent_id];
	if(!x) {
		x = new Array();
		tabs[parent_id] = x;
	}
	//x.unshift(tab_id);
	x.push(tab_id);
}

function switch_tab(parent_id, base_id, title, proc_mode) {
	var blue = proc_mode ? 'blue2' : 'blue';
	var x = tabs[parent_id]
	if(!x)
		return;
	var idx = 0;
	for(i = 0; i < x.length; i++) {
		var prevsel = i > 0 && x[i-1] == base_id;
		if(x[i] == base_id) {
			idx = i + 1;
			ge(x[i] + '_div').className = 'hidden-tab visible-tab';
			var xt1 = ge(x[i] + '_t1');
			if(xt1)
				xt1.className = 'tabs tabs-' + (i == 0 ? ('none-' + blue) : (prevsel ? blue : 'gray') + '-' + blue);
			var xt2 = ge(x[i] + '_t2');
			if(xt2)
				xt2.className = 'tabs tabs-' + blue + '-bkg';
			if(i == x.length - 1) {
				var xt3 = ge(x[i] + '_t3');
				if(xt3)
					xt3.className = 'tabs tabs-' + blue + '-none';
			}
			var xt4 = ge(x[i] + '_t4');
			if(xt4)
				xt4.className = 'sel-true';
			
			var qf = ge(x[i] + '_qf');
			if(qf)
				qf.style.display = 'block';
				
			//view quick search
			var vqs = ge(x[i] + '_vqs');
			if(vqs)
				vqs.style.display = 'block';
				
			var hr = ge(x[i] + '_hr' );
			if(hr)
				hr.style.display = 'block';
			
			var sf_on = x[i] + '_sf';
			if(window[sf_on])
				window[sf_on]();
		}
		else {
			ge(x[i] + '_div').className = 'hidden-tab';
			var xt1 = ge(x[i] + '_t1');
			if(xt1)
				xt1.className = 'tabs tabs-' + (i == 0 ? 'none-gray' : (prevsel ? blue : 'gray') + '-gray');
			var xt2 = ge(x[i] + '_t2');
			if(xt2)
				xt2.className = 'tabs tabs-' + 'gray' + '-bkg';
			if(i == x.length - 1) {
				var xt3 = ge(x[i] + '_t3');
				if(xt3)
					xt3.className = 'tabs tabs-gray-none';
			}
			var xt4 = ge(x[i] + '_t4');
			if(xt4)
				xt4.className = 'sel-false';

			var qf = ge(x[i] + '_qf');
			if(qf)
				qf.style.display = 'none';
				
			//view quick search
			var vqs = ge(x[i] + '_vqs');
			if(vqs)
				vqs.style.display = 'none';
			
			var hr = ge(x[i] + '_hr' );
			if ( hr)
				hr.style.display = 'none';
		}
	}
	try {
		var store_id = !title || title == '' ? parent_id : title;
		get_json().UIServer.storeSectionPreset(store_id, idx);
	}
	catch(e) {
		alert('Cannot store tab preference, session timeout? Please reload the page.\n[' + e + ']');
	}
}

function picviewCheck(id, obj) {
	try {
		get_json().PictureEditServer.selectPicture(id, obj.checked);
	}
	catch(e) {
		alert(e);
	}
}

function picviewCheck2(id, obj, meta) {
	try {
		get_json().PictureEditServer.selectPicture(id, obj.checked, meta);
	}
	catch(e) {
		alert(e);
	}
}

function picviewDelete(id, obj) {
	try {
		get_json().PictureEditServer.deletePicture(id);
		var o = ge(id + '_cell');
		o.parentNode.removeChild(o);
	}
	catch(e) {
		alert(e);
	}
}

function pageWidth() {
	return window.innerWidth != null ? 
		window.innerWidth : 
		document.documentElement && document.documentElement.clientWidth ?  
			document.documentElement.clientWidth : 
			document.body != null ? 
				document.body.clientWidth : 
				null;
}

function pageHeight() {
	return  window.innerHeight != null ? 
		window.innerHeight : 
		document.documentElement && document.documentElement.clientHeight ? 
			document.documentElement.clientHeight : 
			document.body != null ? 
				document.body.clientHeight : 
				null;
}

function posLeft() {
	return typeof window.pageXOffset != 'undefined' ? 
		window.pageXOffset :
		document.documentElement && document.documentElement.scrollLeft ? 
			document.documentElement.scrollLeft : 
			document.body.scrollLeft ? 
				document.body.scrollLeft : 
				0;
}

function posTop() {
	return typeof window.pageYOffset != 'undefined' ? 
		window.pageYOffset : 
		document.documentElement && document.documentElement.scrollTop ? 
			document.documentElement.scrollTop : 
			document.body.scrollTop ? 
				document.body.scrollTop : 
				0;
}

function posRight() {
	return posLeft() + pageWidth();
}

function posBottom() {
	return posTop() + pageHeight();
}

function di3_checkall(from, to) {
	var all_checked = true;
	from = parseInt(from);
	to = parseInt(to);
	for(var i = from; i <= to; i++) {
		var chk = ge('di3_' + i);
		if(!chk)
			continue;
		if(!chk.checked) {
			all_checked = false;
			break;
		}
	}
	for(var i = from; i <= to; i++) {
		var chk = ge('di3_' + i);
		if(!chk)
			continue;
		chk.checked = !all_checked;
	}
}

function di3_delete(from, to) {
	from = parseInt(from);
	to = parseInt(to);
	for(var i = from; i <= to; i++) {
		var chk = ge('di3_' + i);
		if(!chk)
			continue;
		if(chk.checked) {
			try {
				get_json().DataImport3Server.deleteItem(chk.getAttribute('dtype'), i);
			}
			catch(e) {
				alert('Could not delete, reason: ' + e + '\nPlease refresh the page.');
				break;
			}
			chk.nextSibling.parentNode.removeChild(chk.nextSibling);
			chk.parentNode.removeChild(chk);
		}
	}
}

function toggle_table(id) {
	var t = ge(id);
	if(!t)
		return;
	var bb = /Gecko/.test(navigator.userAgent) ? 'table' : 'block';
	if(t.style.display == bb)
		t.style.display = 'none';
	else
		t.style.display = bb;
}

function select_url2(url) {
	window.location.href = url;
}

var elm = ['select','object','embed'];
var closePopupIcon;

function setClosePopupIcon( icon )
{
	closePopupIcon = icon;
}

function getAbsolutePosition( element ) 
{
	var SL = 0, ST = 0;
	var is_div = /^div$/i.test(element.tagName);
	if (is_div && element.scrollLeft)
		SL = element.scrollLeft;
	if (is_div && element.scrollTop)
		ST = element.scrollTop;
	var r = { x: element.offsetLeft - SL, y: element.offsetTop - ST };
	if (element.offsetParent) {
		var tmp = getAbsolutePosition(element.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
};

function fixPosition(box) {
		if (box.x < 0)
			box.x = 0;
		if (box.y < 0)
			box.y = 0;
		var cp = document.createElement("div");
		var s = cp.style;
		s.position = "absolute";
		s.right = s.bottom = s.width = s.height = "0px";
		document.body.appendChild(cp);
		var br = getAbsolutePosition(cp);
		document.body.removeChild(cp);
		if ( /msie/i.test(navigator.userAgent) &&
		   !/opera/i.test(navigator.userAgent) ) { //if ie
			br.y += document.body.scrollTop;
			br.x += document.body.scrollLeft;
		} else {
			br.y += window.scrollY;
			br.x += window.scrollX;
		}
		var tmp = box.x + box.width - br.x;
		if (tmp > 0) box.x -= tmp;
		tmp = box.y + box.height - br.y;
		if (tmp > 0) box.y -= tmp;
};

function showGoogleMapBig( latitude, longitude, zoomLevel, width, height )
{	 
	/* hide everything what can cause a trouble. */
	for(a=0;a<elm.length;a++) 
	{
		var sel = document.getElementsByTagName(elm[a]);
		for(b=0;b<sel.length;b++) 
		{
			sel[b].style.visibility = 'hidden';
		}
	}

	/* show popup div */
	obj = document.getElementById('bigmap');
	obj.innerHTML = "<p id='close'><a href='#' onclick='return closeGoogleMapBig();'><img src='" + closePopupIcon + "' alt='' width='17' height='17' class='big-google-map-close'/></a></p><div id='bigGoogleMapDiv' class='big-google-map-div' style='width: "+width+"; height: "+height+";'>"

	obj.style.display = 'block';
	/*
	position = getAbsolutePosition( obj.parentNode );
	position.x  += (obj.parentNode.offsetWidth / 2 ) - ( obj.offsetWidth / 2 );
	position.y += (obj.parentNode.offsetHeight / 2 ) - ( obj.offsetHeight / 2 );
	position.width = obj.offsetWidth;
	position.height = obj.offsetHeight + 40;
	fixPosition( position );
	obj.style.left = position.x;
	obj.style.top = position.y;
	*/
	
	/* show google map */
	var map = new google.maps.Map2(document.getElementById("bigGoogleMapDiv"));
	map.setCenter(new GLatLng( latitude , longitude ), zoomLevel );
	
	if (google.maps.BrowserIsCompatible()) 
	{
		var arrowIcon = new google.maps.Icon();
		arrowIcon.shadow = "http://www.google.com/mapfiles/arrowshadow.png";
		arrowIcon.iconSize = new GSize(39, 34);
		arrowIcon.shadowSize = new GSize(39, 34);
		arrowIcon.iconAnchor = new GPoint(11, 34);
		arrowIcon.infoWindowAnchor = new GPoint(11, 2);
		arrowIcon.infoShadowAnchor = new GPoint(19, 25);
		arrowIcon.image = "http://www.google.com/mapfiles/arrow.png";
	
		var point = new google.maps.LatLng(	latitude , longitude );
		markerOptions = { icon:arrowIcon, clickable:false };
		marker = new google.maps.Marker(point, markerOptions );
		var map = new google.maps.Map2(document.getElementById( "bigGoogleMapDiv" )); 
		map.setCenter( point, zoomLevel );
		map.addOverlay( marker );
		map.addControl(new GLargeMapControl());
	}			
}

function closeGoogleMapBig()
{
	/* show everything what was hidden */
 	for(a=0;a<elm.length;a++) 
 	{
 		var sel = document.getElementsByTagName(elm[a]);
 		for(b=0;b<sel.length;b++) 
 		{
 			sel[b].style.visibility = 'visible';
 		}
 	}

	/* hide popup div */
 	obj = document.getElementById('bigmap');
 	obj.style.display = 'none';
 	
 	google.maps.Unload();
 	return false;
}

function showPopup( parentId , popupDivClass, closePopupIcon, popupContent )
{	 
	/* hide everything what can cause a trouble. */
	for(a=0;a<elm.length;a++) 
	{
		var sel = document.getElementsByTagName(elm[a]);
		for(b=0;b<sel.length;b++) 
		{
			sel[b].style.visibility = 'hidden';
		}
	}

	/* show popup div */
	obj = document.getElementById( 'popup-div' );
	obj.className = popupDivClass;
	obj.innerHTML = "<p class='popup-header' id='close'><a href='#' onclick='return closePopup();'><img class='popup-close' src='" + closePopupIcon + "' alt='' width='17' height='17'/></a></p><div class='popup-content-div'>" + popupContent + "</div>";
	obj.style.visibility = 'hidden';
	obj.style.display = 'block';
	
	var parentNode = document.getElementById( parentId );
	position = getAbsolutePosition( parentNode );
	//position.x  += ( parentNode.offsetWidth / 2 ) - ( obj.offsetWidth / 2 );
	
	var screen_left = (position.x + parentNode.offsetWidth);
	position.x =  screen_left - obj.offsetWidth;
	
	position.y += ( parentNode.offsetHeight / 2 ) - ( obj.offsetHeight / 2 );
	position.width = obj.offsetWidth;
	position.height = obj.offsetHeight + 40;	
	//fixPosition( position );
	
	obj.style.left = position.x;
	obj.style.top = position.y;		
	obj.style.visibility = 'visible';	
	
	return false;
}

function closePopup()
{
	/* show everything what was hidden */
 	for(a=0;a<elm.length;a++) 
 	{
 		var sel = document.getElementsByTagName(elm[a]);
 		for(b=0;b<sel.length;b++) 
 		{
 			sel[b].style.visibility = 'visible';
 		}
 	}

	/* hide popup div */
 	obj = document.getElementById('popup-div');
 	obj.style.display = 'none';
 	 	
 	return false;
}

function show_plugin(xxid) {
   	var xxtype = navigator && navigator.appName ? navigator.appName : null;
   	var obj;
   	if(xxtype == 'Netscape') {
   		obj = ge(xxid + '_embed');
   	}
   	else if(xxtype == 'Microsoft Internet Explorer') {
   		obj = ge(xxid + '_object');
   	}
   	else {
   		obj = ge(xxid + '_none');
   	}
   	if(obj)
   		obj.style.display = "block";
}

function IterableElements(e) {
	this.elements = [];
	var cn = e.childNodes;
	for(var i = 0; i < cn.length; i++) {
		var n = cn.item(i);
		if(n.nodeType == 1)
			this.elements.push(n);
	}
	this.ptr = 0;
	this.hasNext = function() {
		return this.ptr < this.elements.length;
	};
	this.next = function() {
		return this.elements[this.ptr++];
	};
}

function evx(e) {	
	if(!e) var e = window.event;
	return { target: e.target ? e.target : e.srcElement, event: e, key: e.keyCode ? e.keyCode : e.which };
}

function get_url_param(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if(results == null)
    return "";
  else
    return results[1];
}

/*
parseUri 1.2.1
(c) 2007 Steven Levithan <stevenlevithan.com>
MIT License
*/

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;
	
	while (i--) uri[o.key[i]] = m[i] || "";
	
	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});
	
	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

//endof parseuri


function ac(p, c) {
	if(c)
		p.appendChild(c);
	return p;
}

function tab(args, rows) {
	var tb = t('table', args);
	for(var i = 0; i < rows.length; i++) {
		var tr = tb.insertRow(tb.rows.length);
		for(var j = 0; j < rows[i].length; j++) {
			var td = tr.insertCell(tr.cells.length);
			var d = rows[i][j];
			if(d instanceof Array) {
				if(d.length > 0) {
					var z = 0;
					if(typeof(d[0]) == 'string') {
						td.className = d[0];
						z = 1;
					}
					else if(typeof(d[0]) == 'object' && !d[0].tagName) {
						t_args(td, d[0]);
						z = 1;
					}
					for(; z < d.length; z++) {
						var o = d[z];
						if(o != null) {
							if(typeof(o) == 'string') {
								o = document.createTextNode(o);
							}
							td.appendChild(o);
						}
					}
				}
			}
			else {
				if(d != null) {
					if(typeof(d) == 'string') {
						d = document.createTextNode(d);
					}
					td.appendChild(d);
				}
			}
		}
	}
	return tb;
}

function gt(e) {
	if(!e) var e = window.event;
	var t = e.target ? e.target : e.srcElement;
	cancel_event(e);
	return t;
}

function ga(e, a) {
	return e.getAttribute(a);
}

function sa(e, a, v) {
	e.setAttribute(a, v);
}

function t_args(e, args) {
	for(var k in args) {
		var v = args[k];
		if(k == '$text') {
			e.appendChild(document.createTextNode(v));
			continue;
		}
		else if(k.charAt(0) == '$') {
			k = k.substring(1);
		}
		if(k == 'class')
			e.className = v;
		else if(k == 'style') {
			for(var j in v) {
				e.style[j] = v[j];
			}
		}
		else if(k == 'href' || typeof v == 'function' || k == 'checked')
			e[k] = v;
		else {
			try {
				e.setAttribute(k, v);
			}
			catch(e) {
				console.dir(e);
				throw e;
			}
		}
	}
}

function t() {
	var tag = arguments[0];
	var args = arguments[1];
	var e = document.createElement(tag);
	if(args)
		t_args(e, args);
	if(arguments.length > 2) {
		for(var i = 2; i < arguments.length; i++)
			if(arguments[i])
				e.appendChild(arguments[i]);
	}
	return e;
}

function a(name, link, className) {
	return !name || !link ? null : t('a', { $class: className, $text: name, href: link });
}

function txt(t) {
	return document.createTextNode(t);
}

function className(c, n) {
	c.className = n;
	return c;
}

function purgeChildren(t) {
	while(t.childNodes.length > 0)
		t.removeChild(t.childNodes.item(0));
}

function purgeChildrenExceptFirst(t, n) {
	while(t.childNodes.length > n)
		t.removeChild(t.childNodes.item(n));
}

function toSet(o) {
	var oo = {};
	for(var i = 0; i < o.length; i++)
		oo[o[i]] = o[i];
	return oo;
}

function toHash(o, name) {
	var oo = {};
	for(var i = 0; i < o.length; i++)
		oo[o[i][name]] = o[i];
	return oo;
}

function gehtc(id) {
	var ctl = ge(id);
	var val = ctl.value;
	var ht = ga(ctl, 'help-text');
	return val == ht ? '' : val;
}

function serialize_url_params() {
	var a = [];
	for(var i = 0; i < arguments.length; i+=2) {
		var n = arguments[i], v = arguments[i + 1];
		a.push(n + '=' + encodeURIComponent(v));
	}
	return a.join('&');
}

function plural(word) {
	//monkey -> monkeys [+s]
	//country -> counties [-y +ies]
	//dress -> dresses [+es]
	//district -> districts [+s]
	if(/.*ey$/.test(word))
		word += 's'; 
	else if(/.*y$/.test(word))
		word = word.replace(/(.*)y$/, '$1ies'); 
	else if(/.*s$/.test(word))
		word += 'es'; 
	else
		word += 's'; 
	return word;
}

function subcol(master, subordinate, no_onchange, pcn) {
	var sel = geregx(master, pcn);
	var sel2 = geregx(subordinate, pcn);
	if(!sel || !sel2)
		return;
	var id = get_selecto(sel);
	var ret = [];
	if(id != 0 && id != '' && id != null) {
		if(pcn != null)
			ret = get_json().ProjectServer.get_subcols_cn(processName, pcn, master, subordinate, [ Number(id) ], null);
		else
			ret = get_json().ProjectServer.get_subcols(processName, master, subordinate, [ Number(id) ], null);
	}
	
	set_selecto(sel2, ret, 0, 1, null, true);
	if(!no_onchange)
		on_changeo(sel2);
}

function pubcol(master, subordinate, no_onchange) {
	var sel = geregx(master);
	var sel2 = geregx(subordinate);
	if(!sel || !sel2)
		return;
	var id = get_selecto(sel);
	var ret = [];

	if(id != 0 && id != '' && id != null)
		ret = get_json().ProjectServer.get_subcols(processName, master, subordinate, [ Number(id) ], get_url_param('id'));
	
	set_selecto(sel2, ret, 0, 1, null, true);
	
	for(var d in ret) {
		if(ret[d][2] == true) {
			select_selecto(sel2, ret[d][0], true);
			break;
		}
	}
}


function subcols(master, subordinate) {
	var sel = geregx(master);
	var sel2 = geregx(subordinate);
	if(!sel || !sel2)
		return;
	//var method = 'get_' + plural(subordinate) + '_for_' + plural(master);
	get_values_for_values(master, subordinate, sel, sel2);
	if(check_multi_dyna)
		check_multi_dyna(sel2);
}

function get_values_for_values(master, subordinate, sel, sel2) {
	if(sel2.getAttribute('select-type') == 'multicheck-dyna-cola') {
		var ret = get_json().ProjectServer.get_subcols(processName, master, subordinate, get_multiselecto_colacheck(sel), get_url_param('id'));
		var msel = get_multiselecto_colacheck(sel2);
		set_selecto_colacheck(sel2, ret, 0, 1, null, false, function(o, en, arg) {
			if(arg.length == 0 && en[2]) {
				o.checked = true;
			}
			else {
				for(x = 0; x < arg.length; x++) {
					if(arg[x] == en[0]) {
						o.checked = true;
						break;
					}
				}
			}
		}, msel);
		on_changeo(sel2);
	}
	else if(sel2.getAttribute('select-type') == 'checkboxes') {
		var ret = get_json().ProjectServer.get_subcols(processName, master, subordinate, get_multiselecto_dynacheck(sel), get_url_param('id'));
		var msel = get_multiselecto_dynacheck(sel2);
		set_selecto_dynacheck(sel2, ret, 0, 1, null, false, function(o, en, arg) {
			if(arg.length == 0 && en[2]) {
				check_dynacheck_option(sel2, o, true);
			}
			else {
				for(x = 0; x < arg.length; x++) {
					if(arg[x] == en[0]) {
						check_dynacheck_option(sel2, o, true);
						break;
					}
				}
			}
		}, msel);
		on_changeo(sel2);
	}
	else {
		var ret = get_json().ProjectServer.get_subcols(processName, master, subordinate, get_multiselecto(sel), null);
		var msel = get_multiselecto(sel2);
		set_selecto(sel2, ret, 0, 1, null, false, function(o, key, val, arg) {
			for(x = 0; x < arg.length; x++) {
				if(arg[x] == key) {
					o.selected = true;
					break;
				}
			}
		}, msel);
		on_changeo(sel2);
	}
}

function dynamix() {
	var ctl = arguments[0];
	var vids;
	
	if(ga(ctl, 'select-type') == 'checkboxes') {
		vids = get_multiselecto_dynacheck(ctl); //dynamic multi checkbox, multicheckbox?
	}
	else if(ctl.tagName == 'SELECT') {
		vids = get_multiselecto(ctl); //multiselect, select
	}
	else if(ctl.tagName == 'INPUT' && (ga(ctl, 'type') == 'checkbox' || ga(ctl, 'type') == 'radio')) { //checkbox, radio
		if(ctl.checked == true)
			vids = [ ctl.value ];
	}
	else {
		return;
	}
	
	if(!vids || vids.length == 0)
		vids = [ '~' ]; //hide everything
	
	for(var i = 1; i < arguments.length; i++) {
		var arr = arguments[i];
		var key = String(arr[0]);
		for(var k = 0; k < vids.length; k++) {
			var vid = vids[k];
			if(vid == key || (key == '*' && vid != '')) { //show this one
				for(var j = 1; j < arr.length; j++) {
					dynamix_show(arr[j], true);
				}
			}
			else { //hide all others
				for(var j = 1; j < arr.length; j++) {
					dynamix_show(arr[j], false);
				}
			}
		}
	}
}

function dynamix_show(id, show) {
	var c = ge(id);
	if(c && c.tagName == 'TABLE') { //it's a section
		if(show) {
			x_unhide(c, id);
		}
		else {
			x_hide(c, id);
		}
	}
	else { //it's a form entry
		var ix = geregx_id(id);
		if(!ix)
			return;
		var ctl = ge('control-' + ix);
		var lab = ge('label-' + ix);
		if(show) {
			x_unhide(ctl, ix);
			x_unhide(lab);
		}
		else {
			x_hide(ctl, ix);
			x_hide(lab);
		}
	}
}

var anim_ctl = [];
var anim_timer = 5; //5
var anim_step = 500; //250

function anim_tick(id) {
	var ctl = anim_ctl[id];
	var elapsed = new Date().getTime() - ctl.start_time;
	if(elapsed <= anim_step) {
		var d = Math.round(elapsed / anim_step * ctl.target_height);
		if(!ctl.direction_unhide)
			d = ctl.target_height - d;
		ctl.ad.style.height = d + 'px';
	}
	else {
		clearInterval(ctl.timer);
		ctl.ad.style.height = '';
		ctl.ad.style.overflow = '';
		if(!ctl.direction_unhide)
			ctl.t.className += ' x-hidden';
		delete anim_ctl[id];
	}
}

function x_unhide(c, id) {
	if(c != null && c.className != null) {
		var ad;
		var anim = c.tagName == 'TABLE' && (ad = ge(id + '_animated')) != null;
		if(anim) {
			ad.style.height = '1px';
			ad.style.overflow = 'hidden';
		}
		
		c.className = c.className.replace(/x-hidden/g,'').replace(/\s{2,}/g,' ');
		if(id)
			x_hidden_off(id);

		if(anim) {
			if(anim_ctl[id])
				clearInterval(anim_ctl[id].timer);
			anim_ctl[id] = {
				ad: ad, 
				t: c,
				target_height: c.offsetHeight, 
				start_time: new Date().getTime(), 
				direction_unhide: true,
				timer: setInterval('anim_tick(\'' + id + '\');', anim_timer)
			};
		}
	}
}

function x_hide(c, id) {
	if(c != null && c.className != null && c.className.indexOf('x-hidden') == -1) {
		var ad;
		if(c.tagName == 'TABLE' && (ad = ge(id + '_animated')) != null) {

			if(anim_ctl[id])
				clearInterval(anim_ctl[id].timer);

			ad.style.overflow = 'hidden';
			ad.style.height = c.offsetHeight + 'px';

			anim_ctl[id] = {
				ad: ad, 
				t: c,
				target_height: c.offsetHeight,
				//target_height: 1, 
				start_time: new Date().getTime(), 
				direction_unhide: false,
				timer: setInterval('anim_tick(\'' + id + '\');', anim_timer)
			};
		}
		else {
			c.className += ' x-hidden';
		}
		
		if(id)
			x_hidden_on(id);
	}
}

var x_hiddens = {};

function x_hidden_on(id) {
	var c = ge(id);
	if(c && c.tagName == 'TABLE')
		hide_table(c, true);
	else
		x_hiddens[id] = true;
}
function x_hidden_off(id) {
	var c = ge(id);
	if(c && c.tagName == 'TABLE')
		hide_table(c, false);
	else
		delete x_hiddens[id];
}
function x_hiddens_onsubmit() {
	var xr = '';
	for(var xh in x_hiddens) {
		xr += xh + ',';
	}
	ge('x_hiddens').value = xr;
}

function hide_table(t, hide) {
	/*if(hide)
		console.log('hiding table ' + t.id);
	else
		console.log('unhiding table ' + t.id);*/
	hide_table2(t, hide);
}

function hide_table2(t, hide) {
	var cn = t.childNodes;
	for(var i = 0; i < cn.length; i++) {
		var n = cn.item(i);
		if(n.nodeType == 1) {
			if(n.tagName == 'INPUT' || n.tagName == 'SELECT') {
				//ignore elements disabled from the getgo
				//try display:none if disabled=true fails
				if(hide) {
					if(n.disabled == true)
						continue;
					n.disabled = true;
					n.hide_table_managed = true;
				}
				else {
					if(n.hide_table_managed == true)
						n.disabled = false;
				}
			}
			else {
				hide_table2(n, hide);
			}
		}
	}
}

function exec_all() {
	//cheap tricks inc.
}

