﻿//Script para marcacao do menu
function ActiveMenu(identidade){    
    var endereco = location.pathname;
    var links = $('#' + identidade).find('a');
    
    //separo as pastas
    endereco = endereco.split('/');
    
    
    for(var i=0; i<links.length; i++){
        linkQuebrado = $(links[i]).attr('href').split('/')
        
        //se menu superior
        if(identidade == 'menuTop'){
            if((linkQuebrado[1] == endereco[1]) && linkQuebrado[1] != ''){
                $(links[i]).addClass('active');
            }
        }
        //se outros menus
        else{
            if((linkQuebrado[2] == endereco[2]) && linkQuebrado[2] != ''){
                $(links[i]).addClass('active');
            }
        }
    }
}



//Script par acontrolar Exibicao de Banners 
function bannerShow(endereco){

    var bust;
        if (typeof bust == 'undefined') {
        bust = Math.floor(1000000*Math.random());
    }

    //retiro a tipo de arquivo
    endereco = endereco.substring(0,endereco.lastIndexOf('.'))
    endereco = endereco.split('_')

    //descubro a medida e a referencia de pasta onde ficara o banner
    var medida = endereco[endereco.length - 1];
    var local = endereco[endereco.length - 2];

    //separo as medidas
    var medidas = medida.split('x');
    var medidaX = medidas[0];
    var medidaY = medidas[1];
    
    if ((!document.images && navigator.userAgent.indexOf('Mozilla/2.') >= 0) || navigator.userAgent.indexOf("WebTV")>= 0) {
        document.write('<a href="http://ad.doubleclick.net/jump/ng.mobile/' + local + ';sz=7' + medida + ';tile=5;ord='+bust+'">');
        document.write('<img src="http://ad.doubleclick.net/ad/ng.mobile/' + local + ';sz=' + medida + ';tile=5;ord='+bust+'" border="0" height="' + medidaY + '" width="' + medidaX + '"></a>');
    } else {
        document.write('<scr' + 'ipt language="JavaScript1.1" SRC="http://ad.doubleclick.net/adj/ng.mobile/home;dcopt=ist;sz=' + medida + ';tile=5;ord='+bust+'">');
        document.write('<a href="http://ad.doubleclick.net/jump/ng.mobile/' + local + ';sz=' + medida + ';tile=5;ord='+bust+'">');
        document.write('<img src="http://ad.doubleclick.net/ad/ng.mobile/' + local + ';sz=' + medida + ';tile=5;ord='+bust+'" border="0" height="' + medidaY + '" width="' + medidaX + '"></a>');
        document.write('</scr' + 'ipt>');
    }
} 

//Scripts carregados apos o onload da pagina
$(function(){
   
    //Inclui as imagens das curvas laterais nos titulos e subtitulos das páginas (h2 / h3)
    $('h2').before('<img src="/Images/title_right_1.gif" title="" alt="" class="floatRight" /><img src="/Images/title_left_1.gif" title="" alt="" class="floatLeft" />')
    $('h3').before('<img src="/Images/title_right_2.gif" title="" alt="" class="floatRight" /><img src="/Images/title_left_2.gif" title="" alt="" class="floatLeft" />')


    //inclui bordas laterais nos botões floater
    $('.floaterButton').before('<img src="/Images/box_yellow_left.gif" title="" alt="" class="floatLeft" />');
    $('.floaterButton').after('<img src="/Images/box_yellow_right.gif" title="" alt="" class="floatLeft" />');
    
    //inclui bordas laterais nos botões amarelos
    $('.smallButton').before('<img src="/Images/bullet_yellow_left.gif" title="" alt="" class="smallButtonImage" />');
    $('.smallButton').after('<img src="/Images/bullet_yellow_right.gif" title="" alt="" class="smallButtonImage" />');

    //marco o menu Superior
    ActiveMenu('menuTop');
    
    //chamo a fun;cao que pula os campos do formulario
    jump()
    
    //caso click no enter submeto o serach
     pressEnter();
        
    //ajusto a tela do floater no login
    $('.fullOnRight').parent().after('<br class="clear" />');
})

