$(document).ready(function() {

    // after the overlay loads it fires this event, we can then do stuff in the overlay DOM
    $().bind('cbox_complete', function(){
        // popup windows
        $(".popupwindow").popupwindow();
    });

    // handler for directory overlays
    $(".overlayLink").colorbox({ width:"800px", height:"480px", iframe:false, current:"{current} of {total}"});

    // handler for clicking on letters on directory page.
    $('.letterLink, .letterAllLink').click(letterClickHandler);

    // click handler for location page links
    $('.locationLink').click(createDealerClickHandler('activeLocationLink', 'locationDetails'));
    $('.categoryLink').click(createDealerClickHandler('activeCategoryLink', 'categoryDetails'));
});

function createDealerClickHandler(activeLinkClass, detailsClass) {
    return function() {
        $('.'+activeLinkClass).removeClass(activeLinkClass);
        if(!$('.'+this.id).is(':visible')) $(this).addClass(activeLinkClass);
        $('.'+detailsClass+':visible').slideUp();
        var details = $('.'+this.id);
        $(this).parent().after(details.remove());
        $('.overlayLink', details).colorbox({width:"800px", height:"480px",iframe:false, current:"{current} of {total}"});
        details.slideToggle();
    };
}

function letterClickHandler() {
    var clickedId = this.id;
    if(clickedId == 'letterAll') {
        $('#oneLetter').slideUp(function() {
            $('#allLetters').slideDown();
        });
    } else {
        $('#oneLetter').slideUp(function() {
            var table = $('#allLetters').clone(false);
            table.id = '';

            table.find('.hidable:not(.'+clickedId+')').remove();
            $('#oneLetter').html(table.show());
            if($('#allLetters').is(':visible')) $('#allLetters').slideUp();
            $('#oneLetter a').each(function() {this.rel = '#oneletterOverlay'});

            $("#oneLetter .overlayLink").colorbox({ width:"800px", height:"480px", iframe:false, current:"{current} of {total}"});
            $('#oneLetter').slideDown();
            
        });
    }
}