/**
 * This is the place for vert/aces-specific functions.
 * Don't put any direct-execution code here!
 *
 * This code relies on the prototype.js library.
 * Don't go trying to use this without FIRST including that!
 *
 * This file was coded against prototype 1.5.1.1.
 *
 * @author		dustin
 */

// Verification state machine variables
var addressVerified = false;
var phoneVerified = false;
var doVerification = false;


// Prototype Ajax.Request container, so we don't run multiple validation requests
var validationObject = false;

// Prototype Ajax.Request container, so we don't run multiple verification requests
var verifyObject = false;

// Prototype Ajax.Updater container
var switchingAjax = false;

// minirfi previous highlighted target. used so we can de-color rows quickly
var previousTarget = false;


/**
 * Runs the rfi form validation for verticals
 * Override this function for other sites...
 *
 * @author		dustin
 */
function validateForm()
{
	var formText = $('rfiForm').serialize();
	
	var url = '/requestinfo/validate.php?schoolID=' + schoolID + '&setsite=' + site;

	if ( validationObject && callInProgress(validationObject.transport) )
		validationObject.transport.abort();

	validationObject = new Ajax.Request(url, {
		method: 'POST',
		parameters: formText,
		evalScripts: true,

		// allow us a timeout before we send to server
		onLoading: function(request)
		{
			// IE6 doesn't let us add variables to the xmlhttp object
			// we can say request['timeoutID'] in prototype 1.6.0 where
			// the request object is wrapped by prototype for all browsers.
			this.validationObjectTimeoutID = window.setTimeout(
				function()
				{
					if ( callInProgress(request) )
					{
						failureFunc = validationObject.options.onFailure || Prototype.emptyFunction;
						failureFunc(request);

						//onFailure takes care of the rest...
					}
				},
				5000 // 5 seconds
			);

			$('activityIndicator').show();
		},

		onComplete: function(request)
		{
			validationObject = false;
			window.clearTimeout(this.validationObjectTimeoutID);
		},

		onFailure: function(request)
		{
			if ( callInProgress(request) )
			{
				request.abort();
			}

			validationObject = false;

			// If the ajax returns a 404 or 500 or something else undecipherable...
			// Or, if it times out...
			$('rfiForm').submit();
		}
	});
}


/**
 * This does the address and phone verification
 *
 * @author		dustin
 */
function doVerify()
{
	if ( !doVerification )
	{
		// we want to avoid verification for some reason...
		$('rfiForm').submit();
		return;
	}

	if ( !phoneVerified )
	{
		type = 'phone';
	}
	else if ( !addressVerified )
	{
		type = 'address';
	}
	else
	{
		// We're done here.
		$('rfiForm').submit();
		return;
	}

	formText = $('rfiForm').serialize();
	url = '/requestinfo/verify.php?schoolID=' + schoolID + '&setsite=' + site + '&type=' + type;

	if ( verifyObject && callInProgress(verifyObject.transport) )
		verifyObject.transport.abort();

	verifyObject = new Ajax.Updater({success: 'lightbox'}, url, {
		method: 'POST',
		parameters: formText,
		evalScripts: true,

		// allow us a timeout before we send to server
		onLoading: function(request)
		{
			this.verifyObjectTimeoutID = window.setTimeout(
				function()
				{
					if ( callInProgress(request) )
					{
						// Now, if you just say lbhandler, it'll throw an exception
						// and stop execution if it's undefined. But, if you use this.lbhandler,
						// it won't throw an exception.. go javascript!
						// How it's undefined when phoneValidated is defined is a secret only IE programmers know
						if ( this.lbhandler )
						{
							// Now we're in a situation where we've timed out, but the
							// request has actually completed just fine. The clearTimeout
							// was never triggered. Why? Only IE programmers know...

							// So, it's not a failure. Ignore it.
							return;
						}

						failureFunc = verifyObject.options.onFailure || Prototype.emptyFunction;
						failureFunc(request);

						//onFailure takes care of the rest...
					}
				},
				7000 // 7 seconds
			);

			$('activityIndicator').show();
		},

		onComplete: function(request)
		{
			verifyObject = false;
			window.clearTimeout(this.verifyObjectTimeoutID);
		},

		onFailure: function(request)
		{
			if ( callInProgress(request) )
			{
				request.abort();
			}

			// If we get a 404 or 500 from the server, or some other failure...
			// Let's mark this one as already verified, and move on..
			if ( type == 'phone' )
			{
				phoneVerified = true;
			}
			else if ( type == 'address' )
			{
				addressVerified = true;
			}

			verifyObject = false;

			// It's a timeout so nothing changed. Let's just go to next verify step.
			doVerify();
		}

	});
}



/**
 * Chooses a school from the div list
 *
 * @author		dustin, others
 */
function schoolSelect(id, item, site, synd, collapse)
{
	if ( typeof site == 'undefined' )
		site = '';

	if (typeof synd == 'undefined' )
		synd = '';
		
	if (typeof collapse == 'undefined' )
		collapse = '0';

	if ( switchingAjax && callInProgress(switchingAjax.transport) )
		switchingAjax.transport.abort();

	colorit(id);
	showstatus('loading...');
	loadit(item, site, synd,collapse);
	changeStep();

	// set schoolID in global space...
	schoolID = item;
}


/**
 * Shows a status update (like loading...)
 *
 * @author		dustin, others)
 */
function showstatus(message)
{
	$('status').show().innerHTML = message;
}


/**
 * Applies coloring for selected school
 *
 * @author		dustin, others
 */
function colorit(id)
{
	$(id).className = 'selected';

	if ( previousTarget != '' && previousTarget != id )
	{
		$(previousTarget).className = 'deselected';
	}

	previousTarget = id;
}


/**
 * Changes the step in the minirfi.
 *
 * @author		dustin, others
 */
function changeStep()
{
	target = $("stepone");
	target.className = "step";
	target = $("steptwo");
	target.className = "currentstep";
}


/**
 * Runs the mini rfi validation
 *
 * @author		dustin
 */
function minirfiValidator()
{
	// We don't want to do verification on the mini rfi
	doVerification = false;
	validateForm();
}


/**
 * After a program is selected, show the next one
 *
 * @author		dustin
 */
function showNext(fieldNum)
{
	if ( $('specDiv'+(1+fieldNum)) != null )
		$('specDiv'+(1+fieldNum)).style.display='';
}
