/* General Functions for region filter */
var currentRegionSelected = false;
var globalRegionIds = new Array();
var regionFilterTitles = new Array(new Array ('Район','Районы','Любой'),new Array ('Метро','Метро','Любое'),new Array ('Все страны','Страны','Изменить'));
var selectedFilterRegions = new Array();
var regionFilterTypesMapMulti = {'город':'города','район':'районы','метро':'метро','шоссе/направление':'шоссе/направления','шоссе':'шоссе/направления','страна':'страны'};

var regionFilterArrayRegions = new Array();
var regionFilterArrayRegionsIds = new Array();
var regionFilterArrayRegionsNames = new Array();
var regionFilterArrayRegionsTree = new Array();
var regionFilterArrayTitles = new Array();
var regionFilterTabs='';
var ForeignRegionId = '1290';
var MoscowRegionId='3';
var MoscowOblRegionId='206';
var PiterRegionId='417';


var regionFilterTemplate = '\
		<div class="searchForm"><div class="filters_vkladka"><div class="b_l"><!-- //--></div><div class="b_r"><!-- //--></div><ul>#tabs#</ul></div></div>\
		<div class="contenerMap">\
			<table width="100%" border="0">\
					<tr>\
						<td class="ul_map">\
							<div class="rows" style="margin-right: 17px;">\
								#colsTitle#\
                            </div>\
                            <div class="ul_map">\
                            	#colsContent#\
                            </div>\
                            <div class="buttons">\
                            	<div class="wrapBtn">\
                            		<div class="button-style btn-c" style="width: 39px;"><i><!-- //--></i><span><input type="submit" onclick="setFilterRegion(); return false;" value="ОК" /></span></div>\
                            	</div>\
                            </div>\
                        </td>\
                        <td class="text_map">\
                        	<div class="Qseach">\
                            	<p>Быстрый поиск</p>\
                                <div class="rows">\
                                <form onsubmit="return false"><input type="text" onblur="hideQSLikedRegion();" onkeyup="getQSLikedRegions(this, event)" id="id_qsregion" autocomplete="off" style="width: 178px; margin-right: 3px;" id="" name=""/><input type="image" style="width: 18px; height: 15px; margin-top: 3px;" src="/site/pic/b_ok.gif" alt="ok" onclick="setQSFilterRegionByName(); return false" /></div></form>\
                                <div style="z-index: 10000; display: none; width: 180px;" class="textHint" id="id_likedRegions"></div>\
                            </div>\
                            #blocks#\
							<div class="buttons">\
                            </div>\
						</td>\
					</tr>\
				</table>\
			</div>';
	
var regionForeignFilterTemplate = '\
	<div class="searchForm">\
		<div class="filters_vkladka"><div class="b_l"><!-- //--></div><div class="b_r"><!-- //--></div><ul><li class="activ"><a>Списком</a></li></ul></div>\
	</div>\
	<div class="contenerMap" id="Id_country">\
		<table width="100%" border="0">\
		<tr>\
			<td class="ul_map" style="padding-left: 0px">\
				<div class="ul_map">\
					<ul class="ul_country">\
		            	#content#\
		            </ul>\
				</div>\
	        </td>\
	        <td class="text_map">\
		        <div class="Qseach">\
		        	<p>Быстрый поиск</p>\
		            <div class="rows">\
		            <form onsubmit="return false"><input type="text" onblur="hideQSLikedRegion();" onkeyup="getQSLikedRegions(this, event)" id="id_qsregion" autocomplete="off" style="width: 178px; margin-right: 3px;" id="" name=""/><input type="image" style="width: 18px; height: 15px; margin-top: 3px;" src="/site/pic/b_ok.gif" alt="ok" onclick="setQSFilterRegionByName(); return false" /></div></form>\
		            <div style="z-index: 10000; display: none; width: 180px;" class="textHint" id="id_likedRegions"></div>\
	            </div>\
	        	#blocks#\
				<div class="buttons">\
                    <input type="button" onclick="setFilterRegion(); return false;" value="Ок"  style="width:54px;"/> \
	        	</div>\
			</td>\
		</tr>\
	</table>\
    </div>';

function popupElShow(id){
	$('bodyPage').className="noselectsBodies";
	elShow('metrobg');
	elShow(id);
	$(id).style.left=((Ext.Element.get(document.body).getWidth() - Ext.Element.get(id).getWidth()) / 2)+"px";
}

function popupElHide(id){
	$('bodyPage').className="";
	elHide(id);
	elHide('metrobg');
}

function inArray(needle, array){
	var found = false, key;
	for (key in array) {
		if (typeof(array[key])=='function') continue;
		if (array[key]==needle) {
			found=true;
			break;
		}
	}
	return found;
}

function arraySearch(needle, array){
	var index = false, key;
	for (key in array) {
		if (typeof(array[key])=='function') continue;
		if (array[key]==needle) {
			index = key;
			break;
		}
	}
	return index;
}

function showFilterRegion(el){
	currentRegionSelected=el.rel;
	if (currentRegionSelected!='') {
		popupElShow('block_filter_region_loading');
		elHide('region_select_buttons');
		loadFilterRegion(currentRegionSelected);
	}
}

function loadFilterRegionPopupTemplate(name,id,callback){
	if (!$(id)){
		Ext.Ajax.request({
			url: '/ajax/filterRegiontemplate.php',
			success: function(response, options) {
				var res = Ext.decode(response.responseText);
				if (res) {
					$('externalPopups').innerHTML=res;
					popupElHide('block_filter_region_loading');
					eval(callback);
				} else {
					$('idPopupRegionLoadingContent').innerHTML="Ошибка связи.<br />Попробуйте повторить позже.";
				}
			},
			failure: function(){
				$('idPopupRegionLoadingContent').innerHTML="Ошибка связи.<br />Попробуйте повторить позже.";
			},
			params: {name: name}
		});
	} else {
		popupElHide('block_filter_region_loading');
		eval(callback);
	}
}

function loadFilterRegion(id){
	Ext.Ajax.request({
		url: '/ajax/regionsForId.php',
		success: function(response, options) {
			if ($('block_filter_region_loading').style.display=='block') {
				var res = Ext.decode(response.responseText);
				if (res && res.regions && res.regions.length>0) {
					switch (res.id) {
						case ForeignRegionId:
							prepareFilterRegionArrays(res.regions,true);
							popupElHide('block_filter_region_loading');
							printFilterRegionsForeign(res.regions,res.id);
						break;
						case MoscowRegionId:
							prepareFilterRegionArrays(res.regions,false);
							regionFilterTabs = '<li class="activ"><a>Списком</a></li><li><a href="#" onclick="metroMap.switchToMap(); return false">Картой</a></li>';
							loadFilterRegionPopupTemplate('metro.tpl','idPopupMap','metroMap.loadAndOpen()');	
						break;
						case MoscowOblRegionId:
							prepareFilterRegionArrays(res.regions,false);
							regionFilterTabs = '<li class="activ"><a>Списком</a></li><li><a href="#" onclick="moscowMapSwitchToMap(); return false">Картой</a></li>';
							loadFilterRegionPopupTemplate('moscow_map.tpl','idPopupRussiaMap','moscowMapShow()');
						break;
						default:
							prepareFilterRegionArrays(res.regions,false);
							regionFilterTabs = '<li class="activ"><a>Списком</a></li>';
							popupElHide('block_filter_region_loading');
							printFilterRegions(res.regions,res.id);
						break;
					}
				} else {
					if (!res.regions || res.regions.length<1){
						$('idPopupRegionLoadingContent').innerHTML="&nbsp;<br />Для выбранного региона нет районов.";
					} else {
						$('idPopupRegionLoadingContent').innerHTML="Ошибка связи.<br />Попробуйте повторить позже.";
					}
				}
			}
		},
		failure: function(){
			$('idPopupRegionLoadingContent').innerHTML="Ошибка связи.<br />Попробуйте повторить позже.";
		},
		params: {id: id}
	});


}

