/** 
 * @projectDescription Página de um vídeo 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 página de um vídeo.
 */


/**
 * Inicia a visualização de um vídeo e faz a primeira chamada à API do UOL Mais
 * @type {Function}
 * @return {null}
 */
initMediaView = function() { var $ = jQuery;
	setTimeout(function(){
		UOLData.videosMediaComplete = null;
		jQuery('.cachedContent').removeClass("hidden");
		jQuery('#corpo .showOnlyOnLoading').remove();
	}, 5000); // Teimeout de 5 segundos sugerido pelo UOL Mais
	UOLData.videosMediaComplete = function(data) {drawMedia(data);};
	getMedia(mediaId);
};

/**
 * Chamada no callback da API do UOL Mais para renderizar o HTML de um vídeo e adicionar eventos das interações. Também faz a chamada à API para os comentários.
 * @type {Function}
 * @param {Object} data Objeto do UOL Mais contendo todas as informações de um vídeo
 * @return {null}
 */
drawMedia = function(data) { var $ = jQuery;
	// store some variables
	data = data[0];
	window.cachedMedia = data;
	selfName = data.title;
	selfUrl = medialistURL+data.id;
	$('.cachedContent').removeClass("hidden");
	$('.showOnlyOnLoading').addClass('hidden');
	// get the comments asyncronouslly
	UOLData.videosCommentsComplete = drawComments;
	getComments(data.mediaId, 1);
	commentsTimeout = setTimeout(function(){
		UOLData.videosCommentsComplete = function(){void(null);};
	}, 5000);
	// draw and modify the content
	document.title = data.title + ' - ' + document.title;
	$('#videoActions, #otherMedias').removeClass('hidden');
	$('#videoWrapper h4').html(data.publishedAt.toString().replace(/([0-9]{4})-([0-9]{2})-([0-9]{2}).*/, "$3/$2/$1"));
	$('#videoWrapper h2').html(data.title);
	$('#videoViwer').html(MARKUP.media.apply(data));
	$('#videoStats').html(MARKUP.mediaStats.apply(data));
	$('#videoInfo').html(MARKUP.mediaInfo.apply(data));
	$('#mediaExtras').append($('#comments'));
	// Add events for interaction
	$('#reportAbuse').click(abuseClick);
	$('#videoActions .favorite a').click(favoriteClick);
	$('#videoActions .friend') .click(mailtoClick);
	$('#commentForm').submit(commentSubmit);
	voteInit();
};

/**
 * Chamada no callback da API do UOL Mais para renderizar o HTML de comentários e adicionar eventos da paginação.
 * @type {Function}
 * @param {Object} data Objeto do UOL Mais contendo os comentários de um vídeo
 * @return {null}
 */
drawComments = function(data) { $ = jQuery;
	$('#comments .media-nav').remove();
	if($('#comments').parents('#commentsPlace').length != 1) $('#comments').appendTo('#commentsPlace');
	clearTimeout(commentsTimeout);
	//console.dir(data);
	if(data.length == 0) {
		$('.showOnCommentsLoading').remove();
		$('.noComments').removeClass('hidden');
		return;
	}
	commentsPaging = UOLData.videosCommentsPaging();
	commentsPagingMarkup = MARKUP.paging.apply(commentsPaging);
	$('#commentsContent').empty().before(commentsPagingMarkup).after(commentsPagingMarkup);
	$('#comments .media-nav a') .click(function() {
		getComments(window.cachedMedia.mediaId, this.href.match(/currentPage=([0-9]+)/)[1]);
		return false;
	});
	for(var i=0;i<data.length;i++) {
		$('#commentsContent').append(MARKUP.comment.call(data[i],i+1));
	}
};

commentSubmit = function(){
	addComment();
	return false;
};

addComment = function() { $ = jQuery;
	console.info('addComment');
	$('#commentForm .msg-mini').remove();
	$('#commentForm').append('<p class="msg-mini wait-mini">Salvando...</p>')
	UOLData.onError = addCommentError;
	postComment(window.cachedMedia.mediaId, $('#commentText').val(), 'addCommentSuccess');
};

// Essa função antigamente estava no 'UOLData.onError' da função 'addComment' mas agora está obsoleto.
// Mantendo apenas por LEGADO
addCommentResponse = function(data) {
	// UOL Mais ainda não está com API de comentários funcionando OK e é necessário checar um tipo de erro pra ver se foi sucesso
	//console.debug(data);
	if( data.length && (data[1] == 'TAI-W0001' || data[0][1] == 'TAI-W0001')) {
		addCommentSuccess();
	} else {
		addCommentError();
	}
};

