(function(){
	function getAddressInfo(address)
	{
		var result = {
			protocol: '',
			domain: '',
			path: '',
			prehash: '',
			posthash: ''
		};
		var url_re = /^((\w+)?:\/\/([^\/]+))?(.*)$/;
		var m = address.match(url_re);
		if (m && m[4])
		{
			var m2 = m[4].match(/^([^#]*)(#(.*))?$/);
			if (m2)
			{
				result.prehash = m2[1];
				result.posthash = m2[3] || '';
			}
			else
			{
				result.prehash = m[4];
			}
		}
		if (m)
		{
			if (!m[2]) m[2] = ''; if (!m[3]) m[3] = ''; if (!m[4]) m[4] = '';
			result.protocol = m[2].toLowerCase();
			result.domain = m[3].toLowerCase();
			result.path = m[4];
		}
		return result;
	}

	function getLayout(path)
	{
		if ((path == '') || path.match(/^\/(index\.(php|html?))?(#.*)?$/))
		{
			return 1;
		}
		else if (path.match(/^\/company\/news\/rss(\/(index\.(php|html?))?(#.*)?)?$/))
		{
			return 3;
		}
		else if (path.match(/^\/tickets\/schedule(\/(index\.(php|html?))?(#.*)?)?$/))
		{
			return 4;
		}
		else if ((jQuery.browser.opera || jQuery.browser.msie) && path.match(/^\/tickets\/airports(\/(index\.(php|html?))?(#.*)?)?$/))
		{
			return 5;
		}
		else
		{
			return 2;
		}
	}

	function canReloadContent(url, currentUrlInfo)
	{
		if (url.match(/^(javascript|mailto|ftp):/i) || url.match(/\.(jpe?g|png|gif|swf|flv|pdf|docx?|xlsx?|pptx?|txt)$/i))
			return false;

		var urlInfo = getAddressInfo(url);
		currentUrlInfo = currentUrlInfo || getAddressInfo(window.location.href);
		
		if (!urlInfo.protocol)
			urlInfo.protocol = currentUrlInfo.protocol;
		
		if (!urlInfo.domain)
			urlInfo.domain = currentUrlInfo.domain;
		
		if (urlInfo.protocol != 'http' && urlInfo.protocol != 'https' && urlInfo.protocol != '')
			return false;

		if (urlInfo.protocol == currentUrlInfo.protocol 
			&& urlInfo.domain.replace(/^www\./, '') == currentUrlInfo.domain.replace(/^www\./, '')
			&& urlInfo.prehash != currentUrlInfo.prehash)
		{
			var currentLayout = getLayout(urlInfo.prehash);
			var pageLayout = getLayout(currentUrlInfo.prehash);
			if (getLayout(urlInfo.prehash) == getLayout(currentUrlInfo.prehash))
			{
				// same protocol, domain and layout, allow content reloading
				return urlInfo.path;
			}
		}
		return false;
	}
	
	function bindQuickLinks()
	{
		var currentUrlInfo = getAddressInfo(window.location.href);
		$('a').each(function(){
			var path = '';
			var $this = $(this);
			if (!$this.hasClass('no-quick-reload'))
			{
				if (path = canReloadContent(this.href, currentUrlInfo))
				{
					if (!this.hasHashUriEvent)
					{
						this.hasHashUriEvent = true;
						$this.bind('click', function(){
							window.location.href = currentUrlInfo.protocol + '://' + currentUrlInfo.domain + currentUrlInfo.prehash + '#!' + path;
							return false;
						});
					}
				}
			}
		});
	}

	function onHashChange(e)
	{
		var frgm = e.fragment || (e.state ? e.state.fragment : null);
		if (frgm)
		{
			var m = frgm.match(/!(.+)/);
			if (m && m[1])
			{
				var dataContainer = getDataContainer();
				var menuContainer = getMenuContainer();
				dataContainer.css('opacity', 0.5);
				if (canReloadContent(m[1]) || (e.state && e.state.isPrev))
				{
					correctHashUrl();
					$.get(m[1], {qtype: 'ajax'}, function(result){
						var dataResult = result.match(/<content>([\s\S]*)<\/content>/m);
						var menuResult = result.match(/<menu>([\s\S]*)<\/menu>/m);
						var titleResult = result.match(/<title>([\s\S]*)<\/title>/m);
						if (dataResult)
						{
							dataContainer.html(dataResult[1]);
							if (menuResult)
								menuContainer.html(menuResult[1]);
							if (titleResult)
								document.title = 'Авиакомпания «Татарстан» | ' + titleResult[1];
							if ((typeof(pageUpdatedEvent)).toString().toLowerCase() == 'function')
							{
								pageUpdatedEvent();
							}
						}
						else
						{
							dataContainer.html(result);
						}
						dataContainer.css('opacity', 1);
						bindQuickLinks();
					});
				}
				else
				{
					window.location.href = m[1];
				}
			}
		}
	}

	function correctHashUrl()
	{
		if (window.history && window.history.replaceState && typeof(window.history.replaceState) == 'function')
		{
			var urlInfo = getAddressInfo(location.href);
			var m;
			if (urlInfo.posthash && (m = urlInfo.posthash.match(/^\!(\/.*)$/)))
			{
				window.history.replaceState({url: m[1], oldUrl: location.href, isPrev: 1, fragment: urlInfo.posthash}, '', m[1]);
			}
		}
	}

	function getDataContainer()
	{
		return $('div.content').first();
	}

	function getMenuContainer()
	{
		return $('ul.menu').first();
	}

	$(function(){
		if ($.browser.msie && ($.browser.version.slice(0,1) * 1 < 8))
			return;
		bindQuickLinks();
		$(window).bind('hashchange', onHashChange).trigger('hashchange');
		window.onpopstate = function(e) { if (e.state && e.state.isPrev) onHashChange(e); }
	});
})();
