var boxGanchoTimeOut = undefined;
var menuNavegacaoTimeOut = undefined;

var addthis_config =
{
 ui_language: document.documentElement.lang
};

$.fn.googleMap = function(address, options) {
  var defaults = {
    lati: -23.484454,
    longi: -47.473302, //DADOS DE LOCALIZAÇÃO DA DIDIER MATRIZ
    zoom: 14,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  options = $.extend(defaults, options || {});

  var center = new google.maps.LatLng(options.lati, options.longi);
  var map = new google.maps.Map(this.get(0), $.extend(options, { center: center }));

  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({ address: address }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK && results.length) {
      if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map
        });

      }
    }
  });
};


function initMap(latitude,longitude,endereco,alvo){
    var myOptions = {
        lati: latitude,
        longi: longitude,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var center = new google.maps.LatLng(myOptions.lati, myOptions.longi);
    var map = new google.maps.Map(alvo, $.extend(myOptions, { center: center }));
    var latlng = new google.maps.LatLng(longitude, latitude);
    map.setCenter(latlng);
    var marker = new google.maps.Marker({
        position: latlng,
        map: map
    });
}

function printIt(getSlug){
$('.txt *').removeClass().attr('style','');
if($('.txt table').size()){
    $('.txt table').attr('border','1').attr('cellpadding','10');
}

var mode = 'normal';
if((location.href).search("mode=simple")!=-1) mode = 'simple';

    $.post($('base').attr('href')+"print.php",{
        title: $('h1').html(),
        content: $('.txt').html(),
        siteName: $('title').text(),
        siteURL: $('base').attr('href').substring(0,$('base').attr('href').length-1),
        slug: getSlug,
        printMode: mode
    },function(html){
        $('body *').css('display','none');
        $('body').css('background','transparent none');
        $('body').append('<div id="print"><!-- --></div>');
        $('#print').css('display','block');
        $('#print').html(html);
        window.print();
    });
}

$(document).ready(function(){
    //ie6 png fix
    if(typeof(DD_belatedPNG)!='undefined'){
        DD_belatedPNG.fixPng($('#cabecalho .logo_site img').get(0));
        DD_belatedPNG.fixPng($('#corpo').append('<div class="clearFull"><!-- --></div>').get(0));
        DD_belatedPNG.fixPng($('#cabecalho').get(0));
    }
    $('#corpo').append('<div class="clearFull"><!-- Correção Bug IE7--></div>');
    $('body').append('<div class="box_gancho hide"><span class="icon box_gancho_gancho"><!-- --></span><span class="icon box_gancho_gancho_bottom"><!-- --></span><h3>...</h3><p>...</p><div class="box_gancho_gancho_map"></div><a href="javascript:;" class="botgen box_gancho_mapa" rel="map">Ver mapa</a></div><div class="box_fast_news"><div class="box_fast_news_top"><!-- --></div><div class="box_fast_news_content"><h5>'+lang['O que é Fast News?']+'</h5><p>'+lang['Boletim com as últimas notícias do mercado financeiro.']+'</p><strong>'+lang['Preencha o campo abaixo com seu email.']+'</strong><form id="formNLAjax" action="http://'+location.hostname+'/proc/newsletter.php?ajax=true" method="POST"><div><input type="text" name="email" class="entTxt required email" /><input type="submit"  value="'+lang['Assinar']+'" class="submit" /></div></form><a href="javascript:;" class="box_fast_news_close" title="Fechar">X</a></div><div class="box_fast_news_bottom"><!-- --></div></div>');
    $('a[rel=external]').attr('target','_blank');
    if(!jQuery.support.htmlSerialize)
        $('a[rel=sidebar]').click(function(){bookmarksite(this);});
    $('a[rel=suggest]').click(function(){
        try{
            $.showAkModal(this.href,this.title,650,450);
            return false;
        }
        catch(e){
            return false;
        }
    });
    $('a[rel=print]').click(function(){printIt(location.pathname);return false;});
    $('a[rel=increasetext]').click(function(){$.FontSizer.IncreaseSize();return false;});
    $('a[rel=decreasetext]').click(function(){$.FontSizer.DecreaseSize();return false;});
    $('a[rel=map]').click(function(){
        try{
            $.showAkModal(this.href,this.title,900,510);
            return false;
        }
        catch(e){
            return false;
        }
    });

    var $ul_navegacao = $('#corpo .menu_nevagacao ul li ul');
    if($ul_navegacao.size()){
        $ul_navegacao.parent().hover(function(){
            var $li = $(this);
            var $ul = $li.children('ul');
            $ul.stop(true,true).css({'display':'block', 'z-index':'0'});
            $li.addClass('selected');
            $li.mouseleave(function(){
                $ul.stop(true,true).css({'display':'none', 'z-index':'0'});
                $li.removeClass('selected');
            });
        });
    }
    $ul_navegacao.each(function(){
        var maxLength = 0;
        var $anchors = $(this).find('a');
        $anchors.each(function(){
            if($(this).text().length>maxLength){
                maxLength = $(this).text().length;
            }
        });
        maxLength =  Math.ceil(maxLength*11);
        $(this).css('width',maxLength+'px');
    });
    $('.bot_assine_fast_news').click(function(e){
        $('.box_fast_news').css({top: e.pageY+'px', left: (e.pageX-50)+'px'}).show();
        $('.box_fast_news_close').click(function(){
            $('.box_fast_news').hide();
        });
        return false;
    });
    if($('form').size())
        $('form').each(function(){
            var $form = $(this);
            if(!$form.hasClass('edit')){
                $form.find('input[type=text], textarea').focus(function(){
                   var $entTxt = $(this);
                   if($entTxt.attr('readonly')|| $entTxt.attr('disabled')){
                       return false;
                   }
                   if($.trim($entTxt.val()) == this.defaultValue)
                        $entTxt.val('');
                }).blur(function(){
                    var $entTxt = $(this);
                    if($.trim($entTxt.val())=='')
                        $entTxt.val(this.defaultValue);
                });
            }
        });
    if($('.mod-convertxtoreal').size())
        $('.mod-convertxtoreal').each(function(){
            var $this = $(this);
            $this.find('select').change(function(){
                var valor = parseFloat($(this).val().replace(',', '.'));
                var taxa = parseFloat($this.find('.mod-convertxtoreal-taxa-valor').text().replace(',', '.'));
                var total = valor*taxa;
                
                if(total>0){
                  var partInt=parseInt(total);
                  var partDec=parseInt((total%1)*100);
                  if (partDec<10) partDec='0'+partDec;
                  $this.find('.mod-convertxtoreal-total-valor').text(partInt+','+partDec);
                }else{
                  $this.find('.mod-convertxtoreal-total-valor').text('0,00');
                }
            }).change();
        });
        $c7_add_this = $('a[id^=blog-post-]');
        if($c7_add_this.size()){
            $c7_add_this.each(function(){
                addthis.button('#'+this.id, {}, {url: this.href, title: $(this).text()});
            });
        }
        $tipo_entrega = $('[name=tipo_entrega]');
        if($tipo_entrega.size())
            $tipo_entrega.click(function(){
             $this = $(this);
                 $tipo_entrega.each(function(){
                    $('.'+$(this).val()).hide().find(':input').attr('disabled','disabled');
                 });
                 $('.'+$this.val()).show().find(':input').removeAttr('disabled');
            });
            $('#box_servicos li:last').each(function(){
                $this = $(this);
                if($this.text().search('Câmbio')>1){
                    $this.css({'background-image':'url(images/bullet_ball_red.gif)', 'background-position': '0 0.55em'}).find('a').css({'color':'#99473e','text-decoration':'none'});
                }
            });
        
        /*    
        $('.mod-convertxtoreal form').submit(function(){
            $(location).attr('href','ecommerce-carteira.html');
            return false;
        });
        */
        
        var $item_address = $('.box-listagem-filiais .item-address');
        if($item_address.size()){
            $item_address.each(function(){
                $this = $(this);

                var $viewmap = $this.find('.item-address-viewmap');
                var $text = $this.find('.item-address-text');
                
                var latitude = parseFloat($this.find('.item-address-latitude').text());
                var longitude = parseFloat($this.find('.item-address-longitude').text());
                var endereco = $.trim($this.find('.item-address-street').text().replace(/\s{1,}/gi,' '))+','+$.trim($this.find('.item-address-city-state').text().replace(/\s{1,}/gi,' '));
                var id = $.trim($this.attr('id').replace('fil-',''));
                var alvo = $('.googlemaps-map-300x300').get(0);
                var $tracerout = $('.googlemaps-traceroute');
                var aux = function(){
                    var address = 'mapa'+($('html').attr('lang')!='pt-br'?'-'+$('html').attr('lang'):'')+'.php?title='+encodeURI($.trim($this.find('.item-address-title').text()))+'&'
                    +'address='+encodeURI(endereco)+'&'
                    +'longitude='+encodeURI(latitude)+'&'
                    +'latitude='+encodeURI(longitude);
                    
                    $tracerout.attr('href',address);
                    
                    //remove class -selected do elemento $viewmap
                    $item_address.parent().find('.item-address-viewmap-selected')
                    .removeClass('item-address-viewmap-selected').addClass('item-address-viewmap');
    
                    //remove class -selected do elemento $text
                    $item_address.parent().find('.item-address-text-selected')
                    .removeClass('item-address-text-selected').addClass('item-address-text');
    
                    //troca mapa(alvo)
                    initMap(latitude,longitude,endereco,alvo);
    
                    //adiciona classe selected aos elements $viewmap e $text
                    $viewmap.removeClass('item-address-viewmap').addClass('item-address-viewmap-selected');
                    $text.removeClass('item-address-text').addClass('item-address-text-selected');                
                }
                $viewmap.click(function(){
                    try{
                     if(isNaN(latitude) || isNaN(longitude)){
                            latitude = -23.484454; //DADOS DE LOCALIZAÇÃO DA DIDIER MATRIZ
                            longitude = -47.473302;
                            getMaps = true;
                            var geocoder = new google.maps.Geocoder();
                            geocoder.geocode({ address: endereco }, function(results, status) {
                                if (status == google.maps.GeocoderStatus.OK && results.length) {
                                    if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                                        var latlng  =  results[0].geometry.location.toString().match(/[+-]?[0-9]+(.[0-9]+)?/g);
                                        latitude = parseFloat(latlng[1]);
                                        longitude = parseFloat(latlng[0]);
                                        $this.find('.item-address-latitude').text(latitude);
                                        $this.find('.item-address-longitude').text(longitude);
                                        $.post($('base').attr('href')+'proc/updMaps.php', {latitude: latitude, longitude: longitude, fil_id: id });
                                        aux();
                                    }
                                }
                            });
                    
                        }
                        else{
                            aux();
                        }                        
                    }
                    catch(e){
                        alert('Desculpe-nos, não foi possível carregar o mapa, código do erro: ' + e);
                    }
                });
            });
            $item_address.first().find('.item-address-viewmap').click();
        }
        //ie6 png fix
        if(typeof(DD_belatedPNG)!='undefined'){
            var $combo = $('.mod-combosimples');
            if($combo.size()){
                $combo.hover(
                    function(){
                        $(this).find('ul').css('display','block');    
                    },
                    function(){
                        $(this).find('ul').css('display','none');    
                    }
                );        
            }
        }
        
});
$(window).load(function(){
    if((location.href).search("version=print")!=-1)
        $('a[rel=print]').click();
});
