/*<![CDATA[*/
//******************************************************************************
// @name:        noticia_interna.js
// @purpose:     scripts que sao utilizados na interna de noticia.
//
//
// @author:      Ruhan Bidart - ruhan@2xt.com.br
// @created:     22/02/2008
//******************************************************************************
window.onload = function() {
    // inicia o script de voto
/*	var titulo_pag = document.getElementById('titulo_template');
	var titulo_noticia = document.getElementById('titulo_noticia').innerHTML;
	titulo_pag.innerHTML = titulo_noticia; */
    
	Noticia.Comentario.get_imagem_randomica(); // inicia a imagem randomica	
    //Noticia.Avaliacao.iniciar('avaliacao');
    //Noticia.adicionar_view(); // adicionando um view na noticia
	/*var div_imagem = document.getElementById('corpo_pagina').getElementsByTagName('div');
    for(i=0;i<div_imagem.length;i++){
		if(div_imagem[i].getAttribute('id') == "div_imagem"){
			var img= div_imagem[i].getElementsByTagName('img');
			var largura = img[0].width - 35;
			var div = div_imagem[i].getElementsByTagName('div');
			div[0].style.width = img[0].width+'px';
			div[1].style.width = largura+'px';
		}
    }
   */
    if(document.all) Noticia.Fix.IE();    
}

