/**
 * History
 *
 * @version		1.0
 *
 * @license		MIT License
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	2008 Author
 */

var History = $extend(history, {

	implement: function(obj) {
		return $extend(this, obj);
	}

});

History.implement(new Events($empty));

History.implement({

	staate: null,

	start: function() {
		if (this.started) return this;
		this.staate = this.getHash();
		if (Browser.Engine.trident) {
			var iframe = new Element('iframe', {
				'src': "javascript:'<html></html>'",
				'styles': {
					'position': 'absolute',
					'top': '-1000px'
				}
			}).inject(document.body).contentWindow;
			var writeState = function(staate) {
				iframe.document.write('<html><body onload="top.History.$listener(\'', encodeURIComponent(staate) ,'\');">Moo!</body></html>');
				iframe.document.close();
			};
			$extend(this, {
				'$listener': function(staate) {
					staate = decodeURIComponent(staate);
					if (this.staate != staate) this.setHash(staate).changeState(staate);
				}.bind(this),
				'setState': function(staate, force) {
					if (this.staate != staate || force) {
						if (!force) this.setHash(staate).changeState(staate, true);
						writeState(staate);
					}
					return this;
				},
				'trace': function() {
					var staate = this.getHash();
					if (staate != this.staate) writeState(staate);
				}
			});
			var check = (function() {
				if (iframe.document && iframe.document.body) {
					check = $clear(check);
					if (!iframe.document.body.innerHTML) this.setState(this.staate);
				}
			}).periodical(50, this);
		} else {
			if (Browser.Engine.presto915) {
				new Element('img', {
					'src': "javascript:location.href='javascript:History.trace();';",
					'styles': {
						'position': 'absolute',
						'top': '-1000px'
					}
				}).inject(document.body);
			}
		}
		this.trace.periodical(150, this);
		this.started = true;
		return this;
	},

	changeState: function(staate, manual) {
		var staateOld = this.staate;
		this.staate = staate;
		this.fireEvent('changed', [staate, staateOld, manual]);
	},

	trace: function() {
		var staate = this.getHash();
		if (staate != this.staate) {
			this.changeState(staate);
		}
	},

	getHash: function() {
		var href = location.href, pos = href.indexOf('#') + 1;
		return (pos) ? href.substr(pos) : '';
	},

	setHash: function(staate) {
		location.hash = '#' + staate;
		return this;
	},

	setState: function(staate) {
		if (this.staate !== staate) this.setHash(staate).changeState(staate, true);
		return this;
	},

	getState: function() {
		return this.staate;
	}

});

