jQuery(document).ready(function()
{
    
    function setGalleryScroll()
    {
        if(jQuery('#scrollableGallery').length == 0)
            return false;
        scrollable = jQuery('#scrollableGallery div.scrollable');
        gallery = jQuery("#scrollableGallery");
        scroller = jQuery('#scrollableGallery > #scrollGallery > div');
    
        scrollableHeight = scrollable.height();
        galleryHeight = parseInt(gallery.css('height').replace('px',""));
        
        maxTop = scrollableHeight-galleryHeight;
        
        if(scrollableHeight > galleryHeight)
        {
            $('#scrollableGallery > #scrollGallery').show()
            scroller.height(galleryHeight*galleryHeight/scrollableHeight);
            maxScrollerTop = galleryHeight-scroller.height();
        }
        else
        {
            $('#scrollableGallery > #scrollGallery').hide();
        }
    }
    
    setGalleryScroll();
    
    $('#scrollableGallery').mouseover(function()
    {
        setGalleryScroll();
    })
    
    jQuery('#scrollableGallery > #scrollGallery > div').draggable({
        containment: "parent",
        axis: "y",
        drag: function(event, ui)
        {
            // get current Top position
            var top = ui.position.top; 
            
            // if top position is greater then max value or lower then 0 stop the function
            if(top > maxTop || top < 0)
            {
                if(top > maxTop)
                    jQuery('#scrollableGallery > #scrollGallery > div').css('top',maxTop);
                else
                    jQuery('#scrollableGallery > #scrollGallery > div').css('top',0);
                    
                return false;
            }
            
            // set fraction to 0 and get current top position
            var fraction = 0;
            var hiddenTop = parseInt(scrollable.position().top);
            
            // calc fraction
            fraction = top/maxScrollerTop;
            
            // set new top position
            scrollable.css('top',fraction*maxTop*(-1));
            
        }
    });
    
    /*$('a[rel=MainGallery]').click(function(){
        $("a[rel=GalleryItem]").addClass('ShowInFancy');
        var index = $("a.ShowInFancy[rel=GalleryItem][href="+$(this).attr('href')+"]").index('"a.ShowInFancy[rel=GalleryItem]');
        $("a.ShowInFancy[rel=GalleryItem]").fancybox({
            'titleShow'		: false,
            'transitionIn'	: 'elastic',
            'transitionOut'	: 'elastic'
        }).eq(index).trigger('click');
        return false;
    });*/
    
    $("a[rel=GalleryItem]").live('click',function(){
        var href = $(this).attr('href');
        var thumbnail= "../showimage.php?src="+href+"&w=180&y=180";
        var link = $('#thumbToFullLink');
        
        $('#divphoto').animate({
            'opacity' : 0,
        },300,function()
        {
            //$('#divphoto').attr('style',"width: 180px; height: 180px; background: url("+thumbnail+") center center no-repeat;").fadeIn(820);
            $('#divphoto').css({"background" : "url("+thumbnail+") center center no-repeat", "opacity" : 1});
            link.attr('href',href);
        });
        
        return false;
    })
    
    $('#thumbToFullLink').live('click',function()
    {
        var link = $(this).attr('href');
        $('#tempGallery').remove();
        $('body').append('<div id="tempGallery" style="display: none; visibility: hidden;"></div>');
        
        var x = 0;
        
        $('a[rel=GalleryItem]').each(function(index){
            if($(this).attr('href') == link)
                x = index;
                
            $('#tempGallery').append('<a href="'+$(this).attr('href')+'" rel="tempGallery"><img src="'+$(this).attr('href')+'" alt="" vspace="0" hspace="0" /></a>');
        })
        
        $('a[rel=tempGallery]').fancybox({
            'titleShow'		: true,
            'titlePosition' : 'over',
            'transitionIn'	: 'elastic',
            'transitionOut'	: 'elastic'
        });
        
        $('a[rel=tempGallery]:eq('+x+')').trigger('click');
        
        
        
        //console.log($('#tempGallery').html())
        
        return false;
    })
    
    jQuery('a.modalnews').live('click',function()
    {
        
        /*
        
            - zamykanie poprzez ESC
            - zamykanie poprzez kliknięcie w tło
        
        */
        
        
        jQuery('.ui-preloader,#modalbg,#modal').remove();
        
        // get publication ID
        var id = jQuery(this).attr('href').split(',');
        id = parseInt(id[1]);
        
        if(id > 0)
        {
            var box = jQuery('#center_float');
            var windowc = jQuery(this).closest('div.windowc');
            var content = jQuery(this).closest('div.windowc_publication');
            var winHeight = jQuery(window).height();
            
            // calc width, height and position
            var width = 576;//windowc.outerWidth()+1;
            width = width*1.5
            var height = winHeight*0.7;
            var left = "50%";//windowc.offset().left-3;
            var marginleft = "-"+width/2+"px";
            var top = (winHeight-height)/2;
            
            //console.log("####");
            //console.log("var width = "+width);
            //console.log("var height = "+height);
            //console.log("var left = "+left)
            //console.log("var top = "+top)
            
            jQuery.ajax({
                url         :   'index.ajax.php?mod=publicationMore&id='+id,
                beforeSend  :   function()
                {
                    content.append('<div class="ui-preloader" style="width: 100%; position:relative; background-position: center center;"></div>');
                },
                complete    : function(msg)
                {
                    jQuery('body').append('<div id="modalbg"></div>');
                    box.prepend('<div id="modal">'+msg.responseText+'</div>');
                    jQuery('#modal').css({
                        'position'      :   'fixed',
                        'width'         :   width,
                        'height'        :   height,
                        'left'          :   left,
                        'top'           :   top,
                        'margin-left'   :   marginleft
                    })
                    jQuery('#modalbg,#modal').fadeIn(500,function(){
                        jQuery('.ui-preloader').remove();
                    });
                    //console.log("windowc.width() = "+windowc.width())
                    jQuery('#modal .windowc_publication').css({
                        'position'  : 'relative',
                        'overflow'  : 'hidden',
                        'width'     : width-20,//windowc.width()-20, // 20 = padding: 10px;
                        'height'    : height-30-jQuery('#modal .windowc_title').outerHeight()-jQuery('#modal .windowc_details').outerHeight() // 30 = windowc_publication margin-top: 10px; windowc_padding padding: 10px;
                    })
                    
                    //console.log("css height = "+(height-30-jQuery('#modal .windowc_title').outerHeight()-jQuery('#modal .windowc_details').outerHeight()))
                    
                    jQuery('#modal .windowc_publication > div:eq(0)').css('position','absolute');
                    
                    // global vars
                    var overflow = jQuery('#modal .windowc_publication'),
                        hidden = jQuery('#modal .windowc_publication > div:eq(0)'),
                        scrollbar = jQuery('#scrollbar'),
                        scroller = jQuery('#scroller');
                        
                    var overflowHeight = parseInt(overflow.height());
                    var hiddenHeight = hidden.height();
                    /*var hiddenHeight = 0;
                    hidden.children().each(function(){
                        hiddenHeight += jQuery(this).outerHeight(true);
                    })*/
                    //console.log('hiddenHeight = '+hiddenHeight)
                    
                    var maxTop = hiddenHeight-overflowHeight;
                    
                    //console.log(maxTop)
                    
                    //console.log("overflow.height() = "+overflow.height())
                    //console.log("overflow.outerHeight() = "+overflow.outerHeight(true))
                    
                    // set scrollBar
                    if(hiddenHeight > overflowHeight)
                    {
                        scroller.height(overflowHeight*overflowHeight/hiddenHeight);
                        
                        // scrollbar global vars
                        var maxScrollerTop = scrollbar.height()-scroller.height();
                        //console.log(scrollbar.height()+' - '+scroller.height())
                        //console.log('first MAXTOP'+maxScrollerTop)
                        
                        function scrollbarModal(fraction)
                        {
                            console.log('f'+fraction)
                            if(!fraction)
                                var fraction = 0;
                            
                            if(fraction < 0)
                                var fraction = 0;
                                
                            var top = 0;
                            
                            // if fraction is greater then 1 or equal just set maximum top position
                            if(fraction >= 1)
                            {
                                top = maxScrollerTop;
                                //console.log('## f'+fraction+' max'+maxScrollerTop+' t'+top);
                            }
                            // if fraction is between 0 and 1 calc top position
                            else if(fraction > 0 && fraction < 1)
                            {
                                top = fraction*maxScrollerTop;
                                //console.log('f'+fraction+' max'+maxScrollerTop+' t'+top);
                            }
                            
                            // set new top position
                            scroller.css('top',top);
                        }
                        
                        function scrollModal(event,delta)
                        {
                            var hiddenTop = parseInt(hidden.position().top);
                            var newTop = 0;
                                                
                            //-180px
                            //console.log('max'+maxTop)
                                                
                            // move down
                            if(delta == 1)
                                newTop = hiddenTop+10;
                            // move top
                            else
                                newTop = hiddenTop-10;
                            
                            // if newTop is greater then 0 stop the function and set scrollbar to the top
                            if(newTop > 0)
                            {
                                scrollbarModal(0);
                                return false;
                            }
                            // if newTop is lower then maxTop stop the function and set scrollbar to the bottom
                            else if(newTop < -maxTop)
                            {
                                scrollbarModal(1);
                                return false;
                            }
                            // cals the fraction
                            else
                                scrollbarModal((newTop/maxTop)*(-1))
                            // set new top position
                            hidden.css('top',newTop);
                        }
                        
                        jQuery( "#scroller" ).draggable({
                            containment: "parent",
                            axis: "y",
                            drag: function(event, ui)
                            {
                                // get current Top position
                                var top = ui.position.top; 
                                
                                // if top position is greater then max value or lower then 0 stop the function
                                if(top > maxTop || top < 0)
                                    return false;
                                
                                // set fraction to 0 and get current top position
                                var fraction = 0;
                                var hiddenTop = parseInt(hidden.position().top);
                                
                                // calc fraction
                                fraction = top/maxScrollerTop;
                                
                                // set new top position
                                hidden.css('top',fraction*maxTop*(-1));
                                
                            }
                        });
                        
                        // mouseWheel event
                        jQuery('#modal .windowc_publication').bind('mousewheel.fb',function(event, delta){
                            scrollModal(event, delta); return false;
                        });
                    }
                    else
                    {
                        jQuery('#scrollbar').remove();
                        
                        jQuery('#modal').css({
                            'height'    :   hiddenHeight+20+jQuery('#modal .windowc_title').height()+jQuery('#modal .windowc_details').height()
                        })
                        
                        jQuery('#modal .windowc_publication').css({
                            'height'    : hiddenHeight
                        })
                    }
                }
            });
        }
        
        return false;
    })
    
    jQuery('#modal span.close, #modalbg').live('click',function()
    {
        jQuery('#modal, #modalbg').fadeOut(300,function(){
            jQuery(this).remove();
        });
    });
    jQuery(document).keydown(function(event){
        if(event.keyCode === 27 && $('#modal').html())
        {
            jQuery('#modal, #modalbg').fadeOut(300,function(){
                jQuery(this).remove();
            });
        }
    })
})
