function Settings()
{
	this.baseurl = '/';
	this.preloader = ''; // html preloader'a
	this.timeout = 3000; // ajax timeout
	//this.dUP = 800;
} 
Settings.prototype.setBaseUrl = function(baseurl) { this.baseurl = baseurl; }
Settings.prototype.setAjaxTimeout = function(t) { this.timeout = t; }
Settings.prototype.setHtmlPreloader = function(html) { this.preloader = html; }

/* Request */
function Request()
{
	this.action  = '';
	this.section = '';
	this.docurl  = '';
	this.sid = 0;
	this.cid = 0;
	this.id  = 0;
	this.p   = 1;
	this.q   = '';
	this.lng = 'ru';
	
}

Request.prototype.buildUrl = function(parser)
{
	var url = '';
	
	url = this.section;
	
	if (this.sid > 0 && !this.id)
		url += parser.VARS_SEP + 'section' + parser.VALUES_SEP + this.sid;
	else if (this.cid > 0 && !this.id)
		url += parser.VARS_SEP + 'category' + parser.VALUES_SEP + this.cid;
	else if (this.cid > 0 && this.id > 0)
		url += parser.VARS_SEP + 'category' + parser.VALUES_SEP + this.cid + parser.VARS_SEP + 'doc' + parser.VALUES_SEP + this.id; 
	else
		alert('ERROR: buildUrl');
	
	url += parser.VARS_SEP + '1';
	
	return url;
}

/* Ajax Application */
function AjaxApp(settings)
{
	/*this.request.section = '';
	this.action = '';
	this.request.id = 0;
	this.request.p = 0;*/
	
	this.request = {};
	this.parser  = {};
	
	this.cur_href = '';
	this.prev_href = '';
	
	this.section_click = '';
	
	this.settings = settings;
	this.ajax_send = 0; //флаг искусственно блокирующий отправку нескольких запросов; псевдо синхронность
	this.sections = [];
	this.result;
	/*var app_start = 0; //?
	var prev_url = '' // ??*/
	
	this.current_open = '';
	
	this.lng = 'ru';
	
	/*var arr_sections = new Array();
	var arr_block_changed = new Array();*/
	//
	this.isOpera = false;
	
	// массив содержит результаты поиска
	var arr_search_results = new Array();
}

AjaxApp.prototype.ajaxStart = function() { this.ajax_send = 1;}
AjaxApp.prototype.ajaxStop = function() { this.ajax_send = 0;}
AjaxApp.prototype.searchStart = function() 
{
	//alert($('#btn_search').html());
	$('#btn_search').html('<img src="/img/loading_16.gif" class="loading16" height="20" />');
	this.ajaxStart();
	this.closeAll();
}
AjaxApp.prototype.searchStop = function(found) 
{
	//alert(found);
	var txtNotFound;
	txtNotFound = (this.lng == 'en')? 'Unfortunately, no documents were found with this keyword' : 'По вашему запросу ничего не найдено' ;
	
	if  (found != true)
		alert(txtNotFound);
	
	//alert($('#btn_search').html());
	var txt;
	txt = (this.lng == 'en')? 'Search' : 'Поиск';
	$('#btn_search').html(txt);
	this.ajaxStop();
	//this.openAll();
}


AjaxApp.prototype.isRun = function() { return this.ajax_send? true : false; }

AjaxApp.prototype.init = function(params) {	this.request = this.parser.parse_params(params); }

AjaxApp.prototype.addSection = function(s) { this.sections[ this.sections.length ] = s; }

AjaxApp.prototype.back = function()
{
	if (!this.isRun())
		window.history.back();
	else
		alert('Выполняется запрос! Попробуйте позже');
}


AjaxApp.prototype.deactiveAll = function() 
{
	var i, max;
	for (i = 0, max = this.sections.length; i < max; i++)
	{
		$('#block-'+this.sections[i]+' h2').removeClass('active');
		$('#block-'+this.sections[i]+' .nav a.active').removeClass('active');
	}
}

