/*
 Copyright Art. Lebedev | http://www.artlebedev.ru/
 2011-07
*/

jQuery.preventDefaultEvent = function(e, options) {
	options = options || {shift:1, ctrl:1, alt:1, meta:1};
	href = e.currentTarget.href;
	if(((options.shift && e.shiftKey)
		|| (options.alt && e.altKey)
		|| (options.ctrl && e.ctrlKey)
		|| (options.meta && e.metaKey))
		&& href && href.indexOf('#') != 0
		&& href.indexOf('javascript:') != 0
	) return true;
	e.preventDefault();
	return false;
};

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

	// key and at least value given, set cookie...
	if (arguments.length > 1 && String(value) !== "[object Object]") {
		options = jQuery.extend({}, options);

		if (value === null || value === undefined) {
			options.expires = -1;
		}

		if (typeof options.expires === 'number') {
			var days = options.expires, t = options.expires = new Date();
			t.setDate(t.getDate() + days);
		}

		value = String(value);

		return (document.cookie = [
			encodeURIComponent(key), '=',
			options.raw ? value : encodeURIComponent(value),
			options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
			options.path ? '; path=' + options.path : '',
			options.domain ? '; domain=' + options.domain : '',
			options.secure ? '; secure' : ''
		].join(''));
	}

	// key and possibly options given, get cookie...
	options = value || {};
	var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
	return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};


var main = {};

main.popup_box = {
	active: null,

	append: function(params){
		return new this.item(params);
	},

	item: function(params){
		this.init(params);
	}
};
$(document).click(function(event){

	if(main.popup_box.click_on_active || event.button == 2){
		main.popup_box.click_on_active = false;
	}else if(main.popup_box.active){
		main.popup_box.active.close();
	}
});


$(document).keydown(function(event) {
	if (event.keyCode == '27') {
		if(main.popup_box.active){
			main.popup_box.active.close();
		}
	}
});


main.webkitPlaceholder = function() {

	if ($.browser.webkit) return { bind: function() {} };

	$(function() {
		$('input[placeholder]').each(function () {
			bind(this);
		});
	});

	/**
	 * Добавляет функцию плейсхолдера элементу.
	 * @param {String|Array[Element]|Element|jQuery} elem Поле ввода
	 * @param {String} [class_empty] Класс для пустого поля ввода
	 */
	function bind(elem, classEmpty) {
		elem = $(elem);
		classEmpty = ('string' === typeof classEmpty) ? classEmpty : 'empty';

		elem.addClass(classEmpty)

		elem.focus(function () {
			if (this.value === $(this).attr('placeholder')) {
				this.value = '';
			}

			$(this).removeClass(classEmpty);
		});

		elem.blur(function () {
			if (!this.value.length) {
				$(this).addClass(classEmpty);
				this.value = $(this).attr('placeholder');
			}

		});

		$(elem).blur();
	}


	return {
		/**
		 * Вручную добавляет функцию плейсхолдера элементу.
		 * @param {String|Array[Element]|Element|jQuery} elem Поле ввода.
		 * @param {String} [class_empty] Класс для пустого поля ввода.
		 */
		bind: bind
	};
};


main.popup_box.item.prototype = {
	init: function(params){
		if(!params){
			params = {};
		}
		if(!params.parent_element){
			params.parent_element = $('body');
		}
		this.element = params && params.element ? params.element : this.create(params);



		this.element.hide();
		var t = this;
		if(params && params.opener_element){
			params.opener_element.addClass('pseudo_link').click(function(e){if($.preventDefaultEvent(e)) return;if(t.opened){t.close()}else{t.open(this)}; return false;});
		}
		this.element.find('.popup_box_close').click(function(){t.close();});
		this.element.click(function(){main.popup_box.click_on_active = true;});
	},

	create: function(params){
		var popup_box;
		if(params && params.content_element){
			popup_box = params.content_element.addClass('popup_box');
		}else{
			popup_box = $('<div class="popup_box"/>');
		}
		return popup_box.prepend('<div class="popup_box_close"><span class="pseudo_link">'+popup_box_close+'</span><ins class="i"></ins></div>').wrapInner('<div class="popup_box_c content"/>').appendTo(params.parent_element);
	},

	open: function(opener_element){
		if(main.popup_box.active && main.popup_box.active != this){
			main.popup_box.active.close();
		}

		if( $('#outer').height() <  this.element.height() ){
			$('#outer').height(this.element.height() + $(opener_element).offset().top)
		}

		if(opener_element && this.element.attr('id') != 'geo_select' && !this.element.hasClass('video_container') && this.element.attr('id') != 'sitemap'){
			this.element.css({top: $(opener_element).offset().top + 'px', left: $(opener_element).offset().left + 'px'});
		}
		this.element.show();
		if(!$.browser.msie){
			this.element.css({opacity: 0});
			this.element.animate({opacity: 1}, 300);
		}
		main.popup_box.active = this;
		this.opened = true;
	},

	close: function(){
		if(!$.browser.msie) {
			this.element.animate({opacity: 0}, 200);
		}

		$('#outer').height('auto')

		this.element.hide();
		main.popup_box.active = null;
		this.opened = false;
	}
};



