/** 
 * @projectDescription Listagem de vídeos do UOL Mais via API. Depende de video-lib.js e markup preparado.
 *
 * @author  Iraê Carvalho  (irae@irae.por.br / aut_icarvalho@uolinc.com)
 * @version 1.0 RC1
 * @since   Primeira versão do script
 * @since   Chama a API do UOL Mais, escreve o HTML e adiciona eventos para exibição e funcionamento da lista de vídeos
 */
 
/////////////////////////////////////
//            Init Vars            //
/////////////////////////////////////

/**
 * Objeto em escopo global que descreve a paginação atual .
 * @type {Object}
 * @param {Int} currentPage Página atual
 * @param {Int} totalPages Número total de páginas para esta busca
 * @param {Int} totalItems Número total de mídias nessa busca
 * @param {Int} pageSize Número de resultados da busca a cada páginana 
 * @param {Int} previousPage Número da página anterioror ou null se buscou a primeira página
 * @param {Int} nextPage Número da próxima página ou null quando se buscou a última página
 * @param {String} sort Ordenação da busca atual
 */
var paging = {
	currentPage: _GET('currentPage') || 1,
	totalPages: 1,
	totalItems: 0,
	pageSize: _GET('itemsPerPage') || 6,
	previousPage: null,
	nextPage: null,
	sort: _GET('sort') || "mostRecent"
};
/**
 * Objeto em escopo global que complementa a paginação em buscas por palavra-chave
 * @type {Object}
 * @param {Int} start Número de itens a pular na busca usado para paginar.
 * @param {Int} num Número total de mídias por página para esta busca
 */
var search = {
	start : _GET('start') || 1,
	num : _GET('num') || paging.pageSize
};

/**
 * Pode ser usada para mudar o tipo de markup da lista.
 * @type {String}
 */
var outputListsType = outputListsType || 'default';


/////////////////////////////////////
//     General functionality       //
/////////////////////////////////////


/**
 * Inicia a listagem de vídeos e faz a primeira chamada à API do UOL Mais
 * @type {Function}
 * @return {null}
 */
initMediaList = function () {
	var $ = jQuery;
	if(outputListsType == 'resume') {
		search.num = paging.pageSize = 4;
	}
	$('#mediasearch [name="q"]').val(!_GET('q')?'':_GET('q'));
	if(_GET('q')) {
		getMediasBySearch(_GET('q'), 'drawMediaList');
	} else {
		getMediasByMultipleTags(list_tags, 'drawMediaList');
	}
	seUolMaisMorrer = setTimeout(function(){
		var $ = jQuery;
		console.debug('morreu o uolmais, mostrando cache');
		drawMediaList = function(){void(null);};
		$('.cachedContent').removeClass("hidden");
		$('#corpo .showOnlyOnLoading').remove();
	}, 5000); // Timeout de 5 segundos sugerido pelo UOL Mais
};

/**
 * Corrige o objeto global 'paging' em casos de API irregular
 * @type {Function}
 * @return {null}
 */
 fixUnstandardPaging = function () {
	paging.totalItems = paging.totalItems || paging.totalResults;
	paging.previousPage = (paging.previousPage<1)?null:paging.previousPage;
	paging.nextPage = (paging.nextPage>paging.totalPages)?null:paging.nextPage;
};

/**
 * Verifica o carregamento do Frame antes de executar o reload
 * @type {Function}
 * @param {string} frameName Nome da frame a ser recarregada
 * @return {null}
 */
reloadFrame = function(frameName){
	if(frames[frameName].location.protocol == 'http:')
		frames[frameName].location.reload();
	else
		setTimeout(function(){
			reloadFrame(frameName);
		},500);
};

/**
 * Chamada no callback da API do UOL Mais para renderizar o HTML e adicionar eventos de uma listagem de vídeos.
 * @type {Function}
 * @param {Object} data Objeto do UOL Mais contendo todos os resultados dessa página de vídeos
 * @return {null}
 */
drawMediaList = function(data){
	var $ = jQuery;
	//console.debug('listagem uol mais');
	//console.dir(data);
	//console.info('resporta via JS - '+(new Date()).getUTCSeconds()+','+(new Date()).getUTCMilliseconds());
	clearTimeout(seUolMaisMorrer);
	$('.showOnlyOnLoading').remove();
	$('.cachedContent').remove();
	startTabs();
	//console.debug(data); 
	if(!data.length) {
		$('#mediaList td').html(messageNoResult);
	} else {
		$('#mediaList tbody').empty();
	}
	$('#results > h2').remove();
	if(outputListsType!='resume') {
		if(typeof(UOLData.videosByMultipleTagsPaging) =='function') paging = UOLData.videosByMultipleTagsPaging();
		if(typeof(UOLData.videosBySearchPaging) =='function') paging = UOLData.videosBySearchPaging();
		fixUnstandardPaging();
		$('#results ul.tabs').before(MARKUP.listTitle.apply(paging));
		var paginghtml = MARKUP.paging.apply(paging);
	}
	$('#mediaList').before(paginghtml).after(paginghtml);
	for(var i=0;i<data.length;i++) {
		data[i].publishedAt = data[i].publishedAt || '9999-01-01 00:00:00'; // busca despadronizada
		$('#mediaList').append(MARKUP.mediaItem.apply(data[i]));
	}
	if(outputListsType=='resume') adjustFrame();
};

