(function($){
    //cache needed for overagressive garbage collectors.
    var cache = [];
    //images can either be an array of paths to images or a  single image. 
    $.loadImages = function(images, pr, motion, autopl, callback) {
        //convert to array if needed so rest of script works
        if (!(images instanceof Array)) {
            images = [images];
        }
        
        var imagesLength = images.length;
        var loadedCounter = 0;
        
        for (var i = imagesLength; i--;) {
			var cacheImage = document.createElement('img');
			//set the onload method before the src is called otherwise will fail to be called in IE
            cacheImage.onload = function(){
                loadedCounter++;
                if (loadedCounter >= imagesLength) {
                    if ($.isFunction(callback)) {
                        callback(pr, motion, autopl);
                    }
                }
            }
            cacheImage.src = images[i];
            cache.push(cacheImage);
        }
    }
})(jQuery)


var width = 0;

var main_gallery_id = "image1";
var secondary_gallery_id = "image2";

var current_autoplay = null;

var current = 0;

var current_busy = false;

var current_project = 0;
var current_project_busy = false;
var current_project_motion = 'left';

var z = 0;

var projects = [];

function align_main_gallery() {
    width = $(window).width();
    if (width < 698) {
        width = 698;
    }
    main_gallery_width = $('#'+main_gallery_id).width();
    gallery_overlay = $('#gallery-overlay').width();
    
    $('#gallery').css('width', width);
    $('#'+main_gallery_id).css('left', Math.round((width - main_gallery_width)/2));
    $('#'+secondary_gallery_id).css('left', '-600px');
    $('#gallery-overlay').css('left', Math.round((width - gallery_overlay)/2));
}

function start_autoplay() {
    $('#nav-operation').removeClass().addClass('play');
    if (current_autoplay == null) {
        current_autoplay = setInterval(autoplay, 4000);
    }
}

function stop_autoplay() {
    $('#nav-operation').removeClass().addClass('pause');
    clearInterval(current_autoplay);
    current_autoplay = null;
}

function restart_autoplay() {
    if (current_autoplay != null) {
        clearInterval(current_autoplay);
        current_autoplay = setInterval(autoplay, 4000);
    }
}

function toggle_autoplay() {
    if (current_autoplay != null) {
        stop_autoplay();
    } else {
        start_autoplay();
    }
}
        
function autoplay() {
    if (current < projects[current_project].length - 1) {
        next = getNext();
        if (current_project_motion == 'left') {
            showCurrent(current_project, next, 'left', true);               
        } else {
            showCurrent(current_project, next, 'right', true);
        }
        
    } else {
        next = getNextProject();
        if (current_project_motion == 'left') {
            showCurrentProject(next, 'right');
            current_project_motion = 'right';           
        } else {
            showCurrentProject(next, 'left');
            current_project_motion = 'left';
        }
    }
}

$(document).ready(function() {
    align_main_gallery();
    showCurrentProject(current_project, current_project_motion, true);
    start_autoplay();
});
$(window).resize(function() {
    align_main_gallery();
});


function loop() {
    showCurrent(current);
    getNext();
}

function getNext() {
    next = 0;
    stop_flag = false;
    $.each(projects[current_project], function(i, val) {
        if (stop_flag) {
            next = i;
            return false;
        }
        if (current == i) {
            stop_flag = true;
        }
    })
    return next;
}

function getNextProject(curr) {
    next = 0;
    stop_flag = false;
    if (curr === undefined) {
        curr = current_project;
    }
    $.each(projects, function(i, val) {
        if (stop_flag) {
            next = i;
            return false;
        }
        if (curr == i) {
            stop_flag = true;
        }
    })
    return next;
}

function getPrevProject(curr) {
    prev = projects.length - 1;
    if (curr === undefined) {
        curr = current_project;
    }
    $.each(projects, function(i, val) {
        if (curr == i) {
            return false;
        }
        prev = i;                
    })
    return prev;
}

function getPrev() {
    prev = projects[current_project].length - 1;
    $.each(projects[current_project], function(i, val) {
        if (current == i) {
            return false;
        }
        prev = i;                
    })
    return prev;
}

function showCurrentProject(pr, motion, autopl) {
    
    images_to_preload = [];
    $.each(projects[pr], function(i, val) {
        if (projects[pr][i]['loaded'] === undefined) {
            projects[pr][i]['loaded'] = true;
            images_to_preload.push(projects[pr][i]['url']);
        }
    })
    if (images_to_preload.length > 0) {
        if (current_autoplay != null || autopl == true) {
            stop_autoplay();
            autopl = true;
        } else {
            autopl = false;
        }
        $('#ajax-loader').show();
        $.loadImages(images_to_preload, pr, motion, autopl, showCurrentProject_exec);    
    } else {
        showCurrentProject_exec(pr, motion);
    }

}

