var map,
	ccinfowin,
	noBzz = false,
	bzz = true;
	effTimes = new Array(1000),
	mainUrl = baseUrl,
	cache = new Array(),
	req = '',
	curSel = '',
	userResize = false,
	outside = false,
	cityId = 0,
	flags = new Array(),
	f_types = new Array(),
	tpScroll = 0,
	bpScroll = 0,
	curPage = 1,
	Pages = 0,
	vPerPage = 7,
	pagesSize = new Array(),
	getResultTimer = 0,
	getLResultTimer = 0,
	infoTime = 0,
	scrollAction = 0,
	infoBlock = 0,
	pCache = new Array(),
	tCache = new Array(),
	lCache = new Array(),
	tpgReturn = 0,
	loadHisData = true,
	cityStr = '',
	cityLastId = 0,
	hisWorkTimer = 0,
	curResult = '',
	working = false,
	hideSelectors = false,
	venuesMarkers = new Array(),
	venues = new Array(),
	timers = new Array(150,200);
	//is_loc = false
	
	if(isIE(6) || isIE(7))
		timers = new Array(0,0);	

	f_types['ty'] = 'type';
	f_types['pr'] = 'price';
	f_types['ds'] = 'district';
	f_types['cu'] = 'kitchen';
	f_types['mo'] = 'more';
	f_types['mon'] = 'moren';

	flags['type'] = new Array();
	flags['price'] = new Array();
	flags['district'] = new Array();
	flags['kitchen'] = new Array();
	flags['more'] = new Array();
	flags['moren'] = new Array();

function setCoords(id,pop,offset)
{
	var pos = $(id).offset();

	$(pop).css({ 
        position: 'absolute',
        zIndex: 5000,
        left: pos.left-offset, 
        top: pos.top+23
    });
}

function ajax_err()
{
	clearTimeout(getLResultTimer);
	StopAjaxSpinner();

	$("#res_zone").html('');
	$("#res_error").fadeIn(timers[1]);
}

function fcheck(pref,id)
{
	var data = document.location.hash.substr(1).split('/'),
		tmp = new Array(),
		flag = false,
		str = '',
		chb = $("#uf"+id);
		
	if(chb.hasClass('exd'))
	{
		if(chb.attr('checked'))
		{
			$("#exdc").html( (parseInt($("#exdc").html())+1) );
			if($("#exdc").html() == 1)
			{
				$("#exdl").css({width:'350px'});
				$("#exdb").css({display:'block'});
			}
		}
		else
		{
			$("#exdc").html( (parseInt($("#exdc").html())-1) );
			if($("#exdc").html() == 0)
			{
				$("#exdl").css({width:'440px'});
				$("#exdb").css({display:'none'});
			}
		}
	}

	if(chb.hasClass('mo'))
	{
		if(chb.hasClass('pv'))
		{
			if(chb.attr('checked'))
			{
				$("#mpvc").html( (parseInt($("#mpvc").html())+1) );
				if($("#mpvc").html() == 1)
				{
					$("#mpv").css({display:'block'});
				}
			}
			else
			{
				$("#mpvc").html( (parseInt($("#mpvc").html())-1) );
				if($("#mpvc").html() == 0)
				{
					$("#mpv").css({display:'none'});
				}
			}
		}

		if(chb.hasClass('dc'))
		{
			if(chb.attr('checked'))
			{
				$("#mdcc").html( (parseInt($("#mdcc").html())+1) );
				if($("#mdcc").html() == 1)
				{
					$("#mdc").css({display:'block'});
				}
			}
			else
			{
				$("#mdcc").html( (parseInt($("#mdcc").html())-1) );
				if($("#mdcc").html() == 0)
				{
					$("#mdc").css({display:'none'});
				}
			}
		}

		if(chb.hasClass('sm'))
		{
			if(chb.attr('checked'))
			{
				$("#msmc").html( (parseInt($("#msmc").html())+1) );
				if($("#msmc").html() == 1)
				{
					$("#msm").css({display:'block'});
				}
			}
			else
			{
				$("#msmc").html( (parseInt($("#msmc").html())-1) );
				if($("#msmc").html() == 0)
				{
					$("#msm").css({display:'none'});
				}
			}
		}

		if(chb.hasClass('if'))
		{
			if(chb.attr('checked'))
			{
				$("#mifc").html( (parseInt($("#mifc").html())+1) );
				if($("#mifc").html() == 1)
				{
					$("#mif").css({display:'block'});
				}
			}
			else
			{
				$("#mifc").html( (parseInt($("#mifc").html())-1) );
				if($("#mifc").html() == 0)
				{
					$("#mif").css({display:'none'});
				}
			}
		}
	}

	if(chb.hasClass('mon'))
	{
		if(chb.hasClass('rn'))
		{
			if(chb.attr('checked'))
			{
				$("#mrnc").html( (parseInt($("#mrnc").html())+1) );
				if($("#mrnc").html() == 1)
				{
					$("#mrn").css({display:'block'});
				}
			}
			else
			{
				$("#mrnc").html( (parseInt($("#mrnc").html())-1) );
				if($("#mrnc").html() == 0)
				{
					$("#mrn").css({display:'none'});
				}
			}
		}
	}

	for(i in data)
	{
		tmp = data[i].split('-');
		if(tmp[0] == pref)
		{
			data[i] = tmp[0];
			flags[f_types[pref]] = new Array();
			for(j=1;j<tmp.length;j++)
			{				
				if(tmp[j] != id)
				{
					data[i] += '-' + tmp[j];
					flags[f_types[pref]].push(tmp[j]);
				}
				else
				{
					flag = true;
				}
			}
			if(!flag)
			{
				data[i] += '-'+id;
				flags[f_types[pref]].push(id);
				flag = true;
			}
		}
		if(str != '' && data[i] != pref) str += '/';
		if(data[i] != pref)	str += data[i];
	}

	if(!flag)
	{
		str = str + '/' + pref + '-' + id;
		flags[f_types[pref]] = new Array();
		flags[f_types[pref]].push(id);
	}

	hisWorkTimer++;
	$.historyLoad(str);
	
	clearTimeout(getResultTimer);
	getResultTimer = setTimeout(function () { loadPage(1); },700);
}

