/* Image Preload **************************************************************/
(function($) {
    $.fn.preload = function(callback, src) {
        $.preload(toArray(this, src || 'src'), callback, this);
        return this;
    };

    $.preload = function(array, callback, arg) {
        callback = callback || $.noop;
        arg = arg || array;

        var count = array.length;
        var complete = 0;
        var $container = create();

        for (var i in array) {
            $('<img>').load(function(e) {
                complete++;
                $(e.currentTarget).remove();

                if (complete === count) {
                    destroy();
                    callback(arg);
                }
            }).attr('src', array[i]).appendTo($container);
        }
    };

    var threads = 0;

    var create = function() {
        threads++;
        return threads === 1 ? $('<div id="x-preload"></div>').appendTo('body') : $('#x-preload');
    };

    var destroy = function() {
        threads--;
        !threads && $('#x-preload').remove();
    };

    var toArray = function(selector, src) {
        return $.map($(selector).filter('img[' + src + ']').toArray(), function(el) {
            return $(el).attr('src');
        });
    };
})(jQuery);
/* End Image Preload **********************************************************/


AICMedia.SimpleScroll = {

    isAnimated: false,

    initialize: function() {
        this.scroll = $('.js-simple-scroll');
        if ( this.scroll.length ) {
            this.slider = this.scroll.find('.slider');
            this.items = this.scroll.find('.item');
            if (AICMedia.ie8) {
                this.items.hover(function(){
                    $(this).find('.info').show();
                }, function(){
                    $(this).find('.info').hide();
                });
            } else {
                this.items.hover(function(){
                    $(this).find('.info').stop().fadeTo(500, 1);
                }, function(){
                    $(this).find('.info').stop().fadeTo(500, 0);
                });
            }
            this.table = this.scroll.find('.items');
            this.table.width(this.items.length * 320);

            this.table.click($.proxy(this.onClick, this));

            var max = this.items.length * 320 - 959;

            this.slider.find('.knob').draggable({
                containment: 'parent' ,
                drag: $.proxy(function(event, ui){
                    var left = $(event.target).position().left;
                    var a = max/($(event.target).parent().width() - $(event.target).width() + 1);
                    this.slide(a*left)
                }, this),
                stop: $.proxy(function(event, ui) {
                    this.updateButtonState();
                }, this)
            });

            this.updateButtonState();

            $.preload([
                '/img/b-scroller/left.png',
                '/img/b-scroller/right.png',
                '/img/b-simple-scroll/knob.png',
                '/img/b-simple-scroll/body.png'
            ], $.proxy(function() {
                this.scroll.find('[xstyle]').each(function() {
                    var $el = $(this);
                    $el.attr('style', $el.attr('xstyle'));
                    $el.removeAttr('xstyle');
                });
                this.scroll.find('[xsrc]').each(function() {
                    var $el = $(this);
                    $el.attr('src', $el.attr('xsrc'));
                    $el.removeAttr('xsrc');
                });
            }, this));
        }
    },

    onClick: function(e) {
        var target = $(e.target);
        if ( target.hasClass('more') ) {
            var id = $(target).closest('.item').attr('id').split('-')[1];
            var html = $('#client-'+id).find('.description').html();
            AICMedia.TransparentBackdrop.show($.proxy(this.closeClientWindow, this));
            AICMedia.Window.attach('client-window');
            AICMedia.Window.updateContent(html)
            AICMedia.Window.resize();
//            $('#client-window').hide().fadeIn();
        }
    },

    closeClientWindow: function() {
//        AICMedia.Window.currentWindow.fadeOut(function() {
            AICMedia.Window.detach();
            AICMedia.TransparentBackdrop.hide();
//        });
    },

    slide: function(value) {
        this.table.css('margin-left', '-'+(value)+'px');
    },

    getPosition: function() {
        var knob = this.slider.find('.knob');
        return (100 * Math.abs(parseInt(knob.css('left')))) / (this.slider.width() - knob.outerWidth());
    },

    updateButtonState: function() {
        var pos = this.getPosition();
        this.buttonPrevState = true;
        this.buttonNextState = true;
        if (pos <= 0.2) {
            this.buttonPrevState = false;
        }
        if (pos >= 99.8) {
            this.buttonNextState = false;
        }

        if (AICMedia.SimpleScrollArrows.isEnabled) {
            if (this.buttonPrevState && this.buttonNextState) {
                AICMedia.SimpleScrollArrows.setState('both');
            } else if (this.buttonPrevState) {
                AICMedia.SimpleScrollArrows.setState('left');
            } else if (this.buttonNextState) {
                AICMedia.SimpleScrollArrows.setState('right');
            } else {
                AICMedia.SimpleScrollArrows.setState('none');
            }
        }
    },

    buttonSlide: function(count) {
        this.isAnimated = true;

        var ITEM_WIDTH = 320;
        var MAX_POS = (this.items.length - 3) * ITEM_WIDTH - 1;
        var curPos = parseInt(this.table.css('marginLeft'));
        var ABS_SHIFT = Math.abs(count > 0 ? Math.min(MAX_POS + curPos, ITEM_WIDTH * count) : Math.max(curPos, ITEM_WIDTH * count));
        var SLIDE_DURATION = Math.pow(ABS_SHIFT * 5.3, 0.75);


        this.table.animate({
            marginLeft: (count > 0 ? '-=' : '+=') + ABS_SHIFT + 'px'
        }, SLIDE_DURATION);

        var $knob = this.slider.find('.knob');
        var k = (MAX_POS) / (this.slider.width() - $knob.width() + 1)
        $knob.animate({
            left: (count > 0 ? '+=' : '-=') + Math.ceil(ABS_SHIFT / k) + 'px'
        }, SLIDE_DURATION, $.proxy(function() {
            this.isAnimated = false;
            this.updateButtonState();
        }, this));
    }

};





