(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).innerWidth();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);return $(this).find('> a').is('[rel=ext]');}});$('> 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($){var c=['DOMMouseScroll','mousewheel'];$.event.special.mousewheel={setup:function(){if(this.addEventListener){for(var i=c.length;i;){this.addEventListener(c[--i],handler,false)}}else{this.onmousewheel=handler}},teardown:function(){if(this.removeEventListener){for(var i=c.length;i;){this.removeEventListener(c[--i],handler,false)}}else{this.onmousewheel=null}}};$.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}});function handler(a){var b=a||window.event,args=[].slice.call(arguments,1),delta=0,returnValue=true,deltaX=0,deltaY=0;a=$.event.fix(b);a.type="mousewheel";if(a.wheelDelta){delta=a.wheelDelta/120}if(a.detail){delta=-a.detail/3}deltaY=delta;if(b.axis!==undefined&&b.axis===b.HORIZONTAL_AXIS){deltaY=0;deltaX=-1*delta}if(b.wheelDeltaY!==undefined){deltaY=b.wheelDeltaY/120}if(b.wheelDeltaX!==undefined){deltaX=-1*b.wheelDeltaX/120}args.unshift(a,delta,deltaX,deltaY);return $.event.handle.apply(this,args)}})(jQuery);
(function($){$.jScrollPane={active:[]};$.fn.jScrollPane=function(settings){settings=$.extend({},$.fn.jScrollPane.defaults,settings);var rf=function(){return false};return this.each(function(){var $this=$(this);$this.css('overflow','hidden');var paneEle=this;if($(this).parent().is('.jScrollPaneContainer')){var currentScrollPosition=settings.maintainPosition?$this.offset({relativeTo:$(this).parent()[0]}).top:0;var $c=$(this).parent();var paneWidth=$c.innerWidth();var paneHeight=$c.outerHeight();var trackHeight=paneHeight;$('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown',$c).remove();$this.css({'top':0})}else{var currentScrollPosition=0;this.originalPadding=$this.css('paddingTop')+' '+$this.css('paddingRight')+' '+$this.css('paddingBottom')+' '+$this.css('paddingLeft');this.originalSidePaddingTotal=(parseInt($this.css('paddingLeft'))||0)+(parseInt($this.css('paddingRight'))||0);var paneWidth=$this.innerWidth();var paneHeight=$this.innerHeight();var trackHeight=paneHeight;$this.wrap($('<div></div>').addClass('jScrollPaneContainer').css({'height':paneHeight+'px','width':paneWidth+'px'}));$(document).bind('emchange',function(e,cur,prev){$this.jScrollPane(settings)})}if(settings.reinitialiseOnImageLoad){var $imagesToLoad=$.data(paneEle,'jScrollPaneImagesToLoad')||$('img',$this);var loadedImages=[];if($imagesToLoad.length){$imagesToLoad.each(function(i,val){$(this).bind('load',function(){if($.inArray(i,loadedImages)==-1){loadedImages.push(val);$imagesToLoad=$.grep($imagesToLoad,function(n,i){return n!=val});$.data(paneEle,'jScrollPaneImagesToLoad',$imagesToLoad);settings.reinitialiseOnImageLoad=false;$this.jScrollPane(settings)}}).each(function(i,val){if(this.complete||this.complete===undefined){this.src=this.src}})})}}var p=this.originalSidePaddingTotal;var cssToApply={'height':'auto','width':paneWidth-settings.scrollbarWidth-settings.scrollbarMargin-p+'px'};if(settings.scrollbarOnLeft){cssToApply.paddingLeft=settings.scrollbarMargin+settings.scrollbarWidth+'px'}else{cssToApply.paddingRight=settings.scrollbarMargin+'px'}$this.css(cssToApply);var contentHeight=$this.outerHeight();var percentInView=paneHeight/contentHeight;if(percentInView<.99){var $container=$this.parent();$container.append($('<div></div>').addClass('jScrollPaneTrack').css({'width':settings.scrollbarWidth+'px'}).append($('<div></div>').addClass('jScrollPaneDrag').css({'width':settings.scrollbarWidth+'px'}).append($('<div></div>').addClass('jScrollPaneDragTop').css({'width':settings.scrollbarWidth+'px'}),$('<div></div>').addClass('jScrollPaneDragBottom').css({'width':settings.scrollbarWidth+'px'}))));var $track=$('>.jScrollPaneTrack',$container);var $drag=$('>.jScrollPaneTrack .jScrollPaneDrag',$container);if(settings.showArrows){var currentArrowButton;var currentArrowDirection;var currentArrowInterval;var currentArrowInc;var whileArrowButtonDown=function(){if(currentArrowInc>4||currentArrowInc%4==0){positionDrag(dragPosition+currentArrowDirection*mouseWheelMultiplier)}currentArrowInc++};var onArrowMouseUp=function(event){$('html').unbind('mouseup',onArrowMouseUp);currentArrowButton.removeClass('jScrollActiveArrowButton');clearInterval(currentArrowInterval)};var onArrowMouseDown=function(){$('html').bind('mouseup',onArrowMouseUp);currentArrowButton.addClass('jScrollActiveArrowButton');currentArrowInc=0;whileArrowButtonDown();currentArrowInterval=setInterval(whileArrowButtonDown,100)};$container.append($('<a></a>').attr({'href':'javascript:;','class':'jScrollArrowUp'}).css({'width':settings.scrollbarWidth+'px'}).html('Scroll up').bind('mousedown',function(){currentArrowButton=$(this);currentArrowDirection=-1;onArrowMouseDown();this.blur();return false}).bind('click',rf),$('<a></a>').attr({'href':'javascript:;','class':'jScrollArrowDown'}).css({'width':settings.scrollbarWidth+'px'}).html('Scroll down').bind('mousedown',function(){currentArrowButton=$(this);currentArrowDirection=1;onArrowMouseDown();this.blur();return false}).bind('click',rf));var $upArrow=$('>.jScrollArrowUp',$container);var $downArrow=$('>.jScrollArrowDown',$container);if(settings.arrowSize){trackHeight=paneHeight-settings.arrowSize-settings.arrowSize;$track.css({'height':trackHeight+'px',top:settings.arrowSize+'px'})}else{var topArrowHeight=$upArrow.height();settings.arrowSize=topArrowHeight;trackHeight=paneHeight-topArrowHeight-$downArrow.height();$track.css({'height':trackHeight+'px',top:topArrowHeight+'px'})}}var $pane=$(this).css({'position':'absolute','overflow':'visible'});var currentOffset;var maxY;var mouseWheelMultiplier;var dragPosition=0;var dragMiddle=percentInView*paneHeight/2;var getPos=function(event,c){var p=c=='X'?'Left':'Top';return event['page'+c]||(event['client'+c]+(document.documentElement['scroll'+p]||document.body['scroll'+p]))||0};var ignoreNativeDrag=function(){return false};var initDrag=function(){ceaseAnimation();currentOffset=$drag.offset(false);currentOffset.top-=dragPosition;maxY=trackHeight-$drag[0].offsetHeight;mouseWheelMultiplier=2*settings.wheelSpeed*maxY/contentHeight};var onStartDrag=function(event){initDrag();dragMiddle=getPos(event,'Y')-dragPosition-currentOffset.top;$('html').bind('mouseup',onStopDrag).bind('mousemove',updateScroll);if($.browser.msie){$('html').bind('dragstart',ignoreNativeDrag).bind('selectstart',ignoreNativeDrag)}return false};var onStopDrag=function(){$('html').unbind('mouseup',onStopDrag).unbind('mousemove',updateScroll);dragMiddle=percentInView*paneHeight/2;if($.browser.msie){$('html').unbind('dragstart',ignoreNativeDrag).unbind('selectstart',ignoreNativeDrag)}};var positionDrag=function(destY){destY=destY<0?0:(destY>maxY?maxY:destY);dragPosition=destY;$drag.css({'top':destY+'px'});var p=destY/maxY;$pane.css({'top':((paneHeight-contentHeight)*p)+'px'});$this.trigger('scroll');if(settings.showArrows){$upArrow[destY==0?'addClass':'removeClass']('disabled');$downArrow[destY==maxY?'addClass':'removeClass']('disabled')}};var updateScroll=function(e){positionDrag(getPos(e,'Y')-currentOffset.top-dragMiddle)};var dragH=Math.max(Math.min(percentInView*(paneHeight-settings.arrowSize*2),settings.dragMaxHeight),settings.dragMinHeight);$drag.css({'height':dragH+'px'}).bind('mousedown',onStartDrag);var trackScrollInterval;var trackScrollInc;var trackScrollMousePos;var doTrackScroll=function(){if(trackScrollInc>8||trackScrollInc%4==0){positionDrag((dragPosition-((dragPosition-trackScrollMousePos)/2)))}trackScrollInc++};var onStopTrackClick=function(){clearInterval(trackScrollInterval);$('html').unbind('mouseup',onStopTrackClick).unbind('mousemove',onTrackMouseMove)};var onTrackMouseMove=function(event){trackScrollMousePos=getPos(event,'Y')-currentOffset.top-dragMiddle};var onTrackClick=function(event){initDrag();onTrackMouseMove(event);trackScrollInc=0;$('html').bind('mouseup',onStopTrackClick).bind('mousemove',onTrackMouseMove);trackScrollInterval=setInterval(doTrackScroll,100);doTrackScroll()};$track.bind('mousedown',onTrackClick);$container.bind('mousewheel',function(event,delta){initDrag();ceaseAnimation();var d=dragPosition;positionDrag(dragPosition-delta*mouseWheelMultiplier);var dragOccured=d!=dragPosition;return!dragOccured});var _animateToPosition;var _animateToInterval;function animateToPosition(){var diff=(_animateToPosition-dragPosition)/settings.animateStep;if(diff>1||diff<-1){positionDrag(dragPosition+diff)}else{positionDrag(_animateToPosition);ceaseAnimation()}}var ceaseAnimation=function(){if(_animateToInterval){clearInterval(_animateToInterval);delete _animateToPosition}};var scrollTo=function(pos,preventAni){if(typeof pos=="string"){$e=$(pos,this);if(!$e.length)return;pos=$e.offset().top-$this.offset().top}ceaseAnimation();var destDragPosition=-pos/(paneHeight-contentHeight)*maxY;if(preventAni||!settings.animateTo){positionDrag(destDragPosition)}else{_animateToPosition=destDragPosition;_animateToInterval=setInterval(animateToPosition,settings.animateInterval)}};$this[0].scrollTo=scrollTo;$this[0].scrollBy=function(delta){var currentPos=-parseInt($pane.css('top'))||0;scrollTo(currentPos+delta)};initDrag();scrollTo(-currentScrollPosition,true);$('*',this).bind('focus',function(event){var eleTop=$(this).position().top;var viewportTop=-parseInt($pane.css('top'))||0;var maxVisibleEleTop=viewportTop+paneHeight;var eleInView=eleTop>viewportTop&&eleTop<maxVisibleEleTop;if(!eleInView){$container.scrollTop(0);var destPos=eleTop-settings.scrollbarMargin;if(eleTop>viewportTop){destPos+=$(this).height()+15+settings.scrollbarMargin-paneHeight;}scrollTo(destPos)}});if(location.hash){setTimeout(function(){$(location.hash,$this).trigger('focus')},$.browser.msie?100:0)}$(document).bind('click',function(e){$target=$(e.target);if($target.is('a')){var h=$target.attr('href');if(h.substr(0,1)=='#'){$linkedEle=$(h,$this);if($linkedEle.length){$linkedEle.trigger('focus');return false}}}});$.jScrollPane.active.push($this[0])}else{$this.css({'height':paneHeight+'px','width':paneWidth-this.originalSidePaddingTotal+'px','padding':this.originalPadding})}})};$.fn.jScrollPane.defaults={scrollbarWidth:15,scrollbarMargin:5,wheelSpeed:18,showArrows:false,arrowSize:0,animateTo:false,dragMinHeight:1,dragMaxHeight:99999,animateInterval:100,animateStep:3,maintainPosition:true,scrollbarOnLeft:false,reinitialiseOnImageLoad:false};$(window).bind('unload',function(){var els=$.jScrollPane.active;for(var i=0;i<els.length;i++){els[i].scrollTo=els[i].scrollBy=null}})})(jQuery);
/**
 * Slideshow model
 */
SlideshowModel = {
    queue: [],
    options: {'box':'', 'slider':'', 'host':'', 'play': '', 'step': 0, 'zone': 0, 'cursor': 0, 'cursorRight': false, 'wLeft': 0},
    boxsize: {'w': 0, 'h': 0},
    size: 0,
    current: 0,
    loadnow: -1,
    loaded: -1,
    action: false,
    show: false,
    time: 700,
    timer: 5000,
    counter: 0,
    loading: false,
    biff: 0,
    // Инициализация
    init: function(queue, host, box, slider, c_play) {
        SlideshowModel.options.right = $('#photo-slider-wrapper').width();
        SlideshowModel.options.cursor = parseInt($(window).width() / 2);
        
        SlideshowModel.sliderActions();
        SlideshowModel.photoBoxActions();        
        
        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':CoreModel.options.index+'-'+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':CoreModel.options.index+'-'+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.slider = slider;
        SlideshowModel.options.right = $('#photo-slider-wrapper').width();

        //$('#'+c_play).click(function() {return SlideshowModel.play();});
        $('#playButton').click(function() {return SlideshowModel.start();});
        $('#pauseButton').click(function() {return SlideshowModel.finish();});
        
        
        // Start 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);
                        $(tbox).append($(this));

                        if (el.id == 0) {
                            SlideshowModel.options.right -= parseInt($(this).width());
                            $(tbox).addClass('active');
                        }
                        else {
                            SlideshowModel.options.right -= (3 + parseInt($(this).width()));
                        }
                        // Thumb click event
                        $(tbox).click(function() {
                            var id = parseInt($(this).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);
                        $('#i'+el.id).remove();
                        $('#'+SlideshowModel.options.box).append($(this));

                        /**
                         * Center
                         */
                        if ($(this).width() < SlideshowModel.boxsize.w) {
                            $(this).css('left', parseInt((SlideshowModel.boxsize.w - $(this).width()) / 2)+'px');
                        }
                        if ($(this).height() < SlideshowModel.boxsize.h) {
                            $(this).css('top', parseInt((SlideshowModel.boxsize.h - $(this).height()) / 2)+'px');
                        }

                        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;
            $('#'+SlideshowModel.options.box+' img:visible').fadeOut(SlideshowModel.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) {
        $('#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);
        }
        else {
            SlideshowModel.thumbClick(SlideshowModel.size - 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;
                $('#playButton').addClass('active');
                $('#pauseButton').removeClass('active');
                $(document).everyTime(SlideshowModel.timer, 'slideshow', function() {
                    SlideshowModel.nextImage(false);
                    if (SlideshowModel.current >= SlideshowModel.size) {
                        SlideshowModel.play();
                    }
                });
            }
        } else {
            SlideshowModel.show = false;
            $('#playButton').removeClass('active');
            $('#pauseButton').addClass('active');
            $(document).stopTime('slideshow');
        }
        return false;
    },
    start: function() {
        SlideshowModel.show = false;
        return SlideshowModel.play();
    },
    finish: function() {
        SlideshowModel.show = true
        return SlideshowModel.play();
    },
    sliderActions: function() {
        // First time slide init
        $('#photo-slider').animate({top: '35px'}, 300, function() {
            $('#photo-slider').oneTime(5000, 'sliderHide', function() {
                $('#photo-slider').animate({top: '110px'}, 300);
            });
        });
        // Mouseenter
        $('#photo-slider-wrapper, .l-foot').mouseenter(function () {
            $('#photo-slider').stopTime('sliderHide').oneTime(300, 'sliderShow', function() {
                $('#photo-slider').animate({top: '35px'}, 300);
            });
        });
        // Mouseleave
        $('#photo-slider-wrapper, .l-foot').mouseleave(function () {
            $('#photo-slider').stopTime('sliderShow').oneTime(300, 'sliderHide', function() {
                $('#photo-slider').animate({top: '110px'}, 300);
            });
        });
        // Set zone
        SlideshowModel.options.step = parseInt($('#photo-slider-wrapper').width() / 5);
        SlideshowModel.options.wLeft = $('#photo-slider-wrapper').offset().left;
        
        $('#photo-slider').mousemove(function(e) {
            var position = parseInt((e.pageX - SlideshowModel.options.wLeft) / SlideshowModel.options.step)
            if (position != SlideshowModel.options.zone) {
                SlideshowModel.options.zone = position;
            }
        }).hover(function() {
            SlideshowModel.buff = parseInt($('#photo-slider').css('left').replace('px',''));
            $('#photo-slider').everyTime('10ms', 'slideshow-position', function() {
                var left = SlideshowModel.buff;//parseInt($('#photo-slider').css('left').replace('px',''));
                var step = undefined;
                if (SlideshowModel.options.zone <= 0) {
                    step = left + 2;
                    if (step >= 0) step = 0;
                }
                else if (SlideshowModel.options.zone == 1) {
                    step = left + 1;
                    if (step >= 0) step = 0;
                }
                else if (SlideshowModel.options.zone == 3) {
                    step = left - 1;
                    if (step < SlideshowModel.options.right) {
                        step = SlideshowModel.options.rigth;
                    }
                }
                else if (SlideshowModel.options.zone >= 4) {
                    step = left - 2;
                    if (step < SlideshowModel.options.right) {
                        step = SlideshowModel.options.rigth;
                    }
                }
                if (step != undefined) {
                SlideshowModel.buff = step;
                    $('#photo-slider').css('left', step+'px');
                }
                
            })
        }, function() {
                $('#photo-slider').stopTime('slideshow-position');
        });
    },
    photoBoxActions: function() {
        SlideshowModel.boxsize.w = $('#photo-box').width();
        SlideshowModel.boxsize.h = $('#photo-box').height();
        
        $('#photo-box').mouseenter(function(e){
            if (e.clientX >= SlideshowModel.options.cursor) {
                $(this).removeClass('curr-left').addClass('curr-right');
                SlideshowModel.options.cursorRight = true;
            }
            else {
               $(this).removeClass('curr-right').addClass('curr-left');
               SlideshowModel.options.cursorRight = false;
            }
            return false;
        }).mousemove(function(e){
            if (e.clientX >= SlideshowModel.options.cursor && SlideshowModel.options.cursorRight == false) {
              $(this).removeClass('curr-left').addClass('curr-right');
              SlideshowModel.options.cursorRight = true;
            }
            if (e.clientX < SlideshowModel.options.cursor && SlideshowModel.options.cursorRight == true) {
               $(this).removeClass('curr-right').addClass('curr-left');
               SlideshowModel.options.cursorRight = false;
            }
        }).bind('click', function() {
            if (SlideshowModel.options.cursorRight == true) {
               SlideshowModel.nextImage(true);
            }
            else {
               SlideshowModel.privImage(true);
            }
        });
    }    
}

BackgroundModel = {
    queue: [],
    options: {'box': '', 'host': '', 'limit': 1},
    boxsize: {'w': 0, 'h': 0},
    action: false,
    loading: false,
    time: 700,
    timer: 5000,
    timestamp: 0,
    init: function(queue, host, limit, box, timer) {
        // Init vars
        BackgroundModel.queue = queue;
        BackgroundModel.options.box = box;
        BackgroundModel.options.host = host;
        BackgroundModel.options.limit = limit;
        BackgroundModel.options.timer = timer;
        BackgroundModel.action = false;
        BackgroundModel.loading = false;
        BackgroundModel.boxsize.w = $('#'+BackgroundModel.options.box).width();
        BackgroundModel.boxsize.h = $('#'+BackgroundModel.options.box).height();

        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));
            /**
             * Center
             */
            if ($(this).width() < BackgroundModel.boxsize.w) {
                $(this).css('left', parseInt((BackgroundModel.boxsize.w - $(this).width()) / 2)+'px');
            }
            if ($(this).height() < BackgroundModel.boxsize.h) {
                $(this).css('top', parseInt((BackgroundModel.boxsize.h - $(this).height()) / 2)+'px');
            }
            $(this).fadeIn(BackgroundModel.time);
        }).attr('src', BackgroundModel.options.host+CoreModel.options.index+'-'+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));
                    /**
                     * Center
                     */
                    if ($(this).width() < BackgroundModel.boxsize.w) {
                        $(this).css('left', parseInt((BackgroundModel.boxsize.w - $(this).width()) / 2)+'px');
                    }
                    if ($(this).height() < BackgroundModel.boxsize.h) {
                        $(this).css('top', parseInt((BackgroundModel.boxsize.h - $(this).height()) / 2)+'px');
                    }

                    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+CoreModel.options.index+'-'+el);
            }
        } else {
            $(document).stopTime('background-loader');
        }
    },
    slideImages: function() {
        var cimg = $('#'+BackgroundModel.options.box+' img:visible').addClass('active');
        var nimg = $(cimg).next();
        if ($(nimg).size() == 0) {
            nimg = $('#'+BackgroundModel.options.box+' img').eq(0);
        }
        $(cimg).fadeOut(BackgroundModel.time, function() {
            $(this).removeClass('active');
            $(nimg).fadeIn(BackgroundModel.time);
        });
    }
}

