/*---------- ALTERAR APENAS ESTES ITENS ----------*/
var formNomeCanal = "Fabrica"; //nome do canal que será utilizado no envio do formulário
var formEmailFale = "fabrica@email.com"; //email do canal que será utilizado no envio do formulário

/*---------- Funções básicas ----------*/
d=document;
IE=d.all?true:false;
function $(id){return d.getElementById(id)}

//Monta e corrige a url completa (ex: http://www.site.com.br/diretorio/arquivo.html)
var urlSite=location.href.toString();
while(urlSite.indexOf("//")!=-1){ 
  urlSite=urlSite.replace("//","/") 
} 
urlSite=urlSite.replace("http:/","http://")

//Monta o dominio considerando o ambiente (producao ou homolog)
var nomeSiteHomolog = "";
if (window.location.href.indexOf('publicador') >-1){var nomeSiteHomolog = "/hotsites";}
var pathPadrao = "http://"+location.host+nomeSiteHomolog;

function linkPage(){
  url=urlPagina;
  while(url.indexOf("//")>1){
    url=url.replace(/\/\//g,"/")
  }
  return url.replace("http:/","http://");
}

function path(){
  return linkPage().replace(urlBase+pathEspecial,"");
}

function setLinkLogo(){
  $('logoCanal').href=urlBase+pathEspecial;
  $('logoCanal').title=nomeEspecial;
}

//Breadcrumbs
//corrige indexOf emm Arrays no ie
if(!Array.indexOf){Array.prototype.indexOf = function(obj){for(var i=0; i<this.length; i++)if(this[i]==obj){return i};return -1;}}

function BreadCrumbK(tree,          // Árvore amigável de breadcrumbs
                     url,
                     urlBase,       // Porção inicial a desconsiderar 
                     nomeBase,      // Título-base
                     separador      // Opcional
                     ) {
                     
  this.site = this.link(urlBase, nomeBase).link;
  if(separador) this.separador = separador;
    
  this._buildTree(tree);

  this.item = [];   
  this.empilhamento = false;

  var temEmpilhamento = url.indexOf("/veja_mais/") != -1;  
  var anterior = urlBase;
  var extracao = this.stripBase(url, urlBase).split("/");
    
  for(var i = 0; i < extracao.length; i++) {
    var ocorrencia = this.secao.url.indexOf(extracao[i]);
    if(ocorrencia != -1) {
      this.item[this.item.length] = this.link(
        (anterior = anterior + extracao[i] + "/"),
        this.secao.nome[ocorrencia] 
      )
      
      if(temEmpilhamento && this.secao.empilhamento[ocorrencia] != null){
        this.pageName = this.secao.empilhamento[ocorrencia];
        this.empilhamento = true;
      }      
    }
  }
}

BreadCrumbK.prototype.separador = " › ";

// Remove caminho base da url
BreadCrumbK.prototype.stripBase = function(url, base) {
  return url.replace(base, "");
}

// Estrutura interna de breadcrumbs
BreadCrumbK.prototype.secao={url:[], nome:[], empilhamento:[]}; 

// Inicialização da estrutura de breadcrumbs
BreadCrumbK.prototype._buildTree = function(tree) {
  with(this.secao) {
    for(x=0; x < tree.length; x++){
      url[x]  = tree[x][0];
      nome[x] = tree[x][1];
      empilhamento[x] = (tree[x][2] ? tree[x][2] : null);
    }
  }
}

BreadCrumbK.prototype.link = function(url, nome) {
  return {'link': '<a href="' + url + '">' + nome + '</a>', 'nome': nome}; 
}

BreadCrumbK.prototype.print=function(){
  with(this){
    document.write('<a href="http://www.ig.com.br/" title="Home iG">Home iG</a>');
    document.write(separador + site + separador)
    
    for(x = 0; x < item.length - 1; x++)
      document.write(item[x].link + separador);

    //lastItem = empilhamento ? item[x].link + separador + pageName : item[x].nome;
    lastItem = empilhamento ? pageName : item[x].nome;
    document.write(lastItem);
  }
}


function breadCrumbGaleria(){
  var bc = new BreadCrumbK(tree, linkPage(), urlBase, nomeBase, separador_BreadCrumb); // (Separador opcional)
  bc.print()
}


function checaBarraiG() {
  if(window.name!="Galeria"){
    document.getElementById("barra_ig").style.display='block';
    document.getElementById("footer").style.display='block';
  }
}

function $request(name){
	var regexS = "[\?&]"+name+"=([^&#]*)";
	var regex = new RegExp ( regexS );
	var tmpURL = window.location.href;
	var results = regex.exec( tmpURL );
	if( results == null ){
		return"";
	}else{
		return results[1];
	}
}

function showHideCredito(){
  document.getElementById('brtpCreditoFoto').style.display="none";
  if(document.getElementById('brtpCreditoFoto').innerHTML != "&nbsp;")document.getElementById('brtpCreditoFoto').style.display="block";
}

/*---------- TAGS OPEC ----------
function OAS_VARS(OAS_page) {
OAS_sitepage = endereco_opec + OAS_page;
OAS_VARSpos('Position1');
}

function OAS_VARSpos(OAS_pos) {
OAS_listpos =  OAS_pos;}
OAS_url = 'http://adserver.ig.com.br/RealMedia/ads/';
OAS_query = '';
OAS_target = '_blank';
OAS_version = 10;
OAS_rn = '001234567890'; OAS_rns = '1234567890';
OAS_rn = new String(Math.random()); OAS_rns = OAS_rn.substring(2, 11);
function OAS_NORMAL (pos) {
 document.write('<a href="' + OAS_url + 'click_nx.ads/' + OAS_sitepage + '/1' + OAS_rns + '@' + OAS_listpos + '!' + pos + '?' + OAS_query + '" target="'+ OAS_target + '">');
 document.write('<img src="' + OAS_url + 'adstream_nx.ads/' + OAS_sitepage + '/1' + OAS_rns + '@' + OAS_listpos + '!' + pos + '?' + OAS_query + '" border="0"></a>');}

function OAS_START() {
OAS_version = 11;
if (navigator.userAgent.indexOf('Mozilla/3') != -1 || navigator.userAgent.indexOf('Mozilla/4.0 WebTV') != -1)
 OAS_version = 10;
if (OAS_version >= 11)
 document.write('<SCRIP' + 'T LANGUAGE=JavaScript1.1 SRC="' + OAS_url + 'adstream_mjx.ads/' + OAS_sitepage + '/1' + OAS_rns + '@' + OAS_listpos + '?' + OAS_query + '"><\/SCRIP' + 'T>');
}
document.write('');
function OAS_AD(pos){
 if (OAS_version >= 11)
  OAS_RICH(pos);
 else
  OAS_NORMAL(pos);}

function OPEC_START(){
  OAS_VARS(OAS_page);
  OAS_START();
}

function head_init(){
  OPEC_START();
}

*/

/*-------------------- COMPLEMENTOS AJAX --------------------*/
var secao={
url:[
"/galeria/"
],

nome:[
"Galeria"
],

complemento:[
"/complemento/"
]
};

for(_x=0;_x<secao.url.length;_x++){
	if(urlSite.indexOf(secao.url[_x])>-1){
	  secaoNome=secao.nome[_x];
	  secaoComplemento=secao.complemento[_x];
	}
}

function _xStart(){
  if(secaoComplemento!=null)_xCopy(pathPadrao+secaoComplemento);//CARREGA OS COMPLEMENTOS;
}

function getHTTPObject(){if(window.XMLHttpRequest){return new XMLHttpRequest();} else if(window.ActiveXObject){var prefs = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];for(var i = 0; i < prefs.length; i++){try{return new ActiveXObject(prefs[i] + ".XMLHTTP");} catch(e){}}}}

