$(document).ready(function($) {
    if (printGalery) {
        // We only want these styles applied when javascript is enabled
        $('div.content').css('display', 'block');


        // Initially set opacity on thumbs and add
        var onMouseOutOpacity = 0.40;

        // Initialize Advanced Galleriffic Gallery
        var gallery = $('#thumbs').galleriffic({
            delay: 2500,
            numThumbs: numThumbs,
            preloadAhead: numThumbs,
            enableTopPager: false,
            enableBottomPager: false,
            imageContainerSel: '#slideshow',
            controlsContainerSel: '#controls',
            captionContainerSel: '#caption',
            commentsContainerSel: '#comments',
            loadingContainerSel: '#loading',
            renderSSControls: true,
            renderNavControls: false,
            playLinkText: 'SLIDESHOW',
            pauseLinkText: 'PARAR',
            prevLinkText: '&lsaquo; anterior',
            nextLinkText: 'próxima &rsaquo;',
            nextPageLinkText: 'Next &rsaquo;',
            prevPageLinkText: '&lsaquo; Prev',
            imgPrev: imgPrev,
            imgNext: imgNext,
            widthImgPrevNext: widthImgPrevNext,
            heightImgPrevNext: heightImgPrevNext,
            enableHistory: true,
            autoStart: false,
            //syncTransitions: false,
            //defaultTransitionDuration: 900,
            enableKeyboardNavigation: true,
            onSlideChange: function(prevIndex, nextIndex) {
                /*this.find('ul.thumbs').children()
                .eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
                .eq(nextIndex).fadeTo('fast', 1.0);*/
                $("#cdFoto").val(this.find('ul.thumbs').children().eq(nextIndex).find('.cdFoto').html());
                $(".abaComments").html(this.find('ul.thumbs').children().eq(nextIndex).find('.totalComments').html());
                var atual = nextIndex + 1;
                $(".status span").html(atual);
                andacarousel();
            },
            onPageTransitionOut: function(callback) {
                this.fadeTo('fast', 0.0, callback);
            },
            onPageTransitionIn: function() {
                var prevPageLink = this.find('a.prev').css('visibility', 'hidden');
                var nextPageLink = this.find('a.next').css('visibility', 'hidden');

                // Show appropriate next / prev page links
                if (this.displayedPage > 0)
                    prevPageLink.css('visibility', 'visible');

                var lastPage = this.getNumPages() - 1;
                if (this.displayedPage < lastPage)
                    nextPageLink.css('visibility', 'visible');

                this.fadeTo('fast', 1.0);
            }
        });

        //liberando conteúdo
        $('#galeria-display, #compartilhe-videos, #tabs, #tab-outras').css('display', 'block');
        $('.carregando').css('display', 'none');
        /****************************************************************************************/

        /**** Functions to support integration of galleriffic with the jquery.history plugin ****/

        // PageLoad function
        // This function is called when:
        // 1. after calling $.historyInit();
        // 2. after calling $.historyLoad();
        // 3. after pushing "Go Back" button of a browser
        function pageload(hash) {
            // alert("pageload: " + hash);
            // hash doesn't contain the first # character.
            if (hash) {
                $.galleriffic.gotoImage(hash);
            } else {
                gallery.gotoIndex(0);
            }
        }

        // Initialize history plugin.
        // The callback is called at once by present location.hash. 
        $.historyInit(pageload, "/galerias/Templates/advanced.html");
        // set onlick event for buttons using the jQuery 1.3 live method
        $("a[rel='history']").live('click', function(e) {
            if (e.button != 0) return true;

            var hash = this.href;
            hash = hash.replace(/^.*#/, '');

            // moves to a new page. 
            // pageload is called at once. 
            // hash don't contain "#", "?"
            $.historyLoad(hash);

            return false;
        });
        //gerando carrousel
        $('#mycarousel').jcarousel({
            animation: 800,
            easing: 'BounceEaseOut',
            initCallback: mycarousel_initCallback,
            start: getHashFromString(location.hash),
            scroll: numThumbs
        });
        //gerando o compartilhe
        $("#compartilhe").redetvcompartilhe({
            titulo: compartilheTitulo,
            orkut: false
        });
        //ENVIE PRA UM AMIGO
        $('#sendfriend-btn').click(function() {
            $.ajax({
                type: "POST",
                url: urlMethodAjax2,
                data: "{url:'" + window.location.toString() + "', fromName: '" + $("#sendfriend-nome").val() + "', fromMail: '" + $("#sendfriend-email").val() + "', toName: '" + $("#sendfriend-amigo-nome").val() + "', toMail: '" + $("#sendfriend-amigo-email").val() + "', title: '" + $("#gallery-header > h2").html() + "', comment: '" + $("#sendfriend-texto").val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) {
                    var data = eval(response.d);

                    if (data.Status) {
                        $("#sendfriend-nome").val('Seu nome');
                        $("#sendfriend-email").val('Seu email');
                        $("#sendfriend-amigo-nome").val('Nome');
                        $("#sendfriend-amigo-email").val('Email');
                        $("#sendfriend-texto").val('');
                    }
                    $('#sendfriend-feedback').html(data.Mensagem).animate({ 'opacity': 'hide' }, 5000);
                },
                error: function(msg) {
                    $('#sendfriend-feedback').html('Erro: Tente novamente!');
                },
                beforeSend: function() {
                    $('#sendfriend-feedback').html('').show();
                    $('#sendfriend-btn').attr({ disabled: true, src: imgBtnAguarde });
                },
                complete: function() {
                    $('#sendfriend-btn').attr({ disabled: false, src: imgBtnEnviar });
                }
            });
            return false;
        });
        //ENVIAR COMENTÁRIO
        $('#comment-btn').click(function() {
            $.ajax({
                type: "POST",
                url: urlMethodAjax,
                data: "{cdFoto:" + $("#cdFoto").val() + ", nome: '" + $("#comment-nome").val() + "', email: '" + $("#comment-email").val() + "', texto: '" + $("#comment-texto").val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) {
                    var data = eval(response.d);

                    if (data.Status) {
                        $("#comment-nome").val('Nome');
                        $("#comment-email").val('Email');
                        $("#comment-texto").val('');
                    }
                    $('#comment-feedback').html(data.Mensagem).animate({ 'opacity': 'hide' }, 5000);
                },
                error: function(msg) {
                    $('#comment-feedback').html('Erro: Tente novamente!');
                },
                beforeSend: function() {
                    $('#comment-feedback').html('').show();
                    $('#comment-btn').attr({ disabled: true, src: imgBtnAguarde });
                },
                complete: function() {
                    $('#comment-btn').attr({ disabled: false, src: imgBtnEnviar });
                }
            });
            return false;
        });
        //GERANDO AS TABS
        $("#tabs").tabs({
            selected: 1
        });

        //DESABILITANDO A FUNÇÃO TECLADO
        $('input[type="text"], input[type="button"], textarea').bind('blur', function() {
            statusEventKey = true;
        }).bind('focus', function() {
            statusEventKey = false;
        });

        //gerando evendo para os inputs de comentário
        $('#comment-nome').click(function() {
            if ($(this).val() == 'Nome')
                $(this).val('');
        }).blur(function() {
            if ($(this).val() == '')
                $(this).val('Nome');
        });
        $('#comment-email').click(function() {
            if ($(this).val() == 'Email')
                $(this).val('');
        }).blur(function() {
            if ($(this).val() == '')
                $(this).val('Email');
        });
        $('#comment-texto').keyup(function() {
            var tot_full = 250;
            if ((tot_full - $(this).val().length) < 0) {
                $(this).val($(this).val().substr(0, tot_full));
            }
            $('.restam > strong').html(tot_full - $(this).val().length);
        });
        //gerando evendo para os inputs de 'envia pra um amigo'
        $('#sendfriend-nome').click(function() {
            if ($(this).val() == 'Seu nome')
                $(this).val('');
        }).blur(function() {
            if ($(this).val() == '')
                $(this).val('Seu nome');
        });
        $('#sendfriend-email').click(function() {
            if ($(this).val() == 'Seu email')
                $(this).val('');
        }).blur(function() {
            if ($(this).val() == '')
                $(this).val('Seu email');
        });
        $('#sendfriend-amigo-nome').click(function() {
            if ($(this).val() == 'Nome')
                $(this).val('');
        }).blur(function() {
            if ($(this).val() == '')
                $(this).val('Nome');
        });
        $('#sendfriend-amigo-email').click(function() {
            if ($(this).val() == 'Email')
                $(this).val('');
        }).blur(function() {
            if ($(this).val() == '')
                $(this).val('Email');
        });
        $('#sendfriend-texto').keyup(function() {
            var tot_full = 250;
            if ((tot_full - $(this).val().length) < 0) {
                $(this).val($(this).val().substr(0, tot_full));
            }
            $('.sendfriend-restam > strong').html(tot_full - $(this).val().length);
        });
    }
    else {
        $('#galeria-display, #tab-outras').css('display', 'block');
        $('.carregando').css('display', 'none');
    }
    //GERANDO AS TABS OUTRAS GALERIAS
    $("#tab-outras").tabs();
});

// Credits: Robert Penners easing equations (http://www.robertpenner.com/easing/).
$.easing['BounceEaseOut'] = function(p, t, b, c, d) {
    if ((t /= d) < (1 / 2.75)) {
        return c * (7.5625 * t * t) + b;
    } else if (t < (2 / 2.75)) {
        return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
    } else if (t < (2.5 / 2.75)) {
        return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
    } else {
        return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
    }
};

function getHashFromString(hash) {
    if (!hash) return -1;
    hash = hash.replace(/^.*#/, '');
    if (isNaN(hash)) return -1;
    return (+hash);
}

var galeria = null;
function mycarousel_initCallback(carousel) {
    galeria = carousel;
}

function andacarousel() {
    var hash = getHashFromString(location.hash) < 0 ? 0 : getHashFromString(location.hash);
    var inicio = (parseInt($("#mycarousel").css("left")) / widthThumb) * -1;
    var fim = inicio + numThumbs;
    if (hash < inicio || hash >= fim) {
        galeria.scroll(getHashFromString(location.hash));
    }
}
