destVideos = {
	load: function(url) {
		$.getJSON(url, function(data){
			destVideos.build(data);
		});
	},

	build: function(data) {
		estilo="bxEsq";
		$("#ltmDestaques").html('');
		$.each(data.data, function(i, val) {
			dt = val.publicationDate.split("T")[0].split("-");
			url_vid = location.protocol + "//" + location.host + "/" + location.pathname.split('/')[1] + "/" + val.json_video_url;
			chapeu = val.subtitle == "" ? getCateg.cat[val.category_id] : val.subtitle ;
            exibDesc = val.views != 1 ? "exibi&ccedil;&otilde;es" : "exibi&ccedil;&atilde;o" ;
			$("#ltmDestaques").append('<div class="blocoVideo ' + estilo + '"> <a href="' + url_vid + '"><div class="imgVideo"><img width="143" height="80" border="0" src="' + val.thumbnail + '"/><div class="tempoVideo">' + formatDuration(val.duration) + ' </div></div><div class="textoVideo"><h3>' + chapeu + '</h3><h2><b>' + val.title + '</b></h2><p class="dataVideos">' + dtExt(dt[0]+'/'+dt[1]+'/'+dt[2]) +'</p><p><span class="bold333">' + val.views + '</span> ' + exibDesc + '</p></div></a></div>');
			if (i==1) {$("#ltmDestaques").append('<div style="width:590px;float:left;" class="sepHorz"></div>')}
			estilo = (estilo == "bxEsq" ) ? "bxDir" : "bxEsq"; 
		} )
	}
		
}

listVideos = {
	load: function(url,obj) {
		$.getJSON(url, function(data){
			listVideos.build(data,obj);
		});
	},

	build: function(data,trg) {

		$("#"+trg).html('');
		
		$.each(data.data, function(i, val) {
			if(i>0) $("#"+trg).append('<div class="sepHorz"></div>') ;
			dt = val.publicationDate.split("T")[0].split("-");
			url_vid = location.protocol + "//" + location.host + "/" + location.pathname.split('/')[1] + "/" + val.json_video_url;
			chapeu = val.subtitle == "" ? getCateg.cat[val.category_id] : val.subtitle ;
            exibDesc = val.views != 1 ? "exibi&ccedil;&otilde;es" : "exibi&ccedil;&atilde;o" ;
			$("#"+trg).append('<div class="blocoVideo"> <a href="' + url_vid + '"><div class="imgVideo"><img width="143" height="80" border="0" src="' + val.thumbnail + '"/><div class="tempoVideo">' + formatDuration(val.duration) + ' </div></div><div class="textoVideo"><h3>' + chapeu + '</h3><h2><b>' + val.title + '</b></h2><p class="dataVideos">' + dtExt(dt[0]+'/'+dt[1]+'/'+dt[2]) +'</p><p><span class="bold333">' + val.views + '</span> ' + exibDesc + '</p></div></a></div>');
		} )
	}
}



listCategoria = {
	catStart: "",
	parentStart: "",
	url: "",
	data: "",
	load: function(url){
		listCategoria.url = url
		$.getJSON(listCategoria.url, function(data){
			listCategoria.data = data
			listCategoria.build()
		});
	},
	build: function() {
		$('#listaCategorias').html('')
		$('#listaCategorias').append('<ul>')
		$.each(listCategoria.data, function(i, val) {
			if (val.total_videos>0) {
				$('#listaCategorias').append('<li>' + val.description + '</li>')
			}
		});
		$('#listaCategorias').append('</ul>')
		$('#atCol1 .navMenu .menuSecoes').click(function() {
			$('#atCol1 .navMenu li').css({'background-color' : '#FFF', 'color' : '#000'})
			$(this).css({'background-color' : '#5595b6', 'color' : '#FFF'})
			if(!$(this).parent().hasClass("float_menu")) {
				$('#atCol1 .navMenu .float_menu').css({'display': 'none'})
				$('#' + this.value).css({'display': 'block'})
			}
			$('#listTitleSection').html(this.title)
			shVideos.load('/mediacenter/json/medias?category='+this.value+'&callback=?')
			$('#ltmNoticias').html('Carregando...')
		})
		if (listCategoria.parentStart != "") { $('#m_' + listCategoria.parentStart).trigger('click')}
		$('#m_' + listCategoria.catStart).trigger('click')
	}
}


