/*
Script Name: Simple Javascript Browser/OS detection
Authors: George Anestis, Websites: http://www.music.tuc.gr/

Version 1.0.0
Copyright (c) 12 Nov 2007

*/

/******************************************************************************
Handle History (back/forward buttons) for Ajax applications.. 

dependencies:
		* the browser-detection.js

We test for basic browser type (ie, op, or moz/netscape > 6).
******************************************************************************/

/*
* Create a global object named ajaxHistory that is the entry point for 
* manipulating the browser's history. The ajaxHistory object provides a history 
* abstraction for AJAX applications
*
* Use the object literal syntax for creating a new object using asign to the 
* browser's window object
*/

var ajaxHistory = {
  /** Properties */
  
  /** 
   * Private: A variable that indicates whether this is the first time this page 
   * has been loaded. 
   */
  firstLoad: null,
  
  /** Private: Our current hash location, without the "#" symbol. */
  currentLocation: null,
  
  /*Private: Our history change listener.*/
  listener: null,
  
  /* Private: MS to wait between add requests - will be reset for certain browsers*/
  waitTime: 200,
	
  /* Private: MS before an add request can execute*/
  currentWaitTime: 0,
  
  /** 
   * Private: Flag used to keep checkLocation() from doing anything when it 
   * discovers location changes we've made ourselves programmatically with the 
   * add() method. Basically, add() sets this to true. When checkLocation() 
   * discovers it's true, it refrains from firing our listener, then resets the 
   * flag to false for next cycle. That way, our listener only gets fired on
   * history change events triggered by the user via back/forward buttons and 
   * manual hash changes. This flag also helps us set up	IE's special 
   * iframe-based method of handling history changes.
   */
  ignoreLocationChange: null,
  
  /** 
   * Private: A variable to handle an important edge case in IE. In IE, if a 
   * user manually types an address into their browser's	location bar, we must 
   * intercept this by calling checkLocation() at regular intervals. 
   * However, if we are programmatically changing the location bar ourselves 
   * using the add() method, we need to ignore these changes in checkLocation(). 
   * Unfortunately, these changes take several lines of code to complete, so for 
   * the duration of those lines of code, we set this variable to true.
   * That signals to checkLocation() to ignore the change-in-progress. Once 
   * we're done with our chunk of location-change code in add(), we set this 
   * back to false. We'll do the same thing when capturing user-entered address 
   * changes in checkLocation itself.
   */
  ieAtomicLocationChange: null,
  
  /* Private: Hidden iframe used to detect history changes */
  iframe: null,
  
  /** Methods */
  
  /* Public: Create the AJAX history infrastructure */
  create: function(options) {
    
    this.firstLoad = true;    	        
    
    var that = this;
    
    /* Get our initial location */
	 var initialHash = this.getCurrentLocation();

	 /* Save it as our current location */
    this.currentLocation = initialHash;        
        
    /**
     * This isn't our first page load, so indicate that we want to pay attention
     * to this location change
     */
    this.ignoreLocationChange = true;
    
    /* Now that we have a hash, create IE-specific code */
	 
   // this.createIFrame(initialHash);
    
    /* The iframe will get loaded on page load, and we want to ignore this fact */
    this.ignoreLocationChange = true;
    
    /** 
     * Other browsers can use a location handler that checks at regular 
     * intervals as their primary mechanism; we use it for IE as
     * well to handle an important edge case; see checkLocation() for details
     */
    var locationHandler = function() {
      that.checkLocation();
    };
    /** 
     * The setInterval method continuously evaluates the specified expression 
     * until the timer is removed with the clearInterval method.
     */
   setInterval(locationHandler, 300);
  },
  
  /** ************************************************************************** 
   * Public: Initialize ajaxHistory object. You must call this after the page 
   * is finished loading.
   * ************************************************************************ */
  initialize: function() {       
    
    if (this.iframe == null) {     
      this.iframe = window.frames[0];     
    }        
  },
  
  /** ************************************************************************** 
   * Private: See if the browser has changed location. This is the primary 
   * history mechanism for Firefox. For IE, we use this to handle an important 
   * edge case: if a user manually types in a new hash value into their IE 
   * location bar and press enter, we want to intercept this and notify any 
   * history listener.
   * ************************************************************************ */
  checkLocation: function() {	    
    /* 
     * Ignore any location changes that we made ourselves for browsers other 
     * than IE
     */        
    if (this.ignoreLocationChange) {
      this.ignoreLocationChange = false;
      return;
    }
    
    /**
     * If we are dealing with IE and we are in the middle of making a location 
     * change from an iframe, ignore it
     */
    if (this.ieAtomicLocationChange) {
      return;
    }
	
    if (this.firstLoad) {
      return;
    }            
    
    functionID = this.getIFrameParam(0); 
    hash = this.getIFrameParam(1);    
    //alert("hash is:" + hash + "| curLoc is:" + this.currentLocation + "|");    
    
    /* Do nothing if there's been no change */
    if (hash == this.currentLocation) {       
      return;
    }           
    
    /* Save this new location */          
    this.currentLocation = hash;

   //this.ieAtomicLocationChange = false;
       
    /* Notify listeners of the change*/   
   this.fireHistoryEvent(functionID, hash);
  },

  getIFrameParam: function(i) {
   
   var that = this; 
   var doc1 = that.iframe.document;               
   var params;
   //alert(doc1.childNodes[0].innerHTML);   
   //alert(doc1.all[0].childNodes[0].innerHTML);
   //alert(doc1.childNodes[0].childNodes[1].innerHTML);
   //alert(doc1.childNodes[0].childNodes[1].childNodes[0].innerHTML);
   //alert(doc1.childNodes[0].childNodes[1].innerHTML);
   if (op8 || op9) {
      params = doc1.all[0].childNodes[0].innerHTML;
   }
   else {
     params = doc1.childNodes[0].childNodes[1].childNodes[0].innerHTML;      
     if (!params) {     
        params = doc1.childNodes[0].childNodes[1].innerHTML;       
     } 
   }
   params = params.replace(/myID/g, 'sect');
   params = params.replace(/&amp;/g,"&");
   //params = params.substr(0, params.length -1);

   paramsArray = params.split('|');   
   
   return paramsArray[i];      
  },    

  /** **************************************************************************
   * Private: Notify the listener of new history changes.
   * ************************************************************************ */
  fireHistoryEvent: function(functionID, newHash) {		
    /* call our listener */
    this.listener.call(null, functionID, newHash);
  },    
  
  /** ************************************************************************** 
   * Public 
   * ************************************************************************ */
  getCurrentLocation: function() {
    var r = this.getCurrentHash()
		
    return r;
  },
	
  /** **************************************************************************
   * Public: Manually parse the current url for a hash 
   * ************************************************************************ */
  getCurrentHash: function() {
    var r = window.location.href;
    var i = r.indexOf("#");        
		return (i >= 0
			? r.substr(i+1)
			: ""
		);
  },
  
  /** **************************************************************************
   * Private: Remove any leading hash that might be on a location.
   * ************************************************************************ */
  removeHash: function(hashValue) {
    var r;
    if (hashValue === null || hashValue === undefined) {
      r = null;
    }
    else if (hashValue === "") {
      r = "";
    }
    else if (hashValue.length == 1 && hashValue.charAt(0) == "#") {
      r = "";
    }
    else if (hashValue.length > 1 && hashValue.charAt(0) == "#") {
      r = hashValue.substring(1);
    }
    else {
      r = hashValue;
    }
    return r;
  },
  
  /** **************************************************************************
   * Public: Add a history point    
   * Most browsers require that we wait a certain amount of time before 
   * changing the location, such as 200 MS; rather than forcing external 
   * callers to use window.setTimeout to account for this, we internally 
   * handle it by putting requests in a queue.     
   * ************************************************************************ */
  add: function(functionID, newLocation ) {                    
    var that = this;       
    var addImpl = function() {
      
       /*Indicate that the current wait time is now less*/
       if (that.currentWaitTime > 0) {
         that.currentWaitTime = that.currentWaitTime - that.waitTime;
       }
         /* Remove any leading hash symbols on newLocation */
       newLocation = that.removeHash(newLocation);

       /*
        * Indicate to the browser to ignore this upcomming location change 
        * since we're making it programmatically
        */
       that.ignoreLocationChange = true;

       /* Indicate to IE that this is an atomic location change block */
       that.ieAtomicLocationChange = true;

       /* Save this as our current location */      
       that.currentLocation = newLocation;       
       
       /* Change the browser location */       
       //window.location.hash = newLocation;    
       
      // that.iframe.location.href= newLocation;       
       
       var modifiedLocation = newLocation.replace(/sect/g, 'myID');
       
       //modifiedLocation = modifiedLocation.replace(/mem/g, 'myganest');
       
       var doc = that.iframe.document;
       doc.open("javascript:'<html></html>'");           
       doc.write(functionID);
       doc.write("|")
       doc.write(modifiedLocation);       
       doc.close();
       
       //alert("add called: " + doc.childNodes[0].innerHTML);
      // window.frames[0].innerHTML = "<div id='functionID'>showDataInBody</div>";       
       that.firstLoad = false;
       /* Change the hidden iframe's location if on IE */                        
                      
        /* End of atomic location change block for IE */
        that.ieAtomicLocationChange = false;      
    }
    
    /* Now queue up this add request */
    window.setTimeout(addImpl, this.currentWaitTime);        
    
    /* Indicate that the next request will have to wait for a while */
    this.currentWaitTime = this.currentWaitTime + this.waitTime;    
  },
  
  /** **************************************************************************
   * Public: Adds a history change listener. Note that only one listener is 
   * supported at this time.
   * ************************************************************************ */
  addListener: function(listener) {
    this.listener = listener;    
  },
  
  /** **************************************************************************
   * Private: Create IE-specific DOM nodes and overrides
   * write out a hidden iframe and set the amount of time to wait between add() 
   * requests
   * Set the iframe property
   * ************************************************************************ */
  createIFrame: function(initialHash) {
    
    this.waitTime = 200; /* IE needs longer between history updates */
    var styles="width:0px; height:0px; border: 0px";
    var iframeID = "ajaxHistoryFrame";
    var iframeHTML = '<iframe frameborder="0" id="' + iframeID + '" style="' + styles + '" src="blank.html?' + initialHash + '"></iframe>';    
    d.write( iframeHTML );    
    this.iframe = d.getElementById(iframeID);            
  }           
}


