///
/// $Workfile: $
/// $Revision: $
/// $Project: $
/// $Folder: $ 
/// $Date: $
/// $Author: $
///
/// The main JavaScript functions used to extend WebSurveyor. 
///
/// Inputs: N/A
/// Outputs: N/A
/// Return Values: N/A
///
/// Created By: Ken Riley <kenr@nodots.com>
/// Date Created: 2006.08.22
///

/// global var declarations
var	institutionTypeId =	"";
var institutionId = -1;
var surveyId = -1;
var schoolInfoSet = false;
var popupLaunched = false;
var existingSurvey = false;
var completedSurvey = false;
var email = "";
var password = "";
var haveRateUs = false;
var nextButtonHTML = "<input type='image' src='/ss/images/btn_next.gif' value='Next Page'>";
var submitButtonHTML = "<input type='image' src='/ss/images/btn_submit.gif' value='Submit'>";
var InstitutionIDMultiSchool = 0;
// survey type ids
var collegeSTID = 1;
var lawSTID = 5;
var bizSTID = 2;
var medSTID = 11;

// optin qids
var collegeOptInQID = 134;
var mbaOptInQID = 259;
var lawOptInQID = 205;
var medOptInQID = 235;

// surveyURLs
var surveyBaseURL = "http://survey.review.com/ss/";
var collegeURL = surveyBaseURL + "wsb.dll/1/college_0910.htm";
var lawURL = surveyBaseURL + "wsb.dll/1/law_0910.htm";
var bizURL = surveyBaseURL + "wsb.dll/1/mba_0910.htm";
var medURL = surveyBaseURL + "wsb.dll/1/med_0910.htm";

// web services host
var webServicesHost = "http://survey.review.com";

///
/// Start general form validation code 
///

// Check to ensure that we have everything we need to deliver survey pages
function tprSurveyStatusCheck() {
	////alert("tprSurveyStatusCheck()");
}

// The main validation function. Called onclick from the login form.
function validateForm()	{
	resetErrorMessages();
	var errorCt = 0;
	if ( checkEmail() == false ) {
		errorCt++;
	} 
	if ( checkPassword() == false ) {
		errorCt++;
	}
	if ( checkPasswordMatch() == false ) {
		errorCt++;
	} 
	if ( checkSurveyType() == false ) {
		errorCt++;
	}
	if ( checkGradYear() == false ) {
		errorCt++;
	}
	// All of the "simple" stuff is correct. Time for a couple of calls to the Web Service.
	if ( errorCt == 0	) {

		var	email =	document.getElementById("email").value;
		var password = document.getElementById("password").value;
		var	selectTypeMenu = document.getElementById('schoolType');
		var	selectedTypeIndex =	selectTypeMenu.selectedIndex;
		itid = selectTypeMenu[selectedTypeIndex].value;
		////alert("calling getInstitutionInfoForEmailIID");
		////alert(email);
		////alert(itid);
		
		loginMultiSchool(email,password,itid);
		//alert('start: ' + InstitutionIDMultiSchool);
		
		getInstitutionInfoForEmailITID(email,itid);
		existingSurvey = false;
		completedSurvey = false;
		////alert("schoolInfoSet = " + schoolInfoSet);
		if ( schoolInfoSet ) {
			checkExistingSurvey();	
		} else {
			////alert("School info is not set!");
		}
		////alert("existingSurvey = " + existingSurvey);
		////alert("completedSurvey = " + completedSurvey);

		//checkExistingSurvey will send user to the login page if they have 
		//an existing survey that is incomplete or to the "completed" page
		//if they have a survey that is completed
		if ( schoolInfoSet && !popupLaunched && !existingSurvey && !completedSurvey ) {
			setFormAction(institutionTypeId);
			document.startSurvey.submit();
		}
	}
}

// Simple function to clear out all error message text. Called at the beginning of validateForm()
function resetErrorMessages() {
	document.getElementById("emailError").innerHTML	= "";
	document.getElementById("passwordError").innerHTML	= "";
	document.getElementById("confirmError").innerHTML	= "";
	document.getElementById("schoolTypeError").innerHTML	= "";
	document.getElementById("gradYearError").innerHTML	= "";
	return;
}