AjaxApp.prototype.clearSearchQuery = function() { $('input[name=q]').val(''); }
AjaxApp.prototype.setParser = function(parser) { this.parser = parser; }
AjaxApp.prototype.setSectionClick = function(s) { this.section_click = s; }
AjaxApp.prototype.clearSectionClick = function() { this.section_click = ''; }
AjaxApp.prototype.setCurrent = function(s)
{
	$('#block-'+this.current_open+' h2').removeClass('active');
	$('#block-'+s+' h2').addClass('active');
	this.current_open = s;
}

AjaxApp.prototype.openSections = function (sections)
{
	if (sections.length)
		for (var i = 0; i < sections.length; i++)
			$('#block-'+sections[i]+' .block-body').slideDown({duration: dDown});
}

AjaxApp.prototype.checkOpera = function()
{
	var browser = jQuery.browser;
	//alert(browser.m);
	//alert(jQuery.browser.version.indexOf('Opera'));
	this.isOpera = (browser.opera)? true : false;
}

AjaxApp.prototype.openAll = function() { $('.block-body').show(); }
AjaxApp.prototype.closeAll = function() { /*$('.block-body .content').html('');*/ this.deactiveAll(); $('.block-body').hide(); }
AjaxApp.prototype.closeOther = function(s) 
{ 
	var i, max;
	for (i = 0, max = this.sections.length; i < max; i++)
	{
		if (this.sections[i] != s)
			this.closeSection(this.sections[i]);
		/*else
			alert(s);*/
		
	}
}

AjaxApp.prototype.closeSection = function(s) 
{ 
	$('#block-'+s+' .block-body').slideUp({duration: dUp});
	//$('#block-'+current_open+' .block-body').hide('slow');
	//$('#block-'+current_open+' h2').toggleClass('active');
	//$('#block-'+s+' .block-body').hide();
	$('#block-'+s+' h2').removeClass('active');
}
AjaxApp.prototype.openSection = function(s, clear, preloader) 
{
	//$('#block-'+section+' .block-body').slideDown({duration: dDown});
	if (clear)
		$('#block-'+s+' .block-body').html(' ');
	
	$('#block-'+s+' .block-body').slideDown({duration: dDown});
	
	if (preloader)
		$('#block-'+s+' .block-body').html(this.settings.preloader);
}
AjaxApp.prototype.updateSection = function(s, data, replace) 
{
	if (replace)
		$('#block-'+s+' .block-body').replaceWith(data);
	else
		$('#block-'+s+' .block-body').html(data);
}

AjaxApp.prototype.clearSection = function(s) { $('#block-'+s+' .block-body').html(''); }

AjaxApp.prototype.checkRedirect = function()
{
	if (this.request.p > 1)
	{

		var old_r;
		if (this.prev_href != '')
			old_r = this.parser.parse_params(this.prev_href);
		dbg('prev_href: '+this.prev_href+' , cur_href: '+this.cur_href+', p: '+this.request.p);
		if (old_r)
			dbg('old.p: '+old_r.p);
		// сверяем урл. текущий берется без указания номера страницы
		if ((this.prev_href.indexOf(this.cur_href.replace('='+this.request.p, '')) == -1 ||
			(this.prev_href.indexOf(this.cur_href.replace('='+this.request.p, '')) != -1 &&
			 old_r.id && (this.request.p - old_r.p) > 1)) && this.request.action != 'search')
		{
			this.redirect();
		}
		else
		{
			if (this.prev_href)
			{
				//alert(old_r.p + ' > ' + this.request.p);
				if (old_r.p > this.request.p)
				{
					//удаление блоков постр. навигации
					for (var i = this.request.p; i <= old_r.p; i++)
					{
						$('#block-'+this.request.section+' .pp'+i).remove();
						$('#block-'+this.request.section+' .index.page'+i).remove();
					}
				}
			}
		}
	}
	
	return false;
}


