var dominio = "header"+".com.br";

$(document).ready(function(){

    $('#icones, #marca, #textointroducao, img[src$=.png]').ifixpng();
    $("a.email").attr("href","mail"+"to:"+"contato"+"@"+dominio);
    
    TamTela(true);
    
    $("#carregandosite").hide();
    
    $(window).bind("resize",function(){
        TamTela(false);        
    });
    
    /* CAMADA */
    
    $("a.linkconteudo").click(function(e){ e.stopImmediatePropagation(); e.preventDefault(); Link(this); });
        
    /* CONTATO */
    
    /*$("form").bind("submit",function(){
        if ($("input[name=nome]").val() != ""){
            var valores = $(this).serialize();
            $.post("post.php", valores, function(d){
                $("form").unbind("submit");
                $("#avisogeral").html(d);
                $(".feedbackcontato").toggle();
            });
        } else 
            alert("Preencha seu nome");
    });*/
    
});

function PosFuncao(){
    $("#camadaconteudo a.email").attr("href","mail"+"to:"+"contato"+"@"+dominio).append("@"+dominio);
    
    $(".campoform input, .campoform textarea").each(function(){
        $(this).addClass("semtexto").val($(this).prev("label").text());
        $(this).bind("focus",function(e){
            if ($(this).is(".semtexto"))
                $(this).val("");
            
        }).bind("blur",function(e){
            if ($(this).val()=="")
                $(this).val($(this).prev("label").text()).addClass("semtexto");
            
        }).bind("keyup change",function(e){
            if ($(this).val()!="") $(this).removeClass("semtexto");
            
        });
    });
    
    if ($.browser.msie && parseInt($.browser.version)<8)
        $("a.linkconteudo").click(function(e){ e.preventDefault(); LinkIE7(this); });
    else
        $("a.linkconteudo").click(function(e){ e.preventDefault(); Link(this); });
    
    $(".grupoexp a.tituloexp").click(function(){
        $(this).toggleClass("grupoaexpandir grupoarecolher").next(".conteudoexp").slideToggle();
        
    });
    
    $("#camadaconteudo div.fechar a.atalho").hover(function(){
        $(this).animate({opacity:.5},500);
    },function(){
        $(this).animate({opacity:.2},500);
    }).click(function(e){
        e.preventDefault();
        var destino = $(this).attr("rel");
        var posq = $(this).position();
        $("#opcoesportfolio"+destino).slideToggle().css({top:posq.top+23+28, left:posq.left-19});
    });
    
    $("#menuportfolio a.navportfolio, #camadaconteudo a.linkfechar").css({opacity:.6}).hover(function(){
        $(this).animate({opacity:.9},500);
    },function(){
        $(this).animate({opacity:.6},500);
    });
    
    $("#camadaconteudo .opcoesportfolio a.opcao").click(function(e){
        e.preventDefault();
        var num = $(this).attr("href");
        var texto = $(this).attr("rel").split("¬")[0];
        var cor = $(this).attr("rel").split("¬")[1];
        var nomecod = $(this).attr("rel").split("¬")[2];
        $("#textoitemportfolio").html(texto);
        $("#sequenciaportfolio").val(num);
        $("#imagemportfolio").fadeOut("fast",function(){            
            $(this).css({backgroundColor:"#"+cor, backgroundImage:"url(estilo/imagens/portfolio/"+nomecod+".jpg)"}).fadeIn();            
        });
    });
    $("#menuportfolio a.anterior, #menuportfolio a.proximo").click(function(e){
        e.preventDefault();
        var maximo = parseInt($("#numeroitensportfolio").val());
        var num = parseInt($("#sequenciaportfolio").val());
        if ($(this).hasClass("proximo")) num++; else num--;
        if (num>maximo) num = 1;
        if (num==0) num = maximo;
        var valor = $("#itemportfolio_"+num).val();
        
        var texto = valor.split("¬")[1];
        var cor = valor.split("¬")[2];
        var nomecod = valor.split("¬")[0];
        
        $("#textoitemportfolio").html(texto);
        $("#sequenciaportfolio").val(num);
        $("#imagemportfolio").fadeOut("fast",function(){
            $(this).css({backgroundColor:"#"+cor, backgroundImage:"url(estilo/imagens/portfolio/"+nomecod+".jpg)"}).fadeIn();
        });
    });
    
    $("#camadaconteudo div.fechar a.linkfechar").click(function(e){
        e.preventDefault();
        $("#camadaconteudo").slideUp();
    });
    
    $("#enviarcontato").click(function(){        
        var nome = $("input[name=nome]").val();
        var email = $("input[name=email]").val();
        var condemail = (nome != "" && email !== "") && (nome != "nome" && email !== "e-mail");
        
        if (condemail){
            $(this).fadeOut("slow");
            $(".botaoform").append("<span id='enviandocontato'>Enviando mensagem...</span>");
            var form = $("#formcontato").serialize();
            
            $.post("retornocontato.php",form,function(d){
                $("#camadaconteudo .secao .textos").eq(1).html("<div id='retornocontato'>"+d+"</div>");
            });
            
        } else {
            alert("O nome e o e-mail são obrigatórios");
            
        }
    });
    $("a.produtosuplementar").click(function(e){ e.preventDefault(); alert("Site em desenvolvimento"); });
    
    $('img[src$=.png]').ifixpng();
}