function pageload(hash)
{
	//var p_ok = false;
		//is_loc = false;
	
	if((loadHisData || hisWorkTimer == 0) && hash != '')
	{
		loadHisData = true;
		var data = hash.split('/'),
			tmp = new Array();

		flags['type'] = new Array();
		flags['price'] = new Array();
		flags['district'] = new Array();
		flags['kitchen'] = new Array();
		flags['more'] = new Array();
		flags['moren'] = new Array();

		$(".add_cb").attr('checked',false);
		$("#cb_wifi_txt").css({color:'#777',fontWeight:'normal'});
		$("#cb_deliver_txt").css({color:'#777',fontWeight:'normal'});
		$("#cb_photo_txt").css({color:'#777',fontWeight:'normal'});
		$("#cb_menu_txt").css({color:'#777',fontWeight:'normal'});
		$("#outside").attr('checked',false);
		$("#only_outside").css({color:'#8996A0'});

		for(i in data)
		{
			tmp = data[i].split('-');
			if(tmp[0] == 'p')
			{
				if(tmp[1] != 'district')
					$("#"+tmp[1]).click();
				curSel = tmp[1];
				p_ok = true;
			}
			else if(tmp[0] == 'c')
			{				
				cityId = tmp[1];
				if(cityId != 2)	getLocation();
 				is_loc = true;
			}
			else if(tmp[0] == 'ty')
			{
				for(j=1;j<tmp.length;j++)
				{
					flags['type'].push(tmp[j]);
				}			
			}
			else if(tmp[0] == 'pr')
			{
				for(j=1;j<tmp.length;j++)
				{
					flags['price'].push(tmp[j]);				
				}
			}
			else if(tmp[0] == 'ds')
			{
				for(j=1;j<tmp.length;j++)
				{
					flags['district'].push(tmp[j]);				
				}			
			}
			else if(tmp[0] == 'cu')
			{
				for(j=1;j<tmp.length;j++)
				{
					flags['kitchen'].push(tmp[j]);				
				}			
			}
			else if(tmp[0] == 'mo')
			{
				for(j=1;j<tmp.length;j++)
				{
					flags['more'].push(tmp[j]);				
				}			
			}
			else if(tmp[0] == 'mon')
			{
				for(j=1;j<tmp.length;j++)
				{
					flags['moren'].push(tmp[j]);
				}
			}
			else if(tmp[0] == 'sr')
			{
				changeSort(tmp[1],$("#s"+tmp[1]));
				if(tmp[2] == 2)
				changeSort(tmp[1],$("#s"+tmp[1]));
			}
			else if(tmp[0] == 'os')
			{
				if(tmp[1] == 1)
				{
					$("#outside").click();
					$("#outside").attr('checked',true);
					$("#only_outside").css({color:'green'});
				}
			}
			else if(tmp[0] == 'wifi')
			{
				$("#cb_wifi").attr('checked',true);
				$("#cb_wifi_txt").css({color:'#60AB2B',fontWeight:'bold'});
			}
			else if(tmp[0] == 'delv')
			{
				$("#cb_deliver").attr('checked',true);
				$("#cb_deliver_txt").css({color:'#60AB2B',fontWeight:'bold'});
			}
			else if(tmp[0] == 'phto')
			{
				$("#cb_photo").attr('checked',true);
				$("#cb_photo_txt").css({color:'#60AB2B',fontWeight:'bold'});
			}
			else if(tmp[0] == 'menu')
			{
				$("#cb_menu").attr('checked',true);
				$("#cb_menu_txt").css({color:'#60AB2B',fontWeight:'bold'});
			}
		}

		if(!is_loc)
		{
			cityId = 0;
			getLocation();
		}

		loadCheckboxes(curSel);
		
		if(hideSelectors)
		{
			$("#hide_fbar").click();
		}

		//if(cityId == 0)
		//{
			//cityId = 2;
			//getLocation();
		//}
		if(cityId != 0)
		{
			if(curSel == 'district')
			{
				$("#"+curSel).click();
			}
		}

		getResult();
		loadHisData = false;
		
	}
	else
	{
		setTimeout(function () { if(hisWorkTimer > 0) hisWorkTimer--; }, 200);
	}
}

function getLocation()
{
	if(cityId == 0)	cityId = 2;

	if(isset(lCache[cityId]))
	{
		$("#city_selector").val(lCache[cityId]);
		$("#city_ind").css({backgroundPosition:'right',visibility:'visible'});
		if(curSel == 'district')
		{					
			$("#"+curSel).click();
		}
	}
	else
	{	
 		$.ajax({
 			type: "GET",
 			url: mainUrl + "ajax/catalog/food/",
 			dataType: "text",
 			data: {sel:'city',cid:cityId},
 			error: function () {
  				ajax_err();
  			},
			success: function(msg)
			{
				if(msg != '')
				{
					$("#city_selector").val(msg);
					lCache[cityId] = msg;
					$("#city_ind").css({backgroundPosition:'right',visibility:'visible'});
					if(curSel == 'district')
					{					
						$("#"+curSel).click();
					}
				}
   			}
		});
	}
	//alert(cityId);
}

function show_bzz()
{
	if(!noBzz)
		$("#bzz").fadeIn(effTimes[0]);
	else
		noBzz = false;
}

function activeExLink()
{
	var size = 300,
		id = '';

	$(".ex_lnk").unbind().click(function ()
	{
		id = $(".f-bl-bg-s").attr("id") || $(".f-bl-bg-cs").attr("id")
		switch(id)
		{
			case 'type': size=150; break;
		}

		if($("#ex_data").css('display') == 'none')
		{			
			if(!userResize && $("#flags_area").height() < size)
				$("#flags_area").css({height: size+'px'});
			$("#ex_data").slideDown(500);
		}
		else
		{
			if(!userResize)
				$("#flags_area").css({height: '120px'});
			$("#ex_data").css({display:'none'});
		}
	});
}

