var openedTab = null;

window.onload = function() {
	mediaTabsInit();
}

var mediaTabsInit = function() {
	var tabs = $('.mt-tab');
	var tabsHeight = $('.mt-container').height() * tabs.length;
	var tabOverlayWidth = $('.mt-overlay').width();

	drawTabs(tabs, tabsHeight);
	triggerTabs(tabs, tabOverlayWidth);

	$(window).resize(function() {
		drawTabs(tabs, tabsHeight);
		var windowHeight = $(window).height();
		var infoBoxHeight = $('#info_box').height();
		ytHeight = windowHeight - 35 - 230 - infoBoxHeight - 240;
		$('#upload_conteiner_yt').css('height', ytHeight);
	});
}

var drawTabs = function(tabs, tabsHeight) {
	var container = $(window);
	var tabsTopPosition = centerize(tabsHeight, container);

	tabs.each(function() {
		var tabContainer = $(this).find('.mt-container');
		var tabLabel = tabContainer.find('img');
		// setting top position of tab container
		tabContainer.css('top', tabsTopPosition + 'px');
		tabsTopPosition += tabContainer.height();
		tabLabel.css('top', centerize(tabLabel.height(), tabContainer) + 'px');
	});

	$('.mt-container').css('visibility', 'visible');
}

var triggerTabs = function(tabs) {
	tabs.each(function() {
		var tabId = this.id;
		var overlay = $(this).find('.mt-overlay');
		var container = $(this).find('.mt-container');

		$(this).find('.mt-tab-controls').hover(function() {
			$(this).addClass("mt-open");
		}, function() {
			$(this).removeClass("mt-open");
		});

		$(this).find('.mt-tab-controls, .mt-close, .mt-twitter-close').click(function() {
			tabOpenCloseCallback(tabId, overlay, container);
		});
	});
}

var tabOpenCloseCallback = function(id, overlay, container) {
	if (isTabOpened(id)) {
		closeTab(overlay, container);
	} else {
		openTab(id, overlay, container);
	}
}

var centerize = function(elementsHeight, container) {
	return Math.round(container.height() / 2) - Math.round(elementsHeight / 2);
}

var isTabOpened = function(id) {
	if (openedTab == id)
		return true;
	return false;
}

var openTab = function(id, overlay, container) {
	openedTab = id;
	overlay.animate({left: 0});
	container.animate({left: overlay.width()}, function() {
		container.addClass('mt-open');
	});
}

var closeTab = function(overlay, container) {
	openedTab = null;
	overlay.animate({left: -(overlay.width())});
	stopOnClose();
	container.animate({left: 0}, function() {
		container.removeClass('mt-open');
	});
}