function prepareFilterRegionArrays(regions,foreign){
	regionFilterArrayRegions = new Array();
	regionFilterArrayRegionsIds = new Array();
	regionFilterArrayRegionsNames = new Array();
	regionFilterArrayRegionsTree = new Array();
	regionFilterArrayTitles = new Array();
	selectedFilterRegions =  new Array();
	regionFilterTabs='';
	if ($('sp_place_'+currentRegionSelected).value!='') {
		selectedFilterRegions = $('sp_place_'+currentRegionSelected).value.split(',');
	} else {
		selectedFilterRegions = new Array();
	}
	for (i=0; i<regions.length; i++){
		if (foreign) {
			regionFilterArrayRegionsTree.push(regions[i]);
			regionFilterArrayRegionsIds[regions[i]['id']]=regions[i];
			regionFilterArrayRegionsNames[regions[i]['title']]=regions[i];
			for (j=0;j<regions[i].regions.length;j++){
				if (!regionFilterArrayRegions[regions[i].regions[j].type]) {
					regionFilterArrayRegions[regions[i].regions[j].type] = new Array();
					regionFilterArrayTitles.push(regions[i].regions[j].type);
				}
				regionFilterArrayRegionsIds[regions[i].regions[j]['id']]=regions[i].regions[j];
				regionFilterArrayRegionsNames[regions[i].regions[j]['title']]=regions[i].regions[j];
			}
		} else {
			if (regions[i].type && regions[i].type!='null' && regions[i].type!=''){
				if (!regionFilterArrayRegions[regions[i].type]) {
					regionFilterArrayRegions[regions[i].type] = new Array();
					regionFilterArrayTitles.push(regions[i].type);
				}
				regionFilterArrayRegions[regions[i].type].push(regions[i]);
				regionFilterArrayRegionsIds[regions[i]['id']]=regions[i];
				regionFilterArrayRegionsNames[regions[i]['title']]=regions[i];
			}
		}
	}
}

function printFilterRegions(regions,id){
	var itemId, itemTitle, itemClass, template, colsTitle='', colsContent='', blocks='', title='', countCols;
	template=regionFilterTemplate;
	countCols = regionFilterArrayTitles.length;
	if (countCols>3) countCols=3;
	for (i=0;i<countCols; i++){
		colTitle=regionFilterArrayTitles[i];
		title+=(title=='')?colTitle:((i<countCols-1)?', ':' или ')+colTitle;
		colsTitle+='<div class="titleColom" '+((countCols==3)?'style="width: 32%"':'')+'><div class="wrapTit">'+colTitle+'<div class="ico-set"><!-- //--></div></div></div>';
		blocks+='<div class="checkParam" style="height:100px;"><p>Выбранные '+regionFilterTypesMapMulti[colTitle]+'</p><ul id="regionsText_'+i+'" style="height: 30%">';
		colsContent+='<ul '+((countCols==3)?'style="width: 32%"':'')+'>';
		for (j=0; j<regionFilterArrayRegions[colTitle].length; j++){
			itemId=regionFilterArrayRegions[colTitle][j]['id'];
			itemTitle=regionFilterArrayRegions[colTitle][j]['title'];
			if (inArray(itemId,selectedFilterRegions)) {
				itemClass='act';
				blocks+='<li id="regionsText_'+itemId+'"><a href="#" onclick="unSelectFilterRegionItem('+itemId+'); return false">'+itemTitle+'</a></li>';
			} else {
				itemClass='';
			}
			colsContent+='<li class="'+itemClass+'" id="selectRegion_'+itemId+'"><a href="#" onclick="switchFilterRegionItem(this); return false"><span>'+itemTitle+'</span></a></li>';
		}
		blocks+='</ul></div>';
		colsContent+='</ul>';
	}
	template=template.replace('#title#',title);
	template=template.replace('#tabs#',regionFilterTabs);
	template=template.replace('#colsTitle#',colsTitle);
	template=template.replace('#colsContent#',colsContent);
	template=template.replace('#blocks#',blocks);
	$('block_filter_region_content').innerHTML=template;
	popupElShow('block_filter_region');
}

function printFilterRegionsForeign(regions,id){
	var template, itemId, itemClass, gItem, lItem, content='', regionslength_3, block, flagActive, blocks='';
	blocks+='<div class="checkParam" style="height:100px;"><p>Выбранные '+regionFilterTypesMapMulti['страна']+'</p><ul id="regionsText_0" style="height: 30%">';
	template=regionForeignFilterTemplate;
	for (i=0; i<regionFilterArrayRegionsTree.length; i++) {
		gItem=regionFilterArrayRegionsTree[i];
		block = '';
		flagActive=false;
		regionslength_3=Math.round(gItem.regions.length/3);
		for (j=0; j<gItem.regions.length; j++){
			lItem=gItem.regions[j];
			itemId=lItem['id'];
			if (inArray(itemId,selectedFilterRegions)){
				flagActive=true;
				blocks+='<li id="regionsText_'+itemId+'"><a href="#" onclick="unSelectFilterRegionItem('+itemId+'); return false">'+lItem['title']+'</a></li>';
				itemClass='act';
			} else {
				itemClass='';
			}
			block+='<li class="'+itemClass+'" id="selectRegion_'+itemId+'" ><a href="#"  onclick="switchFilterRegionItem(this); return false"><span>'+lItem['title']+'</span></a></li>';
			if (j==regionslength_3-1 || j==regionslength_3*2-1) {
				block+='</ul><ul>';
			}
		}
		content+='<li class="'+((flagActive)?'':'no_activ')+'" id="regionsBlockOut_'+gItem['id']+'"><div class="name_country"  onclick="showHideRegionBlock('+gItem['id']+'); return false"><div class="end_musk"></div><div class="plus_minus"><a href="#"></a></div><a style="cursor: pointer"><span>'+gItem['title']+'</span></a></div> <div class="check_all"><div>(<a href="#" onclick="selectAllBlockFilterRegions('+gItem['id']+'); return false">Выбрать всё</a>)</div></div><div class="wrapUl" id="regionsBlock_'+gItem['id']+'"><ul>';
		content+=block;
		content+='</ul></div></li>';		
	}
	blocks+='</ul></div>';
	template=template.replace('#content#',content);
	template=template.replace('#blocks#',blocks);
	$('block_filter_region_content').innerHTML=template;
	popupElShow('block_filter_region');
}