function getHUrl(code)
{
	var hash = document.location.hash.substr(1),
		blocks = hash.split('/'),
		url = '';

	if(hash != '')
	{
		for(i in blocks)
		{
			if(blocks[i].indexOf(code+'-') === -1)
			{
				if(url != '') url = url+'/';
				url = url+blocks[i];
			}
		}
		if(url != '') url = url+'/';
		return url;
	}
	return '';
}

function getFlagsData()
{
	var hash = document.location.hash.substr(1),
		blocks = hash.split('/'),
		tmp = '',
		arr = new Array(),
		isPage = false;

	if(hash != '')
	{
		for(i in blocks)
		{
			tmp = blocks[i].split('-');
			for(j=1;j<tmp.length;j++)
			{				
				if(tmp[0] == 'cu' || tmp[0] == 'mo')
				{
					if(!isset(arr.f)) arr.f = new Array();
					arr['f'].push(tmp[j]);
				}
				else if(tmp[0] == 'ty')
				{
					if(!isset(arr.t)) arr.t = new Array();
					arr['t'].push(tmp[j]);
				}
				else if(tmp[0] == 'pr')
				{
					if(!isset(arr.p)) arr.p = new Array();
					arr['p'].push(tmp[j]);
				}
				else if(tmp[0] == 'ds')
				{
					if(!isset(arr.d)) arr.d = new Array();
					arr['d'].push(tmp[j]);
				}
				else if(tmp[0] == 'mon')
				{
					if(!isset(arr.n)) arr.n = new Array();
					arr['n'].push(tmp[j]);
				}
				else if(tmp[0] == 'pg')
				{
					if(!isset(arr.g)) arr.g = new Array();
					arr['g'].push(tmp[j]);
					curPage = tmp[j];
					isPage = true;
				}
				else if(tmp[0] == 'sr')
				{
					if(!isset(arr.s)) arr.s = new Array();
					arr['s'].push(tmp[j]);
				}
				else if(tmp[0] == 'os')
				{
					if(!isset(arr.o)) arr.o = new Array();
					arr['o'].push(1);
				}				
				else if(tmp[0] == 'wifi')
				{
					if(!isset(arr.wf)) arr.wf = new Array();
					arr['wf'].push(1);
				}
				else if(tmp[0] == 'delv')
				{
					if(!isset(arr.dl)) arr.dl = new Array();
					arr['dl'].push(1);
				}
				else if(tmp[0] == 'phto')
				{
					if(!isset(arr.ph)) arr.ph = new Array();
					arr['ph'].push(1);
				}
				else if(tmp[0] == 'menu')
				{
					if(!isset(arr.mn)) arr.mn = new Array();
					arr['mn'].push(1);
				}
			}
		}
	}
	
	if(!isPage) curPage = 1;
	return arr;
}

function writeBottomPages()
{
	if(Pages > 1)
	{
		$("#pbbl").css({display:'block'});
		$('#pbottom').paginator({pagesTotal:Pages,pagesSpan:10,pageCurrent:curPage,baseUrl: function (page){ loadPage(page); hide_selectors(); }});
	}
	else
	{
		$("#pbbl").css({display:'none'});
	}
}

function getResult()
{
	var data = getFlagsData(),
		dt = '';
	
	if(isset(data.f))
	{
		data.f.sort();
		dt += 'f-'+data.f.join('-')+':';
	}
	if(isset(data.d))
	{
		data.d.sort();
		dt += 'd-'+data.d.join('-')+':';
	}
	if(isset(data.n))
	{
		data.n.sort();
		dt += 'n-'+data.n.join('-')+':';
	}
	if(isset(data.t))
	{
		data.t.sort();
		dt += 't-'+data.t.join('-')+':';
	}
	if(isset(data.p))
	{
		data.p.sort();
		dt += 'p-'+data.p.join('-')+':';
	}
	if(isset(data.g))
	{
		data.g.sort();
		dt += 'pg-'+data.g.join('-')+':';
	}
	if(isset(data.s))
	{
		data.s.sort();
		dt += 'sr-'+data.s.join('-')+':';
	}
	if(isset(data.o))
	{
		dt += 'os-'+data.o.join('-')+':';
	}
	if(isset(data.wf))
	{
		dt += 'wf-'+data.wf.join('-')+':';
	}
	if(isset(data.dl))
	{
		dt += 'dl-'+data.dl.join('-')+':';
	}
	if(isset(data.ph))
	{
		dt += 'ph-'+data.ph.join('-')+':';
	}
	if(isset(data.mn))
	{
		dt += 'mn-'+data.mn.join('-')+':';
	}

	try
	{
		//req_res.abort();
		//alert('System stop!');
	}
	catch(err) {}

	if(curResult == dt+'--'+cityId)
		return true;

	curResult = dt+'--'+cityId;

	if(isset(tCache[dt+'--'+cityId]))
	{
		window.scroll(0,0);
		clearTimeout(getLResultTimer);
		StopAjaxSpinner();

		$("#res_error").fadeOut(timers[1],function() { 
		//$("#h_corrector").css({height:$("#res_zone").height()+'px'});
		//$("#h_corrector").css({display:'block'});

		$("#res_zone").fadeOut(timers[1], function () {
			$("#res_zone").html(tCache[dt+'--'+cityId].output);
			$("#res_zone").fadeIn(timers[1],function () {
				writeBottomPages(); setMarkers();
			});
			//$("#h_corrector").css({display:'none'});
			initInfoBlock();
		});
		Pages = Math.ceil(tCache[dt+'--'+cityId]['t-count']/vPerPage);

		if(Pages < 2) { $("#pbbl").css({display:'none'}); }
		
		writePage();
		});
		return true;
	}

	getLResultTimer = setTimeout(function(){ StartAjaxSpinner(); }, 1000);

	$("#res_error").fadeOut(timers[1],function() { 

	req_res = $.ajax({
		type: "POST",
	 	url: mainUrl + "ajax/catalog/food/",
	 	dataType: "json",
	 	data: {fl:dt,city:cityId},
   		error: function () {
   			ajax_err();
   		},
		success: function(msg)
		{
			window.scroll(0,0);
			clearTimeout(getLResultTimer);
			StopAjaxSpinner();
			//$("#h_corrector").css({height:$("#res_zone").height()+'px'});
			//$("#h_corrector").slideDown(100);

			$("#res_zone").fadeOut(timers[1], function () {				
				$("#res_zone").html(msg.output);
				if(!loadHisData) $("#res_zone").fadeIn(timers[1], function () {
					writeBottomPages(); setMarkers();
				});
				else
				{
					$("#res_zone").css({display:'block'});
					setTimeout(function() { writeBottomPages(); setMarkers(); }, 500);
				}
				//$("#h_corrector").css({display:'none'});
				initInfoBlock();
				loadHisData = false;
				
				Pages = Math.ceil(msg['t-count']/vPerPage);
				
				if(Pages < 2) { $("#pbbl").css({display:'none'}); }
				
				tCache[dt+'--'+cityId] = new Array();
				tCache[dt+'--'+cityId].output = msg.output;
				tCache[dt+'--'+cityId]['t-count'] = msg['t-count'];
				writePage();
			});
		}});
	
	});
	noHostory = true;
}

