﻿Utils = function () {
	this.Utils = Utils;
	this.name = 'Util';
	this.version = '1.0v';
	this._link = '#';
 	this.enviaAmigo = new EnviaAmigo();
  this.enviaAmigo.init();
}

var utils = Utils.prototype;

utils.newWindow = function() { window.open(this._link) };

utils.openWindow = function(windowName, features) { window.open(this._link, windowName, features); }

utils.exec = function(cmd,link)
{
	this._link = link;
	eval("this."+cmd);
}

utils.getBrowse = function()
{
	if(navigator.userAgent.indexOf('Mac_PowerPC') > -1)
	{
		return("MAC");
	}
	else if(navigator.userAgent.indexOf('MSIE 6.0') > -1)
	{
		return("WINIE");	
	}
	else if(navigator.userAgent.indexOf('Gecko') > -1)
	{
		return("MOZILLA");
	}
}

utils.getQueryString = function(){
    var URL = location.href;
    var PARAMS = URL.substring(URL.indexOf("?")+1);
    var PARAM = new Array();
    PARAM = PARAMS.split("&");
    var par = new Array();
    
    for(var x=0; x < PARAM.length; x++)
    {
        var VALOR = new Array();
        VALOR = PARAM[x].split("=");
       	var re = /\+/gi;
       	if(VALOR[0] && VALOR[1]){
        	par[VALOR[0]] = this.decodeUTF8(unescape(VALOR[1].replace(re," ")));
        }
    }
    
    return par;
}

utils.decodeUTF8 = function(utftext){
     var plaintext = ""; var i=0; var c=c1=c2=0;
     while(i<utftext.length)
         {
         c = utftext.charCodeAt(i);
         if (c<128) {
             plaintext += String.fromCharCode(c);
             i++;}
         else if((c>191) && (c<224)) {
             c2 = utftext.charCodeAt(i+1);
             plaintext += String.fromCharCode(((c&31)<<6) | (c2&63));
             i+=2;}
         else {
             c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2);
             plaintext += String.fromCharCode(((c&15)<<12) | ((c2&63)<<6) | (c3&63));
             i+=3;}
         }
     return plaintext;
}

utils.encodeUTF8 = function(wide){
    var c, s;
    var enc = "";
    var i = 0;

    while(i<wide.length) {
        c= wide.charCodeAt(i++);
        // handle UTF-16 surrogates
        if (c>=0xDC00 && c<0xE000) continue;
        if (c>=0xD800 && c<0xDC00) {
          if (i>=wide.length) continue;
          s= wide.charCodeAt(i++);
          if (s<0xDC00 || c>=0xDE00) continue;
          c= ((c-0xD800)<<10)+(s-0xDC00)+0x10000;
    }

    // output value
    if (c<0x80) enc += String.fromCharCode(c);
        else if (c<0x800) enc += String.fromCharCode(0xC0+(c>>6),0x80+(c&0x3F));
        else if (c<0x10000) enc += String.fromCharCode(0xE0+(c>>12),0x80+(c>>6&0x3F),0x80+(c&0x3F));
        else enc += String.fromCharCode(0xF0+(c>>18),0x80+(c>>12&0x3F),0x80+(c>>6&0x3F),0x80+(c&0x3F));
    }
    return enc;
}

Cookie = function () {
	this.Cookie = Cookie;
	this.name = 'Cookie';
	this.version = '1.0v';
}

var cookie = Cookie.prototype;

cookie.getValue = function(offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1)
	   endstr = document.cookie.length;
	   return unescape(document.cookie.substring(offset, endstr));
}

cookie.get = function(name) {
	 var arg = name + "=";
	 var alen = arg.length;
	 var clen = document.cookie.length;
	 var i = 0;

	 while (i < clen) 
	 {           
	  var j = i + alen;									   
	  if (document.cookie.substring(i, j) == arg)
		  return this.getValue(j);
		  i = document.cookie.indexOf(" ", i) + 1;
	  if (i == 0) 
		  break; 
	 }
	 return null;
}