function regionFilterHide(){
	popupElHide('block_filter_region');
}


function selectFilterRegionItem(id){
	var area, indexType, li;
	indexType = arraySearch(regionFilterArrayRegionsIds[id]['type'],regionFilterArrayTitles);
	selectedFilterRegions.push(id);
	$('selectRegion_'+id).className='act';
	area = $('regionsText_'+indexType);
	if (area) {
		li = document.createElement("LI");
		li.id = 'regionsText_'+id;
		area.appendChild(li);
		$('regionsText_'+id).innerHTML='<a href="#" onclick="unSelectFilterRegionItem('+id+'); return false">'+regionFilterArrayRegionsIds[id]['title']+'</a>';
	}
}

function unSelectFilterRegionItem(id){
	var area, indexId, indexType;
	indexType = arraySearch(regionFilterArrayRegionsIds[id]['type'],regionFilterArrayTitles);
	indexId = arraySearch(id,selectedFilterRegions);
	selectedFilterRegions.splice(indexId,1);
	$('selectRegion_'+id).className='';
	area = $('regionsText_'+indexType);
	if (area) {
		area.removeChild($('regionsText_'+id));
	}
}

function switchFilterRegionItem(el){
	var id;
	id = el.parentNode.id.replace('selectRegion_','');
	if (inArray(id,selectedFilterRegions)){
		unSelectFilterRegionItem(id);
                metroMap.regionUnSelect(id);
	} else {
		selectFilterRegionItem(id);
                metroMap.regionSelect(id);
	}
        if (inArray(id,metroMap.list_regions)){
                metroMap.save();
                printFilterRegions();
}
}

function clearFilterRegion(){
	while (selectedFilterRegions.length>0) {
		if (regionFilterArrayRegionsIds[selectedFilterRegions[0]]) {
			unSelectFilterRegionItem(selectedFilterRegions[0]);
		} else {
			selectedFilterRegions.splice(0,1);
		}
	}
}

function setFilterRegion(array,idRegion){
	var selectedRegions = new Array();
	if (idRegion) {
		currentRegionSelected=idRegion;
		selectedFilterRegions=array;
	} else {
		refresQuickSearch(selectedFilterRegions,currentRegionSelected);
	}
	if (selectedFilterRegions.length>0) {
		$('sp_place_'+currentRegionSelected).value=selectedFilterRegions.join(',');
		$('regionChilds_'+currentRegionSelected).innerHTML='выбрано '+selectedFilterRegions.length+' ';
		$('regionChildsLink_'+currentRegionSelected).innerHTML='<span>Изменить</span>';
	} else {
		$('sp_place_'+currentRegionSelected).value='';
		$('regionChilds_'+currentRegionSelected).innerHTML='';
		$('regionChildsLink_'+currentRegionSelected).innerHTML='<span>Выбрать</span>';
	}
	for (i=0; i<globalRegionIds.length; i++) {
		if ($('sp_place_'+globalRegionIds[i]) && $('sp_place_'+globalRegionIds[i]).value!='') {
			selectedRegions=selectedRegions.concat($('sp_place_'+globalRegionIds[i]).value.split(','));
		}
	}
	$('place').value=selectedRegions.join(',');
	regionFilterHide();
}

function selectAllBlockFilterRegions(id){
	var blockEl,liEls,el;
	blockEl = $('regionsBlock_'+id);
	if (blockEl) {
		liEls=blockEl.getElementsByTagName('LI');
		for (i=0;i<liEls.length; i++) {
			el=liEls[i];
			if (el.id.indexOf('selectRegion_')===0 && el.className!='act') {
				selectFilterRegionItem(el.id.replace('selectRegion_',''));
			}		
		}
	}

}

function showHideRegionBlock(id){
	var blockEl;
	blockEl = $('regionsBlockOut_'+id);
	if (blockEl) {
		if (blockEl.className=='no_activ'){
			blockEl.className='';
		} else {
			blockEl.className='no_activ';
		}
	}
}

function diffArrays(needle, haystack){
	var i,j, result;
	i=0;
	while (i<haystack.length){
		j=0; 
		while (j<needle.length) { 
			if (haystack[i]==needle[j]) {
				needle.splice(j,1);
				j=needle.length+1;
			} else {
				j++;
			}
		}
		if (j==needle.length+1) {
			haystack.splice(i,1);
		} else {
			i++;
		}
		if (needle.length==0) {
			return false;
		}
	}
	return true;
}

function setQuickSearch(el,idRegion){
	var ids,selectedRegions, diff;
	if (el && idRegion) {
		ids = el.rel.split(',');
		if ($('sp_place_'+idRegion).value!=''){
			selectedRegions = $('sp_place_'+idRegion).value.split(',');
		} else {
			selectedRegions = new Array();
		}
		diff = diffArrays(ids,selectedRegions);
		if (diff==false) {
			el.parentNode.className='';
			setFilterRegion(selectedRegions,idRegion);
		} else {
			el.parentNode.className='selected';
			if ($('sp_place_'+idRegion).value!=''){
				selectedRegions = $('sp_place_'+idRegion).value.split(',');
			} else {
				selectedRegions = new Array();
			}
			setFilterRegion(selectedRegions.concat(ids),idRegion);
		}
	}
}

function refresQuickSearch(array,idRegion){
	var block,el,els,qsArray,diff,resultsArray;
	if (block=$('quicksearch_block_'+idRegion)){
		els = block.getElementsByTagName('A');
		for (i=0; i<els.length; i++) {
			el=els[i];
			if (el.rel && el.rel!='') {
				qsArray=el.rel.split(',');
				resultsArray=array.slice(0);
				diff = diffArrays(qsArray,resultsArray);
				if (diff==false) {
					el.parentNode.className='selected';
				} else {
					el.parentNode.className='';
				}
			}
		}
	}
}
/*End General Functions for region filter */

