/* Copyright (c) 2008 Astronim* (astronim.com) */



var selector = {
	
	object : null,
	closeTop : 0,
	is_open : false,
	
	init : function (object) {

		var context = this;

		if (object) {
			this.object = object;
		}
		else {
			this.object = $('#selector');
		}
		$('li a', this.object).click(function () {

			if (false == context.is_open) {
				context.open();
			}
			else {

				var reAt = /block=(.*)/;
				var match = reAt.exec(this.href);
				
				if (match.length && match && match[1]) {
					var block = match[1];
					context.setCurrent(this, block);
					context.close();
				}

			}
			
			return false;

		});
		
		$(document).click(function () {
			context.close();
		});
		
		if ( $('.current', this.object).length ) {
			this.closeTop = $('.current', this.object).offset().top;
		}
		
	},

	open : function () {
		
		this.object.addClass('opened');
		
		var openTop = $('.current', this.object).offset().top;
		this.object.css('top', 2 * this.closeTop - openTop);
		
		this.is_open = true;
		
	},

	close : function () {

		this.object.removeClass('opened');
		this.object.css('top', this.closeTop);
		
		this.is_open = false;
		
	},

	setCurrent : function (object, block_id) {

		$('li', this.object).removeClass('current');
		$(object).parent('li').addClass('current');
		
		menu.setCurrentBlock(++block_id);

	}

}


function selectFrom(iFirstValue, iLastValue) {
	var iChoices = iLastValue - iFirstValue + 1;
	return Math.floor(Math.random() * iChoices + iFirstValue);
}

banners.getBlock = function (block_id) {
	
	var length = 0;
	var array = [];

	for(var item in this) {
		
		if (this[item].image) {
			if (null != block_id && -1 != block_id) {
				if (this[item].group == block_id) {
					array.push(this[item]);
				}
			}
			else {
				array.push(this[item]);
			}
		}
		
	}
	
	return array;
	
}




var slide = {
	
	_block_id : -1,
	_bannersCells : null,
	_timer : null,
	_finished : false,

	Init : function () {

		var context = this;
		
		this._bannersCells = $('#banner_slide .banner_item');
		
		$('#banner_slide .left').click(function () {
			context.stopAnimate();
			context.startAnimate();
			
			context.SlidePrev.call(context);
			return false;
		});
		
		$('#banner_slide .right').click(function () {
			context.stopAnimate();
			context.startAnimate();

			context.SlideNext.call(context);
			return false;
		});
		
		this.ResetSlide();
		
		this.startAnimate();

	},
	
	startAnimate : function () {
		this.__timer = setInterval(this.Automatic.bind(this), 10000);
	},
	
	stopAnimate : function () {
		clearInterval(this.__timer);
	},
	
	Automatic : function () {
		
		if (this._finished == false) {
			this.SlideNext();
		}
		else {
			this.SlidePrev();
		}
		
	},
	
	SetBlock : function (block) {
		
		this._block_id = block;
	},

	GetRandomBanners : function () {
		
		var banner_block = banners.getBlock(this._block_id);
		return banner_block;
		
	},
	
	SetBlockRand : function () {

		var banners = this.GetRandomBanners();
		var context = this;
		
		this._bannersCells.parent().fadeOut(500, function () {
			
			var items = $('a', this);
			items.each(function () {
				$(this).hide();
			});

			for (var i = 0, length = banners.length; i < length; i++) {
			
				$(items[i]).css('background-image', 'url(' +banners[i].image + ')');
				$(items[i]).css('display', 'block');
				
			}

			$(this).fadeIn(500, function () {
				context.ResetSlide();
			});
			
		});

	},
	
	_current_left : 0,
	
	GetNumBanners : function() {
		
		var length = 0;
		this._bannersCells.each(function (i) {

			if($('a', this).css('display') != 'none') {
				length++;
			}
		});

		return length;
		
	},
	
	ToggleStr : function () {

		this.ShowRightStr();
		this.ShowLeftStr();
		
		if (this._current_left == 0 || this.GetNumBanners() <= 3) {
			this.HideLeftStr();
		}
		
		if (this._current_left >= this.GetNumBanners() - 3) {
			this.HideRightStr();
		}
		
	},
	
	HideRightStr : function () {
		$('#banner_slide .right').addClass('hidden');
	},
	
	ShowRightStr : function () {
		$('#banner_slide .right').removeClass('hidden');
	},
	
	
	HideLeftStr : function () {
		$('#banner_slide .left').addClass('hidden');
	},
	
	ShowLeftStr : function () {
		$('#banner_slide .left').removeClass('hidden');
	},
	
	GetNextLeft : function() {
		
		this._current_left += 3;
		
		if (this._current_left >= this.GetNumBanners() - 3) {
			this._current_left = this.GetNumBanners() - 3;
			this._finished = true;
		}
	
		this.ToggleStr();
		
		return $('#overley').width() * this._current_left / 3;
		
	},
	
	ResetSlide : function () {
		
		$('.slide_banners').css('left', 0);
		this._current_left = 0;
		
		this.ToggleStr();
		
	},
	
	GetPrevLeft : function() {
		
		this._current_left -= 3;
		
		if (this._current_left <= 0) {
			this._current_left = 0;
			this._finished = false;
		}
		
		this.ToggleStr();
		
		return $('#overley').width() * this._current_left / 3;
		
	},
	
	SlideNext : function () {
		
		var left = this.GetNextLeft();
		$('.slide_banners').animate({left : -left}, 1000, 'swing')
		
		
	},

	SlidePrev : function () {
		var left = this.GetPrevLeft();
		$('.slide_banners').animate({left : -left}, 1000, 'swing')
	}
	
};


