/**
 * @author Vlad Yakovlev (scorpix@design.ru)
 * @copyright Art.Lebedev Studio (http://www.artlebedev.ru)
 * @version 0.1 (13.04.2009)
 * @requires jQuery
 */

var ie6FixPngImagePath = '/f/1/global/i/0.gif';

jCommon = {

	/**
	 * Создает куки или возвращает значение.
	 *
	 * @example $.cookie('the_cookie', 'the_value');
	 * @desc Задает значение куки.
	 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'site.com', secure: true });
	 * @desc Создает куки с опциями.
	 * @example $.cookie('the_cookie', 'the_value');
	 * @desc Создает куки для сессии.
	 * @example $.cookie('the_cookie', null);
	 * @desc Удаляет куки.
	 * @example $.cookie('the_cookie');
	 * @desc Возвращает значение куки.
	 *
	 * @param String name Имя куки.
	 * @param String value Значение куки.
	 * @param Object options Объект опций куки.
	 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
	 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
	 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
	 *                             when the the browser exits.
	 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
	 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
	 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
	 *                        require a secure protocol (like HTTPS).
	 * @return Значение куки или объект jCommon.
	 * @author Klaus Hartl/klaus.hartl@stilbuero.de
	 */
	cookie: function(name, value, options) {

		if ('undefined' != typeof value) {
			options = options || {};

			if (null === value) {
				value = '';
				options.expires = -1;
			}

			var expires = '';

			if (options.expires && ('number' == typeof options.expires || options.expires.toUTCString)) {
				var date;

				if (typeof options.expires == 'number') {
					date = new Date();
					date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
				} else {
					date = options.expires;
				}

				expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
			}

			// CAUTION: Needed to parenthesize options.path and options.domain
			// in the following expressions, otherwise they evaluate to undefined
			// in the packed version for some reason...
			var path = options.path ? '; path=' + options.path : '';
			var domain = options.domain ? '; domain=' + options.domain : '';
			var secure = options.secure ? '; secure' : '';
			document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');

			return this;
		}

		var cookieValue = null;

		if (document.cookie && '' != document.cookie) {
			var cookies = document.cookie.split(';');

			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);

				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));

					break;
				}
			}
		}

		return cookieValue;
	},


	/**
	 * Объект для работы с другими объектами.
	 */
	object: {

		/**
		 * Копирует свойства и методы одного объекта в свойства и методы другого.
		 * @param {Object} destination Объект, в который копируются свойства.
		 * @param {Object} source Объек, чьи свойства копируются.
		 * @param {Boolean} replace Флаг замены свойства, если оно уже есть.
		 * @return {Object}
		 */
		extend: function(destination, source, replace) {

			for (var i in source) {
				if ((replace || 'undefined' == typeof(destination[i])) && 'undefined' != typeof(source[i])) {
					destination[i] = source[i];
				}
			}

			return destination;
		}
	},

	utils: {
		popupDefaults: {
			height: 600,
			menubar: 'no',
			resizeable: 'yes',
			scrollbars: 'yes',
			status: 'yes',
			toolbar: 'no',
			width: 540
		},

		/**
		 * Создает попап.
		 * @param {String} url Адрес, по которому откроется попап. Если указано изображение, то создается тело документа.
		 * @param {String} name
		 * @param {Object} options
		 * @return {Boolean}
		 */
		popup: function(url, name, options) {
			options = jCommon.object.extend(jCommon.utils.popupDefaults, options, true);

			/** @type {Number} */
			var leftOffset = screen.availWidth / 2 - options.width / 2;
			/** @type {Number} */
			var topOffset = screen.availHeight / 2 - options.height / 2;
			/** @type {Window} */
			var newWindow = window.open(url, '', 'left=' + leftOffset + ', top = ' + topOffset + ', width=' + options.width + ', height=' +
				options.height + ', menubar=' + options.menubar + ', toolbar=' + options.toolbar + ', resizable=' + options.resizeable +
				', scrollbars=' + options.scrollbars + ', status=' + options.status);

			if (url.match(/\.(gif|jpe?g|png)$/i)) {
				newWindow.document.open();
				newWindow.document.write('<html><head>' + ('' != name ? '<title>' + name + '</title>' : '') + '</head><body style="background: #FFF; margin: 0; padding: 0;">' +
					'<table cellpadding="0" cellspacing="0" border="0" width="100%" height="100%"><tr><td align="center">' +
					'<img src="' + url + '" />' + '</td></tr></table></body></html>');
				newWindow.document.close();
			}

			newWindow.focus();

			return false;
		},

		navigationLinks: {
			'start': { keyCode: 0x24 },
			'prev':  { keyCode: 0x25 },
			'up':    { keyCode: 0x26 },
			'next':  { keyCode: 0x27 },
			'down':  { keyCode: 0x28 }
		},

		keyNavigationInit: function() {
			var me = this;

			$('link').each(function() {
				/** @type {String} */
				var rel = $(this).attr('rel');

				if (me.navigationLinks[rel]) {
					me.navigationLinks[rel].href = $(this).attr('href');
				}
			});

			$(document).keydown(function(event) {
				if (!event.ctrlKey) return true;

				var links = jCommon.utils.navigationLinks;

				for (var rel in links) {
					if (links[rel].keyCode == event.keyCode && '' != links[rel].href && undefined !== links[rel].href) {
						document.location = links[rel].href;
					}
				}
			});
		}
	}
};


