/*
 * Javascript functions specific for  session timeout warning /redirect in adaptive package flow pages,
 * The script requires Prototype 1.6+.
*  The script also assumes that the startaction to initiate the adaptive flow is either "VisaProduct.do" or "setupPackage.do"
*  Url's containing that will be considered a valid restartURL if the session times out.
  *
 * @author mace09, jace21
 *
 * Change History <br>
 * Date       Author Comment <br>
 * ---------- ------ ---------------------------------------------- <br>
 * 2008-10-12 mace09,jabe21 Initial version.
 * 2008-10-15 mace09 Fixed IR28315
 * 2008-10-22 mace09 Fixed IR28323 
 */
 
 //Hook in initialization script
Event.observe(window,"load",createTimerObject);

//page scoped variable to hold a reference to our timer class instance
var sessionTimer;

//initialize contstants
var TOTAL_DELAY_MS= 9.70 * 60 * 1000; //Timeout redirect after 9 minutes and 42 sec. (Actual server / subsystem connection  timeout is 10 minutes)
var POPUP_WARNING_DELAY_MS= 8 * 60 * 1000; //First timer warning should appear after 8 minutes.
var COUNTDOWN_INTERVAL_MS=60000; // Update countdown every 60 sec.
var DIVIDER = 60000;
var RESTARTURL_COOKIE_KEY="AdaptiveFlow_restartUrl";



function createTimerObject() {
	//create an object instance of the timer
	sessionTimer = new SessionTimer();
	sessionTimer.reset(false);
}

