/*
 Copyright Art. Lebedev | http://www.artlebedev.ru/
*/

jQuery.preventDefaultEvent = function(e, options) {
	options = options || {shift:1, ctrl:1, alt:1, meta:1};
	var 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;
};


var main = {};


main.logo_piano = {
	init: function() {
		var t = this;
		t.logo_element = $('#header .logo .reducer');
		t.items = [];
		t.logo_element.find('a img').each(function(eq){
			t.items.push(new t.item({ eq: eq, element: $(this) }));
		});
	},

	item: function(params) {
		var t = this;
		t.eq = params.eq;
		t.element = params.element;
		t.element.css({display: 'block', float: 'left'});
		t.element.hover(function(){
			$(this).css('marginTop', '-2px');
		}, function(){
			$(this).css('marginTop', '0');
		});
	}
	
};

main.path_navigation = {
	init: function() {
		var t = this;
		if(!$('.path_navigation_popup_link').size()) return;
		t.path_navigation_element = $('.path_navigation');
		t.popup_element = $('.path_navigation_popup');
		t.popup_link_element = $('.path_navigation_popup_link');
		t.popup_link_element.find('a').addClass('pseudo_link');
		t.popup = main.popup.append({
			parent_element: t.path_navigation_element,
			content_element: t.popup_element,
			opener_element: t.popup_link_element,
			close_label: 'Закрыть'
		});
		t.geo_parts_element = t.popup_element.find('.path_navigation_geo_parts');
		t.geo_countries_element = t.popup_element.find('.path_navigation_geo_countries');
		t.geo_cities_element = t.popup_element.find('.path_navigation_geo_cities');
		t.loading_element = $('<div class="loading"></div>');
		t.document_url = document.location.href.replace(/^https?:\/\/[^\/]+/, '');
		t.path = t.popup_link_element[0].onclick();
		t.geo_type = 'geo_main';
		t.geo_parts = new t._geo_parts(this, this);
	},

	_geo_parts: function(t, m) {
		var item_geo_parts_element = null;
		$.getJSON(t.path, function(data) {
			t.geo_parts_extra_element = $('<ins class="path_navigation_extra"></ins>');
			t.geo_parts_main_element = $('<ins class="path_navigation_main"></ins>');
			if (data.overview_title) t.geo_parts_main_element.html('<h5><a href="'+data.href+'">'+data.overview_title+'</a></h5>');
			if (data.type == 'geo_parts') {
				t.geo_parts_items_element = $('<table class="path_navigation_items"><tr><td class="geo_most"></td><td></td></tr></table>');
				item_geo_parts_element = m.geo_countries_element;
			}
			else if (data.type == 'geo_countries') {
				t.geo_parts_items_element = $('<table class="path_navigation_items"><tr><td></td><td></td><td></td><td></td><td></td></tr></table>');
				item_geo_parts_element = m.geo_cities_element;
			}
			else if (data.type == 'geo_cities') {
				t.geo_parts_items_element = $('<table class="path_navigation_items"><tr><td></td><td></td><td></td><td></td><td></td></tr></table><h6>'+data.regions_title+'</h6><table class="path_navigation_items"><tr><td></td><td></td><td></td><td></td><td></td></tr></table>');
				item_geo_parts_element = m.geo_cities_element;
			}
			else if (data.type == 'geo_most') {
				t.geo_parts_items_element = $('<h6>'+data.countries_title+'</h6><table class="path_navigation_items"><tr><td></td><td></td><td></td><td></td><td></td><td></td></tr></table><h6>'+data.cities_title+'</h6><table class="path_navigation_items"><tr><td></td><td></td><td></td><td></td><td></td><td></td></tr></table>');
				item_geo_parts_element = m.geo_countries_element;
			}
			t.geo_parts_main_element.append(t.geo_parts_items_element);
			t.geo_parts_items_td_elements = t.geo_parts_items_element.find('td');
			if (data.accent_off && data.accent_on) {
				t.accent_off_element = $('<span class="pseudo_link">'+data.accent_off+'</span>');
				t.accent_on_element = $('<span class="pseudo_link">'+data.accent_on+'</span>').hide();
				t.geo_parts_extra_element.append(t.accent_off_element).append(t.accent_on_element);
				t.accent_off_element.click(function(){m.insert_items(t, false, true);});
				t.accent_on_element.click(function(){m.insert_items(t, true, true);});
			}
			t.items = [];
			for (var i=0; i<data.items.length; i++) { t.items.push(new m._item(data.items[i], i, m, t, item_geo_parts_element)); }
			m.insert_items(t, true, true);
		});
	},

	_item: function(params, i, m, p, geo_parts_element) {
		var t = this;
		t.id = i;
		t.geo_type = params.type;
		t.geo_parts_element = geo_parts_element;
		t.accent = params.accent;
		t.element = $('<p class="path_navigation_item"></p>');
		if (p.geo_type != 'geo_most' && m.document_url.match(new RegExp('^' + params.href))) {
			t.selected = true;
			t.element.addClass('selected');
		}
		else t.selected = false;
		if (!params.href || params.href == m.document_url) t.element_link = $('<b>'+params.name+'</b>');
		else t.element_link = $('<a href="'+params.href+'">'+params.name+'</a>');
		t.element.append(t.element_link);
		if (params.path) {
			t.path = params.path;
			t.element_link.addClass('pseudo_link');
			t.element_link.click(function(e){
				if ($.preventDefaultEvent(e)) return;
				if (t.items && t.geo_parts_main_element.is(':visible')) return false;
				if (typeof p.selected_id == 'number') {
					p.items[p.selected_id].selected = false;
					p.items[p.selected_id].element.removeClass('selected');
				}
				p.selected_id = t.id;
				t.selected = true;
				t.element.addClass('selected');
				if (t.geo_type == 'geo_most') m.popup_element.addClass('path_navigation_most');
				else m.popup_element.removeClass('path_navigation_most');
				m.clear_data(t.geo_type);
				if (p.accent_off) m.insert_items(p, true, true);
				else {
					if (t.items) m.insert_items(t, true, false);
					else t.geo_parts = new m._geo_parts(t, m);
				}
				return false;
			});
		}
	},

	insert_items: function(t, accent, show_children) {
		var height_start = t.geo_parts_element.height(), height_end = 0, speed = 0, column_qty = t.geo_parts_items_td_elements.size(), items_qty = 0, items_for_columns_qty = 0, items_modulo_qty = 0, selected_id;
		if (t.geo_type == 'geo_main') column_qty --;
		if (t.geo_type == 'geo_country' || t.geo_type == 'geo_most') {
			column_qty = column_qty / 2;
			var regions_qty = 0, regions_for_columns_qty = 0, regions_modulo_qty = 0;
		}
		for (var i=0; i<t.items.length; i++) {
			if (!accent || t.items[i].accent || t.items[i].selected) {
				if ((t.geo_type == 'geo_country' && t.items[i].geo_type == 'geo_region') || (t.geo_type == 'geo_most' && t.items[i].geo_type == 'geo_city')) regions_qty ++;
				else items_qty++;
			}
		}
		items_for_columns_qty = Math.floor(items_qty / column_qty);
		items_modulo_qty = items_qty % column_qty;
		if (t.geo_type == 'geo_country' || t.geo_type == 'geo_most') {
			regions_for_columns_qty = Math.floor(regions_qty / column_qty);
			regions_modulo_qty = regions_qty % column_qty;
		}
		t.geo_parts_element.css({height: height_start, overflow: 'hidden'});
		t.geo_parts_element.animate({opacity: 0}, 200, function() {
			if (accent && t.accent_off_element && t.accent_on_element) {
				t.accent_off_element.css({display: 'inline'});
				t.accent_on_element.css({display: 'none'});
			}
			else if (!accent && t.accent_off_element && t.accent_on_element) {
				t.accent_off_element.css({display: 'none'});
				t.accent_on_element.css({display: 'inline'});
			}
			t.geo_parts_element.children().each(function(){$(this).detach();});
			for (var i=0, i_qty = 0, r_qty = 0, i_column_eq = 0, r_column_eq = 0; i<t.items.length; i++) {
				t.items[i].element.detach();
				if (!accent || t.items[i].accent || t.items[i].selected) {
					if ((t.geo_type == 'geo_country' && t.items[i].geo_type == 'geo_region') || (t.geo_type == 'geo_most' && t.items[i].geo_type == 'geo_city')) {
						if (r_column_eq < regions_modulo_qty && r_qty == regions_for_columns_qty + 1) {r_qty = 0; r_column_eq ++;}
						else if (r_column_eq >= regions_modulo_qty && r_qty == regions_for_columns_qty) {r_qty = 0; r_column_eq ++;}
						t.geo_parts_items_td_elements.eq(r_column_eq + column_qty).append(t.items[i].element);
						r_qty ++;
					}
					else {
						if (t.geo_type == 'geo_main' && t.items[i].geo_type == 'geo_most') i_column_eq = 0;
						else if (t.geo_type == 'geo_main') i_column_eq = 1;
						else if (i_column_eq < items_modulo_qty && i_qty == items_for_columns_qty + 1) {i_qty = 0; i_column_eq ++;}
						else if (i_column_eq >= items_modulo_qty && i_qty == items_for_columns_qty) {i_qty = 0; i_column_eq ++;}
						t.geo_parts_items_td_elements.eq(i_column_eq).append(t.items[i].element);
						if (t.items[i].selected) {
							if (show_children) selected_id = i;
							else {
								selected_id = null;
								t.items[i].selected = false;
								t.items[i].element.removeClass('selected');
							}
						}
						i_qty ++;
					}
				}
			}
			if (t.geo_type == 'geo_main' && typeof selected_id != 'number') selected_id = 0;
			if (accent && typeof selected_id == 'number') setTimeout(function(){t.items[selected_id].element_link.click()}, 200);
			accent ? t.accent_off = false : t.accent_off = true;
			t.geo_parts_element.append(t.geo_parts_extra_element).append(t.geo_parts_main_element);
			height_end = t.geo_parts_main_element.outerHeight();
			speed = parseInt(Math.abs(height_end - height_start) * 2);
			t.geo_parts_element.animate({opacity: 1, height: height_end}, speed, function(){t.geo_parts_element.removeAttr('style');});
		});
	},

	clear_data: function(type) {
		var t = this;
		if (type == 'geo_part' || type == 'geo_most') {
			t.geo_countries_element.children().each(function(){$(this).detach();});
			t.geo_cities_element.children().each(function(){$(this).detach();});
			t.geo_countries_element.append(t.loading_element);
		}
		else if (type == 'geo_country') {
			t.geo_cities_element.children().each(function(){$(this).detach();});
			t.geo_cities_element.append(t.loading_element);
		}
	}
};

