String.prototype.trim = function() {
a = this.replace(/^\s+/, '');
return a.replace(/\s+$/, '');
};

String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}

var generalError = "An unexpected error has occurred.";
var unansweredFieldsPrompt = "You have not responded to one or more of the survey items.  If you would like to respond, please select the Cancel button.  If you prefer not to answer, please select the OK button to continue.";

document.onkeydown = function(e)
{	
	var key = 0;
	
	if(document.all)
		key = event.keyCode;
	else
		key = e.which;
	
	if(key == 13) 
	{
		questionSubmit();
		return false;
	}
}

function loadInitialBody(currentStep)
{
	document.pubSurveyForm.currentStep.value = currentStep;
	document.pubSurveyForm.initialLoad.value = "true";
	ajaxPostCall("/survey.do", document.getElementById('bodyContent'), document.pubSurveyForm, loadInitialBodySuccess, generalFailure);
}
function loadInitialBodySuccess(response)
{
	document.pubSurveyForm.initialLoad.value = "false";	
	document.pubSurveyForm.backStep.value = "false";
	document.getElementById('bodyContent').innerHTML = response;
	
	if(document.getElementById("progressIndicatorCurrentStep"))
		document.pubSurveyForm.currentStep.value = document.getElementById("progressIndicatorCurrentStep").innerHTML;
	
	if(document.getElementById("nextStep"))
		document.pubSurveyForm.currentStep.value = document.getElementById("nextStep").innerHTML;
	
	if(document.getElementById("totalQuestionCount"))
		document.pubSurveyForm.totalQuestions.value = document.getElementById("totalQuestionCount").value;
	
	updateProgressBar();
}
function generalFailure(response)
{
	document.getElementById('bodyContent').innerHTML = generalError;
}

