
function get_templates_for_category() {
	var category_select = gereg('iflowcrm.job-role_cz.c2d.asprecruiter.data.OpenPosition.category');
	var postype_select = gereg('iflowcrm.job-role_cz.c2d.asprecruiter.data.OpenPosition.positionType');
	if(category_select == null && postype_select == null)
		return;
	
	var cat_id = get_selecto(category_select);
		
	get_json();
	var templates = json.OpenPositionCategoryServer.get_templates_for_category(cat_id);
	
	set_selecto(postype_select, templates, 0, 1, null, true);
	on_changeo(postype_select);
}

var template_bubbles;

function show_template_texts() {
	var postype_select = gereg('iflowcrm.job-role_cz.c2d.asprecruiter.data.OpenPosition.positionType');
	if(postype_select == null)
		return;
	
	var temp_id = get_selecto(postype_select);
	if(temp_id == null || temp_id == '') {
		cancel_template_texts();
		return;
	}

	get_json();
	var tx = json.OpenPositionCategoryServer.get_template_texts(temp_id);
	if(tx == null)
		return;
		
	template_bubbles = new Array();
	var any_shown = false;
	
	for(var prop in tx) {
		if(prop == 'javaClass')
			continue;
			
		var val = tx[prop];
		var div_id = 'div_' + prop;
		if(val == null || val == '') {
			hide(div_id);
			continue;
		}
		
		//check if there's such a form control
		var ctrl = gereg('iflowcrm.job-role_cz.c2d.asprecruiter.data.OpenPosition.' + prop);
		if(ctrl == null)
			continue;
		
		//create new div if we don't have one yet
		var div = ge(div_id);
		if(div == null) {
			div = document.createElement('div');
			div.id = div_id;
			div.className = 'area-bubble';
			div.style.width = ctrl.clientWidth + 'px';
			ctrl.parentNode.appendChild(div);
			
			var a = document.createElement('a');
			a.className = 'copy-text-arrow';
			a.title = 'Copy text';
			a.href = 'javascript:copy_template_text("' + div_id + '", "' + ctrl.id + '")';
			div.appendChild(a);
		}
	
		set_valueo(div, val, null);
		template_bubbles[template_bubbles.length] = div;
		showo(div);
		any_shown = true;
	}
	
	var canc_id = postype_select.id + "_cancel";
	if(any_shown) {
		var div = ge(canc_id);
		if(div == null) {
			var div = document.createElement('div');
			div.style.position = 'relative';
			div.id = canc_id;
			postype_select.parentNode.appendChild(div);
			
			var a = document.createElement('a');
			a.className = 'cancel-bubbles';
			a.href = 'javascript:cancel_template_texts()';
			a.title = 'Hide template texts';
			div.appendChild(a);
		}
		showo(div);
	}
	else {
		var cdiv = ge(canc_id);
		if(cdiv != null)
			hideo(cdiv);
	}
}

function copy_template_text(src_id, dest_id) {
	var src = ge(src_id);
	if(!src)
		return;
	var val = src.firstChild.nodeValue;
	
	var tinyControl = tinyMCE.getInstanceById(dest_id);
	if(tinyControl != null) {
		//TODO: replace \n for <br> if the source isn't tinyMCE?
		//tinyControl.setHTML(val);
		tinyMCE._setHTML(tinyControl.getDoc(), val);
	}
	else {
		set_value(dest_id, val, null);
	}
}

function cancel_template_texts() {
	if(template_bubbles == null)
		return;
	for(var div in template_bubbles)
		hideo(template_bubbles[div]);
	var postype_select = gereg('iflowcrm.job-role_cz.c2d.asprecruiter.data.OpenPosition.positionType');
	var cdiv = ge(postype_select.id + "_cancel");
	hideo(cdiv);
}

var g_thumbs;

function animate_thumbnails(thumbs) {
	var ms = 1000;
	g_thumbs = thumbs;
	for(i = 0; i < thumbs.length; i++) {
		var o = thumbs[i];
		
		if(o.arr.length < 2)
			continue;

		setTimeout('animate_thumbnails_sub(' + i + ')', ms);
		ms += 600;
	}
}

function animate_thumbnails_sub(ix) {
	var o = g_thumbs[ix], to, from;
	var from = o.arr[o.ptr];
	o.ptr++;
	if(o.ptr >= o.arr.length)
		o.ptr = 0;
	var to = o.arr[o.ptr];
	new Effect.Fade(from);
	setTimeout('animate_thumbnails_sub2(' + ix + ')', 1000);
}

function animate_thumbnails_sub2(ix) {
	var o = g_thumbs[ix], to, from;
	var to = o.arr[o.ptr];
	new Effect.Appear(to);
	setTimeout('animate_thumbnails_sub(' + ix + ')', 4000);
}

function show_popupks(e) {
	if(!e) var e = window.event;
	var targ = e.target ? e.target : e.srcElement;
	var text = targ ? targ.getAttribute("popup-text") : null;
	if(!text)
		return;
	var pop;
	pop = ge('popupks');
	if(!pop)
		return;
	if(pop.style.visibility != 'visible')
		pop.innerHTML = text;

	var posx = 0, posy = 0, poosx = 0, poosy = 0;
	if (e.pageX || e.pageY) {
		posx = e.pageX;
		posy = e.pageY;
		poosx = posx - document.body.scrollLeft;
		poosy = posy - document.body.scrollTop;
	}
	else if (e.clientX || e.clientY) {
		posx = e.clientX + document.body.scrollLeft;
		posy = e.clientY + document.body.scrollTop;
		poosx = e.clientX;
		poosy = e.clientY;
	}
	
	poosx += 10;
	poosy += 10;
	posx += 10;
	posy += 10;
	
	var ph = pageHeight();
	var ch = pop.clientHeight;
	if(poosy + ch > ph)
		posy = (ph - pop.clientHeight) + (e.clientY ? document.body.scrollTop : 0);
	
	pop.style.left = posx;
	pop.style.top = posy;
	pop.style.visibility = "visible";
}

function hide_popupks() {
	ge('popupks').style.visibility = "hidden";
}

var thumbs;
var margin = 6, halfmargin = margin / 2 - 1;

function slide_left(ksflag) {
	ksshow = ksflag;
	var s = ge('slider');
	var o = 0;
	var mark = s.scrollLeft;
	for(var i = 0; i < thumbs.length; i++) {
		var ti = thumbs[i];
		o += ti.width + margin;
		if(o > mark) {
			o -= ti.width + margin;
			break;
		}
	}
	var diff = mark - o + halfmargin;
	var ns = s.scrollLeft - diff;
	if(ns < 0)
		ns = 0;
	//s.scrollLeft = ns;
	start_animate('th_slide', s, 'scrollLeft', ns, slide_step, slide_ms, 'update_arrows()');
}

var slide_step = 3;
var slide_ms = 10;

function slide_right(ksflag) {
	ksshow = ksflag;
	var s = ge('slider');
	var o = 0;
	var mark = s.scrollLeft + s.clientWidth;
	for(var i = 0; i < thumbs.length; i++) {
		var ti = thumbs[i];
		o += ti.width + margin;
		if(o > mark)
			break;
	}
	var diff = o - mark + halfmargin;
	var ns = s.scrollLeft + diff;
	if(ns > s.scrollWidth)
		ns = s.scrollWidth;
	//s.scrollLeft = ns;
	start_animate('th_slide', s, 'scrollLeft', ns, slide_step, slide_ms, 'update_arrows()');
}

var anims = {};
var anims_id = {};
var anims_id_cnt = 0;

function start_animate(id, obj, prop, targ, step, ms, fnc) {
	if(anims[id])
		anims_id[id] = null;
	if(obj[prop] > targ)
		step *= -1;
	var id2 = anims_id_cnt++;
	anims[id] = { id2: id2, obj: obj, prop: prop, targ: targ, step: step, ms: ms, fnc: fnc };
	anims_id[id] = id2;
	animate(id);
}

function start_animate2(id, obj, prop_arr, targ, curr, pfix, step, ms, wait, fnc) {
	if(anims[id])
		anims_id[id] = null;
	if(curr > targ)
		step *= -1;
	var id2 = anims_id_cnt++;
	anims[id] = { id2: id2, obj: obj, prop: prop_arr, targ: targ, curr: curr, pfix: pfix, step: step, ms: ms, wait: wait, fnc: fnc };
	anims_id[id] = id2;
	animate2(id);
}

function animate(id) {
	var a = anims[id];
	if(!a)
		return;
	if(a.id2 != anims_id[id])
		return;

	var p = a.obj[a.prop];
	p += a.step;
	
	var done = a.step > 0 ? p >= a.targ : p <= a.targ;
	if(done) {
		a.obj[a.prop] = a.targ;
		anims[id] = null;
		if(a.fnc)
			eval(a.fnc);
	}
	else {
		a.obj[a.prop] = p;
		setTimeout('animate("' + id + '")', a.ms);
	}
}

function animate2(id) {
	var a = anims[id];
	if(!a)
		return;
	if(a.id2 != anims_id[id])
		return;

	var last = a.prop.length - 1;
	var o = a.obj;
	for(var i = 0; i < last; i++) {
		o = o[a.prop[i]];
	}
	
	a.curr += a.step;
	
	var done = a.step > 0 ? a.curr >= a.targ : a.curr <= a.targ;
	if(done) {
		o[a.prop[last]] = a.targ + a.pfix;
		anims[id] = null;
		if(a.fnc)
			setTimeout(a.fnc, a.wait);
	}
	else {
		o[a.prop[last]] = a.curr + a.pfix
		setTimeout('animate2("' + id + '")', a.ms);
	}
}