main.suggest = {
	init: function(){
		this.input_element = $('.with_suggest');
		if(!this.input_element.length) return;
		var t = this;

		this.input_element.attr('autocomplete', 'off');

		var params = this.input_element[0].onclick();
		this.suggest_href = params.suggest;

		this.form_href = this.input_element.parent('form').attr('action') + '?' + this.input_element.attr('name') + '=';

		$('<div class="example">Например: <span class="pseudo_link">' + params.example + '</span></div>').insertAfter(this.input_element.parent()).find('.pseudo_link').click(function(){
			t.input_element.val(params.example);
			t.input_element.focus();
		});

		this.suggest_element = $('<div class="suggest"></div>').insertAfter(this.input_element.parent());
		this.suggest_element.bind('focus mousedown keydown', function(){t.over = true;});
		this.suggest_element.bind('blur mouseup keyup', function(){t.over = false; t.input_element.focus();});
		this.suggest_element.hide();

		this.data = [];

		this.input_element.bind('focus keyup mouseup change', function(){
			t.show();
		});
		this.input_element.blur(function(){
			if(!t.over){
				t.hide();
			}
		});
	},

	show: function(){
		var value = this.input_element.val();
		if(!value){
			this.hide();
			return;
		}
		if(this.data[value] == undefined){
			t = this;
			clearTimeout(this.loading);
			this.loading = setTimeout(function(){
				$.getJSON(
					t.suggest_href + escape(value),
					function(data){
						t.data[value] = {data: data};
						if(!data || !data.total){
							t.suggest_element.hide();
						}else{
							t.make(value);
							t.suggest_element.show();
						}
					}
				).error(function(){t.data[value] = '';});
			}, 500);
		}else{
			this.make(value);
			this.suggest_element.show();
		}
	},

	hide: function(){
		this.suggest_element.hide();
	},

	make: function(value){
		if(this.old_value == value) return;
		this.old_value = value;
		var d = this.data[value];
		if(d.data && !d.html){
			d.html = '<div class="results">';
			for(var i = 0, group, ii, item; i < d.data.groups.length; i++){
				group = d.data.groups[i];
				d.html += '<div class="group"><div class="group_title">' + group.title + '</div>';
				for(ii = 0; ii < group.items.length; ii++){
					item = group.items[ii];
					d.html += '<div class="item">';
					d.html += '<a href="' + item.href + '">';
					if(item.icon){
						d.html += '<img src="' + item.icon + '"/> ';
					}
					d.html += item.title + '</a>';
					if(item.extra){
						d.html += ', ' + item.extra;
					}
					d.html += '</div>';
				}
				d.html += '</div>';
			}
			d.html += '</div><div class="total"><a href="' + this.form_href + escape(value) + '">Все результаты (' + d.data.total + ')</a></div>';
		}
		this.suggest_element.html(d.html);
	}
};

