﻿(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().children('a').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($){$.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);

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,
    mousewheel: false,
    mousewheelTime: 200,
    // Инициализация
    init: function(queue, host, box, slider, index, c_play, c_next, c_priv) {
        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_play).click(function() {return SlideshowModel.play();});
        $('#'+c_priv).click(function() {return SlideshowModel.privImage(true);});
        $('#'+c_next).click(function() {return SlideshowModel.nextImage(true);});
        $('#'+c_next).hover(function(){
            $(this).attr('src', '/images/a-next.png');
        }, function(){
            $(this).attr('src', '/images/next.png');
        });
        $('#'+c_priv).hover(function(){
            $(this).attr('src', '/images/a-priv.png');
        }, function(){
            $(this).attr('src', '/images/priv.png');
        });
        
        /**
         * Add mousewheel for photos slider
         */                 
        $('#'+SlideshowModel.options.slider).mousewheel(function(event, delta) {
            if (SlideshowModel.mousewheel == false) {
                SlideshowModel.mousewheel = true;
                var top = parseInt($('#'+SlideshowModel.options.slider).css('top').replace('px',''));
                top +=  delta * 83;
                if (top <= 0 && top >= (SlideshowModel.size - 6) * (-83)) {
                    $('#'+SlideshowModel.options.slider).animate({top: top+'px'}, SlideshowModel.mousewheelTime, function() {SlideshowModel.mousewheel = false;});
                }
                else {
                    SlideshowModel.mousewheel = false;                    
                }            
            }
        });

        // Strt loader
        $(document).everyTime('25ms', 'slideshow-load-queue', function() {
            SlideshowModel.loadQueue();
        });
    },
    loadQueue: function() {
        // If queue not empty
        if (SlideshowModel.queue.length > 0) {
            if (SlideshowModel.loading == false) {
                // Set loading flag
                SlideshowModel.loading = true;
                var el = SlideshowModel.queue.shift();
                var img = new Image();
                // Element is thumb
                if (el.type == 't') {
                    $(img).bind("load", function() {
                        var tbox = $('#t'+el.id);
                        var abox = $('<a href="#"></a>').append($(this));
                        tbox.find('.img').remove().end().append(abox);
                        if (el.id == 0) {
                            tbox.addClass('active');
                        }
                        // Thumb click event
                        $(abox).click(function() {
                            var id = parseInt($(this).parent().attr('id').replace('t',''));
                            SlideshowModel.thumbClick(id, true);
                            return false;
                        });
                        SlideshowModel.loading = false;
                    }).attr('src', SlideshowModel.options.host+el.src);
                }
                // Element is photo
                else {
                    $(img).bind("load", function() {
                        $(this).css('display','none').attr('id', 'i'+el.id);
                        $('#'+SlideshowModel.options.box).append($(this));
                        if (SlideshowModel.buff != null && el.id == SlideshowModel.buff) {
                            $('#'+SlideshowModel.options.box).removeClass('loading');
                            // Start slideshow
                            if (el.id == 0) {
                                SlideshowModel.play();
                                SlideshowModel.showImage(el.id, false);
                            }
                            else {
                                SlideshowModel.showImage(el.id, true);
                            }
                            SlideshowModel.buff = null;
                        }
                        $('#t'+el.id).addClass('loaded');
                        SlideshowModel.loaded += 1;
                        SlideshowModel.loading = false;
                    }).attr('src', SlideshowModel.options.host+el.src);
                }
            }
        }
        else {
            $(document).stopTime('slideshow-load-queue');
            SlideshowModel.loading = false;
        }
    },
    // Формирование очереди загрузок
    formationQueue: function(index) {
      //  SlideshowModel.loading = true;
        var buff = [];
        var el = null;
        // Make new queue
        for (var i = 0; i < SlideshowModel.queue.length; i++) {
            if (SlideshowModel.queue[i].id != index) {
                buff.push(SlideshowModel.queue[i]);
            }
            else {
                el = SlideshowModel.queue[i];
            }
        }
        // If el == null, it is mean, that image loading or loaded
        if (el != null) {
            buff.splice(0,0,el);
            if (el.type == 'i') {
                SlideshowModel.buff = el.id;
            }
        }
        else {
            // If image loaded, show it
            if ($('#t'+index).is('.loaded')) {
                $('#'+SlideshowModel.options.box).removeClass('loading');
                SlideshowModel.showImage(index, true);
            }
            // Change SlideshowModel.buff, image would show in loadQueue method
            else {
               SlideshowModel.buff = index;
            }
        }
        SlideshowModel.queue = buff;
       // SlideshowModel.loading = false;
    },
    // Обработка клика по фотке
    thumbClick: function(index, manual) {
        var loaded = $('#t'+index).is('.loaded');
        // Фотка еще не загружена
        if (loaded == false) {
            SlideshowModel.action = true;
            $('#'+SlideshowModel.options.box+' img:visible').fadeOut(SlideshowModel.time, function() {
                $('#'+SlideshowModel.options.box).addClass('loading');
                SlideshowModel.activeThumb(index);
                SlideshowModel.formationQueue(index);
            });
        }
        else if (SlideshowModel.action == false && SlideshowModel.current != index) {
            SlideshowModel.action = true;
            $('#'+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');
        if (SlideshowModel.size > 6) {
            var tlimit = ((index - 2) < 0) ? 0 : (index - 2);
            if (SlideshowModel.size <= index + 3) {
                tlimit = SlideshowModel.size - 6;
            }
            $('#'+SlideshowModel.options.slider).animate({top:'-'+tlimit * 83+'px'}, 300);
        }
        SlideshowModel.current = index;
        $('#'+SlideshowModel.options.index).html(parseInt(SlideshowModel.current) + 1);
    },
    // Показываем картинку
    showImage: function(index, manual) {
        $('#i'+index).fadeIn(SlideshowModel.time, function() {
            if (SlideshowModel.show == true && manual == true) {
                SlideshowModel.play();
            }
            SlideshowModel.action = false;
        });
    },
    privImage: function() {
        if (SlideshowModel.current > 0) {
            SlideshowModel.thumbClick(SlideshowModel.current - 1, true);
        }
        return false;
    },
    nextImage: function(manual) {
        if (SlideshowModel.current < SlideshowModel.loaded) {
           SlideshowModel.thumbClick(SlideshowModel.current + 1, manual);
        }
        return false;
    },
    play: function() {
        /**
         * Play
         */
        if (SlideshowModel.show == false) {
            if (SlideshowModel.current < (SlideshowModel.size - 1)) {
                SlideshowModel.show = true;
                $('#'+SlideshowModel.options.play+' a').html('стоп');
                $(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('старт');
            $(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).removeClass('none').jScrollPane({dragMaxHeight: 15, showArrows : true});
                    $('.jScrollPaneContainer').css({opacity: 0}).animate({opacity: 1}, TextModel.time);
                });
            });
        }).attr('src',host+'storage/backgrounds/'+image);
    }
}