AICMedia.SimpleScrollArrows = {
    $leftArrow: null,
    $rightArrow: null,
    $hint: null,
    $both: null,
    showState: null,
    timer: null,
    isEnabled: false,
    isHovered: false,

    start: function() {
        var $scroller = AICMedia.PageLoader.currentFrame.find('.b-simple-scroll');
        this.$leftArrow = $scroller.find('.arrow-prev img');
        this.$rightArrow = $scroller.find('.arrow-next img');

        if (!($scroller.length && this.$leftArrow.length && this.$rightArrow.length)) {
            return;
        }

        this.$hint = AICMedia.PageLoader.currentFrame.find('.b-scroller-hint').css(AICMedia.ie8 ? {display: 'none'} : {opacity: 0});
        this.$both = this.$leftArrow.add(this.$rightArrow);
        this.$both.addClass('disabled').css(AICMedia.ie8 ? {display: 'none'} : {opacity: 0}).hover($.proxy(function() {
            this.isHovered = true;
            this._updateHint();
        }, this), $.proxy(function() {
            this.isHovered = false;
        }, this));

        this._updateState();

        this.$leftArrow.closest('a').bind('click', $.proxy(this._prev, this));
        this.$rightArrow.closest('a').bind('click', $.proxy(this._next, this));
        $(window).keydown($.proxy(this._keyDown, this));

        this.isEnabled = true;

        $scroller.mousemove($.proxy(function() {
            this._updateButtons();
            this._timer();
        }, this));
    },

    _keyDown: function(event) {
        if (event.ctrlKey && event.keyCode == 37) {
            this.$leftArrow.closest('a').click();
            event.preventDefault();
        } else if (event.ctrlKey && event.keyCode == 39) {
            this.$rightArrow.closest('a').click();
            event.preventDefault();
        }
    },

    _updateState: function() {
        if (AICMedia.SimpleScroll.buttonPrevState && AICMedia.SimpleScroll.buttonNextState) {
            this.showState = 'both';
        } else if (AICMedia.SimpleScroll.buttonPrevState) {
            this.showState = 'left';
        } else if (AICMedia.SimpleScroll.buttonNextState) {
            this.showState = 'right';
        } else {
            this.showState = 'none';
        }
    },

    _prev: function(event) {
        if (!AICMedia.SimpleScroll.isAnimated && AICMedia.SimpleScroll.buttonPrevState) {
            AICMedia.SimpleScroll.buttonSlide(-3);
        }
        event.preventDefault();
    },

    _next: function(event) {
        if (!AICMedia.SimpleScroll.isAnimated && AICMedia.SimpleScroll.buttonNextState) {
            AICMedia.SimpleScroll.buttonSlide(3);
        }
        event.preventDefault();
    },

    stop: function() {
        if (this.isEnabled) {
            this._hide(this.$both);
            this.isEnabled = false;
            this.$leftArrow.closest('a').unbind('click');
            this.$rightArrow.closest('a').unbind('click');
            this.$both.addClass('disabled').removeClass('show, hide');
        }
    },

    setState: function(state) {
        if (this.isEnabled) {
            this.showState = state;
            this._updateButtons();
            this._updateHint();
        }
    },

    _updateHint: function() {
        if (this.isHovered && !this.$hint.hasClass('show')) {
            if (AICMedia.ie8) {
                this.$hint.show();
            } else {
                this.$hint.removeClass('hide').addClass('show').stop().show().fadeTo(300, 1, function() {
                    $(this).removeClass('show');
                });
            }
        } else if (!this.isHovered && !this.$hint.hasClass('hide')) {
            if (AICMedia.ie8) {
                this.$hint.hide();
            } else {
                this.$hint.removeClass('show').addClass('hide').stop().fadeTo(1000, 0, function() {
                    $(this).hide();
                    $(this).removeClass('hide');
                });
            }
        }
    },

    _updateButtons: function() {
        switch(this.showState) {
        case 'both':
            this.$both.removeClass('disabled');
            break;
        case 'left':
            this.$leftArrow.removeClass('disabled');
            this.$rightArrow.addClass('disabled');
            break;
        case 'right':
            this.$rightArrow.removeClass('disabled');
            this.$leftArrow.addClass('disabled');
            break;
        case 'none':
        default:
            this.$both.addClass('disabled');
            break;
        }

        this._show(this.$both.filter(':not(.disabled)'));
        this._hide(this.$both.filter('.disabled'));
    },

    _show: function($buttons) {
        $buttons = $buttons.filter(':not(.show)');
        if (this.isEnabled && $buttons.length) {
            $buttons.removeClass('hide').addClass('show');
            $buttons.closest('a').css({display: 'block'});

            if (AICMedia.ie8) {
                $buttons.show();
                $buttons.removeClass('show');
            } else {
                $buttons.stop().animate({opacity: 1}, 300, function() {
                    $buttons.removeClass('show');
                });
            }
        }
    },

    _hide: function($buttons) {
        $buttons = $buttons.filter(':not(.hide)');
        if (this.isEnabled && $buttons.length) {
            $buttons.removeClass('show').addClass('hide');

            if (AICMedia.ie8) {
                $buttons.hide();
                $buttons.closest('a').css({display: 'none'});
                $buttons.removeClass('hide');
            } else {
                $buttons.stop().fadeTo(1000, 0, function() {
                    $buttons.closest('a').css({display: 'none'});
                    $buttons.removeClass('hide');
                });
            }
        }
    },

    _timer: function() {
        clearTimeout(this.timer);
        this.timer = setTimeout($.proxy(function() {
            this._updateHint();
            if (!this.isHovered) {
                this._hide(this.$both);
            }
        }, this), 1000);
    }
};
