var active_element = '';
var filled_elements = 0;
var invalid_elements = 0;
var valid_points = 0;
var invalid_points = 0;
var requirements = new Object;
var query_string = new Array();
var windows = new Object;

var scroll_objects = new Array();
var scroll_top = new Array();
var scroll_old = new Array();
var scroll_window = new Array();
var scroll_document = new Array();

var default_state = new Object();

function cancel_event(e) {
	return false;
}

function get_target(e, curr_window) {
	var targ = null;
	if (!curr_window) curr_window = window;
	if (!e) var e = curr_window.event;
	if (e) {
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;
	//	if (targ.nodeType == 3) // defeat Safari bug
	//		targ = targ.parentNode;
	}
	return targ;
}

var scroll_object = null;

window.onload = onload_main_page;
function onload_main_page(e) {
	var curr_window = this;
	var curr_document = get_target(e, curr_window);
	if (!curr_document) curr_document = curr_window.document;
	if (curr_document.forms[0]) curr_document.forms[0].onsubmit = cancel_event;
	scroll_object = null;
	if (curr_window.onload_page != null);
	eval('if (curr_window.onload_'+curr_app+'__'+curr_script+' != null) { curr_window.onload_'+curr_app+'__'+curr_script+'(); }');
	if (scroll_object) {
		scroll_top[scroll_top.length] = 0;
		scroll_old[scroll_old.length] = 0;
		scroll_window[scroll_window.length] = curr_window;
		scroll_document[scroll_document.length] = curr_document;
		scroll_object.style.position = 'absolute';
		scroll_objects[scroll_objects.length] = scroll_object;
	}

	var modules = curr_document.getElementsByName('modules[]');
	for(var i = 0; i < modules.length; i++) {
//		alert('curr_window.onload_'+modules[i].value);
		eval('if (curr_window.onload_'+modules[i].value+' != null) { curr_window.onload_'+modules[i].value+'(); }');
		//scroll_object = my_getDivById('div___'+modules[i].value);
		if (scroll_object) {
			scroll_top[scroll_top.length] = 0;
			scroll_old[scroll_old.length] = 0;
			scroll_window[scroll_window.length] = curr_window;
			scroll_document[scroll_document.length] = curr_document;
			scroll_object.style.position = 'absolute';
			scroll_objects[scroll_objects.length] = scroll_object;
		}
	}
	if (curr_document.forms[0]) {
		for(var i = 0; i < curr_document.forms[0].elements.length; i++) {
//			külön fgv-be kell tenni a set_element_flag-es hívásokat és azokat kell csak meghívni itt
//			if (curr_document.forms[0].elements[i].onchange) curr_document.forms[0].elements[i].onchange();
		}
	}
	if (curr_document && curr_document.forms[0] && curr_document.forms[0].autofocus) {
		//var old_focus=null; var old_obj=get_element(focus);
		//if (old_obj.onfocus) { old_focus=old_obj.onfocus; old_obj.onfocus=null; }
		//var focus = get_element_value('autofocus');
		//set_element_focus(focus, '', (focus == ''));
		//if (old_focus) old_obj.onfocus=old_focus;
	}
	if (scroll_objects.length > 0) onscroll_object();
}

window.onresize = onresize_main_page;
function onresize_main_page(e) {
	var modules = document.getElementsByName('modules[]');
	for(var i = 0; i < modules.length; i++) {
		eval('if (window.onresize_'+modules[i].value+' != null) onresize_'+modules[i].value+'();');
	}
}

function onscroll_object() {
	for (var i=0; i<scroll_objects.length; i++) {
		if (!scroll_window[i].closed) {
			if (scroll_window[i].innerHeight)	{
				pos = scroll_window[i].pageYOffset;
			}
			else if (scroll_document[i].documentElement && scroll_document[i].documentElement.scrollTop) {
				pos = scroll_document[i].documentElement.scrollTop;
			}
			else if (scroll_document[i].body) {
				pos = scroll_document[i].body.scrollTop;
			}
			if (pos < scroll_top[i]) pos = scroll_top[i];
			if (pos == scroll_old[i]) {
				scroll_objects[i].style.top = pos;
			}
		}
		scroll_old[i] = pos;
	}
	temp = setTimeout('onscroll_object()', 500);
}

function reload_main_page(params) {
	return onsubmit_main_page('', '', params);
}

function parse_url(url, query_elements) {
	var url_parts = url.split('?');
	if (url_parts.length == 1) {
		url_parts[1] = '';
	}
	if (query_elements !== true) {
		for(var i = 0; i < query_elements.length; i++) {
			var items = query_elements[i].split('=');
			var flag = items[0].substr(0, 1);
			if ((flag == '-') || (flag == '+') || (flag == 'X')) {
				items[0] = items[0].substr(1);
			}
			else {
				flag = '';
				url_parts[1] = '';
			}
			if (flag == 'X') {
				flag = '-';
				items[0] += '[^=]*';
			}
			url_parts[1] = url_parts[1].replace(new RegExp('(^|&)'+items[0]+'=[^&]*(?:&|)'), '$1');
			url_parts[1] = url_parts[1].replace(/&+$/, '');
			if ((items[1] != null) && (flag != '-')) {
				url_parts[1] = url_parts[1]+'&'+items[0]+'='+items[1];
			}
			url_parts[1] = url_parts[1].replace(/^&+/, '');
		}
	}
	return url_parts[0]+(((url_parts.length == 1) || (url_parts[1] == '')) ? '' : '?'+url_parts[1]);
}

