/*
	Module:			Questionnaire_v#.js
	Description:	Javascript for EmbeddedEmailOrLinkedQuestionnaire.xslt and Questionnaire.xslt

	Change History:
	
		Created:	Alex Moses		17 Sep 2007
		Modified:	Alex Moses		29 Oct 2007		Fixed bug in validation of check boxes
					Alex Moses		19 Nov 2007		Fixed bug in validation of extra titles [BugID 17277]
					Alex Moses		14 Jan 2008	v2:	Added pre-population funcationality as part of 'email me' project
					Alex Moses		19 Feb 2008	v3:	Made pre-population onLoad trigger case insensitive [BugID 17914]

*/


function windowOnload() {
	var aSplitQueryStringValues = window.location.search.substring(1).split('&'); 
	var numIndex;
	var oElement;
	var bPrepopulationRequest = false;

	for (numIndex = 0; numIndex < aSplitQueryStringValues.length && !bPrepopulationRequest; numIndex++) { 
		if (aSplitQueryStringValues[numIndex].substring(0,2) == 'pp') {
			bPrepopulationRequest = true;
		}
	} 
	if (bPrepopulationRequest && document.frmQuestionnaire) {
		// Check for errors
		oElement = document.getElementById('error');
		if (oElement) {
			// Encourage customer to Contact Us because it is likely that this content should be available
			oElement.innerHTML = '<h1>we are sorry but there is a problem with this page</h1>' +
								'<p>We are currently unable to fulfil your request due to an unexpected problem.</p>' +
								'<p>Please <a href="/ContactUs/">contact us</a> in order that we can do our best to resolve the issue for you.</p>';
		} else {
			prepopulate(aSplitQueryStringValues);
		}
	}
}


function prepopulate(paSplitQueryStringValues) {
	var strQSName, strQSValue;
	var aPrePopQuestionText = new Array();
	var aPrePopAnswerText = new Array();
	var aPrePopAnswerValue = new Array();
	var oQAElements, oAElements;
	var oTargetElement, oElement, oClone;
	var numIndex;
	var numPositionOfEqualSign;
	var numQATDCounter, numATDCounter;
	var bFinishedQuestion;

	// Split query string name-value pairs and extract pre-population data in tuples
	for (oElement in paSplitQueryStringValues) {
		numPositionOfEqualSign = paSplitQueryStringValues[oElement].indexOf('='); 
		if (numPositionOfEqualSign >= 0) { 
			strQSName = paSplitQueryStringValues[oElement].substring(0,numPositionOfEqualSign);
			strQSValue = unescape(paSplitQueryStringValues[oElement].substring(numPositionOfEqualSign+1));
			
			// Only interested in parameters with pre-population prefix
			if (strQSName.substring(0,2) == 'pp')
			{
				// Get a zero-based index for this tuple
				numIndex = strQSName.substring(3) - 1;
				// Add to relevant Question/Answer/Value array
				switch (strQSName.substring(2,3)) {
					case 'q':
						aPrePopQuestionText[numIndex] = strQSValue;
						break;
					case 'a':
						aPrePopAnswerText[numIndex] = strQSValue;
						break;
					case 'v':
						aPrePopAnswerValue[numIndex] = strQSValue;
						break;
				}
			}
		} 
	}	

	// Loop possible locations of Question (+ Answer) section labels
	oQAElements = document.frmQuestionnaire.getElementsByTagName('td')
	for (numQATDCounter=0; numQATDCounter < oQAElements.length; numQATDCounter++) {
		if (oQAElements[numQATDCounter].innerHTML)
		{
			// Loop values for pre-population
			for (numIndex in aPrePopAnswerValue) {
				if (aPrePopAnswerValue[numIndex].length > 0 &&
					oQAElements[numQATDCounter].innerHTML.indexOf(aPrePopQuestionText[numIndex]) > -1)
				{				
					if (aPrePopAnswerText[numIndex] &&
						aPrePopAnswerText[numIndex].length > 0)
					// Use both Question label AND Answer label to identify target field...
					{
						// Loop possible locations of Answer section labels
						oAElements = oQAElements[numQATDCounter].parentNode.parentNode.getElementsByTagName('td');
						for (numATDCounter=0; numATDCounter < oQAElements.length; numATDCounter++) {
							if (oAElements[numATDCounter].innerHTML &&
								oAElements[numATDCounter].innerHTML == aPrePopAnswerText[numIndex])
							{
								// Set value of first input found within NEXT ROW (refer to sample Questionnaire layout in xslt)
								oTargetElement = oAElements[numATDCounter].parentNode.nextSibling.getElementsByTagName('input')[0];
								oTargetElement.value = aPrePopAnswerValue[numIndex];
									
								/******** Begin reformatting of Answer Section ********/
									
								// Hide input element
								oTargetElement.style.visibility='hidden';
								// Clone input's td
								oClone = oTargetElement.parentNode.cloneNode(true);
								// Remove original tr for input's td (now cloned)
								oTargetElement.parentNode.parentNode.parentNode.removeChild(oTargetElement.parentNode.parentNode);
								// Prepend Answer text and value as new label for input
								oClone.innerHTML = aPrePopAnswerText[numIndex] + ': <strong>' + oTargetElement.value + '</strong>' + oClone.innerHTML; 
 								// Use cloned td instead of that used for the Answer Section label
								oAElements[numATDCounter].parentNode.replaceChild(oClone,oAElements[numATDCounter]);
									
								/********* End reformatting of Answer Section *********/
									
								// Break loop because this Answer section is finished with
								break; 
							}
						}
						// There may be other relevant Answer sections under this Question, so...
						bFinishedQuestion = false;
					}
					else
					// Question label is sufficient to identify target field...
					{
						// N.B. Refer to sample Questionnaire layout in xslt
						if (gbCompactMode) {
							// Select first input found within NEXT ROW
							oTargetElement = oQAElements[numQATDCounter].nextSibling.getElementsByTagName('input')[0];
						}
						else {
							// Select first input found within PARENT TABLE
							oTargetElement = oQAElements[numQATDCounter].parentNode.parentNode.getElementsByTagName('input')[0];
						}
						// Set value
						oTargetElement.value = aPrePopAnswerValue[numIndex];
						// Hide input element
						oTargetElement.style.visibility='hidden';
						// Prepend value for read-only display
						oTargetElement.parentNode.innerHTML = oTargetElement.value + oTargetElement.parentNode.innerHTML; 

						bFinishedQuestion = true;
					}

					if (bFinishedQuestion) {
						break; // loop
					}
				}
			}
		}
	}		
}


