
/* --------------------------------------------------------------------------*
 *              session plugin                                             *
 * Note:this script relies on code from /pathways/zxml.js                    *
 *---------------------------------------------------------------------------*/

//* Global Variables *
var hostElementID;
var dbg = 0;
var sessionPtr;
var app_id;

var SessionData = Class.create(AjaxPlugin, {
    
  initialize: function (element_id, app_id)
  {
    // Remember our host element
    hostElementID = element_id;
    sessionPtr = this;
    appId = app_id;
    
    this.setupSessionName();
    
    // Create a client-side cache:
    this.cache = new Object();
    
    // Use a Queue to save parameters to the back-end in order:
    this.serverQueue = new Array();
    this.saveInProgress = false;
    
    // Figure out our server path, so we can call our back-end reliably
    $$('script').each(function(script){
        if (script.src.match(/sessionData\.js/)) 
        {
          this.serverpath = script.src.replace(/sessionData\.js/, 'sessionData.php') +
          '?session_id='+this.session_name; 
        }
    }.bind(this));
    
    //*---------------------------------------------------------------------------*
    // Main: Call the initializeHtml function we just defined:
    if (hostElementID && !hostElementID.empty())
    {
      this.initializeHtml();
    }

    this.connect();

  },
  
  setupSessionName: function()
  {
    this.session_name = this.getCookieVal('GA_SESSID');
    if (this.session_name == null || this.session_name == '') {
      this.session_name = GA_UTIL.getUID();
    }
    // Make the session ID persistent for 1 month
    this.setCookieVal('GA_SESSID', this.session_name, 1, 'months');
  },

  //*---------------------------------------------------------------------------*
  initializeHtml: function()
  {
	 var myHtml = "<div id=\"divSessionInfo\"></div>";
				  
    // Add this HTML to our host element
    var hostElement = document.getElementById(hostElementID);
    if (dbg == 1) alert ("this.initializeHtml-hostElement: " + hostElement.id);
    hostElement.innerHTML = myHtml;
  },

  newSession: function()
  {
    // Create a brand new, empty session:
    
    var URL = this.serverpath + "&cmd=new&" + Math.random();
    new Ajax.Request(URL, 
                     {
                       method: 'get',
                       asynchronous: false,
                       onSuccess: function(transport) 
                         {
                           if ($("divSessionInfo")) // if it exists
                             $("divSessionInfo").innerHTML = transport.responseText;
                         },
                       onFailure: function(transport)
                         {
                           alert("ajax call error: " + URL + 
                                 " - " + transport.statusText);
                         }                         
                     });
    
    
  }, // End of this.newSession()

  connect: function()
  {
    // Connect to an existing session, if one exists:
    var URL = this.serverpath + '&cmd=connect&cacheStop=' + Math.random();
    new Ajax.Request(URL, 
                     {
                       method: 'get',
                       onSuccess: function(transport) 
                         {
                           if ($("divSessionInfo")) // if it exists
                             $("divSessionInfo").innerHTML = transport.responseText;
                         },
                       onFailure: function(transport)
                         {
                           alert("ajax call error: " + URL + 
                                 " - " + transport.statusText);
                         }                         
                     });
    
    
  }, // End of this.connect()

  setSession: function(session_id)
  {
    // Tell the server to connect to a specific session:
    //(this could be done just by setting a cookie here, right??)
    var URL = this.serverpath+'&cmd=setSession&session_id='+ session_id +
              '&' + Math.random();;
    new Ajax.Request(URL, 
                     {
                       method: 'get',
                       asynchronous: false,
                       onSuccess: function(transport) 
                         {
                           if ($("divSessionInfo")) // if it exists
                             $("divSessionInfo").innerHTML = transport.responseText;
                         },
                       onFailure: function(transport)
                         {
                           alert("ajax call error: " + URL + 
                                 " - " + transport.statusText);
                         }                         
                     });
    
  }, // End of this.setSession()

  saveQueueContents: function()
  {
    if (this.saveInProgress) { return; }
    this.saveInProgress = true;

    // Start saving the queue contents asynchronously:
    this.recursivePopAndSave();
    
  },
  
  recursivePopAndSave: function()
  {
    
    var command = null;
    if (this.serverQueue.length > 0)
    {
      command = this.serverQueue.pop();
    }
    
    if (command === null)
    {
      this.saveInProgress = false;
      return;
    }
    
    var cmd = command[0];
    var var_value  = command[1];
    var varName = var_value[0];
    var value   = var_value[1];
    
    var URL=this.serverpath;
    new Ajax.Request(URL, 
                     {
                       method: 'post',
                       parameters: {
                                    cmd:     'set',
                                    varName: varName,
                                    value:   value
                                   }, //command,
                       onSuccess: function(transport) 
                         {
                           sessionPtr.recursivePopAndSave();
                         },
                       onFailure: function(transport)
                         {
                           alert("ajax call error: " + URL + 
                                 " - " + transport.statusText);
                         }                         
                     });

  },
  
  newSessionByQueue: function()
  {
    // enqueue a command:
    this.serverQueue.unshift("cmd=new");
    
    this.saveQueueContents();

  }, // End of this.initializeHtml()


  //*---------------------------------------------------------------------------*
  setParam: function(param, value)
  {
    param = appId + "_" + param;
    // If the incoming value is the current value, then just ignore the request:
    if (this.cache[param] != null && this.cache[param] == value)
    {
      return;
    }
    
    // Save the value in our cache:
    this.cache[param] = value;
    
    var command = ['set', [param, encodeURIComponent(value)]];
    
    // enqueue a command to save it:
    this.serverQueue.unshift(command);
    
    this.saveQueueContents();

  }, // End of this.setParam()

  //*---------------------------------------------------------------------------*
  getParam: function(param)
  {
    param = appId + "_" + param;
    // Check our cache for the most current value
    if (this.cache[param] != null)
    {
      return this.cache[param];
    }
    
    var xmlHttp = zXmlHttp.createRequest();
    var cacheStopper = Math.random();
    var URL = this.serverpath + '&cmd=get&varName='+param+'&cachestopper='+cacheStopper;
    xmlHttp.open("get", URL, false);
    xmlHttp.send(null);
    if (xmlHttp.status == 200) {
      return xmlHttp.responseText;
    } else {
        alert("session.js getParam error: " + URL + " - " +
              xmlHttp.statusText); //statusText is not always accurate
    }
    
  }, // End of this.getParam()

  //*---------------------------------------------------------------------------*
  delParam: function(param)
  {
    param = appId + "_" + param;
    // Delete the parameter from our cache:
    this.cache[param] = null;

    // enqueue a command to save it:
    this.serverQueue.unshift("cmd=del,"+param);
    
    this.saveQueueContents();
  }, // End of this.delParam()

  resetSessionData: function()
  {
    if (confirm('This will reset your page and remove your selected targets.'+
                "\nIs that OK?"))
    {
      this.newSession();
      window.location.href=window.location.href; // reloads the page
    }
  }
});// End of session 