var offices = {
	
	Init : function () {

		this.initOblast();
		this.initUslugi();
		
		$('.reset_filter').click(function () {
			$('.all').click();
			return false;
		});
		
	},

	_makeRequest : function () {
		
		var array_request = {ajax: 1};
		
		// пїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ пїЅпїЅпїЅпїЅпїЅпїЅ пїЅпїЅ пїЅпїЅпїЅпїЅпїЅпїЅпїЅ пїЅпїЅпїЅпїЅпїЅ пїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ
		$('.catFilters a.here').each(function () {

			if ($(this).is('.all')) {
				return;
			}

			var requestGet = this.href.split('?')[1];
			var key = requestGet.split('=')[0];
			var val = requestGet.split('=')[1];
			
			if (array_request[key]) {
				
				if (typeof(array_request[key]) != 'object') {
					var temp  = array_request[key];
					array_request[key] = [];
					array_request[key][0] = temp; 
				}
				
				array_request[key].push(val);
				
			}
			else {
				array_request[key] = val;
			}
		});

		// пїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ пїЅпїЅпїЅ jquery пїЅпїЅпїЅ пїЅпїЅпїЅпїЅпїЅпїЅ пїЅ пїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ
		for(var key in array_request) {
			if (typeof(array_request[key]) == 'object') {
				var temp = array_request[key];
				delete(array_request[key]);
				array_request[key + '[]'] = temp;
			}
		}
		
		
		return array_request;
		
	},
	
	SendRequest : function () {
		
		var request = offices._makeRequest();
		var baseUrl = location.href.split('?')[0];

		$.get(baseUrl, request, function (data) {

			var html = $('#catalog', data).html();
			$('#catalog').html(html);

		})

	},

	/**
	 * пїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ пїЅпїЅпїЅпїЅпїЅпїЅ пїЅпїЅ пїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ 
	 */
	initOblast : function () {
		
		$('.oblast a').click(function () {
			
			var _parent = $(this).parents('tr:first');
			
			$('.oblast a.here', _parent).removeClass('here');
			$(this).addClass('here');

			offices.SendRequest();

			return false;
			
		});

	},

	
	/**
	 * пїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ пїЅпїЅпїЅпїЅпїЅпїЅ пїЅпїЅ пїЅпїЅпїЅпїЅпїЅпїЅпїЅ 
	 */
	initUslugi : function () {
		
		$('.uslugi a').click(function () {
			
			if ($(this).is('.all_uslugi')) {
				$('.uslugi a').removeClass('here');
			}
			else {
				$('.uslugi a.all_uslugi').removeClass('here');
				
			}
			
			if ($(this).is('.here')) {
				$(this).removeClass('here');
			}
			else {
				$(this).addClass('here');
			}

			if ($('.uslugi a.here').length == 0) {
				$('.uslugi a.all_uslugi').addClass('here');
			}

			offices.SendRequest();
			
			return false;
			
		});
		
	},

	fullInfo : function (ev, link) {

		$('.owerflov').height($(document).height());
		
		ev = window.event ? window.event : ev;
		var request = {ajax: 1};
		if (!ev.pageY) {
			ev.pageY = ev.clientY + $(document).scrollTop();
		}
		var top = ev.pageY-ev.clientY;		

		$.get(link.href, request, function (data) {

			
			$('.onner_overlay').html(data);
			
			$('.overlay').hide();

			$('.overlay').css("top", top);
			$('.overlay').css('margin-left', -$('.overlay').width() / 2);
			//$('.overlay').css('margin-top', -$('.overlay').height() / 2);
			$('.overlay').css('left', '50%');
			
			var click = function () {
				$('.overlay').fadeOut(500, function () {
					$('.owerflov').hide();
					$('.overlay').remove();
				});
				return false;
			}
			
			
			$('.owerflov').one('click', click);
			$('.overlay .close').click(click);

			$('.owerflov').show();
			$('.overlay').fadeIn(500);
			
			var _dataMap = $('.ya_map_data').html().split(','),
				_d = _dataMap[0] || 53.8982,
				_s = _dataMap[1] || 27.5577;
			
			// Создание обработчика для события window.onLoad
			YMaps.jQuery(function () {
				// Создание экземпляра карты и его привязка к созданному контейнеру
				var map = new YMaps.Map(YMaps.jQuery(".ya_map_data")[0]);
				map.addControl(new YMaps.Zoom());
				map.addControl(new YMaps.TypeControl());
				
				
				// Установка для карты ее центра и масштаба
				map.setCenter(new YMaps.GeoPoint(_s, _d), _dataMap[2] || 6);
				
				// Создаем метку и добавляем ее на карту
				var placemark = new YMaps.Placemark(new YMaps.GeoPoint(_s, _d), {
					offset: new YMaps.Point(5, 5)
				});
				placemark.name = $(link).html();
				placemark.description = "";
				map.addOverlay(placemark);
				
				// Открываем балун
				placemark.openBalloon();
			});
			/*
			var _dataMap = $('.ya_map_data').html().split(',');
			
			var geocoder = new google.maps.Geocoder(),
				latLng = new google.maps.LatLng(_dataMap[0] || 53.8982, _dataMap[1] || 27.5577);
					
			map = new google.maps.Map($('.ya_map_data').get(0), {
				zoom: parseInt(_dataMap[2]) || 6,
				center: latLng,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			});
			var marker = new google.maps.Marker({
				position: latLng,
				map: map
			});
				
			
			google.maps.event.trigger(map, 'resize');
			*/
			

		})
		
		return false;
	}

};


