/*
 Copyright Art. Lebedev | http://www.artlebedev.ru/
 Created 2010-03-03 by vlalek
 Updated 2010-08-16 by vlalek
 Updated 2010-09-09 by chemist
 Updated 2010-09-15 by levenets
*/
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;
};

var main = {};

main.popup_box = {
	active: null,

	append: function(params){
		return new this.item(params);
	},

	item: function(params){
		this.init(params);
	}
};
$(document).click(function(){
	if(main.popup_box.click_on_active){
		main.popup_box.click_on_active = false;
	}else if(main.popup_box.active){
		main.popup_box.active.close();
	}
});

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"><ins class="i"></ins><span class="pseudo_link">'+popup_box_close+'</span></div>').wrapInner('<div class="popup_box_c content"/>').prepend('<ins class="popup_box_t popup_box_l"><ins/></ins><ins class="popup_box_t popup_box_r"><ins/></ins>').append('<ins class="popup_box_b popup_box_l"><ins/></ins><ins class="popup_box_b popup_box_r"><ins/></ins><iframe frameborder="no"/>').appendTo(params.parent_element);
	},

	open: function(opener_element){
		if(main.popup_box.active && main.popup_box.active != this){
			main.popup_box.active.close();
		}
		if(opener_element){
			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);
		}
		this.element.hide();
		main.popup_box.active = null;
		this.opened = false;
	}
};

main.button = {
	append: function(params){
		return new this.item(params);
	},

	item: function(params){
		if(!params){
			params = {};
		}
		this.init(params);
	}
};

main.button.item.prototype = {
	init: function(params){
		this.element = params && params.element ? params.element : this.create(params);
	},

	create: function(params){
		var button_box;
		if(params && params.content_element){
			button_box = params.content_element.addClass('button' + (params.class_name ? ' ' + params.class_name: ''));
		}else{
			button_box = $('<ins class="button' + (params.class_name ? ' ' + params.class_name: '') + '"/>');
		}
		return button_box.wrapInner('<ins class="button_c"/>').prepend('<ins class="button_t button_l"><ins/></ins><ins class="button_t button_r"><ins/></ins>').append('<ins class="button_b button_l"><ins/></ins><ins class="button_b button_r"><ins/></ins>');
	}
};

main.geo_select = {
	init: function(){
		var links = $('#header .geo_select a');
		if(links.length == 2){
			main.popup_box.append({
				parent_element: $('#header .reducer'),
				content_element: $('<div id="geo_select" class="navigation"/>'),
				opener_element: $(links[1])
			});
			$.ajax({
				url: links[1].href,
				success: function(data){
					main.geo_select.initilization = true;
					$('#geo_select .content').append('<hr/>').append(data.replace(/^(?:.|\n)*(<table)/, '$1').replace(/(<\/table>)(?:.|\n)*$/, '$1'));
				}
			});
		}
	}
};


main.navigation = {
	init: function(){
		if(!$('#menu')[0]){
			return;
		}
		main.popup_box.append({
			parent_element: $('#path'),
			content_element: $('#navigation'),
			opener_element: $('#menu')
		});

		var parts = [], selected = null, url = $('#menu a')[0].getAttribute('rel');
		function show(path, item){
			function select(){
				$('#navigation .extra').html(parts[path]);
				$('#navigation')[0].className+='';
				if(selected){
					selected.removeClass('selected');
				}
				selected = item;
				selected.addClass('selected');
				setTimeout(function(){$('.popup_box .popup_box_b ins').css('display', 'none').css('display', 'block');}, 10);
			};
			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('<a [^>]*href="' + url + '"[^>]*>(.*?)<\\/a>', 'g'), '<b class="selected">$1</b>');
						//data = data.replace(new RegExp('<li>[^<]*<a [^>]*href="' + url + '"[^>]*>(.*?)<\\/a>[^<]*</li>', 'g'), '<li class="selected"><b class="selected">$1</b></li>');
						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();
					}
				});
			}

		};

		$('#navigation .main p').each(function(){
			var path = this.onclick();
			$(this).find('a, b').addClass('pseudo_link').append('<ins class="i"/>').click(function(e){
				if($.preventDefaultEvent(e)) return;
				show(path, $(this.parentNode));
			});
		});
		var selected_on_load = $('#navigation .main p .selected');
		if(selected_on_load[0]){
			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);
			}
		});
	}
};


