// just some html, here for convenience
// this is a global var
var ajaxLoaderTag = '<img src="/images/ajaxLoader.gif" class="spinner"/>';

// store the URL of the currently selected category -- makes it easier to
// update the category again when modifying links
var currentCategoryURL = '';

$(document).ready( function() {
    // Contact form {{{
    $('#contactForm').submit( function() {
        $('#contactForm').fancyForm({
            postSuccess: function( responseText ) {
                if( responseText.Saved == true ) {
                    $('#Box_Contact').empty();
                    $('#Box_Contact').html( '<h4>Contact Me</h4><p>Your message will be delivered soon.</p>' );
                }
             }
        });
        return false;
    }); // }}}
    // Clear error markings from input fields when they're focused {{{
        $('.Error').livequery( 'focus', function() {
            $(this).removeClass('Error');
            $('label[for='+$(this).attr('id')+']').removeClass('Error');
        });
    // }}}
    // clicking on the category list {{{
    // select (and load) that category into the div panel below to show the
    // links in that category
    $('#CategoryList ul li a.CategoryLink').live( 'click', function( event ) {
        if( isLClick( event )) { return; }
        selectCategory( $(this).attr('href') );
        return false;
    }); // }}}
    // clicking on the friends list {{{
    $('#Box_Friends ul li a.pagination').live( 'click', function( event ) {
        if( isLClick( event )) { return; }
        $('#Box_Friends ul').html( ajaxLoaderTag );
        $('#Box_Friends ul').fadeOut('fast');
        $.ajax({
            url: this.href,
            cache: false,
            success: function( result ) {
                $('#Box_Friends ul').html( result ).fadeIn('fast');
            }
        });
        return false;
    }); // }}}
    // clicking on the LARGE friends list {{{
    $('#Box_LargeFriends ul li a.pagination').live( 'click', function( event ) {
        if( isLClick( event )) { return; }
        $('#Box_LargeFriends ul').fadeOut('fast');
        $.ajax({
            url: this.href,
            cache: false,
            success: function( result ) {
                $('#Box_LargeFriends ul').html( result ).fadeIn('fast');
            }
        });
        return false;
    }); // }}}
    // Link popups {{{
    // FUCK YOU, MICROSOFT, your z-index handling blows
    // the margin-left and margin-top stuff is to keep the popups from
    // appearing off screen
    $('div.SquishImageWrapper').livequery( function() {
        $(this).hover(
            function() {
                // Entering
                if( $.browser.msie ) {
                    $(this).css({ 'z-index' : '3' });
                    $('.PopupContent').css({ 'z-index' : '3' });
                }

                var offset  = $(this).offset();
                var pWidth  = $(this).children('.PopupContent').outerWidth();
                var pHeight = $(this).children('.PopupContent').outerHeight();
                var right  = $(window).width()  + $(window).scrollLeft();
                var bottom = $(window).height() + $(window).scrollTop();

                if( offset.left + pWidth > right ) {
                    var toMove = right - ( offset.left + pWidth ) - 14;
                    $(this).children( '.PopupContent' ).css({ 'margin-left' : toMove });
                }

                if( offset.top + pHeight > bottom ) {
                    var toMove = bottom - ( offset.top + pHeight ) - 14;
                    $(this).children( '.PopupContent' ).css({ 'margin-top' : toMove });
                }

                $(this).children('.PopupContent').fadeIn('medium');

            },
            function() {
                // leaving
                if( $.browser.msie ) {
                    $(this).css({'z-index':'0'});
                    $('.PopupContent').css({ 'z-index' : '0' });
                }
                $('.PopupContent').stop( true, true );
                $(this).children('.PopupContent').hide();
                $(this).children('.PopupContent').css({ 'margin-top' : '0' });
                $(this).children('.PopupContent').css({ 'margin-left' : '0' });
            }
        );
    });
    // }}}
    // nyroModal popups {{{
    $('a.modal').live( 'click', function( event ) {
        if( isLClick( event )) { return; }
        event.preventDefault();
        $('.PopupContent').hide();
        $(this).nyroModalManual({
            autoSizeable: true,
            resizable: true,
            minWidth: 10,
            minHeight: 10,
            padding: 40
        });
        return false;
    });
    // }}}
});
function switchRatingToStars() { // {{{
    if( $('.PopupRating').length <= 0 ) { return; }
    $('.LinkRatingForm').stars({
        inputType: 'select',
        callback: function( ui, type, value, event, formID ) {
            fID = $('#'+formID);
            fID.fancyForm({
                postSuccess: function( response ) {
                    if( response.Saved == true ) {
                        refreshLinkInfo( response.LinkID );
                    }
                }
            });
        }
    });
    $('.LinkRatingForm').each( function() {
        var average    = $(this).find('input[name="average"]').val();
        var hasAverage = $(this).find('input[name="average"]').val().length;
        var hasVoted   = $(this).find('input[name="hasVoted"]').val();
        if( hasVoted == 0 && hasAverage != 0 ) {
            $(this).data('stars').set( average, true );
        }
    });
    $('.RatingSubmit').hide();
}
// }}}
function selectCategory( URL ) { // {{{
    if( '' == URL ) { return selectFirstCategory(); }
    currentCategoryURL = URL;
    $('#CategoryLinkContainer').empty();
    $('#CategoryLinkContainer').html( ajaxLoaderTag );
    hlCategory( URL );
    $.ajax({
        url: URL,
        cache: false,
        success: function( result ) {
            $('#CategoryLinkContainer').empty();
            $('#CategoryLinkContainer').html( result );
            makeFancy();
        }
    });
} // }}}
function makeFancy() { // {{{
    switchRatingToStars();
    equalHeight( $('.SquishLink' ) );
    equalWidth( $('.SquishLink' ) );
    fixFavicon();
    makeLinkTitleTooltips();
} // }}}
function fixFavicon() { // {{{
    $('.PopupFavicon').preload({
        placeholder: '/images/missing_favicon.png',
        notFound: '/images/missing_favicon.png'
    });
} // }}}
function selectCategoryByID( id ) { // {{{
    selectCategory( $('li#Category_'+id+' a').attr('href') );
} // }}}
function selectFirstCategory() { // {{{
    selectCategory( $('#CategoryList ul li.Sortable a.CategoryLink:first').attr('href') );
} // }}}
function hlCategory( URL ) { // {{{
    $('#CategoryList ul li a').each( function() {
        if( $(this).attr('href') == URL ) {
            $(this).addClass('SelectedCategory');
        } else {
            $(this).removeClass('SelectedCategory');
        }
    });
} // }}}
function equalHeight( group ) { // {{{
    tallest = 0;
    group.each( function() {
        thisHeight = $(this).height();
        if( thisHeight > tallest ) {
            tallest = thisHeight;
        }
    });
    group.height( tallest );
} // }}}
function equalWidth( group ) { // {{{
    widest = 0;
    group.each( function() {
        thisWidth = $(this).width();
        if( thisWidth > widest ) {
            widest = thisWidth;
        }
    });
    group.width( widest );
} // }}}
function isLClick( event ) { // {{{
    // Detection for whether a click was made with only the left button, and without any modifiers
    if( event.button != 0 || event.ctrlKey || event.shiftKey || event.altKey ) {
        return true;
    } else {
        return false;
    }
} // }}}
function refreshLinkInfo( id ) { // {{{
    $.ajax({
        type: 'GET',
        url: '/link/refreshInfo/?id='+id,
        success: function( response ) {
            $('#Link_'+id+' * img.SquishImage').each( function() {
                $(this).attr('src', response.Thumbnail );
            });
            if( !response.Rating ) {
                $('#Link_'+id+' * div.PopupRatingDisplay').html( 'Nobody has rated this link' );
            } else {
                $('#Link_'+id+' * div.PopupRatingDisplay').html( 'Rating average of '+response.Rating.Average+' stars by '+response.Rating.Total+' users' );
            }
            $('#Link_'+id+' * div.PopupViewCount').html( 'Viewed '+response.ViewCount+' times' );
        },
        cache: false,
        dataType: 'json'
    });
} // }}}
function makeLinkTitleTooltips() { // {{{
    $('div.LinkTitle span').tooltip({
        track: true,
        delay: 0,
        showURL: false,
        opacity: 1,
        showBody: '|',
        top: -15,
        fade: 250
    });
} // }}}
