var sLang = $("html").attr("siteLang");

(function()
{
	window.$c = {};
	$(document.documentElement || document.body).attr('class', 'js');
})();

if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent)) {
	try{ document.execCommand("BackgroundImageCache", false, true); } catch(e) {}
}

function fixPNG(element, scale_mode)
{
	if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent)) {
		var src;


		scale_mode = scale_mode || 'crop';

		if (element.tagName == 'IMG') {
			if (/\.png$/.test(element.src)) {
				src = element.src;
				element.src = "/f/1/global/i/px.gif";
			}
		} else {
			src = element.currentStyle.backgroundImage
					.match(/url\("(.+\.png)"\)/i)
			if (src) {
				src = src[1];
				element.runtimeStyle.backgroundImage = "none";
			}
		}

		var re_scale_mode = /iesizing\-(\w+)/;
		var m = re_scale_mode.exec(element.className);
		if (m) {
			scale_mode = m[1];
		}


		if (src)
			element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"
					+ src + "',sizingMethod='" + scale_mode + "')";
	}
}

/**
 * @author John Resig (http://jquery.com/), Vlad Yakovlev (red.scorpix@gmail.com)
 * @version 1.0
 */
$c.browser = (function() {
	var userAgent = window.navigator.userAgent.toLowerCase();

	return {
		version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
		webkit: /webkit/.test(userAgent),
		opera: /opera/.test(userAgent),
		msie: /msie/.test(userAgent) && !/opera/.test(userAgent),
		mozilla: /mozilla/.test(userAgent ) && !/(compatible|webkit)/.test(userAgent),
		safari: /safari/.test(userAgent) && !/chrome/.test(userAgent),
		chrome: /chrome/.test(userAgent)
	};
})();


$c.webkitPlaceholder = function()
{
	if ($c.browser.webkit) return { bind: $.noop };

	$(function() {
		$('input[placeholder]').each(function () {
			bind(this);
		});
	});

	/**
	 * Добавляет функцию плейсхолдера элементу.
	 * @param {String|Array[Element]|Element|jQuery} els Поля ввода
	 * @param {String} [class_empty = 'empty'] Класс для пустого поля ввода
	 */
	function bind(els, classEmpty) {
		els = $(els);
		classEmpty = ('string' === typeof classEmpty) ? classEmpty : 'empty';

		els.focus(function () {
			if (this.value === $(this).attr('placeholder')) {
				this.value = '';
			}

			$(this).removeClass(classEmpty);
		});

		els.blur(function () {
			if (!this.value.length) {
				this.value = $(this).attr('placeholder');
				$(this).addClass(classEmpty);
			}
		});

		els.each(function() {
			$(this).val().length || $(this).blur();
		});
	}

	return {
		/**
		 * Вручную добавляет функцию плейсхолдера элементу.
		 * @param {String|Array[Element]|Element|jQuery} elem Поле ввода.
		 * @param {String} [class_empty] Класс для пустого поля ввода.
		 */
		bind: bind
	};
}();

/**
 * Объект для работы с клавиатурными сокращениями.
 *
 * @example
 * jCommon.shortcuts.unbind('next');
 * jCommon.shortcuts.bind('prev', 'http://ya.ru', 0x24, true);
 *
 * @version 1.0
 * @date 2009-08-11
 */
