(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);
/*
 * jQuery Tools 1.2.5 - The missing UI library for the Web
 */
(function(e){function p(f,c){var b=e(c);return b.length<2?b:f.parent().find(c)}function u(f,c){var b=this,n=f.add(b),g=f.children(),l=0,j=c.vertical;k||(k=b);if(g.length>1)g=e(c.items,f);e.extend(b,{getConf:function(){return c},getIndex:function(){return l},getSize:function(){return b.getItems().size()},getNaviButtons:function(){return o.add(q)},getRoot:function(){return f},getItemWrap:function(){return g},getItems:function(){return g.children(c.item).not("."+c.clonedClass)},move:function(a,d){return b.seekTo(l+
a,d)},next:function(a){return b.move(1,a)},prev:function(a){return b.move(-1,a)},begin:function(a){return b.seekTo(0,a)},end:function(a){return b.seekTo(b.getSize()-1,a)},focus:function(){return k=b},addItem:function(a){a=e(a);if(c.circular){g.children("."+c.clonedClass+":last").before(a);g.children("."+c.clonedClass+":first").replaceWith(a.clone().addClass(c.clonedClass))}else g.append(a);n.trigger("onAddItem",[a]);return b},seekTo:function(a,d,h){a.jquery||(a*=1);if(c.circular&&a===0&&l==-1&&d!==
0)return b;if(!c.circular&&a<0||a>b.getSize()||a<-1)return b;var i=a;if(a.jquery)a=b.getItems().index(a);else i=b.getItems().eq(a);var r=e.Event("onBeforeSeek");if(!h){n.trigger(r,[a,d]);if(r.isDefaultPrevented()||!i.length)return b}i=j?{top:-i.position().top}:{left:-i.position().left};l=a;k=b;if(d===undefined)d=c.speed;g.animate(i,d,c.easing,h||function(){n.trigger("onSeek",[a])});return b}});e.each(["onBeforeSeek","onSeek","onAddItem"],function(a,d){e.isFunction(c[d])&&e(b).bind(d,c[d]);b[d]=function(h){h&&
e(b).bind(d,h);return b}});if(c.circular){var s=b.getItems().slice(-1).clone().prependTo(g),t=b.getItems().eq(1).clone().appendTo(g);s.add(t).addClass(c.clonedClass);b.onBeforeSeek(function(a,d,h){if(!a.isDefaultPrevented())if(d==-1){b.seekTo(s,h,function(){b.end(0)});return a.preventDefault()}else d==b.getSize()&&b.seekTo(t,h,function(){b.begin(0)})});b.seekTo(0,0,function(){})}var o=p(f,c.prev).click(function(){b.prev()}),q=p(f,c.next).click(function(){b.next()});if(!c.circular&&b.getSize()>1){b.onBeforeSeek(function(a,
d){setTimeout(function(){if(!a.isDefaultPrevented()){o.toggleClass(c.disabledClass,d<=0);q.toggleClass(c.disabledClass,d>=b.getSize()-1)}},1)});c.initialIndex||o.addClass(c.disabledClass)}c.mousewheel&&e.fn.mousewheel&&f.mousewheel(function(a,d){if(c.mousewheel){b.move(d<0?1:-1,c.wheelSpeed||50);return false}});if(c.touch){var m={};g[0].ontouchstart=function(a){a=a.touches[0];m.x=a.clientX;m.y=a.clientY};g[0].ontouchmove=function(a){if(a.touches.length==1&&!g.is(":animated")){var d=a.touches[0],h=
m.x-d.clientX;d=m.y-d.clientY;b[j&&d>0||!j&&h>0?"next":"prev"]();a.preventDefault()}}}c.keyboard&&e(document).bind("keydown.scrollable",function(a){if(!(!c.keyboard||a.altKey||a.ctrlKey||e(a.target).is(":input")))if(!(c.keyboard!="static"&&k!=b)){var d=a.keyCode;if(j&&(d==38||d==40)){b.move(d==38?-1:1);return a.preventDefault()}if(!j&&(d==37||d==39)){b.move(d==37?-1:1);return a.preventDefault()}}});c.initialIndex&&b.seekTo(c.initialIndex,0,function(){})}e.tools=e.tools||{version:"1.2.5"};e.tools.scrollable=
{conf:{activeClass:"active",circular:false,clonedClass:"cloned",disabledClass:"disabled",easing:"swing",initialIndex:0,item:null,items:".items",keyboard:true,mousewheel:false,next:".next",prev:".prev",speed:400,vertical:false,touch:true,wheelSpeed:0}};var k;e.fn.scrollable=function(f){var c=this.data("scrollable");if(c)return c;f=e.extend({},e.tools.scrollable.conf,f);this.each(function(){c=new u(e(this),f);e(this).data("scrollable",c)});return f.api?c:this}})(jQuery);
(function(b){var f=b.tools.scrollable;f.autoscroll={conf:{autoplay:true,interval:3E3,autopause:true}};b.fn.autoscroll=function(c){if(typeof c=="number")c={interval:c};var d=b.extend({},f.autoscroll.conf,c),g;this.each(function(){var a=b(this).data("scrollable");if(a)g=a;var e,h=true;a.play=function(){if(!e){h=false;e=setInterval(function(){a.next()},d.interval)}};a.pause=function(){e=clearInterval(e)};a.stop=function(){a.pause();h=true};d.autopause&&a.getRoot().add(a.getNaviButtons()).hover(a.pause,
a.play);d.autoplay&&a.play()});return d.api?g:this}})(jQuery);
(function(d){function p(b,g){var h=d(g);return h.length<2?h:b.parent().find(g)}var m=d.tools.scrollable;m.navigator={conf:{navi:".navi",naviItem:null,activeClass:"active",indexed:false,idPrefix:null,history:false}};d.fn.navigator=function(b){if(typeof b=="string")b={navi:b};b=d.extend({},m.navigator.conf,b);var g;this.each(function(){function h(a,c,i){e.seekTo(c);if(j){if(location.hash)location.hash=a.attr("href").replace("#","")}else return i.preventDefault()}function f(){return k.find(b.naviItem||
"> *")}function n(a){var c=d("<"+(b.naviItem||"a")+"/>").click(function(i){h(d(this),a,i)}).attr("href","#"+a);a===0&&c.addClass(l);b.indexed&&c.text(a+1);b.idPrefix&&c.attr("id",b.idPrefix+a);return c.appendTo(k)}function o(a,c){a=f().eq(c.replace("#",""));a.length||(a=f().filter("[href="+c+"]"));a.click()}var e=d(this).data("scrollable"),k=b.navi.jquery?b.navi:p(e.getRoot(),b.navi),q=e.getNaviButtons(),l=b.activeClass,j=b.history&&d.fn.history;if(e)g=e;e.getNaviButtons=function(){return q.add(k)};
f().length?f().each(function(a){d(this).click(function(c){h(d(this),a,c)})}):d.each(e.getItems(),function(a){n(a)});e.onBeforeSeek(function(a,c){setTimeout(function(){if(!a.isDefaultPrevented()){var i=f().eq(c);!a.isDefaultPrevented()&&i.length&&f().removeClass(l).eq(c).addClass(l)}},1)});e.onAddItem(function(a,c){c=n(e.getItems().index(c));j&&c.history(o)});j&&f().history(o)});return b.api?g:this}})(jQuery);


