﻿var user_logado;
var idBrinSel = "";
var on = 1; // sonido

/*****************************************************************/
/************************** JQUERY *******************************/
/*****************************************************************/
$(document).ready(function() {

    $('#slider_div li').removeClass('hide');

    $("#slider_div").jCarouselLite({
        btnNext: ".button_carousel_next",
        btnPrev: ".button_carousel_previous",
        visible: 5,
        circular: true,
        scroll: 1,
        afterEnd: function(a) {
            a.each(function(index) {
                if ($(this).find(">:first-child").attr('id') == idBrinSel) {
                    $(this).find(">:first-child div#select_brincadeiras").show();
                    $(this).find(">:first-child div#select_brincadeiras").removeClass('hide');
                }
            });
        }
    });

    $('#slider_div li').addClass('hide');

    $("#detail_product").jScrollPane({ verticalDragMinHeight: 25, verticalDragMaxHeight: 25, showArrows: true });

    $('.carousel li').hover(
        function() {
            $(this).find("div#hover_brincadeiras").show();
        },
        function() {
            $(this).find("div#hover_brincadeiras").hide();
        }
    );

    preload('images/products.png');

    if ($('.avatar_deslogado').length > 0) {
        showAvisoPromo();
        setTimeout(function() { hideAvisoPromo(); }, 12000);
    }

    $('.button_carousel_previous').click(function() {
        tracker_event('brincadeira', 'click', 'Esquerda');
    });

    $('.button_carousel_next').click(function() {
        tracker_event('brincadeira', 'click', 'Direita');
    });
});

var images = new Array();

function preload() {
    for (i = 0; i < preload.arguments.length; i++) {
        images[i] = new Image();
        images[i].src = $('#urlBase').val() + preload.arguments[i];
    }
}

function reloadCufonH1() {
    Cufon.refresh('h1');
}

function reloadCufonH2() {
    Cufon.refresh('h2');
}

function resizeImage(img, max_width, max_height) {
    var height = img.height();
    var width = img.width();

    if (height == 0 || width == 0)
        return;

    var ratio = ((max_width / width) < (max_height / height) ? max_width / width : max_height / height);
    width = ratio * width;
    height = ratio * height;

    var margin_top = Math.round(height / -2);
    var margin_left = Math.round(width / -2);

    img.attr("height", Math.round(height));
    img.attr("width", Math.round(width));
    img.css({ "margin-top": margin_top, "margin-left": margin_left, "position": "absolute", "top": "50%", "left": "50%" });
}

function reloadPage() {

    if (getCookie('chamyto_brincadeira') != null) {
        idBrinSel = getCookie('chamyto_brincadeira');

        deleteCookie('chamyto_brincadeira');

        document.location = 'Default.aspx?idb=' + idBrinSel;
    } else {
        window.location.reload();
    }
}

function goToTop() {
    $('html, body').animate({ scrollTop: 0 }, 'slow');
}