$(document).ready(
	function() {
		
		$('a[rel=lightbox]').lightBox({
			imageLoading:			_root + 'public/i/lightbox/lightbox-ico-loading.gif',
			imageBtnPrev:			_root + 'public/i/lightbox/lightbox-btn-prev.gif',
			imageBtnNext:			_root + 'public/i/lightbox/lightbox-btn-next.gif',
			imageBtnClose:			_root + 'public/i/lightbox/lightbox-btn-close.gif',
			imageBlank:				_root + 'public/i/lightbox/lightbox-blank.gif'
		});

		// only for IE6
		if($.browser.msie && parseInt($.browser.version) < 7){
			$('#consultant').mouseover(function () {
				$('#consultant .up').show();
			});
			$('#consultant').mouseout(function () {
				$('#consultant .up').hide();
			});
		}

		/*  пїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ пїЅпїЅпїЅпїЅпїЅпїЅпїЅ */
		//$("tr:nth-child(even)").addClass("chet");
		$("#content tr > td:nth-child(1)").addClass("first");
		
		InitRatesTables();
		InitConverter();

		selector.init();
		slide.Init();
		offices.Init();

		var focus = function () {
			$(this).addClass('focus');
		}
		
		var blur = function () {
			$(this).removeClass('focus');
		}
		
		$("input:text").focus(focus);
		$("textarea").focus(focus);
		
		$("input:text").blur(blur);
		$("textarea").blur(blur);
		
		$('#auth A.top_link').click(function () {

			if ( $('#authUp').is(':visible') ) {
				$('#authUp').fadeOut(500);
			}
			else {
				$('#authUp').fadeIn(500);
			}

			$('#authUp .close').click(function () {
				$('#authUp').fadeOut(500);
				return false;
			});

			return false;

		});
		/*
		var funcRes = function () {
			$('#selector').width($('#menuHead .item_1').width()-5);
		}
		funcRes();
		$(window).resize(funcRes);
		*/
		$('.rowtable tr').hover(function(){
			$(this).addClass('rowHover');
		},function(){
			$(this).removeClass('rowHover');
		})
		$('.coltable td').hover(function(){
			var indexNumber = $('td', $(this).parent('tr')).index(this) + 1;
			$(this).parents('table:last').find('td:nth-child(' + indexNumber + ')').addClass('colHover');
		},function(){
			$(this).parents('table:last').find('td').removeClass('colHover');
		})
		
	}
)