function validateLoginForm() {
	document.getElementById("emailError").innerHTML	= "";
	document.getElementById("passwordError").innerHTML	= "";
	document.getElementById("schoolTypeError").innerHTML	= "";
	var errorCt = 0;
	var	email =	document.getElementById("email").value;
	
	var password = document.getElementById("password").value;
	var	selectTypeMenu = document.getElementById('schoolType');
	var	selectedTypeIndex =	selectTypeMenu.selectedIndex;
	itid = selectTypeMenu[selectedTypeIndex].value;
	if ( !validateEmail() ) {
		errorCt++;
	}
	if ( password.length == 0 ) {
		document.getElementById("passwordError").innerHTML = "Password is a required field.";
		errorCt++;
	}
	if ( !checkSurveyType() ) {
		errorCt++;		
	}
	if ( errorCt == 0 ) {
	   
	    //remove - for multischools
	    loginMultiSchool(email,password,itid);
	   //alert('login: ' + InstitutionIDMultiSchool);
	   //alert('login: ' + InstitutionIDMultiSchool);
	    getInstitutionInfoForEmailITID(email,itid);
		getRespondentIdForEmail(email);
		checkCompletedSurvey();
		if ( !completedSurvey ) {
			//alert("calling login()");
			//alert(email + " " + " " + password + " " + itid);
			login(email,password,itid);
		}
	}	

}



// Tests for existence of email address. If address exists, call validateEmail
// which will determine if it is a *good* address
function checkEmail() {
	email =	document.getElementById("email").value;
	var validEmail;
	// first, check	to make	sure that there	is something in	the	email field. If	so,	send it	off	for	validation
	if ( email.length == 0 ) {
		document.getElementById("emailError").innerHTML	= "Email Address is	required.";
		validEmail = false;
	} else {
		document.getElementById("emailError").innerHTML	= "";
		validEmail = validateEmail();
	}
	return validEmail;
}

// Test for valid .edu email
function validateEmail() {
	email =	document.getElementById("email").value;
	// standard	email regex
	var	filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	if (filter.test(email))	{
		document.getElementById("emailError").innerHTML	= "";
		// call a web service to see if this is a domain we have in the system.
		checkExistingDomain();
		validEmail = true; 
		createCookie("email",email,0);			
	} else {
		// write the error message for non-edu email
		document.getElementById("emailError").innerHTML	= "Invalid email address.";
		validEmail = false;
	}
	return validEmail;
}

function checkPassword() {
	var password = document.getElementById("password").value;
	var passwordLength = password.length; 
	var passwordExists = false;
	if  ( password.length == 0 ) {
		document.getElementById("passwordError").innerHTML = "Password is required.";
		document.getElementById("confirmError").innerHTML = "";
//		document.startSurvey.password.focus();
	} else {
		passwordExists = true;
	}
	return passwordExists;
}

// Checks that the values enter for password and confirm are identical.
// If not, clears both fields, displays an error, and shifts focus back
// to password field. Called with an onblur event on the confirm field
function checkPasswordMatch() {
	password = document.getElementById("password").value;
	var	confirm	= document.getElementById("confirm").value;
	var validPassword = false;
	if ( confirm !=	password ) {
		document.getElementById("password").value =	"";
		document.getElementById("confirm").value = "";
		document.startSurvey.password.focus();
		document.getElementById("passwordError").innerHTML = "Password and confirm did not match,";
		document.getElementById("confirmError").innerHTML =	"please	re-enter both.";
		validPassword = false;
	} else if ( password.length > 0 ) {
		document.getElementById("passwordError").innerHTML = "";
		document.getElementById("confirmError").innerHTML =	"";
		validPassword = true;
	}
	return validPassword;
	
}

// Checks that the user has selected a value from the surveyType select menu
function checkSurveyType() {
	var	selectTypeMenu = document.getElementById('schoolType');
	var	selectedTypeIndex =	selectTypeMenu.selectedIndex;
	var validSurveyType = false;
	if ( selectedTypeIndex == 0	) {
		document.getElementById("schoolTypeError").innerHTML = "Survey Type	is required.";
		validSurveyType = false;
	} else {
		document.getElementById("schoolTypeError").innerHTML = "";
		institutionTypeId =	selectTypeMenu[selectedTypeIndex].value; 
		if ( institutionTypeId == 1 ) {
			var surveyId = 1;
		} else if ( institutionTypeId == 5 ) {
			var surveyId = 2;
		} else if ( institutionTypeId == 2 ) {
			var surveyId = 4;
		} else if ( institutionTypeId == 11 ) {
			var surveyId = 5;
		}
		if ( surveyId ) {
			createCookie("sid",surveyId);
		}
		validSurveyType = true;
	}
	return validSurveyType;
}

// Checks that the user has selected a value from the gradYear select menu
function checkGradYear() {
	var	gradYearMenu = document.getElementById('gradYear');
	var	gradYearIndex =	gradYearMenu.selectedIndex;
	var validGradYear = false;
	if ( gradYearIndex == 0	) {
		document.getElementById("gradYearError").innerHTML = "Graduation Year is required.";
		validGradYear = false;
	} else { 
		document.getElementById("gradYearError").innerHTML = "";
		validGradYear = true;
	}
	return validGradYear;
}

