$(document).ready(function() {
    $('#hg').slideshow();
    
    $('#boxes a').click(function() {
        var box = '';
        
        switch ($(this).parents('.box').attr('id'))
        {
            case 'prev':
                box = 'Last project';
                break;
            case 'next':
                box = 'Next project';
                break;
            case 'support':
                box = 'Support box';
                break;
        }
        _gaq.push(['_trackEvent', 'Homepage', 'Boxes', box]);
    });
});

var SM = {};
SM.SlideShow = function(el, options) {
    if (el) 
    {
        this.init(el, options);
    }
};
$.extend(SM.SlideShow.prototype, {
    name: 'ui-slideshow',
    config: {
        type: 1,
        configxml: '/Xml/Photogallery/homepage.xml',
        loader: '/Images/UI/ui-loader.swf'
    },
    elements: {
        ul: null,
        div: null,
        items: null,
        loader: $('<div class="ui-loader" />')
    },
    init: function(el, options) {
        this.element = $(el).addClass(this.name);
        this.element.bind('destroy', $.proxy(this.teardown, this));
        this.bind();
        $.data(el, this.name, this);
        $.extend(this.config, options || {});
        
        
        this.elements.loader.append($('<div id="ui-loader" />')).appendTo(this.element);
        
        swfobject.embedSWF(this.config.loader, 'ui-loader', '32', '32', '9.0.0', '', '', '', {
            quality: 'best',
            wmode: 'transparent'
        });
        
        this.loadConfig();
    },
    loadConfig: function() {
        var self = this;
        
        $.ajax({
            url: self.config.configxml,
            dataType: 'xml',
            error: function() {
                self.selectType(self.config.type);
            },
            success: function(doc) {
                var xd = self.xmlDoc = $(doc);
                self.selectType(xd.find('type').attr('id'));
            }
        });
    },
    selectType: function(type) {
        var self = this;
        if (type == '0') 
        {
            self.elements.items = self.xmlDoc.find('item');
            self.gallery.init(self.element);
        }
        else 
        {
            self.slide.init(self);
        }
    },
    gallery: {
        init: function(el) {
            var self = this;
            self.obj = SM.SlideShow.prototype;
            self.ul = self.obj.elements.ul = $('<ul />');
            self.element = el;
            self.loadImage(self.obj.elements.items.length - 1);
        },
        loadImage: function(index) {
            var self = this;
            var items = self.obj.elements.items;
            
            if (index >= 0) 
            {
                $(new Image()).load(function() {
                    $('<li />').append($(this)).appendTo(self.obj.elements.ul);
                    self.loadImage(index - 1);
                }).attr({
                    src: items.eq(index).attr('path'),
                    width: 996,
                    height: 480
                });
            }
            else 
            {
                self.element.empty().append($('<div class="hg" />').append(self.obj.elements.ul), $('<div />').addClass('ui-slideshow-frame'));
                setTimeout(function() {
                    self.start()
                }, 3000)
            }
        },
        start: function() {
            var self = this;
            $('li:last-child img').animate({
                opacity: 0
            }, 1500, function() {
                $(this).css('opacity', 1).stop().parent().prependTo(self.ul);
                
                setTimeout(function() {
                    self.start()
                }, 3000)
            })
        }
    },
    slide: {
        init: function(that) {
            $(new Image()).load(function() {
                that.element.empty().iSlider({
                    xmlDoc: that.xmlDoc,
                    image: $(this)
                });
            }).error(function() {
            }).attr('src', that.xmlDoc.find('type').attr('path'));
        }
    },
    destroy: function() {
        this.element.unbind('destroyed', this.teardown);
        this.teardown();
    },
    teardown: function() {
        $.removeData(this.element[0], this.name);
        this.element.removeClass(this.name);
        this.unbind();
        this.element = null;
    },
    bind: function() {
    
    },
    unbind: function() {
    
    }
});