AjaxApp.prototype.run = function(params)
{
	//alert('params: '+params);
	
	if (!this.isRun())
	{
		if (params != '')
			this.init(params);
		
		//alert('prev: ' + this.prev_href);
		
		this.checkRedirect();
		
		// т.е. если урл с постр. навигацией но не та секция, то редирект на секцию с p=1
		//alert(this.prev_href);
		/*if (this.current_open != this.request.section && this.request.p > 1)
		{
			this.redirect();
		}*/
		
		this.request.lng = this.lng;
		
		switch (this.request.action)
		{
			case 'section': this.SectionAction(); break;
			
			case 'category': this.CategoryAction(); break;
			
			case 'doc': 
			/*case 'docurl':*/ this.DocAction(); break;
			
			case 'search': 
				if (this.request.q == '')
				{
					alert('Введите запрос!');
					return false;
				}
				
				if (this.request.p > 1)
					this.SectionSearchAction(this.request.section, this.request.q, this.request.p);
				else
					this.SearchAction(this.request.q);
				
				break;
			
			default: alert('Error: unknown action!'); 
		}
	}
	
	this.clearSectionClick();
	
	return false;
}

AjaxApp.prototype.redirect = function()
{
	var url = this.request.buildUrl(this.parser);
	//alert('redirect: ' + url);
	
	dbg('redirect: '+url);
	this.prev_href = this.cur_href;
	this.cur_href = url;
	$.address.value(url);
	$.address.update();
}

AjaxApp.prototype.SectionAction = function()
{
	/*if (this.request.section == this.current_open && this.request.p <= 1)
	{
		this.closeSection(this.current_open);
		this.current_open = '';
		return;
	}*/
	
	if (this.section_click == this.request.section)
	{
		this.closeSection(this.current_open);
		this.current_open = '';
		return;
	}

	// т.е. если это не первый клик по секции
	if (this.current_open != '' && this.request.section != this.current_open)
	{
		this.closeSection(this.current_open);
	}
	
	// т.е. если урл с постр. навигацией но не та секция, то редирект на секцию с p=1
	//alert(this.prev_href);
	/*if (this.current_open != this.request.section && this.request.p > 1)
	{
		this.redirect();
	}*/
	
	this.closeOther( this.request.section );
	this.clearSearchQuery();
	
	// loading
	if (this.request.p <= 1)
	{
		this.openSection(this.request.section, true, true);
	}
	else
	{
		$('#block-'+this.request.section+' .pagenavigation.pp'+(this.request.p-1)).before(this.settings.preloader);
	}
		
	this.ajaxStart(); 
	
	var params;
	params = (this.request.p > 1)? {section_id : this.request.sid, page : this.request.p, ajax : 1, lng : this.request.lng} : {section_id : this.request.sid, lng : this.request.lng};
	
	$.ajax({
		type : "POST",
		url : "/ajax.php", 
		data : params,
		timeout : this.settings.timeout,
		error : function () { ajaxapp.ajaxStop(); //ajax_send = 0; //alert('error ajax');
	},
	success : function (data){
		ajaxapp.ajaxStop();
		
		//$('#block-'+section+' .block-body').replaceWith(data);
		
		if (ajaxapp.request.p > 1)
		{
			
			$('#block-'+ajaxapp.request.section+' div.loading').replaceWith('');
			//$('#block-'+section+' .pagenavigation').after(data);
			$('#block-'+ajaxapp.request.section+' .pagenavigation.pp'+(ajaxapp.request.p-1)).after(data);
			$('#block-'+ajaxapp.request.section+' .pp'+(ajaxapp.request.p-1)).hide();
			
			back_event(ajaxapp.request.section, ajaxapp.request.p);
		}
		else
		{
			ajaxapp.updateSection(ajaxapp.request.section, data, true);
			
			$('.content a:not(.noaddress)').address();
			$('.index a').address();
			
		}
		ajaxapp.focusTo( ajaxapp.request.section );
		tip_event();
		a_event();
	}});
	
	this.setCurrent(this.request.section);
	this.focusTo(this.request.section);
}

