if( window.console === undefined ) {
    window.console =  {};
    window.console.log = function() {};
}

var AMSK = AMSK || {};

AMSK.slideshow = function(id, interval, width) {
    var $imgs = [], heights = [], $div = $("#" + id), curImg = 0, h = 0;

    if( width ) {
        $div.width( width );
    }

    $("#" + id + " img").each( function() {

        function storeImage( img ) {
            var $img = $(img);
            $imgs.push( $img );
            $img.css("margin", "0px");
            $img.css("border", "0px");
            $img.css("padding", "0px");

            if( h < $img.height() ) {
                h = $img.height();
            }
            if( width && $img.width() > width ) {
                $img.width( width );
            }
            heights.push( $img.height() );

            (function( $this ) {
                $(window).resize( function() {
                    $this.css("margin-left", 
                              ($div.width() - $this.width()) / 2 +  "px");
                }).trigger("resize");
            })( $img );
            
            $img.hide();
        }

        if( this.complete ) {
            storeImage(this);
        } else {
            $(this).load( function() {
                storeImage(this);
            });
        }
    });
    
    function showNext() {
        if( $imgs.length == 0 ) {
            setTimeout( showNext, 100 ); // come back fast
            return;
        }

        var $img = $imgs[curImg],
            $last = $div.find("img:visible");

        function showImg() {
            $div.height( h + "px" );
            $img.css( "margin-top", ((h - heights[curImg]) / 2) + "px" );
            $img.fadeIn( function() {
                             curImg = (curImg + 1) % $imgs.length;
                             setTimeout( showNext, interval );
                         });
        }

        if( $last.length ) {
            $last.fadeOut( showImg );
        } else {
            showImg();
        }
    }

    showNext();
};

AMSK.fixExternalLinks = function() {
  $("#content a[href^=http]")
        .filter( function () {
                     return $(this).children( "img" ).length == 0;
                 })
        .addClass( "offsite-link" )
        .attr("target", "_blank");
};

$(AMSK.fixExternalLinks);
