/**
 * Copyright (c) 2010 Anders Ekdahl (http://coffeescripter.com/)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version: 1.2.4
 *
 * Demo and documentation: http://coffeescripter.com/code/ad-gallery/
 */
(function ($) {
    $.fn.adGallery = function (b) {
        var c = {
            loader_image: base_path + 'images/loader.gif',
            start_at_index: 0,
            description_wrapper: false,
            thumb_opacity: 0.7,
            animate_first_image: false,
            animation_speed: 400,
            width: false,
            height: false,
            display_next_and_prev: true,
            display_back_and_forward: true,
            scroll_jump: 0,
            slideshow: {
                enable: true,
                autostart: false,
                speed: 5000,
                start_label: 'Começar',
                stop_label: 'Parar',
                stop_on_scroll: true,
                countdown_prefix: '(',
                countdown_sufix: ')',
                onStart: false,
                onStop: false
            },
            effect: 'fade',
            enable_keyboard_move: true,
            cycle: true,
            callbacks: {
                init: false,
                afterImageVisible: false,
                beforeImageVisible: false
            }
        };
        var d = $.extend(false, c, b);
        if (b && b.slideshow) {
            d.slideshow = $.extend(false, c.slideshow, b.slideshow)
        };
        if (!d.slideshow.enable) {
            d.slideshow.autostart = false
        };
        var e = [];
        $(this).each(function () {
            var a = new AdGallery(this, d);
            e[e.length] = a
        });
        return e
    };

    function VerticalSlideAnimation(a, b, c) {
        var d = parseInt(a.css('top'), 10);
        if (b == 'left') {
            var e = '-' + this.image_wrapper_height + 'px';
            a.css('top', this.image_wrapper_height + 'px')
        } else {
            var e = this.image_wrapper_height + 'px';
            a.css('top', '-' + this.image_wrapper_height + 'px')
        };
        if (c) {
            c.css('bottom', '-' + c[0].offsetHeight + 'px');
            c.animate({
                bottom: 0
            }, this.settings.animation_speed * 2)
        };
        if (this.current_description) {
            this.current_description.animate({
                bottom: '-' + this.current_description[0].offsetHeight + 'px'
            }, this.settings.animation_speed * 2)
        };
        return {
            old_image: {
                top: e
            },
            new_image: {
                top: d
            }
        }
    };

    function HorizontalSlideAnimation(a, b, c) {
        var d = parseInt(a.css('left'), 10);
        if (b == 'left') {
            var e = '-' + this.image_wrapper_width + 'px';
            a.css('left', this.image_wrapper_width + 'px')
        } else {
            var e = this.image_wrapper_width + 'px';
            a.css('left', '-' + this.image_wrapper_width + 'px')
        };
        if (c) {
            c.css('bottom', '-' + c[0].offsetHeight + 'px');
            c.animate({
                bottom: 0
            }, this.settings.animation_speed * 2)
        };
        if (this.current_description) {
            this.current_description.animate({
                bottom: '-' + this.current_description[0].offsetHeight + 'px'
            }, this.settings.animation_speed * 2)
        };
        return {
            old_image: {
                left: e
            },
            new_image: {
                left: d
            }
        }
    };

    function ResizeAnimation(a, b, c) {
        var d = a.width();
        var e = a.height();
        var f = parseInt(a.css('left'), 10);
        var g = parseInt(a.css('top'), 10);
        a.css({
            width: 0,
            height: 0,
            top: this.image_wrapper_height / 2,
            left: this.image_wrapper_width / 2
        });
        return {
            old_image: {
                width: 0,
                height: 0,
                top: this.image_wrapper_height / 2,
                left: this.image_wrapper_width / 2
            },
            new_image: {
                width: d,
                height: e,
                top: g,
                left: f
            }
        }
    };

    function FadeAnimation(a, b, c) {
        a.css('opacity', 0);
        return {
            old_image: {
                opacity: 0
            },
            new_image: {
                opacity: 1
            }
        }
    };

    function NoneAnimation(a, b, c) {
        a.css('opacity', 0);
        return {
            old_image: {
                opacity: 0
            },
            new_image: {
                opacity: 1
            },
            speed: 0
        }
    };

    function AdGallery(a, b) {
        this.init(a, b)
    };
    AdGallery.prototype = {
        wrapper: false,
        image_wrapper: false,
        gallery_info: false,
        nav: false,
        loader: false,
        preloads: false,
        thumbs_wrapper: false,
        scroll_back: false,
        scroll_forward: false,
        next_link: false,
        prev_link: false,
        slideshow: false,
        image_wrapper_width: 0,
        image_wrapper_height: 0,
        current_index: 0,
        current_image: false,
        current_description: false,
        nav_display_width: 0,
        settings: true,
        images: false,
        in_transition: true,
        animations: true,
        init: function (b, c) {
            var d = this;
            this.wrapper = $(b);
            this.settings = c;
            this.setupElements();
            this.setupAnimations();
            if (this.settings.width) {
                this.image_wrapper_width = this.settings.width;
                this.image_wrapper.width(this.settings.width);
                this.wrapper.width(this.settings.width)
            } else {
                this.image_wrapper_width = this.image_wrapper.width()
            };
            if (this.settings.height) {
                this.image_wrapper_height = this.settings.height;
                this.image_wrapper.height(this.settings.height)
            } else {
                this.image_wrapper_height = this.image_wrapper.height()
            };
            this.nav_display_width = this.nav.width();
            this.current_index = 0;
            this.current_image = false;
            this.current_description = false;
            this.in_transition = false;
            this.findImages();
            if (this.settings.display_next_and_prev) {
                this.initNextAndPrev()
            };
            var e = function (a) {
                    return d.nextImage(a)
                };
            this.slideshow = new AdGallerySlideshow(e, this.settings.slideshow);
            this.controls.append(this.slideshow.create());
            if (this.settings.slideshow.enable) {
                this.slideshow.enable()
            } else {
                this.slideshow.disable()
            };
            if (this.settings.display_back_and_forward) {
                this.initBackAndForward()
            };
            if (this.settings.enable_keyboard_move) {
                this.initKeyEvents()
            };
            var f = parseInt(this.settings.start_at_index, 10);
            if (window.location.hash && window.location.hash.indexOf('#ad-image') === 0) {
                f = window.location.hash.replace(/[^0-9]+/g, '');
                if ((f * 1) != f) {
                    f = this.settings.start_at_index
                }
            };
            this.loading(true);
            this.showImage(f, function () {
                if (d.settings.slideshow.autostart) {
                    d.preloadImage(f + 1);
                    d.slideshow.start()
                }
            });
            this.fireCallback(this.settings.callbacks.init)
        },
        setupAnimations: function () {
            this.animations = {
                'slide-vert': VerticalSlideAnimation,
                'slide-hori': HorizontalSlideAnimation,
                'resize': ResizeAnimation,
                'fade': FadeAnimation,
                'none': NoneAnimation
            }
        },
        setupElements: function () {
            this.controls = this.wrapper.find('.ad-controls');
            this.gallery_info = $('<p class="ad-info"></p>');
            this.controls.append(this.gallery_info);
            this.image_wrapper = this.wrapper.find('.ad-image-wrapper');
            this.image_wrapper.empty();
            this.nav = this.wrapper.find('.ad-nav');
            this.thumbs_wrapper = this.nav.find('.ad-thumbs');
            this.preloads = $('<div class="ad-preloads"></div>');
            this.loader = $('<img class="ad-loader" src="' + this.settings.loader_image + '">');
            this.image_wrapper.append(this.loader);
            this.loader.hide();
            $(document.body).append(this.preloads)
        },
        loading: function (a) {
            if (a) {
                this.loader.show()
            } else {
                this.loader.hide()
            }
        },
        addAnimation: function (a, b) {
            if ($.isFunction(b)) {
                this.animations[a] = b
            }
        },
        findImages: function () {
            var f = this;
            this.images = [];
            var g = 0;
            var h = 0;
            var j = this.thumbs_wrapper.find('a');
            var k = j.length;
            if (this.settings.thumb_opacity < 1) {
                j.find('img').css('opacity', this.settings.thumb_opacity)
            };
            j.each(function (i) {
                var a = $(this);
                var b = a.attr('href');
                var c = a.find('img');
                if (!f.isImageLoaded(c[0])) {
                    c.load(function () {
                        g += this.parentNode.parentNode.offsetWidth;
                        h++
                    })
                } else {
                    g += c[0].parentNode.parentNode.offsetWidth;
                    h++
                };
                a.addClass('ad-thumb' + i);
                a.click(function () {
                    f.showImage(i);
                    f.slideshow.stop();
                    return false
                }).hover(function () {
                    if (!$(this).is('.ad-active') && f.settings.thumb_opacity < 1) {
                        $(this).find('img').fadeTo(300, 1)
                    };
                    f.preloadImage(i)
                }, function () {
                    if (!$(this).is('.ad-active') && f.settings.thumb_opacity < 1) {
                        $(this).find('img').fadeTo(300, f.settings.thumb_opacity)
                    }
                });
                var a = false;
                if (c.data('ad-link')) {
                    a = c.data('ad-link')
                } else if (c.attr('longdesc') && c.attr('longdesc').length) {
                    a = c.attr('longdesc')
                };
                var d = false;
                if (c.data('ad-desc')) {
                    d = c.data('ad-desc')
                } else if (c.attr('alt') && c.attr('alt').length) {
                    d = c.attr('alt')
                };
                var e = false;
                if (c.data('ad-title')) {
                    e = c.data('ad-title')
                } else if (c.attr('title') && c.attr('title').length) {
                    e = c.attr('title')
                };
                f.images[i] = {
                    thumb: c.attr('src'),
                    image: b,
                    error: false,
                    preloaded: false,
                    desc: d,
                    title: e,
                    size: false,
                    link: a
                }
            });
            var l = setInterval(function () {
                if (k == h) {
                    f.nav.find('.ad-thumb-list').css('width', g + 'px');
                    clearInterval(l)
                }
            }, 100)
        },
        initKeyEvents: function () {
            var a = this;
            $(document).keydown(function (e) {
                if (e.keyCode == 39) {
                    a.nextImage();
                    a.slideshow.stop()
                } else if (e.keyCode == 37) {
                    a.prevImage();
                    a.slideshow.stop()
                }
            })
        },
        initNextAndPrev: function () {
            this.next_link = $('<div class="ad-next"><div class="ad-next-image"></div></div>');
            this.prev_link = $('<div class="ad-prev"><div class="ad-prev-image"></div></div>');
            this.image_wrapper.append(this.next_link);
            this.image_wrapper.append(this.prev_link);
            var a = this;
            this.prev_link.add(this.next_link).mouseover(function (e) {
                $(this).css('height', a.image_wrapper_height);
                $(this).find('div').show()
            }).mouseout(function (e) {
                $(this).find('div').hide()
            }).click(function () {
                if ($(this).is('.ad-next')) {
                    a.nextImage();
                    a.slideshow.stop()
                } else {
                    a.prevImage();
                    a.slideshow.stop()
                }
            }).find('div').css('opacity', 0.7)
        },
        initBackAndForward: function () {
            var c = this;
            this.scroll_forward = $('<div class="ad-forward"></div>');
            this.scroll_back = $('<div class="ad-back"></div>');
            this.nav.append(this.scroll_forward);
            this.nav.prepend(this.scroll_back);
            var d = 0;
            var e = false;
            $(this.scroll_back).add(this.scroll_forward).click(function () {
                var a = c.nav_display_width - 50;
                if (c.settings.scroll_jump > 0) {
                    var a = c.settings.scroll_jump
                };
                if ($(this).is('.ad-forward')) {
                    var b = c.thumbs_wrapper.scrollLeft() + a
                } else {
                    var b = c.thumbs_wrapper.scrollLeft() - a
                };
                if (c.settings.slideshow.stop_on_scroll) {
                    c.slideshow.stop()
                };
                c.thumbs_wrapper.animate({
                    scrollLeft: b + 'px'
                });
                return false
            }).css('opacity', 0.6).hover(function () {
                var b = 'left';
                if ($(this).is('.ad-forward')) {
                    b = 'right'
                };
                e = setInterval(function () {
                    d++;
                    if (d > 30 && c.settings.slideshow.stop_on_scroll) {
                        c.slideshow.stop()
                    };
                    var a = c.thumbs_wrapper.scrollLeft() + 1;
                    if (b == 'left') {
                        a = c.thumbs_wrapper.scrollLeft() - 1
                    };
                    c.thumbs_wrapper.scrollLeft(a)
                }, 10);
                $(this).css('opacity', 1)
            }, function () {
                d = 0;
                clearInterval(e);
                $(this).css('opacity', 0.6)
            })
        },
        _afterShow: function () {
            this.gallery_info.html((this.current_index + 1) + ' / ' + this.images.length);
            if (!this.settings.cycle) {
                this.prev_link.show().css('height', this.image_wrapper_height);
                this.next_link.show().css('height', this.image_wrapper_height);
                if (this.current_index == (this.images.length - 1)) {
                    this.next_link.hide()
                };
                if (this.current_index == 0) {
                    this.prev_link.hide()
                }
            };
            this.fireCallback(this.settings.callbacks.afterImageVisible)
        },
        _getContainedImageSize: function (a, b) {
            if (b > this.image_wrapper_height) {
                var c = a / b;
                b = this.image_wrapper_height;
                a = this.image_wrapper_height * c
            };
            if (a > this.image_wrapper_width) {
                var c = b / a;
                a = this.image_wrapper_width;
                b = this.image_wrapper_width * c
            };
            return {
                width: a,
                height: b
            }
        },
        _centerImage: function (a, b, c) {
            a.css('top', '0px');
            if (c < this.image_wrapper_height) {
                var d = this.image_wrapper_height - c;
                a.css('top', (d / 2) + 'px')
            };
            a.css('left', '0px');
            if (b < this.image_wrapper_width) {
                var d = this.image_wrapper_width - b;
                a.css('left', (d / 2) + 'px')
            }
        },
        _getDescription: function (a) {
            var b = false;
            if (a.desc.length || a.title.length) {
                var c = '';
                if (a.title.length) {
                    c = '<strong class="ad-description-title">' + a.title + '</strong>'
                };
                var b = '';
                if (a.desc.length) {
                    b = '<span>' + a.desc + '</span>'
                };
                b = $('<p class="ad-image-description">' + c + b + '</p>')
            };
            return b
        },
        showImage: function (a, b) {
            if (this.images[a] && !this.in_transition) {
                var c = this;
                var d = this.images[a];
                this.in_transition = true;
                if (!d.preloaded) {
                    this.loading(true);
                    this.preloadImage(a, function () {
                        c.loading(false);
                        c._showWhenLoaded(a, b)
                    })
                } else {
                    this._showWhenLoaded(a, b)
                }
            }
        },
        _showWhenLoaded: function (a, b) {
            if (this.images[a]) {
                var c = this;
                var d = this.images[a];
                var e = $(document.createElement('div')).addClass('ad-image');
                var f = $(new Image()).attr('src', d.image);
                if (d.link) {
                    var g = $('<a href="' + d.link + '" target="_blank"></a>');
                    g.append(f);
                    e.append(g)
                } else {
                    e.append(f)
                }
                this.image_wrapper.prepend(e);
                var h = this._getContainedImageSize(d.size.width, d.size.height);
                f.attr('width', h.width);
                f.attr('height', h.height);
                e.css({
                    width: h.width + 'px',
                    height: h.height + 'px'
                });
                this._centerImage(e, h.width, h.height);
                var i = this._getDescription(d, e);
                if (i) {
                    if (!this.settings.description_wrapper) {
                        e.append(i);
                        var j = h.width - parseInt(i.css('padding-left'), 10) - parseInt(i.css('padding-right'), 10);
                        i.css('width', j + 'px')
                    } else {
                        this.settings.description_wrapper.append(i)
                    }
                };
                this.highLightThumb(this.nav.find('.ad-thumb' + a));
                var k = 'right';
                if (this.current_index < a) {
                    k = 'left'
                };
                this.fireCallback(this.settings.callbacks.beforeImageVisible);
                if (this.current_image || this.settings.animate_first_image) {
                    var l = this.settings.animation_speed;
                    var m = 'swing';
                    var n = this.animations[this.settings.effect].call(this, e, k, i);
                    if (typeof n.speed != 'undefined') {
                        l = n.speed
                    };
                    if (typeof n.easing != 'undefined') {
                        m = n.easing
                    };
                    if (this.current_image) {
                        var o = this.current_image;
                        var p = this.current_description;
                        o.animate(n.old_image, l, m, function () {
                            o.remove();
                            if (p) p.remove()
                        })
                    };
                    e.animate(n.new_image, l, m, function () {
                        c.current_index = a;
                        c.current_image = e;
                        c.current_description = i;
                        c.in_transition = false;
                        c._afterShow();
                        c.fireCallback(b)
                    })
                } else {
                    this.current_index = a;
                    this.current_image = e;
                    c.current_description = i;
                    this.in_transition = false;
                    c._afterShow();
                    this.fireCallback(b)
                }
            }
        },
        nextIndex: function () {
            if (this.current_index == (this.images.length - 1)) {
                if (!this.settings.cycle) {
                    return false
                };
                var a = 0
            } else {
                var a = this.current_index + 1
            };
            return a
        },
        nextImage: function (a) {
            var b = this.nextIndex();
            if (b === false) return false;
            this.preloadImage(b + 1);
            this.showImage(b, a);
            return true
        },
        prevIndex: function () {
            if (this.current_index == 0) {
                if (!this.settings.cycle) {
                    return false
                };
                var a = this.images.length - 1
            } else {
                var a = this.current_index - 1
            };
            return a
        },
        prevImage: function (a) {
            var b = this.prevIndex();
            if (b === false) return false;
            this.preloadImage(b - 1);
            this.showImage(b, a);
            return true
        },
        preloadAll: function () {
            var a = this;
            var i = 0;

            function preloadNext() {
                if (i < a.images.length) {
                    i++;
                    a.preloadImage(i, preloadNext)
                }
            };
            a.preloadImage(i, preloadNext)
        },
        preloadImage: function (a, b) {
            if (this.images[a]) {
                var c = this.images[a];
                if (!this.images[a].preloaded) {
                    var d = $(new Image());
                    d.attr('src', c.image);
                    if (!this.isImageLoaded(d[0])) {
                        this.preloads.append(d);
                        var e = this;
                        d.load(function () {
                            c.preloaded = true;
                            c.size = {
                                width: this.width,
                                height: this.height
                            };
                            e.fireCallback(b)
                        }).error(function () {
                            c.error = true;
                            c.preloaded = false;
                            c.size = false
                        })
                    } else {
                        c.preloaded = true;
                        c.size = {
                            width: d[0].width,
                            height: d[0].height
                        };
                        this.fireCallback(b)
                    }
                } else {
                    this.fireCallback(b)
                }
            }
        },
        isImageLoaded: function (a) {
            if (typeof a.complete != 'undefined' && !a.complete) {
                return false
            };
            if (typeof a.naturalWidth != 'undefined' && a.naturalWidth == 0) {
                return false
            };
            return true
        },
        highLightThumb: function (a) {
            this.thumbs_wrapper.find('.ad-active').removeClass('ad-active');
            a.addClass('ad-active');
            if (this.settings.thumb_opacity < 1) {
                this.thumbs_wrapper.find('a:not(.ad-active) img').fadeTo(300, this.settings.thumb_opacity);
                a.find('img').fadeTo(300, 1)
            };
            var b = a[0].parentNode.offsetLeft;
            b -= (this.nav_display_width / 2) - (a[0].offsetWidth / 2);
            this.thumbs_wrapper.animate({
                scrollLeft: b + 'px'
            })
        },
        fireCallback: function (a) {
            if ($.isFunction(a)) {
                a.call(this)
            }
        }
    };

    function AdGallerySlideshow(a, b) {
        this.init(a, b)
    };
    AdGallerySlideshow.prototype = {
        start_link: false,
        stop_link: false,
        countdown: false,
        controls: false,
        settings: false,
        nextimage_callback: false,
        enabled: false,
        running: false,
        countdown_interval: false,
        init: function (a, b) {
            var c = this;
            this.nextimage_callback = a;
            this.settings = b
        },
        create: function () {
            this.start_link = $('<span class="ad-slideshow-start">' + this.settings.start_label + '</span>');
            this.stop_link = $('<span class="ad-slideshow-stop">' + this.settings.stop_label + '</span>');
            this.countdown = $('<span class="ad-slideshow-countdown"></span>');
            this.controls = $('<div class="ad-slideshow-controls"></div>');
            this.controls.append(this.start_link).append(this.stop_link).append(this.countdown);
            this.countdown.hide();
            var a = this;
            this.start_link.click(function () {
                a.start()
            });
            this.stop_link.click(function () {
                a.stop()
            });
            $(document).keydown(function (e) {
                if (e.keyCode == 83) {
                    if (a.running) {
                        a.stop()
                    } else {
                        a.start()
                    }
                }
            });
            return this.controls
        },
        disable: function () {
            this.enabled = false;
            this.stop();
            this.controls.hide()
        },
        enable: function () {
            this.enabled = true;
            this.controls.show()
        },
        toggle: function () {
            if (this.enabled) {
                this.disable()
            } else {
                this.enable()
            }
        },
        start: function () {
            if (this.running || !this.enabled) return false;
            var a = this;
            this.running = true;
            this.controls.addClass('ad-slideshow-running');
            this._next();
            this.fireCallback(this.settings.onStart);
            return true
        },
        stop: function () {
            if (!this.running) return false;
            this.running = false;
            this.countdown.hide();
            this.controls.removeClass('ad-slideshow-running');
            clearInterval(this.countdown_interval);
            this.fireCallback(this.settings.onStop);
            return true
        },
        _next: function () {
            var c = this;
            var d = this.settings.countdown_prefix;
            var e = this.settings.countdown_sufix;
            clearInterval(c.countdown_interval);
            this.countdown.show().html(d + (this.settings.speed / 1000) + e);
            var f = 0;
            this.countdown_interval = setInterval(function () {
                f += 1000;
                if (f >= c.settings.speed) {
                    var a = function () {
                            if (c.running) {
                                c._next()
                            };
                            f = 0
                        };
                    if (!c.nextimage_callback(a)) {
                        c.stop()
                    };
                    f = 0
                };
                var b = parseInt(c.countdown.text().replace(/[^0-9]/g, ''), 10);
                b--;
                if (b > 0) {
                    c.countdown.html(d + b + e)
                }
            }, 1000)
        },
        fireCallback: function (a) {
            if ($.isFunction(a)) {
                a.call(this)
            }
        }
    }
})(jQuery);
