////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//-file: ipmsvalidation.js
//-author : ethan lu
//-create : 03/13/2006
//-description: this file implements IPMS validation functions for landing pages. upon form submission, validation will
// be executed. all validation must pass inorder for the form to be submitted.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//-global variables
var formObject = null;
var validationList = null;
var ipmsRequest = null;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//-public functions

//-called first to setup the entire ipms validation system
//-input: form name
//-output: returns nothing on success. alert message displayed on browser is error occurred.
function initializeIPMSValidation(fName)
{
	if (document.forms[fName] == null)	//-make sure form exists
	{
		alert('Form "' + fName + '" does not exist! Validation intialization failed!');
		return false;
	}

	formObject = document.forms[fName];
	validationList = new Array();

  	for (i = 0; i < formObject.elements.length; i++)
  	{
  		//added if condition to avoid fieldset error alert
		if(formObject.elements[i].name)
		{
  			addValidation(formObject.elements[i].name, formObject.elements[i].type, 'ipms', '');
		}
  	}

	formObject.onsubmit = runValidations;
	return true;
}

//-inserts a new field validation to the validationList
//-input:
//	fldname			: name of the form field
//	fldtype			: form field type. must be one of the following value (text,radio,checkbox,select-one,select-multiple)
//	validtype		: validation type determines how to validate the field value. validation types are:
//                        'req' : checks if field value is not empty or has default value
//	errormsg		: alert message if field validation fails
//-output: returns nothing on success. alert message if error occurs.
function addValidation(fldname,fldtype,validtype,errormsg)
{
	//-make sure field name exists and field type matches
	if ((fldtype != 'function') && (formObject[fldname] == null))
	{
		alert('Form field "' + fldname + '" does not exist! Field validation not added!');
		return;
	}

  	if (validationList.length == 0)
  	{
	    var v = new Object();
	    v.fieldname = fldname;
	    v.fieldtype = fldtype;
	    v.validationtype = validtype;
	    v.message = errormsg;

  	    validationList.push(v);	//-add validation to the list
  	}
  	else
  	{
   	   last = 0;
   	   if (validationList.length > 1)
  	   {
  	       last = validationList.length - 1;
  	   }
  	
  	   if (validationList[last].fieldname != fldname)
  	   {
	      var v = new Object();
	      v.fieldname = fldname;
	      v.fieldtype = fldtype;
	      v.validationtype = validtype;
	      v.message = errormsg;

  	      validationList.push(v);	//-add validation to the list
	   }
	}

	return;
}