main.geo_select = {
	init: function(){
		var that = this;
		var city_id;
		var city_list_loaded = false;
		if(!$('#atm_branch a')[1]) return;
		$('#city').append('<span id="city_arr">&#9660;</span>');
		var links = $('#city');
		main.popup_box.append({
			parent_element: $('#outer'),
			content_element: $('<div id="geo_select" class="navigation"/>'),
			opener_element: $(links)
		});

		$('#city').click(function(){
			/* style fix */
			$('#geo_select .logo_tcb').css({'margin-left' : $('#logo img').position().left - 15});

			$('#geo_select #selected_city').css({'margin-left' : $('#city').position().left - ($('#logo img').position().left + 340) });
		})

		if(String($.cookie('city')) == 'null'){

			$.ajax({
				url: '/selected_city.ihtml?' + Math.random(),
				context: that,
				dataType: 'json',
				success: function(data){
					that.city_id = data.city_id;
					try{ $.cookie('city', that.city_id, { path: '/' }); } catch (e){}

					if(that.city_list_loaded){
						this.select_city()
					}
				}
			});
		} else {
			try{ that.city_id = $.cookie('city'); } catch (e){}
		}

		$.ajax({
			url: '/select_city.ihtml',
			context: that,
			success: function(data){
				$('#geo_select .content').append(data);
				this.bind();

				that.city_list_loaded = true;

				if(that.city_id != 'null'){
					this.select_city()
				}
			}
		});


	},

	bind : function(){
		var that = this;
		main.webkitPlaceholder();
		$('#city_list .pseudo_link').bind('click', {context: that}, function(event){
			that.city_id = $(this).attr('id').substring(3);
			event.data.context.select_city()
		});

		$('.search_form .comment').hide();

		this.atm_branch_links = [$('#atm_branch a')[0].href, $('#atm_branch a')[1].href];

		$('#city_search').bind('keyup', function(){
			that.highlight_filials($(this).val())
		});

		$('#selected_city').click(function(){
			main.popup_box.active.close();
		})
	},

	select_city : function(){
		var that = this;
		if(that.city_list_loaded == true  && $('#id_' + that.city_id).length == 0){
			/* unknown city, set moscow */
			that.city_id = 32330;
		}


		try{ $.cookie('city', that.city_id, { path: '/' }); } catch (e){}
		$('#selected_city').html('<span class="pseudo_link" id="selected_' + that.city_id + '">' + $('#id_' + that.city_id).html() + '</span>')

		if(main.popup_box.active != null){
			main.popup_box.active.close();
		}
		this.set_city_on_page();
	},

	set_city_on_page : function(){
		var that = this;
		$('#atm_branch a')[0].href = this.atm_branch_links[0] + that.city_id + '/';
		$('#atm_branch a')[1].href = this.atm_branch_links[1] + that.city_id + '/';
		$('#city').html($('#id_' + that.city_id).html()).append('<span id="city_arr">&#9660;</span>')
		$('#geolocate').show().trigger('update', {city_id: that.city_id});

		if(window.choose_region){
			choose_region()
		}
	},

	highlight_filials : function (val){
		if(val.length){
			$('#city_list').addClass('searching')
			var pattern = new RegExp(val, 'i');
			$('.search_form .comment').show();

			$('#city_list li').removeClass('matched')
			var matched = $('#city_list span.pseudo_link').filter(function() { return pattern.test($(this).text());});
			$('#search_form_matched').html(matched.length);
			matched.parents('li').addClass('matched');

			matched.parents('ul').find('li:first').addClass('matched');
		} else {
			$('.search_form .comment').hide();
			$('#city_list').removeClass('searching')
			$('#city_list li').removeClass('matched')
		}
	}

};



