$(document).ready(function () {

  $('.slideshowCtrl').each(function(){
    $(this).html('<a id="' + this.id + '_prev" href="#">&lt; Prev</a> ' +
                 '<a id="' + this.id + '_pause" href="#">Pause</a> ' +
                 '<a id="' + this.id + '_resume" href="#">Resume</a> ' +
                 '<a id="' + this.id + '_next" href="#">Next &gt;</a>');
    $("a#" + this.id + "_resume").hide();
  })


  $("a[id$='_pause']").click(function(){

    var parentId = $(this).parent().get(0).id;
    $("div.slideshow#" + parentId).cycle('pause');
    $("a#" + parentId + "_pause").hide();
    $("a#" + parentId + "_resume").show();
    return false;

  });

  $("a[id$='_resume']").click(function(){

    var parentId = $(this).parent().get(0).id;
    $('div.slideshow#' + parentId).cycle('resume');
    $("a#" + parentId + "_resume").hide();
    $("a#" + parentId + "_pause").show();
    return false;

  });



});

$(window).load(function() {

  $('.slideshow').each(function(){
    var prevStr = "#" + this.id + "_prev";
    var nextStr = "#" + this.id + "_next";

    $(this).cycle({
      fx: 'fade',
      speed: 'fast',
      timeout: 5000,
      prev: prevStr,
      next: nextStr,
      before: onBefore,
      after: onAfter
    })

    var newHeight = $(this).height()
    var newWidth = 0;

    $(this).children().each(function(){
      newHeight = ( $(this).height() > newHeight ) ? $(this).height() : newHeight
      newWidth = ( $(this).width() > newWidth ) ? $(this).width() : newWidth
    })

    $(this).height(newHeight)
    $(this).children().width(newWidth)

  })

  function onBefore(current, next, opts) {
      var w = $(next).outerWidth();

      $(next).css({
        marginLeft: ($(this).parent().width() - w) / 2
      });
 
  }

  function onAfter() {

    var parentId = $(this).parent().get(0).id;

    if ( $('div.slideshowOutput#' + parentId ).length ) {
      var altContents = $(this).children('img').attr('alt');
      $('div.slideshowOutput#' + parentId).html(altContents);
    }

  }

});