function Link(elem){
    var pag = $(elem).attr("href");
    
    var iPad = navigator.userAgent.match(/iPad/i) != null;
    var iPod = navigator.userAgent.match(/iPod/i) != null;
    var iPhone = navigator.userAgent.match(/iPhone/i) != null;
    
    if ((iPad | iPod | iPhone) && pag != "portfolio"){
        
        document.location.href = pag;
        
    } else {
    
        $("#camadaconteudo").html("");
        
        if ($("#camadaconteudo").is(":hidden")){
            $("#camadaconteudo").slideDown();
        }

        $("#camadaconteudo").html("<span class='carregandoconteudo'>carregando conteúdo...</span>");
        
        var ck = Math.floor(Math.random()*1000001);
        
        $.get("paginas/"+pag+".php",{ck:ck, h:$(window).height()},function(d,s){
            $("#camadaconteudo").html(d);
            PosFuncao();
        });
        
    }
}

function LinkIE7(elem){
    var pag = $(elem).attr("href");
    
    $("#camadaconteudo").html("");
    
    if ($("#camadaconteudo").is(":hidden")){
        $("#camadaconteudo").slideDown();
    }

    $("#camadaconteudo").html("<span class='carregandoconteudo'>carregando conteúdo...</span>");
    
    var ck = Math.floor(Math.random()*1000001);
    var componentes = pag.split("/");
    pag = componentes[componentes.length-1];
    
    $.ajax({
        url:"paginas/"+pag+".php",
        data:{ck:ck},
        success:function(d,s){
            $("#camadaconteudo").html(d);
            PosFuncao();
        },
        error:function(x,t,e){
            $("#camadaconteudo").html("Erro: "+t+" - Código: "+e);
        }
    });
}

function TamTela(inicio){
    var telah = $(window).height();
    var telaw = $(window).width();
    
    var alturatotal = 200 + 236 + 126;
    var margem = 30; 
    var margemtopo = 30 + (telah - alturatotal)/2;
    
    if (telaw>930) margem = 30 + ((telaw-930)/2);

    if (margemtopo<30) margemtopo = 30;

    var altinterna = telah;
    if (telah<alturatotal) altinterna = alturatotal;
    $("#camadaconteudo").height(altinterna).width(telaw-margem-142);
    
    if (inicio){
        $("#conteudo").css({paddingLeft:margem+142}, 600);
        $("#destaque .recuo").css({marginLeft:margem}, 600);
        $("#logo").animate({marginLeft:margem}, 600, function(){
            $(this).animate({paddingTop:margemtopo}, 600, function(){
                $("#destaque").fadeIn("normal",function(){
                    $("#conteudo").fadeIn("normal");
                });
            });
        });
        
    } else {
        $("#logo, #destaque .recuo").css({marginLeft:margem});
        $("#logo").css({paddingTop:margemtopo});
        $("#conteudo").css({paddingLeft:margem+142});
        
    }
}
