AjaxApp.prototype.CategoryAction = function()
{
	var params;
	params = (this.request.p > 1)? {category_id : this.request.cid, page : this.request.p, ajax : 1, lng : this.request.lng} : {category_id : this.request.cid, lng : this.request.lng};
	
	if (this.request.section != this.current_open)
	{
		this.closeSection(this.current_open);
	}
	
	this.closeOther( this.request.section );
	this.clearSearchQuery();
	
	/*
	// т.е. если урл с постр. навигацией но не та секция, то редирект на секцию с p=1
	if (this.current_open != this.request.section && this.request.p > 1)
	{
		this.redirect();
	}*/
	
	// loading
	if (this.request.p <= 1)
	{
		this.openSection(this.request.section, true, true);
		//$('#block-'+section+' .block-body').html(html_loading);
	}
	else
	{
		$('#block-'+this.request.section+' .pagenavigation.pp'+(this.request.p-1)).before(this.settings.preloader);
		//$('#block-'+section+' .pagenavigation').before(html_loading);
	}
	
	this.ajaxStart();
	
	$.ajax({
		async: true,
		type: "GET",
		url: "/ajax.php",
		data: params,
		timeout : this.settings.timeout,
		error : function (r, t, e) { ajaxapp.ajaxStop(); return this; },
		success: function(data){
			//if (data)
				//alert(data);
				
			ajaxapp.ajaxStop();
			if (ajaxapp.request.p > 1 && $('#block-'+ajaxapp.request.section+' .pp'+(ajaxapp.request.p-1)))
			{
				$('#block-'+ajaxapp.request.section+' div.loading').replaceWith('');
				//$('#block-'+section+' .pagenavigation').after(data);
				$('#block-'+ajaxapp.request.section+' .pagenavigation.pp'+(ajaxapp.request.p-1)).after(data);
				$('#block-'+ajaxapp.request.section+' .pp'+(ajaxapp.request.p-1)).hide();
				//alert(data);
				//eventы на back
				//change text
//					tip_event();
				back_event(ajaxapp.request.section, ajaxapp.request.p);
			}
			else
			{
				ajaxapp.updateSection(ajaxapp.request.section, data, true);
				//$('#block-'+section+' .block-body').replaceWith(data);
				$('.content a:not(.noaddress)').address();
			}
			ajaxapp.focusTo( ajaxapp.request.section );
			tip_event();
			a_event();
		}
	});
	
	this.setCurrent(this.request.section);
	this.focusTo(this.request.section);
	
}

