function sessionCookieTroubleShooter() {
  var sessionValue = null;
  var undefined;

  function getSessionCookie(sessionName) {
    return getXCookie(sessionName);
  }
  
  function setSessionCookie(doc, name, value) {
    var today = new Date();
    expires = new Date(today.getTime() + 28 * 24 * 60 * 60 * 1000);
    path="/";
    if(value == null || value == "null") return;
    doc.cookie = name + "=" + value + ";expires=" + expires.toGMTString() + ";path=" + path;
  }
  
  function getExternalCookie(name, externalDocument) {
    var start = externalDocument.cookie.indexOf(name + "=");
    var len = start + name.length + 1;
    if((!start) && (name != externalDocument.cookie.substring(0, name.length)))
      return null;
    if(start == -1)
      return null;
    var end = externalDocument.cookie.indexOf(";", len);
    if(end == -1)
      end = externalDocument.cookie.length;
    return unescape(externalDocument.cookie.substring(len, end));
  }
  
  //@doc is the document object
  function ensureSession(doc) {
      var jsessionid = null;
      var sessionName = null;
      for(s in belenusHome.sessionName) {
        if(getSessionCookie(belenusHome.sessionName[s]) != null) { 
          sessionName = belenusHome.sessionName[s];
          break;
        }
      }
      var openerwindow = window;
      var loops = 15;
      setSessionCookie(doc, sessionName, getXCookie(sessionName));
      belenusHome.sessionName = sessionName;
      return getXCookie(sessionName);
      //return "static version, no session cookie exist";
      /*
      while(jsessionid == null) {
        if(loops-- < 1 || !openerwindow.top.opener)
          break;
        jsessionid = getXCookie(sessionName);
        if(jsessionid != null) {
          setSessionCookie(doc, sessionName, jsessionid);
          belenusHome.sessionName = sessionName;
          return jsessionid;
        }
        openerwindow = openerwindow.opener;
      }
      return sessionValue;
      */
  }

  this.ensureSession = ensureSession;
  this.setSessionCookie = setSessionCookie;

}

belenusHome.SC = new sessionCookieTroubleShooter();
var sessionCookie = belenusHome.SC.ensureSession(self.document);