Passaporte = function (codSite,codRecurso) {
	this.Passaporte = Passaporte;
	this.name = 'Passaporte';
	this.version = '1.0v';
	this.Cookie = new Cookie();
	
	this.codSite = codSite;
	this.codRecurso = codRecurso;	
}

var passaporte = Passaporte.prototype;

passaporte.logout = function()
{
	pathname = location.pathname;
	myDomain = pathname.substring(0,pathname.lastIndexOf('/')) +'/';
	var largeExpDate = new Date();
	largeExpDate.setTime(largeExpDate.getTime() + (60 * 24 * 3600 * -1000));
	SetCookie('usuario',"unknown",largeExpDate,myDomain);
	SetCookie('Ticket',"unknown",largeExpDate,myDomain);
	this.display();
}

passaporte.login = function()
{
	var inputUsuarioValue = eval("document.loginForm.EMAIL_PESSOA.value");
	var inputSenhaValue = eval("document.loginForm.SENHA_PESSOA.value");
	if((inputUsuarioValue.indexOf('@',0) < 0) || (!inputSenhaValue)) {
		alert('Email e senha são obrigatórios.');		
	} else {
		document.loginForm.submit();
	}
}

passaporte.display = function() {

	this.pstLogin = document.getElementById('pstLogin');
	this.pstLogout = document.getElementById('pstLogout');		

	if( ( this.Cookie.get('usuario') == null) && (this.Cookie.get('ticket') == null) ) {
// codigo abaixo funciona com o DegustadorFilter.java antigo
 document.loginForm.URL_RETORNO.value = window.location.href;
//        document.loginForm.URL_RETORNO.value = 'http://app.exame.abril.com.br/mm/redirecionaPaginaInicial.do?actionFunctionName=redirecionaPaginaInicial&url=http://app.exame.abril.com.br/servicos/melhoresemaiores/';
		
		this.pstLogin.style.display = 'block';
		this.pstLogout.style.display = 'none';
	} else {
		this.pstLogin.style.display = 'none';
		this.pstLogout.style.display = 'block';
	}
}

passaporte.meuRegistro = function() {
	userCookie = this.Cookie.get('usuario');

	var codigo = '';
	
	if(userCookie != null) {
		valores = userCookie.split(';');
		codigo = valores[0];
	}

	if(userCookie == null) {
		location.replace('http://passaporte.abril.com.br/alteraUsuario.do?metodo=prepararAlterarDadosUsuario&COD_SITE=' + this.codSite + '&COD_RECURSO='+this.codRecurso+'&URL_RETORNO='+window.location.href);
	} else {
		location.replace('http://passaporte.abril.com.br/alteraUsuario.do?metodo=prepararAlterarDadosUsuario&COD_SITE=' + this.codSite + '&COD_RECURSO='+this.codRecurso+'&URL_RETORNO='+window.location.href);
	}
}

passaporte.getUsuario =  function() {
	userCookie = this.Cookie.get('usuario');
	if (userCookie != null) {
		var Usuario = new Array;
		
		Usuario = userCookie.split(';');
		
		
		if (Usuario.length < 2){
		   Usuario = userCookie.split('%3B')
		}
		
		for(var x=0;x < Usuario.length;x++) {
			Usuario[x] = Usuario[x].replace(/\+/gi, " ")
		}
		return Usuario;
	} else {
		return "Não existe o nome do usuário.";
	}
};

Publicidade = function () {
	this.Publicidade = Publicidade;
	this.name = 'Publicidade';
	this.version = '1.0v';
	this.listPos = '';
	this.sitePage = '';	
};

var publi = Publicidade.prototype;

