//========================
//--- SessionHttpRequest 
//========================

/*
url-loading object and a request queue built on top of it
*/

/* namespacing object */
var net=new Object();

net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;


/*--- content loader object for cross-browser requests ---*/
net.ContentLoader=function(url,onload,onerror,method,params,contentType){
  this.req=null;
  this.onload=onload;
  this.onerror=(onerror) ? onerror : this.defaultError;
  this.loadXMLDoc(url,method,params,contentType);
}

net.ContentLoader.prototype.loadXMLDoc=function(url,method,params,contentType){
  if (!method){
    method="GET";
  }
  if (!contentType && method=="POST"){
    contentType='application/x-www-form-urlencoded';
  }
  if (window.XMLHttpRequest){
    this.req=new XMLHttpRequest();
  } else if (window.ActiveXObject){
    this.req=new ActiveXObject("Microsoft.XMLHTTP");
  }
  
  if (this.req){
    try{
      var loader=this;
      this.req.onreadystatechange=function(){
        net.ContentLoader.onReadyState.call(loader);
      }
      this.req.open(method,url,true);
      if (contentType){
        this.req.setRequestHeader('Content-Type', contentType);
      }
      this.req.send(params);
    }catch (err){
      this.onerror.call(this);
    }
  }
}


net.ContentLoader.onReadyState=function(){
  var req=this.req;
  var ready=req.readyState;
  if (ready==net.READY_STATE_COMPLETE){
    var httpStatus=req.status;
    if (httpStatus==200 || httpStatus==0) {	
		//alex r: skip if session ended by Session.Abandon()
		if ( this.req.responseText.indexOf("Session Ended:")!= 0 ) {
		this.onload.call(this);
		}
    }else{
      this.onerror.call(this);
    }
  }
}

net.ContentLoader.prototype.defaultError=function(){
  alert("error fetching data!"
    +"\n\nreadyState:"+this.req.readyState
    +"\nstatus: "+this.req.status
    +"\nheaders: "+this.req.getAllResponseHeaders());
}