SlideshowModel = {
    queue: [],
    options: {'box':'', 'slider':'', 'host':'', 'play': '', 'index': ''},
    size: 0,
    current: 0,
    loadnow: -1,
    loaded: -1,
    action: false,
    show: false,
    time: 500,
    timer: 5000,
    counter: 0,
    loading: false,
    mousewheel: false,
    mousewheelTime: 300,
    whalf: 0,
    // Инициализация
    init: function(queue, host, box, slider, 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.slider = slider;
        SlideshowModel.whalf = parseInt($(window).width() / 2);
        SlideshowModel.setCustomCursor();

        $('#'+c_play).click(function() {return SlideshowModel.play();});
        $('#'+c_priv).click(function() {return SlideshowModel.up();});
        $('#'+c_next).click(function() {return SlideshowModel.down();});

        /**
         * Add mousewheel for photos slider
         */
        $('#'+SlideshowModel.options.slider)
        .bind('mousewheel', function(event, delta) {
            if (SlideshowModel.mousewheel == false) {
                SlideshowModel.mousewheel = true;
                var top = parseInt($('#'+SlideshowModel.options.slider).css('top').replace('px',''));
                top +=  delta * 48;
                if (top <= 0 && top >= (SlideshowModel.size - 10) * (-48)) {
                    $('#'+SlideshowModel.options.slider).animate({top: top+'px'}, SlideshowModel.mousewheelTime, function() {SlideshowModel.mousewheel = false;});
            SlideshowModel.show = false;
            $('#'+SlideshowModel.options.play).html('старт слайдшоу');
            $(document).stopTime('slideshow');
                }
                else {
                    SlideshowModel.mousewheel = false;
                }
            }
            return 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 > 10) {
            var tlimit = ((index - 4) < 0) ? 0 : (index - 4);
            if (SlideshowModel.size <= index + 5) {
                tlimit = SlideshowModel.size - 10;
            }
            $('#'+SlideshowModel.options.slider).animate({top:'-'+tlimit * 48+'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;
    },
    up: function() {
        var top  = Math.abs($('#'+SlideshowModel.options.slider).css('top').replace('px',''));
        var height = $('#'+SlideshowModel.options.slider).height();
        if (top > 0) {
            top = (top < 480) ? 0 : top - 480;
            $('#'+SlideshowModel.options.slider).animate({top:'-'+top+'px'}, 300);
        }
        return false;
    },
    down: function() {
        var top  = Math.abs($('#'+SlideshowModel.options.slider).css('top').replace('px',''));
        var height = $('#'+SlideshowModel.options.slider).height();
        var def = height - top - 480;
        if (top >= 0) {
            top = (def < 480) ? top + def : top + 480;
            $('#'+SlideshowModel.options.slider).animate({top:'-'+top+'px'}, 300);
        }
        return false;
    },
    play: function() {
        /**
         * Play
         */
        if (SlideshowModel.show == false) {
            if (SlideshowModel.current < (SlideshowModel.size - 1)) {
                SlideshowModel.show = true;
                $('#'+SlideshowModel.options.play).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).html('старт слайдшоу');
            $(document).stopTime('slideshow');
        }
        return false;
    },

   setCustomCursor: function(box) {
        var pic_box = $('#'+SlideshowModel.options.box).offset();
        var mouse_check_y = pic_box.top+ $('#'+SlideshowModel.options.box+'-t').height();
        var mouse_check_x = pic_box.left+($('#'+SlideshowModel.options.box+'-t').width()/2);
        $('#'+SlideshowModel.options.box).mouseenter(function(e){
            if (e.clientX >= mouse_check_x) {
                $(this).removeClass('left-cursor').addClass('right-cursor');
                SlideshowModel.right = true;
            }
            else {
               $(this).removeClass('right-cursor').addClass('left-cursor');
               SlideshowModel.right = false;
            }

            return false;
        }).mousemove(function(e){
            if (e.clientX >= mouse_check_x) {
              $(this).removeClass('left-cursor').removeClass('default-cursor').addClass('right-cursor');
              SlideshowModel.right = true;
            }
            if (e.clientX < mouse_check_x) {
               $(this).removeClass('right-cursor').removeClass('default-cursor').addClass('left-cursor');
               SlideshowModel.right = false;
            }
            if(e.clientX>(mouse_check_x+400)){
            	 $(this).removeClass('right-cursor').removeClass('left-cursor').addClass('default-cursor');
            	 }
            if(e.clientY>(mouse_check_y-150)){
            	 $(this).removeClass('right-cursor').removeClass('left-cursor').addClass('default-cursor');
            	 }
        }).bind('click', function() {
            if (SlideshowModel.right == true) {
               SlideshowModel.nextImage(true);
            }
            else {
               SlideshowModel.privImage(true);
            }
        });
    }
}

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, bg, text) {
        var img = new Image();
        $(img).load(function() {
        $('#'+bg).removeClass('loading').css('opacity','0').css('background','url("'+$(this).attr('src')+'")');
            $('#'+text).removeClass('none');
            var h = $('#' + text +' .items').height();
            if (h > $('#'+text).height()){
                $('.arrows').css('visibility', 'visible');
                $('#'+text).scrollable({vertical: true, mousewheel: true});
            }
            $('#'+bg).animate({opacity: 1}, 700);
        });
        $(img).attr('src',host+'storage/backgrounds/'+image);
        $('.no-click').click(function(){return false;});
    }
}

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="854" height="475" frameborder="0"></iframe>';
        }
        else {
            var iframe = '<iframe class="youtube-player" type="text/html" width="854" height="475" src="http://www.youtube.com/embed/'+id+'?wmode=transparent" frameborder="0"></iframe>';
        }
        $('#'+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;
                    $(this).removeAttr('height').removeAttr('width').attr('width', 144);
                    if ($(this).height() > 75) {
                        var delta = parseInt((75 - $(this).height()) / 2);
                        $(this).css('top', delta+'px');
                    }

                }).attr('src', el[2]);
            }
        }
        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 - 3) < 0) ? 0 : (index - 3);
            if (VideoModel.size <= index + 3) {
                tlimit = VideoModel.size  - 6;
            }
            // Animate for limit
            $('#'+VideoModel.options.slider).animate({left:'-'+tlimit * 151+'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() {
        CoreModel.initHash();
        CoreModel.initLinks('content');
        /**
         * Menu parts
         */
        $('#menu .top li.submenu > a').click(function(e) {
            var obj = $(this).parent().find('> ul');
            if ($(obj).is(':visible') == false) {
                var uls = $('#menu .top li.submenu ul:visible');
                $(uls).slideUp(300, 'linear');
                $(obj).slideDown(300, 'linear');
            }
            else {
                $(obj).slideUp(300, 'linear');
            }
            return false;
        });

        /**
         * 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 != 'home') {
      	  if (CoreModel.music == false) {
            $('#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 = (hash == '#') ? '#' : CoreModel.cleanHash(hash);
                $(this).bind('click', function() {
                    if (hash != '#') {
                        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;
    }
}
