// We use Ajax to periodically hit an eRights protected url to extend the 
// user's A&E session when viewing some of the premium content types...

// We don't really care about the response - the following were helpful
// during initial development/debugging:

var pingIntervalMinutes = 5;
var maxRetries = 3;
var retryIntervalSeconds = 20;

function handlePingResponse(type, data, evt){
//	alert( "got ping response: " + data);

	// Did A&E successfully extend their session?
	if(data.indexOf("<successful>") == -1) {
		// Nope:  how many times have we tried?	
		if(ioRequest && ioRequest.attemptNumber && ioRequest.attemptNumber < maxRetries) {
			// Let's try again:
			var attempt = ioRequest.attemptNumber + 1;
			setTimeout("pingOnce(" + attempt + ")", retryIntervalSeconds * 1000);      
		}	
	}
}

function handlePingError(type, data, evt, ioRequest) {
//	alert("got ping error: " + data.message);
      
      // We've occasionally seen XMLHttpTransportErrors = 404 page not found
      // We *think* these are simple network failures - so wait a bit and
      // try again:
      if(ioRequest && ioRequest.attemptNumber && ioRequest.attemptNumber < maxRetries) {
      	var attempt = ioRequest.attemptNumber + 1;
		setTimeout("pingOnce(" + attempt + ")", retryIntervalSeconds * 1000);      
      }
}

var keepAliveUrl = "../r/util.dx?method=keepAlive";

var timerId = -1;

var ioRequest = {
        method: "GET",
        load: handlePingResponse,
        error: handlePingError,
        url: "(set dynamically)",
        useCache: false
}

// Ping the server repeatedly to keep our session alive
function ping(attemptNumber){

		// we're done with this timer (make sure we don't try and clear for no reason):
		timerId = -1;
		
		pingOnce();
        
        // We'll ping again after another X minutes
        keepAlive();
}

// Ping the server (just once) to keep our session alive
function pingOnce(attemptNumber){
        //alert("starting the ajax call!");
        var d = new Date();
        
        if(attemptNumber) {
        	ioRequest.attemptNumber = attemptNumber;
        }
        else {
        	ioRequest.attemptNumber = 1; // this is our first attempt         
        }
        ioRequest.url = keepAliveUrl + "&viewId=" + d.getTime();
        dojo.io.bind(ioRequest);
}

// Keep our session alive by repeatedly pinging the server
// (this is the function external callers should call who wish
// to keep their session alive).
function keepAlive(inactivityGracePeriodMinutes){

		// We should only have one (and only one) timer!
		if(timerId != -1) {
			clearTimeout(timerId);
		}
		
		if((typeof(inactivityGracePeriodMinutes) != 'undefined') || inactivityGracePeriodMinutes >= 0) {
			
			// We will cancel the timer after the time period they gave:
	        setTimeout("cancelKeepAlive()", inactivityGracePeriodMinutes * 60 * 1000);
		}
        // Ping the server every pingIntervalMinutes minutes
        timerId = setTimeout("ping()", pingIntervalMinutes * 60 * 1000);
}

function cancelKeepAlive() {
		
		// This makes the final call to A&E to keep the session before timeout
		// to ensure the timeout occurs 15 minutes from now
		pingOnce();
		// We should only have one (and only one) timer!
		if(timerId != -1) {
			clearTimeout(timerId);
		}
}

// Popup matching MedLine journal articles if the user clicks a journal
// reference link.
// Note:  The app can point the variable "popupJournalArticle" at this
//        function to "plug-in" this way of handling journal articles.
function popupMedLineJournalArticle(evt)
{
        // Updating internal timer and updating A&E timeout
        userActivity();
        pingOnce();

        // 'this' should be the actual anchor tag DOM element...
        // this replaces the full article title for the journal name - RJM 4/24/08
        if(this.journalArticleShortTitle) {
                //Strip out all punctuation
                var title = URLDecode(this.journalArticleShortTitle).replace(/[^a-zA-Z 0-9\']+/g,' ');

                var medLineURL = 'http://www.ncbi.nlm.nih.gov/sites/entrez?cmd=search&term="' + title + '"[Jour]';
                
                if(this.journalArticleDate) {
                   medLineURL += ' AND ' + this.journalArticleDate.substring((this.journalArticleDate.length - 4), this.journalArticleDate.length) + '[pdat]';
                }
   
                if(this.journalArticleVolume) {
                   medLineURL += ' AND ' + this.journalArticleVolume.replace(/[A-Z]/g,' ') + '[volume]';
                }
                
                if(this.journalArticleIssue) {
                   medLineURL += ' AND ' + this.journalArticleIssue.replace(/[A-Z]/g,' ') + '[issue]';
                }
                
                if(this.journalArticlePage) {
                   medLineURL += ' AND ' + this.journalArticlePage + '[page]';
                }
                
                openNewWindow(medLineURL, "MedLine", 700, 600, 100, 150);
        }

        // Don't follow the link we've popped up the window ourselves.
        return false;
}