/** ****************************************************************************
 * Handles history change events.             
 * ************************************************************************** */ 
function handleHistoryChange(fuctionID, newLocation ) {  
      
  if (functionID.indexOf("first") >= 0) {
    //window.location="http://147.27.3.129:8084/ece/Controller?actionClass=loadFirstPage&action=loadFirstPage";
    //window.location="http://helios.ced.tuc.gr:8080/ece/Controller?actionClass=loadFirstPage&action=loadFirstPage";
    window.location="http://www.ece.tuc.gr/Controller?actionClass=loadFirstPage&action=loadFirstPage";
  }
  else {
    switch (functionID) {
      case "first" :
        //window.location="http://147.27.3.129:8084/ece/Controller?actionClass=loadFirstPage&action=loadFirstPage";
        //window.location="http://helios.ced.tuc.gr:8080/ece/Controller?actionClass=loadFirstPage&action=loadFirstPage";
        window.location="http://www.ece.tuc.gr/Controller?actionClass=loadFirstPage&action=loadFirstPage";
        break;
      case "showDataInBody" :   
        showDataInBody(newLocation);        
        break;
      case "showLabInfo" :
        showLabInfo(newLocation);
        break;
      case "showPersonCV" :
        showPersonCV(newLocation);
        break;
      default: 
        //window.location="http://147.27.3.129:8084/ece/Controller?actionClass=loadFirstPage&action=loadFirstPage";
        //window.location="http://helios.ced.tuc.gr:8080/ece/Controller?actionClass=loadFirstPage&action=loadFirstPage";
        window.location="http://www.ece.tuc.gr/Controller?actionClass=loadFirstPage&action=loadFirstPage";
        break;      
    }
  }  
}

window.ajaxHistory = ajaxHistory;