//========================================================================
      //------------------------------------------------------
      // SessionTimeoutTimer
      //------------------------------------------------------
      function SessionTimeoutTimer(strLength){

			//Set all of the defaults      
			this.loaded = false;
			this.intHeight = 600;
			this.intDivHeight = 150;
			this.objDiv = null;
			this.objIFr = null;
			this.top = 0;
			this.sessionLength = 1000*60*20 //1000*60*20;
			if(typeof(strLength)!="undefined")this.sessionLength = strLength;
			var timerWarn = window.setTimeout(loadMessage,this.sessionLength);
			this.maxWait = 1000*60*5;
			this.title = "Timeout Notification";
			this.message = "Your current session is about to expire. " + 
						"In order to remain logged in and avoid losing " + 
						"any data you may have entered, please press " + 
						"the <span style='color:green'>Continue</span> button " +
						"to extend your session.";
			this.confirm = "Continue";
			this.ignore = "Exit";
			this.extendedMessage = "Your session has most likely been expired. " +
								"Press the <span style='color:green'>Confirm</span> " +
								"button to verify this."
			this.URL_SessionExtend = null;
			this.URL_SessionEnd=null;
			//this.URL_RedirectOnSessionEnd = null;
			var ref = this;
        
        //some local(private) varaibles
		var timerScroll = null;
		var timerReject = null;
		var intStep = 2;
		var intStop = Math.floor(ref.intHeight/5);
    	var timerUpdate = null;
		var intDotCount = 0;
		var timerWait = null;
        
        
        //------------------------------------------------------
        //determine browser height and height of div
        //------------------------------------------------------
        function calcBrowserSize()
        {
        	if(self.innerHeight){
				ref.intHeight = self.innerHeight;
				ref.intDivHeight = ref.objDiv.scrollHeight;
			}
			else if(document.documentElement && document.documentElement.clientHeight){
				ref.intHeight = document.documentElement.clientHeight;
				ref.intDivHeight = ref.objDiv.clientHeight;
			}
			else if(document.body){
				ref.intHeight = document.body.clientHeight;
				ref.intDivHeight = ref.objDiv.clientHeight;
			}
			ref.intHeight = parseInt(ref.intHeight);
			ref.intDivHeight = parseInt(ref.intDivHeight);
			}

		//------------------------------------------------------
        //Start to display message on scroll
        //------------------------------------------------------
        function loadMessage(){
        
          if(ref.loaded == false)ref.loaded = createConfirm();        
          //set reference
          ref.objDiv = document.getElementById("divSessionTimer");
          ref.objIFr = document.getElementById("ifSessionTimer");
          
          //position block off screen and show it
          ref.objDiv.style.top = "-1000px";
          ref.objIFr.style.top = "-1000px";
          
          //added by alex: set vertical positi0n
          ref.objDiv.style.left="180px";
		  ref.objIFr.style.left="180px";

          ref.objDiv.style.display = "block";
          ref.objIFr.style.display = "block";
          if(navigator.userAgent.toLowerCase().indexOf("opera") != -1)ref.objIFr.style.visibility = "hidden";
          
          //Set all of the elements text
		  document.getElementById("divBut").style.display = "block";
		  document.getElementById("divContent").innerHTML = ref.message;
		  document.getElementById("divTitle").innerHTML = ref.title;
		  document.getElementById("B1").value = ref.confirm;
		  document.getElementById("B2").value = ref.ignore;
		  
		  //position block to top edge of screen
          calcBrowserSize();
          ref.objDiv.style.top = -ref.intDivHeight + "px";
          ref.objIFr.style.top = -ref.intDivHeight + "px";
          
          //prepare block to be scrolled in
          ref.top = -ref.intDivHeight;
          timerScroll = window.setInterval(scrollIn,1);
          timerWait = window.setTimeout(EndSession,ref.maxWait);
        }
        
		//------------------------------------------------------
        //Determine how much user scrolled page down
        //------------------------------------------------------
        function GetScroll()
        {     
          var scrollY = document.documentElement.scrollTop;
          if(!scrollY)scrollY = document.body.scrollTop;            
          if(!scrollY)scrollY = window.pageYOffset;               
          if(!scrollY)scrollY = 0;
          return scrollY;
        }
        
		//------------------------------------------------------
        //Function moves confirmation window into view
        //------------------------------------------------------
        function scrollIn(){
        
			if(parseInt(intStep) + parseInt(ref.top) <= parseInt(intStop) ){
				ref.top += intStep;
				var intT = ref.top + GetScroll();;
				ref.objDiv.style.top =  intT + "px";
				ref.objIFr.style.top =  intT + "px";
			}
			else{
				var cancel = window.clearInterval(timerScroll);
				ref.objDiv.style.top = GetScroll() + intStop + "px";
				ref.objIFr.style.top = ref.objDiv.style.top;
			}
			}
        
//--- buttons actions ----------------------------------------------------------------     
			//Confirm button pressed, make request, hide buttons, start annimation
//----------------------------------------------------------------------
			this.confirmTimer = function(){
			timerUpdate = window.setInterval(updateMessage,250);
			document.getElementById("divBut").style.display = "none";
			makeHttpRequest();		         
			window.clearTimeout(timerWait);
			}
//-----------------------------------------------------------------------------------
			//Hide information if the ignore button was clicked
			this.ignoreTimer = function(){
			ref.objDiv.style.display = "none";
			ref.objIFr.style.display = "none";
			window.clearTimeout(timerWait); //stop timer
			}
			
		//------------------------------------------------------
        //Annimate the request waiting time so it looks fancy
        //------------------------------------------------------
		function updateMessage(){
		  var strDotsMessage = "Updating Session.";
		  for(x=0;x<intDotCount;x++)strDotsMessage+=".";
		  document.getElementById("divContent").innerHTML = strDotsMessage;
		  intDotCount++;
		  if(intDotCount>4)intDotCount = 0;
		}
		
		//--------------------------------------------
		//Call SessionEnd.aspx to abandom the session
		//--------------------------------------------
		function EndSession(){

		  //document.getElementById("divContent").innerHTML = ref.extendedMessage;
		  var loader2 = new net.ContentLoader(ref.URL_SessionEnd,null,null,"POST",null); //Make request
	    
	  	  document.getElementById("divBut").style.display = "none";
	      document.getElementById("divContent").innerHTML = "Warning your session has already timed out!";
          var timerHide1 = window.setTimeout(hideDiv,3000);
          
          //redirect on session end
          if (sessionTimer.URL_RedirectOnSessionEnd){
			//window.location=sessionTimer.URL_RedirectOnSessionEnd;
			 var timerHide2 = window.setTimeout(makeRedirect,2000);
			
		  }

		}
	
		//----------------------------------------
        //Redirect 
        //----------------------------------------
        function makeRedirect(){
        
			window.location=sessionTimer.URL_RedirectOnSessionEnd;
			//window.location.reload(true);
                
        }
	
		//----------------------------------------
        //Function Prepares calls xmlHttpRequest
        //----------------------------------------
        function makeHttpRequest(){
        
          //Make sure we set the server side page          
          if(ref.URL_SessionExtend==null){
            alert('Errror: Server Side Code was not specified by web master!');
            ref.objDiv.style.display = "none";
            ref.objIfr.style.display = "none";
            return false;
          }
          
          //create reg exp so we do not grabbed cached material
          var regEx = /(\s|:)/gi;
          var strDT = "ts=" + new Date().toString().replace(regEx,"");                              
          
          //Make the request to the server
          var loader1 = new net.ContentLoader(ref.URL_SessionExtend,finishRequest,null,"POST",strDT); //Make request
        
        }
        
        //----------------------------------
        //Function takes XML document 
        //----------------------------------
        function finishRequest(){
          timerWarn = window.setTimeout(loadMessage,ref.sessionLength);
          var bx = window.clearTimeout(timerUpdate);
          var strDoc = this.req.responseText;  //Grab HTML
          if(strDoc.indexOf("Session Updated - Server Time:") == 0){
            document.getElementById("divContent").innerHTML = "Your session was updated sucessfully!";
            var timerHide = window.setTimeout(hideDiv,2000);
          }
          else{
            document.getElementById("divContent").innerHTML = "Warning your session has already timed out!";
            var timerHide = window.setTimeout(hideDiv,3000);
          }
                    
        }
        
        //----------------------------------
        // createConfirm
        //----------------------------------
        function createConfirm(){
          var ifr = document.createElement("iframe");
      
          var div1 = document.createElement("div");
          var div2 = document.createElement("div");
          var div3 = document.createElement("div");
          var div4 = document.createElement("div");
      
          var btn1 = document.createElement("input");
          var btn2 = document.createElement("input");
      
          ifr.id = "ifSessionTimer";
          div1.id = "divSessionTimer";
          div2.id = "divTitle";
          div3.id = "divContent";
          div4.id = "divBut"; 
      
          btn1.type="button";
          btn2.type="button";
          btn1.id = "B1";
          btn2.id = "B2";
          btn1.className = "confirm";
          btn2.className = "ignore";
          btn1.onclick = function(){sessionTimer.confirmTimer();return false;}
          btn2.onclick = function(){sessionTimer.ignoreTimer();return false;}
          btn1.value = "text";
          btn2.value = "text";     
     
          div1.appendChild(div2);   
          div1.appendChild(div3);
          div4.appendChild(btn1);
          div4.appendChild(btn2);
          div1.appendChild(div4); 

          document.forms[0].appendChild(ifr);
          document.forms[0].appendChild(div1);
            
          return  true;
        }
        
        //Hide div and iframe
        function hideDiv(){
          ref.objDiv.style.display = "none";
          ref.objIFr.style.display = "none";
        }
     
      }

//=============================================
//Update information here for customization here!
//==============================================

	var sessionTimerTimoutVal = window.sessionShowWarningTime || (20*60*1000);
	var sessionTimerWarningVal = window.sessionMinToShowWarning || (2*60*1000);

     // var sessionTimer = new SessionTimeoutTimer();        //default time 20 minutes
      var sessionTimer = new SessionTimeoutTimer(sessionTimerTimoutVal);  //Specify a time length
      sessionTimer.URL_SessionExtend = "/DIAHome/Common/Templates/SessionExtend.aspx";
      sessionTimer.URL_SessionEnd = "/DIAHome/Common/Templates/SessionEnd.aspx";
      sessionTimer.maxWait = sessionTimerWarningVal;    //defualt time 2 minutes beyond session warning
      sessionTimer.URL_RedirectOnSessionEnd = "/DIAHome/Common/Templates/SessionExpired.aspx"; //"/DIAHome/Common/Templates/Login.aspx?s=e"; //redirect page
      
      
      //sessionTimer.title = "Timeout Notification";
      //sessionTimer.message = "Your current session is about to expire.";
      //sessionTimer.confirm = "Continue";
      //sessionTimer.ignore = "Exit";
      //sessionTimer..extendedMessage = "Your session has most likely been expired. "

