/* -------------------------------------------------------------------

Functions for implementing SNAP surveys
_______________________________________

Script assumes that survey HTML is stored on our servers, 
and includes a single form (or at least that the first form 
encountered in the survey document is the survey form).

For these reasons, these functions do not work properly 
for an externally hosted survey.

------------------------------------------------------------------- */


function svLinkSurvey() {

// find link with ID "survey-link" 
// if found, get survey filename from link href and attach call to svInitSurvey function 

	svLink = document.getElementById('survey-link');	// arguably a class would be better so can do
														// this to multiple links?  but prob no need...
	if (svLink != null) {
		// get survey identifier from link href
		var strHref = svLink.href;
		var strSvName = strHref.substring(strHref.lastIndexOf('/')+1,strHref.lastIndexOf('.'));
		// set onclick to open popup and not follow href
		svLink.onclick = function() { svInitSurvey(strSvName, 1); return false; };
		svLinksDone = 1;
	} else {
		svLinksDone = 0;
		//alert('no link');
	}
}

function svDateToday() {
	var d = new Date();
	var date = d.getDate();
	var month = d.getMonth();
	var year = d.getFullYear();
	today = new Date(year,month,date);
	return today;
}

function svInitSurvey(identifier, requested) {
//alert('svInitSurvey');

// define default property values
// check for survey link 
// check survey status via cookie if present
// if appropriate (depending on status) call svGetConfigXML function 


	// global vars - default values are mostly overwritten later 
	svPath = '/resources-www/surveys/';	
	svMaxOpens = 1;
	svMaxCompletes = 1;
	svExpires = '2999/01/01';								// so if not supplied, will continue till survey removed
	svWinWidth = 400;
	svWinHeight = 500;
	svPreventOtherSurvey = '';
	svCurOpens = 0;
	svCurCompletes = 0;
	svStatus = '';
	svSetStatus = 'CURRENT';
	svName = identifier;

	if (!window.svLinksDone) svLinkSurvey();				// adjust survey link if present and not already done (script will make it a popup) (svLinksDone is set by svLinkSurvey function)

	var cookieValue = (getCookie(svName));					// get cookie if present
	if ((cookieValue != null) && (cookieValue != '')) {		// cookie set previously, so get values
		//alert(cookieValue);								// DEBUG
		var cookieValues = cookieValue.split(';');			// split cookie string into array of name/value pairs
															// following will (re)set svCurOpens, svCurCompletes and svStatus variables
		for (i=0;i<cookieValues.length;i++) {
			var nvp = cookieValues[i].split('=');			// split each name/value pair
			//alert(nvp[0] + ' - ' + nvp[1])				// DEBUG
			eval(nvp[0] + '= "' + nvp[1] + '"');			// set each name as variable with corresponding value
		}
	}

	// check status - abort if "COMPLETED" or "PREVENTED" or "EXPIRED"
	if ((svStatus == 'COMPLETED') || (svStatus == 'PREVENTED') || (svStatus == 'EXPIRED')) {
		// cancel (ie - do nothing)
		//alert(svName + ": " + svStatus);					// DEBUG

		//  if opened from link (ie - not automatically) it is OK to provide an error message
		if (requested) {
			svErrorMessage(svStatus);
		}

	} else {
		svGetConfigXML();									// get config XML if it exists, and set vars
	}
}

function svGetConfigXML() {
//alert('svGetConfigXML');

// get config XML for current survey 
// if found, call svSetConfigVars function

	var strGet = svPath + svName + '.xml';

    svConfigHttp = createRequestObject();
    svConfigHttp.open('get', strGet);
    svConfigHttp.onreadystatechange = svSetConfigVars;
    svConfigHttp.send(null);
}

function svSetConfigVars() {
//alert('svSetConfigVars');

// set survey properties from config XML (values in XML will overwrite defaults set by svInitSurvey function) 

    if(svConfigHttp.readyState == 4) {

        // following try/catch blocks prevent error if XML element is empty or XML doc does not exist
        // better to test if responseXML is not null, then do following...

    	try { var config = svConfigHttp.responseXML.documentElement; }
			catch(e) { }

		// populate js vars from xml document
        // THIS IS CRUDE - surely a more generic way is possible...?
		try { svMaxOpens = config.getElementsByTagName('maxOpens')[0].firstChild.data; }
			catch(e) { }
		try { svMaxCompletes = config.getElementsByTagName('maxCompletes')[0].firstChild.data; }
			catch(e) { }
		try { svWinWidth = config.getElementsByTagName('winWidth')[0].firstChild.data; }
			catch(e) { }
		try { svWinHeight = config.getElementsByTagName('winHeight')[0].firstChild.data; }
			catch(e) { }
		try { svExpires = config.getElementsByTagName('expires')[0].firstChild.data; }
			catch(e) { }
		try { svPreventOtherSurvey = config.getElementsByTagName('preventOtherSurvey')[0].firstChild.data; }
			catch(e) { }

		//alert(svExpires + " - " + Date.parse(svExpires))	// DEBUG

		// if expiry date not passed, open survey
		if (Date.parse(svExpires) > Date.parse(svDateToday())) {
			svLoad();
		} else {
			svSetCookie(svName, 'EXPIRED');					// set to EXPIRED so will not even make request for config in future
			//alert(svName + ': has EXPIRED');				// DEBUG
		}
    }
}

function svLoad() {
//alert('svLoad');

// request survey document and call svOpen function when recieve response

// cannot simply open survey window with survey URL and them modify document as
// causes error because doc is not loaded before script tries to modify it.  So
// have to request document first, then load and modify it.

	var strGet = svPath + svName + '.html';
	//alert(strGet);
    svSurveyHttp = createRequestObject();
    svSurveyHttp.open('get', strGet);
    svSurveyHttp.onreadystatechange = svOpen;
    svSurveyHttp.send(null);
}