var iCallbackTimer = null;

var popup_handle = null;
var popup_orig_module = null;
var popup_orig_action_id = null;
var popup_orig_params = null;
var popup_title = '';
var orig_action = null;

var form_submitted = false;
var form_action_in_progress = false;
function onsubmit_main_page(module, action_id, params, callback, curr_window, https) {
	if (form_submitted || form_action_in_progress) return;
	
	for(var element_name in default_state) {
		if (default_state[element_name] === true) {
			set_element_value(element_name, '');
		}
	}

	form_action_in_progress = true;
	if (!curr_window) curr_window = window;
	curr_document = curr_window.document;
	filled_elements = 0;
	invalid_elements = 0;
	if (callback) {
		popup_orig_module = null;
		popup_orig_action_id = null;
		popup_orig_params = null;
	}
	if (action_id != 'refresh') {
		curr_window.clearInterval(iCallbackTimer);
	}
	var valid = true;
	var orig_module = module;
	var tmp_arr = module.split('___');
	module = tmp_arr[1];
	if (module == '') {
		var tmp = params;
	}
	else {
		toggle_item('block', 'common__error', 'none', false, curr_document);
		if (flag_niceforms && flag_niceforms_needupdate) NFFix();
		function_name = module;
		if (action_id != '') {
			function_name += '_'+action_id;
		}
		eval('if (curr_window.onvalidate_'+function_name+' != null) { var validating = curr_window.onvalidate_'+function_name+'(params); }');
		if (validating) {
			valid_points = 0;
			invalid_points = 0;
			var curr_group_point = 0;
			var is_group_empty = true;
			var ids = '';
			re = /^(.*)___(.*)$/;
			for(var i = 0; i < validating.length; i++) {
				element_arr = re.exec(validating[i]);
				var module_name = '';
				if (element_arr) {
					module_name = element_arr[1];
				}
				var has_validation = false;
				var id = '';
				eval('if (curr_window.validate_'+validating[i]+' != null) { has_validation = true; id = curr_window.validate_'+validating[i]+'(\''+validating[i]+'\', \''+module_name+'\'); }');
				if (has_validation) {
					valid = valid && (id == '');
					if (id != '') {
						ids += '|'+validating[i]+'#'+id;
					}

					var value = get_element_value(validating[i], null, null, curr_document);
					var curr_empty = ((value == '') || (value == null));

					var curr_point = get_element_info('point', validating[i], '');
					if ((curr_point > 0) && (i > 0)) {
						if (is_group_empty) {
							invalid_points += curr_group_point;
						}
						else {
							valid_points += curr_group_point;
						}
						curr_group_point = 0;
						is_group_empty = true;
					}
				}
				curr_group_point += curr_point;
				is_group_empty = curr_empty && is_group_empty;
			}
			if (is_group_empty) {
				invalid_points += curr_group_point;
			}
			else {
				valid_points += curr_group_point;
			}
			ids = ids.substr(1);
			if (ids != '') {
				var errors = ids.split('|');
				for(var i = 0; i < 1; i++) {
					var elements = errors[i].split('#');
					alert(get_element_info('lang', elements[0], elements[1]));
					set_element_focus(elements[0]);
				}
			}
			else {
				var req_valid = true;
				for(var element_name in requirements) {
					if (requirements[element_name].length > 0) req_valid = false;
					for(var c=0; c < requirements[element_name].length; c++) {
						if (requirements[element_name][c]['at_least']){
							var ok = 0;
							for(var i = 0; i < requirements[element_name][c]['of'].length; i++) {
								var value = get_element_value(requirements[element_name][c]['of'][i]);
								if ((value != null) && (value != '')) ok++;
							}
							if (ok >= requirements[element_name][c]['at_least']) {
								req_valid = true;
							}
						}
					}
					if (!req_valid) {
						valid = false;
						invalid_elements++;
						alert(get_element_info('lang', element_name, 'requirement'));
						set_element_focus(element_name);
						break;
					}
				}
			}
		}
		eval('if (curr_window.onsubmit_'+function_name+' != null) { var tmp = curr_window.onsubmit_'+function_name+'(params, valid); }');
	}
	var popup_params = false;
	if (valid) {
		if (tmp == '') {
			form_action_in_progress = false; return false;
		}
		windows_str = '';
		for(var i in windows) {
			if (windows[i] && !windows[i].closed) {
				windows_str = windows_str + "\n- " + (windows[i].document.title ? windows[i].document.title : '[no name]');
			}
		}
		if (onsubmit_popup_windows != 'leave') {
			form_submitted = (windows_str && (onsubmit_popup_windows == 'ask')) ? confirm('The following windows are still open:' + windows_str + "\nAre you sure to close them before continuing?") : true;
			if (!form_submitted) {
				form_action_in_progress = false; return false;
			}
			for(var i in windows) {
				if (windows[i]) {
					windows[i].close();
				}
			}
		}
		if (tmp) {
			if (tmp[0] && tmp[0].substr(0, 1) == '*') {
				popup_params = tmp.shift();
				if (popup_params.substr(1, 1) == ':') {
					popup_title = popup_params.substr(2);
					popup_params = 'scrollbars=no';
				}
				else {
					popup_params = popup_params.substr(1);
					popup_params += (popup_params ? ',' : '')+'scrollbars=yes';
				}
				popup_params += (popup_params ? ',' : '')+'menubar=no,resizable=yes,dependent=yes';
				popup_orig_module = module;
				popup_orig_action_id = action_id;
				popup_orig_params = params;
			}
			if (query_string.length > 0) {
				tmp = tmp.concat(query_string);
				query_string.length = 0;
			}
			orig_action = curr_document.forms[0].action;
			curr_document.forms[0].action = parse_url(curr_document.forms[0].action, tmp);
		}
	}
	if (!valid) {
		form_action_in_progress = false; return false;
	}
	if (https != null) curr_document.forms[0].action = _url_2_https(curr_document.forms[0].action, https, true);
	if (module == '') {
		if (popup_params === false) {
			curr_window.location.href = curr_document.forms[0].action;
		}
		else {
			popup_handle = curr_window.open(curr_document.forms[0].action, curr_app+'_'+function_name, popup_params);
			if (popup_title) {
				popup_handle.document.title = popup_title;
			}
			popup_handle.focus();
		}
	}
	else {
		curr_document.forms[0].submitter_module.value = orig_module;
		curr_document.forms[0].submitter_action_id.value = action_id;
		if (popup_params !== false) {
			popup_handle = curr_window.open('', curr_app+'_'+function_name, popup_params);
			if (popup_title) {
				popup_doc = popup_handle.document.open("text/html", "replace");
				popup_doc.write('<body marginwidth=\'0\' marginheight=\'0\' topmargin=\'0\' bottommargin=\'0\' leftmargin=\'0\' rightmargin=\'0\'><iframe name="' + curr_app+'_'+function_name + '_" height="100%" width="100%" border="0" frameborder="0"></iframe></body>');
				popup_doc.close();
				popup_handle.document.title = popup_title;
				curr_document.forms[0].target = popup_handle.frames[0].name;
			}
			else {
				curr_document.forms[0].target = curr_app+'_'+function_name;
			}
		}
		submit_curr_window = curr_window;
		submit_curr_document = curr_document;
		iCallbackTimer = curr_window.setInterval(submit, 200);
	}
	popup_title = '';
	return true;
}

