$(function() {
    var totalPanels  = $(".scrollContainer").children().size();
    var movingDistance = parseInt($(".panel").css("width")) + parseInt($(".panel").css("padding-left")) + parseInt($(".panel").css("padding-right"));
    var $panels        = $('#slider .scrollContainer > div');
    var $container     = $('#slider .scrollContainer');
    
    $panels.css({'float' : 'left','position' : 'relative'});
    
    $("#slider").data("currentlyMoving", false);
    
    $container
        .css('width', ($panels[0].offsetWidth * $panels.length) + 100)
        .css('left', parseInt($(".scroll").css("width")) / 2 - parseInt($(".panel").css("padding-left")) - parseInt($(".panel").css("width")) / 2 - 315 + "px");
    
    
    
    //direction true = right, false = left
    function change(direction) {
        //if not at the first or last panel
        //if ((direction && !(curPanel < (totalPanels - 2))) || (!direction && (curPanel <= 1))) { return false; }
        if (($("#slider").data("currentlyMoving") == false)) {
            // если мотаем вперед, промотали до середины + 3(?) картинки, то слайдер отбрасывается назад
            if (curPanel >= $panels.length / 2 + 3) {
                $(".scrollContainer").css("left", parseInt($(".scrollContainer").css("left")) + $panels[0].offsetWidth * $panels.length / 2 + "px");
                curPanel -= $panels.length / 2;
            }
            // если мотаем назад, а первая картинка вплотную к левому краю, то слайдер отбрасывается вперед
            if (curPanel <= 2) {
                $(".scrollContainer").css("left", parseInt($(".scrollContainer").css("left")) - $panels[0].offsetWidth * $panels.length / 2 + "px");
                curPanel += $panels.length / 2;
            }
        }
        //if not currently moving
        if (($("#slider").data("currentlyMoving") == false)) {
            $("#slider").data("currentlyMoving", true);
            
            var next      = direction ? curPanel + 1 : curPanel - 1;
            var leftValue = $(".scrollContainer").css("left");
            var movement  = direction ? parseFloat(leftValue) - movingDistance : parseFloat(leftValue) + movingDistance;
            
            $(".scrollContainer")
                .stop()
                .animate({
                    "left": movement
                }, function() {
                    $("#slider").data("currentlyMoving", false);
                });
            
            curPanel = next;
            
            $("#panel_"+(curPanel+1)).unbind(); // remove all previous bound functions
            $("#panel_"+(curPanel+1)).click(function(){ change(true); }); // go forward
            $("#panel_"+(curPanel-1)).unbind(); // remove all previous bound functions
            $("#panel_"+(curPanel-1)).click(function(){ change(false); }); // go back
            $("#panel_"+curPanel).unbind(); // remove all previous bound functions
        }
    }
    
    // устанавливаем начальную картинку
    var curPanel = 2;
    
    $("#panel_"+(curPanel+1)).click(function(){ change(true); });
    $("#panel_"+(curPanel-1)).click(function(){ change(false); });
    
    // обрабатываем нажатие стрелочек на сайте
    $(".right").click(function(){ change(true); });
    $(".left").click(function(){ change(false); });
    
    // обрабатываем нажатие клавиш клавиатуры
    $(window).keydown(function(event){
        switch (event.keyCode) {
            case 13: //enter
                $(".right").click();
                break;
            case 32: //space
                $(".right").click();
                break;
            case 37: //left arrow
                $(".left").click();
                break;
            case 39: //right arrow
                $(".right").click();
                break;
        }
    });
});