function rx($u){return new RegExp("<"+$u+">(.*)</"+$u+">")}

function _xCopy($path) {
    _objg = new getHTTPObject();
    _n = parseInt(Math.random()*1000000);
    _objg.open('GET', $path+"?" + _n, true);
    _objg.onreadystatechange = function() {
        if(_objg.readyState == 4) {
            if(_objg.status == '200') txt= _objg.responseText.replace(/\r\n/g, "");
        }
    };
    _objg.setRequestHeader('Content-type', 'text/html; charset=ISO-8859-1');
    _objg.send(null);
}

var area={//areas que vem por ajax;
  ultimasGalerias:"ultimas_galerias",
  ultimasGaleriasGaleria:"ultimas_galerias_galeria",
  rodape:"rodape_site"
}

function ultimasGalerias(){
  var $u=area.ultimasGalerias;
  $("x_"+$u).innerHTML=rx($u).exec(txt)[1];
}

function ultimasGaleriasGaleria(){
  var $u=area.ultimasGaleriasGaleria;
  $("x_"+$u).innerHTML=rx($u).exec(txt)[1];
}

function footer(){
	var $u=area.rodape;
 	$("x_"+$u).innerHTML=rx($u).exec(txt)[1];
}

_xStart();

/*---------- Função para mostrar a janela de envio de email da galeria ----------*/
function toggleSendMail(){	
	fd=document.getElementById("fade").style
	fd.display=(fd.display=="block")?'none':'block'
	en=document.getElementById("envie").style
	en.display=(en.display=="block")?'none':'block'
	fs=document.getElementById("envie").getElementsByTagName("fieldset");
	fs[0].style.display='block'
	fs[1].style.display='none'
	return false
}

