var WSErrorString1 = '';
var WSErrorString2 = '';
var B_ajaxSubmit = true;

function WSValidateForm(theForm) {
	if (typeof(B_debug) != "undefined" && B_debug) alert('WSValidateForm');

	var err1 = null;
	var err2 = null;
	var ajaxResult = null;

	if (typeof(B_checkRequired) != "undefined" && B_checkRequired)
		err1 = WSCheckRequired(theForm);

	if (typeof(B_checkFilters) != "undefined" && B_checkFilters)
		err2 = WSCheckFilters(theForm);

	if (err1 != null) {
		alert(WSErrorRequired.replace(/%LABEL/, WSErrorString1));
		if (theForm.elements[WSFormInputs[err1]].type == 'text' ||
			theForm.elements[WSFormInputs[err1]].type == 'textarea' || 
			theForm.elements[WSFormInputs[err1]].type == 'password' || 
			theForm.elements[WSFormInputs[err1]].type == 'file' || 
			theForm.elements[WSFormInputs[err1]].type == 'select')
			theForm.elements[WSFormInputs[err1]].focus();
		return false;
	}
	if (err2 != null) {
		alert(WSErrorValid.replace(/%LABEL/, WSErrorString2));
		if (theForm.elements[WSFormInputs[err2]].type == 'text' ||
			theForm.elements[WSFormInputs[err2]].type == 'textarea' || 
			theForm.elements[WSFormInputs[err2]].type == 'password' || 
			theForm.elements[WSFormInputs[err2]].type == 'file' || 
			theForm.elements[WSFormInputs[err2]].type == 'select')
			theForm.elements[WSFormInputs[err2]].focus();
		return false;
	}

	if (typeof(WSSuccessMessage) != "undefined")
		alert(WSSuccessMessage);

	if (typeof(B_useAjax) != "undefined" && B_useAjax) {
        	var WSFilteredBuffer = WSCreateFilteredBuffer(theForm);
		// This will be false if there are any file upload fields
		if (B_ajaxSubmit && ajaxFunction(theForm, WSFilteredBuffer) != false) {
			return false;
		}
	}

	return true;
}

function WSCheckRequired(theForm) {
	if (typeof(B_debug) != "undefined" && B_debug) alert('WSCheckRequired');

	var t_str = '';
	var e_id = null;
	WSErrorString1 = '';

	for (var a = 0; a < WSFormRequired.length; a++) {
		theInput = theForm.elements[WSFormInputs[WSFormRequired[a]]];
		t_str = '';

		if (theInput.type == 'select-one' || theInput.type == 'select-multiple') {
			for (var b = 0; b < theInput.options.length; b++) {
				if (theInput.options[b].selected)
					t_str = t_str + theInput.options[b].value;
			}
		}
		else if (theInput.length > 1) {
			//else if (theInput.type == 'checkbox' || theInput.type == 'radio') {
			for (var b = 0; b < theInput.length; b++) {
				if (theInput[b].checked)
					t_str = t_str + theInput[b].value;
			}

		}
		else
			t_str = theInput.value;

		if (t_str.replace(/(^\s*|\s*$)/g, '').length == 0) {
			if (!e_id) e_id = WSFormRequired[a];
			WSErrorString1 += (WSErrorString1.length ? ', ' : '') + WSFormLabels[WSFormRequired[a]];
		}
	}

	return e_id;
}

function WSCheckFilters(theForm) {
	if (typeof(B_debug) != "undefined" && B_debug) alert('WSCheckFilters');

	var t_str = '';
	var e_id = null;
	WSErrorString2 = '';

	for (var a = 0; a < WSFormInputs.length; a++) {
		theInput = theForm.elements[WSFormInputs[a]];
		t_str = '';

		if (theInput.type == 'select-one' || theInput.type == 'select-multiple') {
			for (var b = 0; b < theInput.options.length; b++) {
				if (theInput.options[b].selected) {
					t_str = theInput.options[b].value;
					if (t_str.length > 0 && t_str.search(WSFormFilters[a]) == -1)
						return a;
				}
			}
		}
		else if (theInput.length > 1) {
			for (var b = 0; b < theInput.length; b++) {
				if (theInput[b].checked) {
					t_str = theInput[b].value;
					if (t_str.length > 0 && t_str.search(WSFormFilters[a]) == -1)
						return a;
				}
			}

		}
		else {
			theInput.value = theInput.value.replace(/(^\s*|\s*$)/g, '');
			t_str = theInput.value;
			if (t_str.length > 0 && t_str.search(WSFormFilters[a]) == -1) {
				if (!e_id) e_id = a;
				WSErrorString2 += (WSErrorString2.length ? ', ' : '') + WSFormLabels[a];
			}
		}
	}

	return e_id;
}

function WSSetSelected(theInput, theValue) {
	if (typeof(B_debug) != "undefined" && B_debug) alert('WSSetSelected');

	for (var a = 0; a < theInput.options.length; a++) {
		if (theInput.options[a].value == theValue) {
			theInput.options[a].selected = true;
			break;
		}
	}
}