function showCurrentProject_exec(curr, motion, autoplay) {
    
    $('#ajax-loader').hide();
    if (current_project_busy || current_busy) {
        return false;
    }
    if (autoplay == true) {
        if (current_autoplay == null) {
            start_autoplay();
        }
    }
    
    current_project_busy = true;
    
    current = 0;
    current_project = curr;
    
    img_holder = $('<div>').css('position', 'absolute').css('z-index', z);
    img_src = $('<img>').attr('src', projects[current_project][current]['url']);
    z++;
    
    img_holder.append(img_src);
    img_holder.prependTo($('#'+secondary_gallery_id));
    

    
    if (motion == 'left') {
        width = $(window).width();
        
        $('#'+secondary_gallery_id).css('position', 'relative').css('left', width);
        $('#'+main_gallery_id).css('position', 'absolute');
        
        left_corner = parseInt($('#'+main_gallery_id).css('left'));
        right_corner = left_corner + 600;
        
        var l0 = width;
        var l1 = right_corner;
        var l2 = left_corner;
        l1 = (l1 - l0)/(l2 - l0);
        var push = true;
        
    } else {
        $('#'+secondary_gallery_id).css('left', -600).css('position', 'absolute');
        $('#'+main_gallery_id).css('position', 'relative');
        
        left_corner = parseInt($('#'+main_gallery_id).css('left'));
        right_corner = left_corner + 600;
        
        var l0 = -600;
        var l1 = left_corner - 600;
        var l2 = left_corner;
        l1 = (l1 - l0)/(l2 - l0);
        var push = true;
        
    }
    
    // задание функции анимации
    jQuery.easing.easeInQuadRight = function (x, current_time, start_value, end_value, total_time) {
        
        //x - (null) this is an extra parameter not needed for the equations, but necessary for compatibility with jQuery
        
        t1 = 0;
        t2 = total_time/8;
        t4 = total_time;
        t3 = t2 + (t4 - t2) / 1.1;

        r1 = start_value;
        r2 = l1;
        r3 = end_value - 0.02;
        r4 = end_value;
        
        if (push && current_time + 30 > t2) {
            push = false;
            if (motion == 'left') {
                push_main_gallery_left(main_gallery_id);
            } else {
                push_main_gallery_right(main_gallery_id);  
            }
        }
        
        if (current_time <= t2) {

            a1 = (r2-r1)/(t2-t1);
            b1 = r1-a1*t1;
            y = a1*current_time + b1;
        } else {
            r1 = r2;
            r2 = r3;
            r3 = r4;

            t1 = t2;
            t2 = t3;
            t3 = t4;                    
            
            a2 = (r3-((t3*(r2-r1)+t2*r1-t1*r2)/(t2-t1)))/(t3*(t3-t1-t2)+t1*t2);
            b2 = ((r2-r1)/(t2-t1)) - a2*(t1+t2);
            c2 = ((t2*r1 - t1*r2)/(t2-t1)) + a2*t1*t2;
            y = a2*current_time*current_time + b2*current_time + c2
        }
        return y;

        //return ((end_value-start_value)/total_time)*current_time + start_value;
    	//return l1;//end_value*(current_time/=total_time)*current_time + start_value;
    };
    
    function push_main_gallery_right(mgallery_id) {
        $('#line-side').hide();
        $('#'+mgallery_id).animate({left: $(window).width()}, 500, function () {
            $('#line-side').css('left', '632px').show();
            $('#'+mgallery_id).hide().css('left', '-600px').show();
        });
    }
    function push_main_gallery_left(mgallery_id) {
        $('#line-side').hide();
        $('#'+mgallery_id).animate({left: -600}, 500, function () {
            $('#line-side').css('left', '49px').show();
        });
    }
    
    if (motion == 'left') {
        $('#'+secondary_gallery_id).animate({left: (left_corner)}, 1000, "easeInQuadRight", function() {
            
            temp = secondary_gallery_id;
            secondary_gallery_id = main_gallery_id;
            main_gallery_id = temp
            
            align_main_gallery();
            current_project_busy = false;
        });
    } else {
        $('#'+secondary_gallery_id).animate({left: (left_corner)}, 1000, "easeInQuadRight", function() {
            
            temp = secondary_gallery_id;
            secondary_gallery_id = main_gallery_id;
            main_gallery_id = temp
            
            align_main_gallery();
            current_project_busy = false;
        });
    }
    

    
    $('#line-bottom *').fadeOut('fast', function () {
        $('#line-bottom').empty();
        addNumbers();
    });
    
    if ($('#line-bottom *').size() == 0) {
        addNumbers();
    }
    
    function addNumbers() {
        $.each(projects[current_project], function (i, val) {
            el = $('<a>').attr('href', '#').attr('id', 'photo-'+current_project+'-'+i).text(pad(i+1, 2));
            el.click(function() {
              showCurrent(current_project, i, current_project_motion);
              return false;
            })

            //$('<a href="#" onclick="showCurrent('+current_project+', '+i+', \'random\');return false;">').attr('id', 'photo-'+current_project+'-'+i).text(pad(i+1, 2));
            if (current == i) {
                el.addClass('active');
            }
            $('#line-bottom').append(el);
        });
        $('#line-bottom *').fadeIn('slow');
    }
    
}

