(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($,window,undefined){
    $.fn.jScrollPane=function(settings){
        var htmlWidth  = $('html').css('width').replace('px','')-400;
        $('.b-gallery-prew').css('width', htmlWidth+'px');
        //$('.b-gallery-prew').css('border','1px solid green');                
        
        
        function JScrollPane(elem,s){
            var settings,jsp=this,pane,paneWidth,paneHeight,container,contentWidth,contentHeight,percentInViewH,percentInViewV,isScrollableV,isScrollableH,verticalDrag,dragMaxY,verticalDragPosition,horizontalDrag,dragMaxX,horizontalDragPosition,verticalBar,verticalTrack,scrollbarWidth,verticalTrackHeight,verticalDragHeight,arrowUp,arrowDown,horizontalBar,horizontalTrack,horizontalTrackWidth,horizontalDragWidth,arrowLeft,arrowRight,reinitialiseInterval,originalPadding,originalPaddingTotalWidth,previousPaneWidth,wasAtTop=true,wasAtLeft=true,wasAtBottom=false,wasAtRight=false,mwEvent=$.fn.mwheelIntent?'mwheelIntent.jsp':'mousewheel.jsp';
            originalPadding=elem.css('paddingTop')+' '+elem.css('paddingRight')+' '+elem.css('paddingBottom')+' '+elem.css('paddingLeft');
            originalPaddingTotalWidth=(parseInt(elem.css('paddingLeft'))||0)+(parseInt(elem.css('paddingRight'))||0);
            initialise(s);
            function initialise(s){
                var clonedElem,tempWrapper,isMaintainingPositon,lastContentX,lastContentY,hasContainingSpaceChanged;
                settings=s;
                if(pane==undefined){
                    elem.css({
                        'overflow':'hidden',
                        'padding':0
                    });
                    paneWidth=elem.innerWidth()+originalPaddingTotalWidth;
                    paneHeight=elem.innerHeight();
                    elem.width(paneWidth);
                    pane=$('<div class="jspPane" />').wrap($('<div class="jspContainer" />').css({
                        'width':paneWidth+'px',
                        'height':paneHeight+'px'
                    }));
                    elem.wrapInner(pane.parent());
                    container=elem.find('>.jspContainer');
                    pane=container.find('>.jspPane');
                    pane.css('padding',originalPadding)
                }else{
                    elem.css('width','');
                    hasContainingSpaceChanged=elem.outerWidth()+originalPaddingTotalWidth!=paneWidth||elem.outerHeight()!=paneHeight;
                    if(hasContainingSpaceChanged){
                        paneWidth=elem.innerWidth()+originalPaddingTotalWidth;
                        paneHeight=elem.innerHeight();
                        container.css({
                            'width':paneWidth+'px',
                            'height':paneHeight+'px'
                        })
                    }
                    previousPaneWidth=pane.innerWidth();
                    if(!hasContainingSpaceChanged&&pane.outerWidth()==contentWidth&&pane.outerHeight()==contentHeight){
                        if(isScrollableH||isScrollableV){
                            pane.css('width',previousPaneWidth+'px');
                            elem.css('width',(previousPaneWidth+originalPaddingTotalWidth)+'px')
                        }
                        return
                    }
                    pane.css('width','');
                    elem.css('width',(paneWidth)+'px');
                    container.find('>.jspVerticalBar,>.jspHorizontalBar').remove().end()
                }
                clonedElem=pane.clone().css('position','absolute');
                tempWrapper=$('<div style="width:1px; position: relative;" />').append(clonedElem);
                $('body').append(tempWrapper);
                contentWidth=Math.max(pane.outerWidth(),clonedElem.outerWidth());
                tempWrapper.remove();
                contentHeight=pane.outerHeight();
                percentInViewH=contentWidth/paneWidth;
                percentInViewV=contentHeight/paneHeight;
                isScrollableV=percentInViewV>1;
                isScrollableH=percentInViewH>1;
                if(!(isScrollableH||isScrollableV)){
                    elem.removeClass('jspScrollable');
                    pane.css({
                        'top':0,
                        'width':container.width()-originalPaddingTotalWidth
                    });
                    removeMousewheel();
                    removeFocusHandler();
                    removeKeyboardNav();
                    removeClickOnTrack();
                    unhijackInternalLinks()
                }else{
                    elem.addClass('jspScrollable');
                    isMaintainingPositon=settings.maintainPosition&&(verticalDragPosition||horizontalDragPosition);
                    if(isMaintainingPositon){
                        lastContentX=contentPositionX();
                        lastContentY=contentPositionY()
                    }
                    initialiseVerticalScroll();
                    initialiseHorizontalScroll();
                    resizeScrollbars();
                    if(isMaintainingPositon){
                        scrollToX(lastContentX);
                        scrollToY(lastContentY)
                    }
                    initFocusHandler();
                    initMousewheel();
                    if(settings.enableKeyboardNavigation){
                        initKeyboardNav()
                    }
                    if(settings.clickOnTrack){
                        initClickOnTrack()
                    }
                    observeHash();
                    if(settings.hijackInternalLinks){
                        hijackInternalLinks()
                    }
                }
                if(settings.autoReinitialise&&!reinitialiseInterval){
                    reinitialiseInterval=setInterval(function(){
                        initialise(settings)
                    },settings.autoReinitialiseDelay)
                }else if(!settings.autoReinitialise&&reinitialiseInterval){
                    clearInterval(reinitialiseInterval)
                }
                elem.trigger('jsp-initialised',[isScrollableH||isScrollableV])
            }
            function initialiseVerticalScroll(){
                if(isScrollableV){
                    container.append($('<div class="jspVerticalBar" />').append($('<div class="jspCap jspCapTop" />'),$('<div class="jspTrack" />').append($('<div class="jspDrag" />').append($('<div class="jspDragTop" />'),$('<div class="jspDragBottom" />'))),$('<div class="jspCap jspCapBottom" />')));
                    verticalBar=container.find('>.jspVerticalBar');
                    verticalTrack=verticalBar.find('>.jspTrack');
                    verticalDrag=verticalTrack.find('>.jspDrag');
                    if(settings.showArrows){
                        arrowUp=$('<a class="jspArrow jspArrowUp" />').bind('mousedown.jsp',getArrowScroll(0,-1)).bind('click.jsp',nil);
                        arrowDown=$('<a class="jspArrow jspArrowDown" />').bind('mousedown.jsp',getArrowScroll(0,1)).bind('click.jsp',nil);
                        if(settings.arrowScrollOnHover){
                            arrowUp.bind('mouseover.jsp',getArrowScroll(0,-1,arrowUp));
                            arrowDown.bind('mouseover.jsp',getArrowScroll(0,1,arrowDown))
                        }
                        appendArrows(verticalTrack,settings.verticalArrowPositions,arrowUp,arrowDown)
                    }
                    verticalTrackHeight=paneHeight;
                    container.find('>.jspVerticalBar>.jspCap:visible,>.jspVerticalBar>.jspArrow').each(function(){
                        verticalTrackHeight-=$(this).outerHeight()
                    });
                    verticalDrag.hover(function(){
                        verticalDrag.addClass('jspHover')
                    },function(){
                        verticalDrag.removeClass('jspHover')
                    }).bind('mousedown.jsp',function(e){
                        $('html').bind('dragstart.jsp selectstart.jsp',function(){
                            return false
                        });
                        verticalDrag.addClass('jspActive');
                        var startY=e.pageY-verticalDrag.position().top;
                        $('html').bind('mousemove.jsp',function(e){
                            positionDragY(e.pageY-startY,false)
                        }).bind('mouseup.jsp mouseleave.jsp',cancelDrag);
                        return false
                    });
                    sizeVerticalScrollbar()
                }
            }
            function movePane(){
                pane.bind('mousedown.jsp',function(e){
                    $('html').bind('dragstart.jsp selectstart.jsp',function(){
                        return false
                    });
                    horizontalDrag.addClass('jspActive');
                    var coef=(contentWidth-pane.width())/(horizontalTrack.width()-horizontalDrag.width());
                    var startX=horizontalDrag.position().left;
                    var startPaneX=e.pageX;
                    $('html').bind('mousemove.jsp',function(e){
                        if(e.pageX>200&&e.pageX<(pane.width()-200)){
                            posX=startX+(startPaneX-e.pageX)/coef;
                            positionDragX(posX,false)
                        }else{
                            cancelDrag()
                        }
                    }).bind('mouseup.jsp mouseleave.jsp',cancelDrag);
                    return false
                })
            }   
            function sizeVerticalScrollbar(){
                verticalTrack.height(verticalTrackHeight+'px');
                verticalDragPosition=0;
                scrollbarWidth=settings.verticalGutter+verticalTrack.outerWidth();
                pane.width(paneWidth-scrollbarWidth-originalPaddingTotalWidth);
                if(verticalBar.position().left==0){
                    pane.css('margin-left',scrollbarWidth+'px')
                }
            }
            function initialiseHorizontalScroll(){                   
                $('#ctest').click(function(){
                    var galleryItem  = Number(($(this).html()));
                    var e  = $('#photo-box #li'+galleryItem+', #video-box #li'+galleryItem);
                    prevScrollToElement(e, true, true);
                });
    
                $('.scroll-right').hover(function(){
                    var scrollStep = 0;
                    switch($(this).attr('class')){
                        case 'scroll-right 1speed':
                            scrollStep = 3;
                            break;
                        case 'scroll-right 2speed':
                            scrollStep = 5;
                            break;            
                    }
                     
                    $(document).everyTime('1ms', 'mouseoverscrollright', function() { 
                        var x = Number(pane.css('left').replace('px',''));              
                        if (x<0){
                            pane.css('left',x+scrollStep);
                        }else{
                            pane.css('left',0);
                        }                  
                    });
                },function(){            
                    $(document).stopTime('mouseoverscrollright');
                });        
                $('.scroll-left').hover(function(){
                    var scrollStep = 0;
                    switch($(this).attr('class')){
                        case 'scroll-left 1speed':
                            scrollStep = 3;
                            break;
                        case 'scroll-left 2speed':
                            scrollStep = 5;
                            break;            
                    }
                    $(document).everyTime('1ms', 'mouseoverscrollleft', function() {
                        var x = Number(pane.css('left').replace('px',''));
                        var paneWidth = Number(pane.css('width').replace('px',''));
                        if (x>-(contentWidth - paneWidth )){
                            pane.css('left',x-scrollStep);
                        }else{
                    }
                    });
                },function(){      
                    $(document).stopTime('mouseoverscrollleft');
                });
    
                if(isScrollableH){        
                    container.append($('<div class="jspHorizontalBar" />').append($('<div class="jspCap jspCapLeft" />'),$('<div class="jspTrack" />').append($('<div class="jspDrag" />').append($('<div class="jspDragLeft" />'),$('<div class="jspDragRight" />'))),$('<div class="jspCap jspCapRight" />')));
                    horizontalBar=container.find('>.jspHorizontalBar');
                    horizontalTrack=horizontalBar.find('>.jspTrack');
                    horizontalDrag=horizontalTrack.find('>.jspDrag');
                    if(settings.showArrows){
                        arrowLeft=$('<a class="jspArrow jspArrowLeft" />').bind('click.jsp',function(){
                            var coef=(contentWidth-pane.width())/(horizontalTrack.width()-horizontalDrag.width());
                            var start=horizontalDrag.position().left;
                            var def=300/coef;
                            var pos=start-def;
                            if(pos<0){
                                pos=0
                            }
                            positionDragX(pos,true)
                        });
                        arrowRight=$('<a class="jspArrow jspArrowRight" />').bind('click.jsp',function(){
                            var coef=(contentWidth-pane.width())/(horizontalTrack.width()-horizontalDrag.width());
                            var start=horizontalDrag.position().left;
                            var def=320/coef;
                            var pos=start+parseInt(def);
                            if(pos>(horizontalTrack.width()-horizontalDrag.width())){
                                pos=horizontalTrack.width()-horizontalDrag.width()
                            }
                            positionDragX(pos,true)
                        });
                        if(settings.arrowScrollOnHover){
                            arrowLeft.bind('mouseover.jsp',getArrowScroll(-1,0,arrowLeft));
                            arrowRight.bind('mouseover.jsp',getArrowScroll(1,0,arrowRight))
                        }
                        appendArrows(horizontalTrack,settings.horizontalArrowPositions,arrowLeft,arrowRight)
                    }
                    horizontalDrag.hover(function(){
                        horizontalDrag.addClass('jspHover')
                    },function(){
                        horizontalDrag.removeClass('jspHover')
                    }).bind('mousedown.jsp',function(e){
                        $('html').bind('dragstart.jsp selectstart.jsp',function(){
                            return false
                        });
                        horizontalDrag.addClass('jspActive');
                        var startX=e.pageX-horizontalDrag.position().left;
                        $('html').bind('mousemove.jsp',function(e){
                            positionDragX(e.pageX-startX,false)
                        }).bind('mouseup.jsp mouseleave.jsp',cancelDrag);
                        return false
                    });
                    horizontalTrackWidth=container.innerWidth();
                    sizeHorizontalScrollbar();
                    movePane()
                }else{}
            }
            function sizeHorizontalScrollbar(){
                container.find('>.jspHorizontalBar>.jspCap:visible,>.jspHorizontalBar>.jspArrow').each(function(){
                    horizontalTrackWidth-=$(this).outerWidth();
                    horizontalTrackWidth-=$(".l-sidebar").width()
                });
                horizontalTrack.width(horizontalTrackWidth+'px');
                horizontalDragPosition=0
            }
            function resizeScrollbars(){
                if(isScrollableH&&isScrollableV){
                    var horizontalTrackHeight=horizontalTrack.outerHeight(),verticalTrackWidth=verticalTrack.outerWidth();
                    verticalTrackHeight-=horizontalTrackHeight;
                    $(horizontalBar).find('>.jspCap:visible,>.jspArrow').each(function(){
                        horizontalTrackWidth+=$(this).outerWidth()
                    });
                    horizontalTrackWidth-=verticalTrackWidth;
                    paneHeight-=verticalTrackWidth;
                    paneWidth-=horizontalTrackHeight;
                    horizontalTrack.parent().append($('<div class="jspCorner" />').css('width',horizontalTrackHeight+'px'));
                    sizeVerticalScrollbar();
                    sizeHorizontalScrollbar()
                }
                if(isScrollableH){
                    pane.width((container.outerWidth()-originalPaddingTotalWidth)+'px')
                }
                contentHeight=pane.outerHeight();
                percentInViewV=contentHeight/paneHeight;
                if(isScrollableH){
                    horizontalDragWidth=1/percentInViewH*horizontalTrackWidth;
                    if(horizontalDragWidth>settings.horizontalDragMaxWidth){
                        horizontalDragWidth=settings.horizontalDragMaxWidth
                    }
                    else if(horizontalDragWidth<settings.horizontalDragMinWidth){
                        horizontalDragWidth=settings.horizontalDragMinWidth
                    }
                    horizontalDrag.width(horizontalDragWidth+'px');
                    dragMaxX=horizontalTrackWidth-horizontalDragWidth;
                    _positionDragX(horizontalDragPosition)
                }
                if(isScrollableV){
                    verticalDragHeight=1/percentInViewV*verticalTrackHeight;
                    if(verticalDragHeight>settings.verticalDragMaxHeight){
                        verticalDragHeight=settings.verticalDragMaxHeight
                    }else if(verticalDragHeight<settings.verticalDragMinHeight){
                        verticalDragHeight=settings.verticalDragMinHeight
                    }
                    verticalDrag.height(verticalDragHeight+'px');
                    dragMaxY=verticalTrackHeight-verticalDragHeight;
                    _positionDragY(verticalDragPosition)
                }
            }
            function appendArrows(ele,p,a1,a2){
                var p1="before",p2="after",aTemp;
                if(p=="os"){
                    p=/Mac/.test(navigator.platform)?"after":"split"
                }
                if(p==p1){
                    p2=p
                }
                else if(p==p2){
                    p1=p;
                    aTemp=a1;
                    a1=a2;
                    a2=aTemp
                }
                ele[p1](a1)[p2](a2)
            }
            function getArrowScroll(dirX,dirY,ele){
                return function(){
                    arrowScroll(dirX,dirY,this,ele);
                    this.blur();
                    return false
                }
            }
            function arrowScroll(dirX,dirY,arrow,ele){
                arrow=$(arrow).addClass('jspActive');
                var eve,doScroll=function(){
                    if(dirX!=0){
                        positionDragX(horizontalDragPosition+dirX*settings.arrowButtonSpeed,false)
                    }
                    if(dirY!=0){
                        positionDragY(verticalDragPosition+dirY*settings.arrowButtonSpeed,false)
                    }
                },scrollInt=setInterval(doScroll,settings.arrowRepeatFreq);
                doScroll();
                eve=ele==undefined?'mouseup.jsp':'mouseout.jsp';
                ele=ele||$('html');
                ele.bind(eve,function(){
                    arrow.removeClass('jspActive');
                    clearInterval(scrollInt);
                    ele.unbind(eve)
                })
            }
            function initClickOnTrack(){
                removeClickOnTrack();
                if(isScrollableV){
                    verticalTrack.bind('mousedown.jsp',function(e){
                        if(e.originalTarget==undefined||e.originalTarget==e.currentTarget){
                            var clickedTrack=$(this),scrollInt=setInterval(function(){
                                var offset=clickedTrack.offset(),pos=e.pageY-offset.top;
                                if(verticalDragPosition+verticalDragHeight<pos){
                                    positionDragY(verticalDragPosition+settings.trackClickSpeed)
                                }else if(pos<verticalDragPosition){
                                    positionDragY(verticalDragPosition-settings.trackClickSpeed)
                                }else{
                                    cancelClick()
                                }
                            },settings.trackClickRepeatFreq),cancelClick=function(){
                                scrollInt&&clearInterval(scrollInt);
                                scrollInt=null;
                                $(document).unbind('mouseup.jsp',cancelClick)
                            };
                
                            $(document).bind('mouseup.jsp',cancelClick);
                            return false
                        }
                    })
                }
                if(isScrollableH){
                    horizontalTrack.bind('click.jsp',function(e){
                        if(e.originalTarget==undefined||e.originalTarget==e.currentTarget){
                            var offset=$(this).offset();
                            var pos=e.pageX-offset.left;
                            positionDragX(pos-horizontalDragWidth/2,true)
                        }
                    })
                }
            }
            function removeClickOnTrack(){
                horizontalTrack&&horizontalTrack.unbind('mousedown.jsp');
                verticalTrack&&verticalTrack.unbind('mousedown.jsp')
            }
            function cancelDrag(){
                $('html').unbind('dragstart.jsp selectstart.jsp mousemove.jsp mouseup.jsp mouseleave.jsp');
                verticalDrag&&verticalDrag.removeClass('jspActive');
                horizontalDrag&&horizontalDrag.removeClass('jspActive')
            }
            function positionDragY(destY,animate){
                if(!isScrollableV){
                    return
                }
                if(destY<0){
                    destY=0
                }else if(destY>dragMaxY){
                    destY=dragMaxY
                }
                if(animate==undefined){
                    animate=settings.animateScroll
                }
                if(animate){
                    jsp.animate(verticalDrag,'top',destY,_positionDragY)
                }else{
                    verticalDrag.css('top',destY);
                    _positionDragY(destY)
                }
            }
            
            function prevPositionDragY(destY,animate){
                if(!isScrollableV){
                    return
                }
                if(destY<0){
                    destY=0
                }else if(destY>dragMaxY){
                    destY=dragMaxY
                }
                if(animate==undefined){
                    animate=settings.prevAnimateScroll
                }
                if(animate){
                    jsp.prevAnimate(verticalDrag,'top',destY,_positionDragY)
                }else{
                    verticalDrag.css('top',destY);
                    _positionDragY(destY)
                }
            }
            function _positionDragY(destY){
                if(destY==undefined){
                    destY=verticalDrag.position().top
                }
                container.scrollTop(0);
                verticalDragPosition=destY;
                var isAtTop=verticalDragPosition==0,isAtBottom=verticalDragPosition==dragMaxY,percentScrolled=destY/dragMaxY,destTop=-percentScrolled*(contentHeight-paneHeight);
                if(wasAtTop!=isAtTop||wasAtBottom!=isAtBottom){
                    wasAtTop=isAtTop;
                    wasAtBottom=isAtBottom;
                    elem.trigger('jsp-arrow-change',[wasAtTop,wasAtBottom,wasAtLeft,wasAtRight])
                }
                updateVerticalArrows(isAtTop,isAtBottom);
                pane.css('top',destTop);
                elem.trigger('jsp-scroll-y',[-destTop,isAtTop,isAtBottom])
            }
            function positionDragX(destX,animate){                
                if(!isScrollableH){
                    return
                }
                if(destX<0){
                    destX=0
                }else if(destX>dragMaxX){
                    destX=dragMaxX
                }
                if(animate==undefined){
                    animate=settings.animateScroll
                }
                if(animate){
                    jsp.animate(horizontalDrag,'left',destX,_positionDragX)
                }else{                  
                    horizontalDrag.css('left',destX);
                    _positionDragX(destX)
                }
            }
            
            function _positionDragX(destX){    
                if(destX==undefined){
                    destX=horizontalDrag.position().left
                }
                container.scrollTop(0);                            
                horizontalDragPosition=destX;
                var isAtLeft=horizontalDragPosition==0,
                isAtRight=horizontalDragPosition==dragMaxX,                
                percentScrolled=destX/dragMaxX,                
                destLeft=-percentScrolled*(contentWidth-paneWidth);
                
                if(wasAtLeft!=isAtLeft||wasAtRight!=isAtRight){
                    wasAtLeft=isAtLeft;
                    wasAtRight=isAtRight;
                    elem.trigger('jsp-arrow-change',[wasAtTop,wasAtBottom,wasAtLeft,wasAtRight])
                }
                updateHorizontalArrows(isAtLeft,isAtRight);
                pane.css('left',destLeft);                        
                elem.trigger('jsp-scroll-x',[-destLeft,isAtLeft,isAtRight])           
            }
            
            function prevPositionDragX(destX,animate){
                if(!isScrollableH){
                    return
                }
                if(destX<0){
                    destX=0
                }else if(destX>dragMaxX){
                    destX=dragMaxX
                }
                if(animate==undefined){
                    animate=settings.prevAnimateScroll
                }
                if(animate){
                    jsp.prevAnimate(horizontalDrag,'left',destX,_positionDragX)
                }else{            
                    horizontalDrag.css('left',destX);            
                    _positionDragX(destX)
                }
            }       
            function updateVerticalArrows(isAtTop,isAtBottom){
                if(settings.showArrows){
                    arrowUp[isAtTop?'addClass':'removeClass']('jspDisabled');
                    arrowDown[isAtBottom?'addClass':'removeClass']('jspDisabled')
                }
            }
            function updateHorizontalArrows(isAtLeft,isAtRight){
                if(settings.showArrows){
                    arrowLeft[isAtLeft?'addClass':'removeClass']('jspDisabled');
                    arrowRight[isAtRight?'addClass':'removeClass']('jspDisabled')
                }
            }
            function scrollToY(destY,animate){
                var percentScrolled=destY/(contentHeight-paneHeight);
                positionDragY(percentScrolled*dragMaxY,animate)
            }
            function prevScrollToY(destY,animate){
                var percentScrolled=destY/(contentHeight-paneHeight);
                prevPositionDragY(percentScrolled*dragMaxY,animate)
            }
            function scrollToX(destX,animate){
                var percentScrolled=destX/(contentWidth-paneWidth);
                positionDragX(percentScrolled*dragMaxX,animate)
            }
            function prevScrollToX(destX,animate){
                var percentScrolled=destX/(contentWidth-paneWidth);
                prevPositionDragX(percentScrolled*dragMaxX,animate)
            }
            function scrollToElement(ele,stickToTop,animate){
                var e,eleHeight,eleWidth,eleTop=0,eleLeft=0,viewportTop,maxVisibleEleTop,maxVisibleEleLeft,destY,destX;
                try{
                    e=$(ele)
                }catch(err){
                    return
                }
                eleHeight=e.outerHeight();
                eleWidth=e.outerWidth();
                container.scrollTop(0);
                container.scrollLeft(0);
                while(!e.is('.jspPane')){
                    eleTop+=e.position().top;
                    eleLeft+=e.position().left;
                    e=e.offsetParent();
                    if(/^body|html$/i.test(e[0].nodeName)){
                        return
                    }
                }
                viewportTop=contentPositionY();
                maxVisibleEleTop=viewportTop+paneHeight;
                if(eleTop<viewportTop||stickToTop){
                    destY=eleTop-settings.verticalGutter
                }else if(eleTop+eleHeight>maxVisibleEleTop){
                    destY=eleTop-paneHeight+eleHeight+settings.verticalGutter
                }
                if(destY){
                    scrollToY(destY,animate)
                }
                viewportLeft=contentPositionX();
                maxVisibleEleLeft=viewportLeft+paneWidth;
                if(eleLeft<viewportLeft||stickToTop){
                    destX=eleLeft-settings.horizontalGutter
                }
                else if(eleLeft+eleWidth>maxVisibleEleLeft){
                    destX=eleLeft-paneWidth+eleWidth+settings.horizontalGutter
                }
                if(destX){
                    scrollToX(destX,animate)
                }
            }

            function prevScrollToElement(ele,stickToTop,animate){
                var e,eleHeight,eleWidth,eleTop=0,eleLeft=0,viewportTop,maxVisibleEleTop,maxVisibleEleLeft,destY,destX;
                try{
                    e=$(ele)
                }catch(err){
                    return
                }
                eleHeight=e.outerHeight();
                eleWidth=e.outerWidth();
                container.scrollTop(0);
                container.scrollLeft(0);
                while(!e.is('.jspPane')){
                    eleTop+=e.position().top;
                    eleLeft+=e.position().left;
                    e=e.offsetParent();
                    if(/^body|html$/i.test(e[0].nodeName)){
                        return
                    }
                }
                viewportTop=contentPositionY();
                maxVisibleEleTop=viewportTop+paneHeight;
                if(eleTop<viewportTop||stickToTop){
                    destY=eleTop-settings.verticalGutter
                }else if(eleTop+eleHeight>maxVisibleEleTop){
                    destY=eleTop-paneHeight+eleHeight+settings.verticalGutter
                }
                if(destY){
                    prevScrollToY(destY,animate)
                }
                viewportLeft=contentPositionX();
                maxVisibleEleLeft=viewportLeft+paneWidth;
                if(eleLeft<viewportLeft||stickToTop){
                    destX=eleLeft-settings.horizontalGutter
                }
                else if(eleLeft+eleWidth>maxVisibleEleLeft){
                    destX=eleLeft-paneWidth+eleWidth+settings.horizontalGutter
                }
                if(destX){                 
                    //slide right size
                    var slideRightWidth = 197;
                    prevScrollToX(destX - slideRightWidth, animate);
                }
            }
            function contentPositionX(){
                return-pane.position().left
            }
            function contentPositionY(){
                return-pane.position().top
            }
            function initMousewheel(){
                container.unbind(mwEvent).bind(mwEvent,function(event,delta,deltaX,deltaY){
                    var dX=horizontalDragPosition,dY=verticalDragPosition;
                    positionDragX(horizontalDragPosition+deltaX*settings.mouseWheelSpeed*paneWidth/(contentWidth-paneWidth),false);
                    positionDragY(verticalDragPosition-deltaY*settings.mouseWheelSpeed*paneHeight/(contentHeight-paneHeight),false);
                    return dX==horizontalDragPosition&&dY==verticalDragPosition
                })
            }
            function removeMousewheel(){
                container.unbind(mwEvent)
            }
            function nil(){
                return false;
            }
            function initFocusHandler(){
                pane.unbind('focus.jsp').bind('focus.jsp',function(e){
                    if(e.target===pane[0]){
                        return
                    }
                    scrollToElement(e.target,false)
                })
            }
            function removeFocusHandler(){
                pane.unbind('focus.jsp')
            }
            function initKeyboardNav(){
                var pressed,pressedTimer;
                elem.attr('tabindex',0).unbind('keydown.jsp').bind('keydown.jsp',function(e){
                    if(e.target!==elem[0]){
                        return
                    }
                    var dX=horizontalDragPosition,dY=verticalDragPosition,step=pressed?2:16;
                    switch(e.keyCode){
                        case 40:
                            positionDragY(verticalDragPosition+step,false);
                            break;
                        case 38:
                            positionDragY(verticalDragPosition-step,false);
                            break;
                        case 34:case 32:
                            scrollToY(contentPositionY()+Math.max(32,paneHeight)-16);
                            break;
                        case 33:
                            scrollToY(contentPositionY()-paneHeight+16);
                            break;
                        case 35:
                            scrollToY(contentHeight-paneHeight);
                            break;
                        case 36:
                            scrollToY(0);
                            break;
                        case 39:
                            positionDragX(horizontalDragPosition+step,false);
                            break;
                        case 37:
                            positionDragX(horizontalDragPosition-step,false);
                            break
                    }
                    if(!(dX==horizontalDragPosition&&dY==verticalDragPosition)){
                        pressed=true;
                        clearTimeout(pressedTimer);
                        pressedTimer=setTimeout(function(){
                            pressed=false
                        },260);
                        return false
                    }
                });
                if(settings.hideFocus){
                    elem.css('outline','none');
                    if('hideFocus'in container[0]){
                        elem.attr('hideFocus',true)
                    }
                }else{
                    elem.css('outline','');
                    if('hideFocus'in container[0]){
                        elem.attr('hideFocus',false)
                    }
                }
            }
            function removeKeyboardNav(){
                elem.attr('tabindex','-1').removeAttr('tabindex').unbind('keydown.jsp')
            }
            function observeHash(){
                if(location.hash&&location.hash.length>1){
                    var e,retryInt;
                    try{
                        e=$(location.hash)
                    }catch(err){
                        return
                    }
                    if(e.length&&pane.find(e)){
                        if(container.scrollTop()==0){
                            retryInt=setInterval(function(){
                                if(container.scrollTop()>0){
                                    scrollToElement(location.hash,true);
                                    $(document).scrollTop(container.position().top);
                                    clearInterval(retryInt)
                                }
                            },50)
                        }else{
                            scrollToElement(location.hash,true);
                            $(document).scrollTop(container.position().top)
                        }
                    }
                }
            }
            function unhijackInternalLinks(){
                $('a.jspHijack').unbind('click.jsp-hijack').removeClass('jspHijack')
            }
            function hijackInternalLinks(){
                unhijackInternalLinks();
                $('a[href^=#]').addClass('jspHijack').bind('click.jsp-hijack',function(){
                    var uriParts=this.href.split('#'),hash;
                    if(uriParts.length>1){
                        hash=uriParts[1];
                        if(hash.length>0&&pane.find('#'+hash).length>0){
                            scrollToElement('#'+hash,true);
                            return false
                        }
                    }
                })
            }
            $.extend(jsp,{
                reinitialise:function(s){
                    s=$.extend({},s,settings);
                    initialise(s)
                },
                scrollToElement:function(ele,stickToTop,animate){
                    scrollToElement(ele,stickToTop,animate)
                },
                scrollTo:function(destX,destY,animate){
                    scrollToX(destX,animate);
                    scrollToY(destY,animate)
                },
                scrollToX:function(destX,animate){
                    scrollToX(destX,animate)
                },
                scrollToY:function(destY,animate){
                    scrollToY(destY,animate)
                },
                scrollBy:function(deltaX,deltaY,animate){
                    jsp.scrollByX(deltaX,animate);
                    jsp.scrollByY(deltaY,animate)
                },
                scrollByX:function(deltaX,animate){
                    var destX=contentPositionX()+deltaX,percentScrolled=destX/(contentWidth-paneWidth);
                    positionDragX(percentScrolled*dragMaxX,animate)
                },
                scrollByY:function(deltaY,animate){
                    var destY=contentPositionY()+deltaY,percentScrolled=destY/(contentHeight-paneHeight);
                    positionDragY(percentScrolled*dragMaxY,animate)
                },
                animate:function(ele,prop,value,stepCallback){
                    var params={};
        
                    params[prop]=value;
                    ele.animate(params,{
                        'duration':settings.animateDuration,
                        'ease':settings.animateEase,
                        'queue':false,
                        'step':stepCallback
                    })
                },
                prevAnimate:function(ele,prop,value,stepCallback){
                    var params={};
        
                    params[prop]=value;
                    ele.animate(params,{
                        'duration':settings.prevAnimateDuration,
                        'ease':settings.prevAnimateEase,
                        'queue':false,
                        'step':stepCallback
                    })
                },
                getContentPositionX:function(){
                    return contentPositionX()
                },
                getContentPositionY:function(){
                    return contentPositionY()
                },
                getIsScrollableH:function(){
                    return isScrollableH
                },
                getIsScrollableV:function(){
                    return isScrollableV
                },
                getContentPane:function(){
                    return pane
                },
                scrollToBottom:function(animate){
                    positionDragY(dragMaxY,animate)
                },
                hijackInternalLinks:function(){
                    hijackInternalLinks()
                }
            })
        }
        settings=$.extend({},$.fn.jScrollPane.defaults,settings);
        var ret;
        this.each(function(){
            var elem=$(this),jspApi=elem.data('jsp');
            if(jspApi){
                jspApi.reinitialise(settings)
            }else{
                jspApi=new JScrollPane(elem,settings);
                elem.data('jsp',jspApi)
            }
            ret=ret?ret.add(elem):elem
        });
        return ret;
    };

    $.fn.jScrollPane.defaults={
        'showArrows':false,
        'maintainPosition':false,
        'clickOnTrack':true,
        'autoReinitialise':false,
        'autoReinitialiseDelay':0,
        'verticalDragMinHeight':0,
        'verticalDragMaxHeight':99999,
        'horizontalDragMinWidth':0,
        'horizontalDragMaxWidth':99999,
        'animateScroll':false,
        'animateDuration':0,
        'animateEase':'linear',
        'prevAnimateScroll':true,
        'prevAnimateDuration':500,                
        'animateEase':'linear',
        'hijackInternalLinks':false,
        'verticalGutter':4,
        'horizontalGutter':4,
        'mouseWheelSpeed':30,
        'arrowButtonSpeed':30,
        'arrowRepeatFreq':100,
        'arrowScrollOnHover':false,
        'trackClickSpeed':30,
        'trackClickRepeatFreq':100,
        'verticalArrowPositions':'split',
        'horizontalArrowPositions':'split',
        'enableKeyboardNavigation':true,
        'hideFocus':false
    }
    
})(jQuery,this);
function slide(navigation_id,pad_out,pad_in,time,multiplier){
    var list_elements=navigation_id+" li.sliding-element";
    var link_elements=list_elements+" a";
    var timer=0;
    $(list_elements).each(function(i){
        $(this).css("margin-left","-180px");
        timer=(timer*multiplier+time);
        $(this).animate({
            marginLeft:"0"
        },timer);
        $(this).animate({
            marginLeft:"15px"
        },timer);
        $(this).animate({
            marginLeft:"0"
        },timer)
    });
    $(link_elements).each(function(i){
        $(this).hover(function(){
            $(this).animate({
                paddingLeft:pad_out
            },150)
        },function(){
            $(this).animate({
                paddingLeft:pad_in
            },150)
        })
    })
}

