var loaded = [], loading = false;
var url = false;

function fireBackground(tmb, href) {
    $(tmb).parents('ul:first').find('.active').removeClass('active').find('img').css('opacity', 0.5);
    $(tmb).find('img').css('opacity', 1).parent().addClass('active');
    
    $('#slides .activeslide').removeClass('activeslide').addClass('prevslide');
    $('#slides .nextslide').hide().attr('src', href).removeClass('nextslide').addClass('activeslide').fadeIn(500);
    $('#slides .prevslide').removeClass('prevslide').addClass('nextslide');
}

function loadImage(tmb, href) {
    if (url != false) {
        var id = $(tmb).attr('id').split('_');
        id = id[1];
        $.get(url + id,
            function(data){
                $('#chg').html(data);
        });
    }
    
    if (jQuery.inArray(href, loaded) < 0) {
        loading = true;
        //$('#loading').show();
        $.cacheImage(href, {
            load : function (e) {
                loaded.push(href);
                fireBackground($(tmb), href);
                loading = false;
                //$('#loading').hide();
            }
        });
    } else {
        fireBackground($(tmb), href);
    }
}

function shiftImage(direction) {
    var act = $('#thumbs').find('a.active');
    
    if (!$(act).length) {
        tmb = direction < 0 ? $('#thumbs').find('li:last a') : $('#thumbs').find('li:first a');
    } else {
        if (direction < 0) {
            var tmb = $(act).parent().prev().length ? $(act).parent().prev().find('a') : $(act).parents('ul:first').find('li:last a');
        } else {
            var tmb = $(act).parent().next().length ? $(act).parent().next().find('a') : $(act).parents('ul:first').find('li:first a');
        }
    }
    loadImage($(tmb), $(tmb).attr('href'));
    
    return false;
}

function initGallery(iurl) {
    if (typeof iurl != 'undefined' && iurl != '') { url = iurl; }
    
    $('#thumbs a').not('.active').find('img').css('opacity', 0.5);
    $('#thumbs a').each(function(i, a) {
        $(a).hover(
            function() { $(this).find('img').css('opacity', 1); },
            function() { if (!$(this).hasClass('active')) { $(this).find('img').css('opacity', 0.5); } }
        );
        $(a).bind('click', function(e) {
            
            var href = $(this).attr('href');
            loadImage($(a), href);
            
            return false;
        });
    });
    
    $('#toggle_left').click(function() { shiftImage(-1); return false; });
    $('#toggle_right').click(function() { shiftImage(1); return false; });
}

jQuery().ready(function() {
    $('a').each(function() {
        $(this).bind('click', function() {
            if (this.blur) {this.blur();}
        });
    });
});