function validateEmbeddedQuestionnaire() {

	var bAlreadyInCookie = false;
	var strMessage = '';
	var strQuestionLabel, strName, strValue
	var numIndex, numQuestion, numElement, numWebContentIDUnanswered, numQWebContentIDStatus;
	var oInput, oRadioGroup, oDiv, oLabels;
	var aQWebContentIDStatus;

	// Loop through Personal Details fields
	for (numQuestion in gaPersonalQName)
	{
		strName = '<Question><QuestionName>' + gaPersonalQName[numQuestion] +
					'</QuestionName><QuestionText>' +
					(gaPersonalQText[numQuestion].length==0 ? gaPersonalQName[numQuestion] : gaPersonalQText[numQuestion]) +
					'</QuestionText></Question>';
		oInput = document.frmEmbeddedQuestionnaire.elements[strName];
		if (oInput)
		{
			oDiv = document.getElementById(strName);
			oLabels = oDiv.getElementsByTagName('label');
			// Assume question label is first
			strQuestionLabel = oLabels[0].innerHTML;
			strValue = oInput.value;
			// Reuse strName variable
			strName = gaPersonalQName[numQuestion];

			if (strName=='Title' && strValue=='more') {
				oInput = document.frmEmbeddedQuestionnaire.elements['inpTitleHidden'];
				strValue = oInput.value;
			}
			
			if (strName=='Postcode') {
				strValue = strValue.replace(/\s/g,'');
				strValue = strValue.toUpperCase();
				//Replace all zeros then restore only those in valid positions
				strValue = strValue.replace(/0/g,'O');
				strValue = strValue.substring(0,strValue.length-3).replace(/[Oo]$/,'0') + ' ' + strValue.substring(strValue.length-3).replace(/^[Oo]/,'0');
				oInput.value = strValue;
			}

			if ( (strQuestionLabel.charAt(strQuestionLabel.length-1)=='*' && (strValue.length==0 ||
				(strName=='Postcode' && (strValue.length < 6 || strValue.length > 8))) ||
				(strName=='Postcode' && strValue.length > 0 && !validatePostcode(strValue)) ||
				(strName=='EmailAddress' && strValue.length > 0 && !checkEmail(strValue)) ||
				(strName=='CustomerNo' && strValue.length > 0 && !ValidateText(strValue,false,true,false))) )
			{
				strMessage = strMessage + '    - ' + gaPersonalFriendly[numQuestion] + '\n';
				markMissing(oDiv, true, !oInput.type.match('text'));
				if (!oInput.type.match('text'))
					oLabels[0].style.color='#CE1449';
			}
			else
			{
				markMissing(oDiv, false, !oInput.type.match('text'));
				if (!oInput.type.match('text'))
					oLabels[0].style.color='';
			}
		}
	}

	// Loop through Question fields
	for (numQuestion in gaQuestionNo)
	{
		strValue = '';

		// N.B. Check Box names handled separately, as they additionally feature the answer text
		strName = '<Question><QPosition>' + gaQuestionNo[numQuestion] + 
					'</QPosition><APosition>' + gaPositionNo[numQuestion] + 
					'</APosition></Question>'
		
		oInput = document.frmEmbeddedQuestionnaire.elements[strName];

		if (!oInput)
		{
			// May be a check box, each of which has a unique name, so prepare regular expression
			strName = '<Question><QPosition>' + gaQuestionNo[numQuestion] + 
						'</QPosition><APosition>' + gaPositionNo[numQuestion] + 
						'</APosition><Answer>.+</Answer></Question>'

			// Try to access check boxes by name
			for (numElement in document.frmEmbeddedQuestionnaire.elements) {
				if (strValue.length==0) {
					oInput = document.frmEmbeddedQuestionnaire.elements[numElement];
					if (oInput && oInput.type && oInput.name)
					{
						if (oInput.type=='checkbox' && oInput.name.match(strName) && oInput.checked)
						{
							strValue = '1';
						}
					}
				}
			}
		}
		else if (oInput && !oInput.type)
		{
			oRadioGroup = oInput;
			oInput = null;
			for (numIndex=0; strValue.length==0 && (numIndex < oRadioGroup.length); numIndex++) {
				oInput = oRadioGroup[numIndex];
				if (oInput.checked)
					strValue = '1';
			}
		}
		else if (oInput.type.match('select'))
		{
			// Drop down box
			for (numIndex=1; strValue.length==0 && (numIndex < oInput.options.length); numIndex++) {
				if (oInput.options[numIndex].selected)
					strValue = '1';
			}
		}
		else
		{
			// Text box
			strValue = oInput.value;
		}
		
		oDiv = document.getElementById('Q' + gaQuestionNo[numQuestion] + 
										'Div' + gaPositionNo[numQuestion]);
		oLabels = oDiv.getElementsByTagName('h3');
		// Assume question label is first h3 element found
		strQuestionLabel = oLabels[0].innerHTML;

		if (strValue.length==0 && strQuestionLabel.charAt(strQuestionLabel.length-1)=='*')
		{
			strMessage = strMessage + '    - "' + gaQuestionText[numQuestion] + '"\n';
			if (oInput.type) {
				markMissing(oDiv, true, !oInput.type.match('text'));
			} else {
				markMissing(oDiv, true);
			}
			oLabels[0].className='informmissingfield';
		}
		else
		{
			if (oInput.type) {
				markMissing(oDiv, false, !oInput.type.match('text'));
			} else {
				markMissing(oDiv, false);
			}
			oLabels[0].className='';
		}
	}

	
	if (strMessage.length==0) {
		/*
		N.B. Questionnaire Web Content ID is stored in the RMSession cookie with
				a binary suffix denoting whether it has been answered.
		   If cookie value ends with 1, Q is answered. To flag Q123456 as answered:
		       123456 * 10 + 1 = 1234561
		   If cookie value ends with 0, Q is unanswered. To flag Q654321 as unanswered:
		       654321 * 10 = 6543210
		*/

		aQWebContentIDStatus = getCookie('RMSession','EmQ').split(',');
		numWebContentIDUnanswered = document.frmEmbeddedQuestionnaire.inpContentref.value.substring(1) * 10;
		for (numQuestion in aQWebContentIDStatus)
		{
			numQWebContentIDStatus = aQWebContentIDStatus[numQuestion];
			if (numQWebContentIDStatus == numWebContentIDUnanswered)
			{
				// Amend WebContentIDStatus in array as answered
				aQWebContentIDStatus[numQuestion] = numWebContentIDUnanswered + 1;
				bAlreadyInCookie = true;
				break;
			}
		}
		if (!bAlreadyInCookie)
		{
			// Append WebContentIDStatus to array as answered
			numQuestion = aQWebContentIDStatus.length - 1;
			if (numQuestion==0 && aQWebContentIDStatus[0].length>0 && aQWebContentIDStatus[0]!='undefined') {
				// Array has a single entry
				numQuestion++
			}
			aQWebContentIDStatus[numQuestion] = numWebContentIDUnanswered + 1;
		}
		// Save array back into cookie
		setCookie('RMSession',aQWebContentIDStatus.join(','),null,'/',null,null,'EmQ')
		
		// Save questionnaire
		document.frmEmbeddedQuestionnaire.submit();
	}
	else {
		alert('Please include the following information:\n\n' + strMessage);
	}

}

// Restrict pre-population functionality to main Questionnaire page
if (window.location.pathname.toLowerCase()=='/contactus/questionnaire.asp') {
	window.onload = windowOnload;
}