shVideos = {
	vidStart: 0,
	vidEnd: 0,
	totVideos: 0,
	espacos: 5,
	url: "",
	data: "",
	query: "",
    sizeBlock: 6,
	currBlock: 1,
	totBlocks: 0,
	paginaTotal: 1,
	paginaAtual: 1,
	

	load: function(url) {
		shVideos.url = url
		$('#lstVideos').html('Carregando...')
		$('#pageControl').html('')
		$("#ltCountIni").html('')
		$("#ltCountEnd").html('')
		$("#ltCountVideos").html('')

		$.getJSON(this.url, function(data){
			shVideos.data = data.data ;
			shVideos.totVideos = data.total_medias ;
			shVideos.build() ;
		});
	},
	
	build: function() {
		$('#pageControl').html('')
		$('#lstVideos').html('')

		shVideos.paginaTotal = Math.ceil(shVideos.totVideos/shVideos.espacos)
		shVideos.totBlocks = Math.ceil(shVideos.paginaTotal / shVideos.sizeBlock)
		
        $("#ltCountVideos").html(shVideos.totVideos)
		
		if (shVideos.totVideos<1) {
			$("#ltCountIni").html("")
			$("#ltCountEnd").html("")
			$('#lstVideos').html('Nenhum v&iacute;deo encontrado.') 
		} else {
			shVideos.formatVideo()
			shVideos.mkPageControl(shVideos.paginaAtual)
		}

	},


    mkPageControl: function(pag) {

		$("#ltCountIni").html(shVideos.vidStart + 1)
		$("#ltCountEnd").html(shVideos.vidEnd)

		if (shVideos.paginaTotal < 2) return 
        
		$('#pageControl').html('<p>')
		
		startPage = (shVideos.currBlock * shVideos.sizeBlock) - shVideos.sizeBlock 
		endPage = (shVideos.currBlock * shVideos.sizeBlock)
		
		if (shVideos.currBlock > 1)
				$('#pageControl').append('<a href="javascript:shVideos.gotoBlock(' + (shVideos.currBlock - 1) + ');"><b>menos</b></a> | ' );

		
		for (i=0;i<shVideos.paginaTotal;i++) {
		   if ( ( i >= startPage ) && (i < endPage ) ) {
				status = (pag == i + 1) ? 'class="selected"' : '' ;
				$('#pageControl').append('<a ' + status + ' href="javascript:shVideos.gotoPage(' + (i + 1) + ');"><b>' + (i + 1) + '</b></a>' );
	           if (i < shVideos.paginaTotal - 1 ) $('#pageControl').append(' | ') ;
		   }

		}

		if (shVideos.currBlock < shVideos.totBlocks) 
			$('#pageControl').append('<a href="javascript:shVideos.gotoBlock(' + (shVideos.currBlock + 1) + ');"><b>mais</b></a>' );
		

		$('#pageControl').append('</p><div class="sepHorz"></div>');

	},

   gotoBlock: function(block) {
       shVideos.currBlock = block ;
	   shVideos.gotoPage( (block * shVideos.sizeBlock) - (shVideos.sizeBlock - 1) ) 

   },

   gotoPage: function(n) {
		shVideos.paginaAtual = n 
		shVideos.vidStart = (n - 1) * shVideos.espacos  ;
        shVideos.vidEnd = shVideos.vidStart ;
		$('#lstVideos').html('') ;
		shVideos.load('/mediacenter/json/medias?start=' + shVideos.paginaAtual + '&limit=5' + shVideos.query + '&callback=?')
		shVideos.mkPageControl(n)
	},

    formatVideo: function() {
		
		$.each(shVideos.data, function(i, val) {
			dt = val.publicationDate.split("T")[0].split("-");
			url_vid = location.protocol + "//" + location.host + "/" + location.pathname.split('/')[1] + "/" + val.json_video_url; 
			chapeu = val.subtitle == "" ? getCateg.cat[val.category_id] : val.subtitle ;
            exibDesc = val.views != 1 ? "exibi&ccedil;&otilde;es" : "exibi&ccedil;&atilde;o" ;
			$('#lstVideos').append('<div class="blocoVideo"><a href="' + url_vid + '"><div class="imgVideo"><img width="143" height="80" border="0" src="' + val.thumbnail + '"/><div class="tempoVideo">' + formatDuration(val.duration) + '</div></div><div class="textoVideo"><h3>' + chapeu + '</h3><h2><b>' + val.title + '</b></h2><p class="dataVideos">' + dtExt(dt[0]+'/'+dt[1]+'/'+dt[2]) + '</p><p><span class="bold333">' + val.views + '</span> ' + exibDesc + '</p></div></a></div>') 
			$('#lstVideos').append('<div class="sepHorz"></div>');
			shVideos.vidEnd = shVideos.vidEnd + 1 ;
		})
	
	}
}


