$.fn.droppy=function(d){d=$.extend({speed:250,delta:50},d||{});this.each(function(){var c=this,zIndex=1000;function getSubnav(a){if(a.nodeName.toLowerCase()=='li'){var b=$('> ul',a);return b.length?b[0]:null}else{return a}}function getActuator(a){if(a.nodeName.toLowerCase()=='ul'){return $(a).parents('li')[0]}else{return a}}function hide(){var a=getSubnav(this);if(!a)return;$.data(a,'cancelHide',false);setTimeout(function(){if(!$.data(a,'cancelHide')){$(a).slideUp(d.speed)}},d.speed+d.delta)}function show(){var a=getSubnav(this);if(!a)return;$.data(a,'cancelHide',true);$(a).css({zIndex:zIndex++}).slideDown(d.speed);if(this.nodeName.toLowerCase()=='ul'){var b=getActuator(this);$(b).addClass('hover');$('> a',b).addClass('hover')}}$('ul, li',this).hover(show,hide);$('li',this).hover(function(){$(this).addClass('hover');$('> a',this).addClass('hover')},function(){$(this).removeClass('hover');$('> a',this).removeClass('hover')})})};
(function($){$.event.special.mousewheel={setup:function(){var b=$.event.special.mousewheel.handler;if($.browser.mozilla)$(this).bind('mousemove.mousewheel',function(a){$.data(this,'mwcursorposdata',{pageX:a.pageX,pageY:a.pageY,clientX:a.clientX,clientY:a.clientY})});if(this.addEventListener)this.addEventListener(($.browser.mozilla?'DOMMouseScroll':'mousewheel'),b,false);else this.onmousewheel=b},teardown:function(){var a=$.event.special.mousewheel.handler;$(this).unbind('mousemove.mousewheel');if(this.removeEventListener)this.removeEventListener(($.browser.mozilla?'DOMMouseScroll':'mousewheel'),a,false);else this.onmousewheel=function(){};$.removeData(this,'mwcursorposdata')},handler:function(a){var b=Array.prototype.slice.call(arguments,1);a=$.event.fix(a||window.event);$.extend(a,$.data(this,'mwcursorposdata')||{});var c=0,returnValue=true;if(a.wheelDelta)c=a.wheelDelta/120;if(a.detail)c=-a.detail/3;a.data=a.data||{};a.type="mousewheel";b.unshift(c);b.unshift(a);return $.event.handle.apply(this,b)}};$.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery);
var size = {};

SlideshowModel = {
    queue: [],
    options: {'box':'', 'slider':'', 'host':'', 'play': '', 'index': ''},
    size: 0,
    current: 0,
    loadnow: -1,
    loaded: -1,
    action: false,
    show: false,
    time: 500,
    timer: 5000,
    counter: 0,
    loading: false,
    // Инициализация
    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':CoreModel.psize.c+'-'+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':CoreModel.psize.c+'-'+queue[i][1]});
           //}
           var b = queue.length % 10;
            var a = (queue.length - b) / 10;
            
            var i = 0;
            var j = 0;
            
            for (i = 0; i <= a; i++) {
                SlideshowModel.queue.push({'id':queue[i][0],'type':'i','src':CoreModel.psize.c+'-'+queue[i][1]});
                if (i < a) { 
                    for (j = (i * 10); j < ((i + 1) * 10); j++) {
                        SlideshowModel.queue.push({'id':queue[j][0],'type':'t','src':'s-'+queue[j][1]});
                    }
                }
                else {
                    for (j = (i * 10); j < queue.length; j++) {
                        SlideshowModel.queue.push({'id':queue[j][0],'type':'t','src':'s-'+queue[j][1]});
                    }                
                }
            }
            
            for (i = (a + 1); i <  queue.length; i++) {
                SlideshowModel.queue.push({'id':queue[i][0],'type':'i','src':CoreModel.psize.c+'-'+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');
        // Фотка еще не загружена
        var time = (index == 1) ? SlideshowModel.time * 3 : SlideshowModel.time;
        if (loaded == false) {
            SlideshowModel.action = true;
            $('#'+SlideshowModel.options.box+' img:visible').fadeOut(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(time, function() {
                SlideshowModel.activeThumb(index);
                SlideshowModel.showImage(index, manual);
            });
        }
    },
    // Движение слайдера и активация привьюшки
    activeThumb: function(index) {
        $('#'+SlideshowModel.options.slider+ ' .active').removeClass('active');
        $('#t'+index).addClass('active');
        SlideshowModel.current = index;
    },
    // Показываем картинку
    showImage: function(index, manual) {
        var time = (index == 0) ? SlideshowModel.time * 3 : SlideshowModel.time;
        $('#i'+index).fadeIn(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);
        }
        return false;
    },
    play: function() {
        /**
         * Play
         */
        if (SlideshowModel.show == false) {
            if (SlideshowModel.current < (SlideshowModel.size - 1)) {
                SlideshowModel.show = true;
                $('#'+SlideshowModel.options.play+' a').html('slideshow stop');
                $(document).everyTime(SlideshowModel.timer, 'slideshow', function() {
                    SlideshowModel.nextImage(false);
                    if (SlideshowModel.current >= (SlideshowModel.size - 2)) {
                        SlideshowModel.play();
                    }
                });
            }
        }
        /**
         * Stop
         */
        else {
            SlideshowModel.show = false;
            $('#'+SlideshowModel.options.play+' a').html('slideshow play');
            $(document).stopTime('slideshow');
        }
        return false;
    }
}

BackgroundModel = {
    images: [],
    host: '',
    count: 0,
    limit: 0,
    box: '',
    action: false,
    current: 0,
    counter: 0,
    time: 1000,
    timer: 3500,
    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){
                  //  console.log('go!');
                   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+CoreModel.psize.c+'-'+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 - BackgroundModel.time, function(){
                            BackgroundModel.pause = true;
                         //   console.log(BackgroundModel.timer - BackgroundModel.time+'ms');
                        });
                    }
                    //если загружен лимит фото - установить признак
                    if (BackgroundModel.counter == BackgroundModel.limit - 1){
                       BackgroundModel.action = true;
                     //  console.log('limit is loaded');
                    }
                    BackgroundModel.counter += 1;
                    BackgroundModel.loading = false;
                    //как только признак загрузки лимита фоток и признак паузы будут установлены -  старт слайдшоу
                }).attr('src', BackgroundModel.host+CoreModel.psize.c+'-'+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 = {
    time: 500,
    action: false,
    init: function(image, host, box, box_bg, box_text, slider, text) {
        var img = new Image();
        $(img).load(function() {
            $('#'+box_bg).append($(this));
            $('#'+box_bg).width($(this).width()).height(CoreModel.psize.h);
            // 40 - left/right margin for text box
            $('#'+box_text).width(CoreModel.psize.w - $(this).width() - 40).height(CoreModel.psize.h);

            var ht = $('#'+text).height();
            if (ht > CoreModel.psize.h) {
                var height = CoreModel.psize.h - 60;
                var delta = 100;
                /**
                 * Set height for text slider
                 */
                $('#'+slider).height(height);
                $('#text-up').bind('click', function() {
                    TextModel.up(text, delta);
                    return false;
                });
                $('#text-down').bind('click', function() {
                    TextModel.down(text, delta, ht, height);
                    return false;
                });
                $('#text').mousewheel(function(e, d) {
                    if (d == 1) {
                        TextModel.up(text, delta);
                    }
                    else {
                        TextModel.down(text, delta, ht, height);
                    }
                });


                $('#'+box_text+' .text-arrow').show();
            }
            /**
             * Small text
             */
            else {
                var top = parseInt((CoreModel.psize.h - ht) / 2);
                $('#'+text).css('top', top);
            }
            $('#'+box).removeClass('loading').css({opacity: 0}).animate({opacity: 1}, TextModel.time, function() {

            });
        }).attr('src',host+'storage/backgrounds/'+CoreModel.psize.c+'-'+image);
    },
    up: function(text, delta) {
        if (TextModel.action == false) {
            TextModel.action = true;
            var top = Math.abs(parseInt($('#'+text).css('top')));
            if (top - delta > 0) {
                top = top - delta;
            }
            else {
                top = 0;
            }
            $('#'+text).animate({'top': '-'+top+'px'}, 200, function() {TextModel.action = false;});
        }
    },
    down: function(text, delta, ht, height) {
        if (TextModel.action == false) {
            TextModel.action = true;
            var top = Math.abs(parseInt($('#'+text).css('top')));
            if ((height + top + delta) < ht) {
                top = top + delta;
            }
            else {
                top = ht - height;
            }
            $('#'+text).animate({'top': '-'+top+'px'}, 200, function() {TextModel.action = false;});
        }
    }
}

CoreModel = {
    wsize : {},
    psize : {},
    whalf : 0,
    right : false,
    sliderAction: false,
    sliderTimer: 800,
    sliderStep: 0,
    sliderZone: 0,
    sliderBottom: 0,
    getWindowSize: function() {
        CoreModel.wsize = {'w': $(window).width(), 'h': $(window).height()};
    },
    getPhotoSize: function(sizes) {
        CoreModel.psize = {'c': 'a', 'w': 600, 'h': 400};
        var result = false;
        for (var i = 0; i < sizes.length; i++) {
            if (sizes[i]['w'] <= CoreModel.wsize.w && (sizes[i]['h'] + 114) <= CoreModel.wsize.h) {
                 CoreModel.psize = {'c': sizes[i]['c'], 'w': sizes[i]['w'], 'h': sizes[i]['h']};
                 result = true;
            }
        }
        return result;
    },
    setSliderAction: function(slider, inner, hs, hi) {
        if (hi > hs) {
            // 1. Разбиваем на куски hs
            CoreModel.sliderBottom = hi - hs;
            CoreModel.sliderStep = parseInt(hs / 5);
            CoreModel.sliderZone = 0;
            $('#'+slider).mousemove(function(e) {
                var position = parseInt(e.pageY / CoreModel.sliderStep);
                if (position != CoreModel.sliderZone) {
                    CoreModel.sliderZone = position;
                }
            });
            $('#'+slider).hover(function() {
                $('#'+slider).everyTime('10ms', 'slideshow-position', function() {
                    var top = parseInt($('#'+inner).css('top').replace('px',''));
                    if (CoreModel.sliderZone == 0) {
                         var step = top + 5;
                         if (step >= 0) {
                            step = 0;
                         }
                         $('#'+inner).css('top', step+'px');                    
                    }
                    if (CoreModel.sliderZone == 1) {
                         var step = top + 2;
                         if (step >= 0) {
                            step = 0;
                         }                         
                         $('#'+inner).css('top', step+'px');
                    }
                    if (CoreModel.sliderZone == 3) {
                         var step = top - 2;
                         if (CoreModel.sliderBottom + step <= 0) {
                            step = (-1)*CoreModel.sliderBottom;
                         }
                         $('#'+inner).css('top', step+'px');
                    }
                    if (CoreModel.sliderZone == 4) {
                         var step = top - 5;
                         if (CoreModel.sliderBottom + step <= 0) {
                            step = (-1)*CoreModel.sliderBottom;
                         }                         
                         $('#'+inner).css('top', step+'px');
                    }                                                                                                
                });        
            }, function() {
                $('#'+slider).stopTime('slideshow-position');
            });            
            
            
            
            /**
            //Scroll the menu on mouse move above the #sidebar layer
            $('#'+slider).mousemove(function(e) {
                if (CoreModel.sliderAction == false) {
                    CoreModel.sliderAction = true;
                    // Top
                    if (e.pageY < 50) {
                        $('#left-slider-inner').css('top', '0px');
                    }
                    // Center
                    else if (e.pageY >= 50 && e.pageY <= (hs - 50)) {
                        var dot = (hi - hs)  /  (hs - 100);
                        var top = parseInt((e.pageY - 50) * dot);
                        $('#'+inner).css('top', '-'+top+'px');

                    }
                    // Bottom
                    else {
                        $('#'+inner).css('top', '-'+(hi-hs)+'px');
                    }
                    CoreModel.sliderAction = false;
                }
            });
            **/
        }
        else {
            var top = parseInt((hs - hi) / 2);
            $('#'+inner).css('top', top+'px');
        }
    },
    setCustomCursor: function(box) {
        CoreModel.whalf = parseInt(CoreModel.wsize.w / 2);
        $('#'+box).mouseenter(function(e){
            if (e.clientX >= CoreModel.whalf) {
                $(this).removeClass('left').addClass('right');
                CoreModel.right = true;
            }
            else {
               $(this).removeClass('right').addClass('left');
               CoreModel.right = false;
            }
            return false;
        }).mousemove(function(e){
            if (e.clientX >= CoreModel.whalf && CoreModel.right == false) {
              $(this).removeClass('left').addClass('right');
              CoreModel.right = true;
            }
            if (e.clientX < CoreModel.whalf && CoreModel.right == true) {
               $(this).removeClass('right').addClass('left');
               CoreModel.right = false;
            }
        }).bind('click', function() {
            if (CoreModel.right == true) {
               SlideshowModel.nextImage(true);
            }
            else {
               SlideshowModel.privImage(true);
            }
        });
    }
}

$(document).ready(function() {
    $('#menu').droppy({speed: 400});
    $('#menu ul li a').hover(
        function(){
            $(this).addClass('active').animate({opacity : 1}, 200);
        },
        function() {
            $(this).animate({opacity: 0.6}, 200, function() {$(this).removeClass('active');});
        }
    );
    /**
     * Get window size
     */
    CoreModel.getWindowSize();
    /**
     * Get photo resolution
     */
    var result = CoreModel.getPhotoSize(psizes);
    if (result == false) {
       /**
        * Header + footer + default height for photo
        */
       CoreModel.wsize.h = 554;
    }
    /**
     * Set size
     */
    $('.l-header').removeClass('none');
    $('#inner').width(CoreModel.psize.w).height(CoreModel.psize.h).removeClass('none');
    $('.l-footer').removeClass('none');
    /**
     * blur effect for menu
     */
    /**
     * blur effect for menu
     */
    function setBlur(){
        $("#home img").attr('src', '/images/blur-home-'+siteLang+'.png');
        $("#portfolio img").attr('src', '/images/blur-portfolio-'+siteLang+'.png');
        $("#blog img").attr('src', '/images/blur-blog-'+siteLang+'.png');
        $("#info img").attr('src', '/images/blur-info-'+siteLang+'.png');
        $("#contact img").attr('src', '/images/blur-contact-'+siteLang+'.png');
    }
    function dropBlur(){
        $("#home img").attr('src', '/images/home-'+siteLang+'.png');
        $("#portfolio img").attr('src', '/images/portfolio-'+siteLang+'.png');
        $("#blog img").attr('src', '/images/blog-'+siteLang+'.png');
        $("#info img").attr('src', '/images/info-'+siteLang+'.png');
        $("#contact img").attr('src', '/images/contact-'+siteLang+'.png');
    }
    $("#home").hover(
        function(){
            setBlur();
            $("#home img").attr('src', '/images/home-'+siteLang+'.png');
        },
        function(){
            dropBlur();
        }
    );
    $("#portfolio").hover(
        function(){
            setBlur();
            $("#portfolio img").attr('src', '/images/portfolio-'+siteLang+'.png');
        },
        function(){
            dropBlur();
        }
    );
    $("#blog").hover(
        function(){
            setBlur();
            $("#blog img").attr('src', '/images/blog-'+siteLang+'.png');
        },
        function(){
            dropBlur();
        }
     );
    $("#info").hover(
        function(){
            setBlur();
            $("#info img").attr('src', '/images/info-'+siteLang+'.png');
        },
        function(){
            dropBlur();
        }
    );
    $("#contact").hover(
        function(){
            setBlur();
            $("#contact img").attr('src', '/images/contact-'+siteLang+'.png');
        },
        function(){
            dropBlur();
        }
    );
});