// Based on the school type, determine the form action.
function setFormAction(surveyTypeId) {
	if (surveyTypeId ==	collegeSTID )	{
		document.startSurvey.action	= collegeURL;
	} else if ( surveyTypeId == lawSTID ) {
		document.startSurvey.action	= lawURL;
	} else if (surveyTypeId == bizSTID ) {	
		document.startSurvey.action	= bizURL;
	} else if ( surveyTypeId == medSTID ) {
		document.startSurvey.action	= medURL;
	} else {
		////alert('surveys of this type not yet implemented');
	}
	return;
}

// Check included at the beginning of every survey page to make sure that 
// all parameters are set
function checkCookies() {
	var thissid = readCookie("sid");
	var thisemail = readCookie("email");
	var thisrid = readCookie("rid");
	var thisiid = readCookie("iid");
	var thisiname = readCookie("iname");
	if ( !thisrid  ) {
		document.location.href = "/ss/login.asp";
	} 
}

// Gathers up information from the form/cookies/GET and calls
// the web service method to add a new respondent and respondent
// survey record.
function beginSurvey() {
	//alert("in beginSurvey()");
	var startMethod = readCookie("startMethod");
	////alert("startMethod = " + startMethod);
	checkCompletedSurvey();
	if ( startMethod == "resume" ){
		return;
	}
	
	var wsKey = getWSKey();
	//alert("START: wsKey = " + wsKey);
	var sid = readCookie("sid");
	//alert("sid = " + sid);
	var email = readCookie("email");
	//alert("email = " + email);
	var iid = readCookie("iid");
	//alert("beginSurvey iid = " + iid);
	////getRespondentIdForEmail(email);
	if ( iid ) {
		var password = getVar("password");
		
		addRespondent(email,password,iid,sid,wsKey);
	} else {
		document.location.href = ("/ss/login.asp");
	}
}

//function setSubmissionKeyCookie() {
//	readCookie("wsSubmissionKey");
//	if ( !wsSubmissionKey ) {
//		var wsSubmissionKey = getWSSubmissionKey();
//		createCookie("wsSubmissionKey",wsSubmissionKey,90);
//	}
//}

// Walks through the cookies and expires them, then hands user
// off to the login page and updates the database
function surveyLogout() {
	//alert("in surveyLogout()");
	var rid = readCookie("rid");
	var sid = readCookie("sid");
	var wsKey = getWSKey();
	var wsCookieName = getWSCookieName();
	clearAllCookies();
	var pl = new SOAPClientParameters();
	pl.add("respondentId",rid);
	pl.add("surveyId",sid);
	pl.add("wsKey",wsKey);	
	SOAPClient.invoke(webServicesHost + "/TPRSurveyTools/TPRSurveyTools.asmx","LogoutSurvey",pl,false,surveyLogoutHandler);

}
function surveyLogoutHandler() {
	document.location.href = "/ss/login.asp";
}

function setSurveyComplete() {
	////alert('in setSurveyComplete()');
	var	pl = new SOAPClientParameters();
	var rid = readCookie("rid");
	var sid = readCookie("sid");
	var completedSurveys = readCookie("completedSurveys");
	if ( !completedSurveys ) {
		var completedString = sid;
	} else {
		var completedString = completedSurveys + "|" + sid;
	}
	createCookie("completedSurveys",completedString,180);
	var wsCookieName = getWSCookieName();
	eraseCookie(wsCookieName);
	pl.add("respondentId",rid);
	pl.add("surveyId",sid);
	SOAPClient.invoke(webServicesHost + "/TPRSurveyTools/TPRSurveyTools.asmx","SetSurveyComplete",pl,false);
}


// sets cookie that tells survey we don't need to create a new user.
function initializeLogin() {
//		createCookie("startMethod","resume",0);
}

///
/// JavaScript calls to Web Services start here.
/// All Web Services calls have two parts:
///		1. A function that calls the web service
///		2. A function that handles the callback from the web service.
/// These are grouped in pairs below
///
function GetPathFromWS(path)
{
   var	ca = path.split('|'); 
   return ca[0];
}
function GetInstitutionIDFromWS(path)
{
//alert('path: ' + path);
   var	ca = path.split('|'); 
   return ca[1];
}
function loginMultiSchool(currentEmail,currentPassword,institutionTypeId) {	
	var	pl = new SOAPClientParameters();
	pl.add("email",currentEmail);
	pl.add("password",currentPassword);
	pl.add("institutionTypeId",institutionTypeId);
	SOAPClient.invoke(webServicesHost + "/TPRSurveyTools/TPRSurveyTools.asmx","Login",pl,false,loginHandlerMultiSchool);
} 
function loginHandlerMultiSchool(sl) {
    if(sl!= null)
    {
	    var numSurveys = sl.length;
	    if ( numSurveys == 1 ) {	        
		    InstitutionIDMultiSchool = GetInstitutionIDFromWS(sl[0].Path);		
	    }
	}
	
	
	
}