;(function($) {

    $.ifixpng = function(customPixel) {
        $.ifixpng.pixel = customPixel;
    };
    
    $.ifixpng.regexp = {
        bg: /^url\(["']?(.*\.png([?].*)?)["']?\)$/i,
        img: /.*\.png([?].*)?$/i
    },
    
    $.ifixpng.getPixel = function() {
        return $.ifixpng.pixel || "js/pixel.gif";
    };
    
    var hack = {
        base    : $('base').attr('href'),
        ltie7    : $.browser.msie && $.browser.version < 7,
        filter    : function(src) {
            return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='"+src+"')";
        }
    };
    
    /**
     * Applies ie png hack to selected dom elements
     *
     * $('img[@src$=.png]').ifixpng();
     * @desc apply hack to all images with png extensions
     *
     * $('#panel, img[@src$=.png]').ifixpng();
     * @desc apply hack to element #panel and all images with png extensions
     *
     * @name ifixpng
     */
     
    $.fn.ifixpng = hack.ltie7 ? function() {
        function fixImage(image, source, width, height, hidden) {
            image.css({filter:hack.filter(source), width: width, height: height})
              .attr({src:$.ifixpng.getPixel()})
              .positionFix();
        }
        
        return this.each(function() {
            var $$ = $(this);
            if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
                var source, img;
                if (this.src && this.src.match($.ifixpng.regexp.img)) { // make sure it is png image
                    // use source tag value if set 
                    source = (hack.base && this.src.substring(0,1)!='/' && this.src.indexOf(hack.base) === -1) ? hack.base + this.src : this.src;
                    // If the width is not set, we have a problem; the image is not probably visible or not loaded
                    // and we need a work around.
                    if (!this.width || !this.height) {
                        $(new Image()).one('load', function() {
                            fixImage($$, source, this.width, this.height);
                            $(this).remove();
                        }).attr('src', source);
                    // If the image already has dimensions (it's loaded and visible) we can fix it straight away.
                    } else fixImage($$, source, this.width, this.height);
                }
            } else if (this.style) { // hack png css properties present inside css
                var imageSrc = $$.css('backgroundImage');
                // Background repeated images we cannot fix unfortunately
                if (imageSrc && imageSrc.match($.ifixpng.regexp.bg) && this.currentStyle.backgroundRepeat == 'no-repeat') {
                    imageSrc = RegExp.$1;
                    var x = this.currentStyle.backgroundPositionX || 0, y = this.currentStyle.backgroundPositionY || 0;
                    if (x || y) {
                        var css = {}, img;
                        if (typeof x != 'undefined') {
                            if (x == 'left') css.left = 0; 
                            // if right is 0, we have to check if the parent has an odd width, because of an IE bug
                            else if (x == 'right') css.right = $$.width() % 2 === 1 ? -1 : 0;
                            else css.left = x;
                        }
                        if (typeof y != 'undefined') {
                            // if bottom is 0, we have to check if the parent has an odd height, because of an IE bug
                            if (y == 'bottom') css.bottom = $$.height() % 2 === 1 ? -1 : 0; 
                            else if (y == 'top') css.top = 0;
                            else css.top = y;
                        }
                        img = new Image();
                        $(img).one('load', function() {
                            var x,y, expr = {}, prop;
                            // Now the image is loaded for sure, we can see if the background position needs fixing with an expression (in case of percentages)
                            if (/center|%/.test(css.top)) {
                                expr.top = "(this.parentNode.offsetHeight - this.offsetHeight) * " + (css.top == 'center' ? 0.5 : (parseInt(css.top) / 100));
                                delete css.top;
                            }
                            if (/center|%/.test(css.left)) {
                                expr.left = "(this.parentNode.offsetWidth - this.offsetWidth) * " + (css.left == 'center' ? 0.5 : (parseInt(css.left) / 100));
                                delete css.left;
                            }
                            // Let's add the helper DIV which will simulate the background image
                            $$.positionFix().css({backgroundImage: 'none'}).prepend(
                                $('<div></div>').css(css).css({
                                    width: this.width,
                                    height: this.height,
                                    position: 'absolute',
                                    filter: hack.filter(imageSrc)
                                })
                            );
                            if (expr.top || expr.left) {
                                var elem = $$.children(':first')[0];
                                for (prop in expr) elem.style.setExpression(prop, expr[prop], 'JavaScript');
                            }
                            $(this).remove();
                        });
                        img.src = imageSrc;
                    } else {
                        $$.css({backgroundImage: 'none', filter:hack.filter(imageSrc)});
                    }
                }
            }
        });
    } : function() { return this; };
    
    /**
     * positions selected item relatively
     */
    $.fn.positionFix = function() {
        return this.each(function() {
            var $$ = $(this);
            if ($$.css('position') != 'absolute') $$.css({position:'relative'});
        });
    };

})(jQuery);