AjaxApp.prototype.DocAction = function()
{
	var params;
	if (this.request.action == 'docurl')
		params = (this.request.p > 1)? {docurl : this.request.docurl, page : this.request.p, ajax : 1, lng : this.request.lng} : {docurl : this.request.docurl, lng : this.request.lng};
	else
		params = (this.request.p > 1)? {docid : this.request.id, page : this.request.p, ajax : 1, lng : this.request.lng} : {docid : this.request.id, lng : this.request.lng};
	
	if (this.request.section != this.current_open)
	{
		//arr_block_changed.push(section);
		this.closeSection(this.current_open);
		/*$('#block-'+current_open+' .block-body').slideUp({duration: dUp});
		$('#block-'+current_open+' h2').toggleClass('active');*/
		a_event();
		
	}
	
	this.closeOther( this.request.section );
	this.clearSearchQuery();
	
	/*
	// т.е. если урл с постр. навигацией но не та секция, то редирект на секцию с p=1
	if (this.current_open != this.request.section && this.request.p > 1)
	{
		this.redirect();
	}*/
	
	/*if (current_open != section)
	{
		$('#block-'+section+' .block-body').slideDown({duration: dDown});
	}*/
	
	
	if (this.request.p <= 1)
	{
		this.openSection(this.request.section, true, true);
		//$('#block-'+this.request.section+' .block-body').html(html_loading);
	}
	else
	{
		if (this.current_open != this.request.section)
			this.openSection(this.request.section, true, true);
		
		$('#block-'+this.request.section+' .pagenavigation.pp'+(this.request.p-1)).before(this.settings.preloader);
	}
	
	this.ajaxStart();
	
	//alert('focus');
	$('#block-'+this.request.section+' .content').focus();
	//return;
	//ajax_send = 1;
	
	$.ajax({
		async: true,
		type: "GET",
		url: "/ajax.php",
		data: params,
		timeout : this.settings.timeout,
		error: function (r, t, e) { ajaxapp.ajaxStop(); return this; },
		success : function (data){
			ajaxapp.ajaxStop();
			//alert(data);
			if (ajaxapp.request.p > 1)
			{
				$('#block-'+ajaxapp.request.section+' div.loading').replaceWith('');
				$('#block-'+ajaxapp.request.section+' .pagenavigation.pp'+(ajaxapp.request.p-1)).after(data);
				$('#block-'+ajaxapp.request.section+' .pp'+(ajaxapp.request.p-1)).hide();
				
				back_event(ajaxapp.request.section, ajaxapp.request.p);
			}
			else
			{
				ajaxapp.updateSection(ajaxapp.request.section, data, true);
				//$('#block-'+section+' .block-body').replaceWith(data);
				
				$('.content a:not(.noaddress)').address();
				$('.index a').address();
			}
			
			ajaxapp.focusTo( ajaxapp.request.section );
			
			tip_event();
			a_event();
			
		}
	});
	
	$('#block-'+this.request.section+' .content').focus();

	if (this.request.section != this.current_open)
		this.clearSection(this.current_open);
		//$('#block-'+current_open+' .block-body').html('');
	
	this.setCurrent(this.request.section);
	//current_open = section;
	
	this.focusTo(this.request.section);
}

AjaxApp.prototype.SearchAction = function(q)
{
	this.searchStart();
	
	$.getJSON( '/ajax.php', {q : this.request.q, ajax : 1, lng : this.request.lng}, function (data, status){
		
		var found = false;
		var o = new Array();
		if (status == 'success' && data)
		{
			$.each(data.result, function(i, item){
				//alert(item.html);
				if (item.html)
				{
					found = true;
					o[ o.length ] = item.section;
					back_event(item.section, 1);
				}
				
				$('#block-'+item.section+' .block-body').html('<div class="results"></div>');
				$('#block-'+item.section+' .block-body .results').html(item.html);
			 });
			 
			 ajaxapp.openSections(o);
		}
		tip_event();
		a_event();
		ajaxapp.searchStop(found);
	});
	
	
	/*$.ajax({
		async: true,
		type: "GET",
		url: "ajax.php",
		data: {q : this.request.id, ajax : 1},
		timeout : this.settings.timeout * 2,
		error : function () { ajaxapp.ajaxStop(); },
		success : function (data){
			alert(data.length);
			
			/*
						{
				$('#block-'+section+' .block-body .results').html(data);
				//$('.content a:not(.noaddress)').address();
				//$('.index a').address();
			}
			tip_event();
			a_event();*/
		/*}
	});*/

}