SliderModel = {
    queue: [],
    size: 0,
    host: '',
    // Init
    init: function(queue, host, box) {
        SliderModel.queue = [];
        if (queue.length >= 1) {
            // Formation queue
            for (var i = 0; i < queue.length; i++) {        
                SliderModel.queue.push({
                    'id':queue[i][0],
                    'src': queue[i][1], 
                    'photo_w': queue[i][2]
                });
            }
            SliderModel.size = queue.length;
        }
        //рассчитываем ширину блока для слайдера
        var w = 390;
        for(var i = 0; i < SliderModel.size; i++){
            w += parseInt(queue[i][2]);
            w += 10;
        }
        $("#"+box).css('width', w+ 'px');
        //создаем пустые блоки для фото и устанавливаем прелоадеры
        for (var i = 0; i < SliderModel.size; i++){
            var li = $('<li id = "li' + queue[i][0] + '" style="width: ' + queue[i][2] + 'px" class = "loading"></li>');
            $("#"+box+" ul").append(li);
        }
        $("#"+box+" ul").append('<li style="width: 180px"><a href=""></a></li>');
        SliderModel.host = host;
        //отображение слайдера
        $('.l-gallery-i .scroll-pane').jScrollPane(
        {
            showArrows: true,
            horizontalDragMinWidth: 60,
            horizontalDragMaxWidth: 60
        }
        );
        // Загружаем картинки
        $(document).everyTime('25ms', 'slideshow-load-queue', function() {
            SliderModel.load();
        });        
        $('.jspHorizontalBar').css({
            'z-index':-100,
            'opacity':0
        });
    },
    load: function(){
        // If queue not empty
        if (SliderModel.queue.length > 0) {
            var el = SliderModel.queue.shift();
            var img = new Image();
            $(img).bind("load", function() {
                var lbox = $('#li'+el.id);
                lbox.removeClass('loading');
                var abox = $('<a href="#" onclick = "return false"></a>').append($(this));
                lbox.append(abox);
            }).attr('src', SliderModel.host+el.src);

        }
        else {
            $(document).stopTime('slideshow-load-queue');
        }
    }
}

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

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

        $('.photo-left').click(function() {
            return SlideshowModel.left(true);
        });
        $('.photo-right').click(function() {
            return SlideshowModel.right(true);
        });

        // Strt loader
        $(document).everyTime('25ms', 'pslideshow-load-queue', function() {       
            SlideshowModel.loadQueue();
        });
    },
    loadQueue: function() {  
       if (SlideshowModel.previewMarginFixed == false){
            //align pveview list
            var panelWidth = $('.b-gallery-prew').css('width').replace('px','');
            var photoWidth = 45;
            var photoCount = $('.b-gallery-prew div.img').size();                                  
            var htmlWidth  = $('html').css('width').replace('px','');
            var spaceBetweenPhotos = 5;
            var visiblePreviewWidth = (Number(photoCount)*(Number(photoWidth) + Number(spaceBetweenPhotos)))-Number(spaceBetweenPhotos);
            var previewSpace = htmlWidth-Number(400);
            var sliderMargin =  Math.ceil((Number(previewSpace) - Number(visiblePreviewWidth))/2);              
            if (sliderMargin>0){
                $('.photo-prew-list').css('margin-left', (sliderMargin+200)+'px');          
            }            
            SlideshowModel.previewMarginFixed = true;      
        }
                        
        // 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() {
                            /* before manual click on preview, it's must be loaded */
                            if (SlideshowModel.loading){
                                return false;
                            }
                            
                            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('pslideshow-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) {
        if (manual){
            $('#ctest').html(index);            
            $('#ctest').click();
        }
        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');
                if (manual){ 
                    SlideshowModel.activeThumb(index);
                }
                SlideshowModel.formationQueue(index);
            });
        }
        else if (SlideshowModel.action == false && SlideshowModel.current != index) {
            SlideshowModel.action = true;
            if (manual){
                SlideshowModel.activeThumb(index);
            }
           
            $('#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 panelWidth = $('.b-gallery-prew').css('width').replace('px','');
        var panelMiddle = Math.ceil( panelWidth/2);

        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 > panelWidth) {
            // Правый предел
            if (left > (slimit - panelMiddle)) {
                left = slimit - panelWidth;
            }
            // Центр
            else if (left > panelMiddle) {
                left -= panelMiddle;
            }
            // Левый предел
            else {
                left = 0;
            }
            $('#'+SlideshowModel.options.slider).animate({
                left:'-'+left+'px'
            }, {
                queue:false, 
                duration: 300
            });
        }
        SlideshowModel.current = index;
        $('#'+SlideshowModel.options.index).html(parseInt(SlideshowModel.current) + 1);
    },
    // Показываем картинку
    showImage: function(index, manual) {
        $('#i'+index).fadeIn(SlideshowModel.time, function() {
            if (SlideshowModel.show == true && manual == true) {
                SlideshowModel.play();
            } 
            SlideshowModel.action = false;
        });
    },    
    privImage: function() {
        if (SlideshowModel.current > 0) {
            SlideshowModel.thumbClick(SlideshowModel.current - 1, true);
        }
        return false;
    },
    nextImage: function(manual) {
        if (SlideshowModel.current < SlideshowModel.loaded) {
            SlideshowModel.thumbClick(SlideshowModel.current + 1, manual);
        }
        if (SlideshowModel.current == SlideshowModel.size - 1){
            SlideshowModel.thumbClick(0, manual);
        }
        return false;
    },
    left: function() {
        var panelWidth = $('.b-gallery-prew').css('width').replace('px','');
        var panelMiddle = Math.ceil( panelWidth/2);
        
        var left  = parseInt($('#'+SlideshowModel.options.slider).css('left').replace('px',''));
        left = ((left+panelMiddle-50) < 0) ? (left+panelMiddle-50) : 0;
        $('#'+SlideshowModel.options.slider).animate({
            left:left+'px'
        }, {
            queue:false, 
            duration: 300
        });
        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 > panelWidth) {
            slimit -= panelWidth;
            left += panelMiddle-50;
            if (left >= slimit) {
                left = slimit;
            }
            $('#'+SlideshowModel.options.slider).animate({
                left:'-'+left+'px'
            }, {
                queue:false, 
                duration: 300
            });
        }
        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) {
                        SlideshowModel.play();
                    }
                });
            }
        } else {
            SlideshowModel.show = false;
            $('#'+SlideshowModel.options.play+' a').html('Слайдшоу старт');
            $(document).stopTime('slideshow');
        }
        return false;
    }
    
}



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

        VideoSlideshowModel.buff = 0;
        VideoSlideshowModel.options.box = box;
        VideoSlideshowModel.options.host = host;
        VideoSlideshowModel.options.play = c_play;
        VideoSlideshowModel.options.index = index;
        VideoSlideshowModel.options.slider = slider;        

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

        $('.photo-left').click(function() {
            return VideoSlideshowModel.left(true);
        });
        $('.photo-right').click(function() {
            return VideoSlideshowModel.right(true);
        });

        // Strt loader
        $(document).everyTime('25ms', 'pslideshow-load-queue', function() {       
            VideoSlideshowModel.loadQueue();
        });
    },
    loadQueue: function() {        
        if (VideoSlideshowModel.previewMarginFixed == false){
            //align pveview list
            var panelWidth = $('.b-gallery-prew').css('width').replace('px','');
            var photoWidth = 100;
            var photoCount = $('.b-gallery-prew div.img').size();                                  
            var htmlWidth  = $('html').css('width').replace('px','');
            var spaceBetweenPhotos = 10;
            var visiblePreviewWidth = (Number(photoCount)*(Number(photoWidth) + Number(spaceBetweenPhotos)))-Number(spaceBetweenPhotos);
            var previewSpace = htmlWidth-Number(400);
            var sliderMargin =  Math.ceil((Number(previewSpace) - Number(visiblePreviewWidth))/2);
            if (sliderMargin > 0){
                $('.video-prew-list').css('margin-left', (sliderMargin+200)+'px !important');
            }
            VideoSlideshowModel.previewMarginFixed = true;
        }

        // If queue not empty
        if (VideoSlideshowModel.queue.length > 0) {
            if (VideoSlideshowModel.loading == false) {
                // Set loading flag
                
                VideoSlideshowModel.loading = true;
                var el = VideoSlideshowModel.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() {
                            /* before manual click on preview, it's must be loaded */
                            if (VideoSlideshowModel.loading){
                                return false;
                            }
                            
                            var id = parseInt($(this).parent().attr('id').replace('t',''));
                            VideoSlideshowModel.thumbClick(id, true);
                            return false;
                        });
                        VideoSlideshowModel.loading = false;
                    }).attr('src', el.src);                                      
                }
                // Element is photo
                else {                   
                    $(img).bind("load", function() {                        
                        $(this).css('display','none').attr('id', 'i'+el.id);              
                        $('#'+VideoSlideshowModel.options.box).append($(this));
                        if (VideoSlideshowModel.buff != null && el.id == VideoSlideshowModel.buff) {
                            $('#'+VideoSlideshowModel.options.box).removeClass('loading');
                            // Start slideshow
                            if (el.id == 0) {
                                VideoSlideshowModel.play();
                                VideoSlideshowModel.showImage(el.id, false);
                            }
                            else {
                                VideoSlideshowModel.showImage(el.id, true);
                            }
                            VideoSlideshowModel.buff = null;
                        }
                        $('#t'+el.id).addClass('loaded');
                        VideoSlideshowModel.loaded += 1;
                        VideoSlideshowModel.loading = false;
                    }).attr('src', el.src);
                }
            }
        }
        else {            
            $(document).stopTime('pslideshow-load-queue');
            VideoSlideshowModel.loading = false;            
        }
    },
    // Формирование очереди загрузок
    formationQueue: function(index) {
        VideoSlideshowModel.loading = true;
        var buff = [];
        var el = null;
        // Make new queue
        for (var i = 0; i < VideoSlideshowModel.queue.length; i++) {
            if (VideoSlideshowModel.queue[i].id != index) {
                buff.push(VideoSlideshowModel.queue[i]);
            }
            else {
                el = VideoSlideshowModel.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') {
                VideoSlideshowModel.buff = el.id;
            }
        }
        else {
            // If image loaded, show it
            if ($('#t'+index).is('.loaded')) {
                $('#'+VideoSlideshowModel.options.box).removeClass('loading');
                VideoSlideshowModel.showImage(index, true);
            }
            // Change VideoSlideshowModel.buff, image would show in loadQueue method
            else {
                VideoSlideshowModel.buff = index;
            }
        }
        VideoSlideshowModel.queue = buff;
        VideoSlideshowModel.loading = false;
    },
    // Обработка клика по фотке
    thumbClick: function(index, manual) {        
 
        
        if (manual){
            $('#ctest').html(index);
            $('#ctest').click();
        }
        var loaded =$('#t'+index).is('.loaded');
        // Фотка еще не загружена
        if (loaded == false) {
            VideoSlideshowModel.action = true;
         
            $('#'+VideoSlideshowModel.options.box+' img:visible').fadeOut(VideoSlideshowModel.time, function() {
                $('#'+VideoSlideshowModel.options.box).addClass('loading');
                if (manual){ 
                    VideoSlideshowModel.activeThumb(index);
                }
                VideoSlideshowModel.formationQueue(index);
            });
        }
        else if (VideoSlideshowModel.action == false && VideoSlideshowModel.current != index) {
            VideoSlideshowModel.action = true;
            if (manual){
                VideoSlideshowModel.activeThumb(index);
            }
           
            // $('#i'+VideoSlideshowModel.current).fadeOut(VideoSlideshowModel.time, function() {
                // VideoSlideshowModel.activeThumb(index);
                // VideoSlideshowModel.showImage(index, manual);
            // });
            
        }
    },
     // Движение слайдера и активация привьюшки
    activeThumb: function(index) {
        $('#'+VideoSlideshowModel.options.slider+ ' .active').removeClass('active');
        $('#t'+index+' > a').addClass('active');
        
        
        var panelWidth = $('.b-gallery-prew').css('width').replace('px','');
        var panelMiddle = Math.ceil( panelWidth/2);

        var left = 0;
        var slimit = 0;
        
        for (var i = 0; i < VideoSlideshowModel.size; i++) {
            if (i <= index) {
                left += $('#t'+i+' img').width() + 5;
            }
            slimit += $('#t'+i+' img').width() + 5;
        }
        
        if (slimit > panelWidth) {
            // Правый предел
            if (left > (slimit - panelMiddle)) {
                left = slimit - panelWidth;
            }
            // Центр
            else if (left > panelMiddle) {
                left -= panelMiddle;
            }
            // Левый предел
            else {
                left = 0;
            }
            $('#'+VideoSlideshowModel.options.slider).animate({
                left:'-'+left+'px'
            }, {
                queue:false, 
                duration: 300
            });
        }
        VideoSlideshowModel.current = index;
        $('#'+VideoSlideshowModel.options.index).html(parseInt(VideoSlideshowModel.current) + 1);
    },
    // Показываем картинку
    showImage: function(index, manual) {
        // $('#i'+index).fadeIn(VideoSlideshowModel.time, function() {
            // if (VideoSlideshowModel.show == true && manual == true) {
                // VideoSlideshowModel.play();
            // } 
            // VideoSlideshowModel.action = false;
        // });
    },    
    privImage: function() {
        if (VideoSlideshowModel.current > 0) {
            VideoSlideshowModel.thumbClick(VideoSlideshowModel.current - 1, true);
        }
        return false;
    },
    nextImage: function(manual) {
        if (VideoSlideshowModel.current < VideoSlideshowModel.loaded) {
            VideoSlideshowModel.thumbClick(VideoSlideshowModel.current + 1, manual);
        }
        if (VideoSlideshowModel.current == VideoSlideshowModel.size - 1){
            VideoSlideshowModel.thumbClick(0, manual);
        }
        return false;
    },
    left: function() {
        //var panelWidth = $('.b-gallery-prew').css('width').replace('px','');
        //var panelMiddle = Math.ceil( panelWidth/2);
        
        var left  = parseInt($('#'+VideoSlideshowModel.options.slider).css('left').replace('px',''));
        left = ((left+panelMiddle-100) < 0) ? (left+panelMiddle-100) : 0;
        $('#'+VideoSlideshowModel.options.slider).animate({
            left:left+'px'
        }, {
            queue:false, 
            duration: 300
        });
        return false;
    },
    right: function() {
        var left  = Math.abs($('#'+VideoSlideshowModel.options.slider).css('left').replace('px',''));
        var slimit = 0;
        for (var i = 0; i < VideoSlideshowModel.size; i++) {
            slimit += $('#t'+i+' img').width() + 5;
        }
        if (slimit > panelWidth) {
            slimit -= panelWidth;
            left += panelMiddle-100;
            if (left >= slimit) {
                left = slimit;
            }
            $('#'+VideoSlideshowModel.options.slider).animate({
                left:'-'+left+'px'
            }, {
                queue:false, 
                duration: 300
            });
        }
        return false;
    },
    play: function() {
        /**
         * Play
         */
        if (VideoSlideshowModel.show == false) {
            if (VideoSlideshowModel.current <= (VideoSlideshowModel.size - 1)) {
                VideoSlideshowModel.show = true;
                $('#'+VideoSlideshowModel.options.play+' a').html('Слайдшоу стоп');
                $(document).everyTime(VideoSlideshowModel.timer, 'slideshow', function() {
                    VideoSlideshowModel.nextImage(false);
                    if (VideoSlideshowModel.current >= VideoSlideshowModel.size) {
                        VideoSlideshowModel.play();
                    }
                });
            }
        } else {
            VideoSlideshowModel.show = false;
            $('#'+VideoSlideshowModel.options.play+' a').html('Слайдшоу старт');
            $(document).stopTime('slideshow');
        }
        return false;
    }
    
}

