/**
 * @author Stepan Reznikov (stepan.reznikov@gmail.com)
 * @copyright Art.Lebedev Studio (http://www.artlebedev.ru)
 */

var Layout = {

	/**
	 * Добавляет внутрь элемента elem уголки.
	 * Если elem не является элементом, то используется this.
	 * 
	 * @param {Element} elem Элемент в который нужно добавить уголки
	 * @param {String} [prefix] Префикс для имен классов уголоков
	 */

	wrapInCorners: function (elem, prefix) {
		elem = (elem && elem.nodeType) ? elem : this;
		prefix = (typeof prefix === 'string') ? prefix + '_' : '';

		$(elem)
			.append('<ins class="' + prefix + 'cn ' + prefix + 'tl"><ins /></ins><ins class="' + prefix + 'cn ' + prefix + 'tr"><ins /></ins>')
			.append('<ins class="' + prefix + 'cn ' + prefix + 'bl"><ins /></ins><ins class="' + prefix + 'cn ' + prefix + 'br"><ins /></ins>');
	},


	/**
	 * Эмулирует поведение input типа search как в Сафари.
	 * Если elem не является элементом, то используется this.
	 * 
	 * @param {Element} elem Поле ввода
	 * @param {String} [classEmpty] Класс для пустого поля ввода
	 */

	makePlaceholder: function (elem, classEmpty) {
		elem = (elem && elem.nodeType) ? elem : this;

		if ($(elem).attr('type') !== 'search') {

			classEmpty = (typeof classEmpty === 'string') ? classEmpty : 'empty';
			var placeholder = $(elem).attr('placeholder');
	
			$(elem).focus(function () {
				if (this.value === placeholder) {
					this.value = '';
					$(this).removeClass(classEmpty);
				}
			});
	
			$(elem).blur(function () {
				if (!this.value.length) {
					this.value = placeholder;
				}
				if (this.value === placeholder) {
					$(this).addClass(classEmpty);
				}
			});
	
			$(elem).blur();
		}
	}
};


Layout.ResizeableImage = function (elem, parent) {
	this.elem = $(elem);
	this.parent = $(parent);
	this.loaded = false;
	var that = this;

	if (this.elem.attr('complete')) {
		this.onLoad();
	}
	else {
		var image = document.createElement('img');
		image.onload = function () {
			that.onLoad();
		};
		image.src = this.elem.attr('src');
	}
};

Layout.ResizeableImage.prototype = {

	onLoad: function () {
		this.loaded = true;
		// Показываем картинку (изначально display: none)
		this.elem.show();
		// Запоминаем размер картинки
		this.width = this.elem.attr('width');
		this.height = this.elem.attr('height');
		// Ставим картинке нормальный position (изначально position: absolute)
		this.elem.css('position', 'static');
		// Фиксим размер
		this.checkWidth();
	},

	checkWidth: function () {
		if (this.loaded) {
			if (this.parent.width() <= this.width) {
				this.elem.addClass('resized_horizontal');
			}
			else {
				this.elem.removeClass('resized_horizontal');
			}
		}
	}
};


Layout.ResizeableImageController = {

	images: [],

	init: function (selectors) {

		var i, blocks;
		var that = this;

		for (i = 0; i < selectors.length; i++) {
			blocks = $(selectors[i]);
			blocks.each(function () {
				var block = this;
				var imgs = $(block).find('img');
				imgs.each(function () {
					// Создаем для каждой картинки объект
					// Сохраняем все объекты в массив, чтобы контроллер знал о всех
					that.images.push(new Layout.ResizeableImage(this, block));
				});
			});
		}

		// Навешиваем событие ресайза окна
		$(window).resize(function () {
			for (i = 0; i < that.images.length; i++) {
				that.images[i].checkWidth();
			}
		});

	}
};


// DOM has finished loading and is ready to be operated on
$(function () {
	$('#j_username').focus();
	$('.corners').each(Layout.wrapInCorners);
	$('input[placeholder]').each(Layout.makePlaceholder);
	Layout.ResizeableImageController.init(['.posts .post .summary', '.posting .content']);
});