/* Moscow metro map */
var metroMap = {
	lines : {
		'koltsevaya' : new Array(116, 109, 51, 115, 158, 80, 66, 134, 1739, 107, 18, 70,62),
		'filevskaya' : new Array(62, 78, 123, 177, 14, 178, 81, 155, 7, 48, 94, 1514, 1513),
		'arbatsko-pokrovskaya' : new Array(1581, 1583, 1582, 154, 97, 75, 78, 190, 119, 56, 118, 145, 192, 16, 80, 125, 11, 147, 62, 117, 1507),
		'sokolnicheskaya' : new Array(173, 183, 130, 149, 71, 66, 72, 186, 85, 113, 22, 74, 116, 179, 151, 43, 176, 133, 193),
		'kaluzhsko-rizhskaya' : new Array(93, 13, 142, 27, 37, 8, 138, 134, 156, 168, 63, 164, 109, 189, 83, 6, 132, 108, 57, 19, 67, 162, 196, 25),
		'serpuhovsko-timiryazevskaya' : new Array(9, 21, 112, 38, 121, 163, 50, 141, 95, 182, 185, 26, 128, 146, 167, 98, 99, 100, 143, 184, 194, 129, 171, 10, 29),
		'kahonovskaya' : new Array(61, 36, 60),
		'zamoskvoretskaya' : new Array(137, 39, 40, 148, 12, 49, 18, 92, 159, 160, 104, 115, 5, 65, 61, 58, 181, 111, 52, 69),
		'lyublinskaya' : new Array(1635, 1634, 166, 152, 187, 139, 73, 53, 64, 122, 42, 31, 90, 87),
		'tagansko-krasnopresnenskaya' : new Array(126, 157, 169, 191, 110, 127, 17, 170, 15, 135, 76, 63, 158, 131, 41, 161, 77, 140, 44, 131),
		'kalininskaya' : new Array( 102, 1898, 120, 188, 4, 124, 88, 164),
		'butovskaya' : new Array(175, 174, 28, 172, 32)
	},
	
	parts : {
		'uygozapadnaya' : new Array(193, 133, 176, 43, 151, 179),
		'bitzevskiy_park' : new Array(25, 196, 162, 67, 19, 57, 108, 132, 6, 83, 189),
		'bulvar_dm_donskogo' : new Array(29, 10, 171, 129, 194, 184,  143, 100, 99, 98, 167),
		'kahonovskaya' : new Array(60, 36, 61),
		'krasnogvardeyskaya' : new Array(69, 52, 111, 181, 58, 61, 65, 5),
		'marino' : new Array(90, 31, 87, 42, 122, 64, 53, 73, 139),
        'marinoR' : new Array(1635, 1634),
		'vihino' : new Array(44, 140, 77, 161, 41, 131),
		'novokosino' : new Array(102, 1898,  120, 188, 4, 124),
		'szhelkovskaya' : new Array(190, 119, 56, 118, 145, 192, 16),
		'podbelskogo' : new Array(173, 183, 130, 149, 71),
		'medvedkovo' : new Array(93, 13, 142, 27, 37, 8, 138),
		'altufevo' : new Array(9, 21, 112, 38, 121, 163, 50, 141),
		'trubnaya' : new Array(166, 152),
		'rechnoy_vokzal' : new Array(137, 39, 40, 148, 12, 49),
		'planernaya' : new Array(126, 157, 169, 191, 110, 127, 17, 170),
		'mezhdunarodnaya' : new Array(94, 48),
		'mezhdunarodnaya1' : new Array(155, 81, 178, 123, 14, 177, 78),
		'mitino' : new Array(1581, 1583, 1582, 154, 75, 97, 117, 78, 1507)
	},
	
	list_regions: new Array(197,198,199,200,201,202,203,204,205),

	regions : {
		'197' : new Array(102, 1898, 120, 188, 190, 119, 56, 145, 192, 173, 183, 130, 149, 44, 118),
		'198' : new Array(62, 117, 133, 193, 75, 97, 78, 123, 177, 14, 178, 81, 155, 1507),
		'199' : new Array(137, 39, 40, 148, 12, 49, 127, 17, 121, 163),
		'200' : new Array(37, 93, 13, 142, 27, 8, 9, 21,112, 38, 50, 141),
		'201' : new Array(126, 1581, 1583, 1582, 154, 157, 169, 191, 110),
		'202' : new Array(138, 134, 152, 156, 168, 177, 63, 164, 109, 18, 92, 159, 160, 104, 115, 124, 139, 88, 16, 80, 187, 125, 11, 147, 1514, 94, 48, 1513, 71, 66, 72, 186, 85, 113, 22, 116, 179, 151, 43, 74, 7, 158, 51, 70, 107, 170, 15, 135, 76, 131, 73, 1635, 1634, 1739, 166, 95, 182, 185, 26, 128, 146),
		'203' : new Array(189, 5, 65, 61, 58, 181, 111, 52, 69, 36, 167, 98, 99, 194, 129, 171, 10),
		'204' : new Array(4, 41, 161, 77, 140, 53, 64, 122, 42, 87, 31, 90),
		'205' : new Array(83, 6, 132, 108, 57, 19, 67, 162, 196, 25, 60, 176, 100, 143, 184, 29, 28, 172, 174, 175, 32)
	},
	
	districts : {
		'197' : new Array(45,68,103,195),
		'198' : new Array(91,101,105,114,136,150,165),
		'199' : new Array(20,33,46,47,180),
		'200' : new Array(84,144),
		'201' : new Array(79,96,153),
		'202' : new Array(),
		'203' : new Array(23,24,30),
		'204' : new Array(54,59,86,89),
		'205' : new Array(34,35),
		'n_himki' : new Array('106'),
		'n_zelenograd' : new Array('55')
	},
		
	adjacent : {
		// Баррикадная - Краснопресненская
		15: new Array('70'),
		70: new Array('15'),

		// Менделеевская - Новослободская
		95: new Array('107'),
		107: new Array('95'),
		
		// Курская - Чкаловская
		80: new Array('187'),
		187: new Array('80'),
		
		// Добрынинская - Серпуховская
		51: new Array('146'),
		146: new Array('51'),
		
		// Александровский сад - Библиотека им. Ленина - Арбатская - Боровицкая
		7: new Array('11', '22', '26'),
		11: new Array('7', '22', '26'),
		22: new Array('7', '11', '26'),
		26: new Array('7', '11', '22'),
	
		// Охотный ряд - Театральная - Площадь революции
		113: new Array('125', '160'),
		125: new Array('113', '160'),
		160: new Array('113', '125'),
		
		// Чистые пруды - Срестинский бульвар - Тургеневская
		152: new Array('168', '186'),
		168: new Array('152', '186'),
		186: new Array('152', '168'),
		
		// Кузнецкий мост - Лубянка
		76: new Array('85'),
		85: new Array('76'),
		
		// Третьяковская - Новокузнецкая
		104: new Array('164'),
		164: new Array('104'),
		
		// Цветной бульвар - Трубная
		166: new Array('182'),
		182: new Array('166'),

        // Достоевская - Пл.Суворова
		1634: new Array('1739'),
		1739: new Array('1634'),
	
		// Тверская - Пушкинская - Чеховская
		135: new Array('159', '185'),
		159: new Array('135', '185'),
		185: new Array('135', '159'),
		
		// Севастопольская - Каховская
		60: new Array('143'),
		143: new Array('60'),
		
		// Бульвар Дм.Донского - Улица Старокачаловская
		29: new Array('175'),
		175: new Array('29'),
		
		// Площадь Ильича - Римская
		124: new Array('139'),
		139: new Array('124'),
		
		// Крестьянская застава - Пролетарская
		73: new Array('131'),
		131: new Array('73'),

		// Марксистская - Таганская
		88: new Array('158'),
		158: new Array('88')
	},
	
	selectedStantions : new Array(),
	selectedLines : new Array(),
	selectedRegions : new Array(),
	selectedDistricts : new Array(),
	allStantions : new Array(),
	allDistricts : new Array(),
	
/* SPECIALS METHODS */
	inArray : function(needle, array){
		var found = false, key;
		for (key in array) {
			if (typeof(array[key])=='function') continue;
			if (array[key]==needle) {
				found=true;
				break;
			}
		}
		return found;
	},
	
	arraySearch : function(needle, array){
		var index = false, key;
		for (key in array) {
			if (typeof(array[key])=='function') continue;
			if (array[key]==needle) {
				index = key;
				break;
			}
		}
		return index;
	},
	
/* GENERAL */
	init : function(){
		var key,keyIn;
		for (key in this.districts) {
			if (typeof(this.districts[key])=='function') continue;
			this.allDistricts.push(key);
			for (keyIn in this.districts[key]) {
				if (typeof(this.districts[key][keyIn])=='function') continue;
				this.allDistricts.push(this.districts[key][keyIn]);
			}
		}
		for (key in this.lines) {
			if (typeof(this.lines[key])=='function') continue;
			for (keyIn in this.lines[key]) {
				if (typeof(this.lines[key][keyIn])=='function') continue;
				this.allStantions.push(this.lines[key][keyIn]);
			}
		}
	},
	
	loadAndOpen : function(){
		var ids, key, cDialog, oPopupsOuter;
		this.reset();
		if (this.allStantions.length<10) {
			this.init();
		}
		if (currentRegionSelected==MoscowRegionId){
			ids=selectedFilterRegions;
			popupElShow('idPopupMap');			
			for (key in ids) {
				if (typeof(ids[key])=='function') continue;
				if (this.regions[ids[key]]) {
					this.regionSelect(ids[key])	
				} else if (this.inArray(ids[key],this.allDistricts)){
					this.districtSelect(ids[key]);
				} else if (this.inArray(ids[key],this.allStantions)){
					this.stantionSelect(ids[key], false, true);
				}
			}
						
		}
	
	},
	
	save : function(){
		var ids,key;
		ids = this.selectedDistricts.concat(this.selectedStantions);
		selectedFilterRegions=ids;
	},
	
	
	reset : function(){
		var key;
		if (this.selectedRegions.length>0){
			while (this.selectedRegions[0]){
				this.regionUnSelect(this.selectedRegions[0]);
			}
		}
		if (this.selectedDistricts.length>0){
			while (this.selectedDistricts[0]){
				this.districtUnSelect(this.selectedDistricts[0]);
			}
		}
		if (this.selectedStantions.length>0){
			while (this.selectedStantions[0]){
				this.stantionUnSelect(this.selectedStantions[0]);
			}
		}
	},
	
/* STANTIONS */
	isStantionSelected : function(stantion){
		return this.inArray(stantion,this.selectedStantions);
	},

	stantionSelect : function(stantion, disableReCalculate, noAdjacent){
		var key, lines=new Array(), line;
		if (!this.isStantionSelected(stantion)) {
			this.selectedStantions.push(stantion);
			this.printStantionSelect(stantion);
			if (!noAdjacent) {
				if (typeof(this.adjacent[stantion]) != 'undefined') {
					for (var i = 0; i < this.adjacent[stantion].length; ++i) {
						this.selectedStantions.push(this.adjacent[stantion][i]);
						this.printStantionSelect(this.adjacent[stantion][i]);
					}
				}
			}
			if (!disableReCalculate) {
				lines=this.getLinesByStantion(stantion);
				for (key in lines) {
					if (typeof(lines[key])=='function') continue;
					line=lines[key];
					if (line && this.isFullLineSelected(line)) {
						this.lineSelect(line,true);
					}
				}
			}
			return true;
		} else {
			return false;
		}
	},
	
	stantionUnSelect : function(stantion, disableReCalculate){
		var key, line;
		if (this.isStantionSelected(stantion)) {
			this.selectedStantions.splice(this.arraySearch(stantion,this.selectedStantions),1);
			this.printStantionUnSelect(stantion);
			if (!disableReCalculate) {
				lines=this.getLinesByStantion(stantion);
				for (key in lines) {
					if (typeof(lines[key])=='function') continue;
					line=lines[key];
					if (line && !this.isFullLineSelected(line)) {
						this.lineUnSelect(line,true);
					}
				}
			}
			return true;
		} else {
			return false;
		}
	},
	
	stantionSwitch : function(stantion){
		if (this.isStantionSelected(stantion)) {
			this.stantionUnSelect(stantion);
		} else {
			this.stantionSelect(stantion);
		}
	},
	
	isStantionOnLine : function(stantion,line){
		if (this.lines[line] && this.inArray(stantion,this.lines[line])) {
			return true;
		} else {
			return false;
		}	
	},
	
		
/* LINES */
	isLineSelected : function(line){
		return this.inArray(line,this.selectedLines);
	},

	lineSelect : function(line, disableReCalculate){
		if (!this.isLineSelected(line)) {
			this.printLineSelect(line);
			this.selectedLines.push(line);
			if (!disableReCalculate){
				this.lineStantionsSelect(line);
			}
			return true;
		} else {
			return false;
		}
	
	},
	
	lineUnSelect : function(line, disableReCalculate){
		if (this.isLineSelected(line)) {
			this.printLineUnSelect(line);
			this.selectedLines.splice(this.arraySearch(line,this.selectedLines),1);
			if (!disableReCalculate){
				this.lineStantionsUnSelect(line);
			}
			return true;
		} else {
			return false;
		}
	},
	
	lineSwitch : function(line){
		if (this.isLineSelected(line)) {
			this.lineUnSelect(line);
		} else {
			this.lineSelect(line);
		}
	},
	
	getLinesByStantion : function(stantion){
		var key, lines=false;
		for (key in this.lines){
			if (typeof(this.lines[key])=='function') continue;
			if (this.isStantionOnLine(stantion,key)){
				if (!lines) {
					lines = new Array();
				}
				lines.push(key);
			}
		}
		return lines;
	},
	
	isFullLineSelected : function(line){
		var full=false, key;
		if (this.lines[line]) {
			full=true;
			for (key in this.lines[line]){
				if (typeof(this.lines[line][key])=='function') continue;
				if (!this.isStantionSelected(this.lines[line][key])){
					full=false;
					break;
				}
			}
		}
		return full;
	},
	
	isEmptyLineSelected : function(line){
		var empty=false, key;
		if (this.lines[line]) {
			empty=true;
			for (key in this.lines[line]){
				if (typeof(this.lines[line][key])=='function') continue;
				if (this.isStantionSelected(this.lines[line][key])){
					empty=false;
					break;
				}
			}
		}
		return empty;
	},
	
	lineStantionsSelect : function(line){
		var key;
		if (this.lines[line]) {
			for (key in this.lines[line]) {
				if (typeof(this.lines[line][key])=='function') continue;
				this.stantionSelect(this.lines[line][key],true,true);
			}
		}
	},
	
	lineStantionsUnSelect : function(line){
		var key, stantion, lines, keyIn, countSelected;
		if (this.lines[line]) {
			for (key in this.lines[line]){
				if (typeof(this.lines[line][key])=='function') continue;
				stantion=this.lines[line][key];
				if (this.isStantionSelected(stantion)) {
					lines = this.getLinesByStantion(stantion);
					countSelected=0;
					for (keyIn in lines) {
						if (typeof(lines[keyIn])=='function') continue;
						if (this.isLineSelected(lines[keyIn])){
							countSelected++;
						}
					}
					if (countSelected<2) {
						this.stantionUnSelect(this.lines[line][key],true);
					}
				}
			}
		}
	},
	
/* PART OF LINES */	
	
	isFullPartSelected : function(part){
		var full=false, key;
		if (this.parts[part]) {
			full=true;
			for (key in this.parts[part]){
				if (typeof(this.parts[part][key])=='function') continue;
				if (!this.isStantionSelected(this.parts[part][key])){
					full=false;
					break;
				}
			}
		}
		return full;
	},
	
	partStantionsSelect : function(part){
		var key;
		if (this.parts[part]) {
			for (key in this.parts[part]){
				if (typeof(this.parts[part][key])=='function') continue;
				this.stantionSelect(this.parts[part][key]);
			}
		}
	},
	
	partStantionsUnSelect : function(part){
		var key;
		if (this.parts[part]) {
			for (key in this.parts[part]){
				if (typeof(this.parts[part][key])=='function') continue;
				this.stantionUnSelect(this.parts[part][key]);
			}
		}
	},
	
	partStantionsSwitch : function(part){
		if (this.isFullPartSelected(part)) {
			this.partStantionsUnSelect(part);	
		} else {
			this.partStantionsSelect(part);
		}
	},
	
	


/* REGIONS */
	isRegionSelected : function(region){
		return this.inArray(region,this.selectedRegions);
	},

	regionSelect : function(region, disableReCalculate){
		if (!this.isRegionSelected(region)) {
			this.selectedRegions.push(region);
			if (!disableReCalculate){
				this.regionStantionsSelect(region);
				this.regionDistrictsSelect(region);
			}
			return true;
		} else {
			return false;
		}
	
	},
	
	regionUnSelect : function(region, disableReCalculate){
		if (this.isRegionSelected(region)) {
			this.selectedRegions.splice(this.arraySearch(region,this.selectedRegions),1);
			if (!disableReCalculate){
				this.regionStantionsUnSelect(region);
				this.regionDistrictsUnSelect(region);
			}
			return true;
		} else {
			return false;
		}
	},
	
	regionSwitch : function(region){
		if (this.isRegionSelected(region)) {
			this.regionUnSelect(region);
		} else {
			this.regionSelect(region);
		}
	},
	
	regionStantionsSelect : function(region){
		var key;
		if (this.regions[region]) {
			for (key in this.regions[region]) {
				if (typeof(this.regions[region][key])=='function') continue;
				this.stantionSelect(this.regions[region][key]);
			}
		}
	},
	
	regionStantionsUnSelect : function(region){
		var key;
		if (this.regions[region]) {
			for (key in this.regions[region]){
				if (typeof(this.regions[region][key])=='function') continue;
				this.stantionUnSelect(this.regions[region][key]);
			}
		}
	},
	
	regionDistrictsSelect : function(region){
		var key;
		if (this.districts[region]) {
			for (key in this.districts[region]) {
				if (typeof(this.districts[region][key])=='function') continue;
				this.districtSelect(this.districts[region][key]);
			}
		}
		this.districtSelect(region);
	},
	
	regionDistrictsUnSelect : function(region){
		var key;
		if (this.districts[region]) {
			for (key in this.districts[region]){
				if (typeof(this.districts[region][key])=='function') continue;
				this.districtUnSelect(this.districts[region][key]);
			}
		}
		this.districtUnSelect(region);
	},


/* DISTRICTS */
	isDistrictSelected : function(district){
		return this.inArray(district,this.selectedDistricts);
	},

	districtSelect : function(district){
		if (!this.isDistrictSelected(district)) {
			this.printDistrictSelect(district);
			this.selectedDistricts.push(district);
			return true;
		} else {
			return false;
		}
	
	},
	
	districtUnSelect : function(district){
		if (this.isDistrictSelected(district)) {
			this.printDistrictUnSelect(district);
			this.selectedDistricts.splice(this.arraySearch(district,this.selectedDistricts),1);
			return true;
		} else {
			return false;
		}
	},
	
	districtSwitch : function(district){
		if (this.isDistrictSelected(district)) {
			this.districtUnSelect(district);
		} else {
			this.districtSelect(district);
		}
	},
	
	
/* PRINTS */

	gE : function(elementId){
		if (document.getElementById(elementId)) {
			return document.getElementById(elementId);
		} else {
			return false;
		}
	},
	
	addStantionText : function(stantion) {
		var area;
		area = this.gE('stantions_text');
		if (!this.gE('stantionText_'+stantion)) {
			area.innerHTML+='<span id="stantionText_'+stantion+'">, <a href="#" onclick="metroMap.stantionUnSelect(\''+stantion+'\'); return false;">'+this.getPrintStantionLink(stantion).alt+'</a></span>';
		}
	},
	
	removeStantionText : function(stantion) {
		var area;
		area = this.gE('stantions_text');
		if (this.gE('stantionText_'+stantion)) {
			area.removeChild(this.gE('stantionText_'+stantion));
		}
	},
	
	getPrintStantionLink : function(stantion){
		return this.gE('link_'+stantion);
	},
	
	getPrintStantionSelector : function(stantion){
		return this.gE('pointer_'+stantion);
	},
	
	printStantionSelect : function(stantion){
		var selector;
		selector = this.getPrintStantionSelector(stantion);
		if (selector && selector.style.display!='block') {
			selector.style.display='block';
		}
		this.addStantionText(stantion);
	},
	
	printStantionUnSelect : function(stantion){
		var selector;
		selector = this.getPrintStantionSelector(stantion);
		if (selector && selector.style.display=='block') {
			selector.style.display='none';
		}
		this.removeStantionText(stantion);
	},

	getPrintLineLink : function(line){
		return this.gE('slink_'+line);
	},
	
	printLineSelect : function(line){
		var link;
		link = this.getPrintLineLink(line);
		if (link && link.style.fontWeight!='bold') {
			link.style.fontWeight='bold';
		}
	},
	
	printLineUnSelect : function(line){
		var link;
		link = this.getPrintLineLink(line);
		if (link && (link.style.fontWeight=='bold' || link.style.fontWeight=='700')) {
			link.style.fontWeight='normal';
		}
	},
	
	getPrintDistrictLink : function(district){
		return this.gE('link_'+district);
	},
	
	printDistrictSelect : function(district){
		var link;
		link = this.getPrintDistrictLink(district);
		if (link && link.className!='check') {
			link.className='check';
		}
		this.addDistrictText(district);
	},
	
	printDistrictUnSelect : function(district){
		var link;
		link = this.getPrintDistrictLink(district);
		if (link && link.className=='check') {
			link.className='';
		}
		this.removeDistrictText(district);
	},
	
	addDistrictText : function(district) {
		var area;
		area = this.gE('districts_text');
		if (!this.gE('districtText_'+district)) {
			area.innerHTML+='<span id="districtText_'+district+'">, <a href="#" onclick="metroMap.districtUnSelect(\''+district+'\'); return false;">'+this.getPrintDistrictLink(district).innerHTML+'</a></span>';
		}
	},
	
	removeDistrictText : function(district) {
		var area;
		area = this.gE('districts_text');
		if (this.gE('districtText_'+district)) {
			area.removeChild(this.gE('districtText_'+district));
		}
	},
	
	switchToList : function(){
		this.save();
		popupElHide('idPopupMap');
		printFilterRegions();
	},
	
	switchToMap : function(){
		popupElHide('block_filter_region');
		this.loadAndOpen();
	}
}