function svOpen() {
//alert('svOpen');

// modify survey HTML (add base tag)
// open window
// write survey HTML to window
// add form.onsubmit to document - calls svComplete

    if(svSurveyHttp.readyState == 4) {

		// test response to ensure survey exists...
		if (svSurveyHttp.status == 200) {

			svSurveyHTML = svSurveyHttp.responseText;						// get survey content
			
			// add BASE tag to survey document
			// this is necessary because the function above opens a window 
			// without providing a URL, so the window tries to resolve relative
			// URLs relative to the page from which the survey was opened rather 
			// than relative to the survey document 
			// ALTERNATIVELY - use absolute URLs...but that makes testing/dev/QA difficult
			
			var strHead = '</head>';
			var strBase = '<base href="http://www.nhm.ac.uk/resources-www/surveys/" /></head>';
			//alert(svSurveyHTML);
			svSurveyHTML = svSurveyHTML.replace(strHead,strBase);
			//alert(svSurveyHTML);

			var svSurveyWindow = popupSurvey('', svWinWidth, svWinHeight);	// open window
			svSurveyWindow.document.write(svSurveyHTML);					// load document
			svSurveyWindow.document.close();								// close document - ends progress meter when visible in FF
			svSurveyWindow.focus();
			
				
			// attach functionality to survey form to run svComplete function if form submitted
			var obj = svSurveyWindow.document.getElementsByTagName('form')[0];
			//alert(obj);
			addEventSimple(obj,'submit',svComplete);

			// update survey cookie details
			svCurOpens++;													// increment counter
			if (svCurOpens >= svMaxOpens) svSetStatus = 'COMPLETED'			// set new status value
			svSetCookie(svName, svSetStatus, svCurOpens, svCurCompletes);

		} else {
			// error condition - no survey file or otherwise failed request...
			// fail quietly...
			// alert('ERROR: no survey HTML');									// DEBUG
		}
	}
}



function svComplete() {
// this is called by popup survey IF FORM SUBMITTED
//alert('hi - just checking!');											// DEBUG

// set status of survey (depending on default/config properties) - status determines whether survey can open or be completed again


	svCurCompletes++;													// increment counter
	if (svCurCompletes >= svMaxCompletes) svSetStatus = 'COMPLETED'		// set new status value
	svSetCookie(svName, svSetStatus, svCurOpens, svCurCompletes);		// update survey cookie details

	// prevent other survey opening if necessary (!!!CHECK THIS WORKS IN DIFF PARTS OF SITE...)
	if (svPreventOtherSurvey != '') {
		svSetCookie(svPreventOtherSurvey, 'PREVENTED');
	}

	// close poup?
}


function svErrorMessage(state) {
	switch(state) {
		case 'EXPIRED':
			var msg = 'Sorry.  This survey has now finished.';
			break;
		case 'PREVENTED':
			var msg = 'There is no need to complete this survey as you have already completed another.';
			break;
		case 'COMPLETED':
			var msg = 'This survey has already been completed.'
			break;
	}
	alert(msg + '\n\n' + 'Thank you.')
}


function svSetCookie(surveyName, setStatus, curOpens, curCompletes) {
	var strValue = 'svStatus=' + setStatus + ';svCurOpens=' + curOpens + ';svCurCompletes=' + curCompletes;
	setCookie(surveyName, strValue);
}


/* ----- event handler functions ---------------------- */
// is this helpful or not???
// event functions from http://www.quirksmode.org/js/eventSimple.html
function addEventSimple(obj,evt,fn) {
	if (obj.addEventListener)
		obj.addEventListener(evt,fn,false);
	else if (obj.attachEvent)
		obj.attachEvent('on'+evt,fn);
}
function removeEventSimple(obj,evt,fn) {
	if (obj.removeEventListener)
		obj.removeEventListener(evt,fn,false);
	else if (obj.detachEvent)
		obj.detachEvent('on'+evt,fn);
}




/* ----- THIS SHOULD WORK BETTER, BUT DOESN'T IN MOZILLA? -------------------------- */
function svOpenTest() {
// this ought to work without the need to issue a seperate request for the survey doc
// then load it. and it does in IE, but apparently not in Mozilla where the documents
// load but the event is not attached.
// err is "obj has no properties" - so prob is being accessed before it loads in Moz
// shame, as it is a lot simpler - it could replace both svLoad and svOpen - miks

	var strGet = svPath + svName + '.html';
	var svSurveyWindow = popupSurvey(strGet, svWinWidth, svWinHeight);	// open window
	// attach functionality to survey form to run svComplete function if form submitted
	var obj = svSurveyWindow.document.getElementsByTagName('form')[0];
	addEventSimple(obj,'submit',svComplete);

}
/* --------------------------------------------------------------------------------- */


/* ----- pre-initialisation ---------------------- */
// svRunSurvey is a variable set by the developer to the filename of a 
// survey which should be invoked automatically when the page loads - see 
// documentation re "invoking a survey automatically"

if (window.svRunSurvey) {
	// developer specified a survey, so supply filename to svInitSurvey function
	window.addOnload(function() { svInitSurvey(svRunSurvey); })
} else {
	// no survey specified, so search document for appropriate survey link (assumes correct ID added to link)	
	window.addOnload(svLinkSurvey);
}



/* ----- debug ----------------------------------- */
function svShowCookie(name) {
	alert(getCookie(name));
}
function svClearCookies(cookieNames) {
	var a = cookieNames.split(',');
	for (i=0;i<a.length;i++) {
		setCookie(a[i], '');
	}
}
