	var pageNumber = 1;
	var isValidated = false;

	/* 
		This function enables or disables the navigation buttons 
		based on the page count in the current form and the current page position
	*/
	function EnableDisableButtons()
	{
		var nextButton = document.getElementById("dmFormNavigationNext");
		var prevButton = document.getElementById("dmFormNavigationPrevious");
		
		if (nextButton != null && prevButton != null)
		{
			// If the current page equals the maxpage of the form, disable "Next" button
			if (parseInt(pageNumber,10) == parseInt(formsPages,10))
				nextButton.disabled = true;
			else
				nextButton.disabled = false;
			
			// If the current page is the first page of the form, disable "Prev" button
			if (parseInt(pageNumber,10) == 1)
				prevButton.disabled = true;
			else
				prevButton.disabled = false;
		}
	}
	
	/*
		This function shows the DIV corresponding to the current page. 
		After displaying the page contents, "EnableDisableButtons" is called to show or hide navigation buttons.
	*/
	function PageNavigation()
	{
		var curDiv = document.getElementById(formsClientId + '_Page' + pageNumber);
		curDiv.style.display ="inline";
		EnableDisableButtons();	
		
		var currentPageLabel = document.getElementById(formsClientId + "_CurrentPage");
		if (currentPageLabel != null)
		{
			currentPageLabel.innerHTML = ReplacePlaceholder(textFormPageLabel, pageNumber, formsPages);
		}
	}

	/*
		This function is called when the user clicks the "Prev" page button.
		1. Validates the input in the current page and if there are no errors.
		2. Decrements the page number by 1 to denote the new current page.
		3. Calls the "PageNavigation" function to display the content of the current page.
	*/
	function PrevPage() {
		if (validateFormInputs(pageNumber))
		{
			if (pageNumber >1) {
				var curDiv = document.getElementById(formsClientId + '_Page' + pageNumber);
				curDiv.style.display="none";
				pageNumber --;
			}
			
			PageNavigation();
			
		}
		return false;
	}
	
	/*
		This function is called when the user clicks the "Prev" page button.
		1. Validates the input in the current page and if there are no errors.
		2. Increments the page number by 1 to denote the new current page.
		3. Calls the "PageNavigation" function to display the content of the current page.
	*/
	function NextPage()
	{
		if ( validateFormInputs(pageNumber) )
		{
			if (pageNumber < formsPages)
			{
				var curDiv = document.getElementById(formsClientId + '_Page' + pageNumber);
				curDiv.style.display="none";
				pageNumber ++;
			}
			
			PageNavigation();
			
		}
		
		return false;
	}
/************ START Default button Logic ***************/
var submitButtonRef = null;
var formClientId = "";
function initDefaultButton(node, first)
{
/*	Javascript support only.
* 1. loop all children of wrapping form markup
* 2. if element is of any "form" type, like input, select ect. add an onKeyPress event to click the submit button
* 3. Except if the "form" type element is of type "submit", then save a reference to this field in a gloval JS variable
* 4. the onKeyUp function runs the "click" command on the submit button.
*/
	if(node)
	{
		if(first)
		{
			formClientId = node.id;
			if(!formClientId)
				formClientId = "";
			// Set hidden-field "submitButtonRef" to false (and again to true when form is submitted)
			document.getElementById("dmFormSubmitStatus"+ formClientId).value = "false";
		}
		for(var i=0; i<node.childNodes.length; i++)
		{
			if(node.childNodes[i].tagName)
			{
				if(node.childNodes[i].tagName.toLowerCase() == "input")
				{
					var inputType = node.childNodes[i].type.toLowerCase();
					
					if(inputType == "submit")
					{
						submitButtonRef = node.childNodes[i];
						node.childNodes[i].setAttribute("formClientId", formClientId); // support for multiple forms on same page
					}
					else if(inputType != "button")
					{
						if(node.childNodes[i].addEventListener)
							node.childNodes[i].addEventListener('keypress', dmTrySubmit, false);
						else
							node.childNodes[i].attachEvent("onkeypress", dmTrySubmit);
					}
				}
				else
				{
					initDefaultButton(node.childNodes[i], false);
				}
			}
		}
	}
}

/************ END Default button Logic ***************/
/*
	This function is called when the user submit the form.
*/
function SaveForm()
{
	if (validateFormInputs(null))
	{
		document.getElementById("dmFormSubmitStatus").value = "true";
		document.forms[0].submit();
	}
}

