var image_href_from_thumb = function(thumb) { 
    return thumb.src.replace(/\/thumbs/i, ''); 
}

var preload = function(image) {
    img = $j(new Image());
    img.attr('src', image);
    img.hide();
};

var open_modal_slideshow = function(hash){ 
    thumbs = $j(hash.t).parents('ul').find('li img');
    
    startingSlide = $j(hash.t).parents('ul').find('li img').index($j(hash.t));
    
    /* Pull the image hrefs out of the slideshow li's and shove them in the modal dialog div
    This relies on a structure of the thumbnail dir. (thumbs/) living inside the full size directory and the files have the same names. (e.g. full size: foo/image.png | thumb: foo/thumbs/image.png)
    */
    slides = ""; thumbs.each(function(index) { 
        slides += "<img src=" + image_href_from_thumb(this) + " />";
    });
    slideshow = $j('<div></div>').attr('class', 'slideshow').append(slides);
    hash.w.find('.contents').html(slideshow);
    hash.w.find('.contents').append($j('<div></div>').attr('class', 'slideshow-nav'));
    slideshow = hash.w.find('.slideshow');
    slideshow.css("height", "100%");

    hash.w.show();
    
    slideshow.cycle({
        fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
        timeout: 0,
        speed: 600,
        startingSlide: startingSlide,
        pager: '.slideshow-nav',
        before: function (curr,next,opts) { // Center the image
            var $slide = $j(next);
            var w = $slide.outerWidth();
            var h = $slide.outerHeight();
            $slide.css({
                marginTop: (slideshow.height() - h) / 2,
                marginLeft: (slideshow.width() - w) / 2
            });
        },
        pagerAnchorBuilder: function(i, el) {
            return '<a href="#"><img src="/m/images/p.gif"/></a>';
        }
    });
};

var open_modal_video = function(hash){
    href = $j(hash.t).siblings('link').get(0).href;
    hash.w.find('.contents').html("").flash({
        swf: href,
        expressInstaller: '/m/scripts/expressInstall.swf',
    	height: 420,
    	width: 620
    });
    hash.w.show();
};

$j(document).ready(function() {
    // Setup image slideshow modal window
    $j(this).find('.jqmWindow.image').jqm({modal: true, trigger: 'ul.image.thumbnails li img',
        closeClass: 'close', overlay: 65, onShow: open_modal_slideshow});

    // Setup video modal window
    $j(this).find('.jqmWindow.video').jqm({modal: true, trigger: 'ul.video.thumbnails li img',
        closeClass: 'close', overlay: 65, onShow: open_modal_video}); 

    // preload slideshow images
    $j.each(['/m/images/layout/close_button.png',
        '/m/images/layout/slide_nav_selected.png',
        '/m/images/layout/slide_nav.png',
        '/m/images/p.gif'], function(index, href) { preload(href) });
     
    $j('ul.image.thumbnails li img').each(function(i) { preload(image_href_from_thumb(this)) });
});