function chSt(el){
	metroMap.stantionSwitch(el.id.replace('link_','').replace('pointer_',''));
}

function chL(el){
	metroMap.lineSwitch(el.id.replace('slink_','').replace('link_',''));
}

function chP(el){
	metroMap.partStantionsSwitch(el.id.replace('link_',''));
}  

function chO(el){
	metroMap.districtSwitch(el.id.replace('link_',''));
}

function chR(el){
	var id = el.id.replace('link_','');
	if (id!=202 && $('mapMenu_'+id) && $('mapMenu_'+id).className!='act' && !metroMap.isRegionSelected(id)) {
		$('mapMenu_'+id).className='act';
	}
	metroMap.regionSwitch(id);
}

function chPM(el) {
	var parent = el.parentNode;
	if (parent.className =='act') {
		parent.className="";
	} 
	else {
		parent.className="act";
	}	
}

/*End Moscow metro map */


/* Moscow region map */
function WardHide(id1,id2){
	if ($(id1) || $(id2)) {
		$(id1).style.display="none";
		$(id2).style.display="none";
	}
	
}

function WardShow(id1,id2){
	if ($(id1) || $(id2)) {
			$(id1).style.display="block";
			$(id2).style.display="block";
		}
}

function checkCity( element ) {
	var indexId, id;
	id = element.id.replace('city_','');
	if( element.checked ) {
		selectedFilterRegions.push(id);
		Ext.DomHelper.append('checkCityId', { tag: 'li', id: 'selected_' + id, children: { tag: 'a', href: '#', onclick: 'delCity("selected_' + id + '", "' + id + '"); return false;', html: element.value } } );
	} else {
		indexId = arraySearch(id,selectedFilterRegions);
		selectedFilterRegions.splice(indexId,1);
		$( 'checkCityId' ).removeChild( Ext.DomQuery.selectNode( '#selected_' + id ) );
	}
}
function checkHighway( element ) {
	var indexId, id;
	id = element.id.replace('highway_','');
	if( element.checked ) {
		selectedFilterRegions.push(id);
		Ext.DomHelper.append('checkHighwayId', {tag: 'li', id:'selected_' + id, children: {tag: 'a', href: '#', onclick: 'delHighway("selected_' + id + '", "' + id + '"); return false;',  html: element.value } } );
		if ($('alt_' + element.id)) {
			$('alt_' + element.id).style.display="block";
			$('alt_' + element.id).style.visibility="visible";
		}
	} else {
		indexId = arraySearch(id,selectedFilterRegions);
		selectedFilterRegions.splice(indexId,1);
		$('checkHighwayId').removeChild( Ext.DomQuery.selectNode('#selected_'+id));
		if ($('alt_' + element.id)){
			$('alt_' + element.id).style.display="none";
			$('alt_' + element.id).style.visibility="hidden";
		}
	}
}
function cleanCity(noClearArray){
	//checkHighwayId
	var highway = Ext.DomQuery.select( '#checkHighwayId/li' );
	for( i in highway ) {
		if( typeof highway[ i ] != "function" ) $( 'checkHighwayId' ).removeChild( highway[ i ] );
	}
	
	var city = Ext.DomQuery.select( '#checkCityId/li' );
	for( i in city ) {
		if( typeof city[ i ] != "function" ) $('checkCityId' ).removeChild( city[ i ] );
	}
	
	var checkboxes = Ext.DomQuery.select( "div.wrapPopub input[@type='checkbox']" );
	for( i in checkboxes ) {
		if( typeof checkboxes[ i ] != "function" ) {
			checkboxes[ i ].checked = false;
		}
	}
	var altPopub = Ext.DomQuery.select('div.wrapHighway div.nameHighway');
	for( i in altPopub ) {
		if( typeof altPopub[ i ] != "function") {
			altPopub[i].style.visibility="hidden";
			altPopub[i].style.display="none";
		}
	}
	if (!noClearArray) {
		selectedFilterRegions = new Array();
	}
	

}