addCommentSuccess = function() {
	console.info('sucesso ao comentar');
	$('#commentForm .msg-mini').remove();
	$('#commentForm').append('<p class="msg-mini ok-mini">Comentário salvo com sucesso.</p>')
	$('#commentText').val('');
};

addCommentError = function() {
	console.info('erro ao comentar -> login');
	$('#commentForm .msg-mini').remove();
	TB_login('Pava comentar, é necessário estar autenticado',medialistURL+'_action_done.jhtm?callback=addComment');
};

voteInit = function() { var $ = jQuery;
	voteNote = null;
	$('#voteForMedia').appendTo('#votePlace');
	//TB_show('Adicionar voto', 'TB_inline?height=200&width=400&inlineId=voteContainer', null);
	$('#voteForMedia ul a')
		.click(addVote)
		.hover(function() {
			jQuery(this).parents('ul:eq(0)').attr('className', this.id);
		}, function() {
			jQuery(this).parents('ul:eq(0)').attr('className', 'star0');
		});
	return false;
};

addVote = function() { var $ = jQuery;
	try{this.blur();}catch(e){void(null)};
	if(window.voteNote == null) {
		window.voteNote = $('span',this).html();
		$(this).parents('ul:first').find('a').unbind();
		$('<p class="msg-mini wait-mini">&nbsp;</p>')
			.css({left:($(this).offset().left-$('#voteForMedia').offset().left)+'px',right:'inherit'})
			.appendTo('#voteForMedia');
	} else {
		$('<p class="msg-mini wait-mini">&nbsp;</p>')
			.appendTo('#voteForMedia');
	}
	UOLData.onError = voteError;
	postVote(cachedMedia.mediaId, voteNote, 'voteSuccess');
	return false;
};

voteError = function () {
	console.info('erro ao votar -> login');
	$('#voteForMedia .msg-mini').remove();
	TB_login('Pava votar, é necessário estar autenticado',medialistURL+'_action_done.jhtm?callback=addVote');
};

voteSuccess = function() { var $ = jQuery;
	console.info('sucesso ao votar');
	$('#voteForMedia .msg-mini').removeClass('wait-mini').addClass('ok-mini');
	//$('#voteForMedia').append('<p class="msg-mini ok-mini">&nbsp;</p>');
	setTimeout(function(){TB_remove();$('#voteForMedia .msg-mini').remove();},1500);
};

favoriteClick = function() {
	favVisibility = null;
	TB_show('Adicionar aos favoritos', 'TB_inline?height=200&width=400&inlineId=favContainer', null);
	return false;
};

addFavorite = function() { var $ = jQuery;
	if(favVisibility == null) {
		favVisibility = $('#TB_ajaxContent input:checked').val();
	}
	$('#TB_ajaxContent').html('<div class="message"><p class="msg wait">Aguarde. Salvando favorito...</p></div>');
	UOLData.onError = favoriteError;
	postFavorite(mediaId, favVisibility, 'favoriteSucess');
};

favoriteError = function() {
	console.info('erro ao adicionar favorito -> login');
	TB_login('Pava adicionar aos favoritos, é necessário estar autenticado',medialistURL+'_action_done.jhtm?callback=addFavorite');
};

favoriteSucess = function () { var $ = jQuery;
	console.info('sucesso favorito');
	$('#TB_ajaxContent').html('<div class="message"><p class="msg ok">Favorito salvo com sucesso.</p></div>');
	setTimeout(function(){TB_remove();},1500);
};

mailtoClick = function() {
	TB_show('Indicar para amigos', medialistURL+'_action_mailto.jhtm?videoName='+selfName+'&videoURL='+selfUrl+'&#TB_iframe=true&height=305&width=420', null);
	return false;
};

mailtoSuccess = function () { var $ = jQuery;
	console.info('sucesso mailto');
	$('#TB_window iframe').wrap('<div id="TB_ajaxContent"></div>');
	$('#TB_ajaxContent').html('<div class="message"><p class="msg ok">E-mail enviado com sucesso.</p></div>');
	setTimeout(function(){TB_remove();},1500);
};

abuseClick = function() {
	top.location.href = 'http://denuncia.uol.com.br/?PaginaDenunciada='+document.location.href;
	return false;
};