function _url_2_https(url, https, submit) {
	if (https) {
		if (url.indexOf('https://') == 0) return url;
		if ((url.indexOf('http://') == 0) && !submit) return url;
		if ((url.indexOf('./') == 0) || (url.indexOf('/') == 0) || submit) {
			if (url.indexOf('/') == 0) {
				url = 'https://' + https_server + url;
			}
			else {
				var pos = url.indexOf('?');
				url = (pos >= 0) ? url.substr(pos) : '';
				url = 'https://' + https_server + curr_script_path + url;
			}
		}
		return url;
	}
	else {
		if (url.indexOf('http://') == 0) return url;
		if ((url.indexOf('https://') == 0) && !submit) return url;
		if ((url.indexOf('./') == 0) || (url.indexOf('/') == 0) || submit) {
			if (url.indexOf('/') == 0) {
				url = 'https://' + https_server + url;
			}
			else {
				var pos = url.indexOf('?');
				url = (pos >= 0) ? url.substr(pos) : '';
				url = 'http://' + http_server + curr_script_path + url;
			}
		}
		return url;
	}
}

function open_popup(url, name, https, open_mode) {
	var handle = null;
	var toolbar = null;
	if (open_mode === true) {
		toolbar = 'toolbar=0,scrollbars=yes';
	}
	else if (open_mode) {
		toolbar = open_mode;
	}
	if ((name != window.name) && windows[name] && !windows[name].closed) {
		 handle = windows[name];
		 if (open_mode == null) {
			alert('Window is already opened! Tab based browsers cannot set the focus to the requested window so you need to find it manually.');
		 }
	}
	else {
		// temporary solution of an illegal &reg... conversion in query string
		if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
			url = url.replace(/&/g, '&amp;');
		}
		if (https != null) url = _url_2_https(url, https);
		if (name == window.name) window.name = '';
		if (toolbar) {
			handle = window.open(url, name, toolbar);
		}
		else {
			handle = window.open(url, name);
		}
		if (name != '_blank') {
			windows[name] = handle;
		}
	}
	if (handle == null) {
		alert('Popup windows are blocked by the browser, please change the settings!');
	}
	else {
		handle.focus();
	}
	return handle;
}

function open_link(url, name, https) {
	var reg = /\.html?(&.*|)$/;
	if (reg.test(url)) {
		if (!name) name = '_blank';
		return open_popup(url, name, https);
	}
	else {
		// temporary solution of an illegal &reg... conversion in query string
		if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
			url = url.replace(/&/g, '&amp;');
		}
		if (https != null) url = _url_2_https(url, https);
		top.location.href = url;
	}
}