function delCity(element, checkId){
	indexId = arraySearch(checkId,selectedFilterRegions);
	selectedFilterRegions.splice(indexId,1);
	checkId = 'city_'+checkId;
	$('checkCityId').removeChild($(element));
	$(checkId).checked = false;
}
function delHighway(element, checkId){
	indexId = arraySearch(checkId,selectedFilterRegions);
	selectedFilterRegions.splice(indexId,1);
	checkId = 'highway_'+checkId;
	$( 'checkHighwayId' ).removeChild($(element));
	$(  checkId ).checked = false;
	if ($('alt_' + checkId)) {
		$('alt_' + checkId).style.display="none";
		$('alt_' + checkId).style.visibility="hidden";
	}
}

function checkMoscowMapItem(id){
	if ($('city_'+id)) {
		$('city_'+id).checked=true;
		if (!$('selected_'+id)) {
			Ext.DomHelper.append('checkCityId', { tag: 'li', id: 'selected_' + id, children: { tag: 'a', href: '#', onclick: 'delCity("selected_' + id + '", "' + id + '"); return false;', html: regionFilterArrayRegionsIds[id]['title']} } );
		}
	} else if ($('highway_'+id)) {
		$('highway_'+id).checked=true;
		if (!$('selected_'+id)) {
			Ext.DomHelper.append('checkHighwayId', {tag: 'li', id:'selected_' + id, children: {tag: 'a', href: '#', onclick: 'delHighway("selected_' + id + '", "' + id + '"); return false;',  html: regionFilterArrayRegionsIds[id]['title']} } );
		}
		if ($('alt_highway_'+id)) {
			$('alt_highway_'+id).style.display="block";
			$('alt_highway_' + id).style.visibility="visible";
		}
	}
}

