function updateImageWhenProductOptionChanged() {
    var color = $(this).val();
    var a = $('a[title="' + color.toUpperCase() + '"]');

    loadImage(a);
}

function updateOptionWhenProductImageClicked() {
    var title = $(this).attr('title').toUpperCase();
    $('#options select option').each(function () {
        var value = $(this).val();
        if (value.toUpperCase() === title) {
            $('#options select').val(value).change();
            return;
        }
    });
}

function loadImage(a) {
    var src = a.attr("href");
    $("#loader").addClass("loading");

    $("#main_image img").load(function(){
        $("#loader").removeClass("loading");
        $(this).css('display', 'none').fadeIn();
    }).attr("src", src);

    $("#main_image #caption").html(a.attr("title"));
}

$(function() {
    if ($('#thumbs a') && $('#options select')) {
        var names = $('#options select option').map(function () {
            return $(this).attr('value').toUpperCase();
        });
        $('#thumbs a').each(function () {
            var a = $(this);
            if ($.inArray(a.attr('title').toUpperCase(), names) < 0) {
                a.remove();
            }
        });
    }

    $("#thumbs").delegate("a", "click", function(){
        loadImage($(this));
        return false;
    });

    var press = $(".press .modal");
    if ('fancybox' in press) {
        press.fancybox();
    }

    $("#movie").fancybox({
        'padding'       : 0,
        'autoScale'     : false,
        'transitionIn'  : 'none',
        'transitionOut' : 'none',
        'width'         : 640,
        'height'        : 360,
        'href'          : 'http://vimeo.com/moogaloop.swf?clip_id=30204106',
        'type'          : 'swf'
    });

    $('#thumbs a').click(updateOptionWhenProductImageClicked);
    $('#options select').change(updateImageWhenProductOptionChanged).change();
});