//inclui bordas os botoes da paginacao
function pagingButtons(){
    setTimeout(function(){
        $('.smallButtonImage').remove(); 
        
        //inclui bordas laterais nos botões amarelos
        $('.smallButton').before('<img src="/Images/bullet_yellow_left.gif" title="" alt="" class="smallButtonImage" />');
        $('.smallButton').after('<img src="/Images/bullet_yellow_right.gif" title="" alt="" class="smallButtonImage" />');

    },4000)
}

//caso presione enter submeto o campo seacrh
function pressEnter(e){
    $(document).keydown(
        function(e){
            var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
            
            if(key == 13){
                seacrh('txtSearch');
                submitInfo();
               return false;
            }
        }
    );
}


function jump(){
    $('form:eq(0),body').find('input').keyup(function(){
        if($(this).attr('maxlength') < 0)
            $(this).attr('maxlength','100');
        
        if($(this).val().length >= $(this).attr('maxlength')){
            //guardo os campos input da página
            var inputs = $('input');
       
            //se o input for do tipo texto
            if($(this).attr('type') == 'text')
                inputs.eq( inputs.index( this ) + 1 ).focus();   
        }
    });
}

//submeto o search
function seacrh(container){
    if($('#' + container).val()){
        if($('#' + container).val().length > 0)
            location.href = "/Search/Search-Result.aspx?SearchText=" + $('#' + container).val();
    }
    
}

//submeto os campos dos forularios
function submitInfo(){
    var alreadyUser = $('#floaterLeft').find('input');
    var newUser = $('#floaterRight').find('input');
    
    //Already User
    for(var i=0; i<alreadyUser.length; i++){
        if($(alreadyUser[i]).val()){
            if($(alreadyUser[i]).val().length > 0)
                __doPostBack('ucLogin$btnLogin','');
        }
    } 
    
    //New User
    for(var a=0; a<newUser.length; a++){
        if($(newUser[a]).val()){
             if($(newUser[a]).attr('type') == 'text')    
                if($(newUser[a]).val().length > 0){
                    __doPostBack('ucRegister$btnStepOne','');
            }
        }
    } 
}

//submeto o help
function help(container){
    if($('#' + container).val() != '')
        location.href = "/Help.aspx?Search=" + $('#' + container).val()
}


//inclui seta no hover do item selecionado em Top Downloads
//se existir referencia incial passar o indice na variavel ref

function topControl(menuId,contentId,referencia){
    //guardo os links do Top DOwnloads
    var lis = $('#' + menuId).find('li');
    var divs = $('#' + contentId).find('div')
    var anterior = $(lis[referencia]); 
    var indiceAnterior;
    
    if(referencia)
        indiceAnterior = referencia;
    else
        indiceAnterior = 0;
    
    
    //mostro a 1 div ao carregar a pagina
    $(divs[indiceAnterior]).show('fast');
    
     //maco a 1 li ao carregar a pagina
    $(lis[indiceAnterior]).addClass('active');
    
    
    
    for(var i=0; i<lis.length; i++){
        lis[i].indice = i;
        
        $(lis[i]).click(function(){
            var atual = this.indice;
            
            
            //escondo a div referente ao indice anterior
            $(divs[indiceAnterior]).hide('fast',function(){
                //mostro a div referente ao indice selecionado
                $(divs[atual]).show('fast');
            });
            
            $(anterior).removeClass('active');
            $(this).addClass('active');
            anterior = this;
            indiceAnterior = this.indice;    
        })        
    }
}

//funcao que escurece a pagina e abre uma div no centro da pagina
function fade(address){
    //guardo a altura da página
    var altura = $(document).height();

    //caso o scroll nao esteja no topo subo ele para exibir o conteudo
     $.scrollTo($('#container'), 800);

    //crio uma div que sera posicionada a frente de todo o conteudo
    $('#container').before('<div id="fade"></div>')
    
    //defino a altura 
    $('#fade').css('height', altura + 'px')
    
    //crio a div que recebera o conteudo a sera exibido por cima do fade
    $('#fade').before("<div id='controlaFloater'></div>")
    
    //carrego o conteudo da página login.aspx
    $('#controlaFloater').html('<div id="loginForm"><iframe src="' + address + '" width="500" height="100"  name="iframeFloater" id="iframeFloater" allowtransparency="true" frameborder="0" scrolling="no"></iframe></div>')
    
    //carrego a div
    $('#controlaFloater').css('display','block');
    
   
    //caso clique na div ela fecha automaticamente
    $('#fade').click(function(){
        $('#controlaFloater').remove();
        $('#fade').remove();
        $('#txtSearch').focus();
    })
}