var ksshow_delay = 4000;
var ksshow = true;
var ksshow_prevthumb;

function prepare_detail(a) {
	thumbs = new Array();
	for(var i = 0; i < a.length; i++) {
		var id = a[i];
		var th = ge('thu_' + id);
		var cw = th.clientWidth;
		if(cw == 0)
			cw = th.firstChild.clientWidth;
		thumbs.push({ id: id, width: cw });
	}
	update_arrows();
	setTimeout('ks_slideshow(' + 0 + ')', 1000);
}

function ks_slideshow(i) {
	if(!ksshow)
		return;
		
	var s = ge('slider');
	if(i == 0) {
		s.scrollLeft = 0;
		update_arrows();
	}
		
	var prev = ksshow_prevthumb;
	var next = thumbs[i];
	
	if(prev) {
		//delsect previous thumb
		ge('thu_' + prev.id).className = 'thlnk';
		ge('pic_' + prev.id).style.visibility = 'hidden';
	}
	
	//select new thumb
	ge('thu_' + next.id).className = 'thlnk-sel';
	ge('pic_' + next.id).style.visibility = 'visible';

	//move the thumb into view if necessary
	var o2 = 0;
	for(var j = i; j >= 0; j--) {
		o2 += thumbs[j].width + margin;
	}
	var o1 = o2 - thumbs[i].width;
	var left = s.scrollLeft;
	var right = s.scrollLeft + s.clientWidth;
	
	//if(o1 < left)
	if(o2 > right)
		slide_right(true);
	
	i++;
	if(i >= thumbs.length)
		i = 0;
		
	ksshow_prevthumb = next;
	
	setTimeout('ks_slideshow(' + i + ')', ksshow_delay);
}

function ksshowpic(id) {
	ksshow = false;
	var prev = ksshow_prevthumb ? ksshow_prevthumb : thumbs[0];
	if(prev.id == id)
		return;
	ge('pic_' + prev.id).style.visibility = 'hidden';
	ge('thu_' + prev.id).className = 'thlnk';
	ge('pic_' + id).style.visibility = 'visible';
	ge('thu_' + id).className = 'thlnk-sel';
	ge('thu_' + id).blur();
	for(var i = 0; i < thumbs.length; i++) {
		if(thumbs[i].id == id) {
			ksshow_prevthumb = thumbs[i];
		}
	}
}

function update_arrows() {
	var s = ge('slider');
	if(s.scrollLeft < s.scrollWidth - s.clientWidth)
		ge('slide_right').className = 'slide-right';
	else
		ge('slide_right').className = 'slide-right-off';
	if(s.scrollLeft > 0)
		ge('slide_left').className = 'slide-left';
	else
		ge('slide_left').className = 'slide-left-off';
	ge('slide_right').blur();
	ge('slide_left').blur();
}



var newsShown = -1;
var news;

function show_news1() {
	if(!ge('newsdiv'))
		return;

	if(!news) {
		news = get_json().NewsServer.getNews();
	}

	//slide out current
	if(newsShown > -1) {
		start_animate2('newsdiv', ge('newsdiv'), [ 'style', 'top' ], 30, 6, 'px', 1, 20, 1000, 'show_news2()');
	}
	else {
		show_news2();
	}
}

function show_news2() {
	if(ge('news-time') == null)
		return;
	//slide in new
	newsShown++;
	if(newsShown >= news.length)
		newsShown = 0;
	var n = news[newsShown];
	//ge('news-type').firstChild.nodeValue = n.type;
	ge('news-time').href = n.url;
	ge('news-time').firstChild.nodeValue = n.date;
	ge('new-slink').href = n.url;
	ge('new-slink').firstChild.nodeValue = n.text;
	
	start_animate2('newsdiv', ge('newsdiv'), [ 'style', 'top' ], 6, 30, 'px', 1, 20, 5000, 'show_news1()');
}

function select_url(sel) {
	var url = get_selecto(sel);
	if(!url)
		return;
	window.location.href = url;
}

function campaignUseAsTemplate() {
	alert('hi');
}

function campaignModify() {
	alert('hi2');
}

function get_values_picklist(id) {
	var data = ge('table_' + id).dx;
	var to = ge(id);
	var arr = [];
	for(var i = 0; i < data.length; i++) {
		var d = data[i];
		if(!d || !d.text)
			continue;
		if(d.se == 'true')
			arr.push(d.val);
	}
	to.value = arr.join(',');
}

function add_picklist(id) {
	var to = ge('ava_' + id);
	var data = ge('table_' + id).dx;
	for(var i = 0; i < to.options.length; i++) {
		if(to.options[i].selected) {
			for(var j = 0; j < data.length; j++) {
				var d = data[j];
				if(!d || !d.text)
					continue;
				if(d.val == to.options[i].value) {
					d.se = 'true';
					break;
				}
			}
		}
	}
	filter_picklist(id);
}

function remove_picklist(id) {
	var to = ge('cur_' + id);
	var data = ge('table_' + id).dx;
	for(var i = 0; i < to.options.length; i++) {
		if(to.options[i].selected) {
			for(var j = 0; j < data.length; j++) {
				var d = data[j];
				if(!d || !d.text)
					continue;
				if(d.val == to.options[i].value) {
					d.se = '';
					break;
				}
			}
		}
	}
	filter_picklist(id);
}

function filter_picklist(id) {
	var filter = ge('filter_' + id);
	var fval = filter.value;
	if(fval == '')
		fval = null;
	else
		fval = ('' + fval).toLowerCase();
	var data = ge('table_' + id).dx;
	var cur = ge('cur_' + id);
	var ava = ge('ava_' + id);
	var acur = [], aava = [];
	for(var i = 0; i < data.length; i++) {
		var d = data[i];
		if(!d || !d.text)
			continue;
		if(d.se == 'true') {
			acur.push(d);
		}
		else if(!fval || d.xtext.indexOf(fval) != -1) {
			aava.push(d);
		}
	}
	set_selecto(cur, acur, 'val', 'text', null, false, null);
	set_selecto(ava, aava, 'val', 'text', null, false, null);
}

function get_values_picklist2(id) {
	var data = ge('table_' + id).dx;
	var to = ge(id);
	var arr = [];
	for(var i = 0; i < data.length; i++) {
		var d = data[i];
		if(!d || !d.text)
			continue;
		if(d.se == 'true') {
			to.value = d.val;
			break;
		}
	}
}

function add_picklist2(id) {
	var to = ge('ava_' + id);
	var data = ge('table_' + id).dx;
	var val = get_selecto(to);
	for(var j = 0; j < data.length; j++) {
		var d = data[j];
		if(!d || !d.text)
			continue;
		if(d.val == val) {
			d.se = 'true';
			continue;
		}
		if(d.se == 'true')
			d.se = '';
	}
	
	filter_picklist2(id);
}

function remove_picklist2(id) {
	var to = ge('cur_' + id);
	var data = ge('table_' + id).dx;
	for(var j = 0; j < data.length; j++) {
		var d = data[j];
		if(!d || !d.text)
			continue;
		if(d.se == 'true') {
			d.se = '';
			break;
		}
	}
	filter_picklist2(id);
}

function filter_picklist2(id) {
	var filter = ge('filter_' + id);
	var fval = filter.value;
	var nosel = true;
	if(fval == '')
		fval = null;
	else
		fval = ('' + fval).toLowerCase();
	var data = ge('table_' + id).dx;
	var cur = ge('cur_' + id);
	var ava = ge('ava_' + id);
	var aava = [];
	for(var i = 0; i < data.length; i++) {
		var d = data[i];
		if(!d || !d.text)
			continue;
		if(d.se == 'true') {
			cur.value = d.text;
			nosel = false;
		}
		else if(!fval || d.xtext.indexOf(fval) != -1) {
			aava.push(d);
		}
	}
	set_selecto(ava, aava, 'val', 'text', null, false, null);
	if(nosel) {
		cur.value = '';
	}
}

function urle_lookup(id) {
	var users = get_json().UserRoleLookupServer.lookupUsers(ge('urle_lookup_' + id).value);
	set_selecto(ge('urle-user-lookup-' + id), users, 0, 1, null, false, null);
}

function urle_add(id) {
	var from = ge('urle-user-lookup-' + id);
	var to = ge('urle-current-users_' + id);
	for(var i = 0; i < from.options.length; i++) {
		if(from.options[i].selected) {
			add_selecto(to, from.options[i].value, from.options[i].firstChild.nodeValue);
		}
	}
}

function urle_remove(id) {
	var to = ge('urle-current-users_' + id);
	var any_selected;
	do {
		any_selected = false
		for(var i = 0; i < to.options.length; i++) {
			if(to.options[i].selected) {
				to.options[i] = null;
				any_selected = true;
				continue;
			}
		}
	}
	while(any_selected);
}

function urle_get_value(id) {
	var from = ge('urle-current-users_' + id);
	var to = ge('urle-val-' + id);
	var arr = [];
	for(var i = 0; i < from.options.length; i++) {
		if(from.options[i].value != '0')
			arr.push(from.options[i].value);
	}
	to.value = arr.join(',');
}

function check_multi_dyna(sel2) {
	var mdc = sel2.parentNode;
	if(mdc.className && mdc.className == 'multi-dyna-cola') {
		cola_title(ga(mdc.parentNode.parentNode.parentNode, 'base-id'));
	}
	else if(ga(sel2, 'select-type') == 'multicheck-dyna-cola') {
		cola_title(ga(sel2, 'cola-id'));
	}
}

