﻿/* 20090910-1318 */

// GLOBAL
var modulesArray = [];
var countryPage = window.location.hostname.split(".");
countryPage = countryPage[countryPage.length-1].replace("/", "");
var tabSelected = "";
var tabPhotosClicked = false;

// Font resize
var fontResize = function(selector) {
	var resize = function(element) {
		var range = 20;

		var indexSize = $(selector).find(".ctn-fontsize a").index(element);
		var newSize = indexSize * range + 80;

		// Active
		$(selector).find(".ctn-fontsize a").removeClass("act");
		element.addClass("act");
	
		// Adjust size
		$(selector).find(".fontsize").each(function() {
			$(this).css("font-size",newSize+"%");
		});
	}

	$(selector).find(".ctn-fontsize a").click(function(evt) {
		resize($(this));
		evt.preventDefault();
	});
}


// Pages
var navigationPages = function() {

	var page = 1;
	var numPages = $(".pages strong span").html();

	var navigate = function(action) {

		$(".p"+page).hide();
		page = page+action;
		$(".p"+page).show();

		var firstPage = page == 1;
		var lastPage = $(".p"+(page+1)).size() == 0;

		$(".pages strong").html(page+" de "+numPages);

		// Class prev/next button
		if (firstPage) {
			$(".pages a:first").removeClass("p").addClass("p-off");
		} else {
			$(".pages a:first").removeClass("p-off").addClass("p");
		}
		if (lastPage) {
			$(".pages a:last").removeClass("n").addClass("n-off"); 
		} else {
			$(".pages a:last").removeClass("n-off").addClass("n");
		}
	}

	// navigation controls
	$(".pages").click(function(evt) {
		var target = evt.target;

		if(target.tagName == "A" && !(/-off$/).test(target.className)){
			if ($(target).hasClass("p")) navigate(-1);
			if ($(target).hasClass("n")) navigate(1);
			
			// scroll to anchor position (comments)
			var anchor = $("a[name='"+target.href.match(/[^#]*$/)+"']"),
				anchorPositionX = (anchor.length) ? anchor.offset().top : 0;
			scrollTo(0, anchorPositionX);
		}
		
		evt.preventDefault(); // prevent default behavior
	});
}

// Layers
var createLayer = function(url,callback) {
	$(".ctn-over").remove();
	$.ajax({
		url: url,
		cache: false,
		success: function(html){
			$("#trr-ctn-body").prepend(html);

			// Close layer
			$(".ctn-over .lnk-close").click(function(evt) {
				$(".ctn-over").remove();

				evt.preventDefault(); // prevent default behavior
			});

			if (typeof(callback) != "undefined") callback();
		}
	});
}

// Socialize
$(".mod-socialize .itm-socialize a").click(function(evt) {
	var element = $(this);
	createLayer("socialize.html",function() {
		// Position
		$(".ctn-socialize").css("top",element.offset().top+element.height()+"px");
		
		$(".ctn-socialize .tabs").tabs();
		$(".ctn-socialize .tabs .tab-content").hide();
		$(".ctn-socialize .selected").removeClass("selected");

		// Socialize network
		$("#socialize-network a").each(function() {
			$(this).attr("href",$(this).attr("href").replace("=u","="+window.location.href).replace("=t","="+escape(document.title)));
		});

		// Get url form
		$(".ctn-socialize .itm-email").click(function() {
			var url = $(".itm-socialize:eq(0) a").attr("href");
			$("#ifm-socialize-email").attr("src",url.substr(url.lastIndexOf("#")+1));
		});
	});

	evt.preventDefault(); // prevent default behavior
});

// Socialize e-mail
$("#socialize-form").submit(function() {
	var exprMail = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
	var error = false;

	if ($("#socialize-form #de_nome").val() == "") error = true;
	if (!exprMail.test($("#socialize-form #de_emai").val())) error = true;
	if ($("#socialize-form #ate_nome").val() == "") error = true;
	if (!exprMail.test($("#socialize-form #ate_emai").val())) error = true;
	if ($("#socialize-form #enteredkey").val() == "") error = true;

	if (error) {
		$(".socialize-email-form").css("display", "none");
		return false;
	}
});
$("#socialize-form .btn-send").click(function() {$("#socialize-form").submit();return false;})
$("#socialize-form .btn-cancel").click(function() {$("#socialize-form").get(0).reset();if($(parent.document).size()>0)$(parent.document).find(".ctn-socialize").remove();return false;})
$(".btn-back").click(function() {$(".socialize-email-form").css("display", "block"); $(".socialize-email-ok").css("display", "none"); return false;})

// Printing
$(".ico-print").click(function() {
	createLayer("printing.html",function() {
		// Position
		$(".ctn-print").css("top",$(".mod-content:eq(1)").offset().top+"px");

		//  Title
		$(".ctn-print .mod-content").before($(".mod-title").clone());

		// Content
		$(".col-left-full .printing").each(function() {
			$(".ctn-print .mod-content").append($(this).clone());
		});

		// Mirror content classes inside the printable div
		$(".ctn-print .mod-content:eq(0)").attr('class', $(".mod-content:eq(1)").attr('class'));

		// Remove links
		$(".ctn-print .contextlink").each(function() {$(this).replaceWith("<span>"+$(this).text()+"</span>");});

		// Links
		$(".ctn-print .mod-links li a").each(function() {
			$(this).after("<cite>"+$(this).attr("href")+"</cite>");
		});

		// Bottom
		$(".ctn-bottom span").html($(".ctn-print .mod-title a strong").html());
		$(".ctn-bottom strong").html(window.location.href);
		if ($("#article").size() > 0) {
			$(".ctn-bottom .txt-gallery").hide();
		} else {
			$(".ctn-bottom .txt-article").hide();
		}

		if ($(".img-article").size() > 0) {
			$.checkboxRadiobutton($(".ctn-print"));
		} else {
			$(".ctn-commands label, input").hide();
		}
		fontResize(".ctn-print");
		$(".ctn-print .scrolling").scrolling();

		// Print
		$(".ctn-print .btn-print").click(function() {
			window.print();
			return false;
		});

		// Show hide photo
		$(".ctn-print .chk-replace, .ctn-print input:checkbox + label").mouseup(function() {
			// objCheckbox
			var objCheckbox = null;
			if ($(this).is("label")) {
				objCheckbox = $(this).prev();
			} else {
				objCheckbox = $(this).next();
			}

			if (objCheckbox.attr("checked")) {
				$(".ctn-print .img-article").show();
			} else {
				$(".ctn-print .img-article").hide();
			}
		});
	});
	return false;
});

// Reload Metrics
var reloadMetrics = function() {

	var urlMetrics = "";
	
	if (typeof(trrConstantData) != "undefined") {
		met_info_service = trrConstantData.metrics.terra_info_service;
		met_info_channel = trrConstantData.metrics.terra_info_channel;

		switch(tabSelected) {
			case "itm-article":
				met_info_type = "NOT";
			break;
			case "itm-video":
				met_info_type = "VID";
			break;
			case "itm-info":
				met_info_type = "INF";
			break;
			default:
				met_info_type = "GAL";
		}
		
		met_info_id = trrConstantData.metrics.terra_info_id;
		met_stats_idCrtfc = trrConstantData.metrics.terra_stats_idCrtfc;
		met_uv_c = trrConstantData.metrics.terra_stats_uv_c;
	} else {
		if (tabSelected == "") {
			met_info_service = terra_info_service;
			met_info_channel = terra_info_channel;
			met_info_type = terra_info_type;
			met_info_id = terra_info_id;
			met_stats_idCrtfc = terra_stats_idCrtfc;
			met_uv_c = uv_c;
		} else {
			met_info_service = terra_info_service[tabSelected];
			met_info_channel = terra_info_channel[tabSelected];
			met_info_type = terra_info_type[tabSelected];
			met_info_id = terra_info_id[tabSelected];
			met_stats_idCrtfc = terra_stats_idCrtfc[tabSelected];
			met_uv_c = uv_c[tabSelected];
		}
	}
	if (countryPage == "br") {
		urlMetrics = "http://stf.terra.com.br/portal/metrics.html?terra_info_service="+met_info_service+"&terra_info_channel="+met_info_channel+"&terra_info_type="+met_info_type+"&terra_info_id="+met_info_id+"&terra_stats_idCrtfc="+met_stats_idCrtfc+"&uv_c="+met_uv_c;
	} else {
		urlMetrics = "http://stf.terra.com/portal/metrics.html?terra_info_service="+met_info_service+"&terra_info_channel="+met_info_channel+"&terra_info_type="+met_info_type+"&terra_info_id="+met_info_id+"&terra_stats_idCrtfc="+met_stats_idCrtfc+"&uv_c="+met_uv_c;
	}

	$("body").append('<iframe src="'+urlMetrics+'" width="0" height="0" style="position:absolute;left:-100px;top:-100px;"></iframe>');
}

navigationPages();
fontResize(".col-left-full");
if ($("#article").size() > 0) {
	$(".col-left-full .tabs").tabs();

	// Author + About info > V6 Compliance
	if ($(".ctn-pre dl").size() > 0){
		$(".ctn-pre dl").html($(".p1 dl").html());
		$(".p1 dl").remove();		
		if ($(".ctn-pre dl dt").size() == 0) {
			$(".ctn-pre dl").html("<dt>&nbsp;</dt><dd>&nbsp;</dd>");
		}
	}

	// Tabs events
	$(".col-left-full .tab-list li a").click(function() {
		tabSelected = $(this).attr("class").split(" ")[0];

		// Create / destroy video
		var objLink = $(this);
		$(".ctn-video").each(function() {
			// Destroy
			if ($(this).find("iframe").size() > 0) {
				$(this).prepend('<a href="'+$(".ctn-video iframe").attr("src")+'"></a>');
				$(this).find("iframe").remove();
			}
		});

		// Create
		$(objLink.attr("href").replace("#t","#")).find(".ctn-video").prepend('<iframe height="386" frameborder="0" width="480" scrolling="no" src="'+$(objLink.attr("href").replace("#t","#")).find(".ctn-video a").attr("href")+'">');
		$(objLink.attr("href").replace("#t","#")).find(".ctn-video a").remove();

		// Show hide divAnnotatio
		if ($(this).hasClass("itm-article")) {
			$("#divAnnotatio").show();
			$("#divAnnotatio").next().show();
		} else {
			$("#divAnnotatio").hide();
			$("#divAnnotatio").next().hide();
		}

		// First click on photos tab
		if (!tabPhotosClicked && tabSelected == "itm-photos") {
			tabPhotosClicked = true;
		} else {
			reloadMetrics();
		}
	});

	// Photos
	var setPhotos = function() {

		objGalleryModule = (
			{
				id:"modPhotoGallery",
				selector:'.mod-photos',
				loadSkin:false,
				params:{
					type:"gallery",
					mediaType:"photo",
					autoplay:false,
					carousel:false,
					effects:true
				}
			}
		);

		if ((/#tphotos/).test(document.location)) {
			modulesArray.push(objGalleryModule);
		} else {
			modMan.load([objGalleryModule]);
		}

		$('.col-left-full .tab-list a.itm-photos').unbind("click",setPhotos);
	}
	$('.col-left-full .tab-list a.itm-photos').bind("click",setPhotos);

	// Start
	$(".col-left-full .tab-list li.selected a").click();

	// Aux tabs
	$(".nav .cross a").click(function() {
		$(".tab-list ."+$(this).attr("class")).trigger("click");
		window.scrollTo(0,0);
	});

}

if ($(".col-left-full .combolist").size() > 0) {
	$(".col-left-full .combolist").combobox();
	$(".col-left-full .combolist .scrolling").scrolling();
	$(".col-left-full .combolist .clickout, .combolist .cmb-value").initClickOut();
}

if ($(".mod-latestnews").size() > 0) {
	$(".mod-latestnews").tabs();
}

// MODMAN	// MODMAN
if (typeof(modMan) != "undefined"){

	if($('.mod-gallery').length) {
		modulesArray.push(
			{
				id:"modPhotoGallery",
				selector:'.mod-gallery',
				loadSkin:false,
				params:{						
					type:"gallery",
					mediaType:"photo",
					autoplay:false,
					carousel:false,
					effects:true
				}
			}
		);
	}
	
	if($('.mod-photoslist').length) {
		modulesArray.push(
			{
				id:"modPhotoGallery",
				selector:'.mod-photoslist',
				loadSkin:false,
				params:{						
					type:"list",
					mediaType:"photo",
					autoplay:true,
					carousel:true,
					effects:true
				}
			}
		);
	}
	
	if($('.mod-videoslist').length) {
		modulesArray.push(
			{
				id:"modPhotoGallery",
				selector:'.mod-videoslist',
				loadSkin:false,
				params:{						
					type:"list",
					mediaType:"video",
					autoplay:true,
					carousel:true,
					effects:true
				}
			}
		);
	}
	
	if($(".mod-poll").length){
		modulesArray.push(
			{
				id:"modPoll",
				selector:'.mod-poll',
				loadSkin:false
			}
		);
	}
	

	if($(".mod-audience_pulse_ver").length){
		modulesArray.push(
			{
				id:"modAudiencePulseVertical",
				selector:'.mod-audience_pulse_ver',
				loadSkin:false
			}
		);
		//behaviorsAudiencePulseVertical();
	}
	
	if($(".mod-clock").length){
		modulesArray.push(
			{
				id:"modClock",
				selector:'.mod-clock',
				skinName:"default",
				loadSkin:false
			}
		);
	}
	
	if($(".mod-terratvsonora").length){
		modulesArray.push(
			{
				id:"modMulti",
				selector:'.mod-terratvsonora',
				loadSkin:false,
				params:{
					modules:[
						{
							id:"modTerraTv",
							selector:'.mod-terratv',
							loadSkin:false,
							params:{
								request_url:"http://stf.terra.com.br/carousel/br/terratv/br_diversao_terratv.js"
							}
						},
						{
							id:"modSonora",
							loadSkin:true,
							skinName:"multi"
						}
					]
				}
			}
		);
	}

	modMan.start({
		configs:{
			//baseURL:'http://mainsite.int.dsv-webx1.terra.com.br/entregas/20090619-0000/pt-br/',
			pageLang:'pt',
			pageCountry:'BR',
			lazyLoad:false,
			transitionEffects:false
		},
		modules:modulesArray
	});
}

// ANNOTATIO
if ($("#divAnnotatio").size() > 0) {
        // Função de callback (opcional)
        function fnCallbackInit(data){
               // Position ADS
               if ($("#ctn-tgm-textlinks").size() > 0) {
                       positionAds("#ctn-tgm-textlinks","#tgm-textlinks");
                       $(".lnkRepliesClosed").next().click(function() {
                               setTimeout(function() {
                                      positionAds("#ctn-tgm-textlinks","#tgm-textlinks");
                               },50);
                       });
               }
               var arrBtComments = ["btComment1", "btComment2"]; // ID´s dos elementos que serão exibidos ao carregar-se o transversal de comentários.
               for(a=0;a < arrBtComments.length;a++){
                       try{
                               document.getElementById(arrBtComments[a]).style.display = '';
                       }catch(e){}
               }
               // Popula divs que necessitem do total de comentarios
               var arrTotalComments = ["dd-total-comments"]; // ID´s dos elementos que serão receberão o total de comentários
               for(a=0;a < arrTotalComments.length;a++){
                       try{
                               document.getElementById(arrTotalComments[a]).innerHTML = data.total_comments;
                       }catch(e){}
               }

               // Comment
               $(".mod-socialize .itm-comment a").click(function(evt) {

                       $('.col-left-full ol a:first').trigger('click'); // return to article's tab

                       // scroll to anchor position (comments)
                       var anchor = $("a[name='"+this.href.match(/[^#]*$/)+"']"),
                               anchorPositionX = (anchor.length) ? anchor.offset().top : 0;
                       scrollTo(0, anchorPositionX); 

                       try{ _self.showModalForm('insert'); }catch(e){} // opens Annotatio's new message layer

                       evt.preventDefault(); // prevent default behavior
               });
        }

		function fnCallbackReplies() {
			positionAds("#ctn-tgm-textlinks","#tgm-textlinks");
		}

        var params = { "objectId": Terra_info_id,
               "application": Terra_info_service,
               "pageSize": 10,
               "pageNum": 1,
               "orderby": "datedesc",
               "uri" : Terra_info_url,
               "groupPath" : Terra_info_channel,
               "objectDescription" : Terra_info_description,
               "objectType" : Terra_info_type,
               "imgThumbPath" : Terra_img_thumb_path,
               "absDescription" : Terra_abs_description
        };

        var tplUrl = "http://transversais.terra.com/comments/v2.1/templates/templateFull.htm";
        var tpl = new TrrTransversais.AnnotatioInterface({ 
               "lang": "PT-BR",  
               "wsUrl": "http://comments.wsv.terra.com",
				"callback": {
					"init": fnCallbackInit,
					"replies": fnCallbackReplies
				}
        });
        tpl.mountTransversal(tplUrl,"divAnnotatio",params);
}

// Show banner
var showBanner = function(selector) {
	window.setTimeout(function(){
		if (countryPage == "br") {
			$(selector).attr("src","http://stf.terra.com.br/portal/advertising.html?tag="+tgmKey+"&area=comments&site="+(typeof(site)!="undefined"?site:"")+"&zone="+(typeof(zone)!="undefined"?zone:""));
		} else {
			$(selector).attr("src","http://stf.terra.com/portal/advertising.html?tag="+tgmKey+"&area=comments&site="+(typeof(site)!="undefined"?site:"")+"&zone="+(typeof(zone)!="undefined"?zone:""));
		}
	},1000);
}

// Reload ADS
var reloadADS = function(arrADS) {

	var urlADS = "http://stf.terra.com.br/portal/advertising.html?tag="+tgmKey+"&area=#area#&site="+(typeof(site)!="undefined"?site:"")+"&zone="+(typeof(zone)!="undefined"?zone:"");

	for (var cont = 0; cont < arrADS.length; cont++) {
		var objADS = arrADS[cont];
		if ($(objADS.selector+" iframe").size() > 0) {
			$(objADS.selector+" iframe").attr("src",urlADS.replace("#area#",objADS.area));
		} else {
			$(objADS.selector).html('<iframe src="'+urlADS.replace("#area#",objADS.area)+'" scrolling="no" width="'+objADS.width+'" height="'+objADS.height+'" allowtransparency="yes" frameborder="0"></iframe>');
		}
	}
}

var reloadAdsArticlePages = function() {
	reloadADS([
		{
			//selector:".tgm-top",
			selector:"#ctn-tgm-top",
			area:"top",
			width:830,
			height:90
		},
		{
			//selector:".adv-halfpage",
			selector:"#ctn-tgm-right",
			area:"right",
			width:300,
			height:600
		},
		{
			//selector:".mod-audience_pulse_ver .ctn-header .ctn-patrocinio",
			selector:"#ctn-tgm-apulse",
			area:"apulse",
			width:220,
			height:45
		},
		{
			//selector:".mod-audience_pulse_ver .mod-noticias .ctn-patrocinio",
			selector:"#ctn-tgm-particles",
			area:"particles",
			width:220,
			height:45
		},
		{
			//selector:".adv-ppp",
			selector:"#ctn-tgm-textlinks",
			area:"textlinks",
			width:619,
			height:88
		}
	]);
}

$(".lst-photos a, .col-left-full .tab-list li a, .nav .controls a:eq(1), .nav .controls a:eq(2)").click(function() {
	reloadAdsArticlePages();
});

/***** CONTEXTLINK TEMP *****/
$(".contextlink").click(function() {
	var element = $(this);
	createLayer("context-links.html",function() {
		// Position
		$(".mod-contextlinks").css({
			"left":element.offset().left+"px",
			"top":element.offset().top+element.height()+"px"
		});
	});
	return false;
});