(function () {
    var MOVE_PHOTO_TO_ALBUM_URL = "/pictures/move";
    var ADD_NEW_ALBUM_URL = "/albums";
    var CURSOR_MARGIN = 15;

    function fixWidth(root) {
        $("ul", root).each(function () {
            var x = 0;//PAD;
            $("> li", this).each(function () {
                $(this).css("left", x);
                x = x + 72;//$(this).outerWidth();
            });
            $(this).width(x);

            var y = $(window).width() - 266;
            if(x < y){
                $("em.nav").addClass("hidden");
            }
        });
    }

    function addEmptyAlbum(root) {
        var album = $(['<li class="{id:0}">',
                         '<div class="holder">',
                           '<div class="cell">',
                             '<a href="#"><img src="/images/empty_album_stub_x64.jpg"></a>',
                           '</div>',
                           '<p><a href="#">Без названия</a></p>',
                         '</div></a>',
                       '</li>'].join('')).appendTo("ul.al", root);
        var rootWidth = $(root).width();
        var ulWidth = $("ul.al", root).outerWidth();
        if(rootWidth < ulWidth+72){
            $("ul.al", root).css({left: rootWidth-ulWidth-72});
        }

        album.data("metadata", {id: Math.round(20 + 50 * Math.random())});

        fixWidth(root);
        bindActions(album, root);

        return album;
    }
    
    function bindActions(ele, root) {
        $(ele).droppable({
            'tolerance': 'pointer',
            'over': function(e, ui){
                $('<div></div>').addClass('drop-ready').appendTo(this);
            },
            'out': function(e, ui){
                $(this).find('.drop-ready').remove();
            },
            'drop': function (e, ui) {
                $(this).find('.drop-ready').remove();

                var album = $(this).metadata({'attr': 'data'});
                var photo = $(ui.draggable).picsaPhoto();
                var new_album;

                if (photo) {
                    if (!album || !album.id) {
                        new_album = addEmptyAlbum(root);
                    }
                    photo.remove();
                    $(ui.helper).remove();

                    $.post(MOVE_PHOTO_TO_ALBUM_URL, {'id': photo.id, 'album_id': album.id},
                            function (resp) {
                                if(new_album !== undefined){
                                    new_album.data("metadata", {id: resp.id});
                                    new_album.find('a').attr('href', resp.url);
                                    new_album.find('img').attr('src', resp.cover_url);
                                }
                            }, "json");
                }
            }
        });
    }

    function cutName(name, limit) {
        if(name.length > limit){
            return name.substr(0, limit) + '...';
        }else{
            return name;
        }
    }
    /**
     * Панель альбомов
     *
     * @param root
     * @param cfg
     *
     * @event scroll
     *
     */
    PICSA.AlbumPanel = function (root, cfg) {
        this.root = root;
        Observable(this);

        if(cfg){
            this._init(root, cfg);
        }
    };

    $.extend(PICSA.AlbumPanel.prototype, {
        _init: function (root, cfg) {
            var me = this;
            me.root = root;
            me.scrollTimer = new Timer();

            var first_item = cfg.default_album;
            $(['<div style="padding:0 133px 0;">',
                 '<div class="special no-album">',
                     '<div class="holder '+ first_item.id +'">',
                       '<div class="cell {id:'+ first_item.id +'}">',
                         '<a href="' + first_item.url + '"><img src="/images/album-cover.png" /></a>',
                       '</div>',
                       '<p class="noedit"><a href="' + first_item.url + '">Не разобрано</a></p>',
                     '</div>',
                 '</div>',
                 '<em class="nav left hidden"></em>',
                 '<div class="albums-wrapper">',
                   '<ul class="al"></ul>',
                 '</div>',
                 '<em class="nav right"></em>',
                 '<div class="special new-album">',
                   '<div class="holder">',
                     '<div class="cell {id:0}">',
                       '<img src="/images/new-album-dropzone.png">',
                     '</div>',
                     '<p class="noedit">Новый альбом</p>',
                   '</div>',
                 '</div>',
               '</div>'].join('')).appendTo(root);
            var album_root = ".albums-wrapper";

            $.each(cfg.albums, function(){
                $("ul.al", me.albums_root).append(['<li class="{id:' + this.id + '}">',
                     '<div class="holder '+this.id+'">',
                       '<div class="cell">',
                         '<a href="' + this.url + '"><img src="' + this.cover_url + '" /></a>',
                       '</div>',
                       '<p class="' + this.id +'"><a href="' + this.url + '">' + cutName(this.name, 8) + '</a></p>',
                     '</div>',
                   '</li>'].join(''));
            });
            fixWidth(root);

            $("ul", album_root).draggable({
                'axis': 'x',
                'drag': function (e, ui) {
                    var x = ui.position.left,
                        ulWidth = $(ui.helper).outerWidth(),
                        rootWidth = $(album_root).width();
                    if (x > 0) {
                        ui.position.left = 0;
                    } else {
                        if (ulWidth > rootWidth) {
                            if (ulWidth + x < rootWidth) {
                                ui.position.left = rootWidth - ulWidth;
                            }
                        } else {
                            ui.position.left = 0;
                        }
                    }
                    me.checkArrows(ui.position.left, ulWidth, rootWidth);
                },
                'stop': function (e, ui) {
                    $.cookies.set("scroll", ui.position.left);
                }
            });

            $(root).droppable({
                'accept': '.photo',
                'over': function(e, ui){
                    $(ui.helper).addClass('drag-preview');
                    
                    var top = e.pageY, left = e.pageX;
                    var ctop = ui.position.top, cleft = ui.position.left;
                    var offset = $('#photos div.photos-holder').offset().top;
                    $(ui.helper).css({marginTop:  top - ctop - offset + CURSOR_MARGIN,
                                      marginLeft: left - cleft + CURSOR_MARGIN
                                });
                },
                'out': function(e, ui){
                    $(ui.helper).removeClass('drag-preview');
                    $(ui.helper).css({marginTop:'', marginLeft:''});
                },
                'tolerance': 'pointer'
            });

            $("em.nav", root).mousedown(function(){
                var dir = $(this).hasClass("right") ? -1 : $(this).hasClass("left") ? 1 : 0;
                me.handleScroll(dir);
            }).mouseup(function () {
                me.scrollTimer.cancel();
            });

            $(window).resize(function(){
                fixWidth(root);
                me.handleScroll(0);
            });

            $("ul > li", album_root).each(function() {
                bindActions(this, root);
            });
            $(".special .cell", root).each(function(){
                bindActions(this, root);
            });
            $(".new-album", root).click(function(){
                var new_album = addEmptyAlbum(root);

                $.post(ADD_NEW_ALBUM_URL, {},
                        function (resp) {
                            new_album.data("metadata", {id: resp.id});
                            new_album.find('a').attr('href', resp.url);
                        }, "json");
                return false;
            });

        },
        handleScroll: function(dir) { // dir = {-1,0,1}
            var me = this;
            var scroll = $("ul", me.root);
            var width = $("ul", me.root).outerWidth();

            function doScroll() {
                var pos = parseInt(scroll.css("left"), 10);
                pos = pos + dir * 100;
                if (pos + width < scroll.parent().width()) {
                    pos = scroll.parent().width() - width;
                }
                if (pos > 0) {
                    pos = 0;
                }
                
                scroll.css("left", pos);
                me.checkArrows(pos, width, scroll.parent().width());
                $.cookies.set("scroll", pos);
            }

            doScroll();
            me.scrollTimer.later(250, function () {
                doScroll();
                me.scrollTimer.periodic(50, doScroll);
            });
        },
        checkArrows: function(pos, ulWidth, rootWidth){
            var me = this;

            if(rootWidth < ulWidth){
                //$("em.nav").removeClass("hidden");
                if(pos == 0){
                    $("em.left", me.root).addClass("hidden");
                    me.scrollTimer.cancel();
                }else{
                    $("em.left", me.root).removeClass("hidden");
                }
                if(pos == rootWidth - ulWidth){
                    $("em.right", me.root).addClass("hidden");
                    me.scrollTimer.cancel();
                }else{
                    $("em.right", me.root).removeClass("hidden");
                }
            }
        }
    });

})();
