var iPage = 0;
var iLimit = 50;
var b24h = false;
var aCurrenciesSelectedIn = [];	//	Выбранные валюты приема
var aCurrenciesSelectedOut = [];	//	Выбранные валюты выдачи
var aOperationsSelected = [];	//	Выбранные операции
var iMetroSelected;
var showOnlineOnly = true;

var elements_cache = {};
function g_element (name) {
	if (typeof elements_cache[name] == 'undefined') {
		elements_cache[name] = $(name);
	}
	return elements_cache[name];
}


$(document).ready(function() {
	//$('h1#docTitle').html();
	var cId = g_element("#page_title_atm").length > 0 && g_element("#page_title_atm").attr("cityid") ? g_element("#page_title_atm").attr("cityid") : (typeof cityId == 'number' ? cityId : '');
	if (!/\/atm\/$/.test(document.location.pathname)) {
	$.getJSON(
		'/_/ajax/_get_city_name.html',
		{cityId:cId},
		function (data) {
			if (data.city_dative.length || data.city_genitive.length || data.city_name.length) {
				if (data.city_dative.length) {
					g_element('h1#docTitle').html(data.atm_name_dative);
				} else {
					if (data.city_genitive.length) {
						g_element('h1#docTitle').html(data.atm_name_genitive);
					} else {
						g_element('h1#docTitle').html(data.atm_name);
					}
				}
			} else {
				if (g_element("#page_title_atm").length > 0) {
					g_element('h1#docTitle').html($("#page_title_atm").html());
				}
			}
		}
	);
	
	var html = '<td class="helpful-interactives-icon popup">' +
		'<a target="_blank" href="'+document.location.href+'printable/"><img src="/f/1/global/i-printer-big.gif" alt=""/></a></td>'+
		'<td class="helpful-interactives-link popup">'+
		'<a target="_blank" href="'+document.location.href+'printable/">&#1042;&#1077;&#1088;&#1089;&#1080;&#1103; <nobr>&#1076;&#1083;&#1103; &#1087;&#1077;&#1095;&#1072;&#1090;&#1080;</nobr></a></td>';
	$("#helpfulInteractivesNew table tr").append(html);
	
	}
	$("#region-switch option").each(function(){$(this).attr("value", $(this).attr("value").replace(/^\/([^\/]+)\/atm\/([^\/]+)\/$/, '/$1/atm/$1/').replace(/^\/atm\/[^\/]+\/$/, '/atm/moscow/'))});
	
	$('#bookmark-list').click(function() {
		showListAtm();
	});
	$('#bookmark-map').click(function() {
		showMetroMap();
	});
	
	// Парсим адресную страку, для проставления фильтров
	initFilters();

	//	Если мы находимся на странице списка отделений
	if($('#metro-map').length){
		$('#atms-list').hide();
	}

	$('#FilterInner div.currency a').click(function() {
		$(this.parentNode.parentNode).toggleClass('selected');
		getSelectedCurrencies();
		filterPoints();
		return false;
	});
	$('#FilterInner div.operation a').click(function() {
		$(this.parentNode.parentNode).toggleClass('selected');
		getSelectedOperations();
		filterPoints();
		return false;
	});
	$('#24h a').click(function() {
		var a = $(this.parentNode.parentNode);
		a.toggleClass('selected');
		if(a.hasClass('selected'))
			b24h = true;
		else
			b24h = false;
		filterPoints();
		return false;
	});
	$('#All a').click(function() {
		clearAllFilters();
		filterPoints();
		return false;
	});
	$('#metro-map div.metro a').click(function() {
		var iMetro = $(this.parentNode).attr('id');
		iMetroSelected = iMetro.substring(6,iMetro.length);

		filterPoints();
		showListAtm();
		return false;
	});
	
	$("#is-offlined").bind($.browser.msie ? 'propertychange': 'change', filterByOnline);//change(filterByOnline);
	
	if (cId == 55 || cId == 41) hideForOmsk();
	sortClick();
	initAtmPayServices();
	initAllAtmParServices();
});

function sortClick () {
	$("#tb-atms-list span.sort-label-name").click();
}

function filterByOnline () {
	showOnlineOnly = $("#is-offlined").attr("checked");
	filterPoints();
}

function hideForOmsk () {
	$("#operation-virtual-card").hide();
}

function initFilters(){
	var operation = getParam('operation');
	if (operation != '')
		$('#FilterInner table #operation-selector #' + operation).toggleClass('selected');
	getSelectedOperations();
	filterPoints();
}

function showMetroMap(){
	iMetroSelected = 0;
	filterPoints();
	$('#Bookmarks a').removeClass('selected');
	$('#bookmark-map').addClass('selected');
	$('#metro-map').show();
	$('#atms-list').hide();
}

function showListAtm(){
	$('#Bookmarks a').removeClass('selected');
	$('#bookmark-list').addClass('selected');
	$('#metro-map').hide();
	$('#atms-list').show();
}