var submit_curr_window = null;
var submit_curr_document = null;
function submit() {
	submit_curr_window.clearInterval(iCallbackTimer);
	submit_curr_document.forms[0].submit();
	if (orig_action != null) submit_curr_document.forms[0].action = orig_action;
	if (popup_handle) {
		if (popup_handle.closed) {
			popup_orig_module = null;
			popup_orig_action_id = null;
			popup_orig_params = null;
		}
		else {
			popup_handle.focus();
		}
	}
	submit_curr_document.forms[0].target = '_self';
	if (popup_orig_module != null) {
		if (eval('submit_curr_window.onsubmit_'+function_name+'_done') != null) {
			submit_curr_window.onsubmit_main_page(popup_orig_module, popup_orig_action_id+'_done', popup_orig_params, true);
			if (popup_handle.closed) {
				popup_orig_module = null;
				popup_orig_action_id = null;
				popup_orig_params = null;
			}
			else {
				popup_handle.focus();
			}
		}
	}
}

function get_keycode(e) {
	if (e.keyCode) {
		kc = e.keyCode;
		shift = e.shiftKey;
		ctrl = e.ctrlKey;
		alt = e.altKey;
	}
	else {
		kc = e.which;
		if (e.modifiers) {
			shift = ((e.modifiers & Event.SHIFT_MASK) != 0);
			ctrl = ((e.modifiers & Event.CONTROL_MASK) != 0);
			alt = ((e.modifiers & Event.ALT_MASK) != 0);
		}
		else {
			shift = e.shiftKey;
			ctrl = e.ctrlKey;
			alt = e.altKey;
		}
	}
	return [kc, shift, ctrl, alt];
}

function __get_element(name, curr_document) {
	if (!curr_document) curr_document = document;
	var obj = curr_document.forms[0].elements[name];
	if (!obj) obj = my_getElementById(name, curr_document);
	return obj;
}

function _get_element(name, curr_document) {
	var obj = __get_element(name+'[]');
	if (!obj) obj = __get_element(name);
	return obj;
}

function get_element(name, curr_document) {
	var obj = _get_element(name);
	if (!obj) {
		var tmp;
		obj = new Array();
		tmp_obj = _get_element(name+'_HH'); if (tmp_obj) obj.push(tmp_obj);
		tmp_obj = _get_element(name+'_MI'); if (tmp_obj) obj.push(tmp_obj);
		tmp_obj = _get_element(name+'_SS'); if (tmp_obj) obj.push(tmp_obj);
	}
	return obj;
}

function process_element_value(flags, value) {
	if ((flags.indexOf('EMPTYISNULL') >= 0) && (value == '')) value = null;
	return value;
}

function get_element_value(element_name, func_code, array_as_obj, curr_document) {
	var element = get_element(element_name, curr_document);
	var value = null;
	if (element) {
		var is_default_element = (element_name.substr(element_name.length-8) == '_default');
		var is_null_element = (element_name.substr(element_name.length-5) == '_null');
		var null_value = is_null_element ? false : get_element_value(element_name+'_null');
		if (!null_value || (null_value != '1')) {
			var type = get_element_type(element);
			flags = ((type != 'hidden') && !is_null_element && !is_default_element) ? get_element_info('flags', element_name, '') : '';
			switch (type) {
				case 'file':
					value = process_element_value(flags, trim(element.value));
					break;	
				case 'text':
				case 'password':
				case 'hidden':
				case 'textarea':
					value = process_element_value(flags, trim(element.value));
					break;	
				case 'checkbox':
					if (element.length && (element.length > 0))	{
						value = new Array();
						for(var i = 0; i < element.length; i++) {
							if (element[i].checked)	{
								value[value.length] = process_element_value(flags, element[i].value);
							}
						}
						if (value.length == 0) value = null;
					}
					else {
						if (element.checked) {
							value = process_element_value(flags, element.value);
						}
					}
					if (value == null) {
						value = get_element_value(element_name+'_default');
					}
					break;
				case 'radio':
					if (element.length && (element.length > 0))	{
						for(var i = 0; i < element.length; i++) {
							if (element[i].checked)	{
								value = process_element_value(flags, element[i].value);
								break;
							}
						}
					}
					else {
						if (element.checked) {
							value = process_element_value(flags, element.value);
						}
					}
					if (value == null) {
						value = get_element_value(element_name+'_default');
					}
					break;
				case 'select':
					value = process_element_value(flags, element.options[element.selectedIndex].value);
					break;
			}
		}
	}
	if (array_as_obj) {
		var o = {};
		if (value) {
			if (value.length && (value.length > 0)) {
				for (var i = 0; i < value.length; i++) o[value[i]] = '';
			}
			else {
				o[value] = '';
			}
		}
		value = o;
	}
	if (func_code == 'l') value = value ? value.length : 0; 
	return value;
}

