
var EMBED_CODE = '<iframe width="_x_" height="_y_" src="http://www.youtube.com/embed/m1iyfxiy9B8?autoplay=1&rel=0&wmode=transparent&autohide=1" frameborder="0"></iframe><a id="close-button"></a>'
var originalDimensions = {}
var lock = false;
var timer;
var myScroll;
var isTouch = false;
var start_with_portfolio = false
var start_with_planos = false

function nothing() {}

function disableScroll(e) {
    e.preventDefault();
}

function RemoveEventHandler () {
    if (document.removeEventListener) {    // all browsers except IE before version 9
        document.removeEventListener ("touchmove", disableScroll, false);
    }
    else {
        if (document.detachEvent) {        // IE before version 9
            document.detachEvent ('touchmove', disableScroll);
        }
    }
}

function install_close_button() {
    $("#close").click(function(){
        
        if (isTouch)
            RemoveEventHandler();
        
        $("#white-overlay").animate({'opacity': 'toggle'}, 500, function() {
            $('#ajax-content').html("");
        })
        
        $("body").removeClass("theater")
    })
}

function closeVideo() {
    $("#preview-video").animate(originalDimensions, 600, "easeInOutCubic", function() {
        $("#play-icon").animate({ opacity: "toggle" }, 600, "easeInOutCubic")
    })
    $("#banner-video").animate({ opacity: 1 }, 250, "easeInOutCubic")
    
    $("#video-player").html("")
}

function openVideo() {
    if (!lock) {
        element = $("#preview-video");
            
        var finalWidth = 505,
            finalHeight = 296,
            ratio = finalWidth / finalHeight,
            windowWidth = $("body").outerWidth(),
            windowHeight = $(window).height()
    
        finalWidth = windowWidth;
        finalHeight = Math.floor(finalWidth / ratio);
    
        if (finalHeight > windowHeight) {
            finalHeight = windowHeight;
            finalWidth = Math.floor(finalHeight * ratio);
        }
        
        var diffShadowWidth = 25 * (finalWidth/505),
            diffShadowHeight = 27 * (finalHeight/296)
    
        originalDimensions = {
                marginLeft: 24,
                width: element.css("width"),
                height: element.css("height")
            }
        
        $("#play-icon").hide()
        
        jQuery.easing.def = "easeInOutCubic";
        
        $("#banner-video").animate({
            opacity: 0
        }, 250)
            
        element.animate({
            width: finalWidth,
            height: finalHeight,
            marginLeft: -(finalWidth-960)/2
        }, 400, "easeInOutCubic", function() {
            code = EMBED_CODE.replace("_x_", finalWidth-diffShadowWidth).replace("_y_", finalHeight-diffShadowHeight)
            
            $("#video-player").html(code)
            $("#video-player").css("top", element.offset().top + (diffShadowHeight/2))
            $("#video-player").css("left", element.offset().left + (diffShadowWidth/2))
            
            $("#close-button").css("top", 5)
            $("#close-button").css("right", 5)
            
            $("#close-button").click(closeVideo)
            
            lock = false
        });
        
        $("html, body").animate({ scrollTop: element.offset().top }, 400, "easeInOutCubic");
        
        lock = true
    }
}

function proximaRevista() {
    
        var icones = $("#container-icones .icones");
        var icone = $("#container-icones img:first-child");
        var container_info = $("#container-info");
        var next_info = $("#container-info"+ icone.attr("indice"));
        
        var capa1 = $("#portfolio .container .capa1");
        var capa2 = $("#portfolio .container .capa2");
        var next_capa = $("#capas_publicacoes .capa"+ icone.attr("indice"));
        
        icones.animate({'marginLeft': 184}, 500, function() { 
            icones.css("margin-left", 316)
        });
    
        icone.animate({'opacity': 'toggle'}, 500, function() {
            icone.remove()
            icones.append(icone)
            
            icone.css("margin", 16)
            $("#container-icones img").show()
        })
        
        container_info.animate({"opacity": 'toggle'}, 500, function() {
            container_info.html( next_info.html() )
            container_info.animate({"opacity": 'toggle'}, 500, function() {
                install_saber_mais()
            })
        })
    
        if (capa1.css("display") == "none")
            capa1.attr("src", next_capa.attr("src"))
        else
            capa2.attr("src", next_capa.attr("src"))
        
        capa1.animate({"opacity": 'toggle'}, 1500)
        capa2.animate({"opacity": 'toggle'}, 1500)
}

