SlideshowModel = {
    queue: [],
    options: {'box':'', 'slider':'', 'host':'', 'play': '', 'index': ''},
    size: 0,
    buff: null,
    current: 0,
    loaded: -1,
    action: false,
    show: false,
    time: 500,
    timer: 5000,
    loading: false,
    // Init
    init: function(queue, host, box, slider, index, c_play, c_next, c_priv) {
        if (queue.length >= 1) {
            // Formation queue
            // First photo
            SlideshowModel.queue.push({'id':queue[0][0],'type':'i','src':queue[0][1]});
            // Thumbs
            for (var i = 0; i < queue.length; i++) {        
                SlideshowModel.queue.push({'id':queue[i][0],'type':'t','src':'s-'+queue[i][1]});        
            }
            // Other photos
            for (i = 1; i < queue.length; i++) {
                SlideshowModel.queue.push({'id':queue[i][0],'type':'i','src':queue[i][1]});                             
            }
            SlideshowModel.size = queue.length;
        }
        SlideshowModel.buff = 0;
        SlideshowModel.options.box = box;
        SlideshowModel.options.host = host;
        SlideshowModel.options.play = c_play;
        SlideshowModel.options.index = index;
        SlideshowModel.options.slider = slider;

        $('#'+c_play).click(function() {return SlideshowModel.play();});
        $('#'+c_priv).click(function() {return SlideshowModel.privImage(true);});
        $('#'+c_next).click(function() {return SlideshowModel.nextImage(true);});

        // Strt loader
        $(document).everyTime('25ms', 'slideshow-load-queue', function() {
            SlideshowModel.loadQueue();
        });
    },
    loadQueue: function() {
        // If queue not empty
        if (SlideshowModel.queue.length > 0) {
            if (SlideshowModel.loading == false) {
                // Set loading flag
                SlideshowModel.loading = true;
                var el = SlideshowModel.queue.shift();
                var img = new Image();
                // Element is thumb
                if (el.type == 't') {
                    $(img).bind("load", function() {
                        var tbox = $('#t'+el.id);
                        var abox = $('<a href="#"></a>').append($(this));
                        tbox.find('.img').remove().end().append(abox);
                        if (el.id == 0) {
                            tbox.addClass('active');
                        }
                        // Thumb click event
                        $(abox).click(function() {
                            var id = parseInt($(this).parent().attr('id').replace('t',''));
                            SlideshowModel.thumbClick(id, true);
                            return false;
                        });
                        SlideshowModel.loading = false;
                    }).attr('src', SlideshowModel.options.host+el.src);
                }
                // Element is photo
                else {
                    $(img).bind("load", function() {
                        $(this).css('display','none').attr('id', 'i'+el.id);
                        $('#'+SlideshowModel.options.box).append($(this));
                        if (SlideshowModel.buff != null && el.id == SlideshowModel.buff) {
                            $('#'+SlideshowModel.options.box).removeClass('loading');
                            // Start slideshow
                            if (el.id == 0) {
                                SlideshowModel.play();
                                SlideshowModel.showImage(el.id, false);
                            }
                            else {
                                SlideshowModel.showImage(el.id, true);
                            }
                            SlideshowModel.buff = null;
                        }
                        $('#t'+el.id).addClass('loaded');
                        SlideshowModel.loaded += 1;
                        SlideshowModel.loading = false;
                    }).attr('src', SlideshowModel.options.host+el.src);
                }
            }
        }
        else {
            $(document).stopTime('slideshow-load-queue');
            SlideshowModel.loading = false;
        }
    },
    // Р¤РѕСЂРјРёСЂРѕРІР°РЅРёРµ РѕС‡РµСЂРµРґРё Р·Р°РіСЂСѓР·РѕРє
    formationQueue: function(index) {
        //SlideshowModel.loading = true;
        var buff = [];
        var el = null;
        // Make new queue
        for (var i = 0; i < SlideshowModel.queue.length; i++) {
            if (SlideshowModel.queue[i].id != index) {
                buff.push(SlideshowModel.queue[i]);
            }
            else {
                el = SlideshowModel.queue[i];
            }
        }
        // If el == null, it is mean, that image loading or loaded
        if (el != null) {
            buff.splice(0,0,el);
            if (el.type == 'i') {
                SlideshowModel.buff = el.id;
            }
        }
        else {
            // If image loaded, show it
            if ($('#t'+index).is('.loaded')) {
                $('#'+SlideshowModel.options.box).removeClass('loading');
                SlideshowModel.showImage(index, true);
            }
            // Change SlideshowModel.buff, image would show in loadQueue method
            else {
               SlideshowModel.buff = index;
            }
        }
        SlideshowModel.queue = buff;
       // SlideshowModel.loading = false;
    },

    thumbClick: function(index, manual) {
        var loaded = $('#t'+index).is('.loaded');

        if (loaded == false) {
            SlideshowModel.action = true;
            $('#'+SlideshowModel.options.box+' img:visible').fadeOut(SlideshowModel.time, function() {
                $('#'+SlideshowModel.options.box).addClass('loading');
                SlideshowModel.activeThumb(index);
                SlideshowModel.formationQueue(index);
            });
        }
        else if (SlideshowModel.action == false && SlideshowModel.current != index) {
            SlideshowModel.action = true;
            $('#i'+SlideshowModel.current).fadeOut(SlideshowModel.time, function() {
                SlideshowModel.activeThumb(index);
                SlideshowModel.showImage(index, manual);
            });
        }
    },
    activeThumb: function(index) {
        $('#'+SlideshowModel.options.slider+ ' .active').removeClass('active');
        $('#t'+index).addClass('active');
	if (SlideshowModel.size > 7) {
        	var tlimit = ((index - 3) < 0) ? 0 : (index - 3);
	        if (SlideshowModel.size <= index + 4) {
         	   tlimit = SlideshowModel.size - 7;
	        }
        	$('#'+SlideshowModel.options.slider).animate({top:'-'+tlimit * 54+'px'}, {queue:false, duration: 300});
	}	
        SlideshowModel.current = index;
        $('#'+SlideshowModel.options.index).html(parseInt(SlideshowModel.current) + 1);
    },

showImage: function(index, manual) {
        $('#i'+index).fadeIn(SlideshowModel.time, function() {
            if (SlideshowModel.show == true && manual == true) {
                SlideshowModel.play();
            }
            SlideshowModel.action = false;
        });
    },
    privImage: function() {
        if (SlideshowModel.current > 0) {
            SlideshowModel.thumbClick(SlideshowModel.current - 1, true);
        }
        return false;
    },
    nextImage: function(manual) {
        if (SlideshowModel.current < SlideshowModel.loaded) {
           SlideshowModel.thumbClick(SlideshowModel.current + 1, manual);
        }
        if (SlideshowModel.current == SlideshowModel.size - 1){
           SlideshowModel.thumbClick(0, manual);
        }
        return false;
    },
    play: function() {
        /**
         * Play
         */
        if (SlideshowModel.show == false) {
            if (SlideshowModel.current <= (SlideshowModel.size - 1)) {
                SlideshowModel.show = true;
                $('#'+SlideshowModel.options.play+' a').html('слайдшоу <span>стоп</span>');
                $(document).everyTime(SlideshowModel.timer, 'slideshow', function() {
                    SlideshowModel.nextImage(false);
                    if (SlideshowModel.current >= SlideshowModel.size) {
                        SlideshowModel.play();
                    }
                });
            }
        } else {
            SlideshowModel.show = false;
            $('#'+SlideshowModel.options.play+' a').html('слайдшоу <span>старт</span>');
            $(document).stopTime('slideshow');
        }
        return false;
    }
}