main.hint = {
	init: function(){
		$('.with_hint').each(function(){
			main.popup.append({
				content_element: $('#for_' + this.id),
				opener_element: $(this).addClass('pseudo_link')
			});
		});
	}
};


main.popup = {
	active: null,
	shade: null,
	append: function (params) { return new this.item(params); },
	item: function (params) { this.init(params); }
};

main.popup.item.prototype = {
	init: function (params){
		var t = this;
		if (!params) params = {};
		if (params.parent_element) t.parent_element = params.parent_element; else params.parent_element = $('#layout');
		//if (params.close_title) params.close_label = '';
		t.element = params && params.element ? params.element : t.create (params);
		if (params.popup_shade) t.popup_shade = true; else t.popup_shade = false;
		t.element.hide();
		if (params && params.opener_element) {
			params.opener_element.click(function(e){
				if ($.preventDefaultEvent(e)) return;
				if (t.opened) t.close(); else t.open(this);
				return false;
			});
		}
		
		if (params.alignByBottom) {
			this.alignByBottom = params.alignByBottom || false;
		}
		
		this.element.find('.popup_close').click(function(){ t.close(); });
		this.element.click(function(){ main.popup.click_on_active = true; });
	},

	create: function(params) {
		var popup_box;
		if (params && params.content_element) popup_box = params.content_element.addClass('popup');
		else popup_box = $('<div class="popup" />');
		if (params.popup_shade && !main.popup.shade) {
			main.popup.shade = $('<div class="popup_shade" />');
			main.popup.shade.appendTo(params.parent_element);
			main.popup.shade.hide();
		}
		popup_box.prepend('<ins class="popup_close">'+(params.close_label ? params.close_label : '')+'<ins class="i"></ins></ins>').wrapInner('<div class="popup_reducer"/>').appendTo(params.parent_element);
		return popup_box;
	},

	open: function(opener_element){
		var timer = 0, t = this;
		if (main.popup.active && main.popup.active != this) { main.popup.active.close(); timer = 200; }
		setTimeout(function(){t.open_delay(opener_element);}, timer);
	},
	
	open_delay: function(opener_element) {
		if (opener_element && !this.parent_element) {
			this.element.css(
				{
					top: $(opener_element).offset().top + (this.alignByBottom ? $(opener_element).height() : 0) - 1, 
					left: $(opener_element).offset().left - 1
				}
			);
		}
		else if (opener_element && this.parent_element) {
			this.element.css(
				{
					top: $(opener_element).offset().top + (this.alignByBottom ? $(opener_element).height() : 0) - this.parent_element.offset().top - 1, 
					left: $(opener_element).offset().left - this.parent_element.offset().left - 1
				}
			);
		}
		
		
		if (this.alignByBottom) {
			this.element.css({ 'min-width' : $(opener_element).width() });
		}
		
		if (this.popup_shade) main.popup.shade.show();
		this.element.show();
		if (!$.browser.msie) {
			this.element.css({opacity: 0});
			this.element.animate({opacity: 1}, 300);
		}
		main.popup.active = this;
		this.opened = true;
	},

	close: function(){
		if (main.popup.shade) main.popup.shade.hide();
		if(!$.browser.msie) this.element.animate({opacity: 0}, 200);
		this.element.hide();
		main.popup.active = null;
		this.opened = false;
	}
};