AjaxApp.prototype.SectionSearchAction = function(section, q, p)
{
	this.closeOther(section);
	this.setCurrent(section);
	
	//alert(p);
	
	var params = {q : q, page : p, section_name: section, ajax : 1, lng : this.request.lng};
	
	$('#block-'+section+' .pagenavigation.pp'+(p-1)).before(this.settings.preloader);
	
	this.ajaxStart();
	
	$.ajax({
		async: true,
		type: "GET",
		url: "/ajax.php",
		data: params,
		timeout : this.settings.timeout,
		error : function () { ajaxapp.ajaxStop() },
		success : function (data){
			//постраничная
			$('#block-'+section+' div.loading').replaceWith('');
			$('#block-'+section+' .pagenavigation.pp'+(p-1)).after(data);
			$('#block-'+section+' .pp'+(p-1)).hide();
			//eventы на back
			//change text
			back_event(section, p);
			tip_event();
			a_event();
			ajaxapp.ajaxStop();
			
			ajaxapp.request = {};
		}
	});
}


/* Parser */
function Parser(vars_separator, values_separator)
{
	this.VARS_SEP = vars_separator;
	this.VALUES_SEP = values_separator;
}

/* return Request object */
Parser.prototype.parse_params = function(str)
{
	if (str == '')
	{
		alert('ERROR: empty argument "str"');
		return null;
	}
	
	var r = new Request();
	var tmp = '';
	
	if (str.indexOf(this.VARS_SEP))
	{
		
		str = str.split(this.VARS_SEP);
		r.section = str[0];
		
		switch (str.length)
		{
			// url: {SECTION}=category_{CID}=doc_{ID}={P}
			case 4:
				r.action = 'doc';
				tmp = str[1].split(this.VALUES_SEP);
				r.cid = tmp[1];
				tmp = str[2].split(this.VALUES_SEP);
				r.id = tmp[1];
				r.p = str[3];
				break;
			
			// url: {SECTION}=section_{SID}={P} 
			//		{SECTION}=category_{CID}=doc_{ID}
			//		{SECTION}=category_{CID}={P} 
			//		{SECTION}=search_{Q}={P}
			
			case 3:
				tmp = str[1].split(this.VALUES_SEP);
				if (tmp[0] == 'section')
				{
					r.action = 'section';
					r.sid = tmp[1];
					r.p = str[2];
				}
				else if (tmp[0] == 'category')
				{
					r.cid = tmp[1];
					if (str[2].indexOf(this.VALUES_SEP) > -1)
					{
						r.action = 'doc';
						tmp = str[2].split(this.VALUES_SEP);
						r.id = tmp[1];
					}
					else
					{
						r.action = 'category';
						r.p = str[2];
					}
				}
				else if (tmp[0] == 'search')
				{
					r.action = 'search';
					//tmp = str[1].split(this.VALUES_SEP);
					r.q = tmp[1];
					r.p = str[2];
				}
				else
				{
					alert('ERROR: fatal error parse params');
					return null;
				}
				
				break;
			
			// url: {SECTION}=docurl_{DOCURL} 
			//		{SECTION}=section_{SID} 
			//		{SECTION}=category_{CID} 
			case 2:
				tmp = str[1].split(this.VALUES_SEP);
				r.action = tmp[0];
				if (tmp[0] == 'docurl')
					r.docurl = tmp[1];
				else if (tmp[0] == 'section')
					r.sid = tmp[1];
				else if (tmp[0] == 'category')
					r.cid = tmp[1];
				
				break;
			
			default: alert('ERROR: invalid params'); r = null;
		}
	}
	else
	{
		alert('ERROR: invalid params string');
		return null;
	}
	
	//alert(r);
	return r;
}

AjaxApp.prototype.focusTo = function(s)
{
	if (!this.isOpera && this.request.p <= 1)
	{
		//var top = $('#block-'+s).offset().top - 60;
		var top;
		switch (s)
		{
			case 'school': top = 0; break;
			case 'agenda': top = 210; break;
			case 'news': top = 420; break;
			case 'gallery': top = 630; break;
		}
		//dbg('top: '+top);
		//$("html,body").animate({scrollTop: top}, 1200);
		$("html,body").animate({scrollTop: top}, 500);
		
		/*
			school = 0
			agenda = 210
			news = 420
			gallery = 630
		*/
	}
}

