/**
 * Cache de imagens.
 */
var imgCache = new Image();
imgCache.src = URL_BASE + '/img/loading1.gif';
imgCache.src = URL_BASE + '/img/loading2.gif';

/**
 * Clear form
 */
$.fn.clearForm = function()
{
    return this.each(function()
    {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (tag == 'form')
            return $(':input',this).clearForm();
        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

/**
 * Lightbox.
 */
function lightbox (e)
{
    if (e)
    {
        $(e).lightBox(
        {
            imageLoading: URL_BASE + '/img/lightbox/lightbox-ico-loading.gif',
            imageBtnClose: URL_BASE + '/img/lightbox/lightbox-btn-close.gif',
            imageBtnPrev: URL_BASE + '/img/lightbox/lightbox-btn-prev.gif',
            imageBtnNext: URL_BASE + '/img/lightbox/lightbox-btn-next.gif',
            imageBlank: URL_BASE + '/img/lightbox/lightbox-blank.gif',
            txtImage: 'Imagem',
            txtOf: 'de'
        });
    }
}

/**
 * Thumbnails.
 */
function thumbnailsEach ()
{
    $('div#fotosThumbs ul.listagem li a').each(function ()
    {
        $(this).click(function ()
        {
            thumbnailsClick($(this));
        });
    });
    thumbnailsClick($('div#fotosThumbs ul.listagem li:first a'));
}

function thumbnailsClick (self)
{
    var img = self.find('img').attr('src');
    if (img != undefined)
    {
        img = img.substr(0, img.length - 6);
        var elem = $('div#fotosView a:first');
        elem.find('img').fadeOut(function ()
        {
            var preloadImage = new Image();
            preloadImage.onload = function ()
            {
                elem.attr('href', img + '_G.jpg');
                elem.find('img').attr('src', '').attr('src', img + '_M.jpg').fadeIn(function ()
                {
                    lightbox(elem);
                    var navZoom = $('div#fotosView ul.nav li.zoom a');
                    navZoom.attr('href', img + '_G.jpg');
                    lightbox(navZoom);
                });
            }
            preloadImage.src = img + '_M.jpg';
        });
    }
    return false;
}

function thumbnailsAdd (src)
{
    $('div#fotosThumbs ul.listagem').append(
        '<li><a href="javascript:void(0);"><img src="' + URL_BASE + '/fotos/' + src + '" alt="" /></a></li>'
    );
}

function thumbnailsClear ()
{
    $('div#fotosThumbs ul.listagem').html('');
}

/**
 * Videos
 */
function videos (elem)
{
    var src = elem.attr('href');
    $('div#videos div.frameVideo').html(
      '<object width="320" height="240">'
    + '    <param name="movie" value="' + src + '"></param>'
    + '    <param name="allowFullScreen" value="true"></param>'
    + '    <param name="allowscriptaccess" value="always"></param>'
    + '    <embed src="' + src + '" type="application/x-shockwave-flash" allowscriptaccess="always" '
    + 'allowfullscreen="true" width="320" height="240"></embed>'
    + '</object>'
    );
}

/* ***************************************************************************************************************** */

$(document).ready(function ()
{
    /**
     * Conteúdo superior.
     */
    $('div.cont ul.nav li.jogo a, div.cont ul.nav li.regulamento a, div.cont ul.nav li.premio a, '
    + 'div.cont ul.nav li.imprensa a, div.cont ul.nav li.contato a').click(function ()
    {
        $(this).parent().parent().find('li a').removeClass('ativo');
        $(this).addClass('ativo');
        var className = $(this).parent().attr('className');
        var filename = '';
        if (className == 'imprensa')
        {
            filename = URL_BASE + '/inc/ajax/' + className + '.php';
        }
        else
        {
            filename = URL_BASE + '/cnt/' + className + '.php';
        }
        $('div.cont div.frame div:first').fadeOut(function ()
        {
            $(this).html('').parent().scrollTo(0);
            $(this).parent().find('div.loading').fadeIn(function ()
            {
                $.ajax(
                {
                    url: filename,
                    success: function (result)
                    {
                        if (result != '')
                        {
                            if (className == 'imprensa')
                            {
                                var spl = result.split("\n");
                                var str = '<ul class="imprensa">';
                                for (var c = 0; c < (spl.length - 1); c++)
                                {
                                    var not = spl[c].split('|');
                                    str += '<li><a href="' + (not[2] ? URL_BASE + '/imprensa/' + not[2] : not[1])
                                         + '"'
                                         + (not[2] ? ' rel="lightbox"' : ' target="_blank"')
                                         + '>' + not[0] + '</a></li>';
                                }
                                str += '</ul>';
                                $('div.cont div.frame div:first').html(str);
                                lightbox('a[rel="lightbox"]');
                            }
                            else
                            {
                                $('div.cont div.frame div:first').html(result);
                            }
                            $('div.cont div.frame div.loading').fadeOut(function ()
                            {
                                $(this).parent().find('div:first').fadeIn();
                            });
                        }
                    },
                    complete: function ()
                    {
                        /**
                         * Form contato
                         */
                        if (className == 'contato')
                        {
                            $('form.contato').submit(function ()
                            {
                                var e = this;
                                $.ajax(
                                {
                                    timeout: 30000,
                                    type: 'post',
                                    data: $(e).serialize(),
                                    url: URL_BASE + '/inc/ajax/contato.php',
                                    success: function (result)
                                    {
                                        if (result == 'OK')
                                        {
                                            $(e).clearForm();
                                            alert('E-mail enviado com sucesso.');
                                        }
                                        else
                                        {
                                            alert(result);
                                        }
                                    },
                                    error: function ()
                                    {
                                        alert('Erro ao enviar e-mail.');
                                    }
                                });
                                return false;
                            });
                        }
                    }
                });
            });
        });
    });

    /**
     * Lightbox.
     */
    lightbox('a[rel="lightbox"]');

    /**
     * Scroll do Frame.
     */
    $('ul.scroll li.sobe').click(function ()
    {
        $('div.frame').scrollTo('-=100px', 500);
        return false;
    });
    $('ul.scroll li.desce').click(function ()
    {
        $('div.frame').scrollTo('+=100px', 500);
        return false;
    });

    /**
     * Scroll da listagem de fotos.
     */
    $('div#fotosListagem ul.nav li.sobe').click(function ()
    {
        $('div#fotosListagem ul.listagem').scrollTo('-=50px', 500);
        // $('div#fotosListagem ul.listagem').scrollTo('-=' + $('div#fotosListagem ul.listagem').outerHeight(true), 500);
        return false;
    });
    $('div#fotosListagem ul.nav li.desce').click(function ()
    {
        $('div#fotosListagem ul.listagem').scrollTo('+=50px', 500);
        // $('div#fotosListagem ul.listagem').scrollTo('+=' + $('div#fotosListagem ul.listagem').outerHeight(true), 500);
        return false;
    });

    /**
     * Scroll da listagem de thumnails
     */
    $('div#fotosThumbs ul.nav li.anterior').click(function ()
    {
        $('div#fotosThumbs ul.listagem').scrollTo('-=219px', 500);
        // $('div#fotosThumbs ul.listagem').scrollTo('-=' + $('div#fotosThumbs ul.listagem').outerHeight(true), 500);
        return false;
    });
    $('div#fotosThumbs ul.nav li.proxima').click(function ()
    {
        $('div#fotosThumbs ul.listagem').scrollTo('+=219px', 500);
        // $('div#fotosThumbs ul.listagem').scrollTo('+=' + $('div#fotosThumbs ul.listagem').outerHeight(true), 500);
        return false;
    });

    /**
     * Listagem de fotos.
     */
    $('div#fotosListagem ul.listagem li a').click(function ()
    {
        var i = parseInt($(this).attr('rel'));
        if (!isNaN(i) && (i > 0))
        {
            $('div#fotosThumbs ul.listagem li').fadeOut(500, function ()
            {
                $('div#fotosThumbs ul.listagem').scrollTo(0);
                $(this).remove();
                
            });
            $.ajax(
            {
                type: 'get',
                data: 'codigo=' + i,
                url: URL_BASE + '/inc/ajax/fotosCarregarThumbs.php',
                success: function (result)
                {
                    if (result != '')
                    {
                        thumbnailsClear();
                        var spl = result.split("\n");
                        for (var c = 0; c < spl.length; c++)
                        {
                            var n = spl[c].length;
                            if (spl[c].substr(n - 4, 4) == '.jpg')
                            {
                                thumbnailsAdd(spl[c]);
                            }
                        }
                    }
                    thumbnailsEach();
                }
            });
        }
        return false;
    });

    $('div#fotosListagem ul.listagem li:first a').click();

    /**
     * Scroll do vídeos.
     */
    $('div#videos ul.nav li.anterior').click(function ()
    {
        $('div#videos div.listagem').scrollTo('-=50px', 500);
        // $('div#videos div.listagem').scrollTo('-=' + $('div#videos div.listagem').outerHeight(true), 500);
        return false;
    });
    $('div#videos ul.nav li.proxima').click(function ()
    {
        $('div#videos div.listagem').scrollTo('+=50px', 500);
        // $('div#videos div.listagem').scrollTo('+=' + $('div#videos div.listagem').outerHeight(true), 500);
        return false;
    });

    /**
     * Vídeos.
     */
    $('div#videos div.listagem ul li a').click(function ()
    {
        videos($(this));
        return false;
    });
    videos($('div#videos div.listagem ul li:first a'));

    /**
     * Navegação no #fotosView.
     */
    $('div#fotosView ul.nav li.anterior').click(function ()
    {
        var img = $(this).parent().prev().find('img').attr('src').replace('_M.jpg', '_P.jpg');
        $('div#fotosThumbs ul.listagem').find('img[src="' + img + '"]').parent().parent().prev().find('a').click();
        return false;
    });

    $('div#fotosView ul.nav li.proximo').click(function ()
    {
        var img = $(this).parent().prev().find('img').attr('src').replace('_M.jpg', '_P.jpg');
        $('div#fotosThumbs ul.listagem').find('img[src="' + img + '"]').parent().parent().next().find('a').click();
        return false;
    });

    /**
     * Fechar div flutuante.
     */
    $('div#flutuante a.fechar').click(function ()
    {
        $('div#flutuante').fadeOut();
        return false;
    });

    /**
     * Salvar imagem maior.
     */
    $('div#fotosView ul.nav li.save').click(function ()
    {
        var f = $(this).parent().prev().attr('href');
        f = f.substr((URL_BASE.length + 7));        
        window.open(URL_BASE + '/downloadImage.php?f=' + f, 'EcoQuizDownloadImage');
        return false;
    });
});

