﻿$(document).ready(function () {

    var SliderThumbs = Slider.Start($('#SliderHome .ThumbsWrapper'), {
        Speed: 450,
        ItemPerGroup: 7,
        Orientation: 'horizontal', //horizontal, vertical
        Navigation: 'arrow', //arrow, bullet, both
        Effect: 'slide', //slide, fade
        Auto: false, //true, false
        Time: 20000,
        ItemLoad: true,
        Object: null
    });

    var SliderWrapper = Slider.Start($('#SliderHome .SliderWrapper'), {
        Speed: 450,
        ItemPerGroup: 1,
        Orientation: 'horizontal', //horizontal, vertical
        Navigation: 'arrow', //arrow, bullet, both
        Effect: 'fade', //slide, fade
        Auto: true, //true, false
        Time: 5000,
        ItemLoad: false,
        Object: SliderThumbs
    });
});



var Slider = new (function () {

    function Slider(rootElement, Options) {
        this.rootElement = rootElement;
        var that = this;
        var Items = new Array();
        var Effect;
        var TimerSlider;
        var OldImageWrapperPosition = 0;
        var ImageAnimationTimer = 15000; //time of imageeffect animation

        //default options
        var Default = {
            Speed: 450,
            ItemPerGroup: 1,
            Orientation: 'horizontal',
            Navigation: 'arrow',
            Effect: 'slide',
            Auto: false,
            Time: 3000,
            ItemLoad: true
        };
        var Options = $.extend(Default, Options);

        //orientation
        if (Options.Orientation == 'horizontal') {
            this.Prev = function () { that.Effect('right', 'left', null); };
            this.Next = function () { that.Effect('left', 'right', null); };
        }
        if (Options.Orientation == 'vertical') {
            this.Prev = function () { that.Effect('down', 'up', null); };
            this.Next = function () { that.Effect('up', 'down', null); };
        };

        //if bullet
        if (Options.Navigation == 'bullet' || Options.Navigation == 'both') {
            this.LoadBullet = function () {
                if (!$(this).hasClass('On')) {
                    $(that.rootElement).find('.Navigation .Bullet').removeClass('On');
                    $(this).addClass('On');
                    that.Effect('left', 'right', $(this).attr('alt'));
                }
            };
        };

        //effect
        this.Effect = function (inDir, outDir, ImageWrapperPosition) {
            that.DisableButtons();

            //direction of slide from loadBullet
            if (ImageWrapperPosition != null) {
                if (ImageWrapperPosition < OldImageWrapperPosition) {
                    inDir = 'right';
                    outDir = 'left';
                };
            }

            OldImageWrapperPosition = ImageWrapperPosition;

            //current & next
            var Current = $(that.rootElement).find('.ItemWrapper.On');

            //if !LoadBullet
            if (ImageWrapperPosition == null) {

                //default to slider and fade
                if (outDir == "down" || outDir == "right") {
                    var Next = $(Current).next('.ItemWrapper');
                    var Position = 'first';
                }
                else {
                    var Next = $(Current).prev('.ItemWrapper');
                    var Position = 'last';
                }

                //auto bullet
                if (Options.Navigation == 'bullet' || Options.Navigation == 'both') {
                    //next bullet
                    if (outDir == 'right')
                        var NextBullet = $(that.rootElement).find('.Navigation .Bullet.On').next('.Bullet');
                    else
                        var NextBullet = $(that.rootElement).find('.Navigation .Bullet.On').prev('.Bullet');

                    $(that.rootElement).find('.Navigation .Bullet').removeClass('On');
                    $(NextBullet).length ? $(NextBullet).addClass('On') : $(that.rootElement).find('.Navigation .Bullet:' + Position + '').addClass('On');
                }

            } else
            //if LoadBullet
                var Next = $(that.rootElement).find('.ItemWrapper:nth-child(' + ImageWrapperPosition + ')');

            //slide
            if (Options.Effect == 'slide') {
                $(Current).hide('slide', { direction: outDir }, Options.Speed, function () { $(this).removeClass("On").hide(); });
                if ($(Next).length != 0) {
                    $(Next).show('slide', { direction: inDir }, Options.Speed, function () {
                        $(this).addClass('On');
                        that.EnableButtons();
                    });
                } else {
                    Next = $(that.rootElement).find('.ItemWrapper:' + Position + '');
                    $(Next).show('slide', { direction: inDir }, Options.Speed, function () {
                        $(this).addClass('On');
                        that.EnableButtons();
                    });
                }
            }

            //fade
            if (Options.Effect == 'fade') {
                $(Current).fadeOut(Options.Speed, function () { $(this).removeClass("On").hide(); });
                if ($(Next).length != 0) {
                    $(Next).fadeIn(Options.Speed, function () {
                        $(this).addClass('On');
                        that.EnableButtons();
                    });
                } else {
                    Next = $(that.rootElement).find('.ItemWrapper:' + Position + '');
                    $(Next).fadeIn(Options.Speed, function () {
                        $(this).addClass('On');
                        that.EnableButtons();
                    });
                }
            }

            //thumb slider2 On
            if (Options.Object != null)
                Options.Object.LoadItem(Next, outDir);

        };

        //disable before effects
        this.DisableButtons = function () {
            that.AutoSlider(false, false);
            if (Options.Navigation == 'arrow' || Options.Navigation == 'both') {
                $(that.rootElement).find('.Navigation .NavNext').unbind('click', that.Next);
                $(that.rootElement).find('.Navigation .NavPrev').unbind('click', that.Prev);
            }
            if (Options.Navigation == 'bullet' || Options.Navigation == 'both')
                $(that.rootElement).find('.Navigation .Bullet').unbind('click', that.LoadBullet);
        };

        //enable after effects
        this.EnableButtons = function () {
            if (Options.Auto) that.AutoSlider(true, true);
            if (Options.Navigation == 'arrow' || Options.Navigation == 'both') {
                $(that.rootElement).find('.Navigation .NavNext').bind('click', that.Next);
                $(that.rootElement).find('.Navigation .NavPrev').bind('click', that.Prev);
            }
            if (Options.Navigation == 'bullet' || Options.Navigation == 'both')
                $(that.rootElement).find('.Navigation .Bullet').bind('click', that.LoadBullet);
        };

        //addBullet
        this.AddBullet = function () {
            $(that.rootElement).find('.ItemWrapper').each(function (i) {
                $(that.rootElement).find('.Navigation').append('<span class="Bullet" alt="' + (i + 1) + '">&nbsp</span>');
            });
            $(that.rootElement).find('.Navigation .Bullet:first').addClass('On');
        };

        //addArrow
        this.AddArrow = function () {
            $(that.rootElement).find('.Navigation .SliderControls').append('<span class="NavPrev"></span><span class="ControlIcon Play"></span><span class="NavNext"></span>');
        };

        //load item info
        this.LoadItemInfo = function (Item) { //check this
            $('#SliderHome').find('.Navigation .ItemInfo h2').text($(Item).find('.Name').val());
            if ($(Item).find('.URL').val() != "")
                $('#SliderHome').find('.Navigation .ItemInfo a').html($(Item).find('.URL').val() + '<span class="MagnifierIcon"></span>');
            else
                $('#SliderHome').find('.Navigation .ItemInfo a').html('')

            $('#SliderHome').find('.Navigation .ItemInfo a').attr('href', $(Item).find('.URL').val());
        }

        //loadItem Zenn
        this.LoadItem = function (ItemWrapper, Direction) {
            if (!$(ItemWrapper).hasClass('On')) {
                var that = this;

                //Load image
                var Img = new Image();
                var URL = $(ItemWrapper).find('.Image').val();

                if (URL.indexOf('?') != -1) URL += '&timestamp=' + new Date().getTime(); //IE caching problem
                else URL += '?timestamp=' + new Date().getTime();

                $(Img).load(function () {
                    $(ItemWrapper).find('.Item').append(this).fadeIn();

                    //Load image effect from image element
                    that.ImageEffect(Img);
                }).error(function () {
                    $(ItemWrapper).find('.Item').append("<b>Impossível apresentar a imagem seleccionada!</b>");
                }).attr('src', '' + URL + '');

                //fadeout itemwrapper on and remove image, less page weight
                $('#SliderHome .SliderWrapper .ItemWrapper.On').removeClass('On').fadeOut(200, function () {
                    $(this).find('img').remove();
                });

                //fade In the new one
                $(ItemWrapper).fadeIn(200).addClass('On');

                //load item info
                that.LoadItemInfo(ItemWrapper);

                //from slider alt
                $(rootElement).find('.Item').each(function () {
                    $(this).removeClass('On');
                    if ($(this).find('.Image').val() == $(ItemWrapper).find('.Image').val()) {
                        if ($(this).parent().hasClass('On')) {
                            $(this).addClass('On');
                        } else {
                            if (Direction == 'right')
                                $(that.rootElement).find('.Navigation .NavNext').click();
                            else
                                $(that.rootElement).find('.Navigation .NavPrev').click();

                            $(this).addClass('On');
                        }

                    }
                });

            }
        };

        //autoSlider
        this.AutoSlider = function (Action, ChangeControl) {
            if (that.rootElement.selector == '#SliderHome .SliderWrapper') //if root element is sliderwrapper
                var Time = ImageAnimationTimer;
            else
                var Time = Options.Time;

            if (Action) {
                clearTimeout(TimerSlider);
                TimerSlider = setTimeout(function () { that.Effect('left', 'right', null); }, Time);
                if (ChangeControl)
                    $(that.rootElement).find('.Navigation .ControlIcon').removeClass('Play').addClass('Pause');
            } else {
                clearTimeout(TimerSlider);
                if (ChangeControl)
                    $(that.rootElement).find('.Navigation .ControlIcon').removeClass('Pause').addClass('Play');
            }
        };

        //auto slide image
        this.ImageEffect = function (Img) {
            var ImageOn = Img;

            //calc sizes to animation
            var ImageHeight = ImageOn.height;
            var SliderHeight = $('#SliderHome .SliderWrapper').height();

            //image animation
            $(ImageOn).stop().css('top', '0px');
            $(ImageOn).animate({ 'top': '-' + (ImageHeight - SliderHeight) + 'px' }, ImageAnimationTimer + 3000, function () { $(this).animate({ 'top': '0px' }, ImageAnimationTimer + 3000); });

        };
        //FULLSCREEN
        this.Fullscreen = function (Item) {
            //reset
            that.FullPrepare(Item);
            $(window).resize(function () { that.FullPrepare(Item); });

            //on click
            $('#LightOff').click(function () { that.FullShowHide(false); });
            $('#Fullscreen').click(function () { that.FullShowHide(false); });

            //on show
            that.FullShowHide(true);
        };

        //calc size and position
        this.FullPrepare = function (Item) {
            var el = $('#Fullscreen');
            var elInner = $(Item).find('.Item img').height();
            var elParent = document.documentElement.clientHeight;

            if (elInner > elParent) elInner = elParent;

            var elMargin = ((elParent - elInner) / 2);

            $(el).css('margin-top', elMargin);
            $(el).find('img').attr('src', $(Item).find('.Item img').attr('src')).height(elInner);
        };

        //show hide
        this.FullShowHide = function (Show) {
            if (Show) {
                $('#LightOff').fadeIn(350);
                $('#Fullscreen').fadeIn(350);
            } else {
                $('#Fullscreen').fadeOut(350);
                $('#LightOff').fadeOut(350);
            }
        };
        //FULLSCREEN END

        //setup slider
        this.Setup = function () {
            if ($(that.rootElement).find('.Item').length == 0) return;

            var Html;
            var totalItems = 0;
            var nItemPerGroup = Options.ItemPerGroup;
            var closed = 0;

            //prepare            
            $(that.rootElement).find('.Item').each(function (i) { totalItems++; });
            $(that.rootElement).find('.Item').each(function (i) {
                if (i == 0)
                    Html = '<div class="ItemWrapper">';

                if (i != nItemPerGroup - 1 && i + 1 != totalItems)
                    Html += '<span class="Item">' + $(this).html() + '</span>';

                if (i + 1 == nItemPerGroup || i + 1 == totalItems) {
                    Html += '<span class="Item last-child">' + $(this).html() + '</span>';
                    Html += '</div>';
                    closed = 1;
                    nItemPerGroup += Options.ItemPerGroup;
                }

                if (i == totalItems - 1) {
                    Html += '</div>';
                    return 0;
                }

                if (closed != 0) {
                    Html += '<div class="ItemWrapper">'
                    closed = 0;
                }
            });

            //slider
            $(that.rootElement).find('.Items').html(Html).delay(300).fadeIn("fast");
            $(that.rootElement).find('.ItemWrapper:first').show();

            //check sliderthumbs
            if (Options.Object != undefined && Options.Object != null) {
                var items = $(that.rootElement).find('.ItemWrapper:first');
                if (items.length > 0) {
                    Options.Object.LoadItem($(items[0]), 'right');
                }
            }

            $(that.rootElement).find('.ItemWrapper:first').addClass('On');
            $(that.rootElement).slideDown(350);

            //add navigation
            if (Options.Navigation == 'bullet' || Options.Navigation == 'both')
                that.AddBullet();

            if (Options.Navigation == 'arrow' || Options.Navigation == 'both')
                that.AddArrow();
            if (Options.ItemLoad) { //check to send item from sliderwrapper
                $(that.rootElement).find('.Item').show().click(function () {
                    var Thumb = this;
                    $('#SliderHome .SliderWrapper .ItemWrapper').each(function () {
                        if ($(this).find('input').val() == $(Thumb).find('.Image').val())
                            that.LoadItem(this);
                    });
                });
            }

            //!=1 to add navigation
            if (totalItems > Options.ItemPerGroup) {
                if (Options.Navigation == 'arrow' || Options.Navigation == 'both') {
                    $(that.rootElement).find('.Navigation .NavNext').show().click(that.Next);
                    $(that.rootElement).find('.Navigation .NavPrev').show().click(that.Prev);
                }

                if (Options.Navigation == 'bullet' || Options.Navigation == 'both')
                    $(that.rootElement).find('.Navigation .Bullet').show().click(that.LoadBullet);
            }

            //fullscreen
            $(that.rootElement).find('.FullscreenIcon').click(function () {
                that.Fullscreen($(that.rootElement).find('.ItemWrapper.On'));
            });

            //autoSlide click
            $(that.rootElement).find('.Navigation .ControlIcon').click(function () {
                if ($(this).hasClass('Play')) var Opt = true;
                else var Opt = false;

                that.AutoSlider(Opt, true);
                Options.Auto = Opt;
            });

            //autostart
            if (Options.Auto)
                that.AutoSlider(Options.Auto, Options.Auto);

        };

        //init
        this.Setup();
    }

    //start
    this.Start = function (rootElement, Options) {
        return new Slider(rootElement, Options);
    };
})();