main.forms = {
	init: function(){
		if(window.ZForms){
			ZForms.attachObserver(
				ZForms.EVENT_TYPE_ON_INIT,
				function(){
					for(var i = 0, form; i < ZForms.aForms.length; i++){
						form = ZForms.aForms[i];
						main.forms.add_values_repository(form, ['product', 'amount', 'summ', 'sum', 'period', 'currency']);
						main.forms.add_gender_dependence(form);
					};
					main.forms.initilization = true;
				}
			);
		}
	},

	add_values_repository: function(form, names){
		var children = form.getChildren();
		for(var i = 0, name, value; i < children.length; i++){
			name = children[i].getName();
			if(name){
				if(!names || names.join().match(new RegExp('(^|,)' + name + '($|,)'))){
					value = jCommon.cookie('zf_' + name);
					if(value && !document.location.search){
						children[i].setValue(children[i].createValue(value));
						if(value != children[i].getValue().get()){
							children[i].oElement.selectedIndex = 0;
						}
					}
					ZForms.attachObserver(
						ZForms.EVENT_TYPE_ON_CHANGE,
						function(sEventType, oWidget){
							jCommon.cookie('zf_' + oWidget.getName(), oWidget.getValue().get(), {path: '/'});
						},
						children[i]
					);
				}
			}else if(children[i].getChildren){
				this.add_values_repository(children[i], names);
			}
		}
	},

	add_gender_dependence: function(form){
		var person = {
			last_name: form.getWidgetById('last_name'),
			first_name: form.getWidgetById('first_name'),
			middle_name: form.getWidgetById('middle_name'),
			gender: form.getWidgetById('gender')
		};
		if(person.last_name && person.first_name && person.gender){
			add_gender_dependence(person.last_name, person);
			add_gender_dependence(person.first_name, person);
			if(person.middle_name){
				add_gender_dependence(person.middle_name, person);
			}
		}

		function add_gender_dependence(widget){
			ZForms.attachObserver(
				ZForms.EVENT_TYPE_ON_CHANGE,
				function(sEventType, oWidget){
					var gender = get_gender_by_name(person.last_name.getValue().get(), person.first_name.getValue().get(), person.middle_name? person.middle_name.getValue().get(): '');
					if(gender == 'male'){
						if(person.gender instanceof ZForms.Widget.Select){
							person.gender.oElement.selectedIndex = 0;
							person.gender.processEvents(true);
							Common.Class.add(person.gender.oClassElement, 'hidden');
						}
					}else if(gender == 'female'){
						if(person.gender instanceof ZForms.Widget.Select){
							person.gender.oElement.selectedIndex = 1;
							person.gender.processEvents(true);
							Common.Class.add(person.gender.oClassElement, 'hidden');
						}
					}else{
						Common.Class.remove(person.gender.oClassElement, 'hidden');
					}
				},
				widget
			);
		};

		function get_gender_by_name(last_name, first_name, middle_name){
			var male = 0, female = 0;
			if(middle_name){
				if(middle_name.match(/ич\s*$/)){
					male += 10;
				}else if(middle_name.match(/на\s*$/)){
					female += 10;
				}
			}
			if(last_name){
				if(last_name.match(/([иы]н|[оеё]в|ый|кий|кой)\s*$/)){
					male += 1;
				}
				if(last_name.match(/(ва|ая|яя|ина|кая)\s*$/)){
					female += 1;
				}
			}
			if(first_name){
				if(first_name.match(/(аба|ад|ак|ам|ар|арид|арь|ат|аум|б|бен|бр|брь|в|ван|вва|вел|вель|вер|вет|вид|вила|г|ге|гель|ген|дан|ди|др|дт|ед|ем|ж|жан|жен|з|зд|зм|иан|идель|иель|изан|ил|илен|илли|иль|илья|им|имен|ин|ир|й|кел|кид|кила|кита|кл|кт|кум|лан|лель|лет|лк|лл|ман|мза|мид|наль|нан|нд|нел|нид|нит|нн|нри|нт|о|од|ол|олен|олит|ом|ома|омен|он|онель|ор|орь|от|п|пан|пит|ран|рд|рен|рет|рик|рк|рл|рм|рн|рри|рт|с|сен|сила|ст|сталь|тан|тер|тит|тр|уан|уд|ук|ука|уль|ур|ут|ф|фан|фрид|х|ц|ш|шид|ыд|ын|ыня|ьд|ьен|ьер|ьм|ьма|ьт|эль|эм|эрлен|юд|юм|юри|ям|ян|ём|ён)\s*$/)){
					male += 1;
				}
				if(first_name.match(/(адель|аза|ала|али|алья|аня|ари|ата|ая|бава|бер|вик|вла|вь|вья|га|да|дита|ева|еза|ела|елли|ема|ета|ея|жет|иба|иза|ика|илит|има|инель|ирь|ия|йла|йя|кла|лер|лита|лла|ля|мила|мма|на|нет|нила|нита|нум|нья|оза|озан|ола|оня|оя|ра|рава|ре|рита|рма|рмен|рта|рья|са|сель|ста|сья|ся|трид|тта|тья|уба|уза|ума|ури|фа|фер|фь|фья|ца|цлава|чел|ьва|ьза|э|\Sслава)\s*$/)){
					female += 1;
				}
			}
			return male > female? 'male': (male < female? 'female': '');
		};
	}

};