//Create our session timer Class
var SessionTimer = Class.create({
  initialize: function() {
	//If this is the starting point in the flow. Keep a reference to the starting point
	var href = location.href;
	if ((href.indexOf('VisaProdukt.do')>0) || ((href.indexOf('setupPackage.do')>0))){
		this.setCookie(RESTARTURL_COOKIE_KEY, href,'','/');	
	} 
	
	this.redirectUrl = this.getCookie(RESTARTURL_COOKIE_KEY);
	if (!this.redirectUrl) this.redirectUrl=href;
	//write out html for warning div.
	Element.insert(document.body,'<div id="orderflow-timeout-message"><p id="orderflow-timeout-hide"><a href="#">Stäng meddelandet</a></p><h3></h3><div class="inner"><h4><span id="minutesleftSpan1">2 minuter</span> kvar</h4>' +
    							 '<p>Din beställning kommer att avbrytas om <span id="orderflow-timeout-counter"><span id="minutesleftSpan2">2 minuter</span></span> på grund av inaktivitet.<br />' +
								 'Tryck <strong>"Fortsätt"</strong> för att återgå till din beställning.</p><p id="orderflow-timeout-continue" alt="Fortsätt beställa" title="Fortsätt beställa"><span><a href="javascript:">Fortsätt beställa</a></span></p></div></div>');
	
	//Hook in extra event for all buttons (href's) containing text "document.adaptiveForm" in this form.
	//These links are the flow navigation buttons, and if they are clicked, the page will be reloaded.
	
	this.onAdaptiveFormClickListenerRef = this.onAdaptiveEvent.bindAsEventListener(this);
	var element = document.adaptiveForm.getElementsByTagName('a');
	i=0;
	while(i < element.length){
		var href = element[i].href;
		// Get all the links that contain "document.adaptiveForm" and add Event.observe
		if (href.include('document.adaptiveForm')) {
			Event.observe(element[i],"click",this.onAdaptiveFormClickListenerRef);
		}
		i++ ;
	}
	
	
  },
  onResetEvent: function() {
	//debug("onResetEvent");
	this.reset(true);
  },
  onAdaptiveEvent: function() {
	//debug("onAdaptiveEvent");
	this.reset(false);
  },
  onPopupWarningEvent: function() {
	//debug("onPopupWarningEvent");
	
	//Register onclick on entire page to trigger the sessionTimeout  reset function. Must use bindAsEventListener to avoid loss of context
	//Call with true as parameter to trigger the serverping
	this.onClickListenerRef = this.onResetEvent.bindAsEventListener(this);
	
	// This object's reset() method should be called whenever the user clicks on the page och presses a key.
	Event.observe(document.body,"click",this.onClickListenerRef);
	Event.observe(document.body,"keyup",this.onClickListenerRef);
	
	//Also, start the countdown to redirect
	this.countdownTimerHandle  = setTimeout(this.onDisplayCountdownEvent.bind(this, 1), COUNTDOWN_INTERVAL_MS);
	this.updateMessage(((TOTAL_DELAY_MS - POPUP_WARNING_DELAY_MS) / DIVIDER));
  },

  onDisplayCountdownEvent: function(invocationCount) {
		//debug("onDisplayCountdownEvent");
		//This is just the first warning..
		var minutesLeft = ((TOTAL_DELAY_MS - POPUP_WARNING_DELAY_MS) - (invocationCount * COUNTDOWN_INTERVAL_MS)) / DIVIDER;
		this.updateMessage(minutesLeft);
		//Also, start a callback timer to this method (to update countdown text)
		this.countdownTimerHandle  = setTimeout(this.onDisplayCountdownEvent.bind(this, (invocationCount+1)), COUNTDOWN_INTERVAL_MS);
  },
  
  onRedirectEvent: function() {
	//reset timers
	this.reset(false);
	this.clearAllTimers();
	//debug("onRedirectEvent");
	
	// html code with the content for the time out page
	var fragment = '<div id="sessionContentMain"><div id="sessionInnerContent"><div id="sessionInnerContentMessage" class="contentPadding">' +
				   '<h1>Avbruten beställning  </h1><span class="contentPadding">Din beställning har avbrutits på grund av 10 minuters inaktivitet. Vi ber dig börja om med din beställning.</span>' +
				   '<div id="startOverButton"><a href="' + this.redirectUrl + '">' +
				   '<img border="0" src="/img/buttons/btn_borja_om.png" alt="Börja om" title="Börja om" width="92" height="19" /></a></div></div></div></div>';

	//
	//	Last we replace the contents of entire form with the snippet. 
	//	This way, we avoid making a server roundtrip via a redirect. Otherwise the session 
	//  would be extended, which sort of contradicts the purpose of this script....
	//
	$(document.adaptiveForm).replace(fragment);
				   
  },

  reset: function(doServerPing) {
	//debug("reset: doServerPing = "  + doServerPing);
	 //stop listeing for click on anything
	Event.stopObserving(document.body,"click",this.onClickListenerRef);
	Event.stopObserving(document.body,"keyup",this.onClickListenerRef);
	//reset timers
	this.clearAllTimers();
	this.popupTimerHandle = setTimeout(this.onPopupWarningEvent.bind(this), POPUP_WARNING_DELAY_MS);
	//Set a timeout for redirect
	this.redirectTimerHandle = setTimeout(this.onRedirectEvent.bind(this), TOTAL_DELAY_MS);

	//hide message
	$("orderflow-timeout-message").style.display = "none";
	
	//Server ping needed?  
	if (doServerPing) {
		//Get a reference to the active form object
		var formObj = document.adaptiveForm;
		
		//Indicate what method/action we want to execute in the FlowController
		formObj.command.value = 'justPing';
		
		//Make the request
		var ajaxRequest = new Ajax.Request(
				formObj.action, 
				{
					method: 'post',
					parameters: $(document.adaptiveForm).serialize(true),
				onComplete: 
					function(transport) {
						//debug("onComplete()");
					}
			});
	}	
  },
 	clearAllTimers: function() {
		clearTimeout(this.redirectTimerHandle);
		clearTimeout(this.popupTimerHandle);
		clearTimeout(this.countdownTimerHandle);
  },

	updateMessage: function(minutesLeft) {
	
		minutesLeft = Math.round(minutesLeft);
		minutesLeft+= (minutesLeft > 1) ? ' minuter' : ' minut';
	
		//show warning message div.
		var scroll = Element.viewportOffset(document.body).top;
		//calculate center position
		var screenDimensions = Element.getDimensions(document.body);

		$("orderflow-timeout-message").style.top = $("orderflow-timeout-message").getHeight() *2 + (-1 * scroll);
		$("orderflow-timeout-message").style.left = (screenDimensions.width / 2) - ( $("orderflow-timeout-message").getWidth() / 2);
		$("orderflow-timeout-message").style.display = "block";

		Element.update($("minutesleftSpan1"),minutesLeft);
		Element.update($("minutesleftSpan2"),minutesLeft);
	},
	getCookie: function getCookie( name ) {
		var start = document.cookie.indexOf( name + "=" );
		var len = start + name.length + 1;
		if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
			return null;
		}
		if ( start == -1 ) return null;
		var end = document.cookie.indexOf( ';', len );
		if ( end == -1 ) end = document.cookie.length;
		return unescape( document.cookie.substring( len, end ) );
	},
	setCookie: function ( name, value, expires, path, domain, secure ) {
		var today = new Date();
		today.setTime( today.getTime() );
		if ( expires ) {
			expires = expires * 1000 * 60 * 60 * 24;
		}
		var expires_date = new Date( today.getTime() + (expires) );
		document.cookie = name+'='+escape( value ) +
			( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
			( ( path ) ? ';path=' + path : '' ) +
			( ( domain ) ? ';domain=' + domain : '' ) +
			( ( secure ) ? ';secure' : '' );
	}



});