SM.ImageSlider = function(el, options) {
    if (el) 
    {
        this.init(el, options);
    }
};
$.extend(SM.ImageSlider.prototype, {
    name: 'ui-sliding',
    config: {
        delta: 0,
        guid: 0,
        maxRight: 0,
        handleWidth: 0,
        scrollStep: 20,
        playing: false
    },
    playable: true,
    init: function(el, options) {
        $.extend(this.config, options || {});
        this.element = $(el).addClass(this.name);
        
        this._create();
        
        this.config.viewportW = this.wrapper.innerWidth();
        this.config.viewportH = this.wrapper.height();
        this.config.maxRight = this.config.image.width() - this.config.viewportW;
        this.config.handleWidth = this.leftScroller.width();
        this.config.imageWidth = this.config.image.width();
        
        this.wrapper.scrollLeft(((this.config.imageWidth - this.config.viewportW) / 2));
        this.player.css({
            top: (this.config.viewportH / 2) - 40,
            left: (this.config.viewportW / 2) - 40
        });
        $('div', this.leftScroller).css('top', this.config.viewportH / 2 - 50);
        $('div', this.rightScroller).css('top', this.config.viewportH / 2 - 50);
        
        this.element.bind('destroy', $.proxy(this.teardown, this));
        this.bind();
        
        $.data(el, this.name, this);
    },
    _create: function() {
        this.leftScroller = $('<div class="ui-scroller-spl"><div /></div>').appendTo(this.element);
        this.rightScroller = $('<div class="ui-scroller-spr"><div /></div>').appendTo(this.element);
        this.wrapper = $('<div class="ui-scroller-wrapper" />');
        this.area = $('<div class="ui-scroller-area" />').append(this.config.image)
        this.player = $('<div class="ui-scroller-button ui-pausing" />').appendTo(this.element);
        
        this.area.appendTo(this.wrapper);
        this.wrapper.appendTo(this.element);
    },
    destroy: function() {
        this.element.unbind('destroyed', this.teardown);
        this.teardown();
    },
    teardown: function() {
        $.removeData(this.element[0], this.name);
        this.element.removeClass(this.name);
        this.unbind();
        this.element = null;
    },
    bind: function() {
        var self = this;
        
        self._mouseMove(this.leftScroller, 'l');
        self._mouseMove(this.rightScroller, 'r');
        
        self._handleHover(this.leftScroller, 'l');
        self._handleHover(this.rightScroller, 'r');
        
        self.element.bind('click', function() {
            if (self.config.playing) 
            {
                clearInterval(self.config.guid);
                self.player.addClass('ui-pausing').removeClass('ui-playing');
                self.config.playing = false;
				self.playable = false;
            }
            else 
            {
                self.player.removeClass('ui-pausing').addClass('ui-playing');
				self.playable = true;
                self._slide();
            }
            
            
            self.player.css('opacity', 1).stop().animate({
                opacity: 0
            }, 4000);
        });
    },
    _handleHover: function(handle, dir) {
        var self = this;
        handle.hover(function() {
            self.config.dir = dir;
            self._slide();
            $(this).stop().animate({
                opacity: .35
            }, 400);
        }, function() {
            self._slide();
            $(this).stop().animate({
                opacity: 0
            }, 400);
        });
    },
    _slide: function() {
        var self = this;
        if (self.playable) 
        {
            var dir = self.config.dir;
            
            clearInterval(self.config.guid);
            self.config.playing = true;
            self.player.removeClass('ui-pausing').addClass('ui-playing');
            self.config.guid = setInterval(function() {
                var d = self.config.delta;
                var scrollLeft = self.wrapper.scrollLeft();
                
                if ((dir == 'l' && scrollLeft > 0) || (dir == 'r' && scrollLeft < self.config.maxRight)) 
                {
                    if (dir == 'l') 
                        d *= -1;
                    
                    self.wrapper.scrollLeft(scrollLeft + d);
                }
            }, 1);
        }
    },
    _mouseMove: function(handle, dir) {
        var self = this;
        handle.bind('mousemove', function(e) {
            var x;
            if (dir == 'r') 
            {
                x = (e.pageX - handle.offset().left);
            }
            else 
            {
                x = self.config.handleWidth - (e.pageX - handle.offset().left);
            }
            
            self.config.delta = Math.round(x / self.config.handleWidth * self.config.scrollStep);
        });
    },
    unbind: function() {
    
    }
});

$.pluginMaker('slideshow', SM.SlideShow);
$.pluginMaker('iSlider', SM.ImageSlider);