/**
 * Acerta o tamanho de um iframe que contém chamadas para a API do UOL Mais.
 * @type {Function}
 * @return {null}
 */
adjustFrame = function() {	var $ = jQuery;
	var myFrame = $('#dontExist');
	try {
		var myFrame = $('#iframeMoreMedias', top.document);
	} catch(e) {void(null);}
	if(myFrame.size()) {
		// Timeout for IE
		if($('body').height() < 300) {
			setTimeout(adjustFrame,500);
		} else {
			myFrame.height($('body').height());
		}
	}
};


/**
 * Reescreve os endereços dos links das tabs de uma listagem de vídeo baseando-se no query string
 * @type {Function}
 * @return {null}
 */
// tabs (chamados no markup)
startTabs = function () { var $ = jQuery;
	var loc = document.location.search.toString();
	if(_GET('q')!=false) {
		$('#results .tabs li').not(':first').remove();
	}
	$('#results .tabs li').each(function() {
		//console.debug(getLink('tab',this.className));
		$('a',this).attr('href', getLink('tab',this.className).replace('&amp;', '&'));
		if(loc.match(this.className)){
			$('#results .tabs .'+this.className).addClass('active');
		}
	});
	if($('#results .tabs .active').size() == 0) {
		$('#results .tabs li:first').addClass('active');
	}
	$('#results .tabs').removeClass('hidden');
};

/////////////////////////////////////
// on Document Load call init funcion
/////////////////////////////////////

jQuery(initMediaList);

/////////////////////////////////////
// isolated markup for code cleaness
/////////////////////////////////////

/**
 * Constroe HTML de título para uma lista de vídeos baseado no objeto "paging" global
 * @type {Function}
 * @return {String} HTML com descrição dos resultados da listagem atual
 */
MARKUP.listTitle = function() {
	var messageNoResult = "Nenhum vídeo foi encontrado."; 
	// require object 'this' to be the paging info
	if(_GET('q')) {
		var html = '<h2>A busca "'+_GET('q')+'" '+((this.totalItems==0)?"não":'')+' teve '+((this.totalItems>0)?this.totalItems:'')+' resultado'+((this.totalItems!=1)?'s':'')+'.</h2>';
	} else if (_GET('tagName')) {
		var html = '<h2>'+((this.totalItems>0)?this.totalItems:'Nenhum')+' video'+((this.totalItems>1)?'s':'')+' com a tag '+_GET('tagName')+'.</h2>'
	} else {
		var html = '<h2>'+((this.totalItems>0)?this.totalItems:'Nenhum')+' video'+((this.totalItems>1)?'s':'')+' publicado'+((this.totalItems>1)?'s':'')+'.</h2>'
	}
	return html;
};

/**
 * Constroe HTML de uma linha da lista de vídeos. Usar .apply para que o escopo seja um objeto de video UOL Mais
 * @type {Function}
 * @return {String} HTML de um vídeo no modo listagem
 */
MARKUP.mediaItem = function() { var $ = jQuery;
	// require the object 'this' to be the media info
	var isComplte = (outputListsType=='default')?true:false;
	if(lastDate < parseDate(this.publishedAt)) {
		var url = medialistURL.replace(/\/[^\/]*$/,'/')+'assistir.jhtm?media='+this.id;
	} else {
		var url = (this.id.length>50)?this.id.substr(0,50):this.id;
		url = medialistURL.replace(/\/[^\/]*$/,'/')+this.publishedAt.toString().replace(/([0-9]{4})-([0-9]{2})-([0-9]{2}).*/, "$1/$2/$3/")+url+'.jhtm';
	}
	var html = '<tr>\
		<td class="imagem"><a target="top" href="'+url+'" target="_top"><img src="'+this.thumbnail+'-medium.jpg" /></a></td>\
		<td class="descricao">\
			<dl>\
				<dt class="title"><a href="'+url+'" target="_top"><strong>'+this.title+'</strong> ('+this.duration+')</a></dt>\
				<dd class="description">'+this.description+'</dd>';
				if(isComplte) {
					html += '<dd class="tags">Tags: ';
					html += MARKUP.tags.apply(this.tags);
					html += '</dd>';
				}
				html += '\
			</dl>\
		</td>';
		if(isComplte) {
		html+='\
		<td class="props">\
			<dl>';
				html += (this.publishedAt&&this.publishedAt!='9999-01-01 00:00:00')?'<dd class="date">Publicação: '+this.publishedAt.toString().replace(/([0-9]{4})-([0-9]{2})-([0-9]{2}).*/, "$3/$2/$1")+'</dd>':'';
				html += (this.rating!=null)?'<dd class="rating">Avaliação: <img  class="rateimg" src="http://cr.i.uol.com.br/uolmais/small-'+((Math.round(this.rating*2)/2)).toString().replace('.','')+'.gif" alt="Nota: '+this.rating+'" title="Nota: '+this.rating+'" /></dd>':'';
				html += (this.views!=null)?'<dd class="views">Visitas: <strong>'+this.views+'</strong></dd>':'';
				html += (this.favorites!=null)?'<dd class="views">Favoritos: <strong>'+this.favorites+'</strong></dd>':'';
				html += (this.comments!=null)?'<dd class="comments">Comentários: <strong>'+this.comments+'</strong></dd>':'';
				html += '\
			</dl>\
		</td>';
		}
		html+='\
	</tr>';
	return html;
};