function SaveFormSubmit(evt, srcObj)	// srcObj --> to have support for multiple forms on same page.
{
	if(!srcObj)
	{
		if (!evt) var evt = window.event;
		srcObj = (evt.target) ? evt.target : evt.srcElement;
	}
	var clientFormId = "";
	if(srcObj)
	{
		clientFormId = srcObj.getAttribute("formClientId");
		if(!clientFormId)
			clientFormId = "";
	}
	if (validateFormInputs(null))
	{
		document.getElementById("dmFormSubmitStatus"+ clientFormId).value = "true";
		return true;
	}
	else
	{
		return false;
	}
}

/*
This function is called to check for valid inputs on the page. This is called during each page
navigation and also during form submit.

1. It gets all the elements in the form into a collection.
2. Filters the elements on the current page from this collection.
3. Validates each of those elements, displaying the error message if any or performing 
	the requested navigation/ submit initiated by the user.
*/
function validateFormInputs(pageToValidate)
{
	var errValidation = "";	
	var ValidationStatus = true;
	isValidated = false;
	
	var validatedElements = ",";
	
	// Loop through all the elements.
	for(var i = 0; i < document.forms[0].elements.length; i++)
	{
		var validationResult = null;
		
		// Get a reference to the input element.
		var element = document.forms[0].elements[i];
		
		// If there is no name specified, just move to next.
		if (element != null && element.name != null && element.name.length == 0)
			continue;
		
		// This is on save, validate every page.
		if (pageToValidate == null || pageToValidate < 1)
		{
			// Only validate same items once. This check is used for groups of radio or checkboxes.
			if (validatedElements.indexOf(element.name) == -1)
			{
				validationResult = ValidateInput(element);
				validatedElements += element.name + ",";
			}
		}
		else
		{
			// Only validate the selected page items.
			if (element.name.indexOf("p" + pageToValidate) == 0)
			{
				// Only validate same items once. This check is used for groups of radio or checkboxes.
				if (validatedElements.indexOf(element.name) == -1)
				{
					validationResult = ValidateInput(element);
					validatedElements += element.name + ",";
				}
			}
		}
		
		// If the result is other than empty, we'll put it in the list of messages.
		if (validationResult != null)
		{
			errValidation += "\n"+ validationResult;
		}
	}
	
	// Alert if there are errors and return false.	
	if (errValidation != null && errValidation  != "")
	{
		alert(errValidation)
		ValidationStatus = false;
	}
	
	return ValidationStatus;
}



/*
	This function that gets called to validate the input on each of the controls that need to be validated.
	This function checks if the control is a mandatory, the checks for the input conformity with the data type 
*/
function ValidateInput(element)
{
	if (element == null)
		return;

	// Skip any input elements that we are not validating.
	if (element.type == "hidden" || element.type == "reset" || element.type == "submit")
		return;
	
	var errorObject;
	var errMessage = "";
	var firstFailedObject;
	var elementDataTypeId = element.getAttribute("DataTypeID");
	var elementRequired = element.getAttribute("required");
	
	// Check for required field
	if (elementRequired != null && elementRequired == "1")
	{
		errMessage = validRequired(element);
	}
	
	// If the input type is textarea, check if the lenght of data is withing the maxlength of the field.
	if (element.type  == "textarea"  && element.maxLength < element.value.length)
	{ 
		errMessage = "Please make the input " + element.maxLength + " characters or less and submit the form again.";
	}
	
	// Check if the field is an integer
	if (elementDataTypeId == "2" && (elementRequired == "1" || element.value.length > 0))
	{
		errMessage = validateInteger(element);
	}
	
	// Check for decimal values
	if (elementDataTypeId == "3" && (elementRequired == "1" || element.value.length > 0))
	{
		errMessage = validateDecimal(element);
	}
	
	// Check for email 
	if (elementDataTypeId == "8" && (elementRequired == "1" || element.value.length > 0))
	{
		errMessage = validEmail(element);
	}

	// Check for URL
	if (elementDataTypeId == "9" && (elementRequired == "1" || element.value.length > 0))
	{
		errMessage = validateURL(element);
	}
	
	// Check for the first control that failed validation and set focus to the control.
	if (!isValidated && errMessage != null && typeof(errMessage) != "undefined" && errMessage != "")
	{
		try
		{
			element.focus();
		}
		catch(ex)
		{
			try
			{
				//it's not on the same page
				var temp = element.getAttribute("name");
				if(temp)
				{
					temp = temp.substring(1, temp.indexOf("_"));
					if(temp != pageNumber)
					{
						//it's on different page.
						errMessage = errMessage + ' (Page ' + temp + ')';
					}
				}
			}
			catch(ex){}
		}
		isValidated = true;
	}

	if (errMessage != null && errMessage != "")
	{
		return errMessage;
	}
	
	return null;
}

