
/**
 * @author Julien Fabre [www.j2fs.com]
 * @copyright 2011 J2FS & PixelStudio
 */

$(document).ready(function(){
	
	//pagination
    $("#news-pager").pagination(parseInt($("#total-news").html()), {
        num_edge_entries   : 2,
        num_display_entries: 11,
        callback           : pageSelectNews,
        items_per_page     : 6,
		prev_show_always   : false,
		next_show_always   : false
    });
	
	$("#actualidade-pager").pagination(parseInt($("#total-actualidade").html()), {
        num_edge_entries   : 2,
        num_display_entries: 11,
        callback           : pageSelectLusa,
        items_per_page     : 6,
		prev_show_always   : false,
		next_show_always   : false
    });
	
	$("#favs-pager").pagination(parseInt($("#total-favs").html()), {
        num_edge_entries   : 2,
        num_display_entries: 11,
        callback           : pageSelectFavs,
        items_per_page     : 6,
		prev_show_always   : false,
		next_show_always   : false
    });
	
	$("#vid-archive-pager").pagination(parseInt($("#total-vid-archive").html()), {
        num_edge_entries   : 2,
        num_display_entries: 11,
        callback           : pageSelectVidArchive,
        items_per_page     : 6,
		prev_show_always   : false,
		next_show_always   : false
    });
	
	$("#news-archive-pager").pagination(parseInt($("#total-news-archive").html()), {
        num_edge_entries   : 2,
        num_display_entries: 11,
        callback           : pageSelectNewsArchive,
        items_per_page     : 6,
		prev_show_always   : false,
		next_show_always   : false
    });
	
	// initialize scrollable together with the navigator plugin
	$("#last-videos-widget").scrollable().navigator();
	$("#playlists-widget").scrollable().navigator();
	
	//live ticker
	if($("#prox-directos li").length > 1)
		$("#prox-directos").newsticker();
	
	//do we need to show a video details?
	if(getParameterByName('p')){
		selectNavTab('videos');
		$("#videos-details").show();
		$("#link-arquivo-videos").show();
		$(".pesquisa").css('top', '-25px');
	}
	else{ 
		var n = getParameterByName('n');
		if(n){
			selectNavTab('news');
			displayNews(n);
		}
		else{
			var c = getParameterByName('c');
			var m = getParameterByName('m');
			if(c && m)
				loadVidCatContent(c, m);
			else{
				if(getParameterByName('mustlogin'))
					jAlert('Tem que entrar na sua conta para poder ver v&iacute;deos pertencentes ao arquivo.', 'Login');
			}
		}
	}
	
	//bind the search form behaviors
	$("#formPesquisar").ajaxForm({
		target: "#search-res-content",
		beforeSubmit: validateSearchForm,
		success: onSearchSuccess
	});	
	
	// Fade out the suggestions box when not active
	$("#search").blur(function(){ $('#search-suggestions').fadeOut(); $("#formPesquisar").animate({"width":36},200); });
	
	//newsletter logic
	$("#newsletter-ok").click(function(){
		
		//do we have an email?
		if($("#newsletter-email").val() == '' || $("#newsletter-email").val() == 'Inserir E-mail')
			return false;
	
		$("#newsletter-loader").show();
		$.post('registerToNewsletter.php', { 'email' : $("#newsletter-email").val() }, function(data){
				
			$("#newsletter-loader").hide();
			jAlert(data.msg, data.title);
			
			if(data.title == 'Sucesso')
				$("#newsletter-email").val('');
		}, 'json');
		
		return false;
	});
});