function get_users_for_company() {
	var sel = gereg('iflowcrm.project_cz.c2d.asprecruiter.data.Project.developerCompany');
	var sel2 = gereg('iflowcrm.project_cz.c2d.asprecruiter.data.Project.primaryDeveloperContact');
	var sel3 = gereg('iflowcrm.project_cz.c2d.asprecruiter.data.Project.secondaryDeveloperContact');
	
	if(!sel || (!sel2 && !sel3))
		return;
	var id = get_selecto(sel);

	//var ret = get_json().ProjectServer.get_people_for_company(id);
	var ret = get_json().ProjectServer.get_subcols(processName, 'developerCompany', 'primaryDeveloperContact', [ Number(id) ], null, 'primaryCompanies');
	
	//ret = get_json().ProjectServer.get_subcols(processName, master, subordinate, [ Number(id) ], null);
	
	if(sel2 != null)
		set_selecto(sel2, ret, 0, 1, null, true);
	if(sel3 != null)
		set_selecto(sel3, ret, 0, 1, null, true);
}

function get_units_for_project() {
	var sel = gereg('iflowcrm.opportunity_cz.c2d.siva.data.Opportunity.project');
	var sel2 = gereg('iflowcrm.opportunity_cz.c2d.siva.data.Opportunity.unit');
	
	if(!sel || !sel2)
		return;
	var id = get_selecto(sel);
	var ret = get_json().OpportunityServer.get_units_for_project(id);
	
	set_selecto(sel2, ret, 0, 1, null, true);
}


function flip_login() {
	var t = ge('top-login');
	if(t.className == 'top-login') { //open
		t.className = 'top-login-open';
		var swap = ge('open_link').firstChild.nodeValue;
		ge('open_link').firstChild.nodeValue = ge('login-links').getAttribute('close-text');
		ge('login-links').setAttribute('close-text', swap);
		//focus onto first empty field
		if(ge('login_username').value == '')
			ge('login_username').focus();
		else
			ge('login_password').focus();
	}
	else { //close
		t.className = 'top-login';
		var swap = ge('open_link').firstChild.nodeValue;
		ge('open_link').firstChild.nodeValue = ge('login-links').getAttribute('close-text');
		ge('login-links').setAttribute('close-text', swap);
	}
}

var popup_menu_switch = false;

function flip_popup_menu() {
	var pmi = ge('popup-menu-img-off');
	var pm = ge('popup-menu');
	if(!popup_menu_switch) {
		if(pmi)
			pmi.style.display = 'none';
		if(pm)
			pm.style.display = 'block';
		popup_menu_switch = true;
	}
	else {
		if(pm)
			pm.style.display = 'none';
		if(pmi)
			pmi.style.display = 'block';
		popup_menu_switch = false;
	}
}

function completeTask(list_id, item_id, completed) {
	try {
		var ret = get_json().ActivityServer.completeTask(list_id, item_id, completed);
		var id = 'chk_' + list_id + '_' + item_id;
		var chk = ge(id);
		var row = chk.parentNode.parentNode;
		if(!row.hasAttribute('baseClassName')) {
			row.setAttribute('baseClassName', new String(row.className).indexOf('-odd-') != -1 ? 'list-odd-row' : 'list-even-row');
		}
		row.className = row.getAttribute('baseClassName') + ' ' + (completed ? 'grayed-task-row' : '');
	}
	catch(e) {
		alert('Error checking the checkbox, please reload the page. (' + e + ')');
	}
}

function selectPortalToPost(list_id, portal_id, checked) {
	try {
		var unit_id = processDataID;
		var ret = get_json().UnitPortalPostServer.completeTask(list_id, unit_id, portal_id, checked);
	}
	catch(e) {
		alert('Error checking the checkbox, please reload the page. (' + e + ')');
	}
}

function videoViewing(video_id) {
	get_json().VideoServer.videoViewed(video_id);
}

function di4_checkall(from, to) {
	var all_checked = true;
	for(var i = 0; i < di4reg.length; i++) {
		var id = di4reg[i];
		var chk = ge(id);
		if(!chk)
			continue;
		if(!chk.checked) {
			all_checked = false;
			break;
		}
	}
	for(var i = 0; i < di4reg.length; i++) {
		var id = di4reg[i];
		var chk = ge(id);
		if(!chk)
			continue;
		chk.checked = !all_checked;
	}
}

function di4_delete(from, to) {
	var td = [];
	for(var i = 0; i < di4reg.length; i++) {
		var id = di4reg[i];
		var chk = ge(id);
		if(chk && chk.checked) {
			td.push(id);
		}
	}
	try {
		var tx = get_json().DataImport3Server.deleteItems(td);
		for(var i = 0; i < td.length; i++) {
			var id = tx[i];
			var chk = ge(id);
			if(chk)
				chk.parentNode.parentNode.parentNode.removeChild(chk.parentNode.parentNode);
		}
	}
	catch(e) {
		alert('Could not delete, reason: ' + e + '\nPlease refresh the page.');
	}
}

var download_props_progress;
function download_properties() {
	if(download_props_progress != null)
		return;
	download_props_progress = new JS_BRAMUS.jsProgressBar($('pbar'), 0, { barImage : [
		'/core/progress/percentImage_back4.png',
		'/core/progress/percentImage_back3.png',
		'/core/progress/percentImage_back2.png',
		'/core/progress/percentImage_back1.png' ] });
	get_json().DownloadPropertiesServer.startDownloadTask();
	setTimeout('download_properties_check_progress()', 3000);
}

function download_properties_check_progress() {
	var pi = get_json().DownloadPropertiesServer.taskStatus();
	if(pi.message != null) { //error
		alert(pi.message);
	}
	else {
		download_props_progress.setPercentage('' + pi.percent);
		if(pi.percent == 100) {
			window.location.href = '/properties/units/my-units'; 
		}
		else {
			setTimeout('download_properties_check_progress()', 3000);
		}
	}
}

function flip_us_params() {
	var d = ge('us-params2');
	if(d.style.visibility == 'hidden') {
		d.style.visibility = 'visible';
		ge('us-filter').focus();
	}
	else {
		d.style.visibility = 'hidden';
		ge('flip-us-params').blur();
	}
}

function us_cat(a) {
	if(a.nextSibling.style.display == 'none')
		a.nextSibling.style.display = 'block';
	else
		a.nextSibling.style.display = 'none';
	a.blur();
	return false;
}

var us_sliders = {}, us_sliders_by_right = {}, us_sliders_by_left = {};

//if 'currency' is empty, it's an integer slider
function us_create_slider(p, from, to, sep, currency) {
	var t = ge('IDPH_criq');
	var parent_id = p.id;
	var sl = t.cloneNode(true);
	replaceIDs(sl, 'IDPH', parent_id);
	p.appendChild(sl);
	var o = {};
	o.main = ge(parent_id + '_criq');
	o.left_ctl = ge(parent_id + '_criq_sleft');
	o.right_ctl = ge(parent_id + '_criq_sright');
	o.runner = ge(parent_id + '_criq_runner');
	o.left_label = ge(parent_id + '_criq_left').firstChild;
	o.right_label = ge(parent_id + '_criq_right').firstChild;
	o.currency_label = ge(parent_id + '_criq_currency');
	if(o.main == null || o.left_ctl == null || o.right_ctl == null || o.runner == null || o.left_label == null || o.right_label == null || o.currency_label == null)
		throw new Error('Slider failed to initialise.');
	if(currency)
		o.currency_label.firstChild.nodeValue = currency;
	else
		o.currency_label.style.display = 'none';
	o.from = from;
	o.to = to;
	o.sep = sep;
	us_sliders[parent_id] = o;
	us_sliders_by_right[parent_id + '_criq_sright'] = o;
	us_sliders_by_left[parent_id + '_criq_sleft'] = o;
	o.main.style.display = 'block';
	us_update_slider(o);
	o.w = o.right_ctl.offsetWidth;
	o.maxRight = o.runner.clientWidth - (o.w * 2);
	o.right_ctl.style.left = o.maxRight;
	o.lpos = 0;
	o.rpos = o.maxRight;
	o.ldrag = false;
	o.rdrag = false;
	o.runnerOffset = getAbsolutePosition(o.runner).x;
}

function us_update_slider(o) {
	var l, r;
	if(o.ldrag) {
		l = 0;
		r = o.rpos;
	}
	else if(o.rdrag) {
		l = o.lpos;
		r = o.maxRight;
	}
	else {
		var lf = us_slider_format(o.from, o);
		o.left_label.nodeValue = lf.t;
		o.lval = lf.v;
		if(o.lpos == 0)
			o.lval = o.from;
		var rf = us_slider_format(o.to, o);
		o.right_label.nodeValue = rf.t
		o.rval = rf.v;
		if(o.rpos == o.maxRight)
			o.rval = o.to;
		return;
	}
	var x = o.dragx - o.offx;
	if(x < l)
		x = l;
	else if(x > r)
		x = r;
	if(o.ldrag) {
		o.lpos = x;
		o.left_ctl.style.left = x;
		var v = o.from + ((o.to - o.from) * (o.lpos / o.maxRight));
		var lf = us_slider_format(v, o);
		o.left_label.nodeValue = lf.t;
		o.lval = lf.v;
		if(o.lpos == 0)
			o.lval = o.from;
	}
	else {
		o.rpos = x;
		o.right_ctl.style.left = x;
		var v = o.from + ((o.to - o.from) * (o.rpos / o.maxRight));
		var rf = us_slider_format(v, o);
		o.right_label.nodeValue = rf.t;
		o.rval = rf.v;
		if(o.rpos == o.maxRight)
			o.rval = o.to;
	}
}