/**
 * Расширения
 */

jCommon.object.extend(String.prototype, {

	/**
	 * Удаляет тэги.
	 * @return {String}
	 */
	stripTags: function() {
		return this.replace(/<\/?[^>]+>/gi, '');
	},

	/**
	 *
	 * @param {String} groupSeparator
	 * @param {String} fractionSeparator
	 * @return {String}
	 */
	formatNumber: function(groupSeparator, fractionSeparator) {
		var
			groupSeparator = groupSeparator || ' ',
			fractionSeparator = fractionSeparator || ',',
			/** @type {Number} */
			fractionIndex = this.indexOf('.'),
			/** @type {String} */
			fraction = fractionIndex > -1 ? this.substring(fractionIndex + 1) : '',
			/** @type {String} */
			number = fractionIndex > -1 ? this.substring(0, fractionIndex) : this;

		if (5 > number.length) {
			return number + (fractionIndex > -1 ? fractionSeparator + fraction : '');
		}

		var result = '';

		while (3 < number.length) {
			result = number.substring(number.length - 3) + (result.length > 0 ? groupSeparator : '') + result;
			number = number.substring(0, number.length - 3);
		}

		result = number + groupSeparator + result + (-1 < fractionIndex ? fractionSeparator + fraction : '');

		return result;
	}
});

jCommon.object.extend(Number.prototype, {

	/**
	 *
	 * @param {String} groupSeparator
	 * @param {String} fractionSeparator
	 * @return {String}
	 */
	formatNumber: function(groupSeparator, fractionSeparator) {
		return this.toString().formatNumber(groupSeparator, fractionSeparator);
	}
});

$(document.documentElement).addClass('js');

$(function() {

	$('.popup').click(function() {
		return jCommon.utils.popup($(this).attr('href'), '');
	});

	jCommon.utils.keyNavigationInit();
});



jCommon.checkCanvas = function() {
	if ('undefined' != typeof(HTMLCanvasElement)) return true;

	// В IE для VML надо добавить схему и стили.
	if (!document.namespaces['v']) {
		document.namespaces.add('v', 'urn:schemas-microsoft-com:vml');

		var ss = document.createStyleSheet();

		//ss.cssText = 'v\\:* {behavior:url(#default#VML);display:block;}';
		ss.cssText = '.vml {behavior:url(#default#VML);display:block;}';
	}

	return false;
}

jCommon.isCanvas = jCommon.checkCanvas();

if ($.browser.msie) {
	try {
		document.execCommand('BackgroundImageCache', false, true);
	} catch(e) {}

	function fixIePng(element) {
		if (!(/MSIE (5\.5|6).+Win/.test(navigator.userAgent)) || undefined === window.ie6FixPngImagePath) return;

		/** @type {String} */
		var src;

		if ('IMG' == element.tagName || ('INPUT' == element.tagName && 'image' == element.type)) {
			if (/\.png$/.test(element.src)) {
				src = element.src;
				element.src = ie6FixPngImagePath;
			}
		} else {
			src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);

			if (src) {
				src = src[1];
				element.runtimeStyle.backgroundImage = 'none';
			}
		}

		var reScaleMode = /iesizing\-(\w+)/;
		var m = reScaleMode.exec(element.className);

		if (src) {
			var scaleMode = m ? m[1] : 'crop';
			element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='" + scaleMode + "')";
		}
	}
}