(function ($)
{
   /*
	* Created by Stormbreaker
	*
	* This script now includes Ben Alman's FREE hashchange plugin 
	* needed to support back button and history in older browsers
	*
	*/
	
	var isLoaded = false;
	
	var myDomain = document.domain.replace(new RegExp("^www\\.", "i"), '');
	var currentPath = window.location.pathname.replace(new RegExp("\\/([^\\/]*?)$", "i"), '').replace("/", "\\/");
	var startPage = window.location.pathname.replace(new RegExp("^((.*)\\/)?([^\\/]*?)$", "i"), '$3');
	
	var regexpHasProtocol = new RegExp("^([^\\/\\?]+)?:", "i");
	var regexpMatchPage = new RegExp("^([^\\#]+)(\\#(.*))?$", "i");
//	var regexpIsFullUrl = new RegExp("^http:\\/\\/(www\\.)?" + myDomain + currentPath + "(\\/(([^\\.\\/]+)\\.(.*)))?$", "i");
	var regexpIsFullUrl = new RegExp("^http:\\/\\/(www\\.)?" + myDomain + "(" + currentPath + "(.*?)?)$", "i");
	
	var GlobalContainer;
	var RegisterForms = true;
	var OverrideHashes = true;

	var RegisteredContainers = [];
	
	var CurrentPage = '';
	
	var AnchorPrefix = '!';
	
	$.fn.InitAjaxer = function(prefix, regForms, OverrideHash)
	{
		GlobalContainer = this;
		isLoaded = true;
		
		if ( regForms != undefined )
			RegisterForms = regForms;
		
		if ( prefix != undefined )
			AnchorPrefix = prefix;
			
		if ( OverrideHash != undefined )
			OverrideHashes = OverrideHash;
		
		var anchorUrl = window.location.hash.match( new RegExp('^\#' + AnchorPrefix + '(.+)$', 'i') );

		if ( anchorUrl && anchorUrl[1] != startPage.replace(new RegExp("^(\\/)?(.*?)(\\/)?$"), currentPath.replace("\\", "") + "/$2") )
		{
			$(GlobalContainer).hide();
			$(GlobalContainer).LoadWithAjaxer(anchorUrl[1], "", 'GET', function(){
				$(GlobalContainer).show();
			}, function(){
				$(GlobalContainer).show();
			},
			false);
		}
			
		$("a").RegisterAjaxer(GlobalContainer);
		
		if ( RegisterForms )
			$("form").RegisterForm(GlobalContainer);
			
		$(window).bind('hashchange', function(){
			var anchorUrl = window.location.hash.match( new RegExp('^\#' + AnchorPrefix + '(.*)$', 'i') );

			if ( anchorUrl && anchorUrl[1] != CurrentPage )				
				$(GlobalContainer).LoadWithAjaxer(anchorUrl[1], "", 'GET');
			else if ( !anchorUrl && window.location.hash == "" )
				$(GlobalContainer).LoadWithAjaxer(startPage, "", 'GET', undefined, undefined, undefined, false);
			else if ( !anchorUrl && window.location.hash != "" && OverrideHashes )
				window.location.hash = AnchorPrefix + CurrentPage;
		});
			
		return $(this);
	};
	
	$.fn.RegisterForm = function(container)
	{
		return this.find("form").andSelf().filter("form").each(function(i){			
			var element = this;
			
			if ( $(this).find("input[type=file]").length > 0 )
			{
				if ( $(this).attr("action") == undefined || $(this).attr("action").length == 0 )
				{					
					target = CurrentPage;
					$(this).attr("action", target);
				}
				
				return;
			}
			$(this).parent().bind("submit.ajaxer", function(event){
				//alert($(event.target).filter(":first").attr('type'));
				
				if ( event.target == element || $(event.target).filter("input[type=submit]").parents("form:first").get(0) == element )
				{
					if ( !event.isDefaultPrevented() )
					{
						var target = $(element).attr("action");
						var PostType = 'GET';
						
						if ( target == undefined || target.length == 0 )
						{
							target = CurrentPage;
							$(element).attr("action", target);
						}
						
						if ( $(element).attr("method").length == 0 )
							PostType = 'GET';
						else if ( $(element).attr("method").match(/^post$/i) || $(element).attr("method").match(/^get$/i) )
							PostType = $(element).attr("method");
						else
						{
							window.location.hash = '';
							
							return true;
						}
						
						$(container).LoadWithAjaxer(target, $(element).AjaxerSerialize(), PostType);
					
						event.stopPropagation();
						event.preventDefault();
						event.stopImmediatePropagation();
					}

					return false;
				}
			});
		});
};
	
	$.fn.AjaxerSerialize = function()
	{
		var s = $(this).serialize();
		var btn = $("input[name][type=submit]");
		
		if ( btn.length == 0 )
			return s;
		
		var str = btn.attr('name') + '=' + btn.val();
		
		if ( s.length > 0 )
			s += '&' + str;
		else
			s = str;
		
		return s;
	};
	
	$.fn.RegisterContainer = function(selector, options)
	{
		options = $.extend({}, $.fn.RegisterContainer.defaults, options);
		
		return this.each(function(){
			if ( selector == undefined && $(this).is("[id]") )
				select = "#" + $(this).attr('id');
			else if ( selector == undefined )
				return;
			else
				select = selector;
			
			RegisteredContainers.unshift({container: this, select: select, showIfHidden: options.showIfHidden, hideWhenNull: options.hideIfNull, type: options.type, removeAfter: options.removeAfter});
		});
	};
	
	$.fn.RegisterContainer.defaults = { hideIfNull: true, showIfHidden: true, type: 'fillcontents', removeAfter: true };
	
	$.fn.UnregisterAjaxer = function()
	{
		this.find("a").andSelf().filter("a").each(function(i){
			$(this).unbind("click.ajaxer");
		});
		
		this.find("form").andSelf().filter("form").each(function(i){
			$(this).parent().unbind("submit.ajaxer");
		});
	}
	
	$.fn.RegisterAjaxer = function(container)
	{
		this.find("a").andSelf().filter("a").each(function(i){
			if ( $(this).attr("href") == undefined )
				return;
			
			if ( container == undefined )
				return;
			
			var link;
			var shouldPrependLink = false;
			
			var matches = $(this).attr("href").match(regexpIsFullUrl);
			var matchLink = $(this).attr("href").match(regexpMatchPage);
			
			if ( matches )
				link = matches[2];
			else if ( $(this).attr("href").match(regexpHasProtocol) )
				return;
			else if ( $(this).attr("href").match(/^\?/i) )
			{
				shouldPrependLink = true;
				link = $(this).attr("href");
			}
			else if ( matchLink )
				link = matchLink[1];
			else
				return;
	
			$(this).bind("click.ajaxer", function(event){
				var rawLink = $(this).attr("href");
				
				$(this).attr("href", "#");

				var elm = this;
				var link2 = link;

				if ( shouldPrependLink )
					link2 = CurrentPage.replace(/\?(.*)$/i, '') + link;
				
				$(container).LoadWithAjaxer(link2, "", 'GET', function(url, container){
					$(elm).attr("href", rawLink);
				}, function(url, container, error){
					$(elm).attr("href", rawLink);
				});
				
				event.preventDefault();			
				return false;
			});
		});
	};
	
	$.fn.LoadWithAjaxer = function(link, PostData, PostType, completeHandler, errorHandler, event, usehash)
	{
		if ( link == undefined )
			return;
			
		if ( event == undefined )
			event = true;
			
		if ( usehash == undefined )
			usehash = true;
			
		CurrentPage = link;
		
		var container = this;
		
		if ( event )
			$(container).trigger("AjaxerBeforeReload", [link, container]);
		
		if ( PostType == undefined )
			PostType = 'GET';

		RealRequest(container, link, PostData, PostType, completeHandler, errorHandler, event, usehash);
		
		return $(this);
	};
	
	function RealRequest(container, link, PostData, PostType, completeHandler, errorHandler, event, usehash)
	{
		$.ajax({cache: false, dataType: 'html', error: function(XMLHttpRequest, textStatus, errorThrown){
			
			if ( errorHandler != undefined )
				errorHandler(link, container, errorThrown);
			
			if ( event )
			$(container).trigger("AjaxerError", [link, container, errorThrown]);
		},
		success: function(data, textStatus)
		{			
		  if ( isLoaded && usehash )
			window.location.hash = AnchorPrefix + link;
			
			$(container).queue(function(){
				$(container).html(data);
				
				if ( isLoaded )
				{
					$(container).RegisterAjaxer(GlobalContainer);
					
					if ( RegisterForms )
						$(container).RegisterForm(GlobalContainer);
				}
				
				var c;
				var d;
				var opt;
	
				for ( key in RegisteredContainers )
				{
	                if ( !$(RegisteredContainers[key].container).is("body *") )
	                    continue;
	             	
					c = $(container).find(RegisteredContainers[key].select);
					
					if ( c.length > 0 )
					{
						d = $(RegisteredContainers[key].container);
						
						d.queue(function(){
							
							opt = RegisteredContainers[key];
							
							if ( event )
								d.trigger("ContainerBeforeReload", [link, d]);
							
							if ( opt.type == 'fillcontents' )
								d.html(c.html());
							else if ( opt.type == 'append' )
								d.append(c.html());
							else if ( opt.type == 'prepend' )
								d.prepend(c.html());
							else if ( opt.type == 'appendonce' )
							{
								if ( d.find(opt.select).length > 0 )
								{
									d = d.find(opt.select);
									d.html(c.html());
								}
								else
									d.append(c.clone());
							}
							else if ( opt.type == 'prependonce' )
							{
								if ( d.find(opt.select).length > 0 )
								{
									d = d.find(opt.select);
									d.html(c.html());
								}
								else
									d.prepend(c.clone());
							}
							
							if ( opt.removeAfter )
								c.remove();
							
							if ( opt.hideWhenNull && d.html().length == 0 )
								d.hide();
							else if ( opt.showIfHidden && d.is(':hidden') )
								d.show();
							
							if ( isLoaded )
							{
								$(d).RegisterAjaxer(GlobalContainer);
								
								if ( RegisterForms )
									$(d).RegisterForm(GlobalContainer);
							}
							
							if ( event )
								d.trigger("ContainerReload", [link, d]);
							
						$(this).dequeue();
						});
					}
				}
				
				if ( completeHandler != undefined )
					completeHandler(link, container);
								
				if ( event )
					$(container).trigger("AjaxerReload", [link, container]);
				
				$(this).dequeue();
			});
		},
		type: PostType, url: link, data: PostData
		});
	}
	
})(jQuery);