function us_remove_slider(parent_id) {
	var o = us_sliders[parent_id];
	delete us_sliders[parent_id];
	delete us_sliders_by_right[parent_id + '_criq_sright'];
	delete us_sliders_by_left[parent_id + '_criq_sleft'];
	delete o.main;
	delete o.left_ctl;
	delete o.right_ctl;
	delete o.runner;
	delete o.left_label;
	delete o.right_label;
	delete o.currency_label;
}

var us_glob_drag_id;

function us_drag(e, left) {
	if(!e) var e = window.event;
	var g = us_glob_drag_id != null ? us_glob_drag_id : (e.target ? e.target : e.srcElement).id;
	us_glob_drag_id = g;
	var x = e.pageX ? e.pageX : e.clientX + document.body.scrollLeft;
	var o = left ? us_sliders_by_left[g] : us_sliders_by_right[g];
	x -= o.runnerOffset;
	return { e: e, x: x, o: o };
}

function us_start_drag(movefunc, upfunc) {
	if(document.attachEvent) {
		document.attachEvent("onmousemove", movefunc);
		document.attachEvent("onmouseup", upfunc);
	}
	else {
		document.addEventListener("mousemove", movefunc, true);
		document.addEventListener("mouseup", upfunc, true);
	}
}

function us_end_drag(movefunc, upfunc) {
	if(document.detachEvent) {
		document.detachEvent("onmousemove", movefunc);
		document.detachEvent("onmouseup", upfunc);
	}
	else {
		document.removeEventListener("mousemove", movefunc, true);
		document.removeEventListener("mouseup", upfunc, true);
	}
}

function us_start_drag_left(e) {
	var d = us_drag(e, true);
	d.o.offx = d.x - d.o.lpos;
	d.o.dragx = d.x;
	d.o.ldrag = true;
	us_eevt(e);
	us_start_drag(us_do_drag_left, us_cancel_drag_left);
}

function us_start_drag_right(e) {
	var d = us_drag(e, false);
	d.o.offx = d.x - d.o.rpos;
	d.o.dragx = d.x;
	d.o.rdrag = true;
	us_eevt(e);
	us_start_drag(us_do_drag_right, us_cancel_drag_right);
}

function us_do_drag_left(e) {
	var d = us_drag(e, true);
	if(d.o.ldrag != true)
		return;
	d.o.dragx = d.x;
	us_update_slider(d.o);
	us_eevt(e);
}

function us_do_drag_right(e) {
	var d = us_drag(e, false);
	if(d.o.rdrag != true)
		return;
	d.o.dragx = d.x;
	us_update_slider(d.o);
	us_eevt(e);
}

function us_cancel_drag_left(e) {
	var d = us_drag(e, true);
	d.o.ldrag = false;
	d.o.rdrag = false;
	us_end_drag(us_do_drag_left, us_cancel_drag_left);
	us_glob_drag_id = null;
	us_refilter_units();
}

function us_cancel_drag_right(e) {
	var d = us_drag(e, false);
	d.o.ldrag = false;
	d.o.rdrag = false;
	us_end_drag(us_do_drag_right, us_cancel_drag_right);
	us_glob_drag_id = null;
	us_refilter_units();
}


function us_eevt(e) {
	if(window.event) {
		window.event.cancelBubble = true;
    	window.event.returnValue = false;
    }
    else if(e.preventDefault) {
    	e.preventDefault();
    }
}

function us_slider_format(v, o) {
	v = Number(v);
	if(v < 0)
		return { t: '< 0', v: 0 };
	if(v < 1000)
		return { t: '' + Math.round(v), v: Math.round(v) };
	if(v < 1000000) { //9.4k 99k 999k
		if(v < 10000) {
			x = v / 1000;
			x = (x - Math.floor(x)) * 10;
			return { t: '' + Math.floor(v / 1000) + o.sep + Math.floor(x) + 'k', v: (Math.floor(v / 1000) * 1000) + (Math.floor(x) * 100) };
		}
		else {
			return { t: '' + Math.round(v / 1000) + 'k', v: Math.round(v / 1000) * 1000 };
		}
	}
	if(v < 1000000000) { //9.4m 99m 999m
		if(v < 10000000) {
			x = v / 1000000;
			x = (x - Math.floor(x)) * 10;
			return { t: '' + Math.floor(v / 1000000) + o.sep + Math.floor(x) + 'm', v: (Math.floor(v / 1000000) * 1000000) + (Math.floor(x) * 100000) };
		}
		else {
			return { t: '' + Math.round(v / 1000000) + 'm', v: Math.round(v / 1000000) * 1000000 };
		}
	}
	if(v >= 1000000000) {
		return { t: '>1bn', v: v };
	}
	return { t: 'NaN', v: 0 };
}

function replaceIDs(node, placeholder, base_id) {
	var id = node.getAttribute('id');
	if(id != null) {
		id = id.replace(placeholder, base_id);
		node.setAttribute('id', id);
	}
	if(!node.hasChildNodes())
		return;
	for(var i = 0; i < node.childNodes.length; i++) {
		var c = node.childNodes.item(i);
		if(!c.nodeType || c.nodeType != 1)
			continue;
		replaceIDs(c, placeholder, base_id);
	}
}

var us_units;

function us_search_init() {
	var a = get_json().UnitSearchServer.loadUnits();
	var cats = a[0];
	var unts = a[1];
	
	var cat_tmpl = ge('us-cat-tmpl');
	var itm_tmpl = ge('us-cat-param-tmpl');
	var params = ge('us-params');
	
	var title_idx1 = a[2][0] + 2;
	var title_idx2 = a[2][1];
	var unitid_idx1 = a[2][2] + 2;
	var unitid_idx2 = a[2][3];
	
	us_units = unts;
	
	var aaid = 0;
	for(var i = 0; i < cats.length; i++) {
		var cat = cats[i];
		var any = false;
		for(var j = 2; j < cat.length; j++) {
			if(cat[j] != null) {
				any = true;
				break;
			}
		}
		if(!any)
			continue;
		var cc = cat_tmpl.cloneNode(true);
		cc.setAttribute('id', 'cat' + i);
		cc.catidx = i;
		cc.firstChild.firstChild.nodeValue = cat[0];
		var type = cat[1];
		cc.setAttribute('cat-type', type);
		params.appendChild(cc);
		cc.style.display = 'block';
		
		//1 - ref, 2 - col, 3 - boolean/YesNo, 4 - string, 5 - money, 6 - number
		for(var j = 2; j < cat.length; j++) {
			var t = cat[j];
			if(!t)
				continue;
			var aa = itm_tmpl.cloneNode(true);
			aa.setAttribute('id', 'itm' + aaid);
			aa.data = t; //will leak?
			aa.typex = j;
			aaid++;
			aa.firstChild.nodeValue = t[0]; // + (t[1].length ? ' (' + t[1].length + ')' : '');
			cc.firstChild.nextSibling.appendChild(aa);
			aa.style.display = 'block';
		}
	}
	
	var res = ge('us-results');
	for(var i = 0; i < unts.length; i++) {
		var unt = unts[i];
		var uid = unt[0];
		var pic = unt[1];
		var lnk = '/properties/units/process?id=' + uid;
		var d1 = document.createElement('div');
		d1.id = 'us-unit-' + uid;
		//d1.setAttribute('uid', uid);
		d1.uid = uid;
		d1.uix = i;
		d1.className = 'us-unt';
		var d2 = document.createElement('div');
		d2.className = 'us-unt-pic';
		var a1 = document.createElement('a');
		a.href = lnk;
		var i1 = document.createElement('img');
		if(pic != null)
			i1.src = '/private/documents/' + pic;
		i1.border = '0';
		a1.appendChild(i1);
		d2.appendChild(a1);
		d1.appendChild(d2);
		var d3 = document.createElement('div');
		d3.className = 'us-unt-data';
		var d4 = document.createElement('div');
		var a2 = document.createElement('a');
		a2.href = lnk;
		var title = unt[title_idx1] ? unt[title_idx1][title_idx2] : null;
		if(!title) 
			title = unt[unitid_idx1] ? unt[unitid_idx1][unitid_idx2] : null;
		if(!title)
			title = 'ID ' + uid;
		a2.appendChild(document.createTextNode(shortenText(title, 50)));
		d4.appendChild(a2);
		d3.appendChild(d4);
		d1.appendChild(d3);
		res.appendChild(d1);
		//next stuff goes under d3
	}
	
	us_filter(ge('us-filter'));
	ge('us-filter').focus();
}


