var loaded = [], imgs = [], cur = 0, loading = false;
var url = false, fadeglow = -1;

function fireBackground(href) {
    $('#slides .activeslide').addClass('prevslide').removeClass('activeslide');
    $('#slides .nextslide').hide().attr('src', href).removeClass('nextslide').addClass('activeslide').fadeIn(500);
    $('#slides .prevslide').removeClass('prevslide').addClass('nextslide');
}

function loadImage(index) {
    if (jQuery.inArray(imgs[index], loaded) < 0) {
        loading = true;
        //$('#loading').show();
        $.cacheImage(imgs[index], {
            load : function (e) {
                loaded.push(imgs[index]);
                fireBackground(imgs[index]);
                loading = false;
                //$('#loading').hide();
            }
        });
    } else {
        fireBackground(imgs[index]);
    }
}

function shiftImage(direction) {
    if (!loading) {
        cur = cur + direction;
        if (cur < 0) {
            cur = imgs.length - 1;
        } else if (cur >= imgs.length) {
            cur = 0;
        }
        loadImage(cur);
    }
    return false;
}

function initGallery(images, start) {
    cur = typeof start == 'number' ? start : 0;
    imgs = images;
    loaded.push(imgs[cur]);
    $('#toggle_left').click(function() { shiftImage(-1); return false; });
    $('#toggle_right').click(function() { shiftImage(1); return false; });
}

function animateLogo(obj, type) {
    if (type == 'on') {
        $(obj).animate({
            'height': 61
        }, 240, 'easeout');
    } else {
        $(obj).animate({
            'height': 49
        }, 120, 'easeout');
    }
}

function fadeGlow(obj) {
    $(obj).animate({
        'opacity' : 0.65
    }, 2400, 'easeinout').animate({
        'opacity' : 0.65
    }, 1800).animate({
        'opacity' : 1
    }, 3200, 'linear');
    
    if (fadeglow == -1) {
        fadeglow = window.setInterval(function() {
            fadeGlow($('#glow'));
        }, 7200);
    }
}

jQuery().ready(function() {
    $('a').each(function() {
        $(this).bind('click', function() {
            if (this.blur) {this.blur();}
        });
    });
    $('a#homelink').css({
        'display': 'block',
        'zIndex' : 50000
    });
    $('a#homelink').hover(
        function() { animateLogo($(this), 'on'); },
        function() { animateLogo($(this), 'off'); }
    );
    
    if ($('#glow').length && $('#glow').hasClass('fade')) {
        fadeGlow($('#glow'));
    }
});
