var curHistoryLocation = "";

// 뒤로가기 구현
window.dhtmlHistory = {
	initialize: function() {
		if(this.isInternetExplorer() == false) {
			return;
		}
		if (historyStorage.hasKey("DhtmlHistory_pageLoaded") == false) {
			this.fireOnNewListener = false;
			this.firstLoad = false;
		}  else {
			this.fireOnNewListener = true;
			this.firstLoad = false;   
		}
   },
             
	addListener: function(callback) {
		this.listener = callback;
		if (this.fireOnNewListener == true) {
			this.fireHistoryEvent(this.currentLocation);
			this.fireOnNewListener = false;
		}
   },
   
   /** public */
	add: function(newLocation, historyData) {
		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;
		}

         newLocation = self.removeHash(newLocation);

         // 히스토리 저장소에 히스토리를 저장한다
		historyStorage.put(newLocation, historyData);
		
		curHistoryLocation = newLocation;
		
		self.ignoreLocationChange = true;
 
		this.ieAtomicLocationChange = false;
                 
         self.currentLocation = newLocation;
         
         // change the browser location
	
         // change the hidden iframe's location if on IE
	     if (self.isInternetExplorer() && newLocation != "top"){
    	    self.iframe.src = "/myop/blank.html?" + newLocation;
		}else{
	         window.location.hash = newLocation;
		}

         // for IE
         this.ieAtomicLocationChange = false;
      };
		window.setTimeout(addImpl, this.currentWaitTime);

      // indicate that the next request will have to wait for awhile
      this.currentWaitTime = this.currentWaitTime + this.WAIT_TIME;
   },
   
   /** public */
	isFirstLoad: function() {
		if (this.firstLoad == true) {
			return true;
		} else {
         return false;
		}
	},
	isInternational: function() {
		return false;
	},
   
	getVersion: function() {
		return "0.01";
	},
   
	getCurrentLocation: function() {
		var currentLocation = this.removeHash(window.location.hash);
		return currentLocation;
   },

		currentLocation: null,

		listener: null,

		iframe: null,
   
		ignoreLocationChange: null,
 
		WAIT_TIME: 200,

		currentWaitTime: 1,

		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;

      //  IE 경우 IFRAME 생성
      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' >"
//                               + "</iframe>");
         
         // wait 400 milliseconds between history
         // updates on IE, versus 200 on Firefox
         this.WAIT_TIME = 200;
      }
      
      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 {
            this.ignoreLocationChange = false;
            this.fireOnNewListener = true;
         }
      }
      else {
         this.ignoreLocationChange = true;
      }
      
      if (this.isInternetExplorer()) {
            this.iframe = document.getElementById("DhtmlHistoryFrame");
      }                                                              

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

		// NOT IE
		if( this.isInternetExplorer() == false){
			setInterval(locationHandler, 200);
		}
   },
   
	fireHistoryEvent: function(newHash) {
		var historyData = historyStorage.get(newHash);

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

	// FIREFOX    
	checkLocation: function() {
		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();
      if(hash == "top") return;

      // see if there has been a change
      if (hash == this.currentLocation)
         return;
         
      this.ieAtomicLocationChange = true;

      if (this.isInternetExplorer()
          && this.getIFrameHash() != hash && hash != "top" ) {
         this.iframe.src = "/myop/blank.html?" + hash;
      }
      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;     
   },          
   
	iframeLoaded: function(newLocation) {
		if (this.ignoreLocationChange == true) {
			this.ignoreLocationChange = false;
			return;
		}
		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);
		}

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

/**http://codinginparadise.org/weblog/2005/08/ajax-tutorial-saving-session-across.html */
window.historyStorage = {
		debugging: false,
		storageHash: new String(),
   
		hashLoaded: true,
		/** public */
		put: function(key, value) {
			window.scrollTo(0,0);
			this.remove(key);
			this.storageHash[key] = value;

			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{
			window.scrollTo(0,0);
			return value; 
		}
   },
   
   /** public */
   remove: function(key) {
      this.assertValidKey(key);
      
      this.loadHashTable();
      
      // delete the value
      delete this.storageHash[key];
      
      // serialize and save the hash table into the 
      // form
      this.saveHashTable();
   },
   reset: function() {
      this.storageField.value = "";
      this.storageHash = new String();
   },
   
   /** 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;
   },
   
	isValidKey: function(key) {
		if (typeof key != "string")
			key = key.toString();
      
      var matcher = 
         /^[a-zA-Z0-9_ \!\@\#\$\%\^\&\*\(\)\+\=\:\;\,\.\/\?\|\\\~\{\}\[\]]*$/;
                     
      return matcher.test(key);
   },
   dum: function() {

   },   
	storageField: null,

	// 초기 TEXTAREA 생성
	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");
   },
	assertValidKey: function(key) {
		if (this.isValidKey(key) == false) {

       }
   },

	loadHashTable: function() {
		if (this.hashLoaded == false) {
			var serializedHashTable = this.storageField.value;
			if (serializedHashTable != "" && serializedHashTable != null) {
				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 = this.storageHash;
		// save this value
		this.storageField.value = serializedHashTable;
   }   
};

function historyInitialize() {
    dhtmlHistory.initialize();
    dhtmlHistory.addListener(historyChange);
    if (dhtmlHistory.isFirstLoad()) {
        dhtmlHistory.add("home", location);
    } 
}

function historyChange(newLocation, historyData) {
	var output = document.getElementById(historyframeName);
    if(newLocation == 'home') {
        var firstURL = historyStorage.get("home");
        //document.location.href = firstURL;
        document.location.reload();
        return;
    }
    if(historyData != null) {
		ajax.arraypost(newLocation+":history");
    }
}
window.historyStorage.init();
window.dhtmlHistory.create();
historyInitialize();