jQuery(document).ready(initMediaView);

// Markup functions


MARKUP.media = function() {
	var src = this.storage+'/'+((flashFullScreen)?'player':'embed')+'.swf?path='+this.filePath+'&amp;id='+this.fileID+'&amp;host='+this.storage+'&amp;mediaId='+this.id+'&amp;start_loading=true&amp;start_paused=false&amp;show_related=false';//&amp;debug=true';
	var html = '\
		<object width="100%" height="100%">\
			<param name="movie" value="'+src+'"></param>\
			<param name="allowfullscreen" value="true"></param>\
			<param name="wmode" value="transparent"></param>\
			<param name="quality" value="best"></param>\
			<embed width="100%" height="100%" allowfullscreen="true" wmode="transparent" quality="best" src="'+src+'"></embed>\
		</object>\
	';
	return html;
};

MARKUP.comment = function(index) {
	var isFirst = (index==1)?'class="first"':'';
	var html = '\
	<dl '+isFirst+'>\
		<dt><a href="'+this.authorPage+'">'+this.author+'</a></dt>\
		<dd class="text">'+this.description+'</dd>\
		<dd class="date">'+this.publishedAt.replace(/([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/i, "$3/$2/$1, $4:$5h")+'</dd>\
	</dl>\
	';
	return html;
}

MARKUP.mediaStats = function() {
	var html = '\
	<ul>\
		<li class="rating">Nota: <img  class="rateimg" src="http://ec.i.uol.com.br/uolmais/small-'+((Math.round(this.rating*2)/2)).toString().replace('.','')+'.gif" alt="Nota: '+this.rating+'" title="Nota: '+this.rating+'" /></li>\
		<li class="rate"><span>Dê sua nota:</span><span id="votePlace"></span></li>\
		<li class="audience">Visitas: <strong>'+this.views+'</strong></li>\
		<li class="favorites">Favoritos: <strong>'+this.favorites+'</strong></li>\
		<li class="comments">Comentários: <strong>'+this.comments+'</strong></li>\
	</ul>\
	';
	return html;
};

MARKUP.mediaInfo = function() { var $ = jQuery;
	var src = this.player+'?path='+this.filePath+'&amp;amp;id='+this.fileID+'&amp;amp;host='+this.storage+'&amp;amp;mediaId='+this.id;
	var html = '\
		<p>'+this.description+'</p>\
		<dl class="tags">\
			<dt>Tags:</dt>\
			<dd>';
				html += MARKUP.tags.apply(this.tags);
				html += '\
			</dd>\
		</dl>\
		<dl class="tocopy">\
			<dt>URL:</dt>\
			<dd><input type="text" name="url_field" value="'+document.location.href+'" /></dd>\
		</dl>\
		<dl class="tocopy">\
			<dt>Código:</dt>\
			<dd><input type="text" name="embed_field" value="&lt;object width=&quot;100%&quot; height=&quot;368&quot;&gt;&lt;param name=&quot;movie&quot; value=&quot;'+src+'&quot; /&gt;&lt;param name=&quot;wmode&quot; value=&quot;window&quot; /&gt;&lt;embed width=&quot;100%&quot; height=&quot;368&quot; wmode=&quot;window&quot; src=&quot;'+src+'&quot; type=&quot;application/x-shockwave-flash&quot;/&gt;&lt;/object&gt;"/></dd>\
		</dl>\
	';
	return html;
};


// Lib para janelinha com opacidade 

function TB_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link
	
	// Patch by Irae Carvalho to solve flash objects that must be wmode=window
	try{
		jQuery('[@wmode="window"]').css('visibility','hidden');
		jQuery('object [@name="wmode"][@value="window"]').parent('object').css('visibility','hidden');
	} catch (e) {void(null)}

	try {
		if (document.getElementById("TB_HideSelect") == null) {
		jQuery("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
		jQuery("#TB_overlay").click(TB_remove);
		}
		
		if(caption==null){caption=""};
		
		jQuery(window).scroll(TB_position);
 		
		TB_overlaySize();
		
		jQuery("body").append("<div id='TB_load'><img src='http://videos.uol.com.br/images/loadingAnimation.gif' /></div>");
		TB_load_position();
		
		
		
	   if(url.indexOf("?")!==-1){ //If there is a query string involved
			var baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		var baseURL = url;
	   }
	   var urlString = /\.jpg|\.jpeg|\.png|\.gif|\.bmp/g;
	   var urlType = baseURL.toLowerCase().match(urlString);
		
		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
				
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = jQuery("a[@rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML == "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {						
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = TB_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			jQuery("#TB_window").append("<a href='' id='TB_ImageOff' title='Fechar'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Fechar'>Fechar</a></div>"); 		
			
			jQuery("#TB_closeWindowButton").click(TB_remove);
			
			if (!(TB_PrevHTML == "")) {
				function goPrev(){
					if(jQuery(document).unbind("click",goPrev)){jQuery(document).unbind("click",goPrev)};
					jQuery("#TB_window").remove();
					jQuery("body").append("<div id='TB_window'></div>");
					TB_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;	
				}
				jQuery("#TB_prev").click(goPrev);
			}
			
			if (!(TB_NextHTML == "")) {		
				function goNext(){
					jQuery("#TB_window").remove();
					jQuery("body").append("<div id='TB_window'></div>");
					TB_show(TB_NextCaption, TB_NextURL, imageGroup);				
					return false;	
				}
				jQuery("#TB_next").click(goNext);
				
			}
			
			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					TB_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
					document.onkeydown = "";
					goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
					document.onkeydown = "";
					goPrev();
					}
				}	
			}
				
			TB_position();
			jQuery("#TB_load").remove();
			jQuery("#TB_ImageOff").click(TB_remove);
			jQuery("#TB_window").css({display:"block"}); //for safari using css instead of show
			}
	  
			imgPreloader.src = url;
		}else{//code to show html pages
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = TB_parseQuery( queryString );
			
			TB_WIDTH = (params['width']*1) + 30;
			TB_HEIGHT = (params['height']*1) + 40;
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;
			
			if(url.indexOf('TB_iframe') != -1){				
					urlNoQuery = url.split('TB_');		
					jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Fechar'>Fechar</a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' onload='TB_showIframe()'> </iframe>");
				}else{
					jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>Fechar</a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");
			}
					
			jQuery("#TB_closeWindowButton").click(TB_remove);
			
				if(url.indexOf('TB_inline') != -1){	
					jQuery("#TB_ajaxContent").html(jQuery('#' + params['inlineId']).html());
					TB_position();
					jQuery("#TB_load").remove();
					jQuery("#TB_window").css({display:"block"}); 
				}else if(url.indexOf('TB_iframe') != -1){
					TB_position();
					if(frames['TB_iframeContent'] == undefined){//be nice to safari
						jQuery("#TB_load").remove();
						jQuery("#TB_window").css({display:"block"});
						jQuery(document).keyup( function(e){ var key = e.keyCode; if(key == 27){TB_remove()} });
					}
				}else{
					jQuery("#TB_ajaxContent").load(url, function(){
						TB_position();
						jQuery("#TB_load").remove();
						jQuery("#TB_window").css({display:"block"}); 
					});
				}
			
		}
		
		jQuery(window).resize(TB_position);
		
		document.onkeyup = function(e){ 	
			if (e == null) { // ie
				keycode = event.keyCode;
			} else { // mozilla
				keycode = e.which;
			}
			if(keycode == 27){ // close
				TB_remove();
			}	
		}
		
	} catch(e) {
		alert( e );
	}
};