main.navigation = {
	init: function(){
		if(typeof $('#menu a').get(0) == 'undefined'){

			return;
		}
		main.popup_box.append({
			parent_element: $('#outer'),
			content_element: $('#sitemap'),
			opener_element: $('#menu a')
		});

		var parts = [], selected = null, url = $('#menu a').get(0).getAttribute('rel');



		function show(path, item){


			function select(){
				$('#sitemap_inner').html(parts[path]);

				if(selected){
					selected.removeClass('sitemap_tabs_column_selected');
				}
				selected = item;
				selected.addClass('sitemap_tabs_column_selected').find('a, b').blur();
				setTimeout(function(){$('.popup_box .popup_box_b ins').css('display', 'none').css('display', 'block');}, 10);

				init_filters ();

				set_filter(get_filter(), 1);

				if(0 && path == '/ru/path/' && $('#retail_nav').length && sRetail_nav_loaded != 'loaded'){
					/* строим навигацию на страница "физическим лицам"*/

					$('#sitemap_inner td').each(function(index){
						if($('#retail_nav_col_' + (index + 1)). length != 0){
							$('#retail_nav_col_' + (index + 1)).html($(this).html())
						} else {
							$('#retail_nav_col_' + (index + 1 - 4)).append($(this).html())
						}
					})

					sRetail_nav_loaded = 'loaded';
				}

			};
			function loading(item){
				item.removeClass('loading' + item.loading_step);
				item.loading_step = (item.loading_step + 1) % 8;
				item.addClass('loading' + item.loading_step);
				item.loading = setTimeout(function(){loading(item);}, 85);
			}

			if(parts[path]){
				select();
			}else{
				item.addClass('loading');
				item.loading_step = 0;
				loading(item);
				$.ajax({
					url: url + '?path=' + path,
					success: function(data){
						item.removeClass('loading');
						clearTimeout(item.loading);
						var url = document.location.href.replace(/^https?:\/\/[^\/]+/, '');
						data = data.replace(new RegExp('<h2>([^<]+)<a [^>]*href="' + url + '"[^>]*>(.*?)<\\/a>', 'g'), '<h2 class="selected_current">&rarr; $1<b>$2</b>');
						data = data.replace(new RegExp('<h3([^>]+)?>(<ins([^>]+)></ins>)?<a [^>]*href="' + url + '"[^>]*>(.*?)<\\/a>', 'g'), '<h3><b class="selected_current">&rarr; $4</b>');

						data = data.replace(new RegExp('<li([^>]+)?><a [^>]*href="' + url + '"[^>]*>(.*?)<\\/a>', 'g'), '<li$1><b class="selected_current">&rarr; $2</b>');

						parts[path] = data.replace(new RegExp('(<a [^>]*href="([^"]+)"[^>]*)>(.*?)<\\/a>', 'g'), function(str, s1, s2, s3){
								if(url.match(new RegExp('^' + s2))){return s1 + ' class="selected">' + s3 + '</a>';}else{return str;}
							}).replace(/<\/?noindex[^>]*>/gi, '');

						select();
					}
				});
			}

		};



		$('#sitemap_tabs .sitemap_tabs_column').each(function(){

			$(this).find('a, b').addClass('pseudo_link').append('<ins class="i"/>').click(function(e){
				var path = this.onclick();
				if($.preventDefaultEvent(e)) return;
				show(path, $(this.parentNode));
			});
		});

		var selected_on_load = $('#sitemap_tabs .sitemap_tabs_column_selected');
		if(selected_on_load[0]){
			$('a, b', selected_on_load).click();
		}else{
			//$('#navigation .main p .pseudo_link').eq(0).click();
		}
		if($('#path > .reducer > span').length > 1){
			var last = $('#path > .reducer > span:last-child');
			var width = last.width();
			last.addClass('animate');
			last.animate(
				{
					width: width + 'px'
				},
				800,
				'swing',
				function(){
					last.css({width: 'auto'});
					last.removeClass('animate');
				}
			);

		}

		$('#menu a').eq(0).click(function(){
			if ($('#navigation').css('display') != 'block') {
				setTimeout(function(){$('.popup_box .popup_box_b ins').css('display', 'none').css('display', 'block');}, 5);
			}
		});

		$('#menu_popuped a').click(function(e){
			if($.preventDefaultEvent(e)) return;
			main.popup_box.active.close();
		})
	}
};