function WSCreateFilteredBuffer(theForm) {
	if (typeof(B_debug) != "undefined" && B_debug) alert('WSCreateFilteredBuffer');

	var t_str = '';
	var t_name = '';
	var result = '';

	for (var a = 0; a < theForm.elements.length; a++) {
		theInput = theForm.elements[a];
		t_str = '';

		if (theInput.name == 'success_url' || theInput.name == 'failure_url')
			continue;

		// If there are any file upload fields, we can't submit
		// using ajax because javascript cannot access local files
		if (theInput.type == 'file')
			B_ajaxSubmit = false;

		if (theInput.type == 'select-one' || theInput.type == 'select-multiple') {
			t_name = theInput.name;
			for (var b = 0; b < theInput.options.length; b++) {
				if (theInput.options[b].selected)
					t_str = t_str + theInput.options[b].value;
			}
		}
		else if (theInput.length > 1) {
			t_name = theInput[0].name;
			for (var b = 0; b < theInput.length; b++) {
				if (theInput[b].checked)
					t_str = t_str + theInput[b].value;
			}

		}
		else if (theInput.type == 'checkbox' || theInput.type == 'radio') {
			t_name = theInput.name;
			if (theInput.checked)
				t_str = t_str + theInput.value;
		}
		else {
			t_name = theInput.name;
			t_str = theInput.value;
		}

		if (t_str) {
			result += (result.length ? '&' : '');
			result += escape(t_name) + '=' + escape(t_str);
		}
	}

	return result;
}

function ajaxFunction(theForm, theData) {
	if (typeof(B_debug) != "undefined" && B_debug) alert('ajaxFunction');

	var xmlHttp;
	var theUrl = theForm.action;

	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
		// In order to avoid a syntax error in Firefox, 
		// if the returned content is NOT valid XML, use the 
		// overrideMimeType method to set the content-type.
		xmlHttp.overrideMimeType('text/html');
	}
	catch (e) {
		// Internet Explorer
		try {
			xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
		}
		catch (e) {
			try {
				xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
			}
			catch (e) {
				// Browser doesn't support AJAX
				return false;
			}
		}
	}

	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4) {
			// Get the data from the server's response
			if (xmlHttp.responseText.match("success") != null) {
				ajaxDoSuccess(theForm);
			}
			else {
				ajaxDoError(theForm, xmlHttp.responseText);
			}
		}
	}

	if (typeof(B_debug) != "undefined" && B_debug) alert(theUrl);
	if (typeof(B_debug) != "undefined" && B_debug) alert(theData);

	xmlHttp.open('POST', theUrl, true);
	if (typeof(B_debug) != "undefined" && B_debug) alert('xmlHttp.open');
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", theData.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.send(theData);
	return true;
}

function loadXML(url, callback, method, data)
{
	var xmlHttp = '';

	if (!data && !method)
		method = 'GET';

	if (!data)
		data = '<foo></foo>';

	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
		// In order to avoid a syntax error in Firefox,
		// if the returned content is NOT valid XML, use the
		// overrideMimeType method to set the content-type.
		xmlHttp.overrideMimeType('text/html');
	}
	catch (e) {
		// Internet Explorer
		try {
			xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
		}
		catch (e) {
			try {
				xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
			}
			catch (e) {
				// Browser doesn't support AJAX
				return false;
			}
		}
	}

	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4) {
			callback(xmlHttp.responseText, url);
		}
	}

	xmlHttp.open(method, url, true);
	xmlHttp.send(data);
}


function ajaxDoSuccess(theForm) {
	if (typeof(B_debug) != "undefined" && B_debug) alert('ajaxDoSuccess');

	var defSuccessMsg = 'Thank you!'

        if (typeof(B_ajaxSuccessAlert) == "undefined" || B_ajaxSuccessAlert) {
		// We want to alert() the message
		if (document.getElementById('formSuccess') != null && document.getElementById('formSuccess').innerHTML)
			alert(document.getElementById('formSuccess').innerHTML);
		else
			alert(defSuccessMsg);
	}
        else if (document.getElementById('formSuccess') != null && document.getElementById('formSuccess').innerHTML && document.getElementById('formContents') != null) {
		// Else, if the div is there, put it inline
		document.getElementById('formContents').innerHTML = document.getElementById('formSuccess').innerHTML;
	}
	else if (typeof(theForm.success_url) != "undefined" && theForm.success_url.value) {
		// Else, if the form param is there, redirect
		location.href = theForm.success_url.value;
	}
	else {
		// Otherwise, alert a default msg
		alert(defSuccessMsg);
	}
}

function ajaxDoError(theForm, theError) {
	if (typeof(B_debug) != "undefined" && B_debug) alert('ajaxDoError');

    if (typeof(B_ajaxErrorAlert) == "undefined" || B_ajaxErrorAlert) {
	// If we want to alert() the message
        alert(theError);
	}
    else if (document.getElementById('formError') != null) {
	// Else, if the div is there, put it inline
	    document.getElementById('formError').innerHTML = theError;
	}
	else if (typeof(theForm.failure_url) != "undefined" && theForm.failure_url.value) {
	// Else, if the form param is there, redirect
	    location.href = theForm.failure_url.value+"?error_msg="+encodeURI(theError);
	}
	else {
		// Otherwise, alert the message
		alert(theError);
	}
}


// Return a query string value by parameter
function getQueryParam(p) {
	var qs = window.location.search.substring(1);
	var params = qs.split('&');
	for (var i = 0; i < params.length; i++) {
		var keyval = params[i].split('=');
		if (keyval[0] == p) {
			return unescape(keyval[1]);
		}
	}
	// Return "null" if no parameter has been found
	return '';
}

// Set form fields from query parameters
function setFormFields(f) {
	var qs = window.location.search.substring(1);
	var theForm = document.getElementById(f);
	if (!theForm) return;

	for (var i = 0; i < theForm.elements.length; i++) {
		var e = theForm.elements[i];
		if (e.type == 'text') {
			var val = getQueryParam(e.name);
			if (val)
				e.value = val;
		}
	}
}