//helper functions below

function TB_showIframe(){
	jQuery("#TB_load").remove();
	jQuery("#TB_window").css({display:"block"});
};

function TB_remove() {
 	jQuery("#TB_imageOff").unbind("click");
	jQuery("#TB_overlay").unbind("click");
	jQuery("#TB_closeWindowButton").unbind("click");
	jQuery("#TB_window").fadeOut("fast",function(){
		jQuery('#TB_window,#TB_overlay,#TB_HideSelect').remove();
		// Patch by Irae Carvalho to solve flash objects that must be wmode=window
		try{
			jQuery('[@wmode="window"]').css('visibility','visible');
			jQuery('object [@name="wmode"][@value="window"]').parent('object').css('visibility','visible');
		} catch (e) {void(null)}
	});
	jQuery("#TB_load").remove();
	return false;
};

function TB_position() {
	var pagesize = TB_getPageSize();	
	var arrayPageScroll = TB_getPageScrollTop();	
	jQuery("#TB_window").css({width:TB_WIDTH+"px",left: (arrayPageScroll[0] + (pagesize[0] - TB_WIDTH)/2)+"px", top: (arrayPageScroll[1] + (pagesize[1]-TB_HEIGHT)/2)+"px" });
};

function TB_overlaySize(){
	if (window.innerHeight && window.scrollMaxY || window.innerWidth && window.scrollMaxX) {	
		yScroll = window.innerHeight + window.scrollMaxY;
		xScroll = window.innerWidth + window.scrollMaxX;
		var deff = document.documentElement;
		var wff = (deff&&deff.clientWidth) || document.body.clientWidth || window.innerWidth || self.innerWidth;
		var hff = (deff&&deff.clientHeight) || document.body.clientHeight || window.innerHeight || self.innerHeight;
		xScroll -= (window.innerWidth - wff);
		yScroll -= (window.innerHeight - hff);
	} else if (document.body.scrollHeight > document.body.offsetHeight || document.body.scrollWidth > document.body.offsetWidth){ // all but Explorer Mac
		yScroll = document.body.scrollHeight;
		xScroll = document.body.scrollWidth;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		yScroll = document.body.offsetHeight;
		xScroll = document.body.offsetWidth;
  	}
	jQuery("#TB_overlay").css({"height":yScroll +"px", "width":xScroll +"px"});
	jQuery("#TB_HideSelect").css({"height":yScroll +"px","width":xScroll +"px"});
};