function writePage()
{
	var str = '';

	if(Pages != 1)
	{
		if(Pages > 100) Pages = 100;

		for(i=1;i<=Pages;i++)
		{
			if(i == curPage)
			{
				str += '<div class="tpg'+i+' f-pg-ps crp1-pcl">'+i+'</div>';
			}
			
			else
			{
				str += '<div class="tpg'+i+' crp1-pcl" onclick="loadPage('+i+');hide_selectors();">'+i+'</div>';
			}
		}
	}
	else
	{
		str += '<div class="tpg1 f-pg-ps crp1-pcl" style="padding-left:19px;">1</div>';
	}
	$("#tpb-bl").html(str);
	
	for(i=1;i<=Pages;i++)
	{
		pagesSize[i] = $(".tpg"+i).outerWidth();
	}	
	
	tpScroll = bpScroll = curPage;
	$("#ftyc").click();
}

function loadPage(id)
{
	$(".crp1-pcl").removeClass('f-pg-ps');
	$(".tpg"+id).addClass('f-pg-ps');

	curPage = id;
	$("#tyc").click();	

	if(id != 1)
	{
		hisWorkTimer++;
		$.historyLoad(getHUrl('pg')+'pg-'+id);
	}

	else if (document.location.hash.indexOf('pg-') !== -1)
	{
		var url = getHUrl('pg');
		url = url.substr(0,url.length-1);
		hisWorkTimer++;
		$.historyLoad(url);
	}		

	if(!loadHisData) getResult();
}

function moreClick(id)
{
		var obj = $('#b'+id),
			plus = $('#p'+id);

		if(obj.css('display') == 'none')
		{
			if(!userResize)
				$("#flags_area").css({height: '300px'});
			obj.slideDown(timers[0]);			
			plus.css({backgroundPosition:'top'});
		}
		else
		{
			obj.slideUp(timers[0]);
			plus.css({backgroundPosition:'bottom'});
		}
}

function loadCheckboxes(pref)
{	
	var flag = false;

	if(isset(flags[pref]) && flags[pref].length > 0)
	{
		for(i=0;i<flags[pref].length;i++)
		{
			if($("#uf"+flags[pref][i]).hasClass('exd'))
			{
				$("#exdc").html( (parseInt($("#exdc").html())+1) );
				flag = true;
			}

			if($("#uf"+flags[pref][i]).hasClass('mo'))
			{
				if($("#uf"+flags[pref][i]).hasClass('pv'))
				{
					$("#mpvc").html( (parseInt($("#mpvc").html())+1) );
					$("#mpv").css({display:'block'});
					$("#b1").css({display:'block'});
					$("#p1").css({backgroundPosition:'top'});
				}

				if($("#uf"+flags[pref][i]).hasClass('dc'))
				{
					$("#mdcc").html( (parseInt($("#mdcc").html())+1) );
					$("#mdc").css({display:'block'});
					$("#b2").css({display:'block'});
					$("#p2").css({backgroundPosition:'top'});
				}

				if($("#uf"+flags[pref][i]).hasClass('sm'))
				{
					$("#msmc").html( (parseInt($("#msmc").html())+1) );
					$("#msm").css({display:'block'});
					$("#b4").css({display:'block'});
					$("#p4").css({backgroundPosition:'top'});
				}

				if($("#uf"+flags[pref][i]).hasClass('if'))
				{
					$("#mifc").html( (parseInt($("#mifc").html())+1) );
					$("#mif").css({display:'block'});
					$("#b5").css({display:'block'});
					$("#p5").css({backgroundPosition:'top'});
				}
			}

			if($("#uf"+flags[pref][i]).hasClass('mon'))
			{
				if($("#uf"+flags[pref][i]).hasClass('rn'))
				{
					$("#mrnc").html( (parseInt($("#mrnc").html())+1) );
					$("#mrn").css({display:'block'});
					$("#b3").css({display:'block'});
					$("#p3").css({backgroundPosition:'top'});
				}
			}

			$("#uf"+flags[pref][i]).attr('checked',true);
			$("#tx"+flags[pref][i]).css({color:'#000'});
			
			if(pref == 'price' && flags[pref][i] == 111)
			{
				$("#noprice").attr('checked',false);
				$("#tx"+flags[pref][i]).css({color:'#777'});
			}
		}
		if(flag)
		{
			$("#exdl").css({width:'350px'});
			$("#exdb").css({display:'block'});
			$("#ex_ln").click();			
		}
	}

	if(pref == 'more')
	{
		loadCheckboxes('moren');
	}
}