function init_filters (){
	$('.sitemap_filters .sitemap_filter').click(function(){
		set_filter($(this).attr('class').replace(/(sitemap_filters_|sitemap_filter|sitemap_filter_selected)/gi, '').replace(/(\s+)/gi, ''), 0)
	})
}



var aFilters = ['default', 'rzd', 'new', 'salary'];
var sSelected_filter, sRetail_nav_loaded = '';

function set_filter (sFilter, isFromCookie){
	if(sFilter == ''){
		sFilter = 'default';
	}
	if($.inArray( sFilter, aFilters ) == -1) {
		return false;
	}

	$('.sitemap_filters .sitemap_filter').each(function(){
		$(this).removeClass('sitemap_filter_selected')
	})
	$('.sitemap_filters .sitemap_filters_' + sFilter).addClass('sitemap_filter_selected');

	for(var i in aFilters){
		$('#outer').removeClass('filter_by_' + aFilters[i])
	}

	$('#outer').addClass('filter_by_' + sFilter)

	$.cookie('filter', sFilter, { path: '/' });


	if(isFromCookie != 1 && typeof isFromCookie != 'undefined'){
		window.location.hash = sFilter;
	}
	sSelected_filter = sFilter;

	$('.sitemap_filters').trigger('update', {type: sFilter});
}

function get_filter (){

	if(sSelected_filter == ''){
		sSelected_filter = 'default';
	}
	return sSelected_filter;
}


/**
 * Сортировка необязательных минибаннеров
 * @requires jQuery
 * @copyright Art. Lebedev | http://www.artlebedev.ru/
 * @author vazzda
*/
var MiniBanners =  function (element) {
	this.element_ = element;
	this.parent_ = element.find('.banners_wrapper');
	this.banners_ = element.find('.banner_item');
	this.mandatoryBanners_ = this.bannersByType_('mandatory');
	this.randomBanners_ = this.bannersByType_('random');
};

/**
 * Пересортировка баннеров
 * @public
*/
MiniBanners.prototype.shuffleBanners = function () {
	var mandatoryBanners, randomBanners, shuffledBanners;

	mandatoryBanners = jQuery.makeArray(this.mandatoryBanners_.clone());
	randomBanners = jQuery.makeArray(this.randomBanners_.clone());
	randomBanners.sort(function () {
		return 0.5 - Math.random();
	});
	shuffledBanners = mandatoryBanners.concat(randomBanners);

	this.parent_.html(jQuery(shuffledBanners));
};

/**
 * Возвращает баннеры по типу
 * @param type {String} Тип возвращаемых баннеров
 * @return jQuery collection
 * @private
*/
MiniBanners.prototype.bannersByType_= function (type) {
	return this.banners_.filter(function (i, item) {
		if (jQuery(item).data('type') === type) {
			return true;
		} else {
			return false;
		}
	});
};



/**
 * Инициализация main.element. элементов в html
 * Элементы описываются в неймспейсе main.element
 * @param element {jQuery} Элемент в доме, обязательный. В поле data-init
 *	 обязательно наличие объекта, описывающего имя элемента и его данные
 * @requires jQuery
 * @copyright Art. Lebedev | http://www.artlebedev.ru/
 * @author vazzda
*/
main.element = { };
main.element.init = function (element) {
	var name, params;

	params = element.data('init');
	name = params.name.slice(0,1).toUpperCase() + params.name.slice(1);
	if (!main.element[name]) {
		return false;
	}
	//new
	return new main.element[name](element[0]);
};


/**
 * Инициализация элемента кнопки
 * @param element {Node} Ссылка на элемент в доме
*/
main.element.Button = function (node) {
	var element;

	this.element_ = element = jQuery(node);
	this.isEnabled_ = true;
	this.isButtonHTMLElement_ = element.is('button');
};

/**
 * Состояние включенности кнопки
 * @return Boolean
 * @public
*/
main.element.Button.prototype.isEnabled = function () {
	return this.isEnabled_;
}