publi.prepare = function(listaPublicidade) {
	var publiDefault = new Array();
	var publiHome = new Array();
	var publiAtual = new Array();
	
	for(var i=0;i <listaPublicidade.length; i++) {

		if(listaPublicidade[i]['canal'] == 'default') {
			publiDefault['listPos'] = listaPublicidade[i]['listPos'];
			publiDefault['sitePage'] = listaPublicidade[i]['sitePage'];
		}
		if(listaPublicidade[i]['canal'] == 'home') {
			publiHome['listPos'] = listaPublicidade[i]['listPos'];
			publiHome['sitePage'] = listaPublicidade[i]['sitePage'];
		}
		if(listaPublicidade[i]['canal'] == canal) {
			publiAtual['listPos'] = listaPublicidade[i]['listPos'];
			publiAtual['sitePage'] = listaPublicidade[i]['sitePage'];
		}
	}

	if(publiAtual['listPos']) {
		this.listPos = publiAtual['listPos'];
		this.sitePage = publiAtual['sitePage'];
	} else if(publiDefault['listPos']) {
		this.listPos = publiDefault['listPos'];
		this.sitePage = publiDefault['sitePage'];
	} else if(publiHome['listPos']) {
		this.listPos = publiHome['listPos'];
		this.sitePage = publiHome['sitePage'];
	}
};




EnviaAmigo = function () {
	this.EnviaAmigo	= EnviaAmigo;
	this.name	= 'Envia Amigo';
	this.version	= '1.0v';
	this.dominio = 'http://portalexame.abril.com.br/';
	this.Cookie	= new Cookie();
	this.Passaporte = new Passaporte();
}

var enviaamigo = EnviaAmigo.prototype;

enviaamigo.send = function() {
 	if( ( this.Cookie.get('usuario') == null) && (this.Cookie.get('ticket') == null) ){
		location.replace('http://passaporte.abril.com.br/autenticaUsuario.do?metodo=checarTipoAutenticacao&COD_SITE=35&COD_RECURSO=83&URL_RETORNO=' + escape(window.location + '?enviaEmail=true'));
		return false;
	}

	var wEnv = window.open(this.dominio+'envieamigo/html0057015.html', 'PopEnviar', 'width=430,height=400,left=0,top=0');
  	wEnv.focus();
}

enviaamigo.init = function() {
  	if(document.URL.indexOf("enviaEmail=true")>0)	{
  		this.removeParameter();
  		this.send();
	}
}

enviaamigo.removeParameter = function(){
	var url = document.location.href;
	var par = new Array;
	var parNew = new Array;
	var count = 0;
	if(url.indexOf("enviaEmail=true") != -1){
		par = url.substr(url.indexOf("?")+1,url.length).split('&');
		for(i=0;i<par.length;i++){
			if(par[i] != 'enviaEmail=true'){
				parNew[count] = par[i];
				count++;
			}
		}
		if(parNew.length > 0){
			document.location.href = url.substr(0, url.indexOf("?")) + '?' + parNew.join('&');
		}
	}
}

Email = function () {
	this.Email = Email;
	this.name = 'Email';
	this.version = '1.0v';
}

var email = Email.prototype;

email.validator = function (email) {
	invalidChars = " /:,;"
	if (email == "") return false;

	for (i=0; i<invalidChars.length; i++) {
		badChar = invalidChars.charAt(i);
		if (email.indexOf(badChar,0) > -1) return false;
	}

	atPos = email.indexOf("@",1);
	if ((atPos == -1) || (email.indexOf("@",atPos+1) != -1)) return false;
	periodPos = email.indexOf(".",atPos)
	if ((periodPos == -1) || (periodPos+3 > email.length)) return false;
	return true;
}