BackgroundModel = {
    queue: [],
    options: {
        'box': '', 
        'host': '', 
        'limit': 1
    },
    action: false,
    loading: false,
    time: 800,
    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').css('z-index', '10');
        var nimg = $(cimg).next();
        if ($(nimg).size() == 0) {
            nimg = $('#'+BackgroundModel.options.box+' img').eq(0);
        }
        $(nimg).show(0, function() {
            $(cimg).animate({
                marginLeft : -1000
            }, BackgroundModel.time, function(){
                $(this).hide(0, function(){
                    $(this).css({
                        'z-index':0,
                        'margin-left':0
                    });
                });
            });
        });
    }
}

TextModel = {
    time: 500,
    init: function(image, host, text, photo) {
        $('#'+text).jScrollPane({
            showArrows: true, 
            verticalDragMinHeight: 60, 
            verticalDragMaxHeight: 60
        });
        var img = new Image();
        $(img).load(function() {
            $('#'+photo).removeClass('loading').css('opacity','0').append($(this));
            $('#'+photo).animate({
                opacity: 1
            }, TextModel.time);
        }).attr('src',host+'storage/backgrounds/'+image);
    }
}

VideoModel = {
    queue: [],
    action: false,
    // Init
    init: function(queue, box) {
        VideoModel.queue = queue;
        //рассчитываем ширину блока для слайдера
        var w = parseInt(VideoModel.queue.length*690) + 390;
        
        $("#"+box).css('width', w+ 'px');
        //создаем пустые блоки для фото и устанавливаем прелоадеры
        var li = '';
        for (var i = 0; i < VideoModel.queue.length; i++){
            li = li + '<li id = "li' + VideoModel.queue[i][0] + '" style="width:680px" class = "loading"></li>';
        }
        $("#"+box+" ul").append(li);
        $("#"+box+" ul").append('<li style="width: 180px"><a href=""></a></li>');
        //отображение слайдера
        $('.l-gallery-i .scroll-pane').jScrollPane(
        {
            showArrows: true,
            horizontalDragMinWidth: 60,
            horizontalDragMaxWidth: 60
        }
        );
        // Загружаем картинки
        $(document).everyTime('25ms', 'video-load', function() {
            VideoModel.load();
        });
        $('.jspHorizontalBar').css({
            'z-index':-100,
            'opacity':0
        });
    },
    load: function(){
        // If queue not empty
        if (VideoModel.queue.length > 0) {
            VideoModel.action = true;
            var el = VideoModel.queue.shift();
            if (el[2] == 'youtube') {                
                var iframe = '<iframe class="youtube-player" type="text/html" width="680" height="450" src="http://www.youtube.com/embed/'+el[1]+'?wmode=transparent" frameborder="0"></iframe>';
            }
            else {                
                var iframe = '<iframe src="http://player.vimeo.com/video/'+el[1]+'?title=0&amp;byline=0&amp;portrait=0" width="680" height="450" frameborder="0"></iframe>';    
            }            
            var lbox = $('#li'+el[0]);
            lbox.append(iframe).removeClass('loading');
        }
        if (VideoModel.queue.length == 0) {
            $(document).stopTime('video-load'); 
        }
    }    
}