/**
 * Включение кнопки
 * @param element {jQuery} Элемент в доме
 * @public
*/
main.element.Button.prototype.enable = function () {
	var element;

	element = this.element_;
	element.removeClass('button_disabled');
	if (this.isButtonHTMLElement_ === true) {
		element.removeAttr('disabled');
	}
	this.isEnabled_ = true;
};

/**
 * Выключение кнопки
 * @param element {jQuery} Элемент в доме
 * @public
*/
main.element.Button.prototype.disable = function () {
	var element;

	this.isEnabled_ = false;
	element = this.element_;
	if (this.isButtonHTMLElement_ === true) {
		element.attr('disabled', 'disabled');
	}
	element.addClass('button_disabled');
};



/**
 * Инициализация элемента ссылки на видео в попапе
 * @param element {node} Ссылка на элемент в доме
*/
main.element.Video = function (node) {
	var element;

	this.element_ = element = jQuery(node);
	this.data_ = element.data('params');

	this.createPopup_();
	this.loadSWF_();

};

/**
 * Сборка попапа для видео (main.popup)
 * @private
*/
main.element.Video.prototype.createPopup_ = function () {
	var data, element, parent, popup, popup_template, popup_width;

	element = this.element_;
	data = this.data_;
	parent = $('#outer');

	popup_template = jQuery('<div class="video_container">' +
			'<div id="' + data.name + '"/>' +
		'</div>');
	popup = main.popup_box.append({
		parent_element: parent,
		content_element: popup_template,
		opener_element: element
	});

	element.bind('click', function (event) {
		event.preventDefault();
		event.stopPropagation();
		popup.open();
	});
	element.addClass('video_inited pseudo_link');
}

/**
 * Загрузка flash плеера
 * @private
*/
main.element.Video.prototype.loadSWF_ = function () {
	var data, flashvars, params, parent;

	data = this.data_;
	flashvars = {
		video: data.video,
		css: "/css/player_skin_default.css",
		skin: "/js/player_default_skin.swf",
		cover: data.cover,
		bgColor: "16777215",
		subs_url: data.subtitles,
		subs_size: 18,
		autoplay: 0
	};
	params = {
		allowFullscreen: "true",
		allowScriptAccess: "always",
		wmode: "transparent"
	};

	swfobject.embedSWF(
		"/js/player_subtitles.swf",
		data.name,
		"900",
		"708",
		"10.0.0",
		false,
		flashvars,
		params
	);
}


$(function(){
	var miniBanners, miniBannersElement, root;

	//браузеры на body
	root = jQuery('body');

	if (jQuery.browser.msie) {
		root.addClass('msie msie_' + Math.floor(jQuery.browser.version));
	}

	if($('#geolocate').length){
		main.geo_select.init();
	}

	if(!$('#home_page')[0]){
		main.navigation.init();
	} else {
	}

	/* шафл минибаннеров */
	miniBannersElement = jQuery('.mini_banners');
	if (miniBannersElement.length) {
		miniBannersElement.addClass('banners_hidden');
		miniBanners = new MiniBanners(miniBannersElement);
		miniBanners.shuffleBanners();
		miniBannersElement.removeClass('banners_hidden');
	}

	/* инициализация видео ссылок */
	jQuery('.video').each(function (index, item) {
		main.element.init(jQuery(item));
	});

	main.webkitPlaceholder();

	if(window.location.hash.substring(1) != '' && $.inArray( window.location.hash.substring(1), aFilters ) ){
		set_filter(window.location.hash.substring(1), 5)
	} else if($.cookie('filter') != null){
		set_filter($.cookie('filter'), 1, { path: '/' })
	}


	$('.foldable').each(function(){
		var t = $(this), d = t.next('*');
		if(!t.hasClass('pseudo_link')){
			t = t.wrapInner('<span class="pseudo_link"></span>').find('.pseudo_link');
		}
		d.hide();
		t.click(function(){
			d.slideToggle();
		})
	})
});


var aMonths = {ru:{normal:["январь","февраль","март","апрель","май","июнь","июль","август","сентябрь","октябрь","ноябрь","декабрь"],genitive:["января","февраля","марта","апреля","мая","июня","июля","августа","сентября","октября","ноября","декабря"]},en:{normal:["january","february","march","april","may","june","july","august","september","october","november","december"],genitive:["january","february","march","april","may","june","july","august","september","october","november","december"]}};

var aDaysOfWeek = {ru:["вс","пн","вт","ср","чт","пт","сб"],en:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]};