dtExt = function(dtNum) {
  var Meses     = new Array("Janeiro","Fevereiro","Mar&ccedil;o","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro");
  nwDate = new Date(dtNum) ;
  return (nwDate.getDate() + " de " + Meses[nwDate.getMonth()].toLowerCase() + " de " + nwDate.getFullYear());
}

getVideos = function (idCat, desc, item) {
	if (idCat!=0){
		showMsg('cat', desc);
	    shVideos.query="&category="+idCat;
		shVideos.gotoPage(1);
    } else {
        $('#msgVideos').html('');
		shVideos.query="";
		shVideos.gotoPage(1);
	}
    chColor(item) ; 	
}

getVideosByTag = function (tag, desc) {
    chColor(-1) ; 
	document.location.href = "#navVideos";
	shVideos.query="&tag="+tag;
	shVideos.gotoPage(1);
	showMsg('tag', desc);
}

getTagByMenu = function (tag, desc, item) {
    getVideosByTag(tag, desc);
    chColor(item) ; 
}


chColor = function (item) {
    $("#opMenu a").each ( function (i) { 
       ( i == item ) ? $(this).addClass("categoriaSelected") : $(this).removeClass("categoriaSelected");
	} )    
}

replaceLink = function (id) {
   $(id + ' a').each ( function() { 
	   tag=this.href.substring(this.href.lastIndexOf("/") + 1);
       this.href="javascript:getVideosByTag('" + tag + "', '" + this.innerHTML + "')"; 
       this.innerHTML = this.innerHTML + ((id == ".tagsVideos") ? " "  : "") ;
    } )
}

showMsg = function(type, msg) {
    tAux = type == 'tag' ? "pela TAG " : "por " ;
	$('#msgVideos').html('<div class="sepHorz" style="width:270px"></div>');
	$('#msgVideos').append('<p>Resultados da busca ' + tAux + '<b>' + msg.toUpperCase() + '</b></p>');
}

altText = function() {
    document.getElementById('boxBusca').value = '' ;
}

searchVideo = function () {
    shVideos.query = "&title=" + document.getElementById('boxBusca').value + "" ;
    showMsg('cat', document.getElementById('boxBusca').value);
	shVideos.gotoPage(1);
}

formatDuration = function (val) {
	 return (val.substring(val.indexOf(':')+1));
}

getCateg = {
    cat:[],
	load: function() {
		$.getJSON("/mediacenter/json/categories?listchildren=true", function(data){
			$.each(data, function(i, val) {
				getCateg.cat[val.id]=val.name ;
			})
		});
	}
}

getCateg.load();

$(document).ready(function() {


	destVideos.load("/mediacenter/json/medias?highlighted=true&limit=4&callback=?")

	listVideos.load("/mediacenter/json/medias?limit=4&callback=?","ltmRecent")

	listVideos.load("/mediacenter/json/medias?order=views&limit=4&callback=?","ltmVistos")

	getVideos(0,'',0)
	replaceLink('.listaTags');
	replaceLink('.tagsVideos');
});