function changeSort(id,obj)
{
	$(".f-b-s-1").removeClass('f-b-s-1s');

	if($("#si"+id).hasClass('f-b-s-1s1'))
	{
		$(".f-b-s-1s").removeClass('f-b-s-1s').addClass('f-b-s-1n');;
		$(".f-b-s-1s1").removeClass('f-b-s-1s1').addClass('f-b-s-1n');
		$("#si"+id).removeClass('f-b-s-1n').removeClass('f-b-s-1s1').addClass('f-b-s-1n');

		if(!loadHisData)
		{
			var url = getHUrl('sr');
			url = url.substr(0,url.length-1);
			hisWorkTimer++;
			$.historyLoad(url);
		}
	}
	else if($("#si"+id).hasClass('f-b-s-1s'))
	{
		$("#si"+id).removeClass('f-b-s-1s').addClass('f-b-s-1s1');
		if(!loadHisData)
		{
			hisWorkTimer++;
			$.historyLoad(getHUrl('sr')+'sr-'+id+'-2');
		}
		$(obj).addClass('f-b-s-1s');
	}
	else
	{
		$(".f-b-s-1s").removeClass('f-b-s-1s').addClass('f-b-s-1n');
		$(".f-b-s-1s1").removeClass('f-b-s-1s1').addClass('f-b-s-1n');
		$("#si"+id).removeClass('f-b-s-1n').removeClass('f-b-s-1s1').addClass('f-b-s-1s');
		if(!loadHisData)
		{
			hisWorkTimer++;
			$.historyLoad(getHUrl('sr')+'sr-'+id+'-1');
		}
		$(obj).addClass('f-b-s-1s');
	}	
	if(!loadHisData) loadPage(1);
}

function initInfoBlock()
{
	loadInfoBlock('.rr-t-i');
	loadInfoBlock('.rr-t-p');
	loadInfoBlock('.rr-t-v');
	loadInfoBlock('.rr-t-3');
	loadInfoBlock('.rr-t-c');
	loadInfoBlock('.rr-t-m');
	loadInfoBlock('.rr-t-d');
	loadInfoBlock('.rr-t-e');
}

function loadInfoBlock(id)
{
	$(id).mouseover(function() {
		infoBlock = this;
		clearTimeout(infoTime);		
		infoTime = setTimeout(function() {
		switch(id)
		{
			case '.rr-t-i': $("#info-bl-txt").html('общая информация'); break;
			case '.rr-t-p': $("#info-bl-txt").html('фотогалерея'); break;
			case '.rr-t-v': $("#info-bl-txt").html('видео'); break;
			case '.rr-t-3': $("#info-bl-txt").html('виртуальные туры'); break;
			case '.rr-t-m': $("#info-bl-txt").html('подробное меню'); break;
			case '.rr-t-e': $("#info-bl-txt").html('события'); break;
			case '.rr-t-d': $("#info-bl-txt").html('скидки'); break;
		}
		setCoords(infoBlock,"#info-block",62);

		if(effects)
			$("#info-block").fadeIn(timers[1]);
		else
			$("#info-block").css({display:"block"});
		}, 200);

	}).mouseout(function() {
			clearTimeout(infoTime);
			$("#info-block").css({display:"none"});
	});
}

function hide_selectors()
{
	if($("#flags_area").css("display") != 'none')
	{
		$("#flags_area").css({display:'none'});
		$("#hide_fbar").html('показать');
		$("#flags_area").resizable('disable');
	}
	hideSelectors = true;
}

