// 200 lines of javascript Godness

var updateScroller;

window.addEvent('domready', function () {
    if ($('sideContent')) { // No need for this function if sideContent doesn't exist on the page

        var fixedTarget = false,
            scrollDirection = 'down',
            scrollPositon = 0,
            worldHeight = $('world').getSize().y,
            subPageFixedHeight = {
                element: $('subPage'),
                height: $('subPage').getScrollSize().y,
                name: 'subPage',
                floating: false
            },
            sideContentFixedHeight = {
                element: $('sideContent'),
                height: $('sideContent').getScrollSize().y,
                name: 'sideContent',
                floating: false
            };

        setContentFixedHeight = function () {
            //console.log('set Scroller variables');
            // SET SCROLLER VARAIBLES
            worldHeight = $('world').getSize().y;
            subPageFixedHeight.height = $('subPage').getScrollSize().y;
            sideContentFixedHeight.height = $('sideContent').getScrollSize().y;

            // Update the divs
            setScroller.bind($('world'));

        };

        //setContentFixedHeight.delay(500); // Because of cufon, this must be delayed. 
        window.addEvent('resize', setContentFixedHeight);

        setScroller = function () {

            //console.log('set Scroller');

            // Calculate Direction
            var newScrollPosition = this.getScroll().y;

            if (newScrollPosition > scrollPositon) {
                direction = 'down';
            }
            else {
                direction = 'up';
            }

            scrollPositon = newScrollPosition;

            if (direction == "down") {  // if the direction is down. Check if the bottom edge of the divs are "inside" the container. If they are, or = 0. Set fixed position and bottom 0 to prevent them from scrolling.             
                //Only one of the divs can be the heighest. Which one is it?
                var targetDiv;
                subPageFixedHeight.height > sideContentFixedHeight.height ? targetDiv = sideContentFixedHeight : targetDiv = subPageFixedHeight;

                if (targetDiv.element.getCoordinates().height < worldHeight) {

                    // CONTENT SMALLER THEN SCREEN

                    if (targetDiv.name == 'subPage') {
                        targetDiv.element.setStyles({
                            position: 'fixed',
                            top: 0,
                            bottom: 'auto'
                        });
                    }
                    else {
                        targetDiv.element.setStyles({
                            position: 'fixed',
                            top: 0,
                            bottom: 'auto',
                            left: 'auto',
                            marginLeft: 554
                        });
                    }

                    targetDiv.element.addClass('fixed');
                    fixedTarget = 'top';
                    targetDiv.floating = false;

                }
                else if (fixedTarget == 'top') {

                    var fixedElement, scrollElement;

                    if (subPageFixedHeight.element.hasClass('fixed')) {
                        fixedElement = subPageFixedHeight;
                        scrollElement = sideContentFixedHeight;
                    }
                    else {
                        fixedElement = sideContentFixedHeight;
                        scrollElement = subPageFixedHeight;
                    }

                    var diff = (scrollElement.element.getCoordinates().top);

                    // Remove old styles and set position of fixed element
                    fixedElement.element.removeProperty('style');
                    fixedElement.element.setStyle('position', 'absolute');
                    fixedElement.element.setStyle('top', -diff);

                    fixedElement.floating = true;
                    fixedTarget = false;

                }
                else if ((targetDiv.element.getCoordinates().height + targetDiv.element.getCoordinates().top) - worldHeight < 0) {

                    // set to fixed bottom
                    if (targetDiv.name == 'subPage') {
                        targetDiv.element.setStyles({
                            position: 'fixed',
                            bottom: 0,
                            top: 'auto'
                        });
                    }
                    else {
                        targetDiv.element.setStyles({
                            position: 'fixed',
                            bottom: 0,
                            top: 'auto',
                            left: 'auto',
                            marginLeft: 554
                        });
                    }
                    targetDiv.element.addClass('fixed');
                    fixedTarget = 'bottom';
                }

            }
            else {

                if (fixedTarget == 'bottom') { // if a div is fixed to the bottom. Place it relative to the "scrolling" div. 

                    //console.log('floating up');

                    var fixedElement, scrollElement;

                    if (subPageFixedHeight.element.hasClass('fixed')) {
                        fixedElement = subPageFixedHeight;
                        scrollElement = sideContentFixedHeight;
                    }
                    else {
                        fixedElement = sideContentFixedHeight;
                        scrollElement = subPageFixedHeight;
                    }

                    //var diff = (scrollElement.height - scrollElement.element.getCoordinates().top) - fixedElement.height;

                    var diff = (((scrollElement.element.getCoordinates().top).abs() - (fixedElement.element.getCoordinates().top).abs()));

                    // Remove old styles and set position of fixed element
                    fixedElement.element.removeProperty('style');
                    fixedElement.element.setStyle('position', 'absolute');
                    fixedElement.element.setStyle('top', diff);

                    fixedElement.floating = true;
                    fixedTarget = false;

                }
                else {

                    //Only one of the divs can be the heighest. Which one is it?
                    var targetDiv;
                    subPageFixedHeight.height > sideContentFixedHeight.height ? targetDiv = sideContentFixedHeight : targetDiv = subPageFixedHeight;

                    //console.log(sideContentFixedHeight.element.getCoordinates().top);

                    if (targetDiv.element.getCoordinates().top > 0) {

                        //console.log('set to fixed top');

                        if (targetDiv.name == 'subPage') {
                            targetDiv.element.setStyles({
                                position: 'fixed',
                                top: 0,
                                bottom: 'auto'
                            });
                        }
                        else {
                            targetDiv.element.setStyles({
                                position: 'fixed',
                                top: 0,
                                bottom: 'auto',
                                left: 'auto',
                                marginLeft: 554
                            });
                        }

                        targetDiv.element.addClass('fixed');
                        fixedTarget = 'top';
                        targetDiv.floating = false;

                    }
                }
            }
        };

        updateScroller = function () {

            var currentScrollPosition = $('world').getScroll().y;

            subPageFixedHeight.element.removeProperty('style').setStyle('position', 'absolute').removeClass('fixed');
            sideContentFixedHeight.element.removeProperty('style').setStyle('position', 'absolute').removeClass('fixed');

            setContentFixedHeight();
            setScroller.apply($('world'));

            $('world').scrollTop = currentScrollPosition;

        }

        // Bind scroll event
        $('world').addEvent('scroll', setScroller);
    }
});