// mode = 1 : clear
//        2 : invert
function set_element_value(element_name, value, clear, invert) {
	var element = get_element(element_name);
	if (!element) return;
	var type = get_element_type(element);
	switch (type) {
		case 'file':
		case 'text':
		case 'password':
		case 'hidden':
		case 'textarea':
			if (element.length > 0) {
				element = element[0];
			}
			element.value = (value == null) ? '' : value;
			if (type == 'file') {
				if (flag_niceforms) NFFix();
			}
			break;
		case 'radio':
			if (element.length && (element.length > 0))	{
				for(var i = 0; i < element.length; i++) {
					if (value == element[i].value) {
						element[i].checked = true;
						break;
					}
				}
			}
			else {
				if (value == element.value) {
					element.checked = true;
				}
			}
			break;
		case 'checkbox':
			if (element.length && (element.length > 0))	{
				for(var i = 0; i < element.length; i++) {
					state = (value == element[i].value);
					b_val = state;
					if (invert) state = !state;
					if (clear) b_val = state ? false : element[i].checked;
					element[i].checked = b_val;
				}
			}
			else {
				state = (value == element.value);
				b_val = state;
				if (invert) state = !state;
				if (clear) b_val = state ? false : element.checked;
				element.checked = b_val;
			}
			break;
		case 'select':
			if (element.options.length > 0) {
				for(var i = 0; i < element.options.length; i++) {
					if (element.options[i].value == value) {
						element.selectedIndex = i;
						break;
					}
				}
			}
			break;
		default:
			//for(var i = 0; i < window.frames.length; i++) alert(i+':'+window.frames[i].name+':'+element_name);
			//alert('a:'+window.frames[element_name]);
			//alert('b:'+window.frames[0]);
			//window.frames[element_name].document.body.innerHTML = value;
			window.frames[element_name].document.open();
			window.frames[element_name].document.write(value);
			window.frames[element_name].document.close();
			break;
	}
}

function update_element(orig_field_name, linked_field_name) {
	var value = get_element_value(orig_field_name);
	var map = eval('typeof(map___' + linked_field_name + ') == "undefined" ? null : map___' + linked_field_name);
	if (map) {
		var linked_obj = get_element(linked_field_name);
		var linked_type = get_element_type(linked_obj);
		if (linked_type == 'select') {
			var orig_id = (linked_obj.selectedIndex >= 0) ? linked_obj.options[linked_obj.selectedIndex].value : null;
			var new_idx = 0;
			linked_obj.options.length = ((linked_obj.options.length == 0) || (linked_obj.options[0].value != "")) ? 0 : 1;
			for(var i in map) {
				if (value == map[i][1]) {
					if (orig_id == map[i][0]) new_idx = linked_obj.options.length;
					linked_obj.options[linked_obj.options.length] = new Option(map[i][2], map[i][0]);
				}
			}
			linked_obj.selectedIndex = new_idx;
			flag_niceforms_needupdate = true;
		}
	}
	if (flag_niceforms && flag_niceforms_needupdate) NFFix();
}

function set_element_focus(element_name, flag, blur) {
	for (var i = 0; (i < document.forms[0].length) && (get_element_name(document.forms[0][i]) != element_name); i++);
	re = /^(.*)___(.*)$/;
	element_arr = re.exec(element_name);
	if (flag != 'next')	{
		element = document.forms[0][i];
	}
	else {
		for (; (i < document.forms[0].length) && (get_element_name(document.forms[0][i]) == element_name); i++);
		if (!element_arr) {
			module_name = '';
		}
		else {
			module_name = element_arr[1];
		}
		module_name_length = module_name.length;
		for (; i < document.forms[0].length; i++) {
			if ((document.forms[0][i].type != 'hidden') && (get_element_name(document.forms[0][i]).substr(0, module_name_length) == module_name)) {
				element = document.forms[0][i];
				break;
			}
		}
	}
	switch (get_element_type(element)) {
		case 'text':
		case 'password':
		case 'checkbox':
		case 'textarea':
		case 'file':
		case 'radio':
			if (element.length > 0) {
				element = element[0];
			}
		case 'select':
			var obj = my_getElementById('notnull_'+element_name);
			if (!obj || (my_getDisplay(obj) != 'none')) {
				if (element.offsetWidth) {
					if (blur) {
						element.blur();
					}
					else {
						element.focus();
					}
				}
			}
			break;	
	}
}

function _set_element_events(element, ptr_function) {
	if (element) {
		element.onfocus = ptr_function;
		element.onchange = ptr_function;
		element.onclick = ptr_function;
		element.onkeypress = ptr_function;
	}
}

function set_element_events(element_name, ptr_function) {
	var obj = get_element(element_name);
	if (obj) {
		var type = get_element_type(obj);
		//if (((!type) || (type && (type[0] == '_'))) && obj.length && (obj.length > 0)) { 
		if ((type != 'select') && obj.length && (obj.length > 0)) { 
//			alert(type);
			for(var i = 0; i < obj.length; i++) { 
				_set_element_events(obj[i], ptr_function);
			}
		}
		else {
			_set_element_events(obj, ptr_function);
		}
	}
}

function get_element_type(element) {
	if (!element) return;
	if (element.options) {
		return 'select';
	}
	if (element.length && (element.length > 0))	{
		return element[0].type;
	}
	return element.type;
}

