// js document

var ua_ie, ua_ie6_min, os_win; // user system

var _form_window; // reference to open form window
var _form_window_closed_poll; // polls the form winodw if it has been closed

var _file_manager_window; // reference to open file manager window 
var _log_source_matching_files_window; // reference to open log source matching file window 

var _debug_window; // reference to open debug window 

var _temp_disabled_links; // array of temporary disabled links which are below the transparent cover
var _temp_disabled_form_elements; // array of temporary disabled input elements which are below the transparent cover

// call to server
var _iframe_object;
var _iframe_object_exists = false;
var _call_to_server_url;

// xmlhttp
var _xmlhttp_post;

window.onunload = init_unload;

function init_unload() {
	
      // close any open form window
      if (_form_window != null) {
            _form_window.close();
      }
}

function user_system() {
	
	os_win = (navigator.userAgent.indexOf('Win') != -1) ? true : false;
	ua_ie = (navigator.appName == 'Microsoft Internet Explorer') && !(navigator.userAgent.indexOf('Opera') != -1) ? true : false;	
	ua_ie6_min = (ua_ie && (ie_ver_num() >= 6)) ? true : false; // MSIE 6+
	// alert('os_win: ' + os_win + '\n ua_ie: ' + ua_ie + '\n ua_ie6_min: ' + ua_ie6_min);
}

function ie_ver_num() { // internet explorer version number
	
	var ua = navigator.userAgent;
	var msie_offset = ua.indexOf('MSIE ');
	if (msie_offset == -1) {
		return 0;
	}
	else {
		return parseFloat(ua.substring(msie_offset + 5, ua.indexOf(';', msie_offset)));
	}
}

function get_user_agent() {
	
	// returns the user agent brand
	
	var user_agent_string = navigator.userAgent.toLowerCase();
	var user_agent_app_name = navigator.appName.toLowerCase();
	var user_agent;
	
	if (user_agent_string.indexOf('safari') != -1) {
		user_agent = 'safari';
	}
	else if (user_agent_string.indexOf('opera') != -1) {
		user_agent = 'opera';
	}
	else if (user_agent_app_name == 'netscape') {
		user_agent = 'netscape';
	}
	else if (user_agent_app_name == 'microsoft internet explorer') {
		user_agent = 'msie';
	}
	else {
		user_agent = 'unknown';
	}
	
	return user_agent;
}

function document_width() { // available document/window width
	
	if (ua_ie6_min) {
		return document.body.parentElement.clientWidth;
	}
	else if (window.innerWidth) {
		return window.innerWidth;
	}
	else if (document.body && document.body.clientWidth) {
		return document.body.clientWidth;
	}
	return 0;
}

function scroll_top() { // scroll top position
	
	if (window.innerHeight) {
		return window.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop) {
		return document.documentElement.scrollTop;
	}
	else if (document.body) {
		return document.body.scrollTop;
	}
	else {
		return 0;
	}
}

function delete_profile_check_confirm(profileNum) {
	
	if (_confirm_box_is_open) {
		setTimeout('delete_profile_check_confirm("' + profileNum + '")', 40);
	}
	else {
		if (_confirm_is_ok) {
			document.getElementById('profiles').style.display = 'none';
			document.getElementById('deleteProfileInfo').style.display = 'block';
			return callToServer('?dp+templates.admin.profiles.delete_profile+webvars.node_to_delete+' + profiles[profileNum].node_name);
		}
	}
}

// -----------
// css display
// -----------

function display_on(element_id) {
	
	document.getElementById(element_id).style.display = 'block';
}

function display_off(element_id) {
	
	document.getElementById(element_id).style.display = 'none';
}

// -------------
// get user name
// -------------

function get_user_name() {

	var user_name;
	var cookie_string = document.cookie;
	var cookie_dat = cookie_string.split(';');

	for (var i = 0; i < cookie_dat.length; i++) {

		var match_user = cookie_dat[i].match(/authuser/);

		if (match_user != null) {
			var user_dat = cookie_dat[i].split('=');
			user_name = user_dat[1];
			return user_name;
		}
	}
}

