  var req;
  var errorMessageList = "";
  var errorMessageLabel = "";
  var method = "POST";
  var SUCCESS_CODE;
  var ERROR_CODE;
  var MESSAGE_ID;
  var HEADER_MESSAGE_ID = "HeaderMessage";
  var ID_ELEMENT = "id";
  var RESPONSE_ELEMENT = "response";
  var URL_ELEMENT = "url";
  var PARENT_ERROR_ELEMENT = "element";
  var APP_ERROR_ELEMENT = "app_error";
  var CHILD_ERROR_ELEMENT = "page_error";
  var MAX_LIMIT = 0;
  var USED_LIMIT = 0;
  var BALANCE_LIMIT = 0;
  var DAILY_COUNT_ELEMENT = "daily_entry_cnt";
  var USG_COUNT_ELEMENT = "usg_entry_cnt";
  var MAX_LIMIT_ALLOWED = 'true';
  var STATUS_ELEMENT = "status";
  //var captchaURL = "/callmcprm/prmentry/VerifyCaptchaChallengeController";
  //var renderImageURL = "/callmcprm/prmentry/RenderImageCaptchaController?customCfgXML=MC_Captcha_Config";
  var SUCCESS_CODE = "success";
  var ERROR_CODE = "failure";
  var captchaURL = "http://10.158.128.144/prmentry/VerifyCaptchaChallengeController";
  var renderImageURL = "http://10.158.128.144/prmentry/RenderImageCaptchaController?customCfgXML=MC_Captcha_Config";
  var CAPTCHA_STATUS_MESSAGE_ELEMENT = "status-message";
  var urlValue;
  var frmValue;
  var processOpt;
  var captchaImageDisplay = "";
  var ERROR_FONT_COLOR;
  var ACTUAL_FONT_COLOR;
  var ERROR_COLOR_CHAGE_REQD;

  function changeFontColor(frm)
  {
		if(ERROR_COLOR_CHAGE_REQD == undefined || ERROR_COLOR_CHAGE_REQD == null || ERROR_COLOR_CHAGE_REQD == "")
		{
			ERROR_COLOR_CHAGE_REQD = 'false';
		}
		if(ERROR_COLOR_CHAGE_REQD == 'true')
		{
			for(paramCount=0;paramCount<frm.elements.length;paramCount++)
			{
				if(frm.elements[paramCount].type == 'hidden' || frm.elements[paramCount].type == 'text' || frm.elements[paramCount].type == 'select-one' || frm.elements[paramCount].type == 'select-multiple' || frm.elements[paramCount].type == 'checkbox' || frm.elements[paramCount].type == 'radio' || frm.elements[paramCount].type == 'textarea')
				{
					controlName = frm.elements[paramCount].name;
					if(ACTUAL_FONT_COLOR == undefined || ACTUAL_FONT_COLOR == null || ACTUAL_FONT_COLOR == "")
					{
						ACTUAL_FONT_COLOR = "#000000";
					}
					elementObj = frm.elements[controlName];
					if(elementObj.length == undefined)
					{			
						if(document.getElementById(controlName+"Id") != null && document.getElementById(controlName+"Id") != undefined) {
                            	document.getElementById(controlName+"Id").style.color = ACTUAL_FONT_COLOR;
						}
					}
					else if(elementObj.length > 1)
					{
						for(elementCnt=0; elementCnt < elementObj.length; elementCnt++) 
						{  
							if(document.getElementById(controlName+"Id" + elementCnt) != null && document.getElementById(controlName+"Id"+elementCnt) != undefined) {
								document.getElementById(controlName+"Id"+elementCnt).style.color = ACTUAL_FONT_COLOR;
							} else { 
								if(document.getElementById(controlName+"Id") != null && document.getElementById(controlName+"Id") != undefined) {
									document.getElementById(controlName+"Id").style.color = ACTUAL_FONT_COLOR;
								}
							}
						}
					} 					
				}
			}
			if(ERROR_FONT_COLOR == undefined || ERROR_FONT_COLOR == null || ERROR_FONT_COLOR == "")
				ERROR_FONT_COLOR = "#ed1b24";
		}	
  }
  function validatePage(url, frm, butOpt)
  {
	
	 // alert("In validate page frm " + frm);
	changeFontColor(frm); // To change the form field colors when initial load
	//urlValue = url;	
	//url = "http://localhost:9080/InteractivePromotionsWeb/" + url;  //For LOCAL
	url = "/callmcprm/prmentry/" + url; //For DEV WITH PROXY
   // url = "https://www.dev.mastercard.com/callmcprm/prmentry/" + url;
	//url = "http://10.158.128.144/prmentry/" + url; //For DEV NO PROXY  
   //url = "http://localhost:3/prmentry/" + url;  //For LOCAL
	frmValue = frm;
	processOpt = butOpt;
	

	var urlContent = buildRequest(frm);
		
	   	if (window.XMLHttpRequest) 
    	{
  			req = new XMLHttpRequest();
		}
    	else if (window.ActiveXObject) 
    	{ // IE
      		req = new ActiveXObject("Microsoft.XMLHTTP");
    	}
      if(req) 
      {
		try
		{

        		req.onreadystatechange = processStateChange;
				req.open(method, url, false);				
				//req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
				req.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8');

				req.send(urlContent);
				
				if (req.onreadystatechange == null) processStateChange();
		}
		catch(exception)
		{
		}
      }      
  }
   function processStateChange() 
  {
		var displayMessage = "";
		if(document.getElementById(MESSAGE_ID) != null)
			document.getElementById(MESSAGE_ID).innerHTML = "";
		if(document.getElementById(HEADER_MESSAGE_ID) != null)
			document.getElementById(HEADER_MESSAGE_ID).innerHTML = "";
  		if (req.readyState == 4) 
   		{
			if (req.status == 200) 
			{
				
				if(SUCCESS_CODE == undefined || SUCCESS_CODE == null)
					SUCCESS_CODE = "success";
				if(ERROR_CODE == undefined || ERROR_CODE == null)
					ERROR_CODE = "failure";					
				if(MESSAGE_ID == undefined || MESSAGE_ID == null)
					MESSAGE_ID = "message";
        			data = req.responseXML;

			
				errorMessageList = "";
				idTag = data.getElementsByTagName(ID_ELEMENT)[0];
				if(idTag != null)
				{
       				responseTag = data.getElementsByTagName(RESPONSE_ELEMENT)[0];
		
					if (responseTag!=null && responseTag.firstChild.data == SUCCESS_CODE) 
					{
						dailyCount = data.getElementsByTagName(DAILY_COUNT_ELEMENT)[0];
						usgCount = data.getElementsByTagName(USG_COUNT_ELEMENT)[0];
								
						if(dailyCount != null && dailyCount.firstChild != null)
						{
							MAX_LIMIT = dailyCount.firstChild.data;
							if(MAX_LIMIT == '')
							{
								MAX_LIMIT_ALLOWED = 'true';
							}
							if(MAX_LIMIT != '' && isNaN(MAX_LIMIT))
							{
								alert('Usage Entry Maximum limit should be numeric value');
							}
						}
						if(usgCount != null && usgCount.firstChild != null)
						{
							USED_LIMIT = usgCount.firstChild.data;
							if(isNaN(USED_LIMIT))
								alert('Usage Entry Used limit should be numeric value');
						}
						if(dailyCount != null && dailyCount.firstChild != null && usgCount != null && usgCount.firstChild != null)
						{
							if(dailyCount.firstChild.data == '')
							{	
								MAX_LIMIT_ALLOWED = 'true';
							}
							else
							{
								MAX_LIMIT_ALLOWED = 'false';
							}
							BALANCE_LIMIT = MAX_LIMIT - USED_LIMIT;
						}
        				urlTag = data.getElementsByTagName(URL_ELEMENT)[0];
						if(urlTag!=null)
						{
							var successURL =  urlTag.firstChild.data;
							if(processOpt == 'SE' || MAX_LIMIT_ALLOWED == 'true')
							{
								 if(urlTag.firstChild.data.indexOf("addusageentry") != -1) {
									var url = urlTag.firstChild.data;
									var index = url.indexOf("addusageentry.do");
									var urlContent = url.substring((index+16));
									getRequestData('addusageentry.do',document.frm,'SE',null,urlContent);	
								}
								else {
									document.location.href = '../'+urlTag.firstChild.data;
								}							
							}
							else if(MAX_LIMIT_ALLOWED == 'false' && BALANCE_LIMIT > 0)
							{
								document.location.href = '../'+urlTag.firstChild.data+'&balanceCount='+BALANCE_LIMIT;
							}
							else if(dailyCount.firstChild.data != '0' && MAX_LIMIT_ALLOWED == 'false' && BALANCE_LIMIT == 0)
							{
								alert('Sorry, You have already reached the limit of max entries for the day.');
								document.location.href = '../'+urlTag.firstChild.data;
							}
							else
							{
								document.location.href = '../'+urlTag.firstChild.data;
							}
						}
					}
					else if (responseTag!=null && responseTag.firstChild.data == ERROR_CODE) 
					{
	        			urlTag = data.getElementsByTagName(URL_ELEMENT)[0];
        				formErrorTag = data.getElementsByTagName(PARENT_ERROR_ELEMENT);	
						var applnMessageObj = data.getElementsByTagName(APP_ERROR_ELEMENT)[0];
						//alert("applnMessageObj.."+applnMessageObj.firstChild.data);
						if(applnMessageObj!=null && applnMessageObj.firstChild!=null)
						{
							displayMessage = applnMessageObj.firstChild.data;
							document.getElementById(HEADER_MESSAGE_ID).innerHTML = "<b><font size=1 face=arial color='#990000'>"+displayMessage+"</font></b><br/>";// implement stylesheet
						}
						var displayMessageObj = data.getElementsByTagName(CHILD_ERROR_ELEMENT)[0];
						if(displayMessageObj!=null)
						{
							displayMessage = displayMessageObj.firstChild.data;
							if(displayMessage.indexOf("User is not registered")!=-1)
							{
							  	displayMessage = "User is not registered. Please register for this promotion";
							}
							else if(displayMessage.indexOf("User is already registered")!=-1) 
							{
								displayMessage = "You have already registered for this promotion, you need to enter only once. Thank you.";
                            } else if(displayMessage.indexOf("The following fields have invalid")!=-1) {
                                displayMessage = "The following fields have invalid input, please re-enter.";
                             }   
							if(document.getElementById(HEADER_MESSAGE_ID) != null)
							{
								document.getElementById(HEADER_MESSAGE_ID).innerHTML = "<b><font size=1 face=arial color='#990000'>"+displayMessage+"</font></b><br/>";// implement stylesheet
							}
						} 
						for(tagCount=0 ; tagCount < formErrorTag.length ; tagCount++)
						{ 
							buildTable(formErrorTag[tagCount]);
						}
						if(document.getElementById(MESSAGE_ID) != null && formErrorTag.length>0) {
                            if(document.getElementById(HEADER_MESSAGE_ID) != null)
							{
								document.getElementById(HEADER_MESSAGE_ID).innerHTML = "<b><font size=1 face=arial color='#990000'>"+displayMessage+"</font></b><br/>";// implement stylesheet
							}
                            document.getElementById(MESSAGE_ID).innerHTML = "<ul>"+errorMessageList+"</ul>";  
                        }
						if(errorMessageList != null && errorMessageList != "")
						{
							if(frmValue.jcaptcha_response !=undefined && frmValue.jcaptcha_response != null && frmValue.jcaptcha_response.value != "")
							{
								if(document.getElementById("jcaptcha_responseId")!=null && document.getElementById("jcaptcha_responseId") != undefined)
								{
									document.getElementById("jcaptcha_responseId").style.color = ERROR_FONT_COLOR;
								}
							}
						}
						if(frmValue.jcaptcha_response !=undefined && frmValue.jcaptcha_response != null)
							callImageCaptcha(frmValue);							
					}
				}
      		} 
			else 
			{
				  alert("Session has been failed. Please login again.");
    		}
	    }
  } 
  function buildTable(formErrorTag)
  {
		var fieldCount = formErrorTag.childNodes.length;		
		// For Form field color change Starts in the case of validation failure
		if(ERROR_COLOR_CHAGE_REQD == 'true')
		{   
			var tgCnt = formErrorTag.childNodes.length;
			formFieldObj = formErrorTag.childNodes.item(0);
			if(formFieldObj.childNodes.item(0) != null)
			{   
				//alert( " IN TAG LEN :: " +tgCnt);
				formField = formFieldObj.childNodes.item(0).data;
				for(c=0; c < tgCnt; c++)
				{
			    // alert( " IN  :: " + formErrorTag.childNodes.item(c).firstChild.data );
				// alert( " IN  :: " + formErrorTag.childNodes.item(c).tagName );
				   if(tgCnt > 2) {
					 if( formErrorTag.childNodes.item(c).tagName =='ind') 
					 {
						var ind = formErrorTag.childNodes(c).getAttribute("ind");
						var res = formErrorTag.childNodes(c).firstChild.data;
						//alert( "IN tgCnt ATT VAL " + res );
						if(res == 'false') {
							if(document.getElementById(formField+"Id"+ind)!=null && document.getElementById(formField+"Id"+ind) != undefined)
							{
								//alert( " getElementById :: " + formField+"Id"+ind);
								document.getElementById(formField+"Id"+ind).style.color = ERROR_FONT_COLOR;
							} else {
								//alert("In Single label " + formField+"Id");
								//alert("In Single label ELEM " + document.getElementById(formField+"Id"));
								document.getElementById(formField+"Id").style.color = ERROR_FONT_COLOR;
							}
						} else {
							if(document.getElementById(formField+"Id"+ind)!=null && document.getElementById(formField+"Id"+ind) != undefined)
							{
								document.getElementById(formField+"Id"+ind).style.color = ACTUAL_FONT_COLOR;
							} 							
						}

                     }
				   } else {
				
					 if(document.getElementById(formField+"Id")!=null && document.getElementById(formField+"Id") != undefined)
						{
							document.getElementById(formField+"Id").style.color = ERROR_FONT_COLOR;
							document.getElementById(formField+"Id").style.fontStyle="normal";
                            document.getElementById(formField+"Id").style.fontSize = "11"; 
						}
				  }
				}
			} 
		}
		// For Form field color change Ends in the case of validation failure
		for(chkCount=1;chkCount<fieldCount;chkCount++)
		{
			errorMsgObj = formErrorTag.childNodes.item(chkCount);
			for(errChkCount = 0; errChkCount < errorMsgObj.childNodes.length; errChkCount++)
			{
				if(errorMsgObj.childNodes.item(errChkCount).firstChild != null)
				{// alert( " errMsg :: " + errorMsgObj.childNodes.item(errChkCount).firstChild.data);
 						errorMessageList += "<font color='#990000' face='arial' size=1><li/>"+ errorMsgObj.childNodes.item(errChkCount).firstChild.data+"</font>";				

				}
			}
		}
  }  
      
  function buildRequest(frm)
  {
	    controlParams = "";	    
	    for(paramCount=0;paramCount<frm.elements.length;paramCount++)
	    {
	    	if(frm.elements[paramCount].type == 'hidden' || frm.elements[paramCount].type == 'text' || frm.elements[paramCount].type == 'select-one' || frm.elements[paramCount].type == 'select-multiple' || frm.elements[paramCount].type == 'checkbox' || frm.elements[paramCount].type == 'radio' || frm.elements[paramCount].type == 'textarea')
	    	{
				if(frm.elements[paramCount].type == 'checkbox')
				{
					if(frm.elements[paramCount].checked)
					{
						frm.elements[paramCount].value = "Y";
						controlParams += frm.elements[paramCount].name+"=";
				    	//controlParams += escape(frm.elements[paramCount].value)+"&";
					  controlParams += encodeURIComponent(frm.elements[paramCount].value)+"&";
					}
				}
				else if(frm.elements[paramCount].type == 'radio')
				{
					if(frm.elements[paramCount].checked == true)
					{
						controlParams += frm.elements[paramCount].name+"=";
			    		//controlParams += escape(frm.elements[paramCount].value)+"&";
					  controlParams += encodeURIComponent(frm.elements[paramCount].value)+"&";
					}
				}
				if(frm.elements[paramCount].type != 'checkbox' && frm.elements[paramCount].type != 'radio')
				{
	    			controlParams += frm.elements[paramCount].name+"=";
	    			//controlParams += escape(frm.elements[paramCount].value)+"&";
				controlParams += encodeURIComponent(frm.elements[paramCount].value)+"&";
				}
	    	}
	    }
	    if(controlParams != "")
	    	controlParams = controlParams.substring(0,controlParams.lastIndexOf("&"));	    	
	  	return controlParams;      	
}
      
  function submitPage(url, frm, butOpt)
  {
		processOpt = butOpt;
	//var urlContent = buildRequest(frm);
		changeFontColor(frm); // To change the form field colors when initial load

		urlValue = url;
		frmValue = frm;
		urlContent = "jcaptcha_response="+frm.jcaptcha_response.value;
    	if (window.XMLHttpRequest) 
    	{        
  			req = new XMLHttpRequest();
		} 
    	else if (window.ActiveXObject) 
    	{ // IE
      		req = new ActiveXObject("Microsoft.XMLHTTP");
    	}
		if(req) 
		{
			try
			{
        		req.onreadystatechange = processCaptchaStateChange;
        		req.open(method, captchaURL, true);
   				req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        		req.send(urlContent);
			}
			catch(exception)
			{
			}
		}   
  }

  function processCaptchaStateChange() 
  {
		// For Captcha Image lebel color change Starts in the case of validation failure
		if(ERROR_COLOR_CHAGE_REQD == 'true')
		{
			formField = "jcaptcha_response";
			if(document.getElementById(formField+"Id")!=null && document.getElementById(formField+"Id") != undefined)
			{
				document.getElementById(formField+"Id").style.color = ERROR_FONT_COLOR;
			}
		}
		// For Captcha Image lebel color change Ends in the case of validation failure
		captchaImageDisplay = "";
		if(document.getElementById(MESSAGE_ID) != null)
			document.getElementById(MESSAGE_ID).innerHTML = "";
		if(document.getElementById(HEADER_MESSAGE_ID) != null)
			document.getElementById(HEADER_MESSAGE_ID).innerHTML = "";
  		if (req.readyState == 4) 
   		{
			if (req.status == 200) 
			{				
				data = req.responseXML;
				statusTag = data.getElementsByTagName(RESPONSE_ELEMENT)[0];
				if(statusTag != null)
				{
        			statusMessage = statusTag.firstChild.data;
					if(statusMessage == 'success')
					{
						validatePage(urlValue, frmValue, processOpt);
					}
					else
					{
						/*erroStatusMessage = data.getElementsByTagName(CAPTCHA_STATUS_MESSAGE_ELEMENT)[0];
						if(erroStatusMessage!=null)
						{
							alert(erroStatusMessage.firstChild.data);
							callImageCaptcha(frmValue);
						}*/
						if(statusMessage != null && statusMessage == 'failure')
							captchaImageDisplay = "<font color='red'><li/>Invalid text has been entered. Please enter the text, which is given in the Captcha Image.</font>";
						else if(statusMessage != null && statusMessage == 'inputError')
							captchaImageDisplay = "<font color='red'><li/>Please enter the text, which is given in the Captcha Image</font>";
						else
							//captchaImageDisplay = "<font color='red'><li/>"+erroStatusMessage.firstChild.data+"</font>";
							captchaImageDisplay = "<font color='red'><li/>System encountered problem. Please try again. Enter the text, which is given in the Captcha Image</font>";
						//captchaImageDisplay += errorMessageList;
						if(document.getElementById(MESSAGE_ID) != null)
							document.getElementById(MESSAGE_ID).innerHTML = "<ul>"+captchaImageDisplay+"</ul>";
					
						callImageCaptcha(frmValue);
	
					}
				}
      		} 
			else 
			{
				  alert("Session has been failed. Please login again.");
    		}
	    }
  }