function get_element_name(element) {
	var name = '';
	if (element.name) {
		name = element.name;
	}
	else {
		if (element.length && (element.length > 0))	{
			name = element[0].name;
		}
	}
	name = name.replace(/\[\]$/, '');
	return name.replace(/#[^#]+$/, '');
}

function get_element_info(type, element_name, id) {
//	return eval('(window.validate_'+element_name+' != null) ? '+type+'_'+element_name+'_'+id+' : ""');
	return eval(type+'_'+element_name+'_'+id);
}

function set_element_flag(element_name, flag, value) {
	if (flag == 'REQUIRES') {
		requirements[element_name] = new Array();
		if (value) {
			reqs_array = value.split(':');
			for(var i=0; i < reqs_array.length; i++) {
				reqs = reqs_array[i].split('/');
				requirements[element_name][i] = new Object;
				requirements[element_name][i]['at_least'] = value ? reqs.shift() : 0;
				requirements[element_name][i]['of'] = reqs;
			}
		}
	}
	else if (flag == 'ENABLED') {
		toggle_item('field', element_name, value == 'yes' ? '' : (value.substr(0, 2) == 'no' ? 'none' : (!value ? false : value)), value != 'no*');
	}
	else if (flag == 'EDIT') {
		var obj = get_element(element_name);
		obj.disabled = (value == 'no');
		flag_niceforms_needupdate = true;
	}
	else {
		var flags = eval('flags_'+element_name+'_');
		flags = flags.replace(new RegExp('[|]?'+flag+'($|[|])'), '');
		flags += (1*value ? '|'+flag : '');
//		alert('flags_'+element_name+'_="'+flags+'";');
		eval('flags_'+element_name+'_="'+flags+'";');
	}
}

function trim(value) {
	value = value.replace(/^\s+/, '');
	return value.replace(/\s+$/, '');
}

function remove(value, chr) {
	return value.replace(new RegExp('['+chr+'].*?$'), '');
}

function expand_all(module, prefix, state) {
	var orig_flag_niceforms = flag_niceforms;
	flag_niceforms = false;
	var tags_img = document.getElementsByTagName("img");
	var prefix_1 = 'img___' + module + '_';
	var prefix_2 = prefix_1 + prefix;
	for (var i = 0; i < tags_img.length; i++) {
		if (tags_img[i].id.substr(0, prefix_2.length) == prefix_2) {
			expand(module, tags_img[i].id.substr(prefix_1.length), state);
		}
	}
	if (orig_flag_niceforms && flag_niceforms_needupdate) NFFix();
	flag_niceforms = orig_flag_niceforms;
}

function expand(module, id, state) {
	if (state === false) {
		state = 'none';
	}
	else if (state === true) {
		state = '';
	}
	else {
		state = false;
	}
	var flag = id.substr(0, 1);
	var display = toggle_item(flag != '_' ? 'block' : 'field', flag != '_' ? module+'_'+id : module+id, state);
	if (display != null) {
		if (flag != '_') {
			var img_obj = my_getElementById('img___' + module + '_' + id);
			img_obj.src = (display == 'none') ? eval('expand___' + module + '_' + id + '[0]') : eval('expand___' + module + '_' + id + '[1]');
		}
		set_element_value(module + ((flag != '_') ? '___state_' + id : '___state' + id), (display == 'none') ? '' : '1');
	}
	if (flag_niceforms && flag_niceforms_needupdate) NFFix();
	return display;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

function getObj(name) {
	var obj;
	if (document.getElementById){
		if (obj = document.getElementById(name)) {
			this.obj = obj;
			this.style = obj.style;
		}
	}
	else if (document.all) {
		if (obj = document.all[name]) {
			this.obj = obj;
			this.style = obj.style;
		}
	}
	else if (document.layers) {
		if (obj = getObjNN4(document, name)) {
			this.obj = obj;
			this.style = obj;
		}
	}
}

function getObjNN4(obj, name) {
	var x = obj.layers;
	var foundLayer;
	for (var i = 0; i < x.length; i++) {
		if (x[i].id == name)
		 	foundLayer = x[i];
		else if (x[i].layers.length)
			var tmp = getObjNN4(x[i], name);
		if (tmp) foundLayer = tmp;
	}
	return foundLayer;
}

function my_setPosition(obj, left, top) {
	if (!obj) return;
	var noPx = document.childNodes ? 'px' : 0;
	if (left != null) obj.style.left = left + noPx;
	if (top != null) obj.style.top = top + noPx;
}

function my_setVisibility(obj, visibility) {
	if (!obj) return;
	if (obj.style) {
		obj.style.visibility = visibility ? 'visible' : 'hidden';
	}
	else {
		obj.visibility = visibility ? 'show' : 'hide';
	}
}

function my_getMousePosition(e, div) {
	var posx = 0;
	var posy = 0;
	var maxx = 0;
	var maxy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY)
	{
		posx = e.pageX;
		posy = e.pageY;
        maxx = (div ? div.scrollWidth : window.innerWidth) + window.pageXOffset;
        maxy = (div ? div.scrollHeight : window.innerHeight) + window.pageYOffset;
	}
	else if (e.clientX || e.clientY)
	{
		posx = e.clientX + document.body.scrollLeft;
		posy = e.clientY + document.body.scrollTop;
        maxx = document.body.clientWidth + document.body.scrollLeft;
        maxy = document.body.clientHeight + document.body.scrollTop;
	}
	return [posx, posy, maxx, maxy];
}

function get_obj_x(obj) {
	if (!obj) return null;
	var x = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			x += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x) {
		x = obj.x;
	}
	return x;
}

function get_obj_y(obj) {
	if (!obj) return null;
	var y = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			y += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y) {
		y = obj.y;
	}
	return y;
}

