
logInterval = 30000; //the time between attempts to save the activity back to the database
responder = '/ajax/session_timeout_responder.html';

actionCount = 0; //global count of actions for tracking activity.
lightboxOpen = false; //global for whether the sign out lightbox window is open
cookieExpire = 0; //global number of days for the session status cookie to last before expiration.

function logActivity()
//record recent activity/inactivity back to the Customizer via AJAX; the Customizer will return whether to sign out based on inactivity
{
	// alert("DEBUG: sessionID: " + sessionID);
    
    var currentStatus = readCookie('MYP_SESSIONSTATUS');    
    var sessionID = readCookie("MYP_SESSION");
    
    if (sessionID) {
        new Ajax.Request( responder,
        	      { method:'post',
        	        parameters: {session_id: sessionID, activity: actionCount, windowopen: lightboxOpen},
        	        onSuccess: function(transport){
        	            var ryes = /signout=yes/i;
                            if ( ryes.test(transport.responseText) ) {
                                if (currentStatus != 'active') {
                                    if (lightboxOpen) {
                                        Sign_Out();
                                    } else {
                                        displayTimeOutMessage();
                                    }
                                }
                            }
         	        },
        	        onFailure: function(transport){
        	        	alert("ajax failure!");
        	        }
        	      });
        
        
        if (currentStatus == 'active') {
            if (lightboxOpen) close_lightbox2();
        } else if (currentStatus == 'signed_out') {
            Sign_Out();
        }
        
        //reset the action count
        actionCount = 0;
        writeStatus('inactive');
        
    } else { //if there's no sessionID then we should be already signed out
        Sign_Out();
    }
}

function recordActivity(){
	actionCount++;
        writeStatus('active');
        return true;
}

function Continue_Working()
{
    recordActivity();
    close_lightbox2();
    lightboxOpen = false;
}

function signOutAllowed()
{ //only do the signout stuff if we're not already on the logout/in page and only on the "top" window (not in iframes)
    if (window.self == window.top && !window.location.pathname.match(/login\.html/) && !document.getElementById("logged_out")) { 
        return true;
    } else {
        return false;
    }
}

function Sign_Out()
{
    var currentStatus = readCookie('MYP_SESSIONSTATUS');
    if (currentStatus != 'signed_out') writeStatus('signed_out');
    if (signOutAllowed()) window.location.href="/your_order/Home?logout=yes";
}

function displayTimeOutMessage()
//display a message in a light box with options to continue working or sign out
{
    if (signOutAllowed()) {
        var message =   "<div id='timeout_box'>"+
                        "<p>You are about to be automatically signed out due to inactivity.</p>"+
                        "<p>To continue working, click the Continue Working button below.</p>"+
                        "<div class='pa-ButtonWrapper'>"+
                        "    <a id='Sign_Out' class='pa-Button' href='javascript:Sign_Out();'><span>Sign Out Now</span></a>"+
                        "</div>"+
                        "<div class='pa-ButtonWrapper'>"+
                        "    <a id='Continue_Working' class='pa-Button' href='javascript:Continue_Working();'><span>Continue Working</span></a>"+
                        "</div>"+
                        "</div>";
            
        openLightBox2( message, "530", "360", 1, 1 );
        lightboxOpen = true;
    }
}

function writeStatus(status)
{
    var currentStatus = readCookie('MYP_SESSIONSTATUS');
    if (currentStatus != 'signed_out') {
        createCookie('MYP_SESSIONSTATUS', status, cookieExpire);
    } else {
        Sign_Out();
    }
}

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 init()
{
    //listen for mousedowns and keydowns on the document and if they happen stop the timeout
    YAHOO.util.Event.addListener(document, "mousedown", recordActivity);
    YAHOO.util.Event.addListener(document, "keydown", recordActivity);
    
    writeStatus('inactive');
}

var activityInterval = window.setInterval("logActivity()", logInterval);

YAHOO.util.Event.onDOMReady(init);