function InitRatesTables() {

	$('#rates h3').each(function(index) {
		if(index != 0){
			$(this).parent().addClass('ratesHidden');
		}
		$(this).click(function() {
			$('#rates h3').each(function(index) {
				$(this).parent().addClass('ratesHidden');
			});
			$(this).parent().removeClass('ratesHidden');
		});
		$(this).mouseover(function() {
			$(this).addClass('hover');
		});
		$(this).mouseout(function() {
			$(this).removeClass('hover');
		});
	});

}

function InitConverter() {
	$('div#converter h4 a').click(function() {
		toggleConverter( );
		return false;
	});
	$('#currencyFromValue,#comissionValue').keyup(function(){
		convertCurrency();
	});
	$('#currencyFromType').change(function() {
		convertCurrency();
	});
}

function toggleConverter( ) {
	$('#converterInner').toggle();
	if($('#converterInner:visible').length > 0) {
		$('div#converter h4 a').addClass('selected');
	}
	else{
		$('div#converter h4 a').removeClass('selected');
	}
}

function stringToFloat(value)
{
	return(value.toString().replace(",", ".").replace(" ", ""));
}

function floatToString(value)
{
	value = value.toFixed(2).toString().replace(".", ",");
	if(value.length <= 7){
		return(value);
	}else{
		if(value.length > 9){
			var position1 = value.length-9;
			var position2 = value.length-6;
			return(value.substring(0,position1)+' '+value.substring(position1,position2)+' '+value.substring(position2, value.length));

		}else{
			var position = value.length-6;
			return(value.substring(0,position)+' '+value.substring(position, value.length));
		}
	}
}

function convertCurrency() {
	var sourceValue = stringToFloat( $('#currencyFromValue').val() );
	var sourceCurrency = $('#currencyFromType').val();

	$('#ConversionResult').html('');

	if(sourceValue > 0) {
		if(sourceCurrency == 'BYR') {
			convertAppendResult('USD', sourceValue/stringToFloat(usd_selling), '');
		}
		if(sourceCurrency == 'USD') {
			convertAppendResult('BYR', sourceValue*stringToFloat(usd_buying), '');
		}
	}
}

function convertAppendResult(currency, value, type) {
	$('#ConversionResult' + type).append('<tr><td class="result"><nobr>'+floatToString(value)+'</nobr></td><td class="currencyResult">'+currency+'</td></tr>');
}

