$(function(){
    // Set up special Twitter block
    $('#div_row_content0\\.1\\.0').html('<div id="stream"></div>');
    $('#div_row_content0\\.1\\.0').parent().parent().removeClass('cols-3 cols-2 cols-1').addClass('cols-1').addClass('columnized');
    $('#link_row_section_header0').html('twitter');
    var currentTime = new Date();
    var month = currentTime.getMonth() + 1;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear().toString();
    $('#link_row_content_extra0\\.1').html( month + '.' + day + '.' + year.substr(2,2) );
    $('#link_row_content_title0\\.1').removeClass('link_row_content_title_off').addClass('link_row_content_title').html( '<a target="_blank" class="link_copy" href="http://www.twitter.com/noahhawley">Follow</a>&nbsp;<a target="_blank" style="color: #ffffff;" href="http://www.twitter.com/noahhawley">@NoahHawley</a>' );
    $('#div_row_content_extra0\\.2').before('<div id="div_row0_section_subheader2" class="div_row_section_subheader_off"><a href="#">blog</a></div>');

    // set contact div to 1-col by default
    $('#div_row5_item1').removeClass('cols-3 cols-2 cols-1').addClass('cols-1');
                
    // set widths on the item rows that are wide enough to contain content
    $('#div_row0, #div_row1, #div_row2, #div_row3, #div_row4, #div_row5').each( function() {
        var numItems = $(this).find('.div_row_item_container').length;
        $(this).css('width', (numItems + 1) * 1000);
    });

    // turn all item blocks off
    function hideAllDivs() {
        $('.current').removeClass('current');
        $('.div_row_content_container_off:hidden').css({
            'display': 'block',
            'z-index': '100'
        });
    }

    // show the next three columns within an item block
    function showMoreContent( myItem ) {
        $(myItem).find('.div_row_content .column:visible:lt(3)').css('display', 'none');

        // if there are no more columns to show, hide button
        if( $( myItem ).find('.div_row_content .column:visible').length <= 3 ) {
            $( myItem ).find('.div_more_arrow').css( 'display', 'none');
        }
        showBackButton( myItem );
    }
    
    // determine if the More button should be displayed
    function showMoreButton( myItem ) {
        if( $( myItem ).find('.div_row_content .column:visible').length > 3 ) {
            $( myItem ).find('.div_more_arrow').css( 'display', 'block');
            $( myItem ).find('.entry-more').unbind().click( function() {
                showMoreContent( myItem );
                return false;
            });
        } else {
            $( myItem ).find('.div_more_arrow').css( 'display', 'none');
        }
    }

    // display the previous three columns within an item block            
    function showBackContent( myItem ) {
        var hiddenCols = $( myItem ).find('.div_row_content .column:hidden').length;
        $( myItem ).find('.div_row_content .column').css('display', '');
        if ( hiddenCols <= 3 ){
            $( myItem ).find('.div_back_arrow').css( 'display', 'none');
            
        } else {
            $(myItem).find('.div_row_content .column:lt(' + (hiddenCols - 3) + ')').css('display', 'none');
        }
        showMoreButton( myItem );               
    }
    
    // determine if the Back button should be displayed
    function showBackButton( myItem ) {
        if( $( myItem ).find('.div_row_content .column:hidden').length >= 3 ) {
            $( myItem ).find('.div_back_arrow').css( 'display', 'block');
            $( myItem ).find('.entry-back').unbind().click( function() {
                showBackContent( myItem );
                return false;
            });
        }
    }
                
    // display an item - turn it on
    function showItem( myItem ) {
        
        $( myItem ).addClass('current').find('.div_row_content_container_off').delay(100).css({
            'display': 'none',
            'z-index': '0'
        });
        
        showMoreButton( myItem );
    }
    
    // main function to display an item block
    function scrollToAndShowItem( currentItem ) {
        // set all item blocks to off-state
        hideAllDivs();
        // highlight the appropriate nav item
        resetNav( currentItem );
        // return to the left side of the page
        $(window).scrollTo( { top: $(window).scrollTop(), left: 0 } );
        
        // activate section header
        var showItemName = $(currentItem).parent().attr('id');
        showItemHeader = showItemName.replace( 'div_row', '#link_row_section_header' );
        $('.link_row_section_header').removeClass().addClass( 'link_row_section_header_off' );
        $( showItemHeader ).addClass( 'link_row_section_header' ).html( 
            $(currentItem).find('.div_row_section_subheader_off a').html()
        );
        
        // if the item block hasn't already been columnized, let's do so now
        if( ! $( currentItem ).hasClass('columnized') ) {
            // columnize item
            $( currentItem ).find('.div_row_content').columnize({
                width: 282,
                height: 220,
                buildOnce: true,
            });
            $( currentItem ).addClass('columnized');

            // move the media column contents to the third column within the content div
            $( currentItem ).find('.column:nth-child(2)').after( function () {
                return $(currentItem).find(".div_row_media").html();
            } );
            
            var videoItem = $( currentItem ).find( '.video' );
            // this item has a video
            if( videoItem.length > 0 ) {
                var videoPath = $( videoItem ).find( '.video-path' ).html();
                var videoContainer = "videocontainer" + $(currentItem).attr('id').replace('div_row', '');

                // setup video player
                jwplayer( videoContainer ).setup({
                    flashplayer: "/common/jwplayer/player.swf", 
                    file: videoPath, 
                    height: 167, 
                    width: 260,  
                    'controlbar': 'bottom', 
                    'backcolor': '#666666',
                });
            }

            // remove any empty columns
            $( currentItem ).find('.column:empty').each(function() {
                var myItemParent = $(this).parent().parent().parent();
                var myParent = $(this).parent();
                $(this).remove();
            });

            // resize the surounding content area if there are less than 3 columns
            $( currentItem ).find('.div_row_content').each( function() {
                var totalCols = $(this).find('.column').length;

                var newCols;
                if( totalCols >= 3 ) {
                    newCols = "cols-3";
                } else {
                    newCols = "cols-" + totalCols;
                }

                $(this).css('width', 282 * totalCols);
                $(this).parent().parent().removeClass('cols-3 cols-2 cols-1').addClass(newCols);
            });
        }
        
        // scroll non-blog rows a little higher
        var goToTop = 0;
        if( $(currentItem).parent().attr('id') != 'div_row0') {
            goToTop = $(currentItem).offset().top - 165
        }
        
        // scroll vertically to the correct row
        $.scrollTo( {
                top: goToTop,
                //left: $(currentItem).offset().left - 233 
            }, 
            500, 
            {
                queue: true, 
                easing: 'swing', 
                axis: 'y', 
                onAfter: scrollHorizontallyToItem( currentItem )
            } );
    }

    // scroll horizontally to the current item block
    function scrollHorizontallyToItem( currentItem ) {
        $( currentItem ).parent().animate(
            {left: 210 - $( currentItem ).position().left },
            500,
            'swing',
            function() {
                showItem( currentItem );
            }
        );
    }

    // highlight the selected nav
    function setNav( selectedNav ) {
        $('.link_nav_main_on').removeClass('link_nav_main_on').addClass('link_nav_main');
        $('.link_nav_main_sub_on').removeClass('link_nav_main_sub_on').addClass('link_nav_main_sub');
        if ( $(selectedNav).hasClass('link_nav_main') ) {
            $( selectedNav ).removeClass('link_nav_main').addClass('link_nav_main_on');
            resetNavWriting();
            resetNavPress();
        } else {
            $( selectedNav ).removeClass('link_nav_main_sub').addClass('link_nav_main_sub_on');
            if( $(selectedNav).parent().attr('id') == 'subnav_main3') {
                resetNavWriting();
            } else {
                resetNavPress();                        
            }
        }
    }

    // hide Writing subnav
    function resetNavWriting() {
        $('#subnav_main1').css('display', 'none');
        $('#link_nav_main_item1').css('display', '');
    }
    
    // hide Press subnav
    function resetNavPress() {
        $('#subnav_main3').css('display', 'none');
        $('#link_nav_main_item3').css('display', '');
    }

    // reset nav
    function resetNav( myItem ) {
        myArray = $(myItem).attr('id').split('_');
        if( myArray.length == 4 ) {
            //subnav item
            
            //row
            var subnavMenu = myArray[1].replace('row', '#subnav_main');
            var subnavLink = myArray[1].replace('row', '#link_nav_main_item');
            $(subnavMenu).css('display', '');
            $(subnavLink).css('display', 'none');
            var selectNav = myArray[2].replace('cat', '#link_nav_main_sub');
            setNav( selectNav );
        } else {
            var navLink = myArray[1].replace('row', '#link_nav_main_item');
            setNav( navLink );
        }
    }

    // when the tweets are ready, add animation effects
    function onTweetsReceived() {
        $('#stream').append('<br style="clear:both;" />');

        // prettify twitter stream scroll
        $('#stream').jScrollPane( { showArrows: true } );

        $('#stream ul').simpleSpy(10, 12000, updateTwitterScrollBars);
    }

    // update the twitter scrollbar
    function updateTwitterScrollBars() {
        $('#stream').jScrollPane( { showArrows: true } );
    }


    // get tweets
    getTwitters('stream', {
        id: 'noahhawley', 
        clearContents: false, // leave the original message in place
        enableLinks: true,
        count: 20, 
        withFriends: true,
        ignoreReplies: false,
        newwindow: true,
        template: '<div><img height="25" width="25" src="%custom_profile_image_url%"><p><b>%user_screen_name%</b> %text% <a href="http://twitter.com/%user_screen_name%/statuses/%id_str%/" class="timestamp" target="_blank">%time%</a></p><br style="clear:both;"/></div>',
        callback: onTweetsReceived
    });

    // show the first item
    showItem( $('#div_row0_item1') );
    
    // make each item block display itself on click
    $('.link_show_entry').click( function() {
        scrollToAndShowItem( $(this).parent().parent() );
        return false;
    });
    
    // activate next and previous arrows
    $('.arrow-next, .arrow-prev').click( function( event ) {
        var targetArray = event.target.href.split('#');
        var targetItem = targetArray[1];
        scrollToAndShowItem( $('#' + targetItem ) );
        return false;
    });
    
    // click event for main nav links
    $('.link_nav_main, .link_nav_main_sub').click( function() {
        setNav( this );
    });
    
    // press hover
    $('#subnav_main3').hover( 
        function(){
            resetNavWriting();
        },
        function() {
            if( $(this).find('.link_nav_main_sub_on').length <= 0 ) {
                resetNavPress();                        
            }
    });
    // writing hover
    $('#subnav_main1').hover( 
        function(){
            resetNavPress();
        },
        function() {
            if( $(this).find('.link_nav_main_sub_on').length <= 0 ) {
                resetNavWriting();                        
            }
    });

    // activate nav items
    $('#link_nav_main_item0').click(function() { scrollToAndShowItem( '#div_row0_item1' ); return false; });
    $('#link_nav_main_item1').hover(
        function() {
            $('#subnav_main1').css('display', 'block');
            $(this).css('display', 'none');
        },
        function() {
            // no hover out activity
        }
    );
    $('#link_nav_main_sub1').click(function() { scrollToAndShowItem( '#div_row1_cat1_item1' ); return false; });
    $('#link_nav_main_sub2').click(function() { scrollToAndShowItem( '#div_row1_cat2_item1' ); return false; });
    $('#link_nav_main_sub3').click(function() { scrollToAndShowItem( '#div_row1_cat3_item1' ); return false; });
    $('#link_nav_main_item2').click(function() { scrollToAndShowItem( '#div_row2_item1' ); return false; });
    $('#link_nav_main_item3').hover(
        function() {
            $('#subnav_main3').css('display', 'block');
            $(this).css('display', 'none');
        },
        function() {
            // no hover out activity
        }
    );
    $('#link_nav_main_sub4').click(function() { scrollToAndShowItem( '#div_row3_cat4_item1' ); return false; });
    $('#link_nav_main_sub5').click(function() { scrollToAndShowItem( '#div_row3_cat5_item1' ); return false; });
    $('#link_nav_main_sub6').click(function() { scrollToAndShowItem( '#div_row3_cat6_item1' ); return false; });
    $('#link_nav_main_item4').click(function() { scrollToAndShowItem( '#div_row4_item1' ); return false; });
    $('#link_nav_main_item5').click(function() { scrollToAndShowItem( '#div_row5_item1' ); return false; });
    
    //activate title links
    $('a.link_row_content_title_off, a.link_row_content_extra_off').click( function() {
        var currentItem =  '#' + $(this).parent().parent().attr('id');
        scrollToAndShowItem( currentItem );
        return false;
    });
    
    // hide previous buttons on first item in row
    $('#div_row1_cat1_item1, #div_row3_cat4_item1').each( function() {
        $(this).find('.arrow-prev').css('display', 'none');
    });
    
    // update target for previous buttons in first item in subnavs
    $('#div_row1_cat2_item1, #div_row1_cat3_item1, #div_row3_cat5_item1, #div_row3_cat6_item1').each( function() {
        $(this).find('.arrow-prev').attr('href', '#' + $(this).prev().prev().attr('id') );
    });
    
    // activate section headers
    $('.link_row_section_header_off').click( function() {
        var currentItem = $(this).attr( 'id' );
        var currentRow = currentItem.replace('link_row_section_header', '');
        if ( currentRow == 1 ) {
            scrollToAndShowItem( '#div_row' + currentRow + '_cat1_item1' ); 
        } else if ( currentRow == 3 ) {
            scrollToAndShowItem( '#div_row' + currentRow  + '_cat4_item1' ); 
        } else {
            scrollToAndShowItem( currentItem.replace('link_row_section_header', '#div_row')  + '_item1' ); 
        }
        return false;
    });
    
    // activate section subheaders 
    $('.div_row_section_subheader_off a').click( function() {
        scrollToAndShowItem( '#' + $(this).parent().parent().attr('id') );
        return false;
    } );

    // activate main quote link
    $('.link_main_quote').click( function(){
        var linkTarget = $(this).attr('href').replace('#goto-', '.');
        var newTarget = '#' + $( linkTarget ).attr('id');
        scrollToAndShowItem( newTarget );
        return false;
    });

});