//-executes validations on all fields in validationList and thn runs ipms validations
//-if all fields are valid, submits form. otherwise, display invalid messages.
function runValidations()
{
	var valid = true;
	var invalidmessages = "";

	for (var v in validationList)
	{
		if (validationList[v].validationtype == 'req')
		{
			if (isEmpty(validationList[v]))
			{
				valid = false;
				invalidmessages += validationList[v].message + "\n";
			}
		}
	}

	if (!valid)	//-all fields are valid, submit form
	{
		alert(invalidmessages);
		return false;
	}
	else
	{
		//-initialize xmlhttprequest object
		try
		{
			ipmsRequest = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
			ipmsRequest.onreadystatechange = ipmsResponseHandler;
		}
		catch (e)
		{
			ipmsRequest = null;
		}

		if (ipmsRequest != null)	//-run ipms validation if able
		{
			//alert(buildParamString());
			//-update the error section of the landing page to display the errors
			var errorObj = document.getElementById('errorsection');
			if (errorObj != null)
				errorObj.innerHTML = "validating...";

			//ipmsRequest.open('GET','validationWrapper.php?timestamp=' + new Date().valueOf() + '&xmlstring=' + buildParamString(),true,'','');
			//ipmsRequest.send(null);
			var debug = '';
			if(document.getElementById('debug_id')){
				if(document.getElementById('debug_id').value==1){
					debug = '&debug=1';
				}
			}
			ipmsRequest.open('POST','/offers/validationWrapper.php?timestamp=' + new Date().valueOf()+debug,true,'','');
			ipmsRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			ipmsRequest.send('&params='+buildParamString());
			return false;
		}
		else	//-otherwise, submit form
		{
			formObject.submit();
			return true;
		}
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//-private functions

//-given the field validation object, runs simple javascript validation based on the field type and validation type
//-returns true if valid, false otherwise
function isEmpty(v)
{
	switch (v.fieldtype)
	{
		case 'text' :
		case 'hidden' :
		case 'textarea':
			return (formObject[v.fieldname].value == '');
			break;
		case 'checkbox' :
		case 'radio' :
			//-radio/checkboxes have similar structure. if more than one radio/checkbox option...a nodelist is created
			if (typeof(formObject[v.fieldname].type) == 'undefined')
			{
				//-radio/check button is empty if none of the options is selected
				var hasCheck = false;
				for (var i = 0; i < formObject[v.fieldname].length ; i++)
					hasCheck = hasCheck | formObject[v.fieldname].item(i).checked;
				return !hasCheck;
			}
			else if ((formObject[v.fieldname].type == 'radio') || (formObject[v.fieldname].type == 'checkbox'))	//-radio/checkbox only has one option
				return !formObject[v.fieldname].checked;
			else
				return true;
			break;
		case 'select-one' :	//-assumes select boxes have a default option value as first option
			return ((formObject[v.fieldname].selectedIndex == 0) && (formObject[v.fieldname].options[formObject[v.fieldname].selectedIndex].value == 'select'));
			break;
		case 'select-multiple' : //-assumes select boxes have a default option as first option
				return (formObject[v.fieldname].selectedIndex <= 0);
			break;
		default :
			return true;
	}
	return true;
}

function buildParamString()
{
	var xmlstring = '<xml>';

	if (formObject['IPMS_Client_ID'] != null)
		xmlstring += '<campaign>' + formObject['IPMS_Client_ID'].value + '<\/campaign>';
	else
		xmlstring += '<campaign>0<\/campaign>';

	xmlstring +='<fields>';
	for (var v in validationList)
	{
		xmlstring += '<' + validationList[v].fieldname.replace(/\[\]/g,'') + '>';
		xmlstring += '<type>' + validationList[v].fieldtype + '<\/type>';
		xmlstring +='<values>';

		switch (validationList[v].fieldtype)
		{
			case 'checkbox' :
			case 'radio' :
				//-radio/checkboxes have similar structure. if more than one radio/checkbox option...a nodelist is created
				if (typeof(formObject[validationList[v].fieldname].type) == 'undefined')
				{
					for (var i = 0; i < formObject[validationList[v].fieldname].length ; i++)
						if (formObject[validationList[v].fieldname].item(i).checked)
							xmlstring += '<value>' + escape(formObject[validationList[v].fieldname].item(i).value) + '<\/value>';
				}
				else
						if (formObject[validationList[v].fieldname].checked)
					                xmlstring += '<value>' + escape(formObject[validationList[v].fieldname].value) + '<\/value>';
				break;
			case 'select-one' :	//-assumes select boxes have a default option value as first option
			case 'select-multiple' : //-assumes select boxes have a default option as first option
				for (var i = 0; i < formObject[validationList[v].fieldname].length; i++)
				{
					if (formObject[validationList[v].fieldname].options){
						if (formObject[validationList[v].fieldname].options[i].selected)
							xmlstring += '<value>' + escape(formObject[validationList[v].fieldname].options[i].value) + '<\/value>';
					}
					else{
						xmlstring += '<value>' + escape(formObject[validationList[v].fieldname].value) + '<\/value>';
					}
				}
				break;
			case 'text' :
		        case 'hidden' :
		        case 'textarea':
			default :
				xmlstring += '<value>' + escape(formObject[validationList[v].fieldname].value) + '<\/value>';
				break;
		}

		xmlstring +='<\/values>';
		xmlstring += '<\/' + validationList[v].fieldname.replace(/\[\]/g,'') + '>';
	}
	xmlstring +='<\/fields>';
	xmlstring += '<\/xml>';

	return xmlstring;
}

//-sends xmlhttprequest to ipms server to run custom validation on the given campaign
function ipmsResponseHandler()
{
	if ((ipmsRequest.readyState == 4) && (ipmsRequest.status == 200))
	{
		//alert('readyState : ' + ipmsRequest.readyState + '\nstatus : ' + ipmsRequest.status + ' - ' + ipmsRequest.statusText + '\n' + 'response : ' + ipmsRequest.responseText);
		//alert('readyState : ' + ipmsRequest.readyState + '\nstatus : ' + ipmsRequest.status + ' - ' + ipmsRequest.statusText + '\n' + 'response : ' + ipmsRequest.responseXML);
		var rcode = ipmsRequest.responseXML.getElementsByTagName("code").item(0).firstChild.nodeValue;
		var rtype = ipmsRequest.responseXML.getElementsByTagName("type").item(0).firstChild.nodeValue;

		if (rcode == 1)	//-if return code is 1, then validation was successful, submit form
		{
			//-submit form
			formObject.submit();
			return true;
		}
		else	//-return code is 0, display error
		{
			var rmessage = ipmsRequest.responseXML.getElementsByTagName("message");
			var errormsg = '';
			for (var i = 0; i < rmessage.length; i++)
				errormsg += rmessage[i].firstChild.nodeValue + "\n";
				//errormsg += '-' + rmessage[i].firstChild.nodeValue + '<BR>';

			//-update the error section of the landing page to display the errors
			var errorObj = document.getElementById('errorsection');
			if (errorObj != null)
			{
				//errorObj.innerHTML = errormsg;
				//window.scrollTo(0,0);	//-scroll to top of page so user can see error messages
				errorObj.innerHTML = '';
				alert(errormsg);
			}

			return false;
		}
	}

	return false;
}