function us_add_item(a) {
	//1 - ref, 2 - col, 3 - boolean/YesNo, 4 - string, 5 - money, 6 - number
	a.blur();
	var cat = a.parentNode.parentNode;
	var ct = cat.getAttribute('cat-type');
	var cr = document.createElement('div');
	cr.setAttribute('id', 'inst_' + a.id);
	cr.className = 'us-criq';
	cr.catidx = cat.catidx;
	var cra = document.createElement('a');
	cra.className = 'us-caq';
	cr.typex = a.typex;
	cra.setAttribute('href', '#');
	listen(cra, 'click', us_rem_caq);
	cra.setAttribute('ctype', ct);
	cr.setAttribute('ctype', ct);
	cra.uspar = a.id;
	a.ushid = true;
	a.style.display = 'none';
	
	//hide section if all items hidden (by filter or ushid)
	var f = ge('us-filter');
	var val = f.value;
	if(val == f.getAttribute('remtext'))
		val = '';
	us_filter_subcat(cat, val, true);
	
	cra.appendChild(document.createTextNode(cat.firstChild.firstChild.nodeValue + ': ' + a.firstChild.nodeValue));
	cr.appendChild(cra);
	ge('us-crits').appendChild(cr);
	
	if(ct == 1 || ct == 2 || ct == 3) {
		cr.data = a.data[1]; //list of units
	}
	else if(ct == 4) { //edit field
		us_create_input(cr);
	}
	else if(ct == 5) { //money range
		us_create_slider(cr, a.data[1], a.data[2], a.data[3], a.data[4]);
	}
	else if(ct == 6) { //int range
		us_create_slider(cr, a.data[1], a.data[2], a.data[3]);
	}
	
	us_refilter_units();
	return false;
}

function us_refilter_units() {
	var rcat = {};
	var ucr = ge('us-crits');
	var ie = new IterableElements(ucr);
	while(ie.hasNext()) {
		var cr = ie.next();
		var ct = cr.getAttribute('ctype');
		if(ct == 1 || ct == 2 || ct == 3) {
			var cat_id = cr.catidx;
			var r = rcat[cat_id];
			if(!r) {
				r = {};
				rcat[cat_id] = r;
			}
			var crd = cr.data;
			for(var i = 0; i < crd.length; i++) {
				var crdi = crd[i];
				r[crdi] = true; //OR inside a single category
			}
		}
	}
	var first = true;
	var any = false;
	var r = {};
	for(var rrx in rcat) {
		var rr = rcat[rrx];
		if(first) {
			for(var ri in rr) {
				//var ri = rr[rx];
				r[ri] = true;
				any = true;
			}
			first = false;
		}
		else {
			var rrr = {};
			for(var ri in rr) {
				//var ri = rr[rx];
				if(r[ri]) {
					rrr[ri] = true; //AND accross categories
					any = true;
				}
			}
			r = rrr;
		}			
	}		

	//abc
	var ciqs = [];
	var ix = new IterableElements(ucr);
	while(ix.hasNext()) {
		var cr = ix.next();
		var ct = cr.getAttribute('ctype');
		if(ct == 4) { //edit field
			var val = ge(cr.id + '_filter').value;
			if(val != '')
				ciqs.push({ uiz: cr.catidx, ct: ct, val: val.toLowerCase(), uiy: cr.typex - 2 });
		}
		else if(ct == 5 || ct == 6) { //int range, money range
			var sl = us_sliders[cr.id];
			ciqs.push({ uiz: cr.catidx, ct: ct, lval: sl.lval, rval: sl.rval, uiy: cr.typex - 2 });
		}
	}
	
	ie = new IterableElements(ge('us-results'));
	while(ie.hasNext()) {
		var unt = ie.next();
		var showx = !any || r[unt.uid];
		if(showx == true) {
			for(var i = 0; showx && i < ciqs.length; i++) {
				var ciq = ciqs[i];
				if(ciq.ct == 4) {
					var dt = us_units[unt.uix][ciq.uiz + 2][ciq.uiy];
					showx = dt != null ? dt.toLowerCase().indexOf(ciq.val) != -1 : false;
				}
				else { //5,6
					var dt = us_units[unt.uix][ciq.uiz + 2];
					var dt = dt != null ? dt[ciq.uiy] : null;
					showx = dt != null ? ciq.lval <= dt && ciq.rval >= dt : false;
				}
			}
		}
		unt.style.display = showx ? 'block' : 'none';
	}
}


function listen(p, evt, func) {
	if(p.attachEvent)
		p.attachEvent('on' + evt, func);
	else
		p.addEventListener(evt, func, true);
}

function unlisten(p, evt, func) {
	if(p.detachEvent)
		p.detachEvent('on' + evt, func);
	else
		p.removeEventListener(evt, func, true);
}


function us_create_input(p) {
	var ip = document.createElement('input');
	ip.setAttribute('id', p.id + '_filter');
	ip.setAttribute('type', 'text');
	listen(ip, 'keyup', us_filter_change);
	ip.className = 'us-criq-filter';
	p.appendChild(ip);
}

function us_filter_change(e) {
	e = evx(e);
	us_refilter_units();
}

function us_rem_caq(e) {
	e = evx(e);
	us_eevt(e);
	var cra = e.target;
	var cr = cra.parentNode;
	var aa = ge(cra.uspar);
	aa.ushid = false;
	if(aa.ctype == 5 || aa.ctype == 6) {
		us_remove_slider(cr.id);
	}
	cr.parentNode.removeChild(cr);
	
	//show item if not filtered
	//show cat if hidden and item is shown
	var f = ge('us-filter');
	var val = f.value;
	if(val == f.getAttribute('remtext'))
		val = '';
	us_filter_subcat(aa.parentNode.parentNode, val, true);
	us_refilter_units();
}

function shortenText(txt, maxlen) {
	if(txt.length >= maxlen)
		return txt.substring(0, maxlen - 3) + "...";
	return txt;
}

function us_filter(f) {
	var val = f.value;
	if(val == f.getAttribute('remtext'))
		val = '';
	val = val.toLowerCase();
	var d = ge('us-params');
		
	var ie = new IterableElements(d);
	ie.next();
	while(ie.hasNext()) {
		var cat = ie.next();
		us_filter_subcat(cat, val, false);
	}
}

function us_filter_subcat(cat, val, preserve) {
	var catp = cat.firstChild.nextSibling;
	var filtering = val != '';
	var showcat = !filtering;
	var catopen = preserve ? catp.style.display == 'block' : false;
	
	var ie2 = new IterableElements(catp);
	while(ie2.hasNext()) {
		var itm = ie2.next();
		if(itm.ushid || (filtering && itm.firstChild.nodeValue.toLowerCase().indexOf(val) == -1)) {
			itm.style.display = 'none';
		}
		else {
			itm.style.display = 'block';
			if(filtering) {
				catopen = true;
				showcat = true;
			}
		}
	}
	catp.style.display = catopen ? 'block' : 'none';
	cat.style.display = showcat ? 'block' : 'none';
}

function us_reset() {
	var f = ge('us-filter');
	f.value = '';
	us_filter(f)
	f.focus();
}

function us_filter_okd(f) {
	if(f.value == f.getAttribute('remtext')) {
		f.value = '';
	}
}

function us_filter_oku(e) {
	e = evx(e);
	if(e.key == 27) {
		e.target.value = '';
	}
	us_filter(e.target);
}

function us_filter_onb(f) {
	if(f.value == '') {
		f.value = f.getAttribute('remtext');
	}
}

function us_filter_clk(f) {
	if(f.value == f.getAttribute('remtext')) {
		f.value = '';
	}
}

var glob_open_adv_listbox_id = null;

function adv_listbox_open(pid, close_button) {
	if(glob_open_adv_listbox_id != null) {
		if(glob_open_adv_listbox_id == pid && close_button) {
			adv_listbox_close(pid, null, null);
		}
		return;
	}
	var ls = ge(pid + '_list');
	glob_open_adv_listbox_id = pid;
	
	listen(document, 'mousedown', adv_listbox_close_cancel);
	
	var hd = ge(pid);
	if(hd.value) {
		hd.tvalue = hd.value;
		select_adv_ls_item(pid, hd.tvalue);
	}
	
	ls.style.visibility = 'visible';
	var ed = ge(pid + '_edit');
	ed.value = '';
	ed.focus();
}

function adv_listbox_refilter(pid) {
	var ed = ge(pid + '_edit');
	var v = ed.value;
	if(v && v == '')
		v = null;
	else {
		v = ('' + v).toLowerCase();
	}
	adv_listbox_refilter_val(pid, v);
}

function adv_listbox_refilter_val(pid, v) {
	var is_tr;
	var ls = ge(pid + '_list');
	for(var i = 0; i < ls.rows.length; i++) {
		var r = ls.rows[i];
		if(r.getAttribute('action') > '')
			continue;
		var show = false;
		if(!v) {
			show = true;
		}
		else {
			var xv = r.getAttribute('xvalue');
			show = xv.indexOf(v) != -1;
		}
		if(show) {
			if(is_tr == undefined) {
				try {
					r.style.display = 'table-row';
					is_tr = true;
				}
				catch(ex) {
					is_tr = false;
				}
			}
			r.style.display = is_tr ? 'table-row' : 'block';
		}
		else {
			r.style.display = 'none';
		}
	}
}

function adv_listbox_click(tr) {
	var pid = tr.getAttribute('pid');
	
	var ac = tr.getAttribute('action');
	if(ac) {
		adv_listbox_close(pid, null, null);
		eval(ac + '(\'' + pid + '\');');
		//alert('TODO: action call: ' + ac + '()');
		//var func;
		//eval('func = ' + ac);
		//alert('func: ' + func);
		//func();
	}
	else {
		var val = tr.getAttribute('value');
		var txt = tr.getAttribute('text');
		adv_listbox_close(pid, val, txt);
	}
}

function adv_lb_clicked_inside(pid, p) {
	var pl = pid + '_list';
	var pt = pid + '_table';
	for(var i = 0; i < 10; i++) {
		if(!p || p.nodeType != 1)
			return false;
		if(p.id && (p.id == pl || p.id == pt))
			return true;
		p = p.parentNode;
	}
	return false;
}

