// Define variables
var remake = 0;
var remake_info = 0;
var black_something = 0;
var to_top_btn = 0;

// Ready
jQuery().ready(function() {
    // Projects Range and Resize
    if ($('#projects').length)
    {
        $(window).resize(function() {
            clearTimeout(remake);
            remake = setTimeout(function() {
                arrange_projects();
            }, 222)
        });
        
        arrange_projects();

        // Hover effect
        $('a:first', $('#projects li')).bind('mouseenter', function() {
            //$('#projects li span').remove();
            
            var dimension = $('img', $(this)).width();
			
            var span = $('span', $(this));
            if (!span.length)
            {
                    $(this).append(' <span>&nbsp;</span>');
                    var span = $('span', $(this));
            }

            span.css({
                width: dimension + 'px',
                height: dimension + 'px',
                'display' : 'block',
                'opacity': 0
            });
            
            // If it is biggest
            var parent = $(this).parent();
            if (parent.hasClass('biggest'))
            {
                var dimension_height = $('img', $(this)).height();
                span.css('height', dimension_height + 'px');
            }
            
            // Stupid IE!!! :(
            span.animate({'opacity': 1, 'filter': ''}, 350);
        }).bind('mouseleave', function() {
            var span = $('span', $(this));

            span.animate({'opacity': 0, 'filter': ''}, 250);
            setTimeout(function() {
                    span.remove();
            }, 250);
			
            //$('#projects li span').hide();
            //$('#projects li span').remove();
        });

        // Set hash things
        var hash = window.location.hash;
        if ($('#filter').length)
        {
            hash = hash.replace('#', '');
            hash = hash.replace('%20', ' ');
            $('#filter ul a').each(function() {
                if ($(this).html() == hash)
                {
                    $(this).click(); // Execute it
                }
            });
        }
    }

    // More info
    if ($("#more_info").length)
    {
        $(window).resize(function() {
            clearTimeout(remake_info);
            remake_info = setTimeout(function() {
                show_more_information();
            }, 222)
        });

        show_more_information();
    }


    // Filter
    if ($('#filter').length)
    {
        var filter = $('#filter');
        var ul = $('ul', filter);

        $('body').bind('click', function(e) {
            $('a:first span', filter).removeClass('opened');
            ul.slideUp('fast');
        });

        $('a:first', filter).bind('click', function(e) {
            var n = $("div").queue("fx");
            if (n.length == 0)
            {
                if (ul.css('display') == 'block')
                {
                    ul.slideUp('fast');
                    $('span', $(this)).removeClass('opened');
                }
                else
                {
                    $('span', $(this)).addClass('opened');
                    ul.slideDown('fast');
                    e.stopPropagation();
                    return false;
                }
            }
        });
        
        $('ul li a', filter).bind('click', function() {
            //$('ul li', filter).removeClass('selected');
            
            //var text = $(this).html();
            //var parent = $(this).parent();
            
            //parent.addClass('selected');

            //$('a:first em', filter).html(text);
            $('a:first span', filter).removeClass('opened');
            ul.slideUp('fast');
        });
    }

    // Go top button
    if ($('#description').length)
    {
        put_scroll_to_top_button();
        
        $(window).resize(function() {
            put_scroll_to_top_button();
        }).scroll(function(){
            put_scroll_to_top_button();
        });
    }

    // Now center the Black thing in right :/
    if ($('.columns .links').length)
    {
        $(window).resize(function() {
            move_black_ball();
        }).scroll(function(){
            move_black_ball();
        });
    }
});