//	Скрываем неактивные станции метро
function filterMetroMap(){
	var metro;
	$('#metro-map div').hide();

	$('#tb-atms-list tr:visible').each(function(index) {
		metro = $(this).attr('metro');
		$('#metro-' + metro).show();
	});
}

function clearAllFilters(){
	b24h = false;
	aCurrenciesSelectedIn = [];
	aCurrenciesSelectedOut = [];
	aOperationsSelected = [];

	g_element('#24h').removeClass('selected');
	g_element('#currency-selector div').removeClass('selected');
	g_element('#operation-selector div').removeClass('selected');
}

function getSelectedCurrencies(){
	aCurrenciesSelectedIn = [];
	aCurrenciesSelectedOut = [];

	g_element('#FilterInner #currency-out-selector .currency').each(function() {
		if($(this).hasClass('selected')){
			var iId = $(this).attr('id');
			iId = iId.substring(4,5);
			aCurrenciesSelectedOut.push(iId * 1);
		}
	});
	g_element('#FilterInner #currency-in-selector .currency').each(function() {
		if($(this).hasClass('selected')){
			var iId = $(this).attr('id');
			iId = iId.substring(4,5);
			aCurrenciesSelectedIn.push(iId * 1);
		}
	});
}

function getSelectedOperations(){
	aOperationsSelected = new Array();

	g_element('#FilterInner .operation').each(function() {
		if($(this).hasClass('selected')){
			var iId = $(this).attr('id');
			iId = iId.substring(10,iId.length);
			aOperationsSelected.push(iId);
		}
	});
}

//	Показываем или гасим пункт "Все виды" в форме поиска
function toggleSelectAll(){
	if($("#is-alfa-atm,#is-not-alfa-atm").filter('.selected').length + aCurrenciesSelectedIn.length + aCurrenciesSelectedOut.length + aOperationsSelected.length + $("#operation-selector div.pay-serv-selected").length == 0 && !(g_element('#24h').hasClass('selected'))){
		g_element('#All').addClass('selected');
	}else{
		g_element('#All').removeClass('selected');
	}
}

function filterPoints(){
	var bShow;
	toggleSelectAll();	

	var pay_services = [];
	$("#operation-selector div.pay-serv-selected span a").each(function(){
		pay_services[pay_services.length] = $(this).attr('service');
	});
	
	var _ext = {
		alfa: $("#is-alfa-atm").hasClass('selected'),
		notAlfa: $("#is-not-alfa-atm").hasClass('selected')
	}
	
	g_element('#atms-list tr').each(function() {
		bShow = true;
		var $this = $(this);

		if (pay_services.length > 0) {
			if ($this.attr('services')) {
				var this_serv = $this.attr('services').toString();
				for (var i = 0; i < pay_services.length && bShow; i++) {
					var _re = new RegExp((";"+pay_services[i]+";|^"+pay_services[i]+";").replace(/\+/g, "\\\+"));
					if (!_re.test(this_serv)) {
						bShow = false;
					}
				}
			} else {
				bShow = false;
			}
		}
		
		
		for (var i=0; i < aCurrenciesSelectedIn.length; i++) {
			if(!($this.attr('currency_in') & aCurrenciesSelectedIn[i])){
				bShow = false;
			}
		};
		for (var i=0; i < aCurrenciesSelectedOut.length; i++) {
			if(!($this.attr('currency_out') & aCurrenciesSelectedOut[i])){
				bShow = false;
			}
		};
		for (var i=0; i < aOperationsSelected.length; i++) {
			if(aOperationsSelected[i] == 'virtual-card'){
				if($this.attr('is_virtual_card') == '0'){
					bShow = false;
				}
			}else{
				if(aOperationsSelected[i] == 'transfer'){
					if($this.attr('is_transfer') == '0'){
						bShow = false;
					}
				}else{
					if(aOperationsSelected[i] == 'bsk'){
						if($this.attr('is_bsk') == '0'){
							bShow = false;
						}
					}else{
						if(aOperationsSelected[i] == 'lifeline'){
							if($this.attr('is_lifeline') == '0'){
								bShow = false;
							}
						}else{
							if(!($this.attr('operation') & aOperationsSelected[i])){
								bShow = false;
							}
						}
					}
				}
			}
		};
		if(b24h && $this.attr('is24h') == '0'){
			bShow = false;
		}
		if(iMetroSelected > 0 && $this.attr('metro') != iMetroSelected){
			bShow = false;
		}
		
		//console.log($this.attr('is_online'));
		if (showOnlineOnly && ($this.attr('is_online') == 0)) {
			bShow = false;
		}
		if (_ext.alfa != _ext.notAlfa) {
			if (_ext.alfa) {
				bShow = !$this.find('div.is-external-title').length && bShow;
			} else {
				bShow = !!$this.find('div.is-external-title').length && bShow;
			}
		}

		if(bShow){
			$this.show();
		}else{
			$this.hide();
		}
	});

	filterMetroMap();
}