// Call to webservice to handle login
function login(currentEmail,currentPassword,institutionTypeId) {
	createCookie("startMethod","resume",0);
	var	pl = new SOAPClientParameters();
	pl.add("email",currentEmail);
	pl.add("password",currentPassword);
	pl.add("institutionTypeId",institutionTypeId);
	//alert(currentEmail);
	//alert(currentPassword);
	//alert(institutionTypeId);
	
	SOAPClient.invoke(webServicesHost + "/TPRSurveyTools/TPRSurveyTools.asmx","Login",pl,false,loginHandler);
} 
function loginHandler(sl) {
	var numSurveys = sl.length;
	if ( numSurveys == 0 ) {
		msg = 'This login information does not match any active surveys. If you are here for the first time, please click <a href="/ss/start.asp">here</a> to begin a survey.';
		document.getElementById("statusWindow").innerHTML = msg;
	} else if ( numSurveys == 1 ) {
		checkCompletedSurvey();
		var rid = sl[0].RespondentId;
		var sid = sl[0].Id;
		var path = GetPathFromWS(sl[0].Path);
		var wskey = sl[0].WSKey;
		var wsCookieName = getWSCookieName();	
		//alert("455 :" + wsCookieName);
		createCookie(wsCookieName,wskey,0);
		updateRespondentSurvey(rid,sid);
		path = path + "?paction=resume";
		//alert(path);
		document.location.href = path;
	}
}

// Call to web service to update survey record for respondent
function updateRespondentSurvey(respondentId, surveyId) {
	////alert("in updateRespondentSurvey()");
	var	pl = new SOAPClientParameters();
	pl.add("respondentId",respondentId);
	pl.add("surveyId",surveyId);
	SOAPClient.invoke(webServicesHost + "/TPRSurveyTools/TPRSurveyTools.asmx","UpdateRespondentSurvey",pl,false);
}

// Call	to web service to see if the school	exists
function checkExistingDomain() {
	var	currentEmail = document.getElementById("email").value;
	var	pl = new SOAPClientParameters();
	pl.add("email",currentEmail);
	SOAPClient.invoke(webServicesHost + "/TPRSurveyTools/TPRSurveyTools.asmx","CheckExistingDomain",pl,false,checkExistingDomainHandler);
	
}	
function checkExistingDomainHandler(r)	{
	if ( r == 0	) {
		document.getElementById("emailError").innerHTML	= "No schools match	this email domain.";
		document.getElementById("startError").innerHTML = "<a href='/TPRSurveyTools/ReportMissingDomain.aspx'>Tell us</a> if we are missing your school.";
		document.startSurvey.email.focus();
	} else {
		document.getElementById("emailError").innerHTML	= "";
	}
}