/* Função que checa se os emails são válidos e se a quantidade de nomes é igual a quantidade de emails
Os valores das variáveis "nomesValue" e "emailsValue" devem estar sepadaros por ";" */
email.checkAllEmail = function(nomesValue, emailsValue){
	var nomes = new Array();
	nomes = nomesValue.split(";");

	if(emailsValue == "") return false;

	var re=/[ +]/g;
	emailsValue = emailsValue.replace(re,"");

	var emails = new Array();
	emails = emailsValue.split(";");

	if(nomes.length > 1) {
		if(nomes.length != emails.length) {
			alert("O campo de nome e endereço do destinatário devem ter a mesma quantidade.");
			return false;
		}
	}

	for (var i=0;i<emails.length;i++) {
		if (!this.validator(emails[i])) {
			alert("Por favor preencha corretamente o campo do endereço do destinatário.");
			return false;
		}
	}
	return true;
}

DateHour = function () {
	this.DateHour = DateHour;
	this.name = 'DateHour';
	this.version = '1.0v';
	this.systemDate = new Array;
	this.systemDate = systemDate.split('/');
}

var dateHour = DateHour.prototype;

dateHour.getSystemDate = function(elementId,format) { 
	var element = document.getElementById(elementId);
	if(format == 'd de MMM de yyyy'){
		element.innerHTML = this.systemDate[2] + ' de ' + this.getMonthName(this.systemDate[1]) + ' de ' + this.systemDate[3];
	} else if(format == 's, d de MMM de yyyy') {
		element.innerHTML = this.getDayWeekName(this.systemDate[0]) + ', ' + this.systemDate[2] + ' de ' + this.getMonthName(this.systemDate[1]) + ' de ' + this.systemDate[3];
	} else if(format == 'dd.mm.yyyy') {
		element.innerHTML = this.systemDate[2] + '.' + this.systemDate[1] + '.' + this.systemDate[3];
	} else {
		element.innerHTML = this.systemDate[2] + '/' + this.systemDate[1] + '/' + this.systemDate[3];
	}
}

dateHour.getSystemDateHourArray = function() {
	return this.systemDate;
}

dateHour.getMonthName = function(month) {
	var monthName = new Array();
		
	monthName[0] = '';
	monthName[1] = 'janeiro';
	monthName[2] = 'fevereiro';
	monthName[3] = 'março';
	monthName[4] = 'abril';
	monthName[5] = 'maio';
	monthName[6] = 'junho';
	monthName[7] = 'julho';
	monthName[8] = 'agosto';
	monthName[9] = 'setembro';
	monthName[10] = 'outubro';
	monthName[11] = 'novembro';
	monthName[12] = 'dezembro';
	
	return monthName[parseInt(month,10)];
}


dateHour.getDayWeekName = function(dayWeek) {
	var dayWeekName = new Array();
	
	dayWeekName[0] = 'Domingo';
	dayWeekName[1] = 'Segunda-feira';
	dayWeekName[2] = 'Terça-feira';
	dayWeekName[3] = 'Quarta-feira';
	dayWeekName[4] = 'Quinta-feira';
	dayWeekName[5] = 'Sexta-feira';
	dayWeekName[6] = 'Sabado';

	dayWeekName['Dom'] = 'Domingo';
	dayWeekName['Seg'] = 'Segunda-feira';
	dayWeekName['Ter'] = 'Terça-feira';
	dayWeekName['Qua'] = 'Quarta-feira';
	dayWeekName['Qui'] = 'Quinta-feira';
	dayWeekName['Sex'] = 'Sexta-feira';
	dayWeekName['Sab'] = 'Sabado';
	
	return dayWeekName[dayWeek];
}


dateHour.getListYear = function(start,end) {
	var listYear = new Array();
	var year = start;
	for(var i=0;i<=(end-start);i++){
		listYear[i] = new Array();
		listYear[i]['value'] = year;
		listYear[i]['text'] = year;
		year++;
	}
	return listYear;
}

dateHour.getListMonth = function(start,end) {
	var listMonth = new Array();
	var month = start;
	for(var i=0;i<=(end-start);i++){
		listMonth[i] = new Array();
		listMonth[i]['value'] = month;
		var monthName = this.getMonthName(month);
		listMonth[i]['text'] = (monthName).charAt(0).toUpperCase() + monthName.substr(1,monthName.length);
		month++;
	}
	return listMonth;
}