$c.shortcuts = (function()
{
	var navigationLinks = {
		'start': { keyCode: 0x24, ctrlKey: true, altKey: false },
		'prev':  { keyCode: 0x25, ctrlKey: true, altKey: false },
		'up':    { keyCode: 0x26, ctrlKey: true, altKey: false },
		'next':  { keyCode: 0x27, ctrlKey: true, altKey: false },
		'down':  { keyCode: 0x28, ctrlKey: true, altKey: false }
	};

	$(function() {
		$('link').each(function() {

			var rel = $(this).attr('rel');

			if (navigationLinks[rel]) {
				navigationLinks[rel].href = $(this).attr('href');
			}
		});

		$(document).keydown(function(event) {
			var links = navigationLinks;

			for (var rel in links) {
				if (links[rel].keyCode == event.keyCode && links[rel].ctrlKey == event.ctrlKey && links[rel].altKey == event.altKey) {
					if (!$('input:focus, textarea:focus').length) {
						if ('string' == typeof links[rel].href && '' != links[rel].href) {
							document.location = links[rel].href;
						} else if ($.isFunction(links[rel].href)) {
							return links[rel].href(event);
						}
					}
				}
			}
		});
	});

	return {
		/**
		 * Привязывает к шорткату клавиатуры действие.
		 * @param {String} name Тип действия.
		 * @param {String|Function} href Если строка, то осуществлять переход по адресу, если функция, то выполнить функцию (первый параметр — объект Event).
		 * @param {Number} keyCode Код нажатой клавиши.
		 * @param {Boolean} [ctrlKey] Нажат ли <code>Ctrl</code>.
		 * @param {Boolean} [altKey] Нажат ли <code>Alt</code>.
		 */
		bind: function(name, href, keyCode, ctrlKey, altKey) {
			ctrlKey = new Boolean(ctrlKey);
			altKey = new Boolean(altKey);

			navigationLinks[name] = {
				href: href,
				keyCode: keyCode,
				ctrlKey: ctrlKey,
				altKey: altKey
			};
		},

		/**
		 * Удаляет действие для шортката.
		 * @param {String} name Тип действия.
		 */
		unbind: function(name) {
			delete navigationLinks[name];
		},

		/**
		 * Удаляет все шорткаты.
		 */
		unbindAll: function() {
			navigationLinks = {};
		}
	};
})();

var MiniPage = $.inherit(
{
	__constructor: function(jContainer)
	{
		this.jContainer = jContainer;
		this.iTopInitial = (this.jContainer.position()).top;
		this.iOffset = this.jContainer.offset().top - this.iTopInitial - 100;
		this.jRoot = $(window);
		
		this.jitterBuffer = 10; //anti-jitter buffer, actually. Set to 0 when not using animation.
		this.timeOutId = 0;

		this.jRoot.scroll(function(){
			this.catchScroll();
		}.scope(this));
	},

	catchScroll: function() //Debounce
	{
		var self = this; //for setTimeout, 'this' always refers to the window
		if (self.timeOutId) clearTimeout (self.timeOutId);
		self.timeOutId = setTimeout(function(){self.doScroll();}, self.jitterBuffer);
	},
	
	doScroll: function()
	{
		jTweener.removeTween(this.jContainer);
		
		var iScroll = this.jRoot.scrollTop();
		if ( iScroll > this.iOffset )
		{
			var iTop = iScroll-this.iOffset+this.iTopInitial;
		}
		else
		{
			var iTop = this.iTopInitial;
		}
		
		$t(this.jContainer).tween({
			top: iTop
		});
		//this.jContainer.css('top', iTop + 'px');
	}
});

if (/Opera/.test (navigator.userAgent)) //для суровых норвежских браузеров
{
	var randomnumber=Math.floor(Math.random()*1000000);
	var fontstyle = $('<style></style>');
	var style = '@font-face {font-family: \'HeliosLightRegular' + randomnumber + '\'; src: local(\'☺\'), url(\'/f/1/global/css/helioslight-webfont.ttf\') format(\'truetype\');}';
	style += ' .site-menu>ul>li>a, .site-menu>ul>li>b, .site-menu>ul li .shadow{font-family:\'HeliosLightRegular' + randomnumber + '\',Arial,Helvetica,sans-serif !important;}';
	fontstyle.html(style).appendTo('head');
}

var FaqLike = $.inherit(
{
	__constructor: function(oParams)
	{

		var jjHead = $(oParams.headSelector)
			.wrapInner('<span class="pseudo"></span>')
			.click(function(e,action)
			{
				action = action || 'toggle';
				$(this).nextUntil(oParams.untilSelector)[action]('normal');
			})
			.click();
	}
});

$(document).ready(function(){
	$('.shadowed a, .shadowed b, dt.shadowed').each(function(){
		var jShadow = $(this).find('.shadow');
		if(jShadow.length > 0 && jShadow.html().length == 0)
		{
			var sNode = $(this).text();
			jShadow.html(sNode);
		}
	});
});