// Call	to web service to find institution info	based on email address. Returns comples SOAP type
function getInstitutionInfoForEmailITID(email, itid) {
	//alert('itid:' + itid);
	institutionTypeId = itid;
	var	pl = new SOAPClientParameters();
	pl.add("email",	email);
	pl.add("itid", itid);
	SOAPClient.invoke(webServicesHost + "/TPRSurveyTools/TPRSurveyTools.asmx", "GetInstitutionsForEmailITID", pl, false, getInstitutionInfoForEmailITIDHandler);	
}
function getInstitutionInfoForEmailITIDHandler(il)	{
	//alert("in getInstitutionForEmailITIDHandler()");
	var	numResults = il.length;
	//alert("numResults = " + numResults);
	var	msg;
	//debugger;
	if ( numResults	== 0 ) {
		msg	= "We do not have a school of that type with that domain name in our system. Please <a href='/TPRSurveyTools/ReportMissingDomain.aspx'>click here</a> to report this to the survey administrator if you believe this is an error.";
		document.getElementById("startError").innerHTML = msg;
		schoolInfoSet == false;
		return;
	} else if (	numResults == 1	) {
		institutionId =	il[0].Id;
		//alert("institutionId for 1 school:" + institutionId);
		var	institutionName	= il[0].Name;
		var	institutionTypeId =	il[0].InstitutionTypeId;
		//belt and suspenders! trying to make sure that	the	institutionName	and	Id get passed into WebSurveyor
		//if this fails, there is another backup--more javascript in the first question!
		document.getElementById('wsInstitutionName').innerHTML = "<input type='hidden' id='institutionNameField' name='WSB57'	value='" + institutionName + "'>";
		document.getElementById('wsInstitutionId').innerHTML = "<input type='hidden' id='institutionIDField' name='WSB58' value='" + institutionId + "'>";
	//alert("1" + institutionName);	
		createCookie("iname",institutionName,0);
		createCookie("iid",institutionId,0);
		schoolInfoSet = true;
		msg	= "You will	be completing a	survey for <b>"	+ institutionName +	"("	+ institutionId	+ ")</b>";
		return;
	} else {
	    //alert("multischool");
	    //giveMeBreak();
	   
	    //alert("after");

		if ( schoolInfoSet == false ) {
			popupLaunched = true;	
			var list = "<p>";	
			
			for	( var c	= 0; c < numResults; c++ ) {
				var	institutionName	= il[c].Name;
				var	institutionID =	il[c].Id;
				var institutionInfo = escape(institutionName + "|" + institutionID);
				
				//giveMeBreak();				
//				alert ("InstitutionIDMultiSchool: " + InstitutionIDMultiSchool);
//				alert ("This survey is for: " + institutionName);
				if(InstitutionIDMultiSchool == institutionID)
				{
				//alert("2" + institutionName);		
				    createCookie("iname",institutionName,0);
		            createCookie("iid",institutionID,0);
		            schoolInfoSet = true;
		            return;
				}
				// build pipe-delimited id|name option list
				list = list + "<input type='radio' name='institutionInfo' onclick=setDelimitedSchoolInfo(" + "'"  + institutionInfo + "'" + ")> " + institutionName + "<br/>";
			}
			list = list + "</p>";
			displayMultiSchoolSelect(list);
			return;
		} else {
			popupLaunched = false;
		}
	}
}
// Pops up a window with a list of the schools that use that domain
function displayMultiSchoolSelect(msg) {
	document.getElementById('listContentOptions').innerHTML = msg;
	document.getElementById('chooseFromSchoolListWindow').className = 'visibleSchoolListWindow';
	// deal with IE quirk--select lists don't acknowledge z-index attributes so always appear on top
	document.getElementById('schoolType').className = 'hiddenPulldown';
	document.getElementById('gradYear').className = 'hiddenPulldown';
	// don't want people boinking on the main survey button now!
	document.getElementById('startSurveyButton').active = false;
}
// Stashes results from the Web Service in a hidden field and in two cookies
// for use later in the survey.
function setDelimitedSchoolInfo(schoolInfo) {
	var decodedSchoolInfo = unescape(schoolInfo);
	var schoolInfoArray = decodedSchoolInfo.split("|");
	var institutionName = schoolInfoArray[0];
	var institutionId   = schoolInfoArray[1];	
	// belt and suspenders! trying to make sure that	the	institutionName	and	Id get passed into WebSurveyor
	// if this fails, there is another backup--more javascript in the first question!
	// WSB57 = required field name for the hidden email field in Web Surveyor.
	document.getElementById('wsInstitutionName').innerHTML = "<input type='hidden' name='WSB57'	value='" + institutionName + "'>";
	// WSB58 = required field name for the hidden email field in Web Surveyor.
	document.getElementById('wsInstitutionId').innerHTML = "<input type='hidden' name='WSB58' value='" + institutionId + "'>";
//alert("3" + institutionName);	
	createCookie("iname",institutionName,0);
	createCookie("iid",institutionId,0);
	// return to normal form state
	document.getElementById('chooseFromSchoolListWindow').className = 'hiddenSchoolListWindow';
	document.getElementById('schoolType').className = 'regElevenBlack';
	document.getElementById('gradYear').className = 'regElevenBlack';
	setFormAction(institutionTypeId);
	document.startSurvey.submit();
}

function checkInstitutionInfo()	{
	var	nameSet	= false;
	var	iidSet = false;
	var	iname =	"";
	var	iid	= "";
	var institutionInfo = new array();
	var	email =	decode(getVar("WSB56"));
	var	itid  = getVar("schoolTypeID");
	var	gname =	decode(getVar("WSB57"));
	var	giid  =	getVar("WSB58");

	// first check if we successfully passed the name as a GET var.	. .
	if ( gname.length >	0 )	{
		nameSet	= true;
		iname =	gname;
		// we're in luck! stash that baby in a cookie so we don't have to do this again!
		//alert("4" + institutionName);	
		createCookie("iname",iname,0);
	} else { 
		var	cname =	 readCookie("iname");
		if ( cname.length >	0 )	{
			nameSet	= true;
			iname =	cname;
		} else {
			nameSet	= false;
		}
	}

	// now check for the iid in the GET vars
	if ( giid.length > 0 ) {
		iidSet = true;
		iid	= giid;
		// disco! we've got the iid. stash it in a cookie
		createCookie("iid",iid,0);
	// then	try	the	cookies	. .	.
	} else { 
		var	ciid =	readCookie("iid");
		if ( cname.length >	0 )	{
			iidSet	= true;
			iid =	ciid;
		} else {
			iidSet	= false;
		}
	}
	// if all else fails, call the webservice to set the values as cookies
	if ( iidSet == false || nameSet == false ) {
		return false;
	} else {
		institutionInfo["iid"] = iid;
		//alert("5" + iname);		
		institutionInfo["iname"] = iname;
		return institutionInfo; 
	}
}