function adv_listbox_close_cancel(e) {
	if(!e) var e = window.event;
	var pid = glob_open_adv_listbox_id;
	if(!pid)
		return;
		
	var src = e.target ? e.target : e.srcElement;
	
	if(adv_lb_clicked_inside(pid, src))
		return;
		
	adv_listbox_close(pid, null, null);
}

function adv_listbox_close(pid, val, txt) {
	var ls = ge(pid + '_list');
	ls.style.visibility = 'hidden';
	var hd = ge(pid);
	if(hd.tvalue) {
		deselect_adv_ls_item(pid, hd.tvalue);
	}
	if(val != null) {
		hd.value = val;
	}
	if(txt != null) {
		ge(pid + '_edit').value = txt;
	}
	else {
		var tr = ge(pid + '_' + hd.value);
		if(tr) {
			txt = tr.getAttribute('text');
			if(txt != null) {
				ge(pid + '_edit').value = txt;
			}
		}
	}
	glob_open_adv_listbox_id = null;
	adv_listbox_refilter_val(pid, null);
	unlisten(document, 'mousedown', adv_listbox_close_cancel);
}

function adv_listbox_over(pid, val) {
	var hd = ge(pid);
	if(hd.tvalue) {
		deselect_adv_ls_item(pid, hd.tvalue);
	}
	hd.tvalue = val;
	select_adv_ls_item(pid, hd.tvalue);
}

function select_adv_ls_item(pid, val) {
	ge(pid + '_' + val).className = 'adv-listbox-sel';
}

function deselect_adv_ls_item(pid, val) {
	ge(pid + '_' + val).className = 'adv-listbox';
}

var new_seller_pid;

function new_seller(pid) {
	var w = open_win('/contacts/people/process?id=0&tmpstyle=true&style=bare&quick-create-seller=true&type=client', 655, 700, 'new_seller', true);
	new_seller_pid = pid;
}

function new_seller_added(id, fname, lname, u2fname, u2lname, icon) {
	//alert('id:'+id+' fname:'+fname+' lname:'+lname+' u2fname:'+u2fname+' u2lname:'+u2lname+' icon:'+icon);
	//alert('new_seller_pid: ' + new_seller_pid);
	adv_listbox_add_item(new_seller_pid, id, u2fname + ' ' + u2lname, fname + ' ' + lname, icon, null);
	adv_listbox_click(ge(new_seller_pid + "_" + id));
}

function adv_listbox_add_item(pid, value, xvalue, text, icon, action) {
	var ls = ge(pid + '_list');
	var row = ls.insertRow(ls.rows.length);
	row.setAttribute('id', pid + '_' + value);
	row.className = 'adv-listbox';
	row.setAttribute('action', action);
	row.setAttribute('onclick', 'adv_listbox_click(this)');
	row.setAttribute('value', value);
	row.setAttribute('text', text);
	row.setAttribute('xvalue', xvalue);
	row.setAttribute('onmouseover', 'adv_listbox_over("' + pid + '", "' + value + '")');
	row.setAttribute('pid', pid);
	var cell1 = row.insertCell(0);
	var cell2 = row.insertCell(1);
	var img = document.createElement('img');
	img.className = 'adv-listbox-icon';
	img.setAttribute('height', '19');
	img.setAttribute('width', '18');
	img.setAttribute('src', '/iflowcrm/iflowcrm/icons/small/lead_small.jpg');
	cell1.appendChild(img);
	cell2.appendChild(document.createTextNode(text));
}


function quick_search_button(base_id) {
	var ed = ge(base_id + '_edit');
	var url = ed.getAttribute('url');
	var val = ed.value;
	if(val)
		window.location.href = url + ed.value;
}

function qfb_focus(ed) {
	var defval = ed.getAttribute('defval');
	var val = ed.value;
	if(val === defval)
		ed.value = '';
}

function qfb_blur(ed) {
	if(ed.value == '')
		ed.value = ed.getAttribute('defval');
}

var address_picker2_id; //closed when null
var address_picker2_map;
var address_data = [];

function address_picker2(ed) {
	if(!address_picker2_id) {
		address_picker2_id = ed.id;
		var dv = ge(address_picker2_id  + '_div');
		if(!dv) {
			//create the structure
			var dvp = document.createElement('DIV');
			dvp.className = 'gm2dvp';
			ed.parentNode.appendChild(dvp);

			dv = document.createElement('DIV');
			dv.id = address_picker2_id  + '_div';
			dv.className = 'gm2dv';
			dvp.appendChild(dv);
			
			var dv2 = document.createElement('DIV');
			dv2.id = address_picker2_id  + '_div2';
			dv2.className = 'gm2dv2';
			dv.appendChild(dv2);
			
			var dv3 = document.createElement('DIV');
			dv3.id = address_picker2_id  + '_div3';
			dv3.className = 'gm2dv3';
			dv.appendChild(dv3);
			
			var map = new google.maps.Map2(dv3, { size: new GSize(398, 398) });
			map.addControl(new GLargeMapControl());
			map.addControl(new GScaleControl());
			map.addControl(new GMapTypeControl());
			//GEvent.addListener(map, "click", map_clicked);
			
			address_picker2_map = map;
		}
		listen(document, 'mousedown', address_picker2_close_cancel);
		dv.style.display = 'block';		
	}
	//clean the addresses
	address_picker2_clean_addresses();
	//load the addresses
	address_picker2_load_addresses();
	//position the map on the first address
}

function address_picker2_clean_addresses() {
	var dv2 = ge(address_picker2_id  + '_div2');
	purgeChildren(dv2);
}

function address_picker2_load_addresses() {
	var dv2 = ge(address_picker2_id  + '_div2');
	var ed = ge(address_picker2_id);
	//Pick an address below, or double click the map...
	var txt_pick_adr = ed.getAttribute('text2')
	var txt_loading = ed.getAttribute('text1')
	
	if(ed.value == '')
		return;

	var dt = t('div', { $class: 'gm2dv4-off', $text: txt_loading });
	ac(dv2, dt);
	
	var new_sys = geregx('administrativeArea') != null;
	
	var adrs = get_json().AddressPicker2Server.standardize(ed.value, new_sys);
	address_data = adrs;
	address_picker2_clean_addresses();
	var sel;
	
	for(var i = 0; i < adrs.length; i++) {
		var adr = adrs[i];
		var d = t('div', { $class: 'gm2dv4-off', data: '' + i, $text: adr.adrString,
			onclick: ap2_onclick, onmouseover: ap2_onmouseover, onmouseout: ap2_onmouseout  });
		ac(dv2, d);
		if(i == 0)
			sel = d;
	}
	if(adrs.length == 0)
		address_picker2_map.setCenter(new google.maps.LatLng(50.087547, 14.420242), 13); //prague for now; later by GeoIP
	else 
		ap2_sel_dv4(sel);
}

function ap2_onclick(e) {
	var dv4 = gt(e);
	dv4.blur();
	ap2_sel_dv4(dv4);
}

function ap2_sel_dv4(dv4) {
	var dv2 = ge(address_picker2_id  + '_div2');
	var ie = new IterableElements(dv2);
	while(ie.hasNext()) {
		var d4 = ie.next();
		if(d4.tagName == 'DIV')
			d4.className = 'gm2dv4-off';
	}
	dv4.className = 'gm2dv4-sel';
	
	var id = Number(ga(dv4, 'data'));
	var adr = address_data[id];
	address_picker2_map.clearOverlays();
	address_picker2_map.setCenter(new google.maps.LatLng(adr.lat, adr.lon), 15);
	var g = new GMarker(new GLatLng(adr.lat, adr.lon));
	address_picker2_map.addOverlay(g);
	var sel;
	
	var dv_msg_id = address_picker2_id + '_div_msg';
	var dv_msg = ge(dv_msg_id);
	if(adr.countryId == 0 || adr.countyId == 0 || adr.cityId == 0 || adr.districtId == 0) {
		var msg = 'It was not possible to fully match the selected address with our database. ' +
			'Just leave the address fields empty and our staff will shortly review and update these for you.';
		
		if(dv_msg != null) {
			set_valueo(dv_msg, msg);
		}
		else {
			dv_msg = t('div', { id: dv_msg_id, $text: msg, $class: 'gm2dvmsg' });
			var dv = ge(address_picker2_id + '_div');
			var dvp = dv.parentNode.parentNode;
			ac(dvp, dv_msg);
		}
	}
	else {
		if(dv_msg) {
			dv_msg.parentNode.removeChild(dv_msg);
		}
	}
	
	//if(ard.new_cz_system == true) {
	
	if(adr.countryId && (sel = geregx('country'))) {
		select_selecto(sel, adr.countryId, false);
		subcol('country', 'county', false);
	}
	
	if(adr.countyId && (sel = geregx('county'))) {
		select_selecto(sel, adr.countyId, false);
		subcol('county', 'city', false);
	}
		
	if(adr.cityId && (sel = geregx('city'))) {
		select_selecto(sel, adr.cityId, false);
		subcol('city', 'district', false);
	}
		
	if(adr.districtId && (sel = geregx('district'))) {
		select_selecto(sel, adr.districtId, false);
		subcol('district', 'suburb', false);
	}
	
	if(adr.suburbId && (sel = geregx('suburb'))) {
		select_selecto(sel, adr.suburbId, false);
		subcol('suburb','streetName');
		subcol('suburb','psc');
	}
	
	if(adr.administrativeAreaId && (sel = geregx('administrativeArea'))) {
		select_selecto(sel, adr.administrativeAreaId, false);
	}

	if(adr.streetName2Id && (sel = geregx('streetName'))) {
		select_selecto(sel, adr.streetName2Id, false);
	}
	
	if(adr.pscId && (sel = geregx('psc'))) {
		select_selecto(sel, adr.pscId, false);
	}

	if(geregx('addressPoint'))
		updateAddressPoints();
	
	if(adr.addressPointId && (sel = geregx('addressPoint'))) {
		select_selecto(sel, adr.addressPointId, false);
	}
	
	if(adr.streetName && (sel = geregx('street'))) {
		set_valueo(sel, adr.streetName);
	}

	if(adr.houseNumber && (sel = geregx('houseNumber'))) {
		set_valueo(sel, adr.houseNumber);
	}

	if(adr.zipCode && (sel = geregx('zipCode'))) {
		set_valueo(sel, adr.zipCode);
	}
	
	if(adr.lat && (sel = geregx('latitude', 'cz.c2d.siva.data.GeoLocation'))) {
		set_valueo(sel, adr.lat);
	}

	if(adr.lon && (sel = geregx('longitude', 'cz.c2d.siva.data.GeoLocation'))) {
		set_valueo(sel, adr.lon);
	}
}