function fadeOut(){
    var controlaFloater = $("#controlaFloater", parent.document.body);
    var fade = $("#fade", parent.document.body);
    var txtSearch = $("#txtSearch", parent.document.body);
    
    $(fade).remove();
    $(controlaFloater).remove();
    $(txtSearch).focus();
    
}

//funcao que calcula o tamanho do pagina e envia a informação ao iframe pai
function calculatesize(){
    var theFrame = $("#iframeFloater", parent.document.body);
    
    $(theFrame).animate({ 
        width: $('#floater').width() + 'px',
        height: $('#floater').height() + 'px'
      }, 500 );
      
      //caso clique no botao fechar
      $('.close').click(function(){
            //removo o floater
            fadeOut()
      })
}

//funcao que fecha a popUp e da reload na pagina
function closeReload(){
    //da reload na tela
     window.parent.location.reload();
}

//funcao que fecha a popUp e redireciona
function closeRedirect(path){
    //da reload na tela
    window.parent.location.href = path;
}

/* 
    ref = recebe a id de referencia, que ira ser a base do valor calculado
    dest = destinatario do valor calculado
    tag = caso o valor a ser adotado seja em uma tag interna a id escreva o nome da tag
    header = caso nao exista um header na div ref, setar valor para esta variavel
*/

//calculo a altura de um elemento e atribuo este valor a outro
function newHeight(ref, dest,tag,header){
  setTimeout(function(){
        var altRef = $('#' + ref).height();
    
        if(!header)
             altRef = altRef - 32;
        else if(header == '0')
            altRef = altRef;
        else
            altRef = altRef - 10;
           
        
       //retiro a diferenca da altura do titulo
        if(tag){
            $('#' + dest).find(tag).css('height',altRef + 'px');
        }
        else{
            $('#' + dest).css('height',altRef + 'px');
        }  
  },1000)
         
  
}

//mudo a imagem do listem ao ser clicada e toco o som
var lastListen

function soundMe(este){
    //limpo os sons anteriores
    clearTimeout(temp)
    
    //se existem um ringtone ja selecionado retiro volto a imagem do fone nele
     if(lastListen){
        
        //caso seja as paginas de checkout incluo a palavra Listen
        if($(este).parent().attr('id') == 'colunLeft')
            $(lastListen).html('<img src="/Images/listen_2.gif" /><span>Listen</span>');
        else
            $(lastListen).html('<img src="/Images/listen_2.gif" />');
        
        
        $(lastListen).removeClass('loadingPlayer');
    }
    
    //se clico no mesmo player enquanto estou tocando (stop), simplesmente paro
    if(lastListen == este){
        //limpo a div que recebe o player
        $('#player').html('');
        
        //limpo o anterior
        lastListen = '';
        
        //limpo os sons anteriores
        clearTimeout(temp)
    }
    else{
        //o ringtone seleciopnado recebe a imagem loading
        $(este).html('<img src="/Images/Load_NatGeo_p.gif" />');
        $(este).addClass('loadingPlayer')
        
        var listenTime = este;
        
       // o payer atual passa a ser o anterior
        lastListen = este;
        
        //guardo o caminho do swf que será tocado
         var endereco = $(este).attr('name');
        
        //limpo a div que recebe o player
        $('#player').html('');
        
        $('#player').html('<iframe src="/Player.aspx?' + endereco + '" width="1" height="1"  name="iframePlayer" id="iframePlayer" allowtransparency="true" frameborder="0" scrolling="no"></iframe>');
        
        //verifico se e IE para dar reload no iframe
        var browserName=navigator.appName;
        
        if (browserName=="Microsoft Internet Explorer")
            iframePlayer.location.reload();

        //após 20 seugndos paro o som e troco a imagem 
        var temp = setTimeout(function(){$(listenTime).find('img').attr('src','/Images/listen_2.gif'); $('#player').html(''); $(lastListen).removeClass('loadingPlayer'); lastListen = ''},40000)

    }
     
}   