main.mailto = function(){
	$('.mt').each(function(){
		var title = this.title.split(' ');
		if(title.length){
			$(this).wrapInner('<a href="mailto:' + title[0] + '@' + title[1] + '"/>');
		}
		$(this).find('.at').text('@');
	});
};

var gallery = {
	init: function() {
        t = this;
		t.items = $('a.popup_img');
		t.count = t.items.size();
		if (t.count) {
			t.create_popup();
			t.items.click(function(){return t.show_popup($(this));});
		}
	},

	create_popup: function() {
		t.popup_pictures_box = main.popup_box.append();
		t.popup_pictures_box.element.show();
	    $('<div class="header"><h3>'+$('h1').html()+'</h3></div>').appendTo(t.popup_pictures_box.element.find('.content'));
	    if (t.count > 1) {
	    	var scroll_html = '';
			for (var i=0; i<t.count; i++) {
				scroll_html += '<a href="'+t.items.eq(i).attr('href')+'">'+t.items.eq(i).html()+'</a>';
			}
			$('<div class="scroll_left"></div><div class="scroll"><div class="scrollcontent">'+scroll_html+'</div></div><div class="scroll_right">').appendTo(t.popup_pictures_box.element.find('.content'));
		}
	    $('<div class="img"></div>').appendTo(t.popup_pictures_box.element.find('.content'))
		t.popup_pictures_box.element.hide();
		$('.scroll a').click(function(){return t.switch_popup($(this))});
		$('.scroll_left').click(function(){
	        var m = parseInt($('.scrollcontent').css('margin-left'));
			if (m) $('.scrollcontent').animate({marginLeft: (m+100)+'px'}, 'normal', t.hide_arrows(m+100));
			return false;
		});
		$('.scroll_right').click(function(){
	        var m = parseInt($('.scrollcontent').css('margin-left'));
			if (m > (t.count-7)*-100) $('.scrollcontent').animate({marginLeft: (m-100)+'px'}, 'normal', t.hide_arrows(m-100));
			return false;
		});
	},

	show_popup: function(el) {
		if (t.count > 1) t.scroll_select(t.items.index(el));
		t.popup_pictures_box.element.find('.img').html('<img onLoad="gallery.image_size()" src="'+el.attr("href")+'" style="display:none;" />');
		t.popup_pictures_box.element.css({top: (($('html')[0].scrollTop ? $('html')[0].scrollTop : $('body')[0].scrollTop) + 20) + 'px', width: '900px', left: '-450px', margin: '0 0 0 50%'});
		t.popup_pictures_box.open();
		return false;
	},

	switch_popup: function(el) {
		if (t.count > 1) t.scroll_select($('.scroll a').index(el));
		t.popup_pictures_box.element.find('.img').html('<img onLoad="gallery.image_size()" src="'+el.attr("href")+'" style="display:none;" />');
		return false;
	},

	scroll_select: function(ind) {
		$('.scroll a.selected').removeClass('selected');
		$('.scroll a').eq(ind).addClass('selected');
		var m = 0;
		if (ind > 3) {
			if (ind < t.count-3) m = ind-3; else m = t.count-7;
		}
		$('.scrollcontent').css('margin-left', (m*-100)+'px');
		t.hide_arrows(m*-100);
	},

	hide_arrows: function(m){
		if (!m) $('.scroll_left').addClass('hide'); else $('.scroll_left').removeClass('hide');
		if (m <= (t.count-7)*-100) $('.scroll_right').addClass('hide'); else $('.scroll_right').removeClass('hide');
	},

	image_size: function() {
		el = t.popup_pictures_box.element.find('.img img');
		if (el.width() >= 800) el.attr('width', '800');
		el.css('display', 'block');
	}
}

$(function(){
	main.mailto();
	main.geo_select.init();
	if(!$('#home_page')[0]){
		main.navigation.init();
	}
	main.forms.init();
	gallery.init();

	$('#header .logo a').hover(function(){$(this).css('top', '-87px');}, function(){$(this).css('top', '0');});


	var bad_ie = /MSIE (5\.5|6).+Win/.test(navigator.userAgent);
	if($.browser.msie) {
		setTimeout(function(){document.body.className+=' '}, 1000);
	}
	if( bad_ie ){
		$(window).resize(function() {
			resize_content();
		});

		resize_content();

		function resize_content(){
			layout.style.width = ((document.documentElement.clientWidth || document.body.clientWidth) < 1000) ? '1000px' : (((document.documentElement.clientWidth || document.body.clientWidth) > 1400) ? '1400px' : '100%');
		}
	}
	
	if(typeof($(document).pngFix) == 'function') {
   		$('.logo, .i').pngFix( { blankgif:'/i/blank.gif' } );
    	$('.popup_box_close').hover(function(){$(this).addClass('hover')},function(){$(this).removeClass('hover')});
	}	
});