function SubmitSearchForm( ) {
	if ( document.searchForm.searchtext.value.length > 0 && document.searchForm.searchtext.value != 'пїЅпїЅпїЅпїЅпїЅ' ) {
		document.searchForm.submit( );
	}
}

function WO(link,ww,hh,title) {
	w=window.open(link,'',(ww ? 'width='+ww+',' : '')+(hh ? 'height='+hh+',' : '')+'toolbar=0,scrollbars=0,resizable=yes');
	if (link.indexOf('.html')==-1) {
		if (document.layers) title='';
		w.document.open();
		w.document.write('<html><head><title>'+title+'</title><meta http-equiv=Content-Type content="text/html; charset=windows-1251"></head>');
		w.document.write('<body bgcolor=white marginwidth=0 marginheight=0 topmargin=0 leftmargin=0><table width=100% height=100% border=0 cellspacing=0 cellpadding=0><tr><td align=center><img src='+link+' width='+ww+' height='+hh+' border=0 alt=""></td></tr></table></body></html>');
		w.document.close();
	}
	w.focus();
}


var select_filters_click = function (link) {
	
	$('.catFilters').show();
	$(link).parent().hide();
	
}



$(function () {
	
	$('#selector1 LI:first, #selector2 LI:first').addClass('current');
	
	var selector_1 = {};
	var selector_2 = {};

	$.extend(selector_1, selector);
	$.extend(selector_2, selector);
	
	selector_1.init($('#selector1'));
	selector_2.init($('#selector2'));
	
})


// форма заказа карточки
$(function () {
	
	
	$('#order_form FORM')
		.removeAttr('onsubmit')
		.submit(function () {
			
			var error = false;
			
			$('.star:visible').each(function () {
				
				if ('' == $('input', $(this).parents('tr')).val()) {
					error = true;
				}

			});
			
			if (error) {
				alert('Заполните поля отмеченные звёздочкой');
				return false;
			}
			
			if (!$('input[name=soglasen]').attr('checked')) {
				alert('Вы должны согласиться с условиями');
				return false;
			}
			
		});
	
	$('input[name=has_card]').click(function () {
		if ($(this).val() == 'да') {
			$('.donthave_card').slideUp();
		}
		else {
			$('.donthave_card').slideDown();
		}
	})

	$('input[name=has_card]').each(function () {
		if ($(this).attr('checked')) {
			$(this).click();
		}
	});

	
})





$(function () {
	
	// обработка срока более 36 месяцев в депозитах
	
	$('select[name=period]').change(function () {
		
		
		if ($(this).val() == '+') {
			//$(this).attr('disabled', 'disabled');
			$('input[name=period_text]').removeAttr('disabled');
		}
		else {
			//$(this).removeAttr('disabled');
			$('input[name=period_text]')
				.val('')
				.attr('disabled', 'disabled');
		}
		
		
	});
	
	$('select[name=period]').change();
	
	
	{	// Вставка цитат
		
		$('.citate_1').each(function () {
			$(this).wrap('<div class="promo-block"></div>');
		});
		
		$('.promo-block').append('<div class="promo-block-tl"></div>');
		$('.promo-block').append('<div class="promo-block-bl"></div>');
		$('.promo-block').append('<div class="promo-block-br"></div>');
		$('.promo-block').append('<div class="clear"></div>');
		
		
		
		$('.citate_2').each(function () {
			$(this).wrap('<div class="quotes"></div>');
		});
		
		$('.quotes').append('<div class="quote-tl"></div>');
		$('.quotes').append('<div class="quote-tr"></div>');
		$('.quotes').append('<div class="quote-bl"></div>');
		$('.quotes').append('<div class="quote-br"></div>');
		$('.quotes').append('<div class="clear"></div>');
		
	}
	
	$('.cat_href').click(function () {
		var catText = $('.cat_text:first', $(this).parents('.cat_block:first'));
		if (catText.is(':visible')) {
			catText.slideUp();
		}
		else {
			catText.slideDown();
		}
		return false;
	});
	
	
})
