/**
 *  Table Stiper
 *  Applies stripes to table body rows on load, hooking into the class
 *  "stripes" applied to any tables.
 *  Last modified: 2010-08-24 {pf}
 */
function tableStriper() {
    $('table.stripes tr:nth-child(even)').addClass('even');
}

function imageSwitchHover() {
    
    //  Fade effects
    var duration = 150;
    $('.client .clientInner, .person a').hover(
        function() {
            $('img.item', this).stop().animate({'opacity':'0'}, duration);
            $('img.photo', this).stop().animate({'opacity':'1'}, duration);
        },
        function() {
            $('img.item', this).stop().animate({'opacity':'1'}, duration);
            $('img.photo', this).stop().animate({'opacity':'0'}, duration);
        }
    );

}


function flyoutPanels() {
    $('a.flyout').bind('click', function() {
        $('a.flyout').removeClass('on');
        $('#meta .panel:visible').fadeOut('fast');
        $(this).siblings('.panel:hidden').fadeIn('fast', function() {
            $(this).siblings('a.flyout').addClass('on');
        });
        return false;
    });
}


function personFlyout() {
    $('.personLink').bind('click', function()
                          {
                            $('.personLink').siblings('p').fadeOut();
                            
                            if ($(this).siblings('p').is(':hidden'))
                            {
                                $(this).siblings('p').fadeIn();
                            }
                            else {
                                $(this).siblings('p').fadeOut();                                
                            }
                            return false;
                          });
    
}

function paginationDimensions() {
    var scrollTop = $(window).scrollTop();
    var contentOffset = $('#content').offset().top;
    var difference = 0;
    
    if (contentOffset - scrollTop > 0)
    {
        difference = contentOffset - scrollTop + 6;
    }
    
    var windowWidth = (($(window).width() - $('#content').width())/2);    
    
    $('#prev').css('width', windowWidth);
    $('#next').css('width', windowWidth);
    
    $('#next').css('margin-left', $(window).width() - $('#next').width());
    
    var distanceFromBottom = $('body').height() - $(window).scrollTop() - $(window).height();
    
    if (distanceFromBottom < $('#footer').height())
    {
        $('#prev').css('margin-bottom', $('#footer').height() - distanceFromBottom);
        $('#next').css('margin-bottom', $('#footer').height() - distanceFromBottom);
        
        var adjustedHeight = $('#prev').css('height') - ($('#footer').height() - distanceFromBottom);
        
        $('#prev').css('height', $(window).height() - ($('#footer').height() - distanceFromBottom));
        $('#next').css('height', $(window).height() - ($('#footer').height() - distanceFromBottom));        
    }
    else {
        
        $('#prev').css('height', $(window).height() - difference);
        $('#next').css('height', $(window).height() - difference);             
        
        $('#prev').css('margin-bottom', '');
        $('#next').css('margin-bottom', '');        
    }
}

function navShow() {
    $('#prev').hover(
        function() {
            $('#prev img').fadeIn(2000)
        },
        function() {
            $('#prev img').stop(true, true).delay(1500).fadeOut("slow");
        });
    $('#next').hover(
        function() {
            $('#next img').fadeIn(2000)
        },
        function() {
            $('#next img').stop(true, true).delay(1500).fadeOut("slow");
        });    
}


function peopleSlider() {
        //scrollpane parts
        var scrollPane = $( ".scroll-pane" ),
            scrollContent = $( ".peopleScroll" );
        
        // work out width of scrollpane
        var pNumber = $(".peopleScroll li").size();
        var pWidth = $(".peopleScroll li").outerWidth(true);
        
        scrollContent.css("width", pNumber * pWidth);
                        
        $('li:last', scrollContent).addClass('last');
        $('li:first', scrollContent).addClass('first');        
        
        //build slider
        var scrollbar = $( ".scroll-bar" ).slider({
                slide: function( event, ui ) {
                        if ( scrollContent.width() > scrollPane.width() ) {
                                scrollContent.css( "margin-left", Math.round(
                                        ui.value / 100 * ( scrollPane.width() - scrollContent.width() )
                                ) + "px" );
                        } else {
                                scrollContent.css( "margin-left", 0 );
                        }
                }
        });
        
        //append icon to handle
        var handleHelper = scrollbar.find( ".ui-slider-handle" )
        .mousedown(function() {
                scrollbar.width( handleHelper.width() );
        })
        .mouseup(function() {
                scrollbar.width( "100%" );
        })
        .append( "<span class='ui-icon ui-icon-grip-dotted-vertical'></span>" )
        .wrap( "<div class='ui-handle-helper-parent'></div>" ).parent();		
        
        //size scrollbar and handle proportionally to scroll distance
        function sizeScrollbar() {
                var remainder = scrollContent.width() - scrollPane.width();
                if (remainder > 0)
                {
                var proportion = remainder / scrollContent.width();
                var handleSize = (scrollPane.width() - ( proportion * scrollPane.width() )) / 2;
                scrollbar.find( ".ui-slider-handle" ).css({
                        width: handleSize,
                        "margin-left": -handleSize / 2
                });
                handleHelper.width( "" ).width( scrollbar.width() - handleSize );
                }
                else {
                    $(".scroll-bar-wrap").hide();
                }
        }
        
        //reset slider value based on scroll content position
        function resetValue() {
                var remainder = scrollPane.width() - scrollContent.width();
                var leftVal = scrollContent.css( "margin-left" ) === "auto" ? 0 :
                        parseInt( scrollContent.css( "margin-left" ) );
                var percentage = Math.round( leftVal / remainder * 100 );
                scrollbar.slider( "value", percentage );
        }
        
        //if the slider is 100% and window gets larger, reveal content
        function reflowContent() {
                        var showing = scrollContent.width() + parseInt( scrollContent.css( "margin-left" ), 10 );
                        var gap = scrollPane.width() - showing;
                        if ( gap > 0 ) {
                                scrollContent.css( "margin-left", parseInt( scrollContent.css( "margin-left" ), 10 ) + gap );
                        }
        }
        
        //change handle position on window resize
        $( window ).resize(function() {
                resetValue();
                sizeScrollbar();
                reflowContent();
        });
        //init scrollbar size
        setTimeout( sizeScrollbar, 10 );//safari wants a timeout
}

