(function($){$.fn.droppy=function(e){e=$.extend({speed:250,delta:50,align:'left',subwidth:'css',className:'droppy',trigger:'hover'},e||{});this.each(function(){var d=this,zIndex=1000;$(d).addClass(e.className);$(d).find('li:has(> ul) > a').addClass('has-subnav');if(e.align='center'){$(d).find('> li > ul').each(function(){var a=$(this).width();var b=$(this).parent().width();if(a>b){var c=-1*parseInt((a-b)/2);$(this).css('left',c+'px')}})}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(e.speed)}},e.speed+e.delta)};function show(){var a=getSubnav(this);if(!a)return;$.data(a,'cancelHide',true);$(a).css({zIndex:zIndex++}).slideDown(e.speed);if(this.nodeName.toLowerCase()=='ul'){var b=getActuator(this);$(b).addClass('hover');$('> a',b).addClass('hover')}return false};if(e.trigger=='click'){$('> li',this).click(function(a){if(a.target==this||a.target.parentNode==this){show.call(this)}});$('> li ul, > li li',this).hover(show,function(){});$('ul, li',this).hover(function(){},hide)}else{if(typeof $.fn.hoverIntent=='function'){$('ul, li',this).hoverIntent($.extend({sensitivity:2,interval:50,timeout:100},e.hoverIntent||{},{over:show,out:hide}))}else{$('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')})})}})(jQuery);
(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);
(function(a){a.tools=a.tools||{version:"v1.2.5"},a.tools.scrollable={conf:{activeClass:"active",circular:!1,clonedClass:"cloned",disabledClass:"disabled",easing:"swing",initialIndex:0,item:null,items:".items",keyboard:!0,mousewheel:!1,next:".next",prev:".prev",speed:400,vertical:!1,touch:!0,wheelSpeed:0}};function b(a,b){var c=parseInt(a.css(b),10);if(c)return c;var d=a[0].currentStyle;return d&&d.width&&parseInt(d.width,10)}function c(b,c){var d=a(c);return d.length<2?d:b.parent().find(c)}var d;function e(b,e){var f=this,g=b.add(f),h=b.children(),i=0,j=e.vertical;d||(d=f),h.length>1&&(h=a(e.items,b)),a.extend(f,{getConf:function(){return e},getIndex:function(){return i},getSize:function(){return f.getItems().size()},getNaviButtons:function(){return m.add(n)},getRoot:function(){return b},getItemWrap:function(){return h},getItems:function(){return h.children(e.item).not("."+e.clonedClass)},move:function(a,b){return f.seekTo(i+a,b)},next:function(a){return f.move(1,a)},prev:function(a){return f.move(-1,a)},begin:function(a){return f.seekTo(0,a)},end:function(a){return f.seekTo(f.getSize()-1,a)},focus:function(){d=f;return f},addItem:function(b){b=a(b),e.circular?(h.children("."+e.clonedClass+":last").before(b),h.children("."+e.clonedClass+":first").replaceWith(b.clone().addClass(e.clonedClass))):h.append(b),g.trigger("onAddItem",[b]);return f},seekTo:function(b,c,k){b.jquery||(b*=1);if(e.circular&&b===0&&i==-1&&c!==0)return f;if(!e.circular&&b<0||b>f.getSize()||b<-1)return f;var l=b;b.jquery?b=f.getItems().index(b):l=f.getItems().eq(b);var m=a.Event("onBeforeSeek");if(!k){g.trigger(m,[b,c]);if(m.isDefaultPrevented()||!l.length)return f}var n=j?{top:-l.position().top}:{left:-l.position().left};i=b,d=f,c===undefined&&(c=e.speed),h.animate(n,c,e.easing,k||function(){g.trigger("onSeek",[b])});return f}}),a.each(["onBeforeSeek","onSeek","onAddItem"],function(b,c){a.isFunction(e[c])&&a(f).bind(c,e[c]),f[c]=function(b){b&&a(f).bind(c,b);return f}});if(e.circular){var k=f.getItems().slice(-1).clone().prependTo(h),l=f.getItems().eq(1).clone().appendTo(h);k.add(l).addClass(e.clonedClass),f.onBeforeSeek(function(a,b,c){if(!a.isDefaultPrevented()){if(b==-1){f.seekTo(k,c,function(){f.end(0)});return a.preventDefault()}b==f.getSize()&&f.seekTo(l,c,function(){f.begin(0)})}}),f.seekTo(0,0,function(){})}var m=c(b,e.prev).click(function(){f.prev()}),n=c(b,e.next).click(function(){f.next()});!e.circular&&f.getSize()>1&&(f.onBeforeSeek(function(a,b){setTimeout(function(){a.isDefaultPrevented()||(m.toggleClass(e.disabledClass,b<=0),n.toggleClass(e.disabledClass,b>=f.getSize()-1))},1)}),e.initialIndex||m.addClass(e.disabledClass)),e.mousewheel&&a.fn.mousewheel&&b.mousewheel(function(a,b){if(e.mousewheel){f.move(b<0?1:-1,e.wheelSpeed||50);return!1}});if(e.touch){var o={};h[0].ontouchstart=function(a){var b=a.touches[0];o.x=b.clientX,o.y=b.clientY},h[0].ontouchmove=function(a){if(a.touches.length==1&&!h.is(":animated")){var b=a.touches[0],c=o.x-b.clientX,d=o.y-b.clientY;f[j&&d>0||!j&&c>0?"next":"prev"](),a.preventDefault()}}}e.keyboard&&a(document).bind("keydown.scrollable",function(b){if(e.keyboard&&!b.altKey&&!b.ctrlKey&&!a(b.target).is(":input")){if(e.keyboard!="static"&&d!=f)return;var c=b.keyCode;if(j&&(c==38||c==40)){f.move(c==38?-1:1);return b.preventDefault()}if(!j&&(c==37||c==39)){f.move(c==37?-1:1);return b.preventDefault()}}}),e.initialIndex&&f.seekTo(e.initialIndex,0,function(){})}a.fn.scrollable=function(b){var c=this.data("scrollable");if(c)return c;b=a.extend({},a.tools.scrollable.conf,b),this.each(function(){c=new e(a(this),b),a(this).data("scrollable",c)});return b.api?c:this}})(jQuery);

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, c_left, c_right) {
        $('#space').hide();
        SlideshowModel.queue = [];
        if (queue.length >= 1) {
            var c = 5;
            var b = queue.length % c;
            var a = (queue.length - b) / c;
            var i = 0;
            var j = 0;            
            for (i = 0; i <= a; i++) {
                SlideshowModel.queue.push({'id':queue[i][0],'type':'i','src':queue[i][1]});
                if (i < a) { 
                    for (j = (i * c); j < ((i + 1) * c); j++) {
                        SlideshowModel.queue.push({'id':queue[j][0],'type':'t','src':'s-'+queue[j][1]});
                    }
                }
                else {
                    for (j = (i * c); 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':queue[i][1]});
            }            
            SlideshowModel.size = queue.length;
        }
        /**
         * Init vars
         */
        SlideshowModel.buff = 0;
        SlideshowModel.show = false;
        SlideshowModel.loaded = -1;
        SlideshowModel.current = 0;
        SlideshowModel.loadnow = -1;
        SlideshowModel.counter = 0;
        SlideshowModel.action = false;
        
        SlideshowModel.options.box = box;
        SlideshowModel.options.host = host;
        SlideshowModel.options.play = c_play;
        SlideshowModel.options.index = index;
        SlideshowModel.options.slider = slider;

        $('#'+c_priv).click(function() {return SlideshowModel.privImage(true);});
        $('#'+c_next).click(function() {return SlideshowModel.nextImage(true);});
        $('#'+c_left).click(function() {return SlideshowModel.left(true);});
        $('#'+c_right).click(function() {return SlideshowModel.right(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) {
                            abox.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;
    },
    // Обработка клика по фотке
    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+' > a').addClass('active');
        var left = 0;
        var slimit = 0;
        for (var i = 0; i < SlideshowModel.size; i++) {
            if (i <= index) {
                left += $('#t'+i+' img').width() + 5;
            }
            slimit += $('#t'+i+' img').width() + 5;
        }
        if (slimit > 705) {
            // Правый предел
            if (left > (slimit - 350)) {
                left = slimit - 705;
            }
            // Центр
            else if (left > 350) {
               left -= 350;
            }
            // Левый предел
            else {
                left = 0;
            }
            $('#'+SlideshowModel.options.slider).animate({left:'-'+left+'px'}, SlideshowModel.time);
        }
        SlideshowModel.current = index;
    },
    // Показываем картинку
    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);
        }
        return false;
    },
    left: function() {
        var left  = parseInt($('#'+SlideshowModel.options.slider).css('left').replace('px',''));
        left = ((left+300) < 0) ? (left+300) : 0;
        $('#'+SlideshowModel.options.slider).animate({left:left+'px'}, SlideshowModel.time);
        return false;
    },
    right: function() {
        var left  = Math.abs($('#'+SlideshowModel.options.slider).css('left').replace('px',''));
        var slimit = 0;
        for (var i = 0; i < SlideshowModel.size; i++) {
            slimit += $('#t'+i+' img').width() + 5;
        }
        if (slimit > 701) {
            slimit -= 701;
            left += 300;
            if (left >= slimit) {
                left = slimit;
            }
            $('#'+SlideshowModel.options.slider).animate({left:'-'+left+'px'}, SlideshowModel.time);
        }
        return false;
    },    
    play: function() {
        /**
         * Play
         */
        if (SlideshowModel.show == false) {
            if (SlideshowModel.current < (SlideshowModel.size - 1)) {
                SlideshowModel.show = true;
                $(document).everyTime(SlideshowModel.timer, 'slideshow', function() {
                    SlideshowModel.nextImage(false);
                    if (SlideshowModel.current >= (SlideshowModel.size - 2)) {
                        SlideshowModel.play();
                    }
                });
            }
        }
        /**
         * Stop
         */
        else {
            SlideshowModel.show = false;
            $(document).stopTime('slideshow');
        }
        return false;
    }
}

