//var xmlHttp;
var errorOnConfig = false;

/*
 * ---------------------------------------------------------------------------
 */

function createXmlHttpRequest() {

//	/* If another request is running, abort it */
//	if (xmlHttp && (xmlHttp.readyState == 2 || xmlHttp.readyState == 3)) {
//		xmlHttp.abort();		
//	}

	/* Create a new XMLHttpRequest object to talk to the Web server */
	var xmlHttp = false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	try {
	  xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
	  try {
	    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	  } catch (e2) {
	    xmlHttp = false;
	  }
	}
	@end @*/
	
	if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
	  xmlHttp = new XMLHttpRequest();
	}

	return xmlHttp;
	
}

/*
 * ---------------------------------------------------------------------------
 */

function getInputFieldsGetString(formId) {
	
	var form = document.getElementById(formId);
	var getString = "";
	
	var inputFields = form.getElementsByTagName('input');
	for (i = 0; i < inputFields.length; i++) {
	
		var field = form.getElementsByTagName('input')[i];
	
		if (field.type == "text" || field.type == "password") {
			getString += field.name + "=" + escape(encodeURI(field.value)) + "&";
        } else if (field.type == "checkbox") {
        	if (field.checked) {
        		getString += field.name + "=" + escape(encodeURI(field.value)) + "&";
       		} else {
       			getString += escape(encodeURI(field.name)) + "=&";
     		}
        } else if (field.type == "radio") {
        	if (field.checked) {
        		getString += field.name + "=" + escape(encodeURI(field.value)) + "&";
        	}
        }
	}

	inputFields = form.getElementsByTagName('textarea');
	for (i = 0; i < inputFields.length; i++) {
		var field = form.getElementsByTagName('textarea')[i];
        getString += field.name + "=" + escape(encodeURI(field.value)) + "&";
	}

	inputFields = form.getElementsByTagName('select');
	for (i = 0; i < inputFields.length; i++) {
		var field = form.getElementsByTagName('select')[i];
        getString += field.name + "=" + escape(encodeURI(field.options[field.selectedIndex].value)) + "&";
	}

	getString = getString.replace(/\+/g, '%252B');
	return getString;
}

/*
 * ---------------------------------------------------------------------------
 */

function saveConfigurationForm(buttonName, formId) {

	document.getElementById('log').innerHTML = 'Please wait, saving form...';

	var formFieldsString = getInputFieldsGetString(formId);
		
	var xmlHttp = createXmlHttpRequest();
	
	xmlHttp.open("POST", encodeURI(context + '/do'), false);
	
	xmlHttp.setRequestHeader(
		"Content-Type",
      	"application/x-www-form-urlencoded");
	
	xmlHttp.send('action=saveForm&buttonName=' + buttonName + '&' + formFieldsString);

	if (xmlHttp.status == 200) {
		document.getElementById('log').innerHTML = '&nbsp;';
		//configSaved = 1;
		return true;
	} else {
		document.getElementById('log').innerHTML = '<span class=\"error\">Failed to save configuration!<br />' + xmlHttp.statusText + '</span>';
		return false;
	}

}

/*
 * ---------------------------------------------------------------------------
 */
 
function doActionSilently(buttonName) {

	var xmlHttp = createXmlHttpRequest();
	
	xmlHttp.open("GET", encodeURI(context + '/do?action=doAction&buttonName=' + buttonName), false);
	
	xmlHttp.send(null);
	
	//result = xmlHttp.responseText;

	if (xmlHttp.status == 200) {
		// result is empty or holds an URL to redirect to
		if (xmlHttp.responseText.length != 0) {
			window.location = xmlHttp.responseText;
		}
		return true;
	} else {
		// result holds an UUID to the error message stored in
		// the session on the server
		GB_showCenter('ERROR!', context + '/error?errorId=' + xmlHttp.statusText, 500, 710);
		return false;
	}
	
}

function popup(url) {
	window.open(url, 'popup', 'location=no, menubar=no, toolbar=no, status=no, resizable, width=700, height=500, scrollbars=yes');
}

/*
 * ---------------------------------------------------------------------------
 */
 
/**
 * popupStyle can be 'fading' oder 'browser'
 */