function afterAnimate() {
    $('#'+main_gallery_id+' div').each(function(i){
        if (i != 0) {
            $(this).remove();
        }
    })
    align_main_gallery();
    current_busy = false;
}

function showCurrent(curr_project, curr, motion, ap) {
    
    
    if (current_project_busy) {
        return false;
    } else if (current_busy && !ap) {
        $('#'+main_gallery_id+' div').stop();
        $('#'+main_gallery_id+' div img').stop();
        $('#'+main_gallery_id+' div').first().animate({ width: '600px', height: '400px'}, 100);//.css({ width: '600px', height: '400px'}); 
        $('#'+main_gallery_id+' div:first img').first().animate({opacity: 1}, 100, function () {
            afterAnimate();
            showCurrent(curr_project, curr, motion);
            restart_autoplay();
        });
        
        return false;
    } else if (current_busy) {
        return false;
    }
    current_busy = true;
    
    current = curr;
    current_project = curr_project;
    
    r = Math.floor(Math.random()*11);
    if (motion == 'random' && r <= 5) {
        motion = 'right';    
    } else if (motion == 'random') {
        motion = 'left';
    }
    
    
    if (motion == 'left' && $.browser.msie && parseInt($.browser.version) <= 7) {
        motion = 'right';
    }
    
    img_holder = $('<div>').css('position', 'absolute').css('z-index', z).css('width', '0px').css('height', '400px');
    img_src = $('<img>').attr('src', projects[curr_project][curr]['url']).css('opacity', 0);
    
    img_holder.append(img_src);
    z++;
    
    if ($('#'+main_gallery_id+' div').size() == 0) {
        img_src.css('opacity', 1);
    }
    img_holder.prependTo($('#'+main_gallery_id));
    
    if ($('#'+main_gallery_id+' div').size() > 1) {
        
        $('#'+main_gallery_id+' div').css('position', 'absolute');
        
        if (motion == 'right') {
            img_src.css('float', 'left');
            img_holder.css('float', 'left').animate({ width: '600px', height: '400px'}, 1500, afterAnimate);
            img_src.animate({opacity: 1}, 1500);
        } else if (motion == 'left') {
            img_src.css('position', 'relative').css('float', 'right');                    
            img_holder.css('float', 'right').css('position', 'relative').animate({ width: '600px', height: '400px'}, 1500, afterAnimate);
            img_src.animate({opacity: 1}, 1500);
        } else if (motion == 'fade') {
            img_holder.css('float', 'left').css('width', '600px');
            img_src.css('float', 'left').animate({opacity: 1}, 1500, afterAnimate);
        }
        
    } else {
        current_busy = false;
    }
    $('#line-bottom a').removeClass('active');
    $('#line-bottom a#photo-'+curr_project+'-'+curr).addClass('active');
    
    
}

function nextPhoto() {
    if (!current_busy && !current_project_busy) {
        next = getNext();
        showCurrent(current_project, next, 'left');   
    }
}

function prevPhoto() {
    if (!current_busy && !current_project_busy) {
        prev = getPrev();
        showCurrent(current_project, prev, 'right');  
    }
}

function nextGallery() {
    if (!current_busy && !current_project_busy) {
        next = getNextProject();
        restart_autoplay();
        showCurrentProject(next, 'left');   
    }
}

function prevGallery() {
    if (!current_busy && !current_project_busy) {
        prev = getPrevProject();
        restart_autoplay();
        showCurrentProject(prev, 'right');   
    }
}

function pad(number, length) {
   
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
   
    return str;

}