function TB_load_position() {
	var pagesize = TB_getPageSize();
	var arrayPageScroll = TB_getPageScrollTop();
	jQuery("#TB_load")
	.css({left: (arrayPageScroll[0] + (pagesize[0] - 100)/2)+"px", top: (arrayPageScroll[1] + ((pagesize[1]-100)/2))+"px" })
	.css({display:"block"});
}

function TB_parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params; // return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
};

function TB_getPageScrollTop(){
	var yScrolltop;
	var xScrollleft;
	if (self.pageYOffset || self.pageXOffset) {
		yScrolltop = self.pageYOffset;
		xScrollleft = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop || document.documentElement.scrollLeft ){	 // Explorer 6 Strict
		yScrolltop = document.documentElement.scrollTop;
		xScrollleft = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScrolltop = document.body.scrollTop;
		xScrollleft = document.body.scrollLeft;
	}
	arrayPageScroll = new Array(xScrollleft,yScrolltop) 
	return arrayPageScroll;
};

function TB_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight
	arrayPageSize = new Array(w,h) 
	return arrayPageSize;
};

function TB_login(message,redir) {
	var html = '\n'+
	'<div id="notauth">\n'+
	'	<h3>'+message+'</h3>\n'+
	'	<iframe src="https://acesso.uol.com.br/login.html?skin=taipei-video-iframe&dest=REDIR|'+redir+'" width="520" height="255" name="acesso_iframe" id="acesso_iframe" border="0" frameborder="0"></iframe>\n'+
	'</div>\n'+
	'';
	fakeLogin = false;
	if($('#TB_window').size() == 0) {
		$('#markup_adicional').append('<div id="fakeLogin"><div>&nbsp;</div></div>');
		TB_show('Identificação', 'TB_inline?height=10&width=10&inlineId=fakeLogin', null);
		fakeLogin = true;
	}
	
	loginWidth = 530;
	loginHeight = 310;
	difWidth = loginWidth - jQuery('#TB_window').css('width').replace('px', '');
	difHeight = loginHeight - jQuery('#TB_window').height();
	prevTop = jQuery('#TB_window').css('top').replace('px', '');
	prevLeft = jQuery('#TB_window').css('left').replace('px', '');
	prevWidth = jQuery('#TB_window').css('width').replace('px', '');
	prevHeight = jQuery('#TB_window').height();
	prevContentWidth = jQuery('#TB_ajaxContent').css('width').replace('px', '');
	prevContentHeight = jQuery('#TB_ajaxContent').css('height').replace('px', '');
	jQuery('#TB_window').animate({
		width: parseInt(loginWidth), height: parseInt(loginHeight), top: parseInt(prevTop-difHeight/2), left: parseInt(prevLeft-difWidth/2)
	}, 'medium');
	jQuery('#TB_ajaxContent').animate({
		width: parseInt(loginWidth-30), height: parseInt(loginHeight-24)
	}, 'medium');
	window.TB_WIDTH = loginWidth;
	window.TB_HEIGHT = loginHeight;
	jQuery('#TB_ajaxContent > div').eq(0).slideUp('medium', function(){
		jQuery('#TB_ajaxContent').append(html);
	});
}