//============================================================================
function getParameterByName(name) {

    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

//============================================================================
function pageSelectNews(page_index, jq){

	$("#news-fb-loader").show();
	$("#news-content").load("getNewsPage.php?page="+(page_index+1), {}, function(){
		$("#news-fb-loader").hide();
	});

    return false;
}

//============================================================================
function pageSelectLusa(page_index, jq){

	$("#actualidade-fb-loader").show();
	$("#actualidade-content").load("getLusaPage.php?page="+(page_index+1), {}, function(){
		$("#actualidade-fb-loader").hide();
	});

    return false;
}

//============================================================================
function pageSelectFavs(page_index, jq){

	$("#favs-fb-loader").show();
	$("#favs-content").load("getFavsPage.php?page="+(page_index+1), {}, function(){
		$("#favs-fb-loader").hide();
	});

    return false;
}

//============================================================================
function pageSelectVidArchive(page_index, jq){

	$("#vid-archive-fb-loader").show();
	$("#vid-archive-content").load("getVideosArchivePage.php?year="+$("#vid-archive-year").val()+"&page="+(page_index+1), {}, function(){
		$("#vid-archive-fb-loader").hide();
	});

    return false;
}

//============================================================================
function vidArchiveChange(){
		
	$("#vid-archive-listing").fadeOut('normal', function(){
		
		$("#main-content-cell").addClass('loading');
		$("#vid-archive-content").load("getVideosArchivePage.php?year="+$("#vid-archive-year").val(), {}, function(){
			
			$("#main-content-cell").removeClass('loading');
			
			//reset pagination
			$("#vid-archive-pager").pagination(parseInt($("#total-vid-archive").html()), {
				num_edge_entries   : 2,
				num_display_entries: 11,
				callback           : pageSelectVidArchive,
				items_per_page     : 6,
				prev_show_always   : false,
				next_show_always   : false,
				fire_initial_event : false
			});
			
			$("#vid-archive-listing").fadeIn('normal');
		});
	});
}

//============================================================================
function pageSelectNewsArchive(page_index, jq){

	$("#news-archive-fb-loader").show();
	$("#news-archive-content").load("getNewsArchivePage.php?year="+$("#news-archive-year").val()+"&page="+(page_index+1), {}, function(){
		$("#news-archive-fb-loader").hide();
	});

    return false;
}

//============================================================================
function newsArchiveChange(){
		
	$("#news-archive-listing").fadeOut('normal', function(){
		
		$("#main-content-cell").addClass('loading');
		$("#news-archive-content").load("getNewsArchivePage.php?year="+$("#news-archive-year").val(), {}, function(){
			
			$("#main-content-cell").removeClass('loading');
			
			//reset pagination
			$("#news-archive-pager").pagination(parseInt($("#total-news-archive").html()), {
				num_edge_entries   : 2,
				num_display_entries: 11,
				callback           : pageSelectNewsArchive,
				items_per_page     : 6,
				prev_show_always   : false,
				next_show_always   : false,
				fire_initial_event : false
			});
			
			$("#news-archive-listing").fadeIn('normal');
		});
	});
}

//============================================================================
function toggleVidSubMenu(){

	$("#link-arquivo-news").hide();
	$("#link-arquivo-videos").show();
	$(".pesquisa").css('top', '-25px');
	if($("#vid-sub-menu").is(':visible')){
		
		$("#vid-sub-menu").slideUp();
	}
	else{
		$("#vid-sub-menu").slideDown();
	}
}

//============================================================================
function selectNavTab(target){

	$("#link-arquivo-news").hide();
	$("#link-arquivo-videos").hide();
	$(".pesquisa").css('top', '-15px');
	if($("#vid-sub-menu").is(':visible'))
		$("#vid-sub-menu").slideUp();
	
	$(".nav_tab_content").hide();
	$(".active_nav_tab").removeClass("active_nav_tab");
	
	$("#"+target+"-content-wrapper").show();
	$("#link-tab-"+target).addClass('active_nav_tab');
	
	$("#tab-arrow").removeClass();
	$("#tab-arrow").addClass('seta_'+target);
	
	if(target == 'news'){
		$("#link-arquivo-news").show();
		$(".pesquisa").css('top', '-25px');
	}
}

//============================================================================
function selectChannelTab(target, id, mother, mom_page){

	$("#link-arquivo-news").hide();
	$("#link-arquivo-videos").hide();
	$(".pesquisa").css('top', '-15px');
	if($("#vid-sub-menu").is(':visible'))
		$("#vid-sub-menu").slideUp();
	
	$(".nav_tab_content").hide();
	$(".active_nav_tab").removeClass("active_nav_tab");
	
	$("#videos-content-wrapper").show();
	$("#link-tab-"+target).addClass('active_nav_tab');
	
	$("#tab-arrow").removeClass();
	$("#tab-arrow").addClass('seta_'+target);
	
	$("#videos-details").hide();
	$("#entidades-details").fadeOut('normal', function(){ $("#entidades-listing").show(); });
	$("#videos-listing").fadeOut('normal', function(){
		
		$("#main-content-cell").addClass('loading');
		$("#videos-content").load("getVideos.php?cat="+id+"&mom="+mother+"&mom_page="+mom_page, {}, function(){
			$("#main-content-cell").removeClass('loading');
			$("#link-arquivo-videos").show();
			$(".pesquisa").css('top', '-25px');
			$("#videos-listing").fadeIn();
			
			//reset the pagination
			$("#videos-pager").pagination(parseInt($("#total-videos").html()), {
				num_edge_entries   : 2,
				num_display_entries: 11,
				callback           : pageSelectVideos,
				items_per_page     : 6,
				prev_show_always   : false,
				next_show_always   : false,
				current_page       : 0,
				fire_initial_event : false
			});
		});
		
		//also load the top views
		$("#videos-top-views").load("getCatTopViews.php?cat="+id);
	});
}

//============================================================================
function backFrom(target){

	$("#"+target+"-details").fadeOut('normal', function(){
		$("#"+target+"-listing").fadeIn();
	});
	
	$("#"+target+"-details-wrapper").fadeOut('normal', function(){
		$("#"+target+"-listing").fadeIn();
	});
}

//============================================================================
function displayNews(id){

	$("#news-listing").fadeOut('normal', function(){
	
		$("#main-content-cell").addClass('loading');
		$("#news-details").load("getNewsDetails.php?id="+id, {}, function(){
			$("#main-content-cell").removeClass('loading');
			$("#news-details").show();
			
			//attach the pirobox behavior
			$().piroBox_ext({
				piro_speed  : 900,
				bg_alpha    : 0.1,
				piro_scroll : true //pirobox always positioned at the center of the page
			});
		});
	});
}

//============================================================================
function displayNewsFromSearch(id){

	selectNavTab('news');
	displayNews(id);
}

//============================================================================
function displayLusa(key){

	key = key.replace(' ', '_');
	
	$("#actualidade-listing").fadeOut('normal', function(){
	
		$("#main-content-cell").addClass('loading');
		$("#actualidade-details").load("getLusaDetails.php?key="+key, {}, function(){
			$("#main-content-cell").removeClass('loading');
			$("#actualidade-details").show();
		});
	});
}

//============================================================================
function displayLusaFromShortcut(key){

	selectNavTab('actualidade');
	displayLusa(key);
}

//============================================================================
function selectWidgetTab(target){

	$(".widget_tab_content").hide();
	$(".active_widget_tab").removeClass('active_widget_tab');
	$("#"+target+"-widget-wrapper").show();
	$("#"+target+"-widget-tab").addClass('active_widget_tab');
}

//============================================================================
//dir: 0 (up in the tree - back) | 1 (down the tree - into a category)
function loadVidCatContent(id, mother, mom_page, dir){
	
	$("#videos-details").hide();
	$("#entidades-details").fadeOut('normal', function(){ $("#entidades-listing").show(); });
	$("#videos-listing").fadeOut('normal', function(){
		selectNavTab('videos');
		$("#main-content-cell").addClass('loading');
		$("#videos-content").load("getVideos.php?cat="+id+"&mom="+mother+"&mom_page="+mom_page, {}, function(){
			$("#main-content-cell").removeClass('loading');
			$("#link-arquivo-videos").show();
			$(".pesquisa").css('top', '-25px');
			$("#videos-listing").fadeIn();
			
			//reset the pagination
			$("#videos-pager").pagination(parseInt($("#total-videos").html()), {
				num_edge_entries   : 2,
				num_display_entries: 11,
				callback           : pageSelectVideos,
				items_per_page     : 6,
				prev_show_always   : false,
				next_show_always   : false,
				current_page       : (dir == 0 ? (mom_page - 1) : 0),
				fire_initial_event : false
			});
		});
		
		//also load the top views
		$("#videos-top-views").load("getCatTopViews.php?cat="+id);
	});
}

//============================================================================
function videosOrderingChange(){

	pageSelectVideos(parseInt($("#videos-pager .pagination .current").html()) - 1);
}

//============================================================================
function pageSelectVideos(page_index, jq){

	$("#videos-fb-loader").show();
	$("#videos-content").load("getVideos.php?cat="+$("#videos-cat").html()+"&mom="+$("#videos-mother").html()+"&page="+(page_index+1)+"&order="+$("#videos-order").val()+"&mom_page="+(page_index+1), {}, function(){
		$("#videos-fb-loader").hide();
	});

    return false;
}

//============================================================================
function moreVideosOrderingChange(cat){

	$("#more-vids-fb-loader").show();
	$("#more-videos-wrapper").load('getMoreVideos.php?cat='+cat+'&order='+$("#more-vids-order").val(), {}, function(){ $("#more-vids-fb-loader").hide(); });
}

//============================================================================
function loadEntityCats(id){

	$("#entidades-listing").fadeOut('normal', function(){
		selectNavTab('entidades');
		$("#main-content-cell").addClass('loading');
		$("#entidades-details").load("getEntitiesCats.php?ent="+id, {}, function(){
			$("#main-content-cell").removeClass('loading');
			//$("#entidades-listing").fadeIn();
			
			//reset the pagination
			$("#entidades-pager").pagination(parseInt($("#total-entidades").html()), {
				num_edge_entries   : 2,
				num_display_entries: 11,
				callback           : pageSelectEntitiesCats,
				items_per_page     : 6,
				prev_show_always   : false,
				next_show_always   : false
			});
			$("#entidades-details").show();
			$("#entidades-details-wrapper").show();
			
			//also load the top views
			$("#entidades-top-views").load("getEntityTopViews.php?ent="+id);
		});
	});
}

//============================================================================
function loadEntityCatsFromSearch(id){
	
	selectNavTab('entidades');
	loadEntityCats(id);
}

//============================================================================
function entitiesCatsOrderingChange(){

	pageSelectEntitiesCats(parseInt($("#entidades-pager .pagination .current").html()) - 1);
}

//============================================================================
function pageSelectEntitiesCats(page_index, jq){

	$("#entidades-fb-loader").show();
	$("#entidades-details").load("getEntitiesCats.php?ent="+$("#entidades-id").html()+"&page="+(page_index+1)+"&order="+$("#entidades-order").val(), {}, function(){
		$("#entidades-fb-loader").hide();
	});

    return false;
}

//============================================================================
function addToFavs(id){

	$("#link-add-favs").hide();
	$("#status-add-favs").show();
	$("#icon-add-favs").hide();
	$("#icon-add-favs-loading").show();
	$.post("addToFavs.php?vid="+id, function(data) {
		$("#status-add-favs").html(data);
		$("#icon-add-favs-loading").hide();
		$("#icon-add-favs-ok").show();
		pageSelectFavs(parseInt($("#favs-pager .pagination .current").html()) - 1);
	});
}

//============================================================================
function delFav(id){

	$("#del-fav-"+id).hide();
	$("#del-fav-load-"+id).show();
	$.post("delFav.php?vid="+id, function(data) {
		pageSelectFavs(parseInt($("#favs-pager .pagination .current").html()) - 1);
	});
}

//============================================================================
function validateSearchForm(formData, jqForm, options){
	
	var form = jqForm[0]; 
    
	//make sure all fieds are filled up
	if (!form.search.value || form.search.value.length < 3 || form.search.value == 'Procurar') { 
		//jAlert('Tem que escrever alguma coisa com pelo menos 3 caracteres.', 'Pesquisa');
        return false; 
    }
	
	$("#search-res-content").html('');
	$("#main-content-cell").addClass('loading');
	selectNavTab('search-res');
	$("#search").val('');

	return true;
}

//============================================================================
function onSearchSuccess(result){

	$("#main-content-cell").removeClass('loading');
}

//============================================================================
function startPlayer(){
	
	$("#player-pic").hide();
	$("#media").show();
}

//============================================================================
function playerReady(obj) {

	if(!getParameterByName('p') && !getParameterByName('code')){
		player = document.getElementById(obj['id']);
		player.sendEvent('PLAY');
	}
}

//============================================================================
function lookup(inputString){

	if(inputString.length < 3)
		$('#search-suggestions').fadeOut(); // Hide the suggestions box
	else{
	
		$.post("getSuggestions.php", {search: ""+inputString+""}, function(data){
		
			$('#search-suggestions').html(data);
			$('#search-suggestions').fadeIn();
		});
	}
}

//============================================================================
function displayLive(id){

	$(".active_nav_tab").removeClass("active_nav_tab");
	$(".nav_tab_content").fadeOut('normal', function(){
	
		$("#main-content-cell").addClass('loading');
		$("#live-details").load("getLiveDetails.php?id="+id, {}, function(){
			$("#main-content-cell").removeClass('loading');
			$("#live-content-wrapper").show();
			$("#live-details").show();
		});
	});
}