BackgroundModel = {
    images: [],
    host: '',
    count: 0,
    limit: 0,
    box: '',
    action: false,
    current: 0,
    counter: 0,
    time: 500,
    timer: 5000,
    pause: false,
    loading: false,
    init: function(images, host, count, limit, box) {
        BackgroundModel.images = images;
        BackgroundModel.host = host;
        BackgroundModel.count = count;
        BackgroundModel.limit = limit;
        BackgroundModel.box = box;
        if (BackgroundModel.count > 1) {
            if (BackgroundModel.count < BackgroundModel.limit) {
                BackgroundModel.limit = BackgroundModel.count;
            }

            BackgroundModel.counter = 0;

            BackgroundModel.loading = false;
            $(document).everyTime('25ms', 'background-loader', function() {BackgroundModel.loadImages()});
            $(document).everyTime('25ms', 'start', function(){
                if (BackgroundModel.action && BackgroundModel.pause){
                   BackgroundModel.slideImages();
                   $(document).everyTime(BackgroundModel.timer, 'slideshow', function() {BackgroundModel.slideImages()});
                   $(document).stopTime('start');
                }
            });
        }
        else {
            BackgroundModel.loadSingleImage();
        }
    },
    loadSingleImage: function() {
        var img = new Image();
        $(img).load(function() {
            $(this).css('display','none');
            $('#'+BackgroundModel.box).removeClass('loading').append($(this));
            $(this).fadeIn(BackgroundModel.time);
        }).attr('src', BackgroundModel.host+BackgroundModel.images[0]);
    },
    loadImages: function() {
        if (BackgroundModel.counter < BackgroundModel.images.length) {
            if (BackgroundModel.loading == false) {
                BackgroundModel.loading = true;
                var img = new Image();
                $(img).bind("load", function() {
                    $(this).css('display','none');
                    $('#'+BackgroundModel.box).append($(this));

                    if (BackgroundModel.counter == 0) {
                        // If first photo loaded, show her
                        $('#'+BackgroundModel.box).removeClass('loading');
                        $('#'+BackgroundModel.box+' img').eq(0).fadeIn(BackgroundModel.time);

                        $(document).oneTime(BackgroundModel.timer, function(){
                            BackgroundModel.pause = true;
                        });
                    }

                    if (BackgroundModel.counter == BackgroundModel.limit - 1){
                       BackgroundModel.action = true;
                    }
                    BackgroundModel.counter += 1;
                    BackgroundModel.loading = false;
                }).attr('src', BackgroundModel.host+BackgroundModel.images[BackgroundModel.counter]);
            }
        } else {
            $(document).stopTime('background-loader');
        }
    },
    slideImages: function() {
        var imgs = $('#'+BackgroundModel.box+' img');
        var size = imgs.size();
        if (BackgroundModel.action) {
            $(imgs[BackgroundModel.current]).fadeOut(BackgroundModel.time, function() {
                if (BackgroundModel.current < (size - 1)) {
                    BackgroundModel.current = BackgroundModel.current + 1;
                } else {
                    BackgroundModel.current = 0;
                }
                $(imgs[BackgroundModel.current]).fadeIn(BackgroundModel.time);
            });
        }
    }
}