function moscowMapShow(){
	cleanCity(true);
	var i;
	for (i=0; i<selectedFilterRegions.length; i++) {
		checkMoscowMapItem(selectedFilterRegions[i]);
	}
	popupElShow('idPopupRussiaMap');
}

function moscowMapSwitchToList(){
	popupElHide('idPopupRussiaMap');
	printFilterRegions();
}

function moscowMapSwitchToMap(){
	popupElHide('block_filter_region');
	moscowMapShow();
}
/*End Moscow region map */


/* Quick search block */
var oldQSRegionName='';
var regionQSSelectActive=false;
function getQSLikedRegions(el, event){
	var newQSRegionName;
	if (el.value!='') {
		newQSRegionName=el.value;
		if (oldQSRegionName!=newQSRegionName){
			showQSRegionsByName(newQSRegionName);
			oldQSRegionName=newQSRegionName;
		} else {
			if (event) {
				if (event.charCode) {
					if (event.keyCode!=40 && event.keyCode!=13){
						return true;
					}
				}
				if (event.keyCode && event.keyCode!=40 && event.keyCode!=13){
					return true;
				}
				switch(event.keyCode){
					case 40:
						if ($('id_likedRegionSelect') && $('id_likedRegions').style.display=='block') {
							try{
								$('id_likedRegionSelect').focus();
								$('id_likedRegionSelect').selectedIndex=0;
							} catch (e){;}
						}
					break;
					case 13:
						setQSFilterRegionByName();
					break;
				}
			}
		}
	} else {
		oldQSRegionName='';
		hideQSLikedRegion();
	}
	return true;
}