//	Было javascript-метод вывода точек, но он оказался крайне медленным
function fillPoints() {
	var sIcon = '';
	var sCurrencies = '';
	$('#atms-list').html('<table class="BranchList"><tbody id="tb-atms-list"></tbody></table>');
	var sCode = '';

	for (var i=0; i < aPoints.length; i++) {
		if(shouldShowPoint(aPoints[i])){
			if(aPoints[i][2] & 1 && aPoints[i][2] & 2)
				sIcon = '<img src="/_files/atm/cash-getput.gif" alt="!!!"/>';
			else if(aPoints[i][2] & 1)
				sIcon = '<img src="/_files/atm/cash-put.gif" />';
			else if(aPoints[i][2] & 2)
				sIcon = '<img src="/_files/atm/cash-get.gif" />';

			if(aPoints[i][1])
				sIcon += '<img src="/f/1/global/24h.gif" />';

			sCurrencies = getCurrencies(aPoints[i][0]);

			sCode += '<tr><td class="name"><a href="' + aPoints[i][4] + '">' + aPoints[i][5] + '</a></td><td class="address">' + aPoints[i][6] + '</td><td class="icons">' + sIcon + '</td><td class="currency">' + sCurrencies + '</td></tr>';
		}
	};
	$('#tb-atms-list').html(sCode);
}

function shouldShowPoint( aPoint ){
	return(1);
}

function getCurrencies( iCurrency ){
	var sCurrencies = '';
	if(iCurrency == 1)
		sCurrencies = 'RUR, ';
	if(iCurrency & 2)
		sCurrencies += 'USD, ';
	if(iCurrency & 4)
		sCurrencies += 'EUR, ';
	if(iCurrency & 8)
		sCurrencies += 'тэнге, ';
	if(sCurrencies.length > 0){
		sCurrencies = sCurrencies.substring(0, sCurrencies.length-2);
	}

	return sCurrencies;
}

var atmPayServices = false;
function initAtmPayServices () {
	if (typeof atm_pay_services != 'undefined' && typeof atm_pays_list != 'undefined') {
		atmPayServices = new AtmPayServices(atm_pay_services);
		atmPayServices.appendTo("#atm-service-list");
	}
}

var AtmPayServices = function(str){
	this.services = atm_pays_list;
	this.s_list = [];
	this.init = function (str) {
		var arr = str.split(';');
		for (var i = 0; i < arr.length; i++) {
			//console.log(arr[i]);
			if (typeof this.services[arr[i]] != 'undefined') {
				this.s_list.push(this.services[arr[i]]);
			}
		}
	};
	this.get_html = function () {
		if (this.s_list.length) {
			var html = '<li>'+atm_pays_list['TITLE']+'<ul>';
			for (var i = 0; i < this.s_list.length; i++) {
				html += '<li>'+this.s_list[i]+'</li>';
			}
			html += '</ul></li>';
			return html;
		} else {
			return '';
			
		}
	};
	this.appendTo = function (to) {
		$(to).append(this.get_html());
	};
	
	this.init(str);
}

var allAtmParServices = false;
function initAllAtmParServices () {
	if (typeof d_services != 'undefined' && typeof atm_pays_list != 'undefined') {
		allAtmParServices = new AllAtmParServices(d_services, filterPoints);
		allAtmParServices.after("#24h");
	}
}
var AllAtmParServices = function (str, filter) {
	this.services = {};
	this.init = function (str) {
		var arr = str.split(';');
		for (var i = 0; i < arr.length; i++) {
			if (arr[i] != '' && typeof this.services[arr[i]] == 'undefined' && atm_pays_list[arr[i]]) {
				this.services[arr[i]] = atm_pays_list[arr[i]];
			}
		}
	}
	
	this.get_html = function () {
		if (atm_pays_list_filter == null) {
			return "";
		}
		
		var table = {0:"",1:"",2:""};
		for (var column in atm_pays_list_filter) {
			for (var row in atm_pays_list_filter[column]) {
				if (this.services[row] != null) {
					table[column] += '<div class="pay-services"><span><a href="#" service="'+row+'">'+atm_pays_list_filter[column][row]+'</a></span></div>';
				}
			}
		}
		var html = "";
		for (var i = 0; i < 3; i++) {
			if (table[i] != "") {
				html += "<td>" + table[i] + "</td>";
			}
		}
		if (html == "") {
			return "";
		}
		html = '<div class="worktime pay-services"><em>&#1054;&#1087;&#1083;&#1072;&#1090;&#1072; &#1091;&#1089;&#1083;&#1091;&#1075;</em></div><table class="pay-services"><tr>' + html + "</tr></table>";
		return html;
	}
	
	this.appendTo = function (to) {
		$(to).append(this.get_html());
	};
	this.after = function (to) {
		$(to)
			.after($(this.get_html()))
			.parent()
			.find("div.pay-services span a")
			.click(this.click);
	}
	this.click = function (obj) {
		$(this.parentNode.parentNode).toggleClass('selected').toggleClass('pay-serv-selected');
		filter.call(document);
		return false;
	}
	
	this.init(str);
}