/* -------------------------------------------------------
 FUNCTIONS
*/

function parse_href(jo)
{
	var id = '';
	var href = jo.attr('href');
	//alert(href.substr(1));
	
	if (href.substr(0, 1) != '/')
	{
		href = href.replace(ajaxapp.settings.baseurl, '');
		jo.attr('href', href);
		//alert(href);
	}
	
	var arr = href.substr(1).split('/');
	id = arr[0];
	
	return [id, 'docurl_'+href];
}

function parse_date(jo)
{
	var dt = jo.attr('href').replace(ajaxapp.settings.baseurl, '').replace('/search/date/', '');
	
	var id = '';
	
	jo.parents('div.block').each(function (){ 
		if ($(this).attr('id').indexOf('block-') > -1)
			id = $(this).attr('id').replace('block-', '');
		});
	
	return [id, 'dt='+dt];
}

// для постраничной навигации
function back_event(section, page)
{
	//alert(section+':'+page);
	$('#block-'+section+' .pagenavigation.pp'+page+' .back').click(function (){
		//alert('event for page# '+page);
		$('#block-'+section+' .pp'+page).remove();
		$('#block-'+section+' .index.page'+page).slideUp({duration: dUp});
		$('#block-'+section+' .index.page'+page).remove();
		$('#block-'+section+' .pp'+(page-1)).show();
	});
	
	// ajaxapp.back();
}

function a_ajax_event()
{
	/* обработка ссылок класса ajax в контенте документа */
	$('.block-body a.ajax').each( function(){
		//var params = parse_href($(this));
		//$(this).attr('rel', params.join('='));
		var href = $(this).attr('href').split('#');
		$(this).attr('rel', href[1]);
	});
	
	
	/*$('.block-body a.date').each( function(){
		var params = parse_date($(this));
		//$(this).attr('rel', params.join('/'));
		$(this).attr('rel', params.join('='));
	});*/
}

function a_event()
{
	a_ajax_event();	
	
	$('.block-body a:not(.noaddress)').address( function (){
		//alert($(this));
		if ($(this).attr('rel'))
		{
			if (!ajaxapp.isRun())
			{
				$.address.value($(this).attr('rel').replace('address:',''));
				$.address.update();
			}
		}
		else
		{
			//alert('ERROR! mistake addresses link');
			var href = $(this).attr('href');
			
			if ( href.substr(0, 1) == '#')
				return;
				
			//alert('external link:' + $(this).attr('href'));
			
			//return false;
			
			$.address.value($(this).attr('href'));
			$.address.update();
			return true;
		}
	})

}

/*---------------------------
 * INIT
*/

$.address.init(function(event) {
}).change(function(e) {
	var href = e.value.substr(1);
	
	//alert(e.value);
	//alert(href);
	
	if (href.substr(0, 4) == 'http')
	{
		// TODO: open in new window
		document.location = href;
		//alert('change: '+ href.substr(0, 4));
		return true;
	}
	
	if (!ajaxapp.isRun())
	{
		//alert('change '+ e.value);
		ajaxapp.cur_href = href;
		dbg('href = '+href);
		
		$('.block > .nav a').removeClass('active');
		var rel = 'address:'+e.value.substr(1);
		var tmp = e.value.substr(1).split( ajaxapp.parser.VARS_SEP );
		var link_s = tmp[0];
		
		$('.block > .nav a').each(function(){
			//alert($(this).attr('rel'));
			//alert(rel.indexOf($(this).attr('rel')));
			//alert(rel);
			
			// выделение категории 
			if (rel.indexOf($(this).attr('rel')) != -1 && rel != 'address:' && $(this).attr('rel')!='')
			{
				var s;
				$(this).parents('div.block').each(function (){ 
					if ($(this).attr('id').indexOf('block-') > -1)
						s = $(this).attr('id').replace('block-', '');
					});
				
				//alert(s);
				// если ссылка ссылается на док внутри секции
				if (link_s == s)
					$(this).addClass('active');
			}
			//if ($(this).attr('rel') == rel && $(this).attr('rel') != '')
				
		});
		
		//alert();
		
	}
	
	//alert(href);
	
	var result;
	//result = (e.value != '/' && !ajaxapp.isRun())? ajaxapp.run( parse_params( href ) ) : false;
	result = (e.value != '/' && !ajaxapp.isRun())? ajaxapp.run( href ) : false;
	ajaxapp.prev_href = href;
	return result;
});