/*****************************************************************/
/************************** SECTIONS *****************************/
/*****************************************************************/
function openLogin() {
    closePanel();
    window.open($('#urlLogin').val(), 'Login', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=800,height=450,top=50,left=250');
}

function openCadastro() {
    closePanel();
    window.open($('#urlCadastro').val(), 'Cadastro', 'width=622,height=585,scrollbars=1');
}

/*****************************************************************/
/************************** MODALS *******************************/
/*****************************************************************/
function hideModals() {
    hideHoverHome();
    $('.modal').fadeOut(300);
}

function showHoverHome() {
    $('.hover_home').removeClass('hide');
}

function hideHoverHome() {
    $('.hover_home').addClass('hide');
}

function centrarModal(selector, extra) {
    $(selector).css({ "top": $(window).scrollTop() + extra });
}

function showTablaNutricional(img, nombreprod) {
    hideModals();

    var imagen = new Image();
    imagen.onload = function() {
        $('.nutritional_table').css("background", "url('./" + img + "') no-repeat scroll left top transparent");
        $('.nutritional_table').css("height", this.height);
        $('.nutritional_table').css("width", this.width);
        $('.nutritional_table').css("margin-left", this.width / -2);

        showHoverHome();
        $('#modal_tabla_nutricional').fadeIn(300);

        tracker('/produtos/tabela_nutricional/subproduto/' + url_friendly(nombreprod));
    }
    imagen.src = "./" + img;
}

function showAvisoPromo() {
    hideModals();
    showHoverHome();
    $('#aviso_promo').fadeIn(300);
}

function hideAvisoPromo() {
    hideHoverHome();
    $('#aviso_promo').fadeOut(300);
}

/*****************************************************************/
/*************************** HEADER ******************************/
/*****************************************************************/
var panel_closed = true;
var moviendo = false;

function changePanel() {

    if (moviendo) {
        return;
    }

    moviendo = true;

    $('#slider_div li').removeClass('hide');
    
    if (panel_closed) {
        $('#container_header').animate({
            top: "40px"
        }, 500, function() {
            $('.button_brincadeiras').addClass("select");
            moviendo = false;
        });

        panel_closed = false;

        tracker('/brincadeiras');
        
    } else {
        $('#container_header').animate({
            top: "-133px"
        }, 500, function() {
            $('.button_brincadeiras').removeClass("select");
            moviendo = false;
        });

        panel_closed = true;
    }

    moviendo = false;
}

function closePanel() {
    panel_closed = false;

    changePanel();
}

function marcarBrincadeira(id) {

    if (typeof id == 'undefined' || id == null || id == "") {
        return;
    } 

    $('#slider_div li').each(function(index) {
        if ($(this).find(">:input[type='hidden']").val() == id) {
            $(this).find(">:first-child div#select_brincadeiras").show();
            $(this).find(">:first-child div#select_brincadeiras").removeClass('hide');
        } else {
            $(this).find(">:first-child div#select_brincadeiras").hide();
            $(this).find(">:first-child div#select_brincadeiras").addClass('hide');
        }
    });

    idBrinSel = id;
}

/*****************************************************************/
/************************** PRODUCTO *****************************/
/*****************************************************************/
function cambiarCategoria(catid, nombrecat) {
    $.post("servicios/getProducto.aspx", { c: catid }, function(data) {

        $('.button_product').removeClass("iogurte_select unoyuno_select leite_select petit_select jelly_select");

        $('.button_product').each(function(index) {
            if (index == catid - 1) {
                var classes = $(this).attr("class").split(/\s+/);
                $(this).addClass(classes[classes.length - 1] + "_select");
            }
        });

        doTransitionProducto(data);

        tracker('/produtos/' + url_friendly(nombrecat));
    });
}

function cambiarProducto(catid, prodid, nombrecat, nombreprod) {
    $.post("servicios/getProducto.aspx", { c: catid, p: prodid }, function(data) {

        doTransitionProducto(data);

        tracker('/produtos/' + url_friendly(nombrecat) + "/subproduto/" + url_friendly(nombreprod));
    });
}

var imagesLoaded = 0;

function doTransitionProducto(data) {
    $('#contenedor_producto').fadeOut(400, function() {
        $('#contenedor_producto').html(data);

        $('#contenedor_producto img').unbind("load");
        $('#contenedor_producto img').load(function() {
            imagesLoaded++;

            if (imagesLoaded == 2) {
                imagesLoaded = 0;
                
                $('#contenedor_producto').show();
                reiniciarScrollProductos();
                $('#contenedor_producto').hide();

                reloadCufonH1();
                reloadCufonH2();

                $('#contenedor_producto').fadeIn(400);
            }
        });
    });
}

function reiniciarScrollProductos() {
    $("#detail_product").jScrollPane({ verticalDragMinHeight: 25, verticalDragMaxHeight: 25, showArrows: true });

    if ($('.jspVerticalBar').length != 0) {
        $('.text_product').css('width', '230px');
    } else {
        $('.text_product').css('width', '203px');
    }
}

/*********************************************************/
/***************** JAVASCRIPT-TO-FLASH *******************/
/*********************************************************/
function getFlashMovie(movieName) {
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
    return (isIE) ? document.getElementById(movieName) : document[movieName];
}

function showBrincadeira(id, nombrebrin) {

    closePanel();

    hideModals();

    setCookie('chamyto_brincadeira', id, 1000);

    if (id != 998 && id != 999) {
        tracker(url_friendly(nombrebrin));
    }

    if (id == 999) {
        tracker('/meu_perfil');
    }

    if (document.getElementById("flashcontent") == null) {
        goHome(id);
    } else {
        getFlashMovie("flashcontent").goSection(id);
    }
}

function changeSound() {

    on = (on == 1 ? 0 : 1);

    getFlashMovie("flashcontent").changeSound(on);
}

function loadFlash(idb) {
    var params = {
        quality: "high",
        wmode: "transparent",
        allowscriptaccess: "always",
        allowfullscreen: "true"
    };

    idBrinSel = idb != "" ? idb : "0";
    
    var flashvars = {
        mute: "1",
        uid: idBrinSel
    };
    var attributes = {
        id: "flashcontent",
        name: "flashcontent"
    };
    swfobject.embedSWF("precarga.swf", "flashcontent", "100%", "478", "6.0.65.0", "swf/expressInstall.swf", flashvars, params, attributes);
}

function loadAvatar() {
    var params = {
        quality: "high",
        wmode: "transparent"
    };
    var flashvars = {};
    var attributes = {
        id: "avatarcontent",
        name: "avatarcontent"
    };
    swfobject.embedSWF("swf/miniAvatar.swf", "avatarcontent", "40", "33", "6.0.65.0", "swf/expressInstall.swf", flashvars, params, attributes);
}

function refreshAvatar() {
    getFlashMovie("avatarcontent").refreshAvatar();
}

function goHome(id) {

    closePanel();

    $('#container_header_flash').fadeOut(500, function() {

        $('#container_header_flash').html("<div id=\"flashcontent\"></div>");

        loadFlash();

        $('#container_header_flash').fadeIn(1000, function() {
            if (id != null) {
                getFlashMovie("flashcontent").goSection(id);
            }
        });
    });
}

/*********************************************************/
/***************** FLASH-TO-JAVASCRIPT *******************/
/*********************************************************/
function goProducto() {
    $.post("Produtos.aspx", {}, function(data) {

        $('#container_header_flash').fadeOut(500, function() {

            $('#container_header_flash').html(data);

            reloadCufonH1();
            reloadCufonH2();

            $('#container_header_flash').show();
            reiniciarScrollProductos();
            $('#container_header_flash').hide();

            $('#container_header_flash').fadeIn(1000);

            tracker('/produtos');
        });
    });
}

function callGame(path) {
    var params = {
        quality: "high",
        wmode: "transparent",
        allowscriptaccess: "always"
    };
    var flashvars = {};
    var attributes = {
        id: "gamecontent",
        name: "gamecontent"
    };
    swfobject.embedSWF(path, "gamecontent", "100%", "628", "6.0.65.0", "swf/expressInstall.swf", flashvars, params, attributes);

    hideModals();
    showHoverHome();
    $('#modal_games').fadeIn(300);
}

function callVideo(path, mute) {
    var params = {
        quality: "high",
        wmode: "transparent",
        allowscriptaccess: "always",
        allowfullscreen: "true"
    };
    var flashvars = {
        path: path,
        mute: mute
    };
    var attributes = {
        id: "videocontent",
        name: "videocontent"
    };
    swfobject.embedSWF("swf/VideoFullScreen.swf", "videocontent", "100%", "628", "6.0.65.0", "swf/expressInstall.swf", flashvars, params, attributes);

    hideModals();
    showHoverHome();
    $('#modal_video').fadeIn(300);
}

/*********************************************************/
/************************ COOKIES ************************/
/*********************************************************/
function setCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function deleteCookie(name) {
    setCookie(name, "", -1);
}

/*********************************************************/
/*********************** TRACKING ************************/
/*********************************************************/
function url_friendly(text) {

    if (typeof text == 'undefined')
        return;

    var url = text.toLowerCase()
				  .replace(/^\s+|\s+$/g, "\-")
				  .replace(/[_|\s]+/g, "\-")
				  .replace(/ã/g, "a")
				  .replace(/ç/g, "c")
				  .replace(/á/g, "a")
				  .replace(/é/g, "e")
				  .replace(/í/g, "i")
				  .replace(/ó/g, "o")
				  .replace(/ú/g, "u")
				  .replace(/ê/g, "e")
				  .replace(/ô/g, "o")
				  .replace(/[^a-z0-9_]+/g, "\-")
				  .replace(/[_]+/g, "\-")
				  .replace(/^_+|_+$/g, "\-");
    return url;
}
