/* requires jQuery 1.3.2+
 * handles the animation of the accesories gallery and pop-up of larger images
 */

var SCROLL_TIMER = null;
var IS_SCROLLING = false;
var MOVE_LEFT = true;
var LARGE_IMAGES = [];

$(document).ready(function() {
    // remove the left margin off the first item:
    $('#accessoriesGallery li:first').css({'margin-left': 0});
    // remove the right margin off the last item:
    $('#accessoriesGallery li:last').css({'margin-right': 0});
    
    // set up handlers for moving over the gallery:
    $('#accessoriesGallery div').hover(stopScrolling, startScrolling);
    
    // set up the mask opacity:
    $('#mask').css({'opacity': 0.7});
    
    // handle clicking on an image:
    $('#accessoriesGallery a').click(popUpAccessory);
    
    // initiate the scrolling:
    startScrolling();
    doScroll();
    
    // handle mask events:
    $('#mask').mouseover(stopScrolling).click(function() {
        $('#largeAccessory').hide();
        $(this).hide();
        startScrolling();
    });
    
    // pre-cache all the large images:
    $('#accessoriesGallery a').each(function() {
        var href = $(this).attr('href');
        var img = new Image();
        img.src = href;
        LARGE_IMAGES.push(img);
    });
    
    // handle window scroll:
    $(window).scroll(testForCentring).resize(testForCentring);
    
    // handle next and previous:
    $('#goNext').click(showNext);
    $('#goPrev').click(showPrev);
});

function findImage() {
    for (var i=0;i<LARGE_IMAGES.length;i++) {
        if (LARGE_IMAGES[i].src.endswith($('#imageHolder img').attr('src'))) {
            return i;
        }
    }
    return -1;
}

function showNext() {
    var currentImage = findImage();
    if (currentImage == LARGE_IMAGES.length - 1) {
        var newImage = 0;
    }
    else {
        var newImage = currentImage + 1;
    }
    showImage(newImage);
}
function showPrev() {
    var currentImage = findImage();
    if (currentImage == 0) {
        var newImage = LARGE_IMAGES.length - 1;
    }
    else {
        var newImage = currentImage - 1;
    }
    showImage(newImage);
}
function showImage(index) {
    var large = $('#largeAccessory');
    large.fadeOut('fast', function() {    
        large.children('#imageHolder').html('<img src="'+LARGE_IMAGES[index].src+'" />');
        centrePopUp();
        large.fadeIn('fast');
    });
}

function testForCentring() {
    if ($('#largeAccessory:visible').length > 0) {
        centrePopUp();
    }
}

function doScroll() {
    // only do work if we're supposed to be scrolling:
    if (IS_SCROLLING) {
        // get the current left of the ol:
        var currentLeft = parseInt($('#accessoriesGallery ol').css('left').rstrip('px'));
        
        // determine which way we want to scroll:
        if (currentLeft >= 0) {
            MOVE_LEFT = true;
        }
        
        // make sure the last image isn't going to scroll too far:
        var lastImage = $('#accessoriesGallery li:last');
        var lastRight = lastImage.offset().left - $('#accessoriesGallery div').offset().left + lastImage.width();
        
        if (lastRight <= $('#accessoriesGallery div').width()) {
            MOVE_LEFT = false;
        }
        
        var newLeft = MOVE_LEFT ? currentLeft - 1: currentLeft + 1;
        
        $('#accessoriesGallery ol').css({'left':newLeft});
    }
    
    SCROLL_TIMER = window.setTimeout(doScroll, 50);
}
function startScrolling() {
    IS_SCROLLING = true;
}
function stopScrolling() {
    IS_SCROLLING = false;
}

function popUpAccessory(e) {
    if ($.browser.msie && $.browser.version < 7) {
        // IE 6 and less should just open the image in a new tab
        return true;
    }
    e.preventDefault();
    
    $('#mask').show();
    var large = $('#largeAccessory');
    large.children('#imageHolder').html('<img src="'+$(this).attr('href')+'" />')
    
    // centre the div:
    centrePopUp();
    
    large.fadeIn();
    return true;
}
function centrePopUp() {
    var large = $('#largeAccessory');
    var win = $(window);
    var left = Math.floor((win.width() - large.width()) / 2) + 'px';
    var top = Math.floor(((win.height() - large.height()) / 2) + $(document).scrollTop()) + 'px';
    large.css({'top':top, 'left': left});
    
    var prev = $('#goPrev');
    var next = $('#goNext');
    var prevTop = Math.floor(((large.height() - 128) / 2)) + 'px';
    var nextTop = Math.floor(((large.height() - 128) / 2)) + 'px';
    prev.css({'top':prevTop});
    next.css({'top':nextTop});
}

/* utility functions */

function rstrip(chars) {
    /* S.rstrip([chars]) -> string
    
    Return a copy of the string S with trailing whitespace removed.
    If chars is given and not null, remove characters in chars instead.
    */
    if (chars === undefined) {
        re = /\s+$/;
    }
    else {
        re = new RegExp('['+chars+']+$');
    }
    return this.replace(re, '');
}

function endswith(suffix) {
    /* S.endswith(suffix) -> bool
    
    Return true if S ends with the specified suffix, false otherwise.
    */
    return this.substr(this.length-suffix.length) == suffix;
}

String.prototype.rstrip = rstrip;
String.prototype.endswith = endswith;