$(document).ready(function() {
	tvlist_get_base_layout();
});

function tvlist_get_base_layout()
{
	$("#list-layout").html('<center><img src="/webroot/delivery/img/loadingAnimation.gif" alt="Загрузка..." /></center>');
	$("#list-layout").load("/channel-tro/tv-guide/data/tpl-tvlist_layout/",
		{},
		function() { tvlist_get_scheldule_layout(0); }
	);
}

var tvlist_layouts = new Array();
var calendar_layouts = new Array();
function tvlist_get_layout(set_date)
{
	$("#list-layout").html('<center><img src="/webroot/delivery/img/loadingAnimation.gif" alt="Загрузка..." /></center>');
	
	if(typeof tvlist_layouts[set_date] != 'undefined') {
		$("#list-layout").html(tvlist_layouts[set_date]);
		tvlist_get_scheldule_layout(0); 
		return;
	} 
	
	$("#list-layout").load("/channel-tro/tv-guide/data/tpl-tvlist_layout/", {date: set_date},
		function() {
			tvlist_layouts[set_date] = $("#list-layout").html()
			tvlist_get_scheldule_layout(0); 
		}
	);
}

function tvlist_get_scheldule_layout(pos)
{
	$('#tvlist-tabs li.selected').removeClass('selected');
	$('#tab-'+pos).addClass('selected');
	$("#scheldule").html('<center><img src="/webroot/delivery/img/loadingAnimation.gif" alt="Загрузка..." /></center>');
	if(pos != 'all')
	{
		$("#scheldule").load("/channel-tro/tv-guide/data/tpl-tvlist_scheldule_layout/", {position: pos});
	}
	else
	{
		$("#scheldule").load("/channel-tro/tv-guide/data/tpl-tvlist_scheldule_layout_all/");
	}
}

function tvlist_show_calendar()
{
	$("div.calendar-popup").html('<div id="tvlist_calendar_loading" style="float: right;"><img src="/webroot/delivery/img/loadingAnimationCalendar.gif" alt="Загрузка..." /></div>');
	$("div.calendar-popup").show(200);
	$("div.calendar-popup").load("/channel-tro/tv-guide/data/tpl-tvlist_calendar_layout/",{}, function(){
		$(document).bind('mousedown', {cal: $("div.calendar-popup"), trigger: this}, tvlist_hide_calendar);
	});
}

function isChildOf(parentEl, el, container) 
{
	if (parentEl == el) {
		return true;
	}
	if (parentEl.contains) {
		return parentEl.contains(el);
	}
	if ( parentEl.compareDocumentPosition ) {
		return !!(parentEl.compareDocumentPosition(el) & 16);
	}
	var prEl = el.parentNode;
	while(prEl && prEl != container) {
		if (prEl == parentEl)
			return true;
		prEl = prEl.parentNode;
	}
	return false;
}			

function tvlist_hide_calendar(ev) {
	if (ev.target != ev.data.trigger && !isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
		$("div.calendar-popup").hide();
		$(document).unbind('mousedown', tvlist_hide_calendar);
	}
};

function tvlist_show_date_calendar(set_date)
{
	$("div.calendar-popup").html('<div id="tvlist_calendar_loading" style="float: right;"><img src="/webroot/delivery/img/loadingAnimationCalendar.gif" alt="Загрузка..." /></div>');
	$("div.calendar-popup").show(200);
	$("div.calendar-popup").load("/channel-tro/tv-guide/data/tpl-tvlist_calendar_layout/",{date: set_date});
}