var lang = (document.location.href.indexOf("/en/") != -1 ? "en" : "ru");

$(document).ready(function(){
	var loading 	= $("#loading");
	var calendar 	= $('#calendar');
	var tags 		= $("#tags");
	var grid 		= $('#video-grid');
	var player 		= $("#player");
	var playerTitle = $("#video-title");
	var playerCtrl 	= $("#video-ctrl");
	var playerTags 	= $("#tags-container");
    var hash        = location.hash.substring(1);
    
    var homeButton  = $('a.video-home');
    var tagsButton  = $('a.video-tags');
    var calendarButton = $('a.video-calendar');
		
	hideAll(); // для начала все скрываем
        
    $('.blur').hint();
    
    function toggleTagsButton(){
        if(tagsButton.hasClass('active')){
            tagsButton.removeClass('active');
        } else {
            tagsButton.addClass('active');
            calendarButton.removeClass('active');
            homeButton.removeClass('active');
        }
    }
    
    function toggleCalendarButton(){
        if(calendarButton.hasClass('active')){
            calendarButton.removeClass('active');
        } else {
            calendarButton.addClass('active');
            tagsButton.removeClass('active');
            homeButton.removeClass('active');
        }
    }
    
    function toggleHomeButton(){
        if(homeButton.hasClass('active')){
            homeButton.removeClass('active');
        } else {
            homeButton.addClass('active');
        }
    }
	
	$('a.has-entries').live('click', function(event){
        calendarDate = $(this).attr('href').substring(10);
		toggleLoading();
		getGrid('calendar/' + calendarDate);
        playerTitle.html('Видеозаписи ' + calendarDate);
		event.preventDefault();
    });
		
	// вешаем эвенты на категории, теги и календарь
	$('a.video-category').click(function(){
		toggleLoading();
		playerTitle.empty();
		$.post($(this).attr('href'), {}, fetchGrid);
		window.location.hash = '';
		return false;
	});
		
	$('a.video-tags').click(function(event){
		showTags();
        window.location.hash = '';
		window.location.hash = '#tags';
        return false;
	});
		
	$('a.video-calendar').click(function(event){
        showCalendar();
        window.location.hash = '';
        window.location.hash = '#calendar';
        return false;
	})
	
	loading.show();
	
	if(hash == 'tags'){
		showTags();
        tagsButton.addClass('active');
		window.location.hash = ''; //нам не нужно чтобы при загрузке страница скролилась до #tags
		window.location.hash = '#tags';
	} else if(hash == 'calendar'){
		showCalendar();
        calendarButton.addClass('active');
		window.location.hash = '';
		window.location.hash = '#calendar';
	} else if(hash.substring(6, 0) == 'video-'){
		getSingleVideo(hash.substring(6));
	} else {
		getGrid('');
        toggleHomeButton();
	}
		
	function toggleLoading(){
		if(loading.is(":hidden")){
			loading.show();
		} else {
			loading.hide();
		}
	}
		
	// прячем все
	function hideAll(){
		tags.hide();
		player.hide();
		playerCtrl.hide();
		playerTags.hide();
		grid.hide();
		loading.hide();
		calendar.hide();
	}
		
	function showTags(){
		if(tags.is(":hidden")){
			toggleLoading();
				
			if(tags.is(":empty")){
				$.post('/video/tags_cloud', {}, function(data){
					hideAll();
					tags.show().html(data);
					playerTitle.html('Облако тегов');
				});
			} else {
				hideAll();
				playerTitle.html('Облако тегов');
				tags.show();
			}
            toggleTagsButton();
		} else {
			return false;
		}
	}
		
	function showCalendar(){
		if(calendar.is(":hidden")){
			toggleLoading();
			
			if(calendar.is(":empty")){
   				$.post('/video/calendar', {}, function(data){
   					hideAll();
   					calendar.show().html(data);
   					playerTitle.html('Видеокалендарь');
   					
   					now = new Date();
   					month = now.getMonth();
       				
       				jQuery.each(calendar.find('#video-calendar table'), function(){
       					table = $(this);
       					tr = table.find("tr");
       					trSize = tr.size();
       					if(trSize < 8){
       						b = 8 - trSize;
       						for(i = b; i > 0; i--){
   				                heading = table.find('th.calendar-heading');
                                heading.html(heading.html());
                                   
       							table.append('<tr><td class="day">&nbsp;</td><td class="day">&nbsp;</td><td class="day">&nbsp;</td><td class="day">&nbsp;</td><td class="day">&nbsp;</td><td class="day">&nbsp;</td><td class="day">&nbsp;</td></tr>');
       						}
       					}
        					
       					table.append("<tr>" + table.find("tr:eq(1)").html() + "</tr>");
       				});
                        
                    calendar.find('#video-calendar').jcarousel({scroll: 1, size: 12, start: month}); 
   				});
			} else {
				hideAll();
				calendar.show();
			}
            toggleCalendarButton();
		} else {
			return false;
		}
	}
	
	// забираем грид видео и показываем
	function getGrid(data){
		$.post((lang != 'ru' ? '/' + lang : '') + '/video/get_grid/' + data, {}, fetchGrid);
	}
	
	function getSingleVideo(video_id){
		$.post('/video/get_one', {'video_id': video_id }, function(data){
			var oAuto = eval("(" + data + ")");
			showPlayer('/video/' + oAuto[0]['large_src'], oAuto[0]['title_' + lang]);
			//playerTags.html(oAuto[0]['tags']);
		});
	}
		
	// рисуем грид с видео
	function fetchGrid(data){
		var oAuto = eval("(" + data + ")");
		var currPreview = $(".video-preview:first");
		
		hideAll();
		
		grid.show();
		//playerTags.empty();
		$(".video-preview").empty();
		
	 	for (var key in oAuto) {
			html = '<a href="#video-' + oAuto[key]['id'] + '" title="' + oAuto[key]['title'] + '" id="videoid-' + oAuto[key]['id'] + '"><img width="235" height="132" src="/images/video-preview/' + oAuto[key]['screenshot'] + '" alt="/video/' + oAuto[key]['large_src'] + '" /></a><div class="hidden-tags">' + oAuto[key]['tags'] + '</div>';
			currPreview.html(html);
			currPreview = currPreview.next('.video-preview');
		}
		$('.hidden-tags').hide();
		
		clickEvent();
	}
		
	// внимание! говорит и показывает плиер
	function showPlayer(video_src, title, tags_container){
		hideAll();
		
		oldPlayerTitle = playerTitle.html();
		
		player.show();
		playerCtrl.show();
			
		flowplayerObj = flowplayer(
			"player", {src: "/flash/flowplayer-3.1.4.swf", wmode: 'opaque'},{
				clip:		{ url: video_src, width: 955 },
				plugins: 	{ controls: null },
				splash: 	{ background: '#fff' },
				canvas:  	{ backgroundGradient: 'none' }
		}).controls("video-ctrl", {duration: 25});
			
		playerTitle.html(title);
		playerCtrl.append('<a href="javascript:void(0)" id="close">close</a>');
		//playerTags.show().html(tags_container);
		
		playerCtrl.find("#close").click(function(){
			flowplayerObj.close();
			player.empty().hide();
			playerTitle.html(oldPlayerTitle);
			playerCtrl.empty().hide();
			//playerTags.empty().hide();
			if(grid.find('div.video-preview:first').is(':empty')){
				toggleLoading();
				getGrid('');
			}
			grid.show();
		});
	}
		
	$("#tags a").live("click", function(){
		toggleLoading();
		playerTitle.empty();
		curr = $(this);
		getGrid('tag/' + curr.attr('href').substring(5));
		playerTitle.show().html('Видео с тегом &laquo;' + curr.html() + '&raquo;');
	});
		
	// эвент выбора видео из грида
	function clickEvent(){
		$('.video-preview a').click(function(){
			curr = $(this);
			showPlayer(curr.find('img').attr('alt'), curr.attr('title'), curr.next("div.hidden-tags").html());
			//playerTags.html($(this).next().html());
		});
	}
});

