(function($) { // block scope

$.ajaxHistory = new function() {

    var RESET_EVENT = 'historyReset';

    var _currentHash = location.hash;
    var _intervalId = null;
    var _observeHistory; // define outside if/else required by Opera

    this.update = function() { }; // empty function body for graceful degradation

    // create custom event for state reset
    var _defaultReset = function() {
        $('.remote-output').empty();
    };
    $(document).bind(RESET_EVENT, _defaultReset);


    if ($.browser.msie) {
        var _historyIframe, initialized = false; // for IE
        // add hidden iframe
        $(function() {
            _historyIframe = $('<iframe style="display: none;"></iframe>').appendTo(document.body).get(0);
            var iframe = _historyIframe.contentWindow.document;
            // create initial history entry
            iframe.open();
            iframe.close();
            if (_currentHash && _currentHash != '#') {
                iframe.location.hash = _currentHash.replace('#', '');
            }
        });

        this.update = function(hash) {
            _currentHash = hash;
            var iframe = _historyIframe.contentWindow.document;
            iframe.open();
            iframe.close();
            iframe.location.hash = hash.replace('#', '');
        };

		var isReallyFirst = true;
        _observeHistory = function() {
            var iframe = _historyIframe.contentWindow.document;
            var iframeHash = iframe.location.hash;
            if (iframeHash != _currentHash) {
                _currentHash = iframeHash;
                if (iframeHash && iframeHash != '#'){
                    // order does matter, set location.hash after triggering the click...
					var loadMe = iframeHash.substr(1);
                    $('a[@href$="' + loadMe + '"]').click();
                    location.hash = iframeHash;
				} else if (initialized) {
                    location.hash = '';
                    $(document).trigger(RESET_EVENT);
                }
			} /*else if(isReallyFirst == true && location.hash ){
                _currentHash = iframeHash;
				var loadMe = iframeHash.substr(1);
                $('a[@href$="' + loadMe + '"]').click();
				location.hash = iframeHash;
				isReallyFirst=false;
			}*/
            initialized = true;
        };

		
		
    } else if ($.browser.mozilla || $.browser.opera) {

        this.update = function(hash) {
            _currentHash = hash;
        };

        _observeHistory = function() {
            if (location.hash) {
                if ( (_currentHash != location.hash) ) {
					_currentHash = location.hash;//.substr(1);
					var loadMe = _currentHash.substr(1);
					$('a[@href$="' + loadMe + '"]').click();
                }
            } else if (_currentHash) {
                _currentHash = '';
                $(document).trigger(RESET_EVENT);
            }
        };
		
    } else if ($.browser.safari) {

        var _backStack, _forwardStack, _addHistory; // for Safari

        // etablish back/forward stacks
        $(function() {
            _backStack = [];
            _backStack.length = history.length;
            _forwardStack = [];

        });
        var isFirst = false, initialized = false;
        _addHistory = function(hash) {
            _backStack.push(hash);
            _forwardStack.length = 0; // clear forwardStack (true click occured)
            isFirst = false;
        };

        this.update = function(hash) {
            _currentHash = hash;
            _addHistory(_currentHash);
        };

        _observeHistory = function() {
            var historyDelta = history.length - _backStack.length;
            if (historyDelta) { // back or forward button has been pushed
                isFirst = false;
                if (historyDelta < 0) { // back button has been pushed
                    // move items to forward stack
                    for (var i = 0; i < Math.abs(historyDelta); i++) _forwardStack.unshift(_backStack.pop());
                } else { // forward button has been pushed
                    // move items to back stack
                    for (var i = 0; i < historyDelta; i++) _backStack.push(_forwardStack.shift());
                }
                var cachedHash = _backStack[_backStack.length - 1];
                $('a[@href$="' + cachedHash + '"]').click();
                _currentHash = location.hash;
            } else if (_backStack[_backStack.length - 1] == undefined && !isFirst) {
                // back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
                // document.URL doesn't change in Safari
                if (document.URL.indexOf('#') >= 0) {
                    $('a[@href$="' + '#' + document.URL.split('#')[1] + '"]').click();
                } else if (initialized) {
                    $(document).trigger(RESET_EVENT);
                }
                isFirst = true;
            }
            initialized = true;
        };

    }

    this.initialize = function(callback) {
        // custom callback to reset app state (no hash in url)
        if (typeof callback == 'function') {
            $(document).unbind(RESET_EVENT, _defaultReset).bind(RESET_EVENT, callback);
        }
        // look for hash in current URL (not Safari)
        if (location.hash && typeof _addHistory == 'undefined') {
         //   $('a[@href$="' + location.hash + '"]').trigger('click');
        }
        // start observer
        if (_observeHistory && _intervalId == null) {
            _intervalId = setInterval(_observeHistory, 200); // Safari needs at least 200 ms
        }
    };

};
$.fn.remote = function(output, settings, callback) {

    callback = callback || function() {};
    if (typeof settings == 'function') { // shift arguments
        callback = settings;
    }
    
    settings = $.extend({
        hashPrefix: 'remote-'
    }, settings || {});

    var target = $(output).size() && $(output) || $('<div></div>').appendTo('body');
    target.addClass('remote-output');

	return this.each(function(i) {
		if (this.href.indexOf('#')<=0) {
			var el = exceptionLinks($(this));
			if ( el != -1 ) if (el == 1) return true; else if(el==0) return false;
			var href = this.href, a = this, hash = '#' + (this.title && this.title.replace(/\s/g, '_') || settings.hashPrefix + (i+1001) );//(Math.round(Math.random()*1000000))), a = this;
			$(this).click(function(e) {
				var temp = href;
				this.href = '#' + href;
				$ANC = $(this);
				if (!target['locked']) {
					// add to history only if true click occured, not a triggered click
					if (e.clientX) { $.ajaxHistory.update(this.href); }
					target.load(temp, {'ajax_check':'true'}, function() {
						$ANC.attr("href",temp);
						target['locked'] = null;
						callback.apply(a);
						if ( typeof check4update != "undefined" ) check4update(this.href);
					});
				}
			});
		}
    });

};

$.fn.history = function(callback) {
   return this.click(function(e) {        
        // add to history only if true click occured, not a triggered click
        if (e.clientX) {
            $.ajaxHistory.update(this.hash);
        }
        typeof callback == 'function' && callback();
    });
};

})(jQuery);






/*



var exceptionLinks = function($href) {
	// return 1 = return true
	// return 0 = return false
	// return -1 = do nothing!
	
	if ( ($href.attr('href').indexOf('language=') > 0 ) ||
	   	 ($href.attr('href').indexOf('javascript:') > 0 ) ||
		 ($href.attr('href').indexOf('ymsgr:') > 0 ) ||
		 ($href.attr('href').indexOf('sendIM') > 0 ) ||
		 ($href.attr('id') == 'forum_link' ) ||
		 ($href.attr('target') == '_blank' )
	) return 1;
};

var check4update = function( to ) {
	$.get('refresher.php',{'formName':'box', 'name':'whats_new'},function(data){ $("#box_whats_new").html(data); });
	$.get('refresher.php',{'formName':'box', 'name':'loginbox'},function(data){ $("#box_loginbox").html(data); });
	$.get('refresher.php',{'formName':'box', 'name':'wishlist'},function(data){ $("#box_wishlist").html(data); });
	$.get('refresher.php',{'formName':'javaload'},function(data){ $("#content").append(data); });
};
*/







