$(function(){
    $('#home a').click(function() {
        if ($(this).hasClass('gallery')) {
            var title = this.title;
            $.get($(this).attr('href') + '/ajax', function(data) {
                if ($('#ajax-load').size) $('#ajax-load').remove();
                
                $('body').append('<div id="ajax-load">' + data + '</div>')
                $('#ajax-load').hide();
                $('#ajax-load a').fancybox({
                    'title': title,
                    'titleFormat': formatTitle,
                    'titlePosition': 'inside',
                    'overlayShow': false
                });
                $('#ajax-load a:first').trigger('click');
            });
        } else {
            $.fancybox({
                'href': $(this).attr('href') + '/ajax',
                'onComplete': function() {
                    $('.page').css('background-color','transparent');
                    setClicks();
                },
                'overlayShow': false
            });
        }

        $('#fancybox-content').css('background-color', $(this).css('color'));
        recordClick($(this).attr('href'), 'Page');

        return false;
    });

    setClicks();

});

function setClicks() {
    $('a[href^="http://"]').attr('target', '_blank');

    // add to onclick handler otherwise Safari popup blocker kills links
    $('a[href^="http://"]').attr('onclick', 'recordClick(this.href, "External"); window.setTimeout("window.open(\'"+this.href+"\')", 100); return false;');
}

function recordClick(href, type) {
    _gat._getTrackerByName()._trackEvent(type, href);
    //_gaq.push(['_trackEvent', type, 'click', href]);
}

function formatTitle(title, currentArray, currentIndex, currentOpts) {
    return (title && title.length ? '<strong style="text-transform:capitalize;">' + title + '</strong> ' : '' ) + (currentIndex + 1) + ' / ' + currentArray.length;
}