main.articles_top = {
	timer: null,

	init: function() {
		var t = this;
		if (!$('.incut_articles_top').size()) return;
		t.pictures_element = $('.incut_articles_top .pictures');
		t.thumbnails_element = $('.incut_articles_top .thumbnails');
		t.items = [];
		t.thumbnails_element.find('.item').each(function(eq){
			t.items.push(new t.item({ eq: eq, thumbnail: $(this), picture: t.pictures_element.find('.item').eq(eq) }));
		});
		
		t.timer = setTimeout(function(){t.change_item()}, 10000);
	},

	item: function(params) {
		var t = this;
		t.eq = params.eq;
		t.thumbnail = params.thumbnail;
		t.picture = params.picture;
		t.selected = t.thumbnail.is('.selected') ? true : false;
		if (t.selected) main.articles_top.selected = t.eq;
		t.thumbnail_link = t.thumbnail.find('a');
		t.thumbnail_link.click(function(e){
			if ($.preventDefaultEvent(e)) return true;
			if (t.selected) return false;
			if (main.articles_top.timer) clearTimeout(main.articles_top.timer);
			t.show();
			return false;
		});
	},

	change_item: function() {
		var t = this, next = t.selected + 1;
		if (next == t.items.length) next = 0;
		t.items[next].show();
		t.timer = setTimeout(function(){t.change_item()}, 8000);
	}
};