function demographicsSubmit()
{
	hideMessage();
	var validationFields = new Array();
	var i = 0;
	var formIndex = 0;
	
	for(formIndex = 0; formIndex<document.pubSurveyForm.elements.length; formIndex++)
	{		
		if((document.pubSurveyForm.elements[formIndex].name.indexOf("demographic_") >= 0) && (document.pubSurveyForm.elements[formIndex].type != "hidden"))
		{
			validationFields[i++] = new ValidationField(document.pubSurveyForm.elements[formIndex].name, validationSelectedIndexNotZero, "Select " + document.getElementById(document.pubSurveyForm.elements[formIndex].name + 'Label').innerHTML);
		}
	}
	
	if((valid(validationFields, 'clientError', true) == false) && (!confirm(unansweredFieldsPrompt)))
	{
		document.getElementById("clientError").style.display = 'none';
		return;
	}
	else
	{
		document.pubSurveyForm.currentStep.value = "0";	
		ajaxPostCall("/survey.do", document.getElementById('bodyContent'), document.pubSurveyForm, demographicsSubmitSuccess, generalFailure);
	}
}
function demographicsSubmitSuccess(response)
{	
	document.pubSurveyForm.backStep.value = "false";
	document.getElementById('bodyContent').innerHTML = response;
	document.pubSurveyForm.currentStep.value = document.getElementById("progressIndicatorCurrentStep").innerHTML;
	document.pubSurveyForm.totalQuestions.value = document.getElementById("totalQuestionCount").value;
	document.pubSurveyForm.questionPages.value = document.getElementById("questionPagesCount").value;
	document.pubSurveyForm.questionIdsStr.value = document.getElementById("questionIdsStrDisplay").value;
	//document.pubSurveyForm.liveOnCampusIndicator.value = document.getElementById("liveOnCampusIndicator").value;
	
	updateProgressBar();
}
function backStep()
{
	hideMessage();
	document.pubSurveyForm.backStep.value = "true";
	var currentStep = parseInt(document.pubSurveyForm.currentStep.value);
	var targetDiv = document.getElementById('bodyContent');
	var successFunction = null;
	var failureFunction = generalFailure;
	
	if(currentStep == 1) //go to demographic page
	{
		document.pubSurveyForm.initialLoad.value = "true";
		document.pubSurveyForm.currentStep.value = 0;
		successFunction = loadInitialBodySuccess;
	}
	else if(currentStep == 2) //go to first question page
	{
		document.pubSurveyForm.currentStep.value = 0;
		successFunction = demographicsSubmitSuccess;
	}
	else //go to previous question page
	{
		document.pubSurveyForm.currentStep.value = currentStep - 2;
		targetDiv = document.getElementById('answerOptionsDisplay');
		successFunction = questionSubmitSuccess;
		failureFunction = questionSubmitFailure;
	}
	
	ajaxPostCall("/survey.do", targetDiv, document.pubSurveyForm, successFunction, failureFunction);
}
function questionSubmit()
{
	hideMessage();
	var currentQuestionIds = document.getElementById("currentQuestionIds").value.split(",");
	clearQuestionLabels(currentQuestionIds);
	var hasError = false;
	
	for(var i=0; i<currentQuestionIds.length; i++)
	{
		if(getRadioValue("answerChoice_" + currentQuestionIds[i]) == null)
		{
			questionLabelError(currentQuestionIds[i]);
			hasError = true;
		}
	}
	
	if((hasError) && (!confirm(unansweredFieldsPrompt)))
	{		
		return;
	}
	
	var targetDiv = document.getElementById('answerOptionsDisplay');
	var successFunction = questionSubmitSuccess;
	
	//if finishing last question then the next refresh is for the whole body
	if(document.pubSurveyForm.currentStep.value == document.pubSurveyForm.questionPages.value)
	{
		targetDiv = document.getElementById('bodyContent');
		successFunction = questionCompleteSuccess;
	}
	
	ajaxPostCall("/survey.do", targetDiv, document.pubSurveyForm, successFunction, questionSubmitFailure);
}
function questionLabelError(questionId)
{
	document.getElementById("question_" + questionId + "_Label").className = "labelError";
}
function clearQuestionLabels(questionIds)
{
	for(var i=0; i<questionIds.length; i++)
		document.getElementById("question_" + questionIds[i] + "_Label").className = "label";
}
function questionSubmitSuccess(response)
{	
	document.pubSurveyForm.backStep.value = "false";
	document.getElementById("answerOptionsDisplay").innerHTML = response;
	document.pubSurveyForm.currentStep.value = document.getElementById("nextStep").innerHTML;
	document.getElementById("progressIndicatorCurrentStep").innerHTML = document.getElementById("nextStep").innerHTML;
	updateProgressBar();
	document.getElementById('questionAnsweringInstructions').style.display = "none";
}
function questionCompleteSuccess(response)
{
	document.getElementById('bodyContent').innerHTML = response;
	document.pubSurveyForm.currentStep.value = document.getElementById("nextStep").innerHTML;	
}
function questionSubmitFailure(response)
{
	document.pubSurveyForm.backStep.value = "false";
	document.getElementById('questionLoadingDiv').innerHTML = "";
	document.getElementById('bodyContent').innerHTML = generalError;
}
function feedbackSubmit()
{
	hideMessage();	
	ajaxPostCall("/survey.do", document.getElementById('bodyContent'), document.pubSurveyForm, feedbackSubmitSuccess, questionSubmitFailure);
}
function feedbackSubmitSuccess(response)
{
	document.getElementById('bodyContent').innerHTML = response;
	document.pubSurveyForm.lowestScoringCategoryId.value = document.getElementById('recipientFeedbackCategoryId').value;
}
function updateProgressBar()
{
	if(document.getElementById('progressBarImg'))
	{
		var currentVal = parseInt(document.pubSurveyForm.currentStep.value);
		var totalVal = parseInt(document.pubSurveyForm.questionPages.value);
		var percentComplete = (currentVal-1) / totalVal;
		var width = parseInt(percentComplete * 250);
		document.getElementById('progressBarImg').style.width = width;
	}
}
function printFeedback()
{
	var url = "/surveyFeedback.do?lowestScoringCategoryId=" + document.pubSurveyForm.lowestScoringCategoryId.value + "&actionType=PRINT_FEEDBACK";
	window.open(url, "Print", "width=440,height=500,scrollbars=yes,status=no,resizable=yes,top=50,left=100");
}
function surveyCompletion()
{
	var url = "/surveyFeedback.do?actionType=SURVEY_COMPLETION&surveyKey=" + document.pubSurveyForm.surveyKey.value;
	window.open(url, "SurveyCompleted", "width=620,height=350,scrollbars=yes,status=no,resizable=yes,top=50,left=100");
}
function emailFeedback()
{
	showEmailPanel();
	
	var url = "/surveyFeedback.do?lowestScoringCategoryId=" + document.pubSurveyForm.lowestScoringCategoryId.value + "&actionType=EMAIL_FEEDBACK";
	ajaxGetCall(url, document.getElementById('panelEmailDiv'), emailFeedbackSuccess, emailFeedbackFailure);
}
function emailFeedbackSuccess(response)
{	
	document.getElementById("panelEmailDiv").innerHTML = response;
	
	if(document.getElementById("feedbackEmailAddress"))
	{
		document.getElementById("feedbackEmailAddress").focus();
		document.getElementById("feedbackEmailAddress").focus(); //some stupid reason, if called twice IE will actually focus
	}
}
function emailFeedbackFailure(response)
{
	document.getElementById("panelEmailDiv").innerHTML = generalError;
}
function emailFeedbackProcess()
{
	document.getElementById('emailClientError').style.display = 'none';
	var enteredAddress = document.getElementById('feedbackEmailAddress').value.trim();
	var errorMessage = "";
	
	if(enteredAddress.indexOf(",") >= 0)
	{
		var enteredAddresses = enteredAddress.split(",");
		var i = 0;
		for(i=0; i<enteredAddresses.length; i++)
		{
			if(isValidEmail(enteredAddresses[i].trim()) == false)
			{
				errorMessage = "One or more entered addresses is invalid.  Please try again.";
				break;
			}
		}
	}
	else		
	{
		if(isValidEmail(enteredAddress) == false)
			errorMessage = "The entered addresses is invalid.  Please try again.";
	}
	
	if(errorMessage.length > 0)
	{
		document.getElementById('emailClientError').style.display = 'block';
		document.getElementById('emailClientError').innerHTML = errorMessage;
		return;
	}
	
	var url = "/surveyFeedback.do?lowestScoringCategoryId=" + document.pubSurveyForm.lowestScoringCategoryId.value + "&actionType=EMAIL_FEEDBACK_SEND" + "&feedbackEmailAddress=" + enteredAddress;
	ajaxGetCall(url, document.getElementById('panelEmailDiv'), emailFeedbackSuccess, emailFeedbackFailure);
}
function isValidEmail(str)
{
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	   
	if(reg.test(address) == false)
		return false;
	else
		return true;

}
function showEmailPanel()
{
	YAHOO.namespace("example.container");
	YAHOO.example.container.panelEmail = new YAHOO.widget.Panel("panelEmail", { zIndex: 2000, fixedcenter: true, width:"350px", modal: true, visible:false, draggable: true, constraintoviewport:true } );
	YAHOO.example.container.panelEmail.render(document.body);
	YAHOO.example.container.panelEmail.show();
}
function hideEmailPanel()
{
	YAHOO.example.container.panelEmail.hide();
}
function toggleQuestionSelection(questionId, radioObj, colorIndex)
{
	var checkedVal = radioObj.checked;
	var radioVal = radioObj.value;

	resetAnswerBoxDisplay(questionId, colorIndex);
	document.getElementById("answerChoice" + radioVal + "_" + questionId + "_td").className = "answerSelected";
}
function resetAnswerBoxDisplay(questionId, colorIndex)
{
	var defaultClassName = "answerUnselected";	
	if(colorIndex < 0)
		defaultClassName = "answerUnselectedAlt";
	
	document.getElementById("answerChoice1" + "_" + questionId + "_td").className = defaultClassName;
	document.getElementById("answerChoice2" + "_" + questionId + "_td").className = defaultClassName;
	document.getElementById("answerChoice3" + "_" + questionId + "_td").className = defaultClassName;
	document.getElementById("answerChoice4" + "_" + questionId + "_td").className = defaultClassName;
	document.getElementById("answerChoice5" + "_" + questionId + "_td").className = defaultClassName;
	
	if(document.getElementById("answerChoice6" + "_" + questionId + "_td"))
		document.getElementById("answerChoice6" + "_" + questionId + "_td").className = defaultClassName;
}