VideoModel = {
    q:[],
    size: 0,
    time: 300,
    action: false,
    loading: false,
    options: {'box':'', 'slider':''},
    init: function(box, slider, source) {
        // Init vars
        VideoModel.q = source;
        VideoModel.action = false;
        VideoModel.loading = false;
        VideoModel.size = source.length;
        // Options
        VideoModel.options.box = box;
        VideoModel.options.slider = slider;
        if (VideoModel.q.length >= 1) {
            VideoModel.loadIframe(VideoModel.q[0][1], VideoModel.q[0][3]);
            // Start loader
            $(document).everyTime('25ms', 'video-load-queue', function() {
                VideoModel.loadQueue();
            });
        }
    },
    loadIframe: function(id, src) {
        $('#'+VideoModel.options.box).addClass('loading');
        if (src == 'vimeo') {
            var iframe = '<iframe src="http://player.vimeo.com/video/'+id+'?title=0&amp;byline=0&amp;portrait=0" width="725" height="408" frameborder="0"></iframe>';    
        }
        else {
            var iframe = '<object width="725" height="408"><param name="movie" value="http://www.youtube.com/v/'+id+'?version=3&autohide=1&showinfo=0"></param><param name="allowScriptAccess" value="always"></param><param name="wmode" value="opaque"></param><embed src="http://www.youtube.com/v/'+id+'?version=3&autohide=1&showinfo=0" type="application/x-shockwave-flash" allowscriptaccess="always" width="725" height="408" wmode="opaque"></embed></object>';
        }
        $('#'+VideoModel.options.box).html('').append(iframe);
        $('#'+VideoModel.options.box+' iframe').load(function() {
            $('#'+VideoModel.options.box).removeClass('loading'); 
        });    
    },
    loadQueue: function() {
        if (VideoModel.q.length > 0) {
            if (VideoModel.loading == false) {
                // Set loading flag
                VideoModel.loading = true;
                var el = VideoModel.q.shift();
                var img = new Image();
                $(img).bind("load", function() {
                    var tbox = $('#t'+el[0]);
                    var abox = $('<a href="#" video-id="'+el[1]+'" source="'+el[3]+'"></a>').append($(this));
                    tbox.append(abox).removeClass('loading').addClass('loaded');
                    // Thumb click event
                    $(abox).click(function() {
                        $('#'+VideoModel.options.slider+' .thumb.active').removeClass('active');
                        $(this).parent().addClass('active');                        
                        var id = $(this).attr('video-id');
                        var src = $(this).attr('source');
                        VideoModel.loadIframe(id, src);
                        var id = parseInt($(this).parent().attr('id').replace('t',''));
                        VideoModel.activeThumb(id);                        
                        return false;
                    });
                    if (el[0] == 0) {
                        tbox.addClass('active');
                    }
                    VideoModel.loading = false;
                }).attr('src', el[2]).removeAttr('width').attr('height', 72);
            }
        }
        else {
            $(document).stopTime('video-load-queue');
            VideoModel.loading = false;
        }
    },
    // Движение слайдера и активация привьюшки
    activeThumb: function(index) {
        $('#'+VideoModel.options.slider+' .active').removeClass('active');
        $('#t'+index).addClass('active');
        // Limit
        if (VideoModel.size > 6) {
            var tlimit = ((index - 2) < 0) ? 0 : (index - 2);
            if (VideoModel.size <= index + 3) {
                tlimit = VideoModel.size  - 6;
            }
            // Animate for limit
            $('#'+VideoModel.options.slider).animate({top:'-'+tlimit * 83+'px'}, VideoModel.time);
        }
    }
}

