/**
 * This is the temporary JS used to control the page/form flow in TravelProfits.
 * There is still much work to be done, but this allows the interim logic to
 * be shared among the current sites.
 *
 * $Id: handleFlow.js 3604 2009-08-13 17:24:51Z tpuhlick $
 *
 * @author Chris Lewis <clewis@ocenture.com>
 */

/**
 * This function is the temporary brain of the TravelProfits flow control.
 * It should be called in the document <head></head>.
 */
function handleFlow() {
	
	var path = location.pathname;
	while(path.endsWith('/') && path.length > 1)
	path = path.substr(0, path.length - 1);
	
	if ( typeof( pagesArray ) == "object" ) {
		var pageSequence = new Array();
		for ( i=0; i < pagesArray.length; i ++ ) {			
			pageSequence[ i ] = new FlowPage( new Array(pagesArray[ i ]) );
		}
	} 
	else {
		var pageSequence = [
			new FlowPage(['/SignUp']),
			new FlowPage(['/BillingInfo']),
			new FlowPage(['/Processing']),
			new FlowPage(['/ChoosePlan']),
			new FlowPage(['/SpecialOffer']),
			new FlowPage(['/Summary'])
		];
	}	
	
	var flow = new WebFlow(pageSequence, path);
	
	var lastUrl = Cookies.get('lastUrl');
	
	if(lastUrl == null) {
		
		/*
		* This is a fresh visit, so make sure that if the current
		* path is in the flow, that the flow is just starting.
		* Otherwise this is a breach and we must redirect.
		*/
		if(! flow.isStarting() && flow.inFlow(path))
		location.href = '/';
		
	} else {
		
		if(! flow.isStarting() && ! flow.inFlow(lastUrl) && flow.inFlow(path)) {
			location.href = lastUrl;
		} else if(flow.isBefore(lastUrl)) {
			alert("We're sorry, but clicking the back button at this time may erase your current browser session and require you to call customer service to complete your order.  Please click 'OK' below to remain on this page and complete your order.");
			Cookies.set('lastUrl', flow.getPrevious(lastUrl).getPath(), 1, '/');
			location.href = lastUrl;
		} else if(! flow.isJustAfter(path) && false) {
			// FIXME
			//alert('cant skip!');
		} else if(flow.atEnd()) {
			Cookies.remove("lastUrl");
		}
		
		
	}
	
	Cookies.set('lastUrl', path, 1, '/');

}


// This results in a window.onunload handler, which prevents FF caching.
Event.observe(window, 'unload', function() {});


// Run it!
handleFlow();