/*
	This function validates the input to a standard email format. It uses a regular expression to 
	check for email syntax
*/
function isEmailAddr(email)
{
	var result = false;
	var theStr = new String(email);
	var index = theStr.indexOf("@");
	if (index > 0)
	{
		var pindex = theStr.lastIndexOf(".");
		if ((pindex > index+1) && (theStr.length > pindex+1) && (parseInt(theStr.length - pindex) >=3 && parseInt(theStr.length - pindex) <=4 ) )
			result = true;
	}
	return result;
}

function validateURL(element)
{
	regExURL = /http:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/gi;
	if (! regExURL.test(element.value))
	{
		retMessage = element.getAttribute("ErrorText");
		
		if (retMessage != null && retMessage != "")
			return retMessage;
		else
			return "Please enter the URL field in correct format.";
	}
	return null;
}

function validEmail(element)
{
	var fieldValue = element.value;
	var retMessage = "";
	
	if ((fieldValue.length < 3) || !isEmailAddr(fieldValue))
	{
		retMessage = element.getAttribute("ErrorText");
		
		if (retMessage == null)
			retMessage = "Please enter email in correct format. Email must have '@' and '.' characters.";
	}
	
	if (retMessage  != "")
	{
		return retMessage ;
	}
}

/*
	This function validate mandatory control for valid input. Valid input means non white space input.	
*/
function validRequired(element)
{
	// The return message.
	var retMessage = "";
	
	// See if the input is checkbox.
	if (element.id.indexOf("chk") == 0)
	{
		// Flag to indicate whether any checkboxes are checked.
		var isChecked = false;
		
		// Get all the elements for a specified checkbox.
		var elements = document.getElementsByName(element.name);
		
		// Loop through all fields and validate.
		for(var i = 0; i < elements.length; i++)
		{
			// Validate if the item is checked.
			if (elements[i].checked)
			{
				// Something is checked so make sure we don't return error message.
				isChecked = true;
			}
		}
		
		// If nothing is checked, return the error message.
		if (!isChecked)
		{
			retMessage = elements[0].getAttribute("ErrorText");
			if (retMessage == null || retMessage == "")
				retMessage = "Required checkbox is not selected.";
		}
	}
	else
	{
		// Regular expression to check against.
		var regEx = / /gi;
	
		// Validate the input against the regular expression.
		if (element.value.replace(regEx,"") == "")
		{
			// Read the error text from the FIRST input field.
			var elements = document.getElementsByName(element.name);
			retMessage = elements[0].getAttribute("ErrorText");
		}
	}
	
	// If the return message is specified, return it.
	if (retMessage != "")
		return retMessage;
	
	return null;
}

// This function validates for an Inter number and returns an erorr if the input is not an Integer
function validateInteger(element)
{
	var retMessage = "";
	
 	regEx = /(^[-]?\d+$)/;
	if (! regEx.test(element.value))
	{
		retMessage = element.getAttribute("ErrorText");
		
		if (retMessage != null && retMessage != "")
			return retMessage;
		else
			return "Please input the number field in a correct format.";
	}
	
	return null;
}

// This function validates for Decimal number and returns an erorr if the input is not a decimal
function validateDecimal(element)
{
	var retMessage = "";
	
	/*
	Description:  A regular expression that matches numbers. Integers or decimal numbers with or without the exponential form. 

	Matches:  [23], [-17.e23], [+.23e+2]  
	Non-Matches:  [+.e2], [23.17.5], [10e2.0]  
	*/
	
 	regEx = /^[+-]?([0-9]*[\.\,]?[0-9]+|[0-9]+[\.\,]?[0-9]*)([eE][+-]?[0-9]+)?$/;
	if (! regEx.test(element.value))
	{
		retMessage = element.getAttribute("ErrorText");
		
		if (retMessage != null && retMessage != "")
			return retMessage;
		else
			return "Please input the decimal field in a correct format.";
	}
	
	return null;
}