// Function to move the black ball or smth.
function move_black_ball()
{
    var link_check = $('.columns .links');
    var height = link_check.height();
    var parent = link_check.parent();
    var columns_height = parent.height();

    var new_margin_top = 0;

    clearTimeout(black_something);
    if (columns_height > height)
    {
        var scrollTop = $(window).scrollTop();
        if (scrollTop > 210)
        {
            new_margin_top = (scrollTop - 200);
            if ((height + new_margin_top) <= columns_height)
            {
                // What i think about?
            }
            else
            {
                new_margin_top = columns_height - height;
                if (new_margin_top < 0) new_margin_top = 0;
            }
        }
        else
        {
            new_margin_top = 0;
        }

        black_something = setTimeout(function(){
            link_check.animate({'margin-top': new_margin_top+'px'}, 700);
        }, 500);
    }
}

function put_scroll_to_top_button()
{
    clearTimeout(to_top_btn);
    
    var content = $('#content');
    var button = $('#button-gotop');
    if (!button.length)
    {
        content.append('<a href="javascript:;" id="button-gotop">Scroll to top...</a>');
        $('#button-gotop').click(function(){
            $( 'html, body' ).animate( {scrollTop: 0}, 'slow' );
        });
    }
    else
    {
        button.fadeOut();
    }
    
    var description = $('#description');
    var window_height = $(window).height();
    var content_height = content.height();
    var height_from_top = content.position().top;
    
    if (window_height < description.height())
    {
        var scroll_top = $(window).scrollTop();

        var where = scroll_top-height_from_top;
        if (where > 0)
        {
            where = (where + window_height) - 36;

            

            to_top_btn = setTimeout(function(){
                button.css('top', where+'px');
                button.fadeIn();
            }, 500);
        }
    }
}