var debug = 0;

var cfg = new Settings();
cfg.setBaseUrl('http://photoschool.by');
cfg.setAjaxTimeout(6000);
cfg.setHtmlPreloader('<div class="loading"></div>');

//var prs = new Parser('=', '_');

var ajaxapp = new AjaxApp(cfg);
//ajaxapp.setParser( parser);
ajaxapp.setParser( new Parser('=', '_') );

$(document).ready( function()
{
	ajaxapp.closeAll();
	ajaxapp.checkOpera();
	
	// установка нужно ли закрывать секцию
	$('.block h2 a').click( function(){
		var s;
		$(this).parents('div.block').each(function (){ 
		if ($(this).attr('id').indexOf('block-') > -1)
			s = $(this).attr('id').replace('block-', '');
		});
		
		// click по открытой секции - значит надо ее закрыть
		if (ajaxapp.current_open == s) 
			ajaxapp.setSectionClick(s);
		
		
		//alert(s);
		
		/*if (ajaxapp.request.section == ajaxapp.current_open)
		{
			this.closeSection(this.current_open);
			this.current_open = '';
			return;
		}*/
	});

	
	
	$('.block h2 > a').address( function(){
		if ($(this).attr('rel'))
		{
			if (!ajaxapp.isRun())//ajax_send == 0 )
			{
				//alert('section: '+ajaxapp.request.section);
				//alert('current: '+ajaxapp.current_open);
				//return false;
				$.address.value($(this).attr('rel').replace('address:', ''));
				$.address.update();
			}
		}
		else // переход по ссылке ?!
		{
			$.address.value($(this).attr('href'));
			return true;
		}
	});
	
	
	$('.block > .nav a.noaddress').click( function() { alert('click'); });
	$('.block > .nav a:not(.noaddress)').address( function(){
		if ($(this).attr('rel'))
		{
			//if (ajax_send == 0 )
			if (!ajaxapp.isRun())
			{
				$.address.value($(this).attr('rel').replace('address:',''));
				$.address.update();
			}
		}
		else
		{
			$.address.value($(this).attr('href'));
			return true;
		}
	});
	
	/*$('.block > .nav a').click( function(){
		alert($(this));
		$('.block > .nav a').removeClass('active');
		$(this).addClass('active');
	});*/
	
	// добавляем все сисимена секций
	$('.block h2 a').each( function (){
		ajaxapp.addSection( $(this).parent().parent().attr('id').replace('block-', '') );
	});
	
	// ивент на поиск
	$('#frmSearch').submit(function (){
		//alert('submit');
		var r = new Request();
		r.action = 'search';
		r.q = $('#frmSearch input[name=q]').val();
		r.lng = ajaxapp.lng;
		//ajaxapp.run([null, 'search', $('#frmSearch input[name=q]').val()]);
		ajaxapp.request = r;
		ajaxapp.run('');
		//i = $(this).find('input [name=q]');
		//alert(i.val());
		return false;
	});
	
	$('#btn_search').click( function (){
		//alert('click');
		$('#frmSearch').submit();
	})
});

function scrollTo(top)
{
	$("html,body").animate({scrollTop: top}, 500);
}

function dbg(str)
{
	if (debug == 1) console.log(str);
}