function hideQSLikedRegion(){
	setTimeout('hideQSLikedRegionOnTime()',100);
}


function hideQSLikedRegionOnTime(){
	if (!regionQSSelectActive) {
		if ($('id_likedRegions').style.display=='block'){
			$('id_likedRegions').style.display='none';
		}
	}
}

function showQSRegionsByName(newStreetName){
	var newStreetNameLC, tmpArray;
	tmpArray = new Array();
	newStreetNameLC = newStreetName.toLowerCase();
	for (i in regionFilterArrayRegionsNames){
		if (i.toLowerCase().indexOf(newStreetNameLC)==0) {
			tmpArray.push(i);
		}
	}
	if (tmpArray.length>0) {
		showQSRegions(tmpArray);
	} else {
		hideQSLikedRegion();
	}
}

function showQSRegions(list){
	html='<select onclick="setQSSelectRegion(this, event)" onkeypress="setQSSelectRegion(this, event)" id="id_likedRegionSelect" size="'+((list.length>10)?10:list.length)+'" onfocus="regionQSSelectActive=true" onblur="regionQSSelectActive=false; hideQSLikedRegion()">';
	for (var i=0; i<list.length; i++) {
		html+='<option value="' +list[i] + '">'+list[i]+'</option>';
	}
	html+='</select>';
	$('id_likedRegions').innerHTML=html;
	if ($('id_likedRegions').style.display!='block'){
		$('id_likedRegions').style.display='block';
	}
}


function setQSSelectRegion(el,event){
	if (el.selectedIndex>-1){
		if (event && el.selectedIndex==0) {
			if (event.charCode) {
				if (event.keyCode==38){
					$('id_qsregion').focus();
					return false;
				}
			}
			if (event.keyCode && event.keyCode==38){
				
				$('id_qsregion').focus();
				return false;
			}
		}
		setQSMapRegion(el.options[el.selectedIndex],event);
	}
}

function setQSMapRegion(value, event){
	if (event) {
		if (event.charCode) {
			if (event.keyCode!=13){
				return false;
			}
		}
		if (event.keyCode && event.keyCode!=13){
			return false;
		}
	}
	$('id_qsregion').value=value.innerHTML;
	$('id_qsregion').focus();
	
	hideQSLikedRegion();
	oldQSRegionName=value.innerHTML;
}

function setQSFilterRegionByName(){
	var name, id;
	name=$('id_qsregion').value;
	if (name!=''){
		if (regionFilterArrayRegionsNames[name]) {
			id=regionFilterArrayRegionsNames[name]['id'];
			if (!inArray(id,selectedFilterRegions)){
				try{
					selectFilterRegionItem(id);
				} catch(e) {}
				try{
					checkMoscowMapItem(id);
				} catch(e) {}
			}
			$('id_qsregion').value='';
		}
	}
}
/* End Quick search block */

/* Quick search block for map*/
var oldQSRegionName2='';
var regionQSSelectActive2=false;
function getQSLikedRegions2(el, event){
	var newQSRegionName2;
	if (el.value!='') {
		newQSRegionName2=el.value;
		if (oldQSRegionName2!=newQSRegionName2){
			showQSRegionsByName2(newQSRegionName2);
			oldQSRegionName2=newQSRegionName2;
		} else {
			if (event) {
				if (event.charCode) {
					if (event.keyCode!=40 && event.keyCode!=13){
						return true;
					}
				}
				if (event.keyCode && event.keyCode!=40 && event.keyCode!=13){
					return true;
				}
				switch(event.keyCode){
					case 40:
						if ($('id_likedRegionSelect2') && $('id_likedRegions2').style.display=='block') {
							try{
								$('id_likedRegionSelect2').focus();
								$('id_likedRegionSelect2').selectedIndex=0;
							} catch (e){;}
						}
					break;
					case 13:
						setQSFilterRegionByName2();
					break;
				}
			}
		}
	} else {
		oldQSRegionName2='';
		hideQSLikedRegion2();
	}
	return true;
}

function hideQSLikedRegion2(){
	setTimeout('hideQSLikedRegionOnTime2()',100);
}


function hideQSLikedRegionOnTime2(){
	if (!regionQSSelectActive2) {
		if ($('id_likedRegions2').style.display=='block'){
			$('id_likedRegions2').style.display='none';
		}
	}
}

function showQSRegionsByName2(newStreetName){
	var newStreetNameLC, tmpArray;
	tmpArray = new Array();
	newStreetNameLC = newStreetName.toLowerCase();
	for (i in regionFilterArrayRegionsNames){
		if (i.toLowerCase().indexOf(newStreetNameLC)==0) {
			tmpArray.push(i);
		}
	}
	if (tmpArray.length>0) {
		showQSRegions2(tmpArray);
	} else {
		hideQSLikedRegion2();
	}
}

function showQSRegions2(list){
	html='<select onclick="setQSSelectRegion2(this, event)" onkeypress="setQSSelectRegion2(this, event)" id="id_likedRegionSelect2" size="'+((list.length>10)?10:list.length)+'" onfocus="regionQSSelectActive2=true" onblur="regionQSSelectActive2=false; hideQSLikedRegion2()">';
	for (var i=0; i<list.length; i++) {
		html+='<option value="' +list[i] + '">'+list[i]+'</option>';
	}
	html+='</select>';
	$('id_likedRegions2').innerHTML=html;
	if ($('id_likedRegions2').style.display!='block'){
		$('id_likedRegions2').style.display='block';
	}
}


function setQSSelectRegion2(el,event){
	if (el.selectedIndex>-1){
		if (event && el.selectedIndex==0) {
			if (event.charCode) {
				if (event.keyCode==38){
					$('id_qsregion2').focus();
					return false;
				}
			}
			if (event.keyCode && event.keyCode==38){
				
				$('id_qsregion2').focus();
				return false;
			}
		}
		setQSMapRegion2(el.options[el.selectedIndex],event);
	}
}

function setQSMapRegion2(value, event){
	if (event) {
		if (event.charCode) {
			if (event.keyCode!=13){
				return false;
			}
		}
		if (event.keyCode && event.keyCode!=13){
			return false;
		}
	}
	$('id_qsregion2').value=value.innerHTML;
	$('id_qsregion2').focus();
	
	hideQSLikedRegion2();
	oldQSRegionName2=value.innerHTML;
}

function setQSFilterRegionByName2(){
	var name, id;
	name=$('id_qsregion2').value;
	if (name!=''){
		if (regionFilterArrayRegionsNames[name]) {
			id=regionFilterArrayRegionsNames[name]['id'];
			if (!inArray(id,selectedFilterRegions)){
				try{
					selectFilterRegionItem(id);
				} catch(e) {}
				try{
					checkMoscowMapItem(id);
				} catch(e) {}
			}
			$('id_qsregion2').value='';
		}
	}
}
/* End Quick search block for map */