function checkExistingSurvey() {
	////alert("in checkExistingSurvey()");
	var sid = readCookie("sid");
	var email = readCookie("email");
	var iid = readCookie("iid");
	////alert(email);
	////alert(sid);
	////alert(iid);
	var	pl = new SOAPClientParameters();
	pl.add("email",email);
	pl.add("iid",iid);
	pl.add("sid",sid);
	SOAPClient.invoke(webServicesHost + "/TPRSurveyTools/TPRSurveyTools.asmx","CheckExistingSurvey",pl,false,checkExistingSurveyHandler);
}
function checkExistingSurveyHandler(r) {
	//alert("in checkExistingSurveyHandler()");
	//alert("r" + r);
	if ( r == true ) {
		completedSurvey = false;
		existingSurvey = true;
		
		checkCompletedSurvey();
		// if we get a hit on a completed survey, we will exit with 
		// a redirect to the completed page, otherwise, send user to
		// the login page
		//alert("completedSurvey" + completedSurvey);
		if ( !completedSurvey ) {
			document.location.href = "/ss/login.asp?reasonID=1";
		}
	} else {
		existingSurvey = false;
	}
}

function checkCompletedSurvey() {
	////alert("in checkCompletedSurvey()");
	var sid = readCookie("sid");
	var email = readCookie("email");
	var	pl = new SOAPClientParameters();
	pl.add("sid",sid);
	pl.add("email",email);
	//debugger;
	SOAPClient.invoke(webServicesHost + "/TPRSurveyTools/TPRSurveyTools.asmx","CheckCompletedSurvey",pl,false,checkCompletedSurveyHandler);
}
function checkCompletedSurveyHandler(r) {
	//alert("in checkCompletedSurveyHandler()");
	//alert(r);
	completedSurvey = false;
	if ( r == true ) { 
		completedSurvey = true;
		alert("You have already completed this survey.");
		document.location.href = "/ss/completed.asp";
	} 
}

function getRespondentIdForEmail(email) {
	var	pl = new SOAPClientParameters();
	pl.add("email",email);
	SOAPClient.invoke(webServicesHost + "/TPRSurveyTools/TPRSurveyTools.asmx","GetRespondentIdForEmail",pl,false,getRespondentIdForEmailHandler);
}
function getRespondentIdForEmailHandler(r) {
    //alert("in getRespondentIdForEmailHandler: " + r);
	createCookie("rid",r,90);	
	return r;
}


function setSurveyVerified() {
	var sid = getVar("sid");
	var rid = getVar("rid");
	var	pl = new SOAPClientParameters();
	pl.add("sid",sid);
	pl.add("rid",rid);
	SOAPClient.invoke(webServicesHost + "/TPRSurveyTools/TPRSurveyTools.asmx","SetSurveyVerified",pl,false,markSurveyVerifiedHandler);
}
function markSurveyVerifiedHandler(r) {
	document.write(r);
}

function addRespondent(email,password,iid, sid, wsKey) {
	//alert('in addRespondent()');
	var	pl = new SOAPClientParameters();
	pl.add("email",email);
	pl.add("password",password);
	pl.add("institutionID",iid);
	pl.add("surveyID",sid);

        if(wsKey == null)
        {
	   wsKey  = "";
        }
	pl.add("wsKey",wsKey);
	SOAPClient.invoke(webServicesHost + "/TPRSurveyTools/TPRSurveyTools.asmx","AddRespondent",pl,false,addRespondentHandler);
}
function addRespondentHandler(r) {
	if ( r == -99 ) {
		//alert("You have already completed this survey.");
		document.location.href = "/ss/completed.asp";
	} else {
		createCookie("rid",r,0);
//		var doc = document.cookie;
//		alert(doc);
	}
	return;
}

// Rate Us globals
var academicsText;
var lifeText;
var studentText;
var careerText;
var admissionsText;