BackgroundModel = {
    queue: [],
    options: {'box': '', 'host': '', 'limit': 1},
    action: false,
    loading: false,
    time: 500,
    timer: 5000,
    timestamp: 0,
    init: function(queue, host, limit, box) {
        // Init vars
        BackgroundModel.queue = queue;
        BackgroundModel.options.box = box;
        BackgroundModel.options.host = host;
        BackgroundModel.options.limit = limit;
        BackgroundModel.action = false;
        BackgroundModel.loading = false;
        
        if (BackgroundModel.queue.length > 1) {
            if (BackgroundModel.queue.length < BackgroundModel.options.limit) {
                BackgroundModel.options.limit = BackgroundModel.queue.length;
            }
            $(document).everyTime('25ms', 'background-loader', function() {BackgroundModel.loadImages()});
        }
        else {
            BackgroundModel.loadSingleImage();
        }
    },
    loadSingleImage: function() {
        var img = new Image();
        $(img).load(function() {
            $(this).css('display','none');
            $('#'+BackgroundModel.options.box).removeClass('loading').append($(this));
            $(this).fadeIn(BackgroundModel.time);
        }).attr('src', BackgroundModel.options.host+BackgroundModel.queue[0]);
    },
    loadImages: function() {
        // If queue not empty
        if (BackgroundModel.queue.length > 0) {
            if (BackgroundModel.loading == false) {
                // Set loading flag
                BackgroundModel.loading = true;
                var el = BackgroundModel.queue.shift();
                var img = new Image();
                $(img).bind("load", function() {
                    $(this).css('display','none');
                    $('#'+BackgroundModel.options.box).append($(this));
                    
                    var imgs = $('#'+BackgroundModel.options.box+' img');
                    var size = $(imgs).size();
                    
                    if (size == 1) {
                        $('#'+BackgroundModel.options.box).removeClass('loading');
                        BackgroundModel.timestamp = new Date;
                        BackgroundModel.timestamp = BackgroundModel.timestamp.getTime();
                        $(imgs).eq(0).fadeIn(BackgroundModel.time);
                    }
                    if (size == BackgroundModel.options.limit) {
                        var delta = new Date;
                        delta = delta.getTime() - BackgroundModel.timestamp;
                        if (delta < BackgroundModel.timer) {
                            $(document).oneTime(BackgroundModel.timer - delta, 'background-slideshow-one', function() {
                                BackgroundModel.slideImages();    
                                $(document).everyTime(BackgroundModel.timer, 'background-slideshow', function() {BackgroundModel.slideImages()});
                            });                             
                        }
                        else {
                            BackgroundModel.slideImages();        
                            $(document).everyTime(BackgroundModel.timer, 'background-slideshow', function() {BackgroundModel.slideImages();});                            
                        }
                    }
                    BackgroundModel.loading = false;
                }).attr('src', BackgroundModel.options.host+el);
            }
        } else {
            $(document).stopTime('background-loader');
        }
    },
    slideImages: function() {
        var cimg = $('#'+BackgroundModel.options.box+' img:visible');
        var nimg = $(cimg).next();
        if ($(nimg).size() == 0) {
            nimg = $('#'+BackgroundModel.options.box+' img').eq(0);
        }
        $(cimg).fadeOut(BackgroundModel.time, function() {
            $(nimg).fadeIn(BackgroundModel.time);
        });
    }
}