function arrange_projects()
{
    if ($('#projects').length)
    {
        // Defaults
        effect = false;

        // Set vars
        var projects = $('#projects');
        var projects_width = projects.width();

        if (effect) {projects.css('opacity', 0.4);}
        $('li.empty', projects).remove();

        var box_img_max = 230;
        var box_img_border = 20;
        var box_margin = parseInt($('li', projects).css('margin-right'));
        var box_height = 320;

        var min_boxes = 4;

        var ostatuk = -1;
        var broi = 0;
        var box_img_tmp = box_img_max;

        var if_something_is_wrong = 0;
        var count_elements = $('li.visible', projects).length;
        
        // Calculate size
        if (count_elements >= 1)
        {
            while (ostatuk > broi || ostatuk < 0)
            {
                if_something_is_wrong++;

                if (broi == 0)
                {
                    broi = Math.round((projects_width/(box_img_tmp+box_margin+box_img_border)));
                }

                ostatuk = projects_width - (broi*(box_img_tmp+box_margin+box_img_border) - box_margin);
                if (ostatuk < 0)
                {
                    box_img_tmp = box_img_tmp - 1;
                }
                else if (ostatuk > broi)
                {
                    broi = broi + 1;
                    box_img_tmp = box_img_max;
                }

                if (if_something_is_wrong > 300) return false;
            }
        }
        
        var biggest = $('li.biggest', projects);
        var new_broi = broi -3;
        
        // Create empty boxes
        var empty_template = '<li class="empty visible" style="display: none;"><img src="' + _root + 'web/images/live/bg-empty-project.png" alt="" /></li>';
        var remains = count_elements/broi;
        if (biggest.length)
        {
            if (count_elements < new_broi*2)
            {
                remains = new_broi*2 - count_elements+1;
                while(remains)
                {
                    remains--;
                    projects.append(empty_template);
                }
            }
            else
            {
                remains = (count_elements-new_broi*2-1)/broi;
                if (!isInteger(remains))
                {
                    remains = broi-((count_elements-1-new_broi*2)-(parseInt(remains)*broi));
                    while(remains)
                    {
                        remains--;
                        projects.append(empty_template);
                    }
                }
            }
            
            if (effect)
            {
                $('li.empty', projects).fadeIn(100);
            }
            else
            {
                $('li.empty', projects).css('display', 'block');
            }
        }
        else
        {
            if (!isInteger(remains))
            {
                remains = broi-(count_elements-(parseInt(remains)*broi));
                while(remains)
                {
                    remains--;
                    projects.append(empty_template);
                }

                if (effect)
                {
                    $('li.empty', projects).fadeIn(100);
                }
                else
                {
                    $('li.empty', projects).css('display', 'block');
                }
            }
        }


        // Calculate and set dimensions
        var width = box_img_tmp + box_img_border;
        var height = box_height - (box_img_max - box_img_tmp);
        
        $('li', projects).removeClass('last').css({width: width + 'px', height: height + 'px'} );

        // $('li.visible:nth-child(' + broi + 'n)', projects).addClass('last'); - From Me, but this selector dosnt work
        // Help from Cvetozar Ninov - the master! :P
        $('li.visible', projects).each(function(e) {
            if (e % broi == (broi -1))
            {
                $(this).addClass('last');
            }
        });
        
        $('img', projects).css('width', box_img_tmp);
        $('del', projects).css({width: box_img_tmp + 'px', height: box_img_tmp + 'px'});
        
        // If we have biggest
        //var biggest = $('li.biggest', projects);
        if (biggest.length)
        {
            // Calculate and set dimesions for biggest one
            var big_box_img_tmp = box_img_tmp*3+(4*box_img_border);
            var big_box_img_tmp_height = box_img_tmp*2+(4.5*box_img_border);
            
            var big_width = width*3+2*box_img_border;
            var big_height = height*2;

            biggest.css({width: big_width + 'px', height: big_height + 'px'});
        
            $('li.visible', projects).each(function(e) {
                $(this).removeClass('last');
                //var new_broi = broi -3;
                
                if (e > 0)
                {
                    if (e <= new_broi*2)
                    {
                        var tmp_br = e/new_broi;
                        if (parseInt(tmp_br) == tmp_br)
                        {
                            $(this).addClass('last');
                        }
                    }
                    else
                    {
                        e = e-(new_broi*2)-1;
                        if (e % broi == (broi -1))
                        {
                            $(this).addClass('last');
                        }
                    }
                }
            });
            
            $('img', biggest).css({width: big_box_img_tmp + 'px', height: big_box_img_tmp_height + 'px'});
            $('del', biggest).css({width: big_box_img_tmp + 'px', height: big_box_img_tmp_height + 'px'});
            
            var video_player = $('.video_player', biggest);
            if (video_player.length)
            {
                video_player.remove();
                $('a:first', biggest).show();
               
                //var html = video_player.html();
                //html = html.replace(/width\="\d+"/gi, 'width="' + big_box_img_tmp + '"').replace(/height\="\d+"/gi, 'height="' + big_box_img_tmp_height + '"');
                //video_player.html(html);
                
                // Change player attr
                // $('object, object embed', video_player).attr('width', big_box_img_tmp);
                // $('object, object embed', video_player).attr('height', big_box_img_tmp_height);
            }
        }

        // If have effect
        if (effect) {projects.animate({'opacity': 1}, 100);}
    }
}

function play_video(video_file)
{
    var parent = $('#projects li.biggest.video');
    var remove = $('a:first', parent);
    
    var width = $('img', remove).width();
    var height = $('img', remove).height();
    
    parent.prepend('<div class="video_player"></div>');
    remove.hide();
    var video = $('.video_player', parent);
    video.html('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="' + width + '" height="' + height + '" id="flvPlayer" bgcolor="#000000"><param name="movie" value="' + _root + 'web/files/flvplayer/player_flv.swf" /><param name="FlashVars" value="flv=' + video_file + '&autoplay=1" /><param name="allowFullScreen" value="true" /><embed src="' + _root + 'web/files/flvplayer/player_flv.swf" FlashVars="flv='+ video_file + '&autoplay=1" width="' + width + '" height="' + height + '" allowFullScreen="true" name="flvPlayer" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed></object>');
}