CategoryModel = {
    options: {h1: 0, h2: 0, d: 0},
    queue: [],
    host: '',
    size: [],
    action: false,
    loading: false,
    init: function(queue, host, size) {
        CategoryModel.host = host;
        CategoryModel.size = size;
        CategoryModel.queue = queue;
        /**
         * Link hover
         */
        if (CategoryModel.queue.length > 0) {
            $('.gallery_i').hover(function() {
                $(this).animate({opacity:1}, 400);
            }, function() {
                $(this).animate({opacity:0.75}, 400);
            })
            $(document).everyTime('25ms', 'category-loader', function() {CategoryModel.loadImages()});
        }
    },
    loadImages: function() {
        // If queue not empty
        if (CategoryModel.queue.length > 0) {
            if (CategoryModel.loading == false) {
                // Set loading flag
                CategoryModel.loading = true;
                var el = CategoryModel.queue.shift();
                var img = new Image();
                $(img).bind("load", function() {
                    $(img).attr('width', CategoryModel.size[CoreModel.options.index][0]);
                    $(img).attr('height', CategoryModel.size[CoreModel.options.index][1]);
                    $('#g-'+el.id+' > a').append(img);
                    CategoryModel.loading = false;
                }).attr('src', CategoryModel.host+CoreModel.options.index+'-'+el.file);
            }
        } else {
            $(document).stopTime('category-loader');
        }
    }
}