TextModel = {
    time: 500,
    init: function(image, host, box, bg, text) {
        var img = new Image();
        $(img).load(function() {
        $('#'+box).removeClass('loading').css({opacity: 0, background: 'url("'+$(this).attr('src')+'")'});
            $('#'+box).animate({opacity: 1}, TextModel.time, function() {
                $('#'+bg).animate({opacity: 0.8}, TextModel.time, function() {
                    $('#'+text).fadeIn(TextModel.time, function() {
                        var h = $('#' + text + ' .items').height();
                        if (h > $('#'+text).height()) {
                            $('.up-down').css('visibility', 'visible');
                            // Opacity for IE 7
                            $('#'+text).scrollable({vertical: true, mousewheel: true});
                            $('.up-down a').bind('click', function() {return false; });
                        }
                        $(this).css('opacity', 1);
                    });
                });
            });
        }).attr('src',host+'storage/backgrounds/'+image);
    }
}

/**
 * CoreModel
 * Model for load site content
 */
CoreModel = {
    // Page hash
    hash: '',
    // Footer flag
    footer: false,
    // Request flag
    request: false,
    // Set hash
    initHash: function() {
        CoreModel.hash = CoreModel.cleanHash(document.location.hash);
    },    
    // Check is hash
    checkHash: function() {
        CoreModel.hash = CoreModel.cleanHash(document.location.hash);
        if (CoreModel.hash == '') {
            $(document).stopTimes();
            var path = CoreModel.cleanPath(document.location.pathname);
            document.location.href = document.location.protocol+'//'+document.location.host+'#' + path;
        }
        CoreModel.initHash();
    },
    cleanHash: function(hash) {
        hash = hash.replace('#','');
        var index = hash.substr((hash.length-1), 1);
        if (index == '/') {
            hash = hash.substr(0, hash.length-1);
        }
        return hash;
    },    
    init: function() {
        $('#menu').droppy({speed: 300, align: 'center'});
        $('#space').show();

        CoreModel.initHash();
        CoreModel.initLinks('#content');
    },
    closePageInit: function() {
        $('#space, .l-footer, .l-main-header').show();     
    },
    load: function(hash) {
        if (CoreModel.request == false) {
            CoreModel.request = true;
            var url = '/ajax/' + hash + '/';
            $(document).stopTimes();
            $.ajax({
                url: url,
                type: 'POST',
                cache: true,
                dataType: 'html',
                timeout: 30000,
                data: {_ajax: true},
                headers: {'HTTP_X_REQUESTED_WITH': 'xmlhttprequest'},
                beforeSend: function() {
                    $('#loadcontent').show();
                },
                success: function(html){
                    $('#content').html(html);
                    $('#loadcontent').hide();
                    if (CoreModel.footer == false) {
                        // Init logo link in header
                        CoreModel.initLinks('.b-logo');
                        // Show footer
                        $('.l-footer, .l-main-header').show();
                        CoreModel.footer = true;
                    }
                    CoreModel.request = false;
                },
                complite: function(jqXHR, textStatus) {
                    $('#loadcontent').hide();
                    if (console) {
                        console.log(jqXHR);
                        console.log(textStatus);
                    }
                    CoreModel.request = false;                    
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    $('#loadcontent').hide();
                    if (console) {
                        console.log(jqXHR);
                        console.log(textStatus);
                        console.log(errorThrown);
                    }
                    CoreModel.request = false;
                }
            });
        }
    },
    cleanPath: function(path) {
        var index = path.substr(0, 1);
        if (index == '/') {
            path = path.substr(1,path.length);
        }
        index = path.substr((path.length-1), 1);
        if (index == '/') {
            path = path.substr(0, path.length-1);
        }
        if (path == '' || path == '/') {
            // Without index page - home
            path = 'home';
        }
        return path;
    },
    initLinks: function(box) {
        var host = document.location.protocol+'//'+document.location.host+'/';
        $(box+' a').each(function() {
            var href = $(this).attr('href');
            if (0 == href.indexOf(host)) {
                var hash = href.replace(host, '');
                hash = CoreModel.cleanHash(hash);
                $(this).bind('click', function() {
                    hash = (hash != '') ? hash : 'home';
                    document.location.hash = '#'+hash;
                    CoreModel.load(hash);
                    return false;
                });
            }
        });    
        $('#menu').droppy({speed: 300});
    }
}