function callServlet(popupStyle, popupCaption, servletUrl, reload) {

	if (popupStyle == 'fading') {
		if (reload) {
			GB_showCenterWithReload(popupCaption, servletUrl, 500, 710);		
		} else {
			GB_showCenter(popupCaption, servletUrl, 500, 710);		
		}
	} else {
		popup(servletUrl);
	}

	return false;
}

function fadingPopup(popupCaption, servletUrl) {
	GB_showCenter(popupCaption, servletUrl, 500, 700);
}

/*
 * ---------------------------------------------------------------------------
 */

function buttonDone(buttonName) {

	var xmlHttp = createXmlHttpRequest();
	
	xmlHttp.onreadystatechange = function() { 
		if (xmlHttp.readyState == 4) {
		    if (xmlHttp.status == 200) {
				result = xmlHttp.responseText;
				document.getElementById('log').innerHTML = result;
	       	} else {
	       		document.getElementById('log').innerHTML = '<span class=\"error\">Failed to get success message!<br />' + xmlHttp.statusText + '</span>';
	       	}
		}
	};
	
	xmlHttp.open("GET", encodeURI(context + '/do?action=showSuccessMessage&buttonName=' + buttonName), true);
	xmlHttp.send(null);	
	
}

/*
 * ---------------------------------------------------------------------------
 */

function deleteLogMessage() {
	
	document.getElementById('log').innerHTML = '&nbsp;';
	
	var xmlHttp = createXmlHttpRequest();
	
	xmlHttp.onreadystatechange = function() { 
		if (xmlHttp.readyState == 4) {
			// nada
		}
	};
	
	xmlHttp.open("GET", encodeURI(context + '/do?action=deleteLastLogMessage'), true);
	xmlHttp.send(null);	
	
}

/*
 * ---------------------------------------------------------------------------
 */

function saveLastActivatedTab(tabName) {
	
	var xmlHttp = createXmlHttpRequest();
	
	xmlHttp.onreadystatechange = function() { 
		if (xmlHttp.readyState == 4) {
			// nada
		}
	};
	
	xmlHttp.open("GET", encodeURI(context + '/do?action=saveLastActivatedTab&tabName=' + tabName), true);
	xmlHttp.send(null);	
	
}

/*
 * ---------------------------------------------------------------------------
 */

function convertDate(year, month, day, format, toField) {
	
	var xmlHttp = createXmlHttpRequest();
	
	xmlHttp.onreadystatechange = function() { 
		if (xmlHttp.readyState == 4) {
			if (xmlHttp.status == 200) {
				// write new date to field
				document.getElementById(toField).value = xmlHttp.responseText;
				document.getElementById(toField + '_errorLabel').innerHTML = '';
			} else {
				// leave field untouched but write error to log div
				document.getElementById('log').innerHTML = '<span class=\"error\">Failed to convert date ' + month + '/' + day + '/' + year + ' to format ' + format + '!</span>';
			}
		}
	};
	
	xmlHttp.open("GET", encodeURI(context + '/do?action=convertDate&year=' + year + '&month=' + month + '&day=' + day + '&format=' + format), true);
	xmlHttp.send(null);	
	
}

/*
 * ---------------------------------------------------------------------------
 */

function validate(inputId, validatorRegex) {
	
	var string = document.getElementById(inputId).value;
	string = escape(encodeURI(string));
	string = string.replace(/\+/g, '%252B');

	var xmlHttp = createXmlHttpRequest();
	
	xmlHttp.onreadystatechange = function() { 
		if (xmlHttp.readyState == 4) {
			if (xmlHttp.status != 200) {
				document.getElementById(inputId + '_errorLabel').innerHTML = xmlHttp.statusText;
				errorOnConfig = true;
			} else {
				document.getElementById(inputId + '_errorLabel').innerHTML = '';
			}
		}
	};
	
	xmlHttp.open("POST", encodeURI(context + '/do'), true);
	xmlHttp.setRequestHeader(
		"Content-Type",
      	"application/x-www-form-urlencoded");
	xmlHttp.send('action=validate&string=' + string + '&regex=' + validatorRegex + '');
	
}

/*
 * ---------------------------------------------------------------------------
 */

GB_showCenterWithReload = function(caption, url, /* optional */ height, width, callback_fn) {
    var options = {
        caption: caption,
        center_win: true,
        height: height || 500,
        width: width || 500,
        fullscreen: false,
        callback_fn: callback_fn,
        reload_on_close: true
    }
    var win = new GB_Window(options);
    return win.show(url);
}

