(function($) {
	// initialize jhistory - the iframe controller and setinterval'd listener (pseudo observer)
	$(function () {
		
		//Init - Create Hidden IFrame
		$('body').append("<iframe id=\"__historyFrame\" style=\"display:none; height: 0;\" src=\"\fileadmin\scripts\blank.html#0\"></iframe>");
		
		//Init Cursors
		$.simplehistory.cursorLast = 0;
		$.simplehistory.cursor = 0;
		$.simplehistory.locked = false;
		$.simplehistory.data = new Array();
		
		//Setup a polling function
		$.simplehistory.intervalId = $.simplehistory.intervalId || window.setInterval(function () {
				//fetch current cursor from the iframe document.URL or document.location depending on browser support
				var cursorStr = $('#__historyFrame').contents().attr( $.browser.msie ? 'URL' : 'location' ).toString().split('#')[1];
				var cursor = parseFloat(cursorStr);
				
				//check if lastknown cursor has changed
				if(cursor != $.simplehistory.cursorLast)
				{
					//try callback function
					if (!$.simplehistory.locked && typeof($.simplehistory.callback) == 'function')
						//call users function 
						$.simplehistory.callback($.simplehistory.cursorLast, $.simplehistory.data[cursor]);
					else
						//release lock
						$.simplehistory.locked = false;					
				}
			
				//save current cursor as lastknown cursor
				$.simplehistory.cursorLast = cursor;
				
				//save current cursor, add 1 for the next cycle
				if($.simplehistory.cursor > 0)
					$.simplehistory.cursor = cursor + 1;
		}, 100);

	});
	
	
	// core history plugin functionality - handles singleton instantiation and history observer interval
	$.simplehistory = function ( data )
	{
		//set a lock so the callback isn't fired twice
		$.simplehistory.locked = true;
		
		//save users data
		$.simplehistory.data[$.simplehistory.cursor] = data;

		if ($.simplehistory.cursor > 0) {
			
			// force the new hash we're about to write into the IE6/7 history stack
			if ($.browser.msie) 
				$('#__historyFrame')[0].contentWindow.document.open().close();
			// write the fragment id to the hash history - webkit required full href reset - ie/ff work with simple hash manipulation
			if ($.browser.safari) 
				$('#__historyFrame').contents()[0].location.href = $('#__historyFrame').contents()[0].location.href.split('?')[0] +
				'?' +
				$.simplehistory.cursor +
				'#' +
				$.simplehistory.cursor;
			else 
				$('#__historyFrame').contents()[0].location.hash = '#' + $.simplehistory.cursor;
		}
		
		//increase counter
		$.simplehistory.cursor++;
					
	}
})(jQuery);