// -----------------------------
// form window
// -----------------------------
function open_form_window(url, window_name, width, height) {
	
	disable_opener_window();
	var content = document.getElementById('content');
	content.onclick = set_focus_on_form_window;
	
	var left = parseInt((screen.availWidth/2) - (width/2));
    var top = parseInt((screen.availHeight/2) - (height/2));
	_form_window = window.open(url,window_name,'width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',status=yes,scrollbars=yes,resizable=yes');
    _form_window.focus();
	
	_form_window_closed_poll = setInterval('check_if_form_window_closed()', 200);
}

function check_if_form_window_closed() {

	if (_form_window.closed) {
		clearInterval(_form_window_closed_poll);
		content.onclick = null;
		restore_opener_window();	
	}
}

function set_focus_on_form_window() {
	_form_window.focus();
}

function disable_opener_window() {
	_temp_disabled_links = new Array();
	_temp_disabled_form_elements = new Array();

	//disable all input form elements
	var input_elements = document.getElementsByTagName('input')
	for (var i = 0; i < input_elements.length; i++) {		
		var id_value = input_elements[i].id;
		if (id_value == '') {
			id_value = 'input_num' + [i];
			input_elements[i].id = id_value;
		}
		var disabled_value = input_elements[i].disabled;
		_temp_disabled_form_elements[i] = {id:id_value, disabled: disabled_value};

		input_elements[i].disabled = 'true';
	}

	//disbale all links which are covered by the transparent cover
	var links_to_disable = document.getElementById('content')
	var links = links_to_disable.getElementsByTagName('a');

	for (var i = 0; i < links.length; i++) {
		var id_value = links[i].id;
		if (id_value == '') {
			id_value = 'link_num' + [i];
			links[i].id = id_value;
		}
		
		var onclick_value = links[i].onclick;

		_temp_disabled_links[i] = {id:id_value, onclick:onclick_value};
	
		links[i].onclick = simulate_disabled_link;
	}
}

function simulate_disabled_link() {
	// function is invoded from a page with disabled links
	return false;
}

function restore_opener_window() {

	// restore disabled form elements
	for (var i = 0; i < _temp_disabled_form_elements.length; i++) {
		var id_value = _temp_disabled_form_elements[i].id;
		var disabled_value = _temp_disabled_form_elements[i].disabled;
		
		var element = document.getElementById(id_value);
		element.disabled = disabled_value;
	}
	_temp_disabled_form_elements.length = 0;

	// restore disabled links
	for (var i = 0; i < _temp_disabled_links.length; i++) {
		var id_value = _temp_disabled_links[i].id;
		var onclick_value = _temp_disabled_links[i].onclick;

		var element = document.getElementById(id_value);
		element.onclick = onclick_value;

		// links[i].onclick = _temp_disabled_links[i];
	}
	_temp_disabled_links.length = 0;
}

// ===============
// form processing
// ===============
function strip_whitespace(value) { // strips leading and trailing whitespace
	value = value.replace(/^\s+/, '');
	value = value.replace(/\s+$/, '');
	return value;	
}

function value_is_not_empty(value) { // checks if a field value is empty or not
	var match_char = value.match(/.+/);
	if (match_char != null) {
		return true;
	}
	return false;
}

function value_is_not_empty_msg(value, msg) { // checks if a field value is empty or not and also shows the corresponding alert message
	var match_char = value.match(/.+/);
	if (match_char != null) {
		return true;
	}
	alert(msg);
	return false;	
}

function value_has_no_leading_or_trailing_space_msg(value, msg) { // checks if a field value starts or ends with a space
	
	if (value.charAt(0) != ' ' && value.charAt(value.length - 1) != ' ') {
		return true;
	}
	alert(msg);
	return false;
}

function value_is_integer_min_msg(value, min, msg) {
	// validates for integer greater or equal min value
	var match_int = value.match(/^[-]?\d+$/); // matches a positiv and negative integer
	if ((match_int != null) && (parseInt(value) >= min)) {
		return true;
	}
	alert(msg);
	return false;
}

function value_is_integer_min_max_msg(value, min, max, msg) {
	// validates if integer is between min max value

	var match_int = value.match(/^[-]?\d+$/); // matches a positiv and negative integer
	if ((match_int != null) && (parseInt(value) >= min) && (parseInt(value) <= max)) {
		return true;
	}
	alert(msg);
	return false;
}

function value_is_integer(value) { // matches a positiv and negative integer
	var match_int = value.match(/^[-]?\d+$/);
	if (match_int != null) {
		return true;
	}
	return false;
}

function value_is_number(value) { // matches any positiv and negative number (float, integer)
	var match_int = value.match(/^[-]?\d*\.?\d*$/);
	if (match_int != null) {
		return true;
	}
	return false;
}

function validate_mysql_database_name_msg(mysql_database_name, msg) {
	// for mysql database names allow alphanumeric characters and underscore only
	var match_invalid_character = mysql_database_name.match(/[^a-zA-Z0-9_]/);
	if (!match_invalid_character) {
		return true;
	}
	alert(msg);
	return false;
}

function convert_dollar_to_hex(value) {
	// converts $ to __HexEsc__24
	// Note, don't use $ or /u0024 conversion within templates,
	// there are general $ escaping problems
	// Using /u0024 in replace wont work in Safarai on Mac
	
	value = value.replace(/\$/g, '__HexEsc__24');
	
	return value;
}

// ============
// debug window
// ============

function open_debug_window(profile_name, debug_node_name) {
	
	var url = '?dp+templates.shared.error_handling.debug';
	url += '+p+' + profile_name;
	url += '+volatile.debug_node_name+' + debug_node_name;
	var window_name = 'debug_window';
	var width = 620;
	var height = 440;

	var left = parseInt((screen.availWidth/2) - (width/2));
    var top = parseInt((screen.availHeight/2) - (height/2));
	_debug_window = window.open(url,window_name,'width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',status=yes,scrollbars=yes,resizable=yes');
    _debug_window.focus();
}

// =============================
// file manager window
// =============================

function open_file_manager_window(pathname_field_id) {
	
	var url = '?dp+templates.shared.file_manager.index';
	url += '+volatile.pathname_field_id+' + pathname_field_id;
	
	var window_name = 'file_manager';
	var width = 570;
	var height = 400;

	// check if a path is defined in the pathname field
	// if a path exists then start the file manager with the defined path
	var pathname = strip_whitespace(document.getElementById(pathname_field_id).value);
	
	// alert('pathname not encoded: ' + pathname);
		
	if (pathname != '') {
				
		pathname = pathname.replace(/\$/g, '__HexEsc__24');
		pathname = pathname.replace(/\\/g, '__HexEsc__5C');
		
		// alert(pathname);
		
		url += '+volatile.pathname_request+' + encodeURIComponent(pathname);
	}
	
	var left = parseInt((screen.availWidth/2) - (width/2));
    var top = parseInt((screen.availHeight/2) - (height/2));
    
	_file_manager_window = window.open(url,window_name,'width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',status=yes,scrollbars=yes,resizable=yes');
    _file_manager_window.focus();
}

function set_pathname_value(pathname_field_id, pathname) { // initiated from file manager
		
	// alert('set pathname to: ' + pathname);
		
	var pathname_field = document.getElementById(pathname_field_id);	
	pathname_field.value = pathname;
}

function convert_name_to_integer_string(name) {
	
	// Converts characters to unicode integers
	
	var int_string = '';
	
	for (var i = 0; i < name.length; i++) {

		var char_to_int = name.charCodeAt(i);
		
		int_string += char_to_int;
		
		if (i < (name.length - 1)) {
		
			int_string += '-';
		}
	}
	
	return int_string;
}

function convert_integer_string_to_name(integer_string) {
	
	// Converts unicode integers to characters
	// format of the_string: 138-97-28-132-...
	
	var dat = integer_string.split('-');
	
	var name = '';
	
	for (var i = 0; i < dat.length; i++) {

		// var int_to_char = String.fromCharCode(dat[i]);
		
		name += String.fromCharCode(dat[i]);
	}
	
	return name;
}

// ---------------------------------
// log source matching files window
// ---------------------------------
function open_log_source_matching_files_window(log_source_location, profile) {

	// var host = window.location.host;
	var url = '?dp+templates.shared.matching_log_source_files.matching_log_source_files';

	// if initiated on the config page use the profiles log source
	if (log_source_location == 'profile') {
		url += '+volatile.log_source_location+profile';
		url += '+volatile.profile+' + profile;
	}
	// if initiated from the "new profiles wizard" get the log source data from the wizard
	else {
		if (validate_log_source()) {
			url += '+volatile.log_source_location+wizard';
			url += _qs_log_source;
		}
		else {
			return false;
		}
	}
	
//	alert(url);

	var window_name = 'log_source_matching_files';
	var width = 570;
	var height = 360;
	
	var left = parseInt((screen.availWidth/2) - (width/2));
    var top = parseInt((screen.availHeight/2) - (height/2));
	_log_source_matching_files_window = window.open(url,window_name,'width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',status=yes,scrollbars=yes,resizable=yes');
	_log_source_matching_files_window.focus();
}


// -----------------------------
// png image handling
// -----------------------------

function fix_png_images(_blank_image_reference) {

	if (ua_ie && os_win) {
		
		for (i = 0; i < document.images.length; i++) {
			if (document.images[i].src.match(/\.png$/i) != null) {
				var img = document.images[i];
				var src = img.src;
				var width = img.width;
				var height = img.height;
				
				// alert('height: ' + height + '\nwidth: ' + width);
				
				/*

				// then fetch the correct image size from the img_ref object
				// required for IE if style.display is set to 'none'

				if (width <= 0) { 
					var img_split = src.split('/');
					var img_name_with_ext = img_split[img_split.length - 1];
					var img_name = img_name_with_ext.match(/\w+(?=\.png)/i);
					var width = img_ref[img_name].width;
					var height = img_ref[img_name].height;
				}
				*/
				
				// alert(document.images[i].id + '\n' + width + ', ' + height);
				// img.src = 'picts/blank.gif';
				img.src = _blank_image_reference;
				img.style.width = width + 'px';
				img.style.height = height + 'px';
				img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')";
				img.style.visibility = 'visible';
			}
		}
	}
	else {
		// make png images visible
		for (i = 0; i < document.images.length; i++) {
			if (document.images[i].src.match(/\.png$/i) != null) {
				var img = document.images[i];
				img.style.visibility = 'visible';
			}
		}
	}
}

// ------------
// error window
// ------------

function server_response_error_callback(error_id) {
	// replcaces the active page with the error page

	// alert('server_response_error_callback started');
	// alert('user_name: ' + user_name);
	
	var url = '?dp+templates.shared.error_handling.error';
	url += '+volatile.error_window+' + true;
	url += '+volatile.error_id+' + error_id;
	
	// var window_name = 'error_window';
	// var width = 570;
	// var height = 400;

	/*
	var left = parseInt((screen.availWidth/2) - (width/2));
    var top = parseInt((screen.availHeight/2) - (height/2));
	var error_window = window.open(url,window_name,'width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',status=yes,scrollbars=yes,resizable=yes');
    error_window.focus();
    */
    
    location.replace(url);
}

// -----------------------------
// call to server
// -----------------------------

function call_to_server(url) {

	if (!document.createElement) {
		return true
	};

	// URL - the volatile variable is used for error handling in error.cfv only!
	_call_to_server_url = url + '+volatile.error_callback+true';

	if (!_iframe_object_exists) {
		// create the IFrame and assign a reference to the
		// object to our global variable iframe_object.
		// this will only happen the first time 
		// callToServer() is called
		
		var temp_iframe = document.createElement('iframe');
		temp_iframe.setAttribute('id','RSIFrame');
		temp_iframe.style.border = '0px';
		temp_iframe.style.width = '0px';
		temp_iframe.style.height = '0px';
		_iframe_object = document.body.appendChild(temp_iframe);

		_iframe_object_exists = true;

		// delay final server response call to give some browsers time to create the iframe object
		setTimeout('call_to_server_final()', 10);	
	}
	else {
		call_to_server_final();
	}
}

function call_to_server_final() {

	var iframe_document;
	
	if (_iframe_object.contentDocument) {
		// For NS6
		iframe_document = _iframe_object.contentDocument; 
	}
	else if (_iframe_object.contentWindow) {
		// For IE5.5 and IE6
		iframe_document = _iframe_object.contentWindow.document;
	}
	else {
		return true;
	}
	
	iframe_document.location.replace(_call_to_server_url);

	return false;
}

// ---------------
// xmlhttp_request
// ---------------

// var xmlhttp;

function xmlhttp_call(url, response_function) {
	
	var xmlhttp;

	// xmlhttp is the xmlhttp object variable defined in the calling function
	
	// alert('OK 1');
	
    // native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
        // xmlhttp.onreadystatechange = process_response;
        xmlhttp.onreadystatechange = response_function;
        xmlhttp.open("GET", url, true);
        xmlhttp.send(null);
    } // IE ActiveX version
    else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        if (xmlhttp) {
            // xmlhttp.onreadystatechange = process_response;
           	xmlhttp.onreadystatechange = response_function;
            xmlhttp.open("GET", url, true);
            xmlhttp.send();
        }
    }
    
    return xmlhttp;
}

// ------------
// xmlhttp POST
// ------------

function xmlhttp_post(url, dat) {
	
	// dat contains form data in query string format
	
	if (dat) {
	
		dat = 'volatile.content_type=text/xml&' + dat; // IMPORTANT, sets Salang content type to text/xml
	}
	else {
		
		// if POST is used without any data, i.e. to avoid caching of the server response object
		
		dat = 'volatile.content_type=text/xml';
	}
	
	// add volatile node for error handling
	
	dat += '&volatile.error_xmlhttp_callback=true';
	
    // native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        _xmlhttp_post = new XMLHttpRequest();
        // _xmlhttp_post.onreadystatechange = process_response;
        _xmlhttp_post.onreadystatechange = xmlhttp_post_response;
        _xmlhttp_post.open("POST", url, true);
        _xmlhttp_post.send(dat);
    } // IE ActiveX version
    else if (window.ActiveXObject) {
        _xmlhttp_post = new ActiveXObject("Microsoft.XMLHTTP");
        if (_xmlhttp_post) {
            // _xmlhttp_post.onreadystatechange = process_response;
           	_xmlhttp_post.onreadystatechange = xmlhttp_post_response;
            _xmlhttp_post.open("POST", url, true);
            _xmlhttp_post.send(dat);
        }
    }
}

function xmlhttp_post_response() {
	
	// The function that is to invoke upon a response
	// is defined in the XML method node
	
	// alert('xmlhttp_post_response');
			
	if (_xmlhttp_post.readyState == 4) {
		
		if (_xmlhttp_post.status == 200) {
	
			// alert(_xmlhttp_post.getAllResponseHeaders());
			// alert(_xmlhttp_post.responseText);
			// alert(_xmlhttp_post.responseXML);
			
			var response = _xmlhttp_post.responseXML;
			
			var method = response.getElementsByTagName('method')[0].firstChild.nodeValue;
			var dat = response.getElementsByTagName('dat')[0].firstChild.nodeValue;
				
			// alert('method: ' + method + '\ndat length: ' + dat.length + '\ndat: ' + dat);
			// prompt('dat:', dat);
			
			eval(method + '(' + dat + ')');
		}	
	}
}

// ----------
// about info
// ----------

function toggle_about_section() {
	
	// hide trial mode switch section
	var trial_mode_switch_section = document.getElementById('trial_mode_switch_section');
	
	if (trial_mode_switch_section != null) {
		
		trial_mode_switch_section.style.display = 'none';
	}
	
	var about_section = document.getElementById('about_section');
	about_section.style.display = (about_section.style.display == 'none') ? 'block' : 'none';
}

// ----------
// about info
// ----------

function print_static_report() {

	var url = parent.main_frame.location.href;
	
	var width = 800;
    var height = 500;
	var window_name = 'print_report';
	
	var left = parseInt((screen.availWidth/2) - (width/2));
    var top = parseInt((screen.availHeight/2) - (height/2));

	_window = window.open(url,window_name,'width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',menubar=yes,status=yes,scrollbars=yes,resizable=yes');
	_window.focus();
}

// -----
// debug
// -----

function write_debug_text(debug_text) {
	// This function writes debug output to the progress page
	// Function is used for debugging only
	
	var reference = document.getElementsByTagName('body');

	var text = document.createTextNode(_debug_count + '. ' + debug_text);
	var p_element = document.createElement('p');
	p_element.appendChild(text);
	p_element.className = 'debug-output';

	document.body.appendChild(p_element);
}