Noticia = {
    _padrao_cookie_views : 'cbnews_noticia_visualizada',
    _padrao_cookie_avaliacao : 'cbnews_noticia_avaliacao',    
    // atividades relacionadas a noticia 
	
	isEmail : function(email){
		validEmail = /^([\w\.\-])+@+([\w\.\-])+([\.])+([\w\.\-])+$/i;
		return validEmail.test(email);
	},
	
	isEmpty : function(s){
		var re = /\s/g;
		var s  = s.replace( re , "" );
		RegExp.multiline = true;
		return ( s.length == 0 || s == '0,0' ) ? true : false;
	},
	
	logar : function() {	   
        //alert('Aguarde...', 'aguarde');
		var form = document.forms['logon'];
		var div_login = document.getElementById('div_login');
		var nome = document.getElementById('nome');
		var email = document.getElementById('email');
		var id_usuario = document.getElementById('id_usuario');
		var div_comentario = document.getElementById('div_comentario');
		var div_valores = document.getElementById('div_valores');
        with(form){
			var errs = [];
			if (!Noticia.isEmail(email_login.value) && !Noticia.isEmpty(email_login.value))errs.push('Digite um e-mail válido.');
			if (password.value == '') errs.push('\nInforme sua senha');
			if(email_login.value == '') errs.push('Informe seu email');
			if (errs.length > 0){
				alert('Ocorreram algum(ns) erro(s):<br />' + errs.join('<br />'),'erro');
				return false;
			}
			
		
		
    	var handler = new XMLHandler();
    	var xmlreq = new XMLClient(URL_AUTENTICA, true);
    	xmlreq.addParam('login',email_login.value);
    	xmlreq.addParam('senha',password.value);
    	handler.onError = function(e) { throw(e); } 
    	handler.onProgress = function() {}
    	handler.onInit = function() {}
    	handler.onLoad = function (xml){
		    values = eval(xml)
			if(values[0] != 'error'){
			    document.getElementById('bt_logar').disabled = true;
				div_login.style.display = 'none';
				div_comentario.style.display = 'block';
				div_valores.style.display = 'block'; 
				nome.value = values[0];
				email.value = values[1];
                id_usuario.value = values[2];				
			}else{
				div_login.style.display = 'block';
				div_comentario.style.display = 'none';
				div_valores.style.display = 'none';
				alert('Dados inválidos.','erro')
			}
    	} 
    	xmlreq.query(handler); 
        }		
	},
	
	 
	
    enviar_amigo : function(args) {
        if (!args) var args = {'width' : 450, 'height' : 350};
        var attributes = '';
        // coloca os atributos informados e assenta de forma que a janela fique no 
        // centro da tela
        for (var i in args) attributes += ("," +  i + "=" + args[i]); 
        if (args.width && args.height) {
            var winl = (screen.width - args.width)/2;
            var wint = (screen.height - args.height)/2;
        } else {
            var winl = (screen.width)/2;
            var wint = (screen.height)/2;
        }
        if (winl < 0) winl = 0;
        if (wint < 0) wint = 0;
        attributes += ", top=" + wint + ", left=" + winl;
		var url_estatica = document.getElementById('a_url').href;
		 
         window.open(URLENVIE	+ '?url=' + escape(url_estatica) + '&titulo=' + TITULO, 'popup', attributes);
    },
        
	_set_title : function(){
		var titulo_pag = document.getElementById('titulo_template');
		var titulo_noticia = document.getElementById('titulo_noticia').innerHTML;
		titulo_pag.innerHTML = titulo_noticia;
	
	},	
		
    adicionar_view : function() {
        // verificando se ja foi vista
        if(Cookie.get_cookie(Noticia._padrao_cookie_views + ID_NOTICIA)) return;
        // adicionando o cookie        
        Cookie.set_cookie(Noticia._padrao_cookie_views + ID_NOTICIA, 'visited', 365);
        var handler = new XMLHandler();
        var xmlreq = new XMLClient(URL_NOTICIA_VIEW, true);
        xmlreq.addParam('id_noticia', ID_NOTICIA);

        handler.onError = function (e) { throw(e); }
        handler.onProgress = function () {}
        handler.onInit = function() {}
        handler.onLoad = function (xml) {}
        xmlreq.query(handler);
    },
    
    imprimir : function() {
        window.print();
		return; 
    },
    
    mostrar_balao_tag : function(obj, tag) {
        var bwidth = document.body.offsetWidth;
        var width = obj.offsetWidth;
    
        var curleft = 0;
        var curtop = 0;
        if(obj.offsetParent) {
            while(1) {
                curleft += obj.offsetLeft;
                curtop += obj.offsetTop;
                if(!obj.offsetParent)
                    break;
                obj = obj.offsetParent;
            }
        } else if(obj.x) {
            curleft += obj.x;
            curtop += obj.y;
        }
        var o = document.getElementById('tag_f5');
        o.innerHTML = TAGS[tag];
		
        var nleft = curleft + width;
        if (nleft > bwidth)
           o.style.left = (curleft - o.offsetWidth) + 'px';
        else
           o.style.left = nleft + 'px';
    
        if (document.all) o.style.top = curtop + 'px'; 
        else o.style.top = (curtop + obj.offsetHeight) + 'px';
           
        o.style.visibility = 'visible';
    },

    esconder_balao_tag : function() {
        var o = document.getElementById('tag_f5');
        o.style.visibility = 'hidden';
    }, 
	
	
	set_session : function(e_tag) {
        alert('Aguarde..','aguarde')
        var handler = new XMLHandler();
		 		
  		var xmlreq = new XMLClient(URL_NOTICIA_SESSION, true);
   		xmlreq.addParam('id_noticia', ID_NOTICIA);
   		xmlreq.addParam('tag', e_tag.getAttribute('tag'));
   		handler.onError = function(e) { throw(e); } 
   		handler.onProgress = function() {}
   		handler.onInit = function() {}
   		handler.onLoad = function (xml){
			    var values = eval(xml);
    			if (values == '1') window.location.href = URL_BUSCA_TAG;
    	} 
    	xmlreq.query(handler);	
	},
    
	_abrir_geral : function(url, width, height, janela) {
        var winl = (screen.width - width)/2;
        var wint = (screen.height - height)/2;
		var union = '';
        if (winl < 0) winl = 0;
        if (wint < 0) wint = 0;
		if(url.indexOf('?') == -1 ) union = '?'
		else{
		   union = '&' 
		} 
        url += union +'opener='+ location.href;
		
        var attributes = 'width=' + width + ', height=' + height + ', scrollbars=yes';
        attributes += ", top=" + wint + ", left=" + winl;
	    window.open(url, janela, attributes);
		
		 
    },
    
    abrir_enquete : function(url) {
        Noticia._abrir_geral(url, 725, 450, 'enquete');	     
    },
    
    abrir_promocao : function(url) {
        Noticia._abrir_geral(url, 740, 431, 'promocao');	         
    },
    
    abrir_forum : function(url) {
        Noticia._abrir_geral(url, 720, 470, 'forum');	         
    },

    abrir_quizz : function(url) {
        Noticia._abrir_geral(url, 720, 430, 'quizz');	         
    },

    abrir_galeria : function(url) {
        Noticia._abrir_geral(url, 700, 590, 'galeria');	         
    },

    email_para: function(email, subject, message) {
        var mailto_link = 'mailto:' + email + '?subject=' + subject + '&body=' + message;
        win = window.open(mailto_link,'emailWindow');
        if (win && win.open &&!win.closed) win.close();    
    },
       
    // atividades relacionadas a fonte
    Fonte : {
        _font_min : 12,        
        _font_max : 20,
        _tags : ['div', 'p', 'h1', 'h2', 'span', 'a','f5','strong'],
        aumentar : function(quant) {
            // validacoes      
            var e_corpo_noticia = document.getElementById('corpo_noticia');
            if (typeof(e_corpo_noticia) != 'object') return; 
            var atual_size = e_corpo_noticia.style.fontSize;             
            // apanhando o tamanho atual
            if(!atual_size) atual_size = 12;
            else atual_size = parseInt(atual_size.replace('px'));
            if(atual_size >= Noticia.Fonte._font_max) return;            
            Noticia.Fonte.modificar_geral(e_corpo_noticia, atual_size + quant);            
        },
        
        diminuir : function(quant) {
            // validacoes      
            var e_corpo_noticia = document.getElementById('corpo_noticia');
            if (typeof(e_corpo_noticia) != 'object') return; 
            var atual_size = e_corpo_noticia.style.fontSize;             
            // apanhando o tamanho atual
            if(!atual_size) atual_size = 12;
            else atual_size = parseInt(atual_size.replace('px'));
            if(atual_size <= Noticia.Fonte._font_min) return;             
            Noticia.Fonte.modificar_geral(e_corpo_noticia, atual_size - quant);            
        }, 
        
        modificar_geral : function(el, size) { 
            el.style.fontSize = size + 'px';
            document.getElementById('bigode').style.fontSize = size + 'px';
			document.getElementById('legenda_publicacao').style.fontSize = size + 'px';
			document.getElementById('legenda_atualizacao').style.fontSize = size + 'px';
			document.getElementById('corpo_publicacao').style.fontSize = size + 'px';
			document.getElementById('corpo_atualizacao').style.fontSize = size + 'px';
			
            var tags = Noticia.Fonte._tags;
            for(var i in tags) {
                // variando nos elmentos e modificando as fontes
                // corrige um eventual "bug" devido a tag dentro de tag
                var l_els = el.getElementsByTagName(tags[i]);
                for(var i=0; i< l_els.length; i++) {
                    l_els[i].style.fontSize = size + 'px';
                }
            }
        }
    },

    // atividades relacionadas ao comentario
    Comentario : {
        _caracteres_max : 600,
        enviar : function() {      					
				var div_imagem_erro = document.getElementById('div_imagem_null');
				var div_imagem_null = document.getElementById('div_imagem_null');
				var div_comentario_null = document.getElementById('div_comentario_null');
				var div_ok = document.getElementById('div_ok');
				var div_erro = document.getElementById('div_erro');
				var div_email_invalido = document.getElementById('div_email_invalido');
				var div_nome_null = document.getElementById('div_nome_null');
				var email = document.getElementById('email');
				var nome = document.getElementById('nome');
				var comentario =  document.getElementById('comentario');
				var cod_imagem =  document.getElementById('letras');
				var blog = document.getElementById('blog').value;

				
				if(nome.value == ''){
					div_nome_null.style.display='block'	;
					div_comentario_null.style.display = 'none';
					div_imagem_null.style.display = 'none';
					div_ok.style.display = 'none';
					div_erro.style.display = 'none' ;
					div_email_invalido.style.display = 'none' ;
					nome.focus();
				} else if(!Noticia.isEmail(email.value)){
					div_email_invalido.style.display = 'block';
					div_imagem_null.style.display = 'none';
					div_nome_null.style.display='none'	;
					div_comentario_null.style.display = 'none';
					div_ok.style.display = 'none';
					div_erro.style.display = 'none' ;
					email.focus();
				}else if(comentario.value == ''){
					div_email_invalido.style.display = 'none';
					div_imagem_null.style.display = 'none';
					div_nome_null.style.display='none'	;
					div_comentario_null.style.display = 'block';
					div_ok.style.display = 'none';
					div_erro.style.display = 'none' ;
					comentario.focus();		
						
				}else if(cod_imagem.value == ''){
					div_imagem_null.style.display = 'block';
					div_email_invalido.style.display = 'none';
					div_nome_null.style.display='none'	;
					div_comentario_null.style.display = 'none';
					div_ok.style.display = 'none';
					div_erro.style.display = 'none' ;	
					cod_imagem.focus();
				}else{
					
					div_imagem_null.style.display = 'none';
					div_email_invalido.style.display = 'none';
					div_nome_null.style.display='none'	;
					div_comentario_null.style.display = 'none';
					div_ok.style.display = 'none';
					div_erro.style.display = 'none' ;
				
					var handler = new XMLHandler();
					var xmlreq = new XMLClient(URL_POSTAR, true);
					// setando para ser sincrono
					xmlreq.setAsync(false);
					handler.bdoAsync = false;
					xmlreq.addParam('id_noticia',ID_NOTICIA);
					xmlreq.addParam('comentario',comentario.value);
					xmlreq.addParam('nome',nome.value);
					xmlreq.addParam('email',email.value);
					xmlreq.addParam('confirma',cod_imagem.value);
					if (blog.length > 7) xmlreq.addParam('blog',blog);
					xmlreq.query(handler);                        
					var postado = parseInt(xmlreq.oXMLRequest.responseText);
					if(postado == 2){
						div_imagem_erro.style.display = 'block';
						div_ok.style.display = 'none';
					}else if(postado == 1){
						div_imagem_erro.style.display = 'none';
						div_ok.style.display = 'block';
												
						//limpa todos os campos
						nome.value = '';
						email.value = '';
						comentario.value = '';
						cod_imagem.value = '';
						get_imagem_randomica();
					
					}
					
						
				}
	
  	 	  },
			  
			  
			  get_imagem_randomica : function() {
					document.getElementById('imagem_randomica').src = URL_IMAGEM_RANDOMICA + '?id=' + Math.random();
				},
					
					verificar_caracteres : function(sender, e_contador) {
						var content = sender.value;
						if(document.all) sender.style.width = '225px'
						if(content.length >= 600) sender.value = content.substring(0, Noticia.Comentario._caracteres_max); 
						if(typeof e_contador == 'object') e_contador.innerHTML = sender.value.length;
						else document.getElementById(e_contador).innerHTML = sender.value.length;
					},		
        mudar_aba : function() {},
        
        ir_para : function() {
            var e_bloco_comentarios = document.getElementById('bloco_comentarios');        
            window.scrollTo(0, e_bloco_comentarios.offsetTop);
            mudar_aba(2, 'defalt');
        },
 
        nao_cadastrado : function() {
            var e_new_window = window.open(URL_CADASTRO);
        }
    },
    
    // atividades relacionadas a avaliacao da noticia
    Avaliacao : {
        _e_imgs : null,
        iniciar : function(e_pai) {
            var nota = Cookie.get_cookie(Noticia._padrao_cookie_avaliacao + ID_NOTICIA);
            // mudando o texto de avaliacao
            if(nota) document.getElementById('texto_avaliacao').innerHTML = 'Você avaliou esta notícia';
            if(typeof e_pai == 'string') e_pai = document.getElementById(e_pai);
            var l_e_imgs = e_pai.getElementsByTagName('img');
            Noticia.Avaliacao._e_imgs = l_e_imgs;
            for(var i=0; i<l_e_imgs.length; i++) {
                // verificando a nota e deixando marcado
                if(nota) {
                    if(i < nota) {
                        l_e_imgs[i].style.cursor = 'not-allowed';
                        l_e_imgs[i].src = l_e_imgs[i].getAttribute('ativa');
                    }
                } else {
                    l_e_imgs[i]['onmouseover'] = new Function('Noticia.Avaliacao.mouse_over(this)');
                    l_e_imgs[i]['onmouseout'] = new Function('Noticia.Avaliacao.mouse_out(this)');                
                    l_e_imgs[i]['onmousedown'] = new Function('Noticia.Avaliacao.avaliar(this, ' + (i+1) + ')');                                                
                    l_e_imgs[i].style.cursor = 'pointer';                
                }
            }    
        },
        
        mouse_over : function(el) {
            var l_e_imgs = Noticia.Avaliacao._e_imgs;

            for(var i=0; i<l_e_imgs.length; i++) {
                l_e_imgs[i].src = el.getAttribute('ativa');
                if(el == l_e_imgs[i]) break;             
            }
        },
        
        mouse_out : function(el) {
            var l_e_imgs = Noticia.Avaliacao._e_imgs;
            for(var i=0; i<l_e_imgs.length; i++) {            
                l_e_imgs[i].src = el.getAttribute('inativa');
            }
        },

        avaliar : function(el, nota) {
            // verificando se ja foi votada
            if(Cookie.get_cookie(Noticia._padrao_cookie_avaliacao + ID_NOTICIA)) return;
            // enviando o voto            
            var handler = new XMLHandler();
            var xmlreq = new XMLClient(URL_NOTICIA_AVALIAR, true);
            xmlreq.addParam('id_noticia', ID_NOTICIA);
            xmlreq.addParam('nota', nota);                
      
            handler.onError = function (e) { throw(e); }
            handler.onProgress = function () {}
            handler.onInit = function() {}
            handler.onLoad = function (xml) {
                if(!eval(xml)) {
                    Noticia.Comentario.ir_para(); 
                    alert('Voc&ecirc; precisa estar logado para avaliar uma not&iacute;cia.');
                    mudar_aba(1, 'defalt');
                    return;
                } else {
                    // adicionando o cookie        
                    Cookie.set_cookie(Noticia._padrao_cookie_avaliacao + ID_NOTICIA, nota, 365);
                    // deixando o que o usuario votou selecionado
                    var l_e_imgs = Noticia.Avaliacao._e_imgs;
                    for(var i=0; i<l_e_imgs.length; i++) {            
                        l_e_imgs[i]['onmouseover'] = null;
                        l_e_imgs[i]['onmouseout'] = null;
                        l_e_imgs[i]['onmousedown'] = null; 
                        l_e_imgs[i].style.cursor = 'not-allowed';                                
                    }
                }
            }
            xmlreq.query(handler);
        }        
    },
    
    // relacionado a correcao de bugs nos browsers
    Fix : {        
        IE : function() {
            // corrige o bug com relacao ao layout das imagens 
            var l_e_imgs = getElementsByNameFix('imagem_noticia', 'img');
            for(var i=0; i<l_e_imgs.length; i++) {
                l_e_imgs[i].parentNode.style.width = l_e_imgs[i].width;
            }
        }
    }
}

// implementa um getElementsByName para o IE (correct bug)
function getElementsByNameFix(name, tag) {
     // reformulando para o IE (bug)
     var arr = new Array();
     if(document.all) {
         var elem = document.getElementsByTagName(tag);
         for(i = 0, iarr = 0; i < elem.length; i++) {
             var att = elem[i].getAttribute("name");
             if(att == name) {
                 arr[iarr] = elem[i];
                 iarr++;
             }
         }
      } else { arr = document.getElementsByName(name); }
      return arr;
}

/*]]*/