main.articles_top.item.prototype = {
	show: function() {
		var t = this;
		main.articles_top.items[main.articles_top.selected].picture.fadeOut(200, function(){
			main.articles_top.items[main.articles_top.selected].thumbnail.removeClass('selected');
			main.articles_top.items[main.articles_top.selected].selected = false;
			t.thumbnail.addClass('selected');
			t.selected = true;
			main.articles_top.selected = t.eq;
			t.picture.fadeIn(400);
		});
	}
};

main.photo_gallery = {
	init: function() {
		var t = this;
		t.photo_gallery_element = $('.incut_photo_gallery .pictures');
		t.items = [];
		t.height = 0;
		t.photo_gallery_element.find('img').each(function(eq){
			t.items.push(new t.item({ eq: eq, element: $(this) }));
			t.height += eq ? 30 : $(this).height();
		});
		t.photo_gallery_element.css({height: t.height});
	},

	item: function(params) {
		var t = this;
		t.eq = params.eq;
		t.element = params.element;
		if (t.eq == 0) {
			t.element.css({position:'absolute', top:'0px', left:'0px'});
		}
		else if (t.eq == 1) {
			var marginLeft = parseInt(t.element.width() / 2 + 5);
			t.element.css({position:'absolute', top:'30px', left:'50%', marginLeft:'-'+marginLeft+'px'});
		}
		else if (t.eq == 2) {
			t.element.css({position:'absolute', top:'60px', right:'0px'});
		}
		t.element.hover(function(){
			t.element.css('z-index', '1');
		}, function(){
			t.element.css('z-index', 'auto');
		});
	}

};


$(document).click(function(){
	if (main.popup.click_on_active) main.popup.click_on_active = false;
	else if (main.popup.active) main.popup.active.close();
}).keydown(function(e){
	if (e.keyCode === 27 && main.popup.active) main.popup.active.close();
});


$(document).ready(function(){
	//main.logo_piano.init();
	main.photo_gallery.init();
	main.path_navigation.init();
	main.suggest.init();
	main.articles_top.init();
	main.hint.init();
});