/*
 * jQuery hashchange event - v1.2 - 2/11/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,i,b){var j,k=$.event.special,c="location",d="hashchange",l="href",f=$.browser,g=document.documentMode,h=f.msie&&(g===b||g<8),e="on"+d in i&&!h;function a(m){m=m||i[c][l];return m.replace(/^[^#]*#?(.*)$/,"$1")}$[d+"Delay"]=100;k[d]=$.extend(k[d],{setup:function(){if(e){return false}$(j.start)},teardown:function(){if(e){return false}$(j.stop)}});j=(function(){var m={},r,n,o,q;function p(){o=q=function(s){return s};if(h){n=$('<iframe src="javascript:0"/>').hide().insertAfter("body")[0].contentWindow;q=function(){return a(n.document[c][l])};o=function(u,s){if(u!==s){var t=n.document;t.open().close();t[c].hash="#"+u}};o(a())}}m.start=function(){if(r){return}var t=a();o||p();(function s(){var v=a(),u=q(t);if(v!==t){o(t=v,u);$(i).trigger(d)}else{if(u!==t){i[c][l]=i[c][l].replace(/#.*/,"")+"#"+u}}r=setTimeout(s,$[d+"Delay"])})()};m.stop=function(){if(!n){r&&clearTimeout(r);r=0}};return m})()})(jQuery,this);
