var productID, imageFace, currentSwatch, testImage;

$(function(){

    productID = $('#ProductID').val();
    setSwatch();
    testImage = $('<img />');

    if ($('#HasBackImage').val() == 'false') {
        $('#FaceToggle #Back').after('<a class="disabled">Back</span>').remove();
    }

    function highlight(swatch) {
        var swatchElement = $('div.swatches .swatch[title='+swatch.replace("_", " ")+']');
        var color = swatchElement.attr('alt');
      //Change border of active swatch by changing the class
        $('div.swatches .swatch').removeClass('active');
        swatchElement.addClass('active');
        setSwatch();
        changeImage();
    }

    highlight($('select#ProductColor').val());

    function setSwatch() {
        currentSwatch = {
                name:   $('div.swatches .swatch.active').attr('title'),
                file:   $('div.swatches .swatch.active').attr('alt')
        };
    }

    function changeImage() {
        var colorName = currentSwatch.file.substring(0, currentSwatch.file.length-4);        
        if ($('#CurrentFace').val() == 'Front') {            
            testImage.attr('src', '/img/products/large/'+productID+'_'+colorName+'.jpg');
        }
        else if ($('#CurrentFace').val() == 'Back') {
            testImage.attr('src', '/img/products/back/large/'+productID+'_'+colorName+'.jpg');
        }
    }

    $('div.swatches .swatch').click(function(){
        if ($(this).is('.active')) { return true; }
        $('select#ProductColor').val( $(this).attr('title').replace("_", " ") );
        highlight($(this).attr('title'));
    });

    $('select#ProductColor').change(function(){
        highlight($(this).val());
    });    

    testImage.error(function(){
        var src = $(this).attr('src');
        if (src != '/img/products/large/'+productID+'.jpg' && testImage.notAvailable != true) {
            $(this).attr('src', '/img/products/large/'+productID+'.jpg');
        }
        else {
            testImage.notAvailable = true;
            $(this).attr('src', '/img/products/large/not_available.jpg');
        }
    });

    testImage.load(function(){
        $('#ProductImage').attr('src', $(this).attr('src'));
    });

/*------------------------------------------------------------------------------
    Front/Back image toggle
*/
    $('#FaceToggle a.toggle').click(function(){
        if ($(this).is('.active')) {
            return true;
        }
        $('#FaceToggle a.toggle').removeClass('active');
        $(this).addClass('active');
        $('#CurrentFace').val($(this).attr('id'));
        changeImage();
    });
    $('#FaceToggle #'+$("#CurrentFace").val()).trigger('click'); //if page is reloaded, revert to previous image


});