function toggleSendMailOk(){
	en=document.getElementById("envie").getElementsByTagName("fieldset");
	en[0].style.display=(en[0].style.display=="block")?'none':'block'
	en[1].style.display=(en[0].style.display=="block")?'none':'block'
}

/*---------- Formulários ----------*/
function envieAmigo(){
    var form_envieAmigo='<form name="formEnvie" action="http://generico.ig.com.br/faleconosco/novashomes/faleconosco.php" method="post" enctype="application/x-www-form-urlencoded" onSubmit="return validaForm();">'+
        '<fieldset id="envio">'+
          '<input type="hidden" name="opcao" value="ENVIE_AMIGO" />'+
          '<input type="hidden" name="nomecanal" value="'+formNomeCanal+'" />'+
          '<input type="hidden" name="emailfale" value="'+formEmailFale+'" />'+
          '<input type="hidden" name="urlpagina" />'+
          '<input type="hidden" name="urlretorno" />'+
          '<input type="hidden" name="copia" value="0" />'+
          '<h2>Envie para um amigo</h2>'+
          '<label for="nome">Seu nome:</label><input id="nome" type="text" name="nome" title="Seu nome" alt="Seu nome" class="field" />'+
          '<label for="email">Seu e-mail:</label><input id="email" type="text" name="email" title="Seu e-mail" alt="Seu e-mail" class="field" />'+
          '<label for="nome_dest">Nome do destinatário:</label><input id="nome_dest" type="text" name="nome_destinatario" title="Nome do destinatário" alt="Nome do destinatário" class="field" />'+
          '<label for="email_dest">E-mail do destinatário:</label><input id="email_dest" type="text" name="email_destinatario" title="E-mail do destinatário" alt="E-mail do destinatário" class="field" />'+
          '<input type="submit" value="enviar" title="enviar" alt="enviar" class="submit send" />'+
          '<input type="button" value="cancelar" title="cancelar" alt="cancelar" class="submit cancel" onclick="toggleSendMail();void(0)" />'+
        '</fieldset>'+
        '<fieldset id="retorno" class="sucesso" style="display:none">'+
          '<h2>Envie para um amigo</h2>'+
          '<label>'+
            'Sua mensagem foi enviada com sucesso!<br />'+
            'Deseja enviar para mais alguém?'+
          '</label>'+
          '<input type="button" value="sim" title="sim" alt="sim" class="submit yes" onclick="toggleSendMailOk();void(0)" />'+
          '<input type="button" value="não" title="não" alt="não" class="submit no" onclick="toggleSendMail();void(0)" />'+
        '</fieldset>'+
		'</form>';
		document.write(form_envieAmigo);
}

function checaEnvio(){
  if($request('enviado')=='true'){
    toggleSendMail();
    $('envio').style.display="none";
    $('retorno').style.display="block";
  }
  document.formEnvie.urlpagina.value = location.href.toString();
  var str = "?enviado=true";
  document.formEnvie.urlretorno.value = location.href.toString().indexOf("enviado")>-1?location.href.toString():location.href.toString()+str;
}

function validaForm(){
	//validar nome
	d = document.formEnvie;
	if (d.nome.value == ""){
		alert("O campo " + d.nome.name + " deve ser preenchido!");
		d.nome.focus();
		return false;
	}
	//validar user
	if (d.email.value == ""){
		alert("O campo " + d.email.name + " deve ser preenchido!");
		d.email.focus();
		return false;
	}
	//validar senha
	if (d.nome_destinatario.value == ""){
		alert("O campo " + d.nome_destinatario.name + " deve ser preenchido!");
		d.nome_destinatario.focus();
		return false;
	}
	//validar email
	if (d.email_destinatario.value == ""){
		alert("O campo " + d.email_destinatario.name + " deve ser preenchido!");
		d.email_destinatario.focus();
		return false;
	}
	//validar email(verificao de endereco eletronico)
  var regexp= new RegExp("^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*@([_a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)$");
  if(!regexp.test(d.email.value)){
    alert("O campo " + d.email.name + " deve ser um endereco eletronico!");
		d.email.focus();
		return false;
	}
	
	//validar email2(verificao de endereco eletronico)
  if(!regexp.test(d.email_destinatario.value)){
    alert("O campo " + d.email_destinatario.name + " deve ser um endereco eletronico!");
		d.email_destinatario.focus();
		return false;
	}
	
	document.formEnvie.submit();
	return true;
}