function my_setbgColor(obj, color) {
	var orig_color = '';
	if (obj) {
		if (obj.style) {
			obj = obj.style;
		}

		if (obj.bgColor) {
			orig_color = obj.bgColor;
		}
		else if (obj.background) {
			orig_color = obj.background;
		}
		else if (obj.backgroundColor) {
			orig_color = obj.backgroundColor;
		}
		obj.bgColor = color;
		if (obj.background)	obj.background = color;
		obj.backgroundColor = color;
	}
	return orig_color;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////


function my_getElementById(id, curr_document) {
	var obj = null;
	if (!curr_document) {
		curr_document = document;
	}
	if (curr_document.getElementById) {
//		obj = curr_document.getElementsByName(id);
		obj = curr_document.getElementById(id);
	} 
	else if (curr_document.all) {
		obj = curr_document.all[id];
	}
	return obj;
}

function my_getDivById(id, doc) {
	var obj = my_getElementById(id, doc);
	if (obj) {
		return obj;
	}
	if (!doc) {
		doc = document;
	}
	if (document.layers) {
		if (doc.layers[id]) {
			return doc.layers[id];
		} 
		else {
			for (var x = 0, y; !y && x < doc.layers.length; x++) {
				y = my_getDivById(id, doc.layers[x].document);
			}
			return y;
		} 
	}
	return obj;
}

function my_getSize(obj) {
	var x = 0;
	var y = 0;
	if (obj) {
		x = obj.offsetWidth;
		y = obj.offsetHeight;
	}
	return [x, y];
}

function my_setSize(obj, x, y, percentage) {
	if (obj) {
		if (obj.style) {
			obj = obj.style;
		}
		if (obj.resizeTo) {
			obj.resizeTo(x, y);
		}
		var noPx = (document.childNodes && !percentage) ? 'px' : 0;
		if (x != null) {
			obj.width = x + noPx + (percentage ? "%" : '');
			if (!percentage) obj.pixelWidth = x;
		}
		if (y != null) {
			obj.height = y + noPx + (percentage ? "%" : '');
			if (!percentage) obj.pixelHeight = y;
		}
	}
}

function my_setzIndex(obj, zIndex) {
	if (obj) {
		if (obj.style) {
			obj = obj.style;
		}
		obj.zIndex = zIndex;
	}
}

function my_setDisplay(obj, display) {
	if (obj) {
		if (obj.style) {
			obj = obj.style;
		}
		if (typeof(obj.display) == 'undefined') {
			return;
		}
		obj.display = display;
	}
}

function my_getDisplay(obj) {
	if (obj) {
		if (obj.style) {
			obj = obj.style;
		}
		if (typeof(obj.display) == 'undefined') {
			return null;
		}
		return obj.display;
	}
	return null;
}

var enabled_last_state = new Object;
var display_dependency = new Object;
function toggle_item(type, name, display, save_state, curr_document) {
	var full_name = type ? type+'___'+name : name;
	var obj = my_getElementById(full_name, curr_document);
	if (obj) {
		orig_display = my_getDisplay(obj);
		if (save_state === '?') return orig_display;
		if (display === false) {
			display = (orig_display == 'none') ? '' : 'none';
		}
		if (display == 'restore') {
			display = typeof(enabled_last_state[full_name]) == 'undefined' ? orig_display : enabled_last_state[full_name];
//			alert(full_name+' state restored:'+display+'/'+orig_display);
		}
		my_setDisplay(obj, display);
		flag_niceforms_needupdate = true;
		if (save_state) {
//			alert(full_name+' state saved:'+display+'/'+orig_display);
			enabled_last_state[full_name] = display;
		}
		if (display_dependency[full_name]) {
			for(var i = 0; i < display_dependency[full_name].length; i++) {
				var tmp_name = display_dependency[full_name][i].split('___');
				toggle_item(tmp_name[0], display_dependency[full_name][i].substr(tmp_name[0].length+3), display, save_state, curr_document);
			}
		}
		return display;
	}
	return null;
}

function set_checkbox(mode, element) {
	var value = !element.checked;
	if (mode == 'all') value = true; else if (mode == 'none') value = false;  
	element.checked = value;
}

function list_selection(mode, list_id, start, max) {
	var element = document.forms[0][list_id];
	if (!element) return false;
	if (element.length) {
		for(var i = 0; (i < element.length) && (i < max); i++) {
			if (i >= start) set_checkbox(mode, element[i]);
		}
	}
	else {
		set_checkbox(mode, element);
	}
	return false;
}

function set_process_status(status, referer, stop, resubmit) {
	var obj = my_getElementById('process_status_'+referer);
	var parent_obj = obj;
	do {
		parent_obj = parent_obj.parentNode;
	}
	while (!parent_obj.id);
	var prefix = '';
	var postfix = '';
	switch (status) {
		case 'not executed':
			prefix = '<span style="color: #888888;">';
			postfix = '</span>';
			break;
		case 'running':
			prefix = '<span style="color: #dd0000;">';
			postfix = '</span>' + (stop ? '&nbsp;<input type="button" value="STOP" onclick="set_process_status(\'terminating...\', \''+referer+'\'); window.frames[\'process_log_'+referer+'\'].location.href=\'?URL=__'+(resubmit ? '*' : '')+'!'+referer+'\'; return false;">' : '');
			if (parent_obj) {
				my_setDisplay(parent_obj, '');
			}
			break;
		case 'executed':
			prefix = '<span style="color: #00ff00;">';
			postfix = '</span>';
			break;
		case 'terminating...':
			break;
		case 'error':
			prefix = '<span style="color: #dd0000;">';
			postfix = '</span>';
			if (parent_obj) {
				my_setDisplay(parent_obj, '');
			}
			break;
	}
	obj.innerHTML = prefix + status + postfix;
}

function onclick_cell(type, row_id, col_id) {
	if (type == 'matrix') {
		if (typeof("_onclick_cell") != "undefined") _onclick_cell(row_id, col_id);
	}
}
////////////////////////////////////////////////////////////////////////////////////////

// Image Preloader
function ImagePreloader(images, callback) {
	// store the callback
	this.callback = callback;

	// initialize internal state.
	this.nLoaded = 0;
	this.nProcessed = 0;
	this.aImages = new Array;

	// record the number of images.
	this.nImages = images.length;

	// for each image, call preload()
	for ( var i = 0; i < images.length; i++ ) 
		this.preload(images[i]);
}

ImagePreloader.prototype.preload = function(image) {
	// create new Image object and add to array
	var oImage = new Image;
	this.aImages.push(oImage);
	
	// set up event handlers for the Image object
	oImage.onload = ImagePreloader.prototype.onload;
	oImage.onerror = ImagePreloader.prototype.onerror;
	oImage.onabort = ImagePreloader.prototype.onabort;
	
	// assign pointer back to this.
	oImage.oImagePreloader = this;
	oImage.bLoaded = false;
	oImage.source = image;
	
	// assign the .src property of the Image object
	oImage.src = image;
}

ImagePreloader.prototype.onComplete = function() {
	this.nProcessed++;
	if ( this.nProcessed == this.nImages )
		this.callback(this.aImages);
}

ImagePreloader.prototype.onload = function() {
	this.bLoaded = true;
	this.oImagePreloader.nLoaded++;
	this.oImagePreloader.onComplete();
}

ImagePreloader.prototype.onerror = function() {
	this.bError = true;
	this.oImagePreloader.onComplete();
}

ImagePreloader.prototype.onabort = function() {
	this.bAbort = true;
	this.oImagePreloader.onComplete();
}

function copyToClipboard(inElement) {
	if ((1==2) && (inElement.createTextRange)) {
		var range = inElement.createTextRange();
		if (range && BodyLoaded==1) range.execCommand('Copy');
	} else {
		var flashcopier = 'flashcopier';
		if (!document.getElementById(flashcopier)) {
			var divholder = document.createElement('div');
			divholder.id = flashcopier;
			document.body.appendChild(divholder);
		}
		document.getElementById(flashcopier).innerHTML = '';
		//var divinfo = '<embed src="'+curr_img_common_path+'_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		var divinfo = '<embed src="'+curr_img_common_path+'_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(inElement)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		document.getElementById(flashcopier).innerHTML = divinfo;
	}
}

function _move_slidebar(x) {
	my_setPosition(moved_obj[moved_obj_name].obj, x);
	document.forms[0].elements[moved_obj_name].value = Math.round((x - moved_obj[moved_obj_name].x_min) / 6.04);
	moved_obj[moved_obj_name].obj.innerHTML = '<div class="slidebar_pointer_text">' + document.forms[0].elements[moved_obj_name].value + '</div>';
}
function move_slidebar(e) {
	var pos = my_getMousePosition(e);
	pos[0] = pos[0] - 11;
	if (pos[0] < moved_obj[moved_obj_name].x_min) pos[0] = moved_obj[moved_obj_name].x_min;
	if (pos[0] > moved_obj[moved_obj_name].x_max) pos[0] = moved_obj[moved_obj_name].x_max;
	_move_slidebar(pos[0]);
}

var moved_obj = new Object;
var moved_obj_name = null;
function move_pointer(obj_name, init, event) {
	if (init && moved_obj[obj_name]) return;
	if (moved_obj_name) {
		document.onmousemove = null;
		window.onscroll = null;
		moved_obj[moved_obj_name].obj.onclick = moved_obj[moved_obj_name].onclick;
		moved_obj_name = null;
	}
	else if (document.forms[0].elements[obj_name]) {
		moved_obj_name = obj_name;
		if (!moved_obj[moved_obj_name]) {
			moved_obj[moved_obj_name] = new Object;
			moved_obj[moved_obj_name].obj = my_getElementById(obj_name);
			moved_obj[moved_obj_name].x = get_obj_x(moved_obj[moved_obj_name].obj);
			moved_obj[moved_obj_name].y = get_obj_y(moved_obj[moved_obj_name].obj)-27;
			document.forms[0].elements[moved_obj_name].value *= 1;
			moved_obj[moved_obj_name].x_min = moved_obj[moved_obj_name].x + 5;
			moved_obj[moved_obj_name].x_max = moved_obj[moved_obj_name].x_min + 604;
			my_setPosition(moved_obj[moved_obj_name].obj, null, moved_obj[moved_obj_name].y);
		}
		_move_slidebar(moved_obj[moved_obj_name].x_min + document.forms[0].elements[moved_obj_name].value * 6.04);
		my_setVisibility(moved_obj[moved_obj_name].obj, true);
		document.onmousemove = move_slidebar;
		window.onscroll = move_slidebar;
		moved_obj[moved_obj_name].onclick = moved_obj[moved_obj_name].obj.onclick;
		moved_obj[moved_obj_name].obj.onclick = move_pointer;
		if (init) move_slidebar(event);
	}
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();