/**
 * 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() {
        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) {
            $('#jplayer').oneTime(1000, 'music-start', function() {
                MusicModel.start();  
            });
            CoreModel.music = true;
        }
        var maxHeight = $(document).height();
        var myHeight = (maxHeight <= 566) ? 15 : (maxHeight - 566)/2 + 15;
        $('.l-header, .l-footer').height(myHeight);
        $('.l-sidebar, .b-mask').css("top", myHeight + 43+"px");
        
        slide(".nav-gallery ul.nav", 25, 15, 150, .8);
        slide(".nav-info ul.nav", 25, 15, 150, .8);
    },
    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 = 'welcome';
        }
        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;
                })
            }
        }); 
        $('#l-sidebar .b-btn-menu-open').animate({
            "right": "-=42px"
        }, "slow").click(function() {
            $(this).animate({
                "right": "-=42px"
            }, "slow");
            $('#l-sidebar .l-sidebar-i').animate ({
                "right": "+=141px"
            }, "slow");
        });
        $('#l-sidebar .l-sidebar-i').animate ({
            "right": "+=141px"
        }, "slow");
        $('#l-sidebar .b-btn-menu-close').click(function() {
            $('#l-sidebar .b-btn-menu-open').animate({
                "right": "+=42px"
            }, "slow");
            $('#l-sidebar .l-sidebar-i').animate ({
                "right": "-=141px"
            }, "slow");
                
        });
    }
}

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;
    }
}