function ap2_onmouseover(e) {
	var dv4 = gt(e);
	if(dv4.className != 'gm2dv4-sel')
		dv4.className = 'gm2dv4-on';
}

function ap2_onmouseout(e) {
	var dv4 = gt(e);
	if(dv4.className != 'gm2dv4-sel')
		dv4.className = 'gm2dv4-off';
}

function address_picker2_clicked_inside(p) {
	var dvid = address_picker2_id  + '_div';
	for(var i = 0; i < 10; i++) {
		if(!p || p.nodeType != 1)
			return false;
		if(p.id && p.id == dvid)
			return true;
		p = p.parentNode;
	}
	return false;
}

function address_picker2_close_cancel(e) {
	if(!e) var e = window.event;
	var src = e.target ? e.target : e.srcElement;
	if(address_picker2_clicked_inside(src))
		return;
	var dv = ge(address_picker2_id  + '_div');
	dv.style.display = 'none';
	unlisten(document, 'mousedown', address_picker2_close_cancel);
	//destroy the map
	//clean the addresses
	address_picker2_clean_addresses();
	address_picker2_id = null;
}

function address_picker2_ed_onfocus(ed) {
	if(ed.value == ed.getAttribute('help-text')) {
		ed.value = '';
	}
	else {
		address_picker2(ed);
	}
}

function address_picker2_ed_onblur(ed) {
	if(ed.value == '') {
		ed.value = ed.getAttribute('help-text');
	};
}

function shortlist_unit_action(unit_id, client_id) {
	var form = ge('form');
	var url = '/properties/units/process?id=' + unit_id + '&client-id=' + client_id + '&x-pc-code=4j8jc8eloi3d';
	form.action = url;
	form.post_control.value = 'unit-process';
	form.poster_control.value = 'unit-process_view_select';
	form.poster_value.value = 'send-to-customers';
	form.submit();
}

function shortlist_opp_action(opp_id, client_id) {
	var form = ge('form');
	var url = '/deals-app/process?id=' + opp_id + '&client-id=' + client_id + '&x-pc-code=4j8jc8eloixx';
	form.action = url;
	form.post_control.value = 'opportunity-process';
	form.poster_control.value = 'opportunity-process_view_select';
	form.poster_value.value = 'newstate9';
	form.submit();
}

var opened_cola;

function cola_flip(e) {
	var co = gt(e);
	cola_flipo(co);
}

function cola_flipo(co) {
	co.blur();
	var tid = ga(co, 'tid');
	var tab = ge(tid + '_cola');
	if(co.className == 'cola_off') {
		co.className = 'cola_on';
		tab.className = 'cola_on';
		opened_cola = tid;
		listen(document, 'mousedown', cola_cancel);
	}
	else {
		co.className = 'cola_off';
		tab.className = 'cola_off';
		cola_title(tid);
		var hid = gens(opened_cola + '_hidden');
		opened_cola = null;
		unlisten(document, 'mousedown', cola_cancel);
		if(hid != null)
			on_changeo(hid);
	}
}

function cola_cancel(e) {
	if(!e) var e = window.event;
	var src = e.target ? e.target : e.srcElement;
	if(cola_clicked_inside(src))
		return;
	cola_flipo(ge(opened_cola + '_colaa'));
}

function cola_clicked_inside(p) {
	var pl = opened_cola + '_cola';
	var pla = opened_cola + '_colaa';
	for(var i = 0; i < 10; i++) {
		if(!p)
			return false;
		if(p.id && (p.id == pl || p.id == pla))
			return true;
		p = p.parentNode;
	}
	return false;
}

function cola_title(id) {
	var a = ge(id + '_colaa');
	var tab = ge(id + '_cola_tb');
	var sb = '';
	var tc;
	
	if(tab.rows.length == 1 && (tc = tab.rows.item(0).cells.item(0)).className && tc.className == 'multi-dyna-cola') {
		var ie = new IterableElements(tc);
		while(ie.hasNext()) {
			var t = ie.next();
			if(t.tagName == 'TABLE') {
				var bid = ga(t, 'base-id');
				if(!bid)
					continue;
				var chid = ga(t, 'value') + '_' + bid;
				var ch = ge(chid);
				var lb = ge(chid + '_lb');
				if(ch.checked) {
					if(sb.length > 0)
						sb += ', ';
					sb += lb.firstChild.nodeValue;
				}
			}
			else if(t.tagName == 'DIV') {
				if(sb.length > 0)
					sb += ', ';
				sb += t.firstChild.nodeValue;
			}
		}
	}
	else {
		for(var i = 0; i < tab.rows.length; i++) {
			var row = tab.rows.item(i);
			var td1 = row.cells.item(0);
			var cnn = row.cells.item(0).childNodes;
			var chk = cnn.item(0).tagName == 'INPUT' ? cnn.item(0) : cnn.item(1);
			var cnx = row.cells.item(1).childNodes;
			var lab = cnx.item(0).tagName == 'LABEL' ? cnx.item(0) : cnx.item(1);
			var txt = lab.firstChild.nodeValue;
			if(chk.checked) {
				if(sb.length > 0)
					sb += ', ';
				sb += txt;
			}
		}
	}
	a.firstChild.nodeValue = sb.length < 1 ? '...' : sb;
}

function cola2_flip(e) {
	var co = gt(e);
	co.blur();
	var tid = ga(co, 'tid');
	var tab = ge(tid + '_cola2');
	if(co.className == 'cola2_off') {
		co.className = 'cola2_on';
		tab.className = 'cola2_on';
	}
	else {
		co.className = 'cola2_off';
		tab.className = 'cola2_off';
	}
}

function cntx_menu_over(xid, mid, state) {
	var gxid = ge(xid);
	var gxidimg = ge('{@xid}-img');
	var gxida = ge('{@xid}-a');
	if(!gxid || !gxidimg || !gxida)
		return;
	gxidimg.src = ga(gxid, 'url') + 'on.jpg';
	gxida.className = 'context{$mid}-menu-a-on';
}

function cntx_menu_out(xid, mid, state) {
	var gxid = ge(xid);
	var gxidimg = ge('{@xid}-img');
	var gxida = ge('{@xid}-a');
	if(!gxid || !gxidimg || !gxida)
		return;
	gxidimg.src = ga(gxid, 'url') + state + '.jpg';
	gxida.className = 'context{$mid}-menu-a-' + state;
}

function biggal(e) {
	var bgm = gt(e);
	var tg = ge(ga(bgm, 'tid'));
	var pic = ga(bgm, 'pic');
	tg.src = pic;
}

function googlemap_init(id, latitude, longitude, zoomLevelString) {
	var m = ge(id);
	if(m && 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(m);
		map.setCenter(point, Number(zoomLevelString));
		map.addOverlay(marker);
		map.disableDragging();
		map.disableDoubleClickZoom();
	}
}

var qkr_query = null;
var qkr_running = false;
var qkr_wait = 1000;

function qkr_oc(q) {
	var qv = trim(q.value);
	if(qkr_query != qv) {
		qkr_query = qv;
		if(!qkr_running) {
			qkr_running = true;
			setTimeout('qkr_loop()', 1);
		}
	}
}

function qkr_loop() {
	var q = qkr_query;
	qkr_work(q);
	if(qkr_query != q)
		setTimeout('qkr_loop()', qkr_wait);
	else
		qkr_running = false;
}

function qkr_of(q) {
	if(q.value == ga(q, 'help-text'))
		q.value='';
}

function qkr_ob(q) {
	if(q.value == '')
		q.value = ga(q, 'help-text');
}