$(document).ready(function(){
    
    if (start_with_portfolio)
        $.get('/portfolio_ajax', function(data) { mostrarAjaxPage(data); install_bubbles(); install_saber_mais(); });
    
    if (start_with_planos)
        $.get('/planos_ajax', function(data) { mostrarAjaxPage(data) });
    
    $("#dados_publicacoes, #capas_publicacoes").hide()
    
    $("#preview-video").click(openVideo)
    $("#play-icon").click(openVideo)
    
    $("#botao_acessar").click(function(){
        $(this).toggleClass("active")
        $("#caixa_login").toggle()
    })
    
    $("#voltar_topo").click(function() {
        $(document).scrollTo(0, 800)
    })
    
    $("textarea[maxlength]").keypress(function(event){
        var key = event.which;
     
        //todas as teclas incluindo enter
        if(key >= 33 || key == 13) {
            var maxLength = $(this).attr("maxlength");
            var length = this.value.length;
            if(length >= maxLength) {
                event.preventDefault();
            }
        }
    });
    
    $("#submit input").click(function(){
        data = {
            "nome": $("#nome").val(),
            "email": $("#email").val(),
            "assunto": $("#assunto").val(),
            "mensagem": $("#mensagem").val()
        }
        
        $("#fundo-bottom #form-contato input, #fundo-bottom #form-contato textarea").attr("disabled", true)
        
        $.ajax({
            type: 'POST',
            url: "/enviar_email_contato",
            data: data,
            success: function(data) {
                $(".mensagem").hide()
                
                if (data["success"]) {
                    $("#fundo-bottom #msg_sucesso").show()
                    $("#fundo-bottom #submit input").addClass("disabled")
                }
                else {
                    $("#msg_erro").show()
                    $("#fundo-bottom #form-contato input, #fundo-bottom #form-contato textarea").attr("disabled", false)
                }
            },
            dataType: "json"
        });
    })
    
    $("#botao_tambem_quero").click(function(){
        $("#botao_acessar").toggleClass("active")
        $("#caixa_login").toggle()
        $(document).scrollTo(4000, 800, {'axis': 'y'})
    })
    
    timer = setInterval(proximaRevista, 11000);
    
    $(window).blur(function(){
        clearInterval(timer)
    });
    
    $(window).focus(function(){
        clearInterval(timer)
        timer = setInterval(proximaRevista, 11000);
    });
    
    $("a#lista_titulos").click(function() {
        $.get('/portfolio_ajax', function(data) { mostrarAjaxPage(data); install_bubbles(); install_saber_mais(); });
    })
    
    $("a#link_planos").click(function() {
        $.get('/planos_ajax', function(data) { mostrarAjaxPage(data) });
    })

    install_saber_mais()
    install_bubbles()
})

var cache_ajax;

function install_saber_mais() {
    $('a.saber_mais').unbind();
    
    $(".saber_mais").click(function(){
        var titulo_id = $(this).attr("titulo_id")
        var from_portfolio = $(this).attr("from_portfolio")

        if (from_portfolio != undefined)
            cache_ajax = $('#ajax-content').html();

        $.ajax({
            url: '/aplicativo/'+titulo_id,
            data: {"from_portfolio": from_portfolio},
            success: function(data) { mostrarAjaxPage(data); install_bubbles(); }
        });
    })
}

function install_troca_categoria() {
    $("#categorias li").click(function() {
        $("#categorias li").removeClass("active")
        $(this).addClass("active")
        
        categoria_id = $(this).attr("categoria_id")
        offsetTop = this.offsetTop
        
        $('#titulos-content').animate({'opacity': 'toggle'}, 500, function() {
            
            $('#titulos-content').html("Carregando")
            
            $.get('/categoria/'+categoria_id+'/titulos', function(data) {
                $('#titulos-categoria').html(data);
                
                install_bubbles()
                install_saber_mais()
                
                if ($("#titulos-categoria").height() < $("#categorias ul").height()) {
                    $("#titulos-categoria").css("margin-top", offsetTop - 20)
                    
                    $("#titulos-content").css("display", "block");
                    altura_box = $("#titulos-categoria").offset().top + $("#titulos-categoria").height()
                    altura_menu = $("#categorias ul").offset().top + $("#categorias ul").height()
                    
                    if (altura_box > altura_menu) {
                        new_top = parseInt($("#titulos-categoria").css("margin-top")) - (altura_box - altura_menu)
                        $("#titulos-categoria").css("margin-top", new_top+10)
                    }
                    $("#titulos-content").css("display", "hidden");
                }
                else {
                    $("#titulos-categoria").css("margin-top", 80)
                }
                
                $("#titulos-content").fadeIn(500)
            });
        });
    })
}

function mostrarAjaxPage(data) {  
    $("body").addClass("theater")          
    $('#ajax-content').html(data);
    
    if (isTouch)
        $("a#close").addClass("touch")
    
    $("#white-overlay").fadeIn(500, function() {
        if (isTouch) {
            myScroll.refresh()
            document.addEventListener('touchmove', disableScroll, false);
        }
    })
}

$(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

function install_bubbles() {
    $("img.ios_inativo").CreateBubblePopup()
    $("img.ios_inativo").each(function(){
        $(this).SetBubblePopupOptions({
            themeName:  'all-black',
            themePath:  '/static/img/jquerybubblepopup-theme',
            alwaysVisible: false,
            innerHtml: "Em breve",
            divStyle: {"z-index": 200}
        });
    })
}
