/** 
   Copyright (c) 2005, Brad Neuberg, bkn3@columbia.edu
   http://codinginparadise.org
   
   Permission is hereby granted, free of charge, to any person obtaining 
   a copy of this software and associated documentation files (the "Software"), 
   to deal in the Software without restriction, including without limitation 
   the rights to use, copy, modify, merge, publish, distribute, sublicense, 
   and/or sell copies of the Software, and to permit persons to whom the 
   Software is furnished to do so, subject to the following conditions:
   
   The above copyright notice and this permission notice shall be 
   included in all copies or substantial portions of the Software.
   
   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 
   CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 
   OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR 
   THE USE OR OTHER DEALINGS IN THE SOFTWARE.
   
	 An object that provides DHTML history, history data, and bookmarking 
    for AJAX applications. */

// JH - If safari, skip everything and create a fake object so that dhtmlHistory.add doesnt throw an error
if(navigator.userAgent.indexOf("Safari") != -1) {
	dhtmlHistory = {add:function(){}};
} else {
window.dhtmlHistory = {
   initialize: function() {
      if (this.isInternetExplorer() == false) {
         return;
      }
         
      // if this is the first time this page has loaded...
      if (historyStorage.hasKey("DhtmlHistory_pageLoaded") == false) {
         this.fireOnNewListener = false;
         this.firstLoad = true;
         historyStorage.put("DhtmlHistory_pageLoaded", true);
      }
      // else if this is a fake onload event
      else {
         this.fireOnNewListener = true;
         this.firstLoad = false;   
      }
   },
             
   addListener: function(callback) {
      this.listener = callback;
      if (this.fireOnNewListener == true) {
         this.fireHistoryEvent(this.currentLocation);
         this.fireOnNewListener = false;
      }
   },
   add: function(newLocation, historyData) {
      var self = this;
      var addImpl = function() {
         // indicate that the current wait time is now less
         if (self.currentWaitTime > 0)
            self.currentWaitTime = self.currentWaitTime - self.WAIT_TIME;

         // remove any leading hash symbols on newLocation
         newLocation = self.removeHash(newLocation);
         
         var idCheck = document.getElementById(newLocation);
         if (idCheck != undefined || idCheck != null) {
            var message = "Exception: History locations can not have the same value as _any_ id's that might be in the document due to a bug in Internet Explorer; please ask the developer to choose a history location that does not match any HTML id's in this document. The following ID is already taken and can not be a location: "                + newLocation;
            throw message; 
         }
         
         // store the history data into history storage
         historyStorage.put(newLocation, historyData);
         
         self.ignoreLocationChange = true;
         this.ieAtomicLocationChange = true;
	       self.currentLocation = newLocation;
         window.location.hash = newLocation;
         
         if (self.isInternetExplorer())
            self.iframe.src = "/files/newsroom/interactives/cdc/blank.html?" + newLocation; // UPDATE RELATIVE URL
            
         this.ieAtomicLocationChange = false;
      };

      window.setTimeout(addImpl, this.currentWaitTime);
   
      this.currentWaitTime = this.currentWaitTime + this.WAIT_TIME;
   },
   
   isFirstLoad: function() {
      if (this.firstLoad == true) {
         return true;
      }
      else {
         return false;
      }
   },
   
   isInternational: function() {
      return false;
   },
   
   getVersion: function() {
      return "0.05";
   },
   

   getCurrentLocation: function() {
      var currentLocation = this.removeHash(window.location.hash);
         
      return currentLocation;
   },
      currentLocation: null,
   
      listener: null,
   
  		iframe: null,
   
   ignoreLocationChange: null,
 
   WAIT_TIME: 200,

   currentWaitTime: 0,
   
  	fireOnNewListener: null,
   
   firstLoad: null,
   
   ieAtomicLocationChange: null,          
   
   create: function() {
      // get our initial location
      var initialHash = this.getCurrentLocation();
      
      // save this as our current location
      this.currentLocation = initialHash;
      
      // write out a hidden iframe for IE and
      // set the amount of time to wait between add() requests
      if (this.isInternetExplorer()) {
         document.write("<iframe style='border: 0px; width: 1px; "
                               + "height: 1px; position: absolute; bottom: 0px; "
                               + "right: 0px; visibility: visible;' "
                               + "name='DhtmlHistoryFrame' id='DhtmlHistoryFrame' "
                               + "src='/files/newsroom/interactives/cdc/blank.html?" + initialHash + "'>" // UPDATE RELATIVE URL
                               + "</iframe>");
         // wait 400 milliseconds between history
         // updates on IE, versus 200 on Firefox
         this.WAIT_TIME = 400;
      }
      
      var self = this;
      window.onunload = function() {
         self.firstLoad = null;
      };
      
      if (this.isInternetExplorer() == false) {
         if (historyStorage.hasKey("DhtmlHistory_pageLoaded") == false) {
            this.ignoreLocationChange = true;
            this.firstLoad = true;
            historyStorage.put("DhtmlHistory_pageLoaded", true);
         }
         else {
            // indicate that we want to pay attention
            // to this location change
            this.ignoreLocationChange = false;
            this.fireOnNewListener = true;
         }
      }
      else { // Internet Explorer
         this.ignoreLocationChange = true;
      }
      
      if (this.isInternetExplorer()) {
            this.iframe = document.getElementById("DhtmlHistoryFrame");
      }                                                              

      var self = this;
      var locationHandler = function() {
         self.checkLocation();
      };
      setInterval(locationHandler, 100);
   },
   

			fireHistoryEvent: function(newHash) {

      var historyData = historyStorage.get(newHash);

      // call our listener      
      this.listener.call(null, newHash, historyData);
   },
   

   checkLocation: function() {
      // ignore any location changes that we made ourselves
      // for browsers other than Internet Explorer
      if (this.isInternetExplorer() == false
         && this.ignoreLocationChange == true) {
         this.ignoreLocationChange = false;
         return;
      }
      
      if (this.isInternetExplorer() == false
          && this.ieAtomicLocationChange == true) {
         return;
      }
      
      // get hash location
      var hash = this.getCurrentLocation();
      
      // see if there has been a change
      if (hash == this.currentLocation)
         return;
         
      this.ieAtomicLocationChange = true;
      
      if (this.isInternetExplorer()
          && this.getIFrameHash() != hash) {
         this.iframe.src = "/files/newsroom/interactives/cdc/blank.html?" + hash; // UPDATE RELATIVE URL
      }
      else if (this.isInternetExplorer()) {
         // the iframe is unchanged
         return;
      }
         
      // save this new location
      this.currentLocation = hash;
      
      this.ieAtomicLocationChange = false;
      
      // notify listeners of the change
      this.fireHistoryEvent(hash);
   },  


   getIFrameHash: function() {
      // get the new location
      var historyFrame = document.getElementById("DhtmlHistoryFrame");
      var doc = historyFrame.contentWindow.document;
      var hash = new String(doc.location.search);

      if (hash.length == 1 && hash.charAt(0) == "?")
         hash = "";
      else if (hash.length >= 2 && hash.charAt(0) == "?")
         hash = hash.substring(1); 
    
    
      return hash;
   },          
   
   /** Removes any leading hash that might be on a location. */
   /** private */ removeHash: function(hashValue) {
      if (hashValue == null || hashValue == undefined)
         return null;
      else if (hashValue == "")
         return "";
      else if (hashValue.length == 1 && hashValue.charAt(0) == "#")
         return "";
      else if (hashValue.length > 1 && hashValue.charAt(0) == "#")
         return hashValue.substring(1);
      else
         return hashValue;     
   },          
   
   /** For IE, says when the hidden iframe has finished loading. */
   /** private */ iframeLoaded: function(newLocation) {
      // ignore any location changes that we made ourselves
      if (this.ignoreLocationChange == true) {
         this.ignoreLocationChange = false;
         return;
      }
      
      // get the new location
      var hash = new String(newLocation.search);
      if (hash.length == 1 && hash.charAt(0) == "?")
         hash = "";
      else if (hash.length >= 2 && hash.charAt(0) == "?")
         hash = hash.substring(1);
      
      // move to this location in the browser location bar
      // if we are not dealing with a page load event
      if (this.pageLoadEvent != true) {
         window.location.hash = hash;
      }

      // notify listeners of the change
      this.fireHistoryEvent(hash);
   },
   
   /** Determines if this is Internet Explorer. */
   /** private */ isInternetExplorer: function() {
      var userAgent = navigator.userAgent.toLowerCase();
      if (document.all && userAgent.indexOf('msie')!=-1) {
         return true;
      }
      else {
         return false;
      }
   }
};

window.historyStorage = {
   debugging: false,
   
   storageHash: new Object(),
   hashLoaded: false, 
		put: function(key, value) {
       this.assertValidKey(key);
       if (this.hasKey(key)) {
         this.remove(key);
       }
       
       // store this new key
       this.storageHash[key] = value;
       
       // save and serialize the hashtable into the form
       this.saveHashTable(); 
   },
   
   /** public */ get: function(key) {
      this.assertValidKey(key);
      
      // make sure the hash table has been loaded
      // from the form
      this.loadHashTable();
      
      var value = this.storageHash[key];

      if (value == undefined)
         return null;
      else
         return value; 
   },
   
   /** public */ remove: function(key) {
      this.assertValidKey(key);
      
      // make sure the hash table has been loaded
      // from the form
      this.loadHashTable();
      
      // delete the value
      delete this.storageHash[key];
      
      // serialize and save the hash table into the 
      // form
      this.saveHashTable();
   },
   
   /** Clears out all saved data. */
   /** public */ reset: function() {
      this.storageField.value = "";
      this.storageHash = new Object();
   },
   
   /** public */ hasKey: function(key) {
      this.assertValidKey(key);
      
      // make sure the hash table has been loaded
      // from the form
      this.loadHashTable();
      
      if (typeof this.storageHash[key] == "undefined")
         return false;
      else
         return true;
   },
   
   /** public */ isValidKey: function(key) {
      // allow all strings, since we don't use XML serialization
      // format anymore
      return (typeof key == "string");
   },
   
   
   
   
   /** A reference to our textarea field. */
   /** private */ storageField: null,
   
   /** private */ init: function() {
      // write a hidden form into the page
      var styleValue = "position: absolute; top: -1000px; left: -1000px;";
      if (this.debugging == true) {
         styleValue = "width: 30em; height: 30em;";
      }   
      
      var newContent =
         "<form id='historyStorageForm' " 
               + "method='GET' "
               + "style='" + styleValue + "'>"
            + "<textarea id='historyStorageField' "
                      + "style='" + styleValue + "'"
                              + "left: -1000px;' "
                      + "name='historyStorageField'></textarea>"
         + "</form>";
      document.write(newContent);
      
      this.storageField = document.getElementById("historyStorageField");
   },
   
   /** Asserts that a key is valid, throwing
       an exception if it is not. */
   /** private */ assertValidKey: function(key) {
      if (this.isValidKey(key) == false) {
         throw "Please provide a valid key for "
               + "window.historyStorage, key= "
               + key;
       }
   },
   
   /** Loads the hash table up from the form. */
   /** private */ loadHashTable: function() {
      if (this.hashLoaded == false) {
         // get the hash table as a serialized
         // string
         var serializedHashTable = this.storageField.value;
         
         if (serializedHashTable != "" &&
             serializedHashTable != null) {
            // destringify the content back into a 
            // real JavaScript object
            this.storageHash = eval('(' + serializedHashTable + ')');  
         }
         
         this.hashLoaded = true;
      }
   },
   
   /** Saves the hash table into the form. */
   /** private */ saveHashTable: function() {
      //this.loadHashTable();
      
      // serialized the hash table
      //var serializedHashTable = JSON.stringify(this.storageHash);
      
      // save this value
      //this.storageField.value = serializedHashTable;
   }   
};


/** Initialize all of our objects now. */
	window.historyStorage.init();
	window.dhtmlHistory.create();
}