$(document).ready(function () {

	//Prepare to WORK!

	//$("#flags_data").html('');
	//$("#res_zone").html('');
	
	$("#map-block").css({display:'block'});

	var ankToRem = $(".arem");

	for(var i=0;i<ankToRem.length;i++)
	{
		tmp = $(ankToRem[i]).html();
		$(ankToRem[i]).replaceWith(tmp);
	}
	//$(".f-bl-bg").removeClass('f-bl-bg-s f-bl-bg-cs');
	
	tmp = $("#findcity").html();
	$("#findcity").replaceWith(tmp);	
	
	//Now we are READY!
	
	$(".add_cb").click(function() {
		if(this.checked)
		{
			$("#"+this.id+"_txt").css({color:'#60AB2B',fontWeight:'bold'});
		}
		else
		{
			$("#"+this.id+"_txt").css({color:'#777',fontWeight:'normal'});
		}
		this.blur();
	});
	
	$("#sprice").click(function() {
		changeSort('price',this);
	});

	$("#srank").click(function() {
		changeSort('rank',this);
	});

	$("#salph").click(function() {
		changeSort('alph',this);
	});

	$("#tpr").click(function() {
		clearTimeout(scrollAction);
		if(tpScroll < Pages)
		{
			var summ = 0;
			tpScroll++;

			if(tpScroll < 3)
				tpScroll++;

			for(i=2;i<tpScroll;i++)
			{
				summ += pagesSize[i];
			}
			if(tpScroll > 9)
				summ += 3;
			if(tpScroll > 99)
				summ += 5;
			$("#tpb").animate({scrollLeft: summ}, 100);
		}
	});
	
	$("#tpr").mousedown(function() {
		clearTimeout(scrollAction);
		scrollAction = setInterval(function() { 

		if(tpScroll < Pages)
		{
			var summ = 0;
			tpScroll++;
			for(i=2;i<tpScroll;i++)
			{
				summ += pagesSize[i];
			}
			if(tpScroll > 9)
				summ += 3;
			if(tpScroll > 99)
				summ += 5;
			$("#tpb").animate({scrollLeft: summ}, 0);
		}
		
		
		}, 200);
	});
	
	$("#tpr").mouseup(function() {
		clearTimeout(scrollAction);
	});

	$("#tpl").click(function() {
		clearTimeout(scrollAction);
		if(tpScroll > 2)
		{
			var summ = 0;
			tpScroll--;
			for(i=2;i<tpScroll;i++)
			{
				summ += pagesSize[i];
			}
			if(tpScroll > 9)
				summ += 3;
			if(tpScroll > 99)
				summ += 5;
			$("#tpb").animate({scrollLeft: summ}, 100);
		}
	});

	$("#tpl").mousedown(function() {
		clearTimeout(scrollAction);
		scrollAction = setInterval(function() { 
		if(tpScroll > 2)
		{
			var summ = 0;
			tpScroll--;
			for(i=2;i<tpScroll;i++)
			{
				summ += pagesSize[i];
			}
			if(tpScroll > 9)
				summ += 3;
			if(tpScroll > 99)
				summ += 5;
			$("#tpb").animate({scrollLeft: summ}, 0);
		}
		},200);
	});

	$("#tpl").mouseup(function() {
		clearTimeout(scrollAction);
	});

	/*$("#bpgl").click(function () {		
		if(bpScroll > 2)
		{
			var summ = 0;
			bpScroll--;
			for(i=2;i<bpScroll;i++)
			{
				summ += pagesSize[i];
			}
			$("#bpgs").animate({scrollLeft: summ}, 100);
		}
	});

	$("#bpgr").click(function () {
		
		if(bpScroll <= Pages)
		{
			var summ = 0;
			bpScroll++;
			for(i=2;i<bpScroll;i++)
			{
				summ += pagesSize[i];
			}
			$("#bpgs").animate({scrollLeft: summ}, 100);
		}
	});
	
	$("#bpgr").mousedown(function() {
		scrollAction = setInterval(function() { 
		if(bpScroll <= Pages)
		{
			var summ = 0;
			bpScroll++;
			for(i=2;i<bpScroll;i++)
			{
				summ += pagesSize[i];
			}
			$("#bpgs").animate({scrollLeft: summ}, 0);
		}
		},200);
	});
	
	$("#bpgr").mouseup(function() {
		clearInterval(scrollAction);
	});

	$("#bpgl").mousedown(function() {
		scrollAction = setInterval(function() { 
		if(bpScroll > 2)
		{
			var summ = 0;
			bpScroll--;
			for(i=2;i<bpScroll;i++)
			{
				summ += pagesSize[i];
			}
			$("#bpgs").animate({scrollLeft: summ}, 0);
		}
		},200);
	});
	
	$("#bpgl").mouseup(function() {
		clearInterval(scrollAction);
	});*/
	
	
	$("#ftyc").click(function() {
		clearTimeout(scrollAction);
		var summ = 0;
		tpScroll = curPage;

		for(i=2;i<curPage;i++)
		{
			summ += pagesSize[i];
		}
		if(tpScroll > 9)
			summ += 3;
		if(tpScroll > 99)
			summ += 6;
		$("#tpb").animate({scrollLeft: summ}, 100);
	});

	if($("#city_selector").length > 0)
	{

	if(navigator.userAgent.indexOf('MSIE 6') === -1)
	{
		$("#flags_area").resizable({
			minHeight: 120,
			maxHeight: 300,
			handles: { 's' : $('#tagalka') }
		});
	}
	else
	{
		$("#tagalka").css({display:'none'});
	}

	$("#flags_area").bind('resizestop', function(event, ui) {
		if($(this).height() != 120)
  			userResize = true;
  		else
  			userResize = false;
	});

	$("#outside").click(function () {
		if(outside)
		{
			$("#only_outside").css({color:'#8996a0'});
			outside = false;
			if(!loadHisData)
			{
				var hs = getHUrl('os');
				hs = hs.substr(0,hs.length-1);
				hisWorkTimer++;
				$.historyLoad(hs);
			}
		}
		else
		{
			$("#only_outside").css({color:'green'});
			outside = true;
			if(!loadHisData)
			{
				hisWorkTimer++;
				$.historyLoad(getHUrl('os')+'os-1');
			}
		}

		clearTimeout(getResultTimer);
		getResultTimer = setTimeout(function () { loadPage(1); },700);
	});
	
	$("#cb_wifi").click(function () {
		if(!this.checked)
		{
			if(!loadHisData)
			{
				var hs = getHUrl('wifi');
				hs = hs.substr(0,hs.length-1);
				hisWorkTimer++;
				$.historyLoad(hs);
			}
		}
		else
		{
			if(!loadHisData)
			{
				hisWorkTimer++;
				$.historyLoad(getHUrl('wifi')+'wifi-1');
			}
		}
		
		clearTimeout(getResultTimer);
		getResultTimer = setTimeout(function () { loadPage(1); },700);
	});
	
	$("#cb_deliver").click(function () {
		if(!this.checked)
		{
			if(!loadHisData)
			{
				var hs = getHUrl('delv');
				hs = hs.substr(0,hs.length-1);
				hisWorkTimer++;
				$.historyLoad(hs);
			}
		}
		else
		{
			if(!loadHisData)
			{				
				hisWorkTimer++;
				$.historyLoad(getHUrl('delv')+'delv-1');
			}
		}
		clearTimeout(getResultTimer);
		getResultTimer = setTimeout(function () { loadPage(1); },700);

	});

	$("#cb_photo").click(function () {
		if(!this.checked)
		{
			if(!loadHisData)
			{
				var hs = getHUrl('phto');
				hs = hs.substr(0,hs.length-1);
				hisWorkTimer++;
				$.historyLoad(hs);
			}
		}
		else
		{
			if(!loadHisData)
			{
				hisWorkTimer++;
				$.historyLoad(getHUrl('phto')+'phto-1');
			}
		}
		clearTimeout(getResultTimer);
		getResultTimer = setTimeout(function () { loadPage(1); },700);
	});
	
	$("#cb_menu").click(function () {
		if(!this.checked)
		{
			if(!loadHisData)
			{
				var hs = getHUrl('menu');
				hs = hs.substr(0,hs.length-1);
				hisWorkTimer++;
				$.historyLoad(hs);
			}
		}
		else
		{
			if(!loadHisData)
			{
				hisWorkTimer++;
				$.historyLoad(getHUrl('menu')+'menu-1');
			}
		}
		clearTimeout(getResultTimer);
		getResultTimer = setTimeout(function () { loadPage(1); },700);
	});

	$("#city_selector").autocomplete(mainUrl+'ajax/catalog/food/?=food',
		{ max: 10, scroll: false, extraParams: { sel:'city' },
		highlight: function(str,query) {
			var reg = new RegExp("(" + query + ")", "i");
			return str.replace(reg, '<span style="font-weight:bold;color:#2a6ebb;">$1<\/span>');
		} });

	$("#city_selector").result(function(event, data, formatted) {		
		if (data)
		{			
			cityId = data[1];
			
			lCache[cityId] = data[0];
			
			hisWorkTimer++;
			$.historyLoad(getHUrl('c')+'c-'+cityId);
			$("#city_ind").css({backgroundPosition:'right',visibility:'visible'});

			cache['district'] = null;
			if(curSel == 'district')
			{
				$("#district").click();
			}
			if(!loadHisData) loadPage(1);
		}
		$("#city_selector").blur();
	});

	$("#city_selector").click(function () {
		if(cityId != 0 && this.value != '')
		{
			cityStr = this.value;
			cityLastId = cityId;
			this.value = '';
			$("#city_ind").css({visibility:'hidden'});
		}
	});

	$("#city_selector").keydown(function (e) {
		if(e.keyCode != 13)
			cityId = 0;
	});

	$("#city_selector").blur(function() {
		if(this.value == '')
		{			
			this.value = cityStr;
			cityId = cityLastId;
			$("#city_ind").css({backgroundPosition:'right'});
		}

		$("#city_ind").css({visibility:'visible'});
		
		if(cityId == 0)
		{
			this.value = cityStr;
			cityId = cityLastId;
			$("#city_ind").css({backgroundPosition:'right'});
		}

		/*if(cityId == 0)
		{
			setT
			//alert('act');
			//$("#city_ind").css({backgroundPosition:'left'});
			//cache['district'] = null;
			//if(curSel == 'district')
				//$("#district").click();
			//url = getHUrl('c');
			//url = url.substr(0,url.length-1);
			//hisWorkTimer++;
			//$.historyLoad(url);
		}*/
	});

	$(".f-bl-bg").click(function () {
		//Visual
		for(i in f_types)
		{
			if(isset(flags[f_types[i]]))
			{
				if(flags[f_types[i]].length > 0)
				{
					if(f_types[i] != 'type')
						$("#"+f_types[i]).addClass('f-bl-bg-w');
					else
						$("#"+f_types[i]).addClass('f-bl-bg-cw');
				}
				else
					$("#"+f_types[i]).removeClass('f-bl-bg-w f-bl-bg-cw');
			}
			else
			{
				$("#"+f_types[i]).removeClass('f-bl-bg-w f-bl-bg-cw');
			}
		}

		$(".f-bl-bg").removeClass('f-bl-bg-s f-bl-bg-cs');
		if(this.id != 'type')
			$(this).addClass('f-bl-bg-s');
		else
			$(this).addClass('f-bl-bg-cs');

		//Proccess
		index = this.id;
		
		if(!loadHisData)
		{
			hisWorkTimer++;
			$.historyLoad(getHUrl('p')+'p-'+index);
		}
		
		curSel = index;

		try
		{
			req.abort();
			clearTimeout(bzz);
		}
		catch(err) {}

		if($("#flags_area").css("display") == 'none')
		{
			$("#hide_fbar").click();
		}

		if(isset(cache[index]))
		{
			$("#flags_data").html(cache[index]);
			activeExLink();
			if(!loadHisData)
				loadCheckboxes(index);
			initChBox('value');
			clearTimeout(bzz);
			noBzz = true;
			$("#bzz").css({display:'none'});
		}
		else
		{
	 		bzz = setTimeout(function () { show_bzz(); },1000);
	 		noBzz = false;
	 		$("#flags_data").html('');

	 		req = $.ajax({
	 			type: "POST",
	 			url: mainUrl + "ajax/catalog/food/",
	 			dataType: "text",
	 			data: {sel:index,city:cityId},
   				error: function () {
   					ajax_err();
   				},
				success: function(msg)
				{
					if($("#bzz").css('display') == 'block')
					{
						$("#bzz").fadeOut(effTimes[0], function () {
							$("#flags_data").html(msg);
							activeExLink();
							loadCheckboxes(index);
							initChBox('value');						
						});
					}
					else
					{
						noBzz = true;
						clearTimeout(bzz);
						$("#flags_data").html(msg);
						activeExLink();
						loadCheckboxes(index);
						initChBox('value');					
					}
					cache[index] = msg;
   				}
	 		});
	 	}
	});
	
	$("#banner_hide").click(function () {
		if($("#banner_block").css('display') == 'none')
		{
			$("#banner_block").slideDown(timers[0]);
			$(this).html('скрыть');
		}
		else
		{
			$("#banner_block").slideUp(timers[0]);
			$(this).html('показать');
		}
	});

	$("#hide_fbar").click(function () {
		if($("#flags_area").css("display") == 'none')
		{
			$("#flags_area").slideDown(timers[0]);
			$(this).html('скрыть');
			$("#flags_area").resizable('enable');
			hideSelectors = false;
		}
		else
		{
			$("#flags_area").slideUp(timers[0]);
			$(this).html('показать');
			$("#flags_area").resizable('disable');
			hideSelectors = true;
		}
	});
	
	//Начало загрузки состояния преложения из истории
	//loadHisData = true;

	

	//в случае, когда история пуста
	/*if(document.location.hash == '')
	{
		//если город не установлен, ставим Киев, потом прикрутить геоАйПи
		if(cityId == 0)
		{
			cityId = 2;
			getLocation();
		}
		//Активируем закладку с типом
		$("#type").click();
		
		hisWorkTimer++;
		loadHisData = false;
		
		$.historyLoad(getHUrl('p')+'p-type');

		getResult();
	}

	//Начало работы приложения, история отключена
	*/
	
	//если город не установлен, ставим Киев, потом прикрутить геоАйПи
	if(cityId == 0)
	{
		cityId = 2;
		is_loc = true;
	}
	
	$.historyInit(pageload);

	loadHisData = false;
	
	working = true;
}

latlng = new google.maps.LatLng(50.4, 30.5);

var myOptions = {
	zoom : 12,
	disableDefaultUI : true,
	navigationControl: true,
	navigationControlOptions: {
		style: google.maps.NavigationControlStyle.SMALL,
		position: google.maps.ControlPosition.TOP_LEFT
	},
	mapTypeControl: false,
	scaleControl: false,
	scrollwheel: false,
	center : latlng,
	mapTypeId : google.maps.MapTypeId.ROADMAP
};

map = new google.maps.Map(document.getElementById("catalog-map"), myOptions);

//working with static data

setMarkers();
writePage();
writeBottomPages();
loadCheckboxes(curSel);
initInfoBlock();
activeExLink();
initChBox('value');

if(flags['type'].length > 0)
{
	var str = '';
	for(var i=0;i<flags['type'].length;i++)
	{
		if(str != '') str += '-';
		str += flags['type'][i];
	}
	hisWorkTimer++;
	$.historyLoad(getHUrl('ty')+'ty-'+str);
}

if(flags['kitchen'].length > 0)
{
	var str = '';
	for(var i=0;i<flags['kitchen'].length;i++)
	{
		if(str != '') str += '-';
		str += flags['kitchen'][i];
	}
	hisWorkTimer++;
	$.historyLoad(getHUrl('cu')+'cu-'+str);
}


//finish working with static data!


	$("#ss-div").click(function ()
	{
		$("#ss-input").val('');
		$("#sa-div").fadeIn(200);
		$("#ss-input").focus();
	});

	$("#ss-input").blur(function ()
	{
		$("#sa-div").fadeOut(200);
	});

	$("#ss-input").autocomplete(mainUrl+'ajax/catalog/food/',
		{ 
			minChars: 3,
			max: 20,
			scroll: true,
			extraParams: { sel:'search', cid:function() { return cityId; } },
			resultsClass: 'ac_results1',
			highlight: function(str,query)
						{
							var pos = str.indexOf('::');
							var query_ex = str.substr(0,pos);
							str = str.substr(pos+2);
							
							query = trim(query);
							
							if(query.indexOf(' ') !== -1)
							{
								var astr = query_ex.split(' '), reg = '';
								for(i in astr)
								{
									reg = new RegExp("(" + astr[i] + ")", "ig");
									str = str.replace(reg, '<span style="font-weight:bold;color:#f29a00;">$1<\/span>');
								}
								
								astr = query.split(' ');
								for(i in astr)
								{
									reg = new RegExp("(" + astr[i] + ")", "ig");
									str = str.replace(reg, '<span style="font-weight:bold;color:#f29a00;">$1<\/span>');
								}								
							}
							else
							{
								var reg = new RegExp("(" + query + ")", "ig");
								str = str.replace(reg, '<span style="font-weight:bold;color:#f29a00;">$1<\/span>');
								
								reg = new RegExp("(" + query_ex + ")", "ig");
								str = str.replace(reg, '<span style="font-weight:bold;color:#f29a00;">$1<\/span>');
							}
							
							str = '<span style="color:#333;"><b>'+str;
							
							reg = new RegExp("(:1:)", "ig");
							str = str.replace(reg, '</b></span><br><span style="font-size:10px;color:#888;">');
							
							reg = new RegExp("(:2:)", "ig");
							str = str.replace(reg, '</span>');
							
							return str;

						}						
		}
	);

	$("#ss-input").result(function(event, data, formatted) {		
		if (data)
		{
			$("#ss-input").val('');
			$("#ss-div").html('выполняется переход...');
			$("#sa-div").css({display:'none'});			
			
			document.location.href = data[1];
			return false;
		}
	});
});