function filter_projects(what)
{
    if ($('#projects').length)
    {
        // Set label
        $('#filter ul li:eq(' + (what)  + ')').each(function() {
            $('#filter ul li').removeClass('selected');
            $(this).addClass('selected');
            var text = $('a', $(this)).html();
            $('#filter a:first em').html(text);

            // Set Hash
            window.location.hash = "#" + text;
        });

        // Projects
        var projects = $('#projects');

        $('li', projects).hide().removeClass('visible').removeClass('visible');

        // Save filter settings
        $.get(_root + "application/xhr", {'method': 'set_filter', 'category' : what});

        if (what == 0)
        {
            $('li', projects).addClass('visible');
            arrange_projects();
        }
        else
        {
            $('li[class~="type_' + what + '"]', projects).addClass('visible');
            arrange_projects();
        }

        $('li.visible, li.empty', projects).show();
    }
}


function filter_type(what)
{
    what = what-1;
    
    // Set label
    $('#filter ul li:eq(' + (what)  + ')').each(function() {
        $('#filter ul li').removeClass('selected');
        $(this).addClass('selected');
        var text = $('a', $(this)).html();
        $('#filter a:first em').html(text);

        $('#filter input[type=hidden]').val(text);
    });
}

// Get news
function get_news(what)
{
    var list = $("#list");
    var current = $('ul.active', list);

    var items = $("ul", list);

    var ind = items.index(current);
    if (ind == 0)
    {
        var prev_item = false;
        var next_item = $("ul:eq(" + (ind+1) + ")", list);
    }
    else
    {
        var prev_item = $("ul:eq(" + (ind-1) + ")", list);
        var next_item = $("ul:eq(" + (ind+1) + ")", list);
    }

    var height = current.height();
    list.css('height', height + 'px');
    $('.navigation a').removeClass('disable');
    if (what == 'prev')
    {
        if (prev_item.length)
        {
            items.removeClass('active');
            
            current.animate({'margin-left' : '20px', 'opacity' : 0}, 300, function() {
                current.hide('fast', function() {
                    prev_item.css({'margin-left': '-20px', 'display' : 'block', 'opacity': 0});
                    var height = prev_item.height();
                    var current_height = current.height();
                    
                    list.animate({'height': height + 'px'}, 400, function(){
                        prev_item.addClass('active');
                        prev_item.animate({'margin-left' : '0', 'opacity' : 1}, 300);
                    });
                });
            });
        }

        var check = $("ul:eq(" + (ind-2) + ")", list);
        if (!check.length)
        {
            $('.navigation .prev').addClass('disable');
        }
    }
    else
    {
        if (next_item.length)
        {
            items.removeClass('active');
            
            current.animate({'margin-left' : '-20px', 'opacity' : 0}, 300, function() {
                current.hide('fast', function() {
                    next_item.css({'margin-left': '20px', 'display' : 'block', 'opacity': 0});
                    var height = next_item.height();
                    var current_height = current.height();
                    
                    list.animate({'height': height + 'px'}, 400, function(){
                        next_item.addClass('active');
                        next_item.animate({'margin-left' : '0', 'opacity' : 1}, 300);
                    });
                });
            });

            // Get more news
            var check = $("ul:eq(" + (ind+2) + ")", list);
            if (!check.length)
            {
                $.get(_root + 'news/get_more_news' , function(data) {
                    list.append(data);

                    var check = $("ul:eq(" + (ind+2) + ")", list);
                    if (!check.length)
                    {
                        $('.navigation .next').addClass('disable');
                    }
                });
            }
        }

        var check = $("ul:eq(" + (ind+2) + ")", list);
        if (!check.length)
        {
            $('.navigation .next').addClass('disable');
        }
    }
}

// More information
function show_more_information()
{
    var more_info = $('#more_info');
    var width = more_info.width();

    if (width > 1200)
    {
        $('ul li', more_info).css({'width': '22%'});
        $('ul li:last', more_info).fadeIn();
    }
    else
    {
        $('ul li', more_info).css({'width': '30%'});
        $('ul li:last', more_info).hide();
    }
}