dateHour.getListDay = function(start,end) {
	var listDay = new Array();
	var day = start;
	for(var i=0;i<=(end-start);i++){
		listDay[i] = new Array();
		listDay[i]['value'] = day;
		listDay[i]['text'] = day;
		day++;
	}
	return listDay;
}

InputSelect = function () {
	this.InputSelect = InputSelect;
	this.name = 'DateHour';
	this.version = '1.0v';
}


var inputSelect = InputSelect.prototype;

inputSelect.loadOption = function(selectObject,arrayList){
	for(var i=0;i<arrayList.length;i++){
		option = new Option(arrayList[i]['text'],arrayList[i]['value']);
		selectObject.options[i] = option;
	}
}

inputSelect.selectValue = function(selectObject,value){
	for(var i=0;i<selectObject.options.length;i++){
		if(selectObject.options[i].value == value){
			selectObject.options[i].selected = true;
		}
	}
}

//Funcoes para alteracao de style na materia
FontStatic = function (valorPadrao, valorMaior, valorMenor) {
	this.FontStatic = FontStatic;
	this.name = 'FontStatic';
	this.version = '1.0v';
	this.maior = valorMaior;
	this.menor = valorMenor;
	this.padrao = valorPadrao;
	sty = document.getElementsByTagName("link");

  for(i = 0;i < sty.length;i ++){
    if(sty[i].href.indexOf(this.maior) != -1){
      sty[i].disabled = true;
      sty[i].href="";


    }
    if(sty[i].href.indexOf(this.menor) != -1){
      sty[i].disabled = true;
      sty[i].href="";

    }
  }
}
var fontS = FontStatic.prototype;

fontS.aumenta = function(){
  var caminho = "/css/" + this.maior;
  sty = document.getElementsByTagName("link");
  for(i = 0;i < sty.length;i ++){
    if((sty[i].href.indexOf(this.padrao) != -1)||(sty[i].href.indexOf(this.maior) != -1)||(sty[i].href.indexOf(this.menor) != -1)){
      sty[i].href = caminho;
    }
  }  

}

fontS.diminui = function(){
  var caminho = "/css/" + this.menor;
  sty = document.getElementsByTagName("link");
  for(i = 0;i < sty.length;i ++){
    if((sty[i].href.indexOf(this.padrao) != -1)||(sty[i].href.indexOf(this.maior) != -1)||(sty[i].href.indexOf(this.menor) != -1)){
      sty[i].href = caminho;
    }
  }  
  
}

fontS.normal = function(){
  var caminho = "/css/" + this.padrao;
  sty = document.getElementsByTagName("link");
  for(i = 0;i < sty.length;i ++){
    if((sty[i].href.indexOf(this.padrao) != -1)||(sty[i].href.indexOf(this.maior) != -1)||(sty[i].href.indexOf(this.menor) != -1)){
      sty[i].href = caminho;
    }
  }  
  
}


BrowserModule = function(){
  this.BrowserModule = BrowserModule;
  this.name = 'BrowserModule';
  this.version = '1.0v';
  this.Home = '';
  this.HelpPage = '';
  this.obj;
}
var modbr = BrowserModule.prototype;

modbr.doHome = function(home, objX){
  this.obj = objX;
  this.obj.style.behavior = 'url(#default#homepage)';
  this.obj.setHomePage(home);
}


modbr.exec = function(cmd,objX){
  this.obj = objX;
  eval("this." + cmd);
}

modbr.doBookmark = function(){
  
  var url = document.location;
  var tit = document.title;
  
  if(window.external){//IE bookmark
    window.external.AddFavorite(url,tit);
  }else if(window.sidebar){ //Mozilla bookmark
    window.sidebar.addPanel(tit,url,"true");
  }else if(window.opera && window.print){ //Opera bookmark
    alert("Seu navegador nao da suporte a este recurso\n Pressione: Ctrl + T");
  }
}