TextModel = {
    init: function(image, host, box, text) {
        var img = new Image();
        $(img).load(function() {
        $('#'+box).removeClass('loading').css('opacity','0').css('background','url("'+$(this).attr('src')+'")');
            $('#'+text).removeClass('none').jScrollPane(
		{
		  showArrows: true,
		  horizontalDragMinWidth: 60,
		  horizontalDragMaxWidth: 60,
		  verticalDragMinHeight: 27,
		  verticalDragMaxHeight: 27

		 }
	 );
            $('#'+box).animate({opacity: 1}, 700);
        }).attr('src',host+'storage/backgrounds/'+image);
    }
}

ContactModel = {
    init: function(image, host, box, text) {
        var img = new Image();
        $(img).load(function() {
        $('#'+box).removeClass('loading').css('opacity','0').css('background','url("'+$(this).attr('src')+'")');
            $('#'+text).removeClass('none');
            $('#'+box).animate({opacity: 1}, 700);
        });
        $(img).attr('src',host+'storage/backgrounds/'+image);
    }
}

$(document).ready(function(){
    $('.b-btn-menu-open').animate({"right": "-=42px"}, "slow");
    $('.l-sidebar-i').animate ({"right": "+=141px"}, "slow");
    $('.b-btn-prev-open').animate({"left": "-=41px"}, "slow");
	$('.l-gallery-prev-i').animate ({"left": "+=95px"}, "slow");


	$('.b-btn-menu-open').click(function() {
		$(this).animate(
			{"right": "-=42px"}, "slow"
		);
		$('.l-sidebar-i').animate (
			{"right": "+=141px"}, "slow"
		);
	});
	$('.b-btn-menu-close').click(function() {
		$('.b-btn-menu-open').animate(
			{"right": "+=42px"}, "slow"
		);
		$('.l-sidebar-i').animate (
			{"right": "-=141px"}, "slow"
		);
	});
	$('.b-btn-prev-open').click(function() {
		$(this).animate(
			{"left": "-=41px"}, "slow"
		);
		$('.l-gallery-prev-i').animate (
			{"left": "+=95px"}, "slow"
		);
	});
	$('.b-btn-prev-close').click(function() {
		$('.b-btn-prev-open').animate(
			{"left": "+=41px"}, "slow"
		);
		$('.l-gallery-prev-i').animate (
			{"left": "-=95px"}, "slow"
		);
	});
});