/**
 *  Tweet This
 *  Automatically creates a status update message for Twitter. Uses the
 *  Bit.ly API to make an appropriate short URL.
 *  Last modified: 2011-02-19 {pf}
 */
function tweetThis() {
    
    var bitly = {
        user: 'markedup',
        key: 'R_2dac0e736fc4d9d4488ea242ae12b979'
    };
    
    var tweet = {
        limit: '140',
        runon: '... ',
        msg: '',
        url: '',
        tags: ''
    };
    
    $('a.tweetThis').click( function() {
        
        //  Show activity
        $(this).css({
            cursor: 'wait',
            backgroundImage: 'url(../img/tweet-wait.gif)'
        });
        $(this).html('Working&hellip;');
        
        //  Get article title
        var title = $('h1').text();
        var lastChar = title.substring( (title.length - 1), title.length );
        var regExp = /^[a-zA-Z0-9]$/;
        if ( regExp.test(lastChar) ) {
            title += ':';
        }
        
        //  Get short URL, build suitable message, move to Twitter
        var call = 'http://api.bitly.com/v3/shorten?login=' + bitly.user + '&apiKey=' + bitly.key + '&longUrl=' + encodeURIComponent(location.href) + '&format=json';
        $.getJSON( call, function(response) {
            tweet.url = response.data.url;
            //  Compile title and short URL
            if ( (title + ' ' + tweet.url).length > tweet.limit ) {
                var stop = tweet.limit - (tweet.runon.length + tweet.url.length);
                tweet.msg = title.substring(0,stop) + tweet.runon + tweet.url;
            }
            else if ( (title + ' ' + tweet.url).length <= tweet.limit ) {
                tweet.msg = (title + ' ' + tweet.url);
            }
            //  Add tags if space
            var tags = $('#content #published span.tags a');
            var i = 0;
            while ( tweet.msg.length < tweet.limit && i < tags.length ) {
                if ( (tweet.msg + ' #' + tags[i].text.split(' ').join('')).length > tweet.limit ) {
                    break;
                }
                tweet.msg += ' #' + tags[i].text.split(' ').join('').toLowerCase();
                i++;
            }
            location.href = 'http://twitter.com/?status=' + encodeURIComponent(tweet.msg);
        });
        
        return false;
        
    });
    
}
                                    

$(window).resize(function() {
    paginationDimensions();
});

$(window).scroll(function() {     
    paginationDimensions();
});

$(document).ready( function() {
    personFlyout();
    flyoutPanels();
    peopleSlider();
    imageSwitchHover();
    navShow();
    paginationDimensions();
    tableStriper();
    //$('#prev').bind('click', function(){
    //    $('#hid').load("person2.html #content > *", function()
    //                         {
    //                            $('#pages').animate({left: -780}, 200, function()
    //                                                 {
    //                                                    $('html, body').animate({scrollTop:$('#content').offset().top}, 'slow');
    //                                                 })
    //                         });
    //    return false;
    //})
    tweetThis();
});


$(document).click(function(e) {
    
    if ($(e.target).is('.more span') || $(e.target).is('.more a') || $(e.target).is('.personLink img')) {
        $('.personLink').siblings('p:visible');
    }
    else {
       $('.personLink').siblings('p').fadeOut();
    }
    
    if ($(e.target).is('#meta .panel') || $(e.target).parents('#meta .panel').length || $(e.target).is('.flyout')) {
    }
    else {
        $('#meta .panel').fadeOut();
        $('#meta .flyout').removeClass('on');
    }
    
}); 