function PageValues()
{
	var xmlControl;
	var docElement;
	var xmlParser = null;
	var xmlRoot = null;
	var isIE = (typeof(DOMParser) == "undefined");
	var isOpera = (navigator.userAgent.indexOf("Opera") >= 0);
	if(isIE){
		xmlParser = new ActiveXObject("Msxml2.DOMDocument.3.0");
		if(xmlParser.loadXML(formsRecordXml))
			xmlRoot = xmlParser.documentElement;
	}
	else{
		xmlParser = new DOMParser();
		xmlRoot = xmlParser.parseFromString(formsRecordXml, "text/xml");
		if(xmlRoot.documentElement.nodeName == "parsererror")
			return;
			xmlRoot = xmlRoot.documentElement;
	}

	if(xmlRoot != null)
	{
		for(var i = 0; i < xmlRoot.childNodes.length; i++)
		{
			var inputFieldName = xmlRoot.childNodes[i].nodeName;
			var inputFieldValue = (isIE) ? 
									xmlRoot.childNodes[i].text : 
									(isOpera) ? xmlRoot.childNodes[i].innerHTML
												: (xmlRoot.childNodes[i].nodeValue) ? xmlRoot.childNodes[i].nodeValue
													:	xmlRoot.childNodes[i].textContent;

			var inputFields = document.getElementsByName(inputFieldName);
			if(inputFields.length == 0 && inputFieldName.indexOf("_hid") > 0)
			{
			    var inputFieldId = inputFieldName.substr(inputFieldName.indexOf("_")+1);
			    var inputField = document.getElementById(inputFieldId);
				if(inputField){
					inputFields = [];
					inputFields[0] = inputField;
			    }
			}
			if (inputFields.length > 0)
			{
				if (inputFields[0].tagName == "INPUT")
				{
					var checkedState = "false";
					if (inputFields[0].type == "radio")
					{
						for(var j = 0; j < inputFields.length; j++)
						{
							inputFields[j].checked = (Trim(inputFields[j].value) == Trim(inputFieldValue));
						}
					}
					else if(inputFields[0].type == "checkbox")
					{
						for(var j = 0; j < inputFields.length; j++)
						{
							var inputValue = Trim(inputFields[j].value);
							var checkedState = "false";
							inputFields[j].checked = (inputFieldValue.indexOf(inputValue) > -1);
						}
					}
					else
					{
						if(location.href.toLowerCase().indexOf("/digimaker/") > 0)
							inputFields[0].value = inputFieldValue;
						else if(inputFields[0].type.toLowerCase() != "hidden")
							inputFields[0].value = inputFieldValue;
					}
				}
				else
				{
					var valueExists = false;
			          if(inputFieldName.indexOf("sel") >= 0)
			          {
                        if(inputFields[0].options)
                        {
                            for(var k = 0; k < inputFields[0].options.length; k++)
                            {
                            
                                if(inputFields[0].options[k].value == inputFieldValue)
                                {
                                    valueExists = true
                                    break;
                                }
                            }
                        
                            if(valueExists)
                            {
                                inputFields[0].value = inputFieldValue;
                            }
                            else
                            {
                                if(inputFields[0].value.indexOf("\r") >= 0)
                                {
                                    if(inputFieldValue.indexOf("\r") >= 0)
                                        inputFields[0].value = inputFieldValue;
                                    else
                                        inputFields[0].value = inputFieldValue + "\r";
                                }
                                else
                                    inputFields[0].value = inputFieldValue;
                                }
                            }
                            else
                            {
                            inputFields[0].value = inputFieldValue;
                            }
			          }
			          else
			          {
							inputFields[0].value = inputFieldValue;
					  }
				}
			}
		}
	}
}


function InitializeForms()
{
	// Get all the date type fields based on the name
	var allDateType = document.getElementsByName("p"+ pageNumber +"_datepicker");
	if (allDateType.length > 0)
	{
	// If there are date fields in the current page
		var currentObject;	
		var inputDateField, btnDatePicker,dateFormat ;
		var elementCount = allDateType.length;
		for (i =0; i < elementCount ; i++)
		{
			currentObject = allDateType[i];
			inputDateField = currentObject.getAttribute("datefield");
			btnDatePicker  = currentObject.getAttribute("id");
			dateFormat = unescape(document.getElementById(inputDateField).getAttribute("dateformat"));
			
			Calendar.setup(
			{
				inputField  : inputDateField ,      // ID of the input field
				ifFormat    : ""+dateFormat +"",    // the date format
				button      : btnDatePicker       // ID of the button
				}
			);
		}
	}
}

/// Replicated from digimaker.js
function Trim(s) 
{
	// Remove leading spaces and carriage returns
	while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
		s = s.substring(1,s.length);
	// Remove trailing spaces and carriage returns
	while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
		s = s.substring(0,s.length-1);
	return s;
}

function ReplacePlaceholder(text, args)
{
	for(var i = 0; i < arguments.length; i++)
	{
		text = text.replace("{" + i + "}", arguments[(i + 1)]);
	}
	
	return text;
}

// Bharat : Limit maxlength for textarea
function CheckTextAreaCharLength(element)
{
    var errMessage;
    if ( (event.keyCode == 32) || (event.keyCode == 13) || (event.keyCode > 47)) 
    {
        if(element != null)
        {
           // If the input type is textarea, check if the lenght of data is withing the maxlength of the field.
	        if (element.value.length >= element.maxlength)
	        { 
		        errMessage = "Please make the input " + element.maxlength + " characters or less.";
		        alert(errMessage);
		        if (window.event) 
		        {
                    window.event.returnValue = null;
                }
	        }
	    }
	}
}