function setMarkers()
{
	clearMarkers();
	while(venuesMarkers.length > 0)
	{
		tmp = venuesMarkers.shift();
		latLng = new google.maps.LatLng(tmp[0], tmp[1]);
		addMarker(latLng,tmp[2],tmp[3],tmp[4]);		
	}
	showAll();
}

function clearMarkers()
{	
	while(venues.length > 0)
	{
		tmp = venues.shift();
		tmp.setMap(null);
	}
}

function showAll()
{
	if(venues.length > 0)
	for(var i=0;i<venues.length;i++)
	{
		if(i == 0)
			bounds = new google.maps.LatLngBounds(venues[i].getPosition(),venues[i].getPosition());
		else
			bounds.extend(venues[i].getPosition());
	}
	map.fitBounds(bounds);
	//alert(bounds);
}

function addMarker(latLng,name,addr,url) {
	var klizma = 'http://static.city-compass.com/imgs/fc/map-vm.png';
	var options={
			position : latLng,
			map : map,
			draggable : false,
			icon: new google.maps.MarkerImage(klizma,
			      // This marker is 20 pixels wide by 32 pixels tall.
			      new google.maps.Size(36, 41),
			      // The origin for this image is 0,0.
			      new google.maps.Point(0,00),
			      // The anchor for this image is the base of the flagpole at 0,32.
			      new google.maps.Point(15, 33))
		};

	venues.push(new google.maps.Marker( options ));

	venues[venues.length-1].vname = name;
	venues[venues.length-1].vaddr = addr;
	venues[venues.length-1].vurl = url;
	
	ccinfowin = new google.maps.InfoWindow({ content: '', maxWidth: 250 });
	
	google.maps.event.addListener(venues[venues.length-1], 'click', function() {
		showMsg(this,this.vname,this.vaddr,this.vurl);
	});	
}

function showMsg(obj,name,addr,url)
{
	ccinfowin.close();
	ccinfowin.setContent('Информация о заведении:<br><div style="margin-top:10px;margin-bottom:10px;"><b><a href="'+url+'/" style="color:#000">'+name+'</a></b></div><span style="font-size:10px;color:#777">'+addr+'</span>');
	ccinfowin.open(map,obj);
}
