Application = function(){
	var app = this;

	app.path = "/";
	app.contentAreaId = "ajax_maincontent";
	app.contentArea = $("#" + app.contentAreaId);
	
	app.mainHost = location.protocol + '//' + location.host;  

	
	
	if ($("#ajax_homecontent").length == 1){
		app.startedOnHomepage = true;
		app.onHomepage = true;
	}
	
	app.previousContent = "";
	app.initialHash = location.hash.replace(/^#/, '');
	
	if (app.contentArea.length == 1){
		var cacheImg = document.createElement("IMG");
		cacheImg.src = "/bitrix/templates/Main/images/loading_indicator.gif";
	
		app.activateLinks();
		$.historyInit(function(path) {app.jumpTo(path)});
	}
}

Application.prototype.activateLinks = function(){
	var app = this;
	$(".ajax:not(.activated)").each(function(){ this.onclick = ""});
	$(".ajax").not(".activated").find("*").each(function(){ this.onclick = function(){ return false}} );
	$(".ajax").not(".activated").bind("click", function(event){
		event.stopImmediatePropagation();
		event.preventDefault();
		
		if (!app.busy){
			var path = $(this).attr("ajaxurl");
			if (!path) path = $(this).attr("href");
			
			if (path.indexOf(app.mainHost) == 0){
				path = path.substring(app.mainHost.length)
			}
			
			path = extractPath(path);
	
			if (app.path != path) {
				if (path.charAt(0) != "/") {
					if (app.path.charAt(app.path.length - 1) != "/") path = "/" + path;
					path = app.path + path;
				}
				$.historyLoad(path);
			}
			return false;
		}
	} ).addClass("activated");
}

Application.prototype.activateMenus = function(){
	var app = this;
	
	$(".ajax.active").not('[ajaxgroup=rightmenu]').removeClass("active");

	$(".ajax").not('[ajaxgroup=rightmenu]').each(function(){
		var thisPath = normalizePath($(this).attr("ajaxurl"));
		var appPath = normalizePath(app.path);
		
		var groupId = $(this).attr("ajaxgroup");
		
		if (groupId == "mainmenu"){
			var thisPath = normalizePath($(this).attr("ajaxurl"), true);
		}
		
		var active = false;

		if (appPath.indexOf(thisPath) == 0){
			active = true;
		}

/*		
		if(groupId == "rightmenu"){
			var additionalUrls = $(this).attr("ajaxadditionalurls");
			if (additionalUrls != ""){
				var urls = additionalUrls.split("|");
				for (var i = 0; i < urls.length; i++) if (appPath.indexOf(normalizePath(additionalUrls)) == 0) active = true;
			}
		
		}
*/		
		if (active) {
			$(this).addClass("active");
		}
	});
}

function fixElementHeight (elem, changeHeight){
	var changeHeight = changeHeight == undefined ? true : changeHeight;
	var elemId = elem.attr("id");
	var container = $("#" + elemId + "_heightFixer");
	if (container.length == 0){
		container = document.createElement("DIV");
		container.id = elemId + "_heightFixer";
		container.style.position = "relative";
		elem.wrap(container);
	}

	if (changeHeight) {
		$(container).height(elem.height());
	}

	return $(container);
}

function releaseElementHeight (elem){
	var container = $("#" + elem.attr("id") + "_heightFixer");
	if (container.length != 0){
		container.height("auto");
	}
}

Application.prototype.loadUrl = function(path){
	var app = this;

	app.loadingComplete = false;
	app.loading = true;
	
	if (app.goingToHomepage){
		app.loadingComplete = true;
		app.loading = false;
		app.path = path;
		app.showLoadedPage();
	} else {
		$.ajax({
			url: extractPath(path),
			cache: false,
			dataType: "html",
			data: {
				AJAX: 1
			},
			success: function(data, textStatus) {
				app.dataLoaded = data;
				
				app.loading = false;
				app.loadingComplete = true;
				app.path = path;
				app.initialHash = null;
				
				window.location.hash = app.path;				
				
				app.showLoadedPage();
			}, 
			error: function(XMLHttpRequest, textStatus, errorThrown){
				app.loading = false;
				app.loadingComplete = true;
				
				app.dataLoaded = app.previousContent;
				app.showLoadedPage();
//				alert("Failed to negotiate with server.");
			}
		});
	}
}


Application.prototype.fadeContent = function(){
	var app = this;
	
	app.fadingTasksCount = 0;
	if (app.onHomepage) {
		app.onHomepage = false;
		app.fadeHomepage();
	} else {
		app.fadeMain();
	}
}

Application.prototype.fadeHomepage = function(){
	var app = this;

	app.homepageHeaderBg = $("div.fading-header-bg:visible");
	
	if (window.homeCorporateSwitchActivated){
		$(".main").removeClass("main-bg1-1");
	}

	app.homepageHeaderBg.fadeOut('normal');
	
	$("#home_maindiv_1").removeClass("main-bg-bug").addClass("main-bg3");
	$("#home_maindiv_2").removeClass("main-bg").addClass("main-bg4");
	$("#home_maindiv_3").removeClass("main-bg1");

	$("#home_leftcolumnbg_1").addClass("left-column-inside1");
	$("#home_leftcolumnbg_2").addClass("left-column-inside");
	

	$("#home_headerdiv_1").addClass("header-inside");
	$("#home_headerdiv_2").addClass("header-inside-bg1");
//	$("#home_headerdiv_3").addClass("header-inside-bg2");

/*
	app.fadingTasksCount++;
	$("#home_rightmenu_container").animate({
		marginTop: '0px'
	}, "slow", function(){
		$(this).addClass("right-menu-inside");
		$(this).css("margin-top", "-180px");

		app.fadingTasksCount--;
		app.showLoadedPage();
	});
*/	


	app.fadingTasksCount++;
	$("#home_headerdiv_3").animate({
		height: '230px'
	}, "slow", function(){
		$(this).addClass("header-inside-bg2");
		$(this).css("height", "auto");
		

		$("#home_phonediv_1").addClass("hidden");
		$("#home_phonediv_2").removeClass("hidden");
		
		app.fadingTasksCount--;
		app.showLoadedPage();
	});

	
	$("#home_subheader_1").addClass("hidden");
	$("#home_subheader_1").addClass("hidden");
	
	
	$("#home_headertext_1").addClass("hidden");
	
	
	$("#home_rightcolumnbg_1").addClass("right-column-inside1");
	$("#home_rightcolumnbg_2").addClass("right-column-inside");
	
	

//	$("#home_rightmenu_linksblock").addClass("hidden");
	$("#home_rightmenu_newsblock").addClass("hidden");
		
	app.fadingTasksCount++;
	$("#ajax_homecontent").fadeOut("slow", function(){
		app.displayLoadingMessage();
		
		app.fadingTasksCount--;
		app.showLoadedPage();
	});	

};


Application.prototype.displayLoadingMessage = function(){
	var app = this;
	
	app.contentArea.css("opacity", "");
	app.contentArea.height("auto");
	app.contentArea.html('<div class="loadingDiv"><img src="/bitrix/templates/Main/images/loading_indicator.gif" width="16" height="16" alt="" align="absmiddle"> Загрузка...</div>');
	app.contentArea.show();
};



Application.prototype.fadeMain = function(){
	var app = this;
	
	fixElementHeight(app.contentArea);
	app.previousContent = app.contentArea.html();
	
	
	if (app.goingToHomepage){
		$("#ajax_menu").hide();
/*	
		app.fadingTasksCount++;
		var menu_container = fixElementHeight($("#main_right_menu"));
		$(menu_container).animate({
			height: '10px'
		}, "slow", function(){
			$("#main_right_menu").html("");
			$(this).css("height", "auto");
			
			app.fadingTasksCount--;
			app.showLoadedPage();
		});
*/		
	}


	app.fadingTasksCount++;
	$("#maintitle_h2").fadeTo("normal", 0.5, function(){
		app.fadingTasksCount--;
		app.showLoadedPage();
	});
	
	
	app.fadingTasksCount++;
	app.contentArea.animate({
		opacity: 0,
		height: '0px'
	}, "fast", function(){
		app.contentArea.html("");
		app.displayLoadingMessage();

		app.fadingTasksCount--;
		app.showLoadedPage();
	});
}


Application.prototype.occupy = function(busy){
	var app = this;

	if (busy){
		app.busy = true;
		$('body').addClass("busy");
	} else {
		app.busy = false;
		$('body').removeClass("busy");
	}
}

Application.prototype.jumpTo = function(path){
	var app = this;
	if ((location.href.indexOf("dictionary.php") == -1 || path != app.initialHash) && normalizePath(path) != normalizePath(app.path)){
		if (!app.busy){
			app.occupy(true);
			app.goingToHomepage = false;
			if (normalizePath(path) == '/index.php' && app.startedOnHomepage) app.goingToHomepage = true;
			app.fadeContent();
			app.loadUrl(path);			
		}
	}
}

Application.prototype.showLoadedPage = function(){
	var app = this;	

	if (app.fadingTasksCount == 0 && app.loadingComplete){
		app.revealingTasksCount = 0;
		if (normalizePath(app.path) == '/index.php' && app.startedOnHomepage){
			app.onHomepage = true;
			app.path = "/";
			app.revealHomepage();
		} else {
			app.revealMain();
		}
	}
}

Application.prototype.revealHomepage = function(){
	var app = this;

	releaseElementHeight(app.contentArea);
	
	$("#home_maindiv_1").addClass("main-bg-bug").removeClass("main-bg3");
	$("#home_maindiv_2").addClass("main-bg").removeClass("main-bg4");
	$("#home_maindiv_3").addClass("main-bg1");

	$("#home_leftcolumnbg_1").removeClass("left-column-inside1");
	$("#home_leftcolumnbg_2").removeClass("left-column-inside");
	


	$("#home_subheader_1").removeClass("hidden");
	$("#home_subheader_1").removeClass("hidden");
	
	$("#home_phonediv_1").removeClass("hidden");
	$("#home_phonediv_2").addClass("hidden");
	
	$("#home_headertext_1").removeClass("hidden");
	
	
	$("#home_rightcolumnbg_1").removeClass("right-column-inside1");
	$("#home_rightcolumnbg_2").removeClass("right-column-inside");

/*	
	$("#home_rightmenu_container").removeClass("right-menu-inside");
	$("#home_rightmenu_linksblock").removeClass("hidden");
	$("#home_rightmenu_newsblock").removeClass("hidden");
	

	$("#main_right_menu_heightFixer").height("auto");
	$("#main_right_menu").html("");
*/
	$("#ajax_maincontent").html("");
	$("#mainbreadcrumbs").html("");
	$("#maintitle_h2").html("");
	$(".ajax.active").removeClass("active");
	
	app.revealingTasksCount++;
	app.homepageHeaderBg.fadeIn('normal', function(){
		$("#home_headerdiv_1").removeClass("header-inside");
		$("#home_headerdiv_2").removeClass("header-inside-bg1");
		$("#home_headerdiv_3").removeClass("header-inside-bg2");
		
		if (window.homeCorporateSwitchActivated){
			$(".main").addClass("main-bg1-1");
		}
		
		app.revealingTasksCount--;
		app.completeRevealingNewPage();
	});

	app.revealingTasksCount++;
	$("#ajax_homecontent").fadeIn("slow", function(){
		app.revealingTasksCount--;
		app.completeRevealingNewPage();
	});

};


Application.prototype.revealMain = function(){
	var app = this;
	
	var container = fixElementHeight(app.contentArea, false);
	app.contentArea.hide();
	app.contentArea.html(app.dataLoaded);
	
	var pagedata = $(".pagedata");
	if (pagedata.length != 0){
		var header = pagedata.find('.pagetitle').html();
		if (header != "") $("#maintitle_h2").fadeOut("fast", function(){
			$("#maintitle_h2").css("opacity", 1);
			$("#maintitle_h2").html(header);
			$("#maintitle_h2").fadeIn("fast");
		});
		
		var breadcrumbs = pagedata.find('.breadcrumbs').html();
		if (breadcrumbs != "") {
			$("#mainbreadcrumbs").hide();
			$("#mainbreadcrumbs").html(breadcrumbs);
			$("#mainbreadcrumbs").fadeIn("fast");
		}
/*
		$(".right_menu").remove();
		var rightmenu = pagedata.find('.right_menu').html();
		if (rightmenu != "") {
			var menu_container = fixElementHeight($("#main_right_menu"));
			$("#main_right_menu").html(rightmenu);
			
			$(menu_container).animate({
					height : $("#main_right_menu").height()
			}, "slow");
		}
*/
		var doctitle = pagedata.find('.browsertitle').html();
		if (doctitle != "") document.title = doctitle;
	}
	$(".pagedata").remove();

	app.revealingTasksCount++;
	app.contentArea.slideDown("slow");
	container.animate({
			height : app.contentArea.height() + 30
	}, "fast", function(){
		releaseElementHeight(app.contentArea);
		
		app.revealingTasksCount--;
		app.completeRevealingNewPage();
	});
}



Application.prototype.completeRevealingNewPage = function(){
	var app = this;
	
	if (app.revealingTasksCount == 0){
		app.dataLoaded = null;
		app.activateMenus();
		app.activateLinks();
		app.occupy(false);
	}
};



$(document).ready(function() {
	window.app = new Application();
});
/*
if (typeof($) == "function"){
	$(document).ready(function() {
//		$(".ajax.active[ajaxgroup=topmenu]").addClass("__activate_sifr");
		if (!($.browser.msie && $.browser.version < 7))
			window.app = new Application();
	});
};
*/







function extractPath (value, endSlash){
	endSlash = endSlash ? endSlash : true;
	var result = value;
	
	if (result) {
		result = result.replace(/#.*$/, '');
		if (result.charAt(result.length - 1) != "/" && result.indexOf(".php") == -1) result += "/";
	} else {
		result = "/";
	}
	if (endSlash == false && result.charAt(result.length - 1) == "/") result = result.substring(0, result.length - 1);
	
	return result;
}

function normalizePath (value, removeIndexScript){
	removeIndexScript = removeIndexScript ? removeIndexScript : false;
	var result = extractPath(value, false);
	
	result = result.replace(/index\.php$/, '');
	
	if (result.charAt(result.length - 1) == "/"){
		result = result + "index.php";
	}
	
	if (removeIndexScript)	result = result.replace(/index\.php$/, '');
	
	return result;
}





jQuery.extend({historyCurrentHash:undefined,historyCallback:undefined,historyInit:function(a){jQuery.historyCallback=a;var b=location.hash;jQuery.historyCurrentHash=b;if(jQuery.browser.msie){if(jQuery.historyCurrentHash==''){jQuery.historyCurrentHash='#'}$("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');var c=$("#jQuery_history")[0];var d=c.contentWindow.document;d.open();d.close();d.location.hash=b}else if($.browser.safari){jQuery.historyBackStack=[];jQuery.historyBackStack.length=history.length;jQuery.historyForwardStack=[];jQuery.isFirst=true}jQuery.historyCallback(b.replace(/^#/,''));setInterval(jQuery.historyCheck,100)},historyAddHistory:function(a){jQuery.historyBackStack.push(a);jQuery.historyForwardStack.length=0;this.isFirst=true},historyCheck:function(){if(jQuery.browser.msie){var a=$("#jQuery_history")[0];var b=a.contentDocument||a.contentWindow.document;var c=b.location.hash;if(c!=jQuery.historyCurrentHash){location.hash=c;jQuery.historyCurrentHash=c;jQuery.historyCallback(c.replace(/^#/,''))}}else if($.browser.safari){if(!jQuery.dontCheck){var d=history.length-jQuery.historyBackStack.length;if(d){jQuery.isFirst=false;if(d<0){for(var i=0;i<Math.abs(d);i++)jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop())}else{for(var i=0;i<d;i++)jQuery.historyBackStack.push(jQuery.historyForwardStack.shift())}var e=jQuery.historyBackStack[jQuery.historyBackStack.length-1];if(e!=undefined){jQuery.historyCurrentHash=location.hash;jQuery.historyCallback(e)}}else if(jQuery.historyBackStack[jQuery.historyBackStack.length-1]==undefined&&!jQuery.isFirst){if(document.URL.indexOf('#')>=0){jQuery.historyCallback(document.URL.split('#')[1])}else{var c=location.hash;jQuery.historyCallback('')}jQuery.isFirst=true}}}else{var c=location.hash;if(c!=jQuery.historyCurrentHash){jQuery.historyCurrentHash=c;jQuery.historyCallback(c.replace(/^#/,''))}}},historyLoad:function(a){var b;if(jQuery.browser.safari){b=a}else{b='#'+a;location.hash=b}jQuery.historyCurrentHash=b;if(jQuery.browser.msie){var c=$("#jQuery_history")[0];var d=c.contentWindow.document;d.open();d.close();d.location.hash=b;jQuery.historyCallback(a)}else if(jQuery.browser.safari){jQuery.dontCheck=true;this.historyAddHistory(a);var e=function(){jQuery.dontCheck=false};window.setTimeout(e,200);jQuery.historyCallback(a);location.hash=b}else{jQuery.historyCallback(a)}}});




;(function(h){var m=h.scrollTo=function(b,c,g){h(window).scrollTo(b,c,g)};m.defaults={axis:'y',duration:1};m.window=function(b){return h(window).scrollable()};h.fn.scrollable=function(){return this.map(function(){var b=this.parentWindow||this.defaultView,c=this.nodeName=='#document'?b.frameElement||b:this,g=c.contentDocument||(c.contentWindow||c).document,i=c.setInterval;return c.nodeName=='IFRAME'||i&&h.browser.safari?g.body:i?g.documentElement:this})};h.fn.scrollTo=function(r,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};a=h.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=h(k),d=r,l,e={},p=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(d)){d=n(d);break}d=h(d,this);case'object':if(d.is||d.style)l=(d=h(d)).offset()}h.each(a.axis.split(''),function(b,c){var g=c=='x'?'Left':'Top',i=g.toLowerCase(),f='scroll'+g,s=k[f],t=c=='x'?'Width':'Height',v=t.toLowerCase();if(l){e[f]=l[i]+(p?0:s-o.offset()[i]);if(a.margin){e[f]-=parseInt(d.css('margin'+g))||0;e[f]-=parseInt(d.css('border'+g+'Width'))||0}e[f]+=a.offset[i]||0;if(a.over[i])e[f]+=d[v]()*a.over[i]}else e[f]=d[i];if(/^\d+$/.test(e[f]))e[f]=e[f]<=0?0:Math.min(e[f],u(t));if(!b&&a.queue){if(s!=e[f])q(a.onAfterFirst);delete e[f]}});q(a.onAfter);function q(b){o.animate(e,j,a.easing,b&&function(){b.call(this,r,a)})};function u(b){var c='scroll'+b,g=k.ownerDocument;return p?Math.max(g.documentElement[c],g.body[c]):k[c]}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);