/**
 * CoreModel
 * Model for load site content
 */
CoreModel = {
    // Page hash
    hash: '',
    // Music flag. If you not want music, delete this var.
    music: false,
    // 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'});
        CoreModel.initHash();
        CoreModel.initLinks('content');
        /**
         * Music parts
         * If you not want music, delete code under this comments
         */
        MusicModel.initControl();
        // Check music status, and page hash
        if (CoreModel.music == false && CoreModel.hash != 'start') {
            $('#jplayer').oneTime(1000, 'music-start', function() {
                MusicModel.start();  
            });
            CoreModel.music = true;
        }
    },
    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) {
                        $('#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) {
        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;
                });
            }
        });        
    }
}

MusicModel = {
    tracks: [],
    swf: '',
    storage: '',
    track: 0,
    player: undefined,
    timer: 1000,
    fadetime: 200,
    pause: true,
    init: function(swf, storage, tracks) {
        MusicModel.swf = swf;
        MusicModel.tracks = tracks;
        MusicModel.storage = storage;
        MusicModel.track = 0; 
        MusicModel.player = $("#jquery_jplayer_1");
        MusicModel.control = $("#jp_interface_1");
        // Init player
        $(MusicModel.player).jPlayer({
            ready: function () {
                $(this).jPlayer("setMedia", {mp3: MusicModel.storage + MusicModel.tracks[MusicModel.track]});
            },
            ended: function (event) {
                $(MusicModel.control).find('.jp-next').click();
            },
            swfPath: MusicModel.swf,
            supplied: "mp3"
        });
        // Handler for previous button
        $(MusicModel.control).find('.jp-previous').click(function() {
            if (MusicModel.track - 1 >= 0) {
                MusicModel.track = MusicModel.track - 1;
            }
            else {
                MusicModel.track = MusicModel.tracks.length - 1;
            }
            $(MusicModel.player).jPlayer("setMedia", {mp3: MusicModel.storage + MusicModel.tracks[MusicModel.track]}).jPlayer("play");            
            return false;
        });
        // Handler for next button
        $(MusicModel.control).find('.jp-next').click(function() {
            if (MusicModel.track + 1 < MusicModel.tracks.length) {
                MusicModel.track = MusicModel.track + 1;
            }
            else {
                MusicModel.track = 0;
            }
            $(MusicModel.player).jPlayer("setMedia", {mp3: MusicModel.storage + MusicModel.tracks[MusicModel.track]}).jPlayer("play");
            return false;
        });         
    },
    initControl: function() {
        // Handlers for player on/off ico
        if (MusicModel.pause == false) {
            $('#jplayer-on-off').addClass('off');    
        }
        $('#jplayer-on-off').click(function() {
            if ($(this).is('.off')) {
                $(this).removeClass('off');
                $(MusicModel.player).jPlayer("play");   
                MusicModel.pause = true;
            }
            else {
                $(this).addClass('off');
                $(MusicModel.player).jPlayer("pause");                
                MusicModel.pause = false;
            }
            return false;
        }).hover(
            function() {
                $(MusicModel.control).stopTime('player-hide');
                $(MusicModel.control).fadeIn(MusicModel.fadetime);
            }, 
            function() {
                $(MusicModel.control).oneTime(MusicModel.timer, 'player-hide', function() {
                    $(MusicModel.control).fadeOut(MusicModel.fadetime);    
                });
            }
        );
        // Handler for player controls
        $(MusicModel.control).hover(
            function() {
                $(MusicModel.control).stopTime('player-hide');
            },
            function() {
                $(MusicModel.control).oneTime(MusicModel.timer, 'player-hide', function() {
                    $(MusicModel.control).fadeOut(MusicModel.fadetime);    
                });
            }
        );    
        return true;
    },
    start: function() {
        $(MusicModel.player).jPlayer('play');   
        return true;
    }
}