function qkr_work(q) {
	var ret = get_json().QuickSearchServer.quickSearch(q);
	var d = ge('lfqs3-div');
	purgeChildren(d);
	var unit_cnt = 0, user_cnt = 0;

	//display
	for(var i = 0; i < ret.length; i++) {
		var e = ret[i];
		if(e.javaClass == 'cz.c2d.asprecruiter.json.QuickSearchServer$header') {
			ac(d, t('div', { $class: 'lfqs3u-header', $text: e.name }));
		}
		else if(e.javaClass == 'cz.c2d.asprecruiter.json.QuickSearchServer$unit') {
			unit_cnt++;
			ac(d, 
				t('div', { $class: 'lfqs3u-entry' + (unit_cnt % 2 == 0 ? ' lfqs3u-even' : '') },
					t('div', { $class: 'lfqs3u-pic' },
						t('a', { href: e.url, $class: 'lfqs3u-pic' }, 
							t('img', { $class: 'lfqs3u-pic', src: e.picUrl })
						)
					),
					t('div', { $class: 'lfqs3u-content' },
						t('a', { href: e.url, $class: 'lfqs3u-title', $text: e.title }),
						t('a', { href: e.url, $class: 'lfqs3u-info', $text: e.info }),
						t('a', { href: e.url, $class: 'lfqs3u-info2' },
							t('a', { href: e.url, $class: 'lfqs3u-saleType', $text: e.saleType }),
							t('span', { $class: 'lfqs3u-sep', $text: '|' }),
							t('a', { href: e.url, $class: 'lfqs3u-price', $text: e.price }),
							t('span', { $class: 'lfqs3u-sep', $text: '|' }),
							t('a', { href: e.url, $class: 'lfqs3u-status', $text: e.status, style: { color: e.status_color } })
						)
					)
				)
			);
		}
		else if(e.javaClass == 'cz.c2d.asprecruiter.json.QuickSearchServer$user') {
			ac(d, 
				t('div', { $class: 'lfqs3u-entry' },
					t('div', { $class: 'lfqs3u-pic' },
						t('a', { href: e.url, $class: 'lfqs3u-pic' }, 
							t('img', { $class: 'lfqs3u-pic', src: e.picUrl })
						)
					),
					t('div', { $class: 'lfqs3u-content' },
						t('a', { href: e.url, $class: 'lfqs3u-title', $text: e.name }),
						t('a', { href: e.url, $class: 'lfqs3u-info', $text: e.phone }),
						t('a', { href: e.url, $class: 'lfqs3u-info', $text: e.email }),
						t('a', { href: e.url, $class: 'lfqs3u-info2' },
							t('a', { href: e.url, $class: 'lfqs3u-status2', $text: e.status, style: { color:  e.status_color } }),
							t('span', { $class: 'lfqs3u-sep', $text: '|' }),
							t('a', { href: e.url, $class: 'lfqs3u-lastContact', $text: e.lastContact, style: { color: e.contact_color } })
						)
					)
				)
			);
		}
		else if(e.javaClass == 'cz.c2d.asprecruiter.json.QuickSearchServer$footer') {
			ac(d, t('div', { $class: 'lfqs3u-footer', $text: e.text }));
		}
	}

	if(!d.style.display || d.style.display == 'none') {
		listen(document, 'mousedown', qkr_cancel);
		d.style.display = 'block';
	}
}

function qkr_cancel(e) {
	if(!e) var e = window.event;
	var src = e.target ? e.target : e.srcElement;
	if(qkr_clicked_inside(src))
		return;
	
	var d = ge('lfqs3-div');
	d.style.display = 'none';
	purgeChildren(d);
	unlisten(document, 'mousedown', qkr_cancel);
}

function qkr_clicked_inside(p) {
	var d = ge('lfqs3-div');
	for(var i = 0; i < 10; i++) {
		if(!p)
			return false;
		if(p == d)
			return true;
		p = p.parentNode;
	}
	return false;
}

function get_link_url(th) {
	window.location = th.getAttribute('url');
}

function ivf_stars_clicked(e) {
	var t = gt(e);
	if(t.tagName != 'TD')
		return;
	var id = ga(t, 'xid');
	var sid = ga(t, 'val');
	var hd = ge(id);
	if(!hd)
		return;
	var on = t.className == 'off';
	var e = on ? 0 : 6;
	var s = on ? -1 : 1;
	for(var i = Number(sid); i != e; i += s) {
		var st = ge('ivf-stars-' + id + '-' + i);
		if(st.className == on ? 'off' : 'on')
			st.className = on ? 'on' : 'off';
		else
			break;
	}
	var v = ivf_stars_value(id);
	hd.value = v;
}

function ivf_stars_value(id) {
	for(var i = 5; i > 0; i--)
		if(ge('ivf-stars-' + id + '-' + i).className == 'on')
			return i;
	return 0;
}

function ivs_stars_set(id, val) {
	for(var i = 1; i < 6; i++) {
		ge('ivf-stars-' + id + '-' + i).className = (i <= val ? 'on' : 'off');
	}
}

function dsr_get_calendar_field_millis(f) {
	if(!f || !f.value || f.value == '')
		return 0;
	try {
		return Date.parseDate(f.value, '%d-%b-%Y').getTime();
	}
	catch(e) {
		return 0;
	}
}

function dsr_refilter() {
	var d = { javaClass: 'cz.c2d.asprecruiter.json.AjaxReportServer$dsr_in' };
	d.project = get_multiselecto_dynacheck(ge('dsr_project'));
	d.layout = get_multiselecto_dynacheck(ge('dsr_layout'));
	d.status = get_multiselecto_dynacheck(ge('dsr_status'));
	d.dateStart = dsr_get_calendar_field_millis(ge('dsr_start'));
	var xc = 'lbl2';
	d.dateEnd = dsr_get_calendar_field_millis(ge('dsr_end'));
	var r = get_json().AjaxReportServer.developerSalesReport(d);

	var t = tab({ $class: 'dsr_box' },
	[
		[
			'', '', '', [ 'bhead', r.sales_statistics ]
		],
		[
			[ 'bhead', r.project_name ],
			[ 'bhead', r.building_name ],
			[ 'bhead', r.unit_id ],
			[ 'bhead2', r.layout ],
			[ 'bhead2', r.inquiries ],
			[ 'bhead2', r.viewings ],
			[ 'bhead2', r.reservations ],
			[ 'bhead2', r.status ],
			[ 'bhead2', r.asking_price ],
			[ 'bhead2', r.sold_price ],
			[ 'bhead2', r.variance ],
			[ 'bhead2', r.time_to_sell ]
		]
	]);
	
	t.rows.item(0).cells.item(3).colSpan = 9;
	
	for(var iprj in r.projects.list) {
		var prj = r.projects.list[iprj];
		var row = t.insertRow(t.rows.length);
		var prj_cell = row.insertCell(row.cells.length);
		var prj_rowspan = 1;
		prj_cell.className = xc;
		ac(prj_cell, a(prj.project_name, '/properties/dev-developments/process?id=' + prj.id));
		
		for(var ibld in prj.buildings.list) {
			var bld = prj.buildings.list[ibld];
			var bld_rowspan = 1;
			if(ibld > 0) {
				prj_rowspan++;
				row = t.insertRow(t.rows.length);
			}
			var bld_cell = row.insertCell(row.cells.length);
			bld_cell.className = xc;
			ac(bld_cell, txt(bld.building_name));
			
			for(var iunt in bld.units.list) {
				var unt = bld.units.list[iunt];
				if(iunt > 0) {
					bld_rowspan++;
					prj_rowspan++;
					row = t.insertRow(t.rows.length);
				}
				var uurl = '/properties/units/process?id=' + unt.id;
				var bc = unt.status_id == 3 ? 'dsr-sold' : unt.status_id == 2 ? 'dsr-reserved' : 'dsr-available';
				ac(className(row.insertCell(row.cells.length), xc), a(unt.unit_id, uurl));

				ac(className(row.insertCell(row.cells.length), bc), a(unt.layout, uurl));
				ac(className(row.insertCell(row.cells.length), bc), a(unt.inquiries, uurl));
				ac(className(row.insertCell(row.cells.length), bc), a(unt.viewings, uurl));
				ac(className(row.insertCell(row.cells.length), bc), a(unt.reservations, uurl));
				ac(className(row.insertCell(row.cells.length), bc), a(unt.status, uurl));
				ac(className(row.insertCell(row.cells.length), bc), a(unt.asking_price, uurl));
				ac(className(row.insertCell(row.cells.length), bc), a(unt.sold_price, uurl));
				ac(className(row.insertCell(row.cells.length), bc), a(unt.variance, uurl));
				ac(className(row.insertCell(row.cells.length), bc), a(unt.time_to_sell, uurl));
			}
			if(bld_rowspan > 1)
				bld_cell.rowSpan = bld_rowspan;
			
		}
		if(prj_rowspan > 1)
			prj_cell.rowSpan = prj_rowspan;
	}
	
	row = t.insertRow(t.rows.length);
	row.className = 'dsr_seprow';
	ac(className(row.insertCell(row.cells.length), 'dsr_seprow'), txt(''));
	
	row = t.insertRow(t.rows.length);
	row.insertCell(row.cells.length);
	row.className = 'dsr_totals';
	row.insertCell(row.cells.length);
	row.insertCell(row.cells.length);
	ac(row.insertCell(row.cells.length), txt(r.totals));
	ac(row.insertCell(row.cells.length), txt(r.total_inquiries));
	ac(row.insertCell(row.cells.length), txt(r.total_viewings));
	ac(row.insertCell(row.cells.length), txt(r.total_reservations));
	row.insertCell(row.cells.length);
	row.insertCell(row.cells.length);
	row.insertCell(row.cells.length);
	row.insertCell(row.cells.length);
	row.insertCell(row.cells.length);

	var box = ge('dsr_box');
	purgeChildren(box);
	ac(box, t);
	
	ac(box, a(r.download_full_report, '/iflowcrm/BB_cenik_311008-1-downloaded.xls', 'dsr_download'));
}

function updateAddressPoints() {
	var ret = get_json().ProjectServer.get_address_points(
		processName, 
		get_selecto(geregx('suburb')), 
		get_selecto(geregx('psc')),
		get_selecto(geregx('streetName')),
		get_url_param('id'));
	set_selecto(geregx('addressPoint'), ret, 0, 1, null, true);
}
