(function(jQuery) {
    var currentHash, previousNav, timer, hashTrim = /^.*#/;

    var msie = {
        iframe: null,
        getDoc: function() {
            return msie.iframe.contentWindow.document;
        },
        getHash: function() {
            return msie.getDoc().location.hash;
        },
        setHash: function(hash) {
            var d = msie.getDoc();
            d.open();
            d.close();
            d.location.hash = hash;
        }
    };

    var historycheck = function() {
        var hash = msie.iframe ? msie.getHash() : location.hash;
		if (hash != currentHash) {
            currentHash = hash;
            if (msie.iframe) {
                location.hash = currentHash;
            }
            var current = jQuery.history.getCurrent();
            jQuery.event.trigger('history', [current, previousNav]);
            previousNav = current;
        }
    };

    jQuery.history = {
        add: function(hash) {
		   hash = '#' + hash.replace(hashTrim, '');
            if (currentHash != hash) {
                var previous = jQuery.history.getCurrent();
                location.hash = currentHash = hash;
                if (msie.iframe) {
                    msie.setHash(currentHash);
                }
              jQuery.event.trigger('historyadd', [jQuery.history.getCurrent(), previous]);
				
            }
            if (!timer) {
                timer = setInterval(historycheck, 100);
            }
        },
        getCurrent: function() {
			//alert('getCurrent ->'+currentHash.replace(hashTrim, ''));
			var myHash=window.location.href.split('?');
        currentHash = (location.hash)? location.hash: myHash[1];
			return currentHash.replace(hashTrim, '');
        }
    };

    jQuery.fn.history = function(fn) {
		jQuery(this).bind('history', fn);
		
    };

    jQuery.fn.historyadd = function(fn) {
        jQuery(this).bind('historyadd', fn);
		
    };

    jQuery(function() {
		var myHash=window.location.href.split('?');
        currentHash = (location.hash)? location.hash: myHash[1];
        if (jQuery.browser.msie) {
            msie.iframe = jQuery('<iframe style="display:none" src="javascript:false;"></iframe>').prependTo('body')[0];
            msie.setHash(currentHash);
            currentHash = msie.getHash();
        }
    });
})(jQuery);
