/*
 * DOM ready
 */
$(function() {
	$('#overlay-frame').overlayEvents();
	$('#overlay-body dl').tabs();
	$('#works').slider().workHandler();
	$('label.placeholder').overlabel();


	/**
	 * Show login form
	 */

	$('#show-enter-form').click(function() {
		$(this).parent().hide();
		$('#login-form').show();
		return false
	})

});

// Проверяет, поддерживает ли браузер CSS-свойство border-radius.
var isBorderRadiusSupported = function () {
    var s = document.documentElement.style;
    return typeof s.borderRadius === "string" ||
           typeof s.WebkitBorderRadius === "string" ||
           typeof s.KhtmlBorderRadius === "string" ||
           typeof s.MozBorderRadius === "string";
};

document.documentElement.className += isBorderRadiusSupported() ?
        " border-radius" : " no-border-radius";

//Cufon
Cufon.replace('.din');


/*
 * Табы и стрелки в портфолио
 */

$.fn.tabs = function() {
	var t = this;
	if (!t.length) return;

	var overlayFrame = $('#overlay-frame');

	//стрелки
	var btns = $('#prev-btn, #next-btn')
		.live('click',function(/*Event*/e) {
			var t = $(this);
			if (t.hasClass('btn-disabled')) return;


			var dl = $('#overlay-body dl');

			// Вычислим количество страниц и сохраним
			if (!dl.data('count')) {
				var count = dl.children().length/2;
				dl.data('count',count);
			}

			if (/next/.test(this.id))
				tabSwitch(dl.find('dd.active').next(), count || dl.data('count'));
			else
				tabSwitch(dl.find('dt.active').prev().prev(), count || dl.data('count'));

			return false;
		})
		.filter('#prev-btn').addClass('btn-disabled').end();

	//кнопки-табы
	t.live('click', function(/*Event*/e) {
		var dt = $(e.target).closest('dt'),
			$this = $(this);

		// Вычислим количество страниц и сохраним
		if (!$this.data('count')) {
			var count = $this.children().length/2;
			$this.data('count',count);
		}

		if (!dt[0] || dt[0].className === 'active') return;
		tabSwitch(dt, count||$this.data('count'));
	});

	//переключатель
	var tabSwitch = function(obj, count) {
		var thisNum = obj
			.siblings().removeClass('active').end()
			.next().andSelf().addClass('active').end().end().text();

			btns.removeClass('btn-disabled');
			if (thisNum == 1 )
				btns.eq(0).addClass('btn-disabled');
			else if (thisNum == count)
				btns.eq(1).addClass('btn-disabled');

			checkOverlayHeight(overlayFrame)
	}
}

function checkOverlayHeight(overlay) {
		var docHeight = $(document).height();
		if (docHeight > overlay.height())
			overlay.height(docHeight)
	}

$.fn.overlayEvents = function() {
	var overlay = this,
		descrOpened = false;

	// Закрыть портфолио
	function overlayHide() {
		overlay.hide();
		$(document).unbind('keyup');
	}

	// Показать/спрятать описание
	function toggleDescription() {
		overlay.toggleClass('description-on');
		descrOpened = !descrOpened;
	}

	// Показать портфолио
	$('a.portfolio').click(function(/*Event*/e) {
		overlay.show();

		checkOverlayHeight(overlay)

		// Внимаем кнопке ESC
		$(document).bind('keyup', function(e) {
			if (e.which === 27) {
				if (descrOpened) toggleDescription(); // Сначала закроем описание,
				else overlayHide(); 				  // а потом портфолио
			}
		});

		//return false;
	});

	// Закрываем портфолио при клике на затемнении
	overlay.click(function(/*Event*/e) {
		if(e.target.id === 'overlay-frame')
			overlayHide();
	});

	// Вешаем событие "закрыть/раскрыть" описание на нужные элементы
	toggleDesc = $('.toggle-description', overlay)
			.click(function(/*Event*/e) {
				if ($(e.target).closest('.toggle-description')[0])
					toggleDescription();
			})
			.eq(0);

	return overlay;
}

// Слайдер работ
$.fn.slider = function() {
	var $this = this,
		docWidth,
		move,
		k,
		liCount = $this.children().length,
		ulWidth = liCount*75+1;

	$this.parent().css({width:ulWidth, marginLeft:-ulWidth/2})

	$(window).resize(function() {
		docWidth = $(document).width();
	}).resize();

	k = (ulWidth - docWidth)/docWidth;
	function calc(X) {
		return (docWidth/2 - X)*k;
	}

	if (ulWidth > docWidth)
		$this.bind('mouseenter mouseleave mousemove', function(/*Event*/e) {
			var etype = e.type,
				X = e.pageX;

			if (etype === 'mouseenter') {
				$this.stop().animate({left:calc(X)},'slow', function() {
					move = true;
				})

			} else if (etype === 'mouseleave') {
				move = false;
				$this.stop().animate({left:calc(docWidth/2)},'slow');

			} else if (etype === 'mousemove' && move) {
				$this.css({left:calc(X)});
			}

		});

	return $this;
}

$.fn.workHandler = function() {
	var t = this;

	t.click(click);
	t.children('li').eq(0).addClass('active')

	var descTitle = $('#project-description div.body');
	var workLink = $('#project-options a');

	function click(e) {
		var link = $(e.target).closest('a');
		if (!link.length || link.closest('.active').length) return false;
		var dl = $('#overlay-body dl')

		$.get(link[0].href, {}, function(responses) {
			var images = responses.images;
			var newDl = '';
			if (responses.description != "") {
				toggleDesc.show()
				descTitle.show().html(responses.description)
			} else
				toggleDesc.hide()

			workLink
					.attr({
						href:responses.link.href,
						title:responses.link.title
					})
					.text(
						responses.link.text
					)

			var className = ' class="active"'

			newDl+='<dl>'
			for (var img in images) {
				newDl+='<dt'+className+'>'+(parseInt(img)+1)+'</dt><dd'+className+'><img src="'+images[img]+'" alt="" /></dd>'
				className = '';
			}
			newDl+='</dl>'

			dl.replaceWith(newDl)

			link
				.parent().siblings().removeClass('active').end()
				.addClass('active')

			$('#next-btn').removeClass('btn-disabled')
			$('#prev-btn').addClass('btn-disabled')
			checkOverlayHeight($('#overlay-frame'))

		}, 'json')

		return false;
	}

	return t;
}

$.fn.overlabel = function() {
   return this.each(function() {
        var $label = $(this),
            $input = $('#' + $label.attr('for'));

        $input
            .bind('focus blur', function(event) {
                $label.css('display', (event.type == 'blur' && !$input.val() ? '' : 'none'));
            }).trigger('blur');
    });
}