modbr.setHelpPage = function(pagina){
  this.HelpPage = pagina;
}

modbr.configHome = function(){
  var url = document.location;
  var param = "?HomePage=" + url;
  var link = this.HelpPage + param;
  window.open(link,'',"width=400,height=400,scrollbars=yes");
}

//Funções para controle de TOOLTIPS

function abreTTipRss(){
	document.getElementById('caixattip1').style.display="block"
}
function fechaTTipRss(){
	document.getElementById('caixattip1').style.display="none"
}
function mantem(){
	document.getElementById('caixattip1').style.display="block"
}

//    ///   ///    ///
ToolTip = function(){
  this.ToolTip = ToolTip;
  this.name = 'ToolTip';
  this.version = '1.0v';
  this._msg = "";
  //this._obj = "";
  this._width = 0;
  this._left = 0;
  this._top = 0;
  this._bgcolor = "#000000";
  this._objName = "";
  this._visible = false;
}

tooltip = ToolTip.prototype;

tooltip.setMessage = function(Url){
  if(Url != ""){
    alert(Url);
    var obj = document.createElement("div");
    obj.id = obj + Url + "";
    var strObj = obj + Url + "";
    var pars = '';
    var my_ajax = new Ajax.Updater(strObj,Url,{method: 'get', parameters: pars});
    alert(obj + "");
    alert(obj.innerHTML + "");
  }
}
//Configura a Mensagem a partir de uma div oculta
tooltip.setMessageDiv = function(Div){
  var objDiv;
  if(Div){
    objDiv = document.getElementById(Div);
    this._msg = objDiv.innerHTML; 
  }
}
//Configura Largura
tooltip.setWidth = function(WidthPixel){
  if(WidthPixel){
    this._width = WidthPixel;
  }
}
//Configura Distancia em relacao ao Objeto
tooltip.setLeft = function(LeftPixel){
  if(LeftPixel){
    this._left = LeftPixel;
  }
}
//Configura Altura em relacao ao Objeto
tooltip.setTop = function(TopPixel){
  if(TopPixel){
    this._top = TopPixel;
  }
}
//Configura Fundo de tela do Objeto
tooltip.setBgColor = function(BgColorPixel){
  if(BgColorPixel){
    this._bgcolor = BgColorPixel;
  }
}

//Action = open || close
tooltip.execute = function(act,objectID){
  var object = document.getElementById(objectID);
  var Nome = "ToolTip" + objectID;
  if(!document.getElementById(Nome)){
    var strLi = object.innerHTML;
    var strCont = "";
    this._objName = "ToolTip" + objectID;
    
    strCont += "<div id=\"" + this._objName + "\" ";
    strCont += "class='toolTip' ";
    strCont += "style=\"";
    strCont += "width: " + this._width + "px;";
    strCont += "left: " + this._left + "px;";
    strCont += "top: " + this._top + "px;";
    strCont += "background-color: " + this._bgcolor + ";";
    strCont += "position: absolute" + ";"; 
    strCont += "display: block" + ";";
    strCont += "\">" + this._msg;
    strCont += "</div>";
    
    this._visible = false;
    
    if(act == "open"){
      object.innerHTML += strCont;
      var objTool = document.getElementById(this._objName);
      Rico.Corner.round(objTool,{color: this._bgcolor, border: '#000000'});
    }
  }else{
    if(act == "open"){
      //object.innerHTML += strCont;
      var objTool = document.getElementById(this._objName);
      //Rico.Corner.round(objTool,{color: this._bgcolor, border: '#000000'});
      objTool.style.display = "block";
    }else if(act == "close"){
      var objTool = document.getElementById(this._objName);
      objTool.style.display = "none";
    }
  }
}