// Web service method to check if TPR has student survey data for the institution
function checkRateUsData() {
	//alert("in checkRateUsData()");
	var iid = readCookie("iid");
	var	pl = new SOAPClientParameters();
	pl.add("institutionID",iid);
	SOAPClient.invoke(webServicesHost + "/TPRSurveyTools/TPRSurveyTools.asmx","CheckRateUsData",pl,false,checkRateUsDataHandler);
}
function checkRateUsDataHandler(r) {
	//alert("in checkRateUsDataHandler()");
	if ( r == 0 ) {
		document.getElementById("oopsWindow").className = "oopsVisible";
		haveRateUs = false;
	} else {
		haveRateUs = true;
	}
}

// Web service method to get Rate Us info w/ its callback
function getRateUs() {
	//alert("in getRateUs()");
	//alert(haveRateUs);
	if ( haveRateUs === true ) {
		var iid = readCookie("iid");
		var	pl = new SOAPClientParameters();
		pl.add("institutionID",iid);
		SOAPClient.invoke(webServicesHost + "/TPRSurveyTools/TPRSurveyTools.asmx","GetRateUsData",pl,false,rateUsDataHandler);
	}
}
function rateUsDataHandler(rateUsData) {
	//alert("in getRateUsDataHandler()");

	if ( rateUsData ) {
		academicsText = rateUsData.Academics;
		lifeText      = rateUsData.Life;
		studentText   = rateUsData.StudentBody;
		careerText	  = rateUsData.Career;
		admissionsText = rateUsData.Admissions;
	}
}

function writeRateUsAcademics() {
	document.write("<p style='font-size: 9pt; margin-left: 20px; margin-right: 20px;' >" + academicsText + "</p>");
}

function writeRateUsLife(r) {
	document.write("<p style='font-size: 9pt; margin-left: 20px; margin-right: 20px;' >" + lifeText + "</p>");
}

function writeRateUsStudents(r) {
	document.write("<p style='font-size: 9pt; margin-left: 20px; margin-right: 20px;' >" + studentText + "</p>");
}

function writeRateUsCareer(r) {
	document.write("<p style='font-size: 9pt; margin-left: 20px; margin-right: 20px;' >" + careerText + "</p>");
}

function writeRateUsAdmissions(r) {
	document.write("<p style='font-size: 9pt; margin-left: 20px; margin-right: 20px;' >" + admissionsText + "</p>");
}
///
/// Utility functions -- these should all be self-explanatory
///
function replaceButtons(pbid) {
	document.getElementById('previousButtonBlock').innerHTML = '';
	var submitHtml = document.getElementById('submitButtonBlock').innerHTML;
	var filter = /(.*?)(SubmitBtn)(.*?)/i
	if (filter.test(submitHtml))	{
		document.getElementById('submitButtonBlock').innerHTML = submitButtonHTML;
	} else {
		document.getElementById('submitButtonBlock').innerHTML = nextButtonHTML;
		document.getElementById("finishButtonBlock").innerHTML = '<a href="#" onclick="goToPage(' + pbid + ')"><img src="/ss/images/btn_submit.gif" border="0"></a>';
	}
}


function focusFirstField() {
	document.startSurvey.email.focus();
}

function clearProgressBar() {
	document.getElementById('tprSurveyStatusBar').innerHTML = "";
}

function writeEmailAddressBlock() {
	var currentEmail = readCookie("email");
	var emailBlockText = '<input type="hidden" name="wsbemailaddress" value="' + currentEmail + '">';
	document.write(emailBlockText);
}

function writeIname() {
	iname = readCookie("iname");
	//alert(iname);
	document.write(iname);
}

function writeEmail() {
	email = readCookie("email");
	document.write(email);
}

function getWSKey() {
	var wsCookieName = getWSCookieName();
	//alert("847 :" + wsCookieName);
	var wsKey = readCookie(wsCookieName);
	////alert(wsKey);
	return wsKey;
}

// the cookie name is a combo of "WSPK-" and the websurveyor id
function getWSCookieName(){
	var sid = readCookie("sid");
	
	switch (sid) 
	{
        case "1": //ugrad
            sid = 53;
            break;
        case "2": //law
            sid = 54;
            break;            
        case "4": //business
            sid = 55;   
            break;
         case "5": //medical
            sid = 24;   
            break;
        default:
            sid = 0;
            break;
    }
//	if(sid == 1)
//	{
//	    sid = 36;
//	}
//	else if(sid == 2)
//	{
//	    sid = 38;
//	}
	var wsCookieName = "WSPK-" + sid;
	return wsCookieName;

}

function calculatePctComplete(thisPage,numPages) {
	var adjustedPage = thisPage - 2; // there are two bogus pages at the start of the survey
	var adjustedNumPages = numPages - 1; // and one bogus page at the end of the survey
	var pctPerPage = 1/adjustedNumPages * 100;
	var pctComplete = Math.round(adjustedPage * pctPerPage);
	
	if ( pctComplete < 0 ) {
		pctComplete = 0;
	}
	document.write(pctComplete);
}

