﻿// Global variable to be assigned to later
var projLink = 0;

// When the DOM is loaded and ready
$(function()
{
    // Element to attach hidden span to for text resize detection
    TextResizeDetector.TARGET_ELEMENT_ID = 'outer';
    // Event listener for text resize
    TextResizeDetector.USER_INIT_FUNC = textResizeInit;

    // Highlight the currently selected project on the sidebar menu
    $('ul#projects > li').each(
        function(index)
        {
            var liID = $(this).attr('id')
            if ($('body[class$=' + liID + ']').length != 0)
            {
                $(this).addClass('current');
            }
        }
    );
    
    // Remove default scrollbars from projects list and add custom nav
    $('div#projects-list-wrapper')
        .css('overflow', 'hidden')
        .append('<div class="scrollUp"></div>')
        .append('<div class="scrollBar"></div>')
        .append('<div class="scrollDown"></div>');
        
    // List vars
    var listViewPort = 0;
    var listOffset = 0;
    var listMaxScroll = 0;
    var currListOffset = 0;
    
    // scrollBar vars
    var scrollBarPlane = 0;
    var scrollBarHeight = 0;
    var scrollBarInitialTop = 0;
    var scrollBarMaxMove = 0;
    var scrollBarOffset = 0;
    var currScrollOffset = 0;
    var scrollRatio = 0;
        
    listScrollInit();
            
    function onScrollDrag()
    {
        var currScrollOffset = $('div.scrollBar').position().top - scrollBarInitialTop;
        var scrollRatio = (scrollBarMaxMove - currScrollOffset) / scrollBarMaxMove;
        scrollRatio--;
        scrollRatio = -scrollRatio;
        var newListOffset = ($('ul#projects').height() - listViewPort) * scrollRatio;
        var newListPos = -newListOffset;
        $('ul#projects').css('top', newListPos);
    }
    
    function startScrollUp()
    {
        // Change cursor to hand
        $(this).css('cursor', 'pointer');
        
        // Wrap the project list in a jQuery object
        var projList = $('ul#projects');
        
        // every 65ms, run this function
        projList.everyTime(65, function()
	    {
	        // If the project list is not at the topmost position
            if (projList.position().top < 0)
            {
                var currListOffset = projList.position().top;
                var newListPos = currListOffset + 10;
                $(this).animate(
                    {top: newListPos},
                    50,
                    'linear'
                );
                
                // Move the scrollBar
                var listMaxScroll = projList.height() - listViewPort;
                var scrollRatio = (listMaxScroll + newListPos) / listMaxScroll;
                scrollRatio--;
                scrollRatio = -scrollRatio;
                var newScrollOffset = scrollBarMaxMove * scrollRatio;
                var newScrollPos = scrollBarInitialTop + newScrollOffset;
                
                $('div.scrollBar').animate(
                    {top: newScrollPos},
                    50,
                    'linear'
                );
            }
        }, 0);
    }
    
    function startScrollDown()
    {
        $(this).css('cursor', 'pointer');
        
        var projList = $('ul#projects');
        var maxHeight = projList.height() - $(this).parent().parent().height() + 20;
        
        projList.everyTime(65, function()
	    {
            if (projList.position().top > -(maxHeight))
            {
                // Move the list
                var currListOffset = projList.position().top;
                var newListPos = currListOffset - 10;
                $(this).animate(
                    {top: newListPos},
                    50,
                    'linear'
                );
                
                // Move the scrollBar
                var listMaxScroll = projList.height() - listViewPort;
                var scrollRatio = (listMaxScroll + newListPos) / listMaxScroll;
                scrollRatio--;
                scrollRatio = -scrollRatio;
                var newScrollOffset = scrollBarMaxMove * scrollRatio;
                var newScrollPos = scrollBarInitialTop + newScrollOffset;
                
                $('div.scrollBar').animate(
                    {top: newScrollPos},
                    50,
                    'linear'
                );
            }
        }, 0);
    }
    
    function stopScroll()
    {
        $('ul#projects').stopTime();
        $('div.scrollBar').stopTime();
    }
    
    function scrollBarHover()
    {
        $(this).css('cursor', 'pointer');
    }
    
    function scrollBarUnHover()
    {
        $(this).css('cursor', 'auto');
    }
    
    function listScrollInit()
    {
        // Calculate size of scrollBar div and do some maths
        listViewPort = $('div#projects-list-wrapper').height() - 20;
        scrollBarPlane = listViewPort - $('div.scrollUp').height() - $('div.scrollDown').height();
        scrollRatio = listViewPort / $('ul#projects').height();
        scrollBarHeight = (scrollBarPlane * scrollRatio) - 10;
        scrollBarInitialTop = listViewPort - scrollBarPlane;
        listOffset = 0;

        // Try to retrieve a list scroll offset from the cookie
        if (readCookie('listOffset'))
        {
            listOffset = readCookie('listOffset') + 'px';
        }

        // If there is an offset, auto-scroll to that
        if (listOffset.length > 0)
        {
            $('ul#projects').css({'top': listOffset});
        }
        
        // Calculate how far the scrollBar css 'top' property can move
        scrollBarMaxMove = scrollBarPlane - scrollBarHeight;
        
        // Set scrollBar initial position based on list initial position
        currListOffset = $('ul#projects').position().top;
        listMaxScroll = $('ul#projects').height() - listViewPort;
        scrollRatio = (listMaxScroll + currListOffset) / listMaxScroll;
        scrollRatio--;
        scrollRatio = -scrollRatio;
        scrollBarOffset = scrollBarInitialTop + (scrollBarMaxMove * scrollRatio);
        
        $('div.scrollBar').css({'height': scrollBarHeight, 'top': scrollBarOffset});
            
        // Add hover scroll functionality to custom scroll arrows
        $('div.scrollUp').hover(startScrollUp, stopScroll);
        $('div.scrollDown').hover(startScrollDown, stopScroll);
        
        // Add click & drag functionality to scrollbar
        var x = $('div.scrollBar').position().left;
        var y1 = scrollBarInitialTop + 92;
        var y2 = scrollBarInitialTop + scrollBarMaxMove + 92;
        
        $('div.scrollBar')
            .hover(scrollBarHover, scrollBarUnHover)
            .draggable({
                axis: 'y',
                containment: [x, y1, x, y2],
                cursor: 'pointer',
                drag: onScrollDrag});
    }

    function textResizeInit()
    {
        var iBase = TextResizeDetector.addEventListener(onFontResize,null );
    }

    function onFontResize( e, args )
    {
        listScrollInit();
    }
    
    // Find the number of showreel images
    var numberOfImages = parseInt($('div.nextImage').size());
    
    // If the page has showreel images
    if (numberOfImages > 0)
    {
        // Add a nextImage button and give it 'firstChild' id
        $('#mainPanel').append('<div class="moreImages"></div>');
        $('div[class^=moreImages]').attr('id', 'firstChild');
        
        // Cycle through each showreel image 
        var i = 0;
        for (i = 0; i < numberOfImages; i++)
        {
            // Calculate position of left hand edge to position showreel images,
            // add nextImage and Back buttons
            var leftOffset = 975 * i;
            $('div.nextImage')
                .slice(i-1, i)
                .css('left',leftOffset)
                .append('<div class="moreImages"></div>')
                .append('<div class="back"></div>');
        }
        
        // Calculate position of left hand edge to position last showreel image
        leftOffset = 975 * numberOfImages;
        $('div.nextImage')
            .slice(numberOfImages - 1)
            .css('left',leftOffset)
            .append('<div class="back"></div>');
                
        // Get the last back button and move it over
        $($('div.back')[numberOfImages - 1]).css('right', '19px');
            
        // Find the secret magical hidden div and get its background color
        var bgColor = '#FFFFFF';
        var opacityMin = 0;
        var opacityMax = 0.1;
        if ($('div#jqBG').size() > 0)
        {
            bgColor = $('div#jqBG').attr('bgColor');
            opacityMin = 0.7;
            opacityMax = 0.9;
        }
        
        $('div[class^=moreImages]').append('<img src="../_images/nav/more_images.png" alt="More images" />');
        $('div[class^=moreImages] img').fadeTo(1, 1);
        
        $('div.back').append('<img src="../_images/nav/back.png" alt="Back" />');
        $('div.back img').fadeTo(1, 1);
    
        // Add jQuery rollover and click events to moreImages buttons
        $('div[class^=moreImages]').css({'background-color': bgColor}).fadeTo(1, opacityMin);
        $('div[class^=moreImages]').hover(
            function()
            {
                $(this).css('cursor', 'pointer').fadeTo(200, opacityMax);
            },
            function()
            {
                $(this).css('cursor', 'auto').fadeTo(200, opacityMin);
            }
        );
        
        $('div[class^=moreImages]').click(
            function()
            {                
                // Check if we're clicking the first moreImages button
                if ($(this).attr('id') == 'firstChild')
                {
                    // Slide to the left by 975px
                    $(this).parent().animate(
                        {left:"-975px"},
                        {duration:1000}
                    );
                }
                // Else if we're clicking the moreImages button on a showreel image
                else
                {
                    // Find out how many images there were before the current one
                    var previousImages = $(this).parent().prevAll().filter('.nextImage').size();
                    // Add two to include the current image and first page
                    previousImages = previousImages + 2;
                    // Calculate left offset of mainPanel in pixels
                    var leftDestination = previousImages * 975;
                    leftDestination = "-" + leftDestination + "px";
                    
                    // Do the slide animation
                    $(this).parent().parent().animate(
                        {left:leftDestination},
                        {duration:1000}
                    );
                }
            }
        );
        
        // Add jQuery rollover and click events to back button
        $('div.back').css({'background-color': bgColor}).fadeTo(1, opacityMin);
        $('div.back').hover(
            function()
            {
                $(this).css('cursor', 'pointer').fadeTo(200, opacityMax);
            },
            function()
            {
                $(this).css('cursor', 'auto').fadeTo(200, opacityMin);
            }
        );
        
        $('div.back').click(
            function()
            {
                // Slide everything back to the starting position
                $(this).parent().parent().animate(
                    {left:"0"},
                    {duration:1000}
                );
            }
        );
    }
    
    
    // Register click event handler for all project list items
    for (var i = 0; i < $('ul#projects > li').size(); i++)
    {
        projLink = $('ul#projects > li')[i];
        projLink.onclick = getScrollOffset;
        if (projLink.captureEvents)
        {
            projLink.captureEvents(Event.CLICK);
        }
    }
});
    
function getScrollOffset(e)
{    
    if (!e)
    {
        var e = window.event;
    }
    
    var listOffset = $('ul#projects').position().top;
    if (listOffset != 0)
    {
        createCookie('listOffset', listOffset);
    }
    else
    {
        eraseCookie('listOffset');
    }
}