//Help
var lastAnswer
function helpMe(itemList){
 
//se existir anterior, escondo
    if (lastAnswer)
        if (($(lastAnswer).find('.answer').html()) != ($(itemList).find('.answer').html()))
            $(lastAnswer).find('.answer').hide('fast');
    
    $(itemList).find('.answer').show('fast');
    lastAnswer = $(itemList);
}

//Gero a numeracao do help
function helpList(indice){
    var indice = indice * 10 - 9;
    
    var helpList = $('.helpList');
    $(helpList).html('');
    
    for(var i=0; i< helpList.length; i++){
       $(helpList[i]).html(indice + i + '. ');
    }
}

//chamando a numeracao apos a paginacao
function pagingHelp(){
    setTimeout(function(){
        var helpList = $('.helpList'); 
        
        if($(helpList[0]).text() == ''){    
           
            var ativo = $('.paging ul li').find('.active');
            var indice = $(ativo).text();
           
           var indice = indice * 10 - 9;
    
            var helpList = $('.helpList');
            $(helpList).html('');
            
            for(var i=0; i< helpList.length; i++){
               $(helpList[i]).html(indice + i + '. ');
            }
        }
        else{
            pagingHelp();
        }
    },100)
}


//funcao que define a altura do scroll
; (function(h) { var m = h.scrollTo = function(b, c, g) { h(window).scrollTo(b, c, g) }; m.defaults = { axis: 'y', duration: 1 }; m.window = function(b) { return h(window).scrollable() }; h.fn.scrollable = function() { return this.map(function() { var b = this.parentWindow || this.defaultView, c = this.nodeName == '#document' ? b.frameElement || b : this, g = c.contentDocument || (c.contentWindow || c).document, i = c.setInterval; return c.nodeName == 'IFRAME' || i && h.browser.safari ? g.body : i ? g.documentElement : this }) }; h.fn.scrollTo = function(r, j, a) { if (typeof j == 'object') { a = j; j = 0 } if (typeof a == 'function') a = { onAfter: a }; a = h.extend({}, m.defaults, a); j = j || a.speed || a.duration; a.queue = a.queue && a.axis.length > 1; if (a.queue) j /= 2; a.offset = n(a.offset); a.over = n(a.over); return this.scrollable().each(function() { var k = this, o = h(k), d = r, l, e = {}, p = o.is('html,body'); switch (typeof d) { case 'number': case 'string': if (/^([+-]=)?\d+(px)?$/.test(d)) { d = n(d); break } d = h(d, this); case 'object': if (d.is || d.style) l = (d = h(d)).offset() } h.each(a.axis.split(''), function(b, c) { var g = c == 'x' ? 'Left' : 'Top', i = g.toLowerCase(), f = 'scroll' + g, s = k[f], t = c == 'x' ? 'Width' : 'Height', v = t.toLowerCase(); if (l) { e[f] = l[i] + (p ? 0 : s - o.offset()[i]); if (a.margin) { e[f] -= parseInt(d.css('margin' + g)) || 0; e[f] -= parseInt(d.css('border' + g + 'Width')) || 0 } e[f] += a.offset[i] || 0; if (a.over[i]) e[f] += d[v]() * a.over[i] } else e[f] = d[i]; if (/^\d+$/.test(e[f])) e[f] = e[f] <= 0 ? 0 : Math.min(e[f], u(t)); if (!b && a.queue) { if (s != e[f]) q(a.onAfterFirst); delete e[f] } }); q(a.onAfter); function q(b) { o.animate(e, j, a.easing, b && function() { b.call(this, r, a) }) }; function u(b) { var c = 'scroll' + b, g = k.ownerDocument; return p ? Math.max(g.documentElement[c], g.body[c]) : k[c] } }).end() }; function n(b) { return typeof b == 'object' ? b : { top: b, left: b} } })(jQuery);

//change device
function changeDevice(maker, model) {
    var phone = $("#cellphone", parent.document.body);

    strHTML = "Phone: <strong>";
    strHTML += maker + " - " + model;
    strHTML += "</strong> ";
    strHTML += "<a href=\"javascript: fade('/CellPhone-Selection.aspx');\" title=\"Change\">Change!</a>";
    strHTML += "<br />";

    $(phone).html(strHTML);
}