$(function() {
    if (Showbiz === undefined) {
        var Showbiz = {};
    }

	$("a.lightbox").lightbox()

	Showbiz.hots = function(){

        var curIdx = 0;

        var $hotsBlock  = $('.hots_block');
        var $items      = $('.hots_block_items a');
        var $title      = $('.hots_block_current h2 > a');
        var $subtitle   = $('.hots_block_current > a');
        var $links      = $('.hots_block_slides, hots_block_current a');

        var player = function() {
                        var curIdx = 0;
                        var $items = $('.hots_block_slides img');
                        return {
                            showItem : function(idx) {
                                idx = idx - 1;

                                if(curIdx == idx) {
                                    return;
                                }

                                $items.eq(curIdx).css('z-index', 30);
                                $items.eq(idx).css('z-index', 20);
                                $items.eq(curIdx).fadeOut(300, function() {
                                    $(this).css({'z-index': 10,  'opacity': 1, 'display': 'inline'});
                                });

                                curIdx = idx;
                            }
                        }
                    }();

        var itemsCount = $items.size();

        var _go = function(idx){
            $nextItem = $items.eq(idx);

            $title.text($nextItem.data('title'));
            $subtitle.text($nextItem.data('subtitle'));
            $links.attr('href', $nextItem.attr('href'));

            $nextItem.addClass('active').siblings().removeClass('active');
            curIdx = idx;

            if (player) {
                player.showItem(idx + 1);
            }

        };

        return {
            goItem: function(idx){
                if (idx === undefined || idx < 0 || idx >= itemsCount) {
                    idx = 0;
                }
                this.pause();
                _go(idx);
            },
            goNext: function(){
                var nextIdx = curIdx + 1;
                if (nextIdx >= itemsCount) {
                    nextIdx = 0;
                }
                _go(nextIdx);
            },
            start: function(){
                $hotsBlock.everyTime('5s', 'hots', this.goNext);
            },
            pause: function(){
                $hotsBlock.stopTime('hots')
                this.start();
            }
        }
    }();

    $('.hots_block_items a').hover(function(){
        Showbiz.hots.goItem($(this).index());
        return false;
    });

    if($(Showbiz.hots.$hotsBlock).size() > 0) {
        Showbiz.hots.start();
    }

    $(".popular_nav a").click(function() {
        $(".popular_nav a").removeClass('active');
        $(this).addClass('active');
        $('.pages_widget ul').css('z-index', 0).eq($(this).index()).css('z-index', 10);
        return false;
    });

    if($('.article_gallery_slides img').size() > 0) {

        $('.article_gallery_slides').css({
            'height' : $('.article_gallery_slides img:first').height()
        })

        Showbiz.article_gallery = function(){
            var curIdx = 0;
            var $container      = $('.article_gallery_slides');
            var $items          = $('.article_gallery_slides img');
            var $title          = $('.article_gallery_slide_title');
            var $photo_idx      = $('#article_gallery_slide_number');

            var player = function() {
                var curIdx = 0;
                //var $items = $('.article_gallery_slides img');
                return {
                    showItem : function(idx) {
                        idx = idx - 1;

                        if(curIdx == idx) {
                            return;
                        }

                        $items.eq(curIdx).css('z-index', 30);

                        $items.eq(idx).css('z-index', 20);
                        $container.animate({'height' : $items.eq(idx).height() - 1}, 200);

                        $items.eq(curIdx).fadeOut(300, function() {
                            $(this).css({'z-index': 10,  'opacity': 1, 'display': 'inline'});
                        });

                        $title.text($items.eq(idx).attr('title'));

                        curIdx = idx;
                    }
                }
            }();

            var preload = function(idx) {
                for(i = 0; i <= 1; i++) {
                    $nextItem = $items.eq(idx+i);
                    if($nextItem.attr('src') == undefined) {
                        $nextItem.attr('src', $nextItem.data('src'));
                        $nextItem.removeData('src');
                    }
                }
            }

            var itemsCount = $items.size();

            var _go = function(idx){
                $nextItem = $items.eq(idx);
                $title.text($nextItem.data('title'));

                preload(idx)

                curIdx = idx;
                if (player) {
                    player.showItem(idx + 1);
                    $photo_idx.text(idx + 1)
                }
            };

            return {
                goItem: function(idx){
                    if (idx === undefined || idx < 0 || idx >= itemsCount) {
                        idx = 0;
                    }
                    this.pause();
                    _go(idx);
                },
                goPrev: function(){
                    var nextIdx = curIdx - 1;
                    if (nextIdx < 0) {
                        nextIdx = itemsCount;
                    }
                    _go(nextIdx);
                },
                goNext: function(){
                    var nextIdx = curIdx + 1;
                    if (nextIdx >= itemsCount) {
                        nextIdx = 0;
                    }
                    _go(nextIdx);
                },
                start: function(){
                    $hotsBlock.everyTime('5s', 'hots', this.goNext);
                },
                pause: function(){
                    $hotsBlock.stopTime('hots')
                    this.start();
                }
            }
        }();

        $('#article_gallery_prev').click(function(){
            Showbiz.article_gallery.goPrev();
            return false;
        });
        $('#article_gallery_next').click(function(){
            Showbiz.article_gallery.goNext();
            return false;
        });
    }
});


/* Gallery one */

//if(gallery_conf != undefined) {
if(false) {

     $.fn.image = function(src, f){

       return this.each(function(){
        $("<img />").appendTo(this).each(function(){
            this.onload = f;
            this.src = src;

         });
       });
    }

    $(function() {
        var slide = null
        var cur_photo = window.location.href.split(/#/)[1] === undefined ? 1 : window.location.href.split(/#/)[1]
        var count_photos = gallery_conf.count_photos;

        $("#gallery-next").attr("href", "#" + get_next()).click(function() {
            load_img(get_next())
            this.blur()
        })
        $("#gallery-prev").attr("href", "#" + get_prev()).click(function() {
            load_img(get_prev())
            this.blur()
        })

        $("#bigimg").mouseover(function() {
            $("#gallery-prev, #gallery-next").stop().animate({"opacity": "1"}, 700)
        }).mouseout(function() {
            $("#gallery-prev, #gallery-next").stop().animate({"opacity": "0"}, 700)
        })
        $("#gallery-prev, #gallery-next").mouseover(function() {
            $("#gallery-prev, #gallery-next").stop().animate({"opacity": "1"}, 700)
        })

        // play & pause slide show control
        $(".bt1").click(function() {
            if (slide === null) {
                start_slideshow()
            } else {
                stop_slideshow()
            }
            this.blur()
            return false
        })

        function start_slideshow() {
            $(".bt1").css("backgroundPosition", "0 -25px")
            go_next_slide()
            slide = 1
        }

        function stop_slideshow() {
            $(".bt1").css("backgroundPosition", "0 0")
            $().stopTime("slideshow")
            $("#timeout").stop().hide()
            slide = null
        }

        function go_next_slide(intrvl) {
            intrvl = intrvl ? intrvl : 5000

            // чтобы не пропустить ни одного изображения в слайдшоу (из-за нашего "бысторого" интернета) биндим по одному вызову и перебиндовываем ПОСЛЕ загрузки изображения!
            $("#timeout").stop().css("width", "90px").show().animate({
                width: "0px"
            }, intrvl)

            $().oneTime(intrvl, "slideshow", function() {
                load_img(get_next())
            })
        }

        function get_next() {
            return parseInt(cur_photo) + 1  > parseInt(count_photos) ? 1 : parseInt(cur_photo) + 1
        }

        function get_prev() {
            return parseInt(cur_photo) - 1  < 1 ? parseInt(count_photos) : parseInt(cur_photo) - 1
        }

        function load_img(i) {
            if(!gallery_conf.images[i]) return;

            $("#loading").show()

            $("#tempimg").image(gallery_conf.images[i].photo, function(){
                $('#tempimg').fadeIn(700, function() {
                    $("#bigimg img").attr({
                        src: $("img", this).attr("src"),
                        alt: gallery_conf.images[i].text || gallery_conf.title,
                        title: gallery_conf.images[i].text || gallery_conf.title
                    })
                    $(this).hide()
                    $("> img", this).remove()

                    $(".deswin-i h1").html(gallery_conf.images[i].author)
                    $("#gallery_txt").html(gallery_conf.images[i].text)
                    $(".bt2 span:eq(0)").html(cur_photo)
                    $(".bt2 span:eq(1)").html(count_photos)

                    $("#loading").hide()
                    $("#gallery-next").attr("href", "#" + get_next())
                    $("#gallery-prev").attr("href", "#" + get_prev())

                    if (slide !== null) {
                        go_next_slide()
                    }
                })
            })

            cur_photo = gallery_conf.images[i].index
            count_photos = gallery_conf.images[i].count
        }

        load_img(cur_photo)

    })
}

slicedGalleryControl=function(l_sSelf,elem_id,text_elem_id)
{
    if(arguments.length<2)
    {
        throw new Error("Incorrect number of minimum parameters supplied when creating a Sliced Gallery Control.");
    }

    if($(elem_id)==undefined)
    {
        throw new Error("Could not find anything with id="+elem_id+" when creating a Sliced Gallery Control.");
    }

    this.target_elem=elem_id;
    this.target=$("#"+elem_id);
    this.self=l_sSelf;
    this.transitioning=false;
    this.pauseButtonPause=false;
    this.mouseOverPause=false;
    this.current=0;
    this.minWidth=90;
    this.minOpacity=0.5;
    this.maxWidth=300;
    this.steps=15;
    this.stepAmount=(this.maxWidth-this.minWidth)/this.steps;
    this.timeBetweenTransitions=3000;
    this.timeBetweenSteps=40;
    this.lastImageMousedOver=-1;

    var me = this;

    this.init=function()
    {
        $(".slicedImageWrapper",me.target).each(function (i) {
            this.style.width=i==me.current ? me.maxWidth : me.minWidth+'px';
            me.setOpacity(this,i==me.current ? 1 : me.minOpacity);
            var left = i==me.current ? "0px" : (0-(me.maxWidth-me.minWidth)/2) + "px";
            $("img:first",this).css("left",left).bind("mouseover",{i: i},me.userMouseOverSlice);
        });
        $(".sliceWrapper",me.target).bind("mouseover",me.mouseOnGallery).bind("mouseout",me.mouseOffGallery);
    };


    this.setOpacity=function(node,opacity)
    {
        if(node!=undefined && opacity!=undefined)
        {
            node.style.opacity=opacity;
            node.style.MozOpacity=opacity;
            node.style.KhtmlOpacity=opacity;
            node.style.filter="alpha(opacity="+opacity*100+")";
        }
    };


    this.userMouseOverSlice=function(event)
    {
        me.lastImageMousedOver=event.data.i;
        me.mouseOverSlice(event.data.i);
    };


    this.mouseOnGallery=function()
    {
        this.mouseOverPause=true;
    };


    this.mouseOffGallery=function()
    {
        this.mouseOverPause=false;
        this.lastImageMousedOver=-1;
    };


    this.mouseOverSlice=function(thisImageIndex)
    {
        if(me.transitioning==false && thisImageIndex!=me.current)
        {
            me.transitioning=true;
            me.toggleSlice(me.current,thisImageIndex);
        }
    };


    this.toggleSlice=function(reduce,grow)
    {
        var reducing=me.reduceSlice(reduce);
        var growing=me.growSlice(grow);

        if(reducing || growing)
        {
            window.setTimeout(me.self+'.toggleSlice('+reduce+','+grow+')',this.timeBetweenSteps);
        }
        else
        {
            me.current=grow;
            me.showLinkInfo(grow);
            me.transitioning=false;
            if(me.mouseOverPause && me.lastImageMousedOver!=-1 && me.lastImageMousedOver!=me.current)
            {
                me.showNextImage();
            }
        }
    };


    this.showLinkInfo=function(grow) {
        if(grow) {
            grow = $(".slicedImageWrapper", me.target).eq(grow);
            $('.sliced_gallery_titles a').attr('href', $(grow).attr('href')).text($('img', grow).attr('title'));
        }
    };


    this.reduceSlice=function(sliceIndex)
    {
        var divWrappers=$('#'+me.target_elem+' .slicedImageWrapper');
        var divWrapper=divWrappers[sliceIndex];
        var nWidth=parseInt($(divWrapper).css("width"),10);

        if(nWidth>me.minWidth)
        {
            $(divWrapper).css("width",nWidth-me.stepAmount+'px');

            var stepCount=(me.maxWidth-parseInt($(divWrapper).css("width"),10))/me.stepAmount;
            var stepOpacity=((1-me.minOpacity)/me.steps)*stepCount;
            me.setOpacity(divWrapper,1-stepOpacity);

            var left = parseInt($("img:first",$(divWrapper)).css("left"),10)-(me.stepAmount/2)+'px';
            $("img:first",$(divWrapper)).css("left",left);
            return true;
        }
        else
        {
            $(divWrapper).css("width",me.minWidth+'px').removeClass('selected');
            me.setOpacity(divWrapper,me.minOpacity);
            $("img:first",$(divWrapper)).css("left",(0-(me.maxWidth-me.minWidth)/2)+'px');
            return false;
        }
    };


    this.growSlice=function(sliceIndex)
    {
        var divWrappers=$('#'+this.target_elem+' .slicedImageWrapper');
        var divWrapper=divWrappers[sliceIndex];
        var nWidth=parseInt($(divWrapper).css("width"),10);
        if(nWidth<me.maxWidth)
        {
            $(divWrapper).css("width",nWidth+me.stepAmount+'px');

            var stepCount=(parseInt($(divWrapper).css("width"),10)-me.minWidth)/me.stepAmount;
            var stepOpacity=((1-me.minOpacity)/me.steps)*stepCount;
            me.setOpacity(divWrapper,me.minOpacity+stepOpacity);

            var left = parseInt($("img:first",$(divWrapper)).css("left"),10)+(me.stepAmount/2)+'px';
            $("img:first",$(divWrapper)).css("left",left);
            return true;
        }
        else
        {
            $("img:first",$(divWrapper)).css("width",me.maxWidth+'px').addClass('selected');
            me.setOpacity(divWrapper,1);
            $("img:first",$(divWrapper)).css("left","0px");
            return false;
        }
    };


    this.masterTimer=function()
    {
        if(me.transitioning==false)
        {
            if((me.mouseOverPause && me.lastImageMousedOver!=-1)||(me.pauseButtonPause==false && me.mouseOverPause==false))
            {
                me.showNextImage();
            }
        }
        window.setTimeout(me.masterTimer,me.timeBetweenTransitions);
    };


    this.showNextImage=function()
    {
        var next=me.current+1;
        if(me.lastImageMousedOver!=-1) {
            next=me.lastImageMousedOver;
        }
//        me.mouseOverSlice((next)%me.slicedData.length);
        me.mouseOverSlice((next) % $("#" + elem_id + " .slicedImageWrapper").size());
    };

    this.init();
    window.setTimeout(me.masterTimer,me.timeBetweenTransitions);

};