function getVar(name) {
	get_string = document.location.search;		   
	return_value = '';	
	do { //This	loop is	made to	catch all instances	of any get variable.
		name_index = get_string.indexOf(name + '=');
			
		if(name_index != -1)
			{
			  get_string = get_string.substr(name_index	+ name.length +	1, get_string.length - name_index);
			  
			  end_of_value = get_string.indexOf('&');
			  if(end_of_value != -1)				
				value =	get_string.substr(0, end_of_value);				   
			  else				  
				value =	get_string;				   
				
			  if(return_value == ''	|| value ==	'')
				 return_value += value;
			  else
				 return_value += ',	' +	value;
			  }
			} while(name_index != -1)
			
		 //Restores	all	the	blank spaces.
		 space = return_value.indexOf('+');
		 while(space !=	-1)
			  {	
			  return_value = return_value.substr(0,	space) + ' ' + 
			  return_value.substr(space	+ 1, return_value.length);
							 
			  space	= return_value.indexOf('+');
			  }
		  
	return(return_value);		 
}

function encode(str) {
	var result = "";
		for (i = 0; i < str.length; i++) {
		if (str.charAt(i) == " ") result += "+";
		else result += str.charAt(i);
	}
	return escape(result);

}

function decode(str) {
	 var result	= "";
	 for (var i	= 0; i < str.length; i++) {
		  if (str.charAt(i)	== "+")	result += "	";
		  else result += str.charAt(i);
		  return unescape(result);
	 }
}

function createCookie(name,value,days) {
	if (days) {
		var	date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var	expires	= "; expires="+date.toGMTString();
	} else {
		var expires = "";
	}
	document.cookie	= name+"="+value+expires+";	path=/";
}

function readCookie(name) {
    var	nameEQ = name +	"=";
	var	ca = document.cookie.split(';');
	for(var	i=0;i < ca.length;i++) {
		var	c =	ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0)	return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function clearAllCookies() {
	var	ca = document.cookie.split(';');
	for(var	i=0;i < ca.length;i++) {
		var	c =	ca[i];
		var ccontents = c.split('=');
		var cname = ccontents[0];
		eraseCookie(cname);		
	}
}

function whichBrowser() {
	var agt=navigator.userAgent.toLowerCase();
		if (agt.indexOf("opera") != -1) return 'Opera';
		if (agt.indexOf("staroffice") != -1) return 'Star Office';
		if (agt.indexOf("webtv") != -1) return 'WebTV';
		if (agt.indexOf("beonex") != -1) return 'Beonex';
		if (agt.indexOf("chimera") != -1) return 'Chimera';
		if (agt.indexOf("netpositive") != -1) return 'NetPositive';
		if (agt.indexOf("phoenix") != -1) return 'Phoenix';
		if (agt.indexOf("firefox") != -1) return 'Firefox';
		if (agt.indexOf("safari") != -1) return 'Safari';
		if (agt.indexOf("skipstone") != -1) return 'SkipStone';
		if (agt.indexOf("msie") != -1) return 'Internet Explorer';
		if (agt.indexOf("netscape") != -1) return 'Netscape';
		if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
		if (agt.indexOf('\/') != -1) {
		if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
		return navigator.userAgent.substr(0,agt.indexOf('\/'));}
		else return 'Netscape';} else if (agt.indexOf(' ') != -1)
		return navigator.userAgent.substr(0,agt.indexOf(' '));
		else return navigator.userAgent;
}

function changeCursor() {
	var browser = whichBrowser();
	if  ( browser == "Internet Explorer" ) {
		document.getElementById("startSurveyButton").style.cursor="hand";
	} else {
		document.getElementById("startSurveyButton").style.cursor="pointer";
	}
}

function setOptInVal(val) {
    var qid = 19999;
    var stidCtrl = document.getElementById('schoolType');
    var stid = stidCtrl.options[stidCtrl.selectedIndex].value;
    var hiddenElement = '';
    switch (stid) {
        case "1":
            var qid = collegeOptInQID;
            break;
        case "5":
            var qid = lawOptInQID;    
            break;
        case "2":
            var qid = bizOptInQID;
            break;    
        case "11":
            var qid = medOptInQID;    
            break;
        default:
            break;
    }
    var optInDiv = document.getElementById('wsOptIn');
    if ( qid > 0 ) {
        var hiddenElement = "<input type='hidden' id='wsOptInField' name='WSB" + qid + "' value='" + val + "' />";
    }
    optInDiv.innerHTML = hiddenElement;

}

