var userAgent = navigator.userAgent.toLowerCase(), jCommon = {};
jQuery.browser = {
	version: (userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1],
	chrome: /chrome/.test( userAgent ),
	safari: /webkit/.test( userAgent ) && !/chrome/.test( userAgent ),
	opera: /opera/.test( userAgent ),
	msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
	mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};
jCommon.browser = jQuery.browser;
jCommon.measurer = (function() {

	var
		callbacks = [],
		interval = 500,
		curHeight,
		el,
		isInit = false,
		isDocReady = false;

	jQuery(function() {
		isDocReady = true;
		isInit && initBlock();
	});

	function initBlock() {
		el = jQuery('<div></div>').css({
			height: '1em',
			left: 0,
			lineHeight: '1em',
			margin: 0,
			position: 'absolute',
			padding: 0,
			top: '-1em',
			visibility: 'hidden',
			width: '100%'
		}).appendTo('body');

		/**
		 * В IE событие <code>onresize</code> срабатывает и на элементах.
		 */
		if (jCommon.browser.msie) {
			el.resize(callFuncs);
			return;
		}

		/**
		 * Для остальных браузеров периодически проверяем изменение размера текста.
		 */
		curHeight = el.height();
		setInterval(function() {
			var newHeight = el.height();

			if (newHeight != curHeight) {
				curHeight = newHeight;
				callFuncs();
			}
		}, interval);
		jQuery(window).resize(callFuncs);
	}

	function callFuncs() {
		for(var i = 0; i < callbacks.length; i++) {
			callbacks[i]();
		}
	}

	return {
		/**
		 * Ручная инициализация события изменения размеров элементов на странице.
		 */
		resize: callFuncs,

		/**
		 * Добавляет обработчик события.
		 * @param {Function} func Ссылка на функцию, которую нужно выполнить.
		 */
		bind: function(func) {
			if (!el) {
				isInit = true;
				isDocReady && initBlock();
			}

			callbacks.push(func);
		},

		/**
		 * Удаляет обработчик события.
		 */
		unbind: function(func) {
			for(var i = 0; i < callbacks.length; i++) {
				callbacks[i] == func && callbacks.splice(i, 1);
			}
		}
	};
})();

var navigation = {
	init:function(o) {
		this.calculate(o);
	},
	calculate:function(o) {
		if(o) {
			this.selected = {pos:false};
			
			this.o = jQuery(o);
			this.items = jQuery("a,b,span", this.o);
			
		}
		jQuery("ins", this.o).remove();
		var that = this,
			items = this.items,
			top = items.eq(0).offset().top,
			t;
		that.num_rows = 0;
		that.rows = [];
		items.each(function(i, o){
			t = items.eq(i+1).offset().top;
			if(jQuery(this).data("row", that.num_rows).is(".selected")) that.selected = {pos:jQuery(this).data("row"), o:jQuery(this)};
			if( i == items.length -1 || t != top ) {
				top = t;
				++that.num_rows == 0 || that.rows[that.rows.push({
					f:that.rows.length ? that.rows[that.rows.length-1].l+1 : 0,
					l:i,
					_w:function() {
						var t = this;
						return this.w || function(f, l) {
							function get_width(o) { var t = jQuery(o); return t.width()+parseInt(t.css("paddingLeft"))+parseInt(t.css("paddingRight")); }
							var s = 0;
							jQuery(that.items).slice(f, l+1).each(function(i, o){
								s =jQuery(this).data("pos",{s:s,e:s+get_width(this)}).data("pos").e;
							});
							return t.w = s;
						}(this.f, this.l);
					}
				})-1]._w();
			}
		});
		that.draw();
	},
	draw:function() {
		var that = this;
		
		function corners(o, empty_sides) {
			var t = jQuery(o);
			if(t.is(".selected")) {
				if(!empty_sides.l && !empty_sides.t.l) t.append('<ins class="tl"></ins>');
				if(!empty_sides.r && !empty_sides.t.r) t.append('<ins class="tr"></ins>');
				if(!empty_sides.l && !empty_sides.b.l) t.append('<ins class="bl"></ins>');
				if(!empty_sides.r && !empty_sides.b.r) t.append('<ins class="br"></ins>');
			} else {
				if(empty_sides.l && empty_sides.t.l) t.append('<ins class="tl"></ins>');
				if(empty_sides.r && empty_sides.t.r) t.append('<ins class="tr"></ins>');
				if(empty_sides.l && empty_sides.b.l) t.append('<ins class="bl"></ins>');
				if(empty_sides.r && empty_sides.b.r) t.append('<ins class="br"></ins>');
			}
		}
		
		this.items.each(function(i, o){
			corners(this, {
				t:function(o) {
					var r = jQuery(o).data("row"),
						ret = {l:true,r:true};
					if(r && (ret.l || ret.r)) {
						ret.l = ret.l && that.rows[--r].w < jQuery(o).data("pos").s
							? true 
							: jQuery(o).data("row")-r<2 && that.selected.pos === r
								? that.selected.o.data("pos").s <= jQuery(o).data("pos").s && that.selected.o.data("pos").e >= jQuery(o).data("pos").s
									? true
									: false
								: false;
						ret.r = ret.r && that.rows[r].w < jQuery(o).data("pos").e
							? true
							: jQuery(o).data("row")-r<2 && that.selected.pos === r
								? that.selected.o.data("pos").s <= jQuery(o).data("pos").e && that.selected.o.data("pos").e >= jQuery(o).data("pos").e
									? true
									: false
								: false;
					}
					return ret;
				}(this),
				r:function(o) {
					if(!jQuery(o).next("a,b,span")[0] || jQuery(o).next("a,b,span").eq(0).offset().top != jQuery(o).offset().top || jQuery(o).next().is(".selected")) return true;
					return false;
				}(this),
				b:function(o) {
					var l = that.rows.length-1,
						r = l-jQuery(o).data("row"),
						ret = {l:true,r:true};
					if(r && (ret.l || ret.r)) {
						ret.l = ret.l && that.rows[l-(--r)].w < jQuery(o).data("pos").s
							? true 
							: l-r-jQuery(o).data("row")<2 && that.selected.pos === l-r
								? that.selected.o.data("pos").s <= jQuery(o).data("pos").s && that.selected.o.data("pos").e >= jQuery(o).data("pos").s
									? true
									: false
								: false;
						ret.r = ret.r && that.rows[l-r].w < jQuery(o).data("pos").e
							? true
							: l-r-jQuery(o).data("row")<2 && that.selected.pos === l-r
								? that.selected.o.data("pos").s <= jQuery(o).data("pos").e && that.selected.o.data("pos").e >= jQuery(o).data("pos").e
									? true
									: false
								: false;
					}
					return ret;
				}(this),
				l:function(o) {
					if(!jQuery(o).prev("a,b,span")[0] || jQuery(o).prev("a,b,span").eq(0).offset().top != jQuery(o).offset().top || jQuery(o).prev().is(".selected")) return true;
					return false;
				}(this)
			});
		});
	}
}