TextModel = {
    init: function(text, box, image) {
        var img = new Image();
        $(img).load(function() {
            $(text).jScrollPane({scrollbarWidth: 5,dragMaxHeight: 30, showArrows : false, mouseWheelSpeed: 10});
            $(box).css({
                'background':"url('/storage/backgrounds/"+CoreModel.options.index+'-'+image+"') no-repeat 100% 0%"
            });
        }).attr('src','/storage/backgrounds/'+CoreModel.options.index+'-'+image);
    }
}


/**
 * CoreModel
 * Model for load site content
 */
CoreModel = {
    // Page hash
    hash: '',
    // Footer flag
    footer: false,
    // Request flag
    request: false,
    // Set hash
    options: {index: 0, w: 0, h: 0},
    // Timeout
    time: 1000,
    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() {
        CoreModel.initHash();
        CoreModel.initLinks('content');
    
        $('.copy').bind('mouseover', function() {
            $('.copy-text').fadeIn(200);
        });
         $('.copy-box').bind('mouseleave', function() {
            $('.copy-text').fadeOut(200);
        });
    },
    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);
                    $('#loadpage').animate({'opacity': 0}, CoreModel.time, function() { $(this).hide(); });
                    $('#loadcontent').hide();
                    if (CoreModel.footer == false) {
                        $('#footer').removeClass('none');
                        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) {
        $('#menu > li').each(function() {
            var w = $(this).outerWidth(true)+20;
            var u = $(this).find('ul');  
            if (w > u.width()) {
                u.css('width', w);
            }
        });
        
        $('#menu > li[class!=active]').hover(
            function() {$(this).find(' > a').animate({'paddingTop':'8px','paddingBottom':'12px'}, 250).parent().find('> span').animate({'opacity': 1}, 150);},
            function() {$(this).find(' > a').animate({'paddingTop':'12px','paddingBottom':'8px'}, 250).parent().find('> span').animate({'opacity': 0}, 150);;}
        );
       
        var host = document.location.protocol+'//'+document.location.host+'/';
        $('#'+box+' a[rel!=nolink]').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;
                    $('#loadpage').show().animate({'opacity': 1}, CoreModel.time, function() {
                        CoreModel.load(hash);
                    });
                    return false;
                });
            }
        });

        $('#menu').droppy({speed: 300, trigger: 'click'});
    },
    getWindowSize: function() {
        CoreModel.options.w = $(window).width();
        CoreModel.options.h = $(window).height();
    },
    getIndexSize: function(sizes) {
        CoreModel.getWindowSize();
        CoreModel.options.index = 0;
        for (var i = 0; i < sizes.length; i++) {
            if (sizes[i]['w'] <= CoreModel.options.w && sizes[i]['h'] <= CoreModel.options.h) {
                 CoreModel.options.index = i;
            }
        }
        var cls = 'l_750';
        switch (CoreModel.options.index) {
            case 0:cls = 'l_750';break;
            case 1:cls = 'l_1050';break;
            case 2:cls = 'l_1350';break;
        }
        $('body').removeClass('l_750').addClass(cls);
    },
    closePage: function() {
        $('#loadpage').animate({'opacity': 0}, CoreModel.time, function() { $(this).hide(); });
        $('.copy').bind('mouseover', function() {
            $('.copy-text').fadeIn(200);
        });
         $('.copy-box').bind('mouseleave', function() {
            $('.copy-text').fadeOut(200);
        });    
    }
}