jQuery(function() {
	jQuery('html').addClass(
		(jQuery.browser.mozilla && jQuery.browser.version >= '1.9.1')
		|| (jQuery.browser.opera && parseFloat(jQuery.browser.version)>=9.8)
		|| (jQuery.browser.safari && !jQuery.browser.chrome)
			? 'with_fontface'
			: 'without_fontface'
		).addClass('js');

	jQuery('html').addClass(jQuery.browser.msie ? 'ie' : (jQuery.browser.opera ? 'opera' : (jQuery.browser.mozilla ? 'firefox' : (jQuery.browser.safari ? 'safari' : (jQuery.browser.chrome ? 'chrome' : 'undefined')))));
	jQuery('html').addClass('v'
		+(jQuery.browser.mozilla 
			? (jQuery.browser.version>='1.9.1' 
				? '3_5'
				: parseInt(jQuery.browser.version))
			: (jQuery.browser.opera 
				? (parseInt(jQuery.browser.version)>=10 
					? '10' 
					: parseInt(jQuery.browser.version))
				: parseInt(jQuery.browser.version)
			)
		)
	);

	jQuery(".rounded_blue > div, .rounded_green > div").eq(0).append('<ins class="t"></ins><ins class="r"></ins><ins class="b"></ins><ins class="l"></ins>');
	
	if(!(jQuery.browser.msie && parseInt(jQuery.browser.version) < 7)) {
		navigation.init("#navigation div.reducer p");
		jCommon.measurer.bind(function(){navigation.calculate("#navigation div.reducer p")});
		jQuery("#subnavigation ul.navigation li.selected:last").each(function(){
			var o = jQuery('a,b', this).eq(0);
			o.html('<span>'+o.text().replace(/ /gi, '</span><span>')+'</span>');
			jQuery('span:eq(0)', o).addClass('f');
			
			navigation.init(o);
			jCommon.measurer.bind(function(){navigation.calculate(o)});
		});
	}
	jQuery('#languages span').click(function(){
		if(jQuery('#languages').is(".show_languages")) {
			jQuery('#languages').removeClass("show_languages");
			jQuery('#shadow_layer').remove();
		} else {
			jQuery('#languages').addClass("show_languages");
			jQuery('<div></div>').attr({
				id:'shadow_layer'
			}).height(jQuery('#layout').height()).click(function(){
				jQuery('#languages').removeClass("show_languages");
				jQuery(this).remove();
			}).appendTo('#layout');
		}
	});
	
});
function shownhide (objName) {
  if ( $(objName).css('display') == 'none' ) {
    $(objName).animate({height: 'show'}, 400);
  } else {
    $(objName).animate({height: 'hide'}, 200);
  }
}
