var GALLERYIMAGEDIVSIZE = {width: 460, height: 460};

var GBFORMSPEED = 400;

// init effects
$(document).ready(function(){
  if($.flashPlayerVersion[0] >= 7) { // only enable mp3 player if flash higher or equal to 7 is installed
    if(!$('ul.playlist').hasClass('ie') && $('ul.playlist li').size() > 0) {
      insertPlayer();
      initPlayer();
    } else {
      //initIEPlayer();
    }
  }
  $(document).pngFix();
  initGallery();
  if($("div#gbform").size() > 0) initGuestbook();
});

/**
* Gallery
*/
function initGallery() {
  
  // image navigation
  enableImageNavigation($("div.galleryimage>img").attr('src'));
  bindImageNavigationEvents();
  
  // load first image
  $("div.galleryimage>img").hide();
  
  $("div.galleryimage>img").load(function() {
    adjustImageMargins(this);
    $(this).fadeIn("fast");
  });
  adjustImageMargins($("div.galleryimage>img").get(0));
  $("div.galleryimage>img").fadeIn("fast");
  
  // random image access from the thumbnail list
  $("ul.gallerythumbnaillist>li>a").click(function() {
    loadNewImage($(this).attr('rel'));
    var targetOffset = $("h2#galleryimagetitle").offset().top;
    $('html,body').animate({scrollTop: targetOffset}, GBFORMSPEED);
    return false;
  });
} // end initGallery()

function adjustImageMargins(image) {
  // get width and height of the image
  var w = $(image).width();
  var h = $(image).height();

  // calculate top and left margins
  var top = (GALLERYIMAGEDIVSIZE.height - h)/2;
  var left = (GALLERYIMAGEDIVSIZE.width - w)/2;
  
  // reset css properties 
  $(image).css({position: 'relative', top: top + "px", display: 'inline'});
} // end adjustImageMargins(image)

function loadNewImage(url) {
  // create new image
  var img = new Image();
    
  // if new image is loaded, perform effects
  $(img).load(function() {

    // set the image hidden by default
    $(this).hide();
    
    // store image object in div
    $.data($("div.galleryimage").get(0), "newimage", this);
    
    // fade out and remove old image and fade in new image
    $("div.galleryimage>img").fadeOut("fast", function() {
      $(this).remove();
      var newimage = $.data($("div.galleryimage").get(0), "newimage");
     
      // append new image
      $("div.galleryimage").append(newimage);
      
      // adjust the margins to display it centered
      adjustImageMargins(newimage);
      
      // fade in image
      $(newimage).fadeIn("fast");
    });
    
    // reload image navigation
    enableImageNavigation(url);
  }).attr({src: url});
} // end loadNewImage(url)

function enableImageNavigation(url) {
  // get the thumbnail link for this image
  var thumbLink = $('ul[@class="gallerythumbnaillist"]>li>a[@rel="'+ url +'"]');
  
  // get the number of the image and write info line
  var imageNo = $("ul.gallerythumbnaillist li").index(thumbLink.parent().get(0)) + 1;
  var span = $("h2#galleryimagetitle").find('span');
  $("h2#galleryimagetitle").text('Bild ' + imageNo + ' von ' + $("ul.gallerythumbnaillist li").size());
  $("h2#galleryimagetitle").append(span);
  
  // set visibility of controls
  if(thumbLink.parent().prev().size() == 0) { // if there is no previous image, disable previous button
    $("a#imageprevlink").css({visibility: 'hidden'});
  } else {
    $("a#imageprevlink").css({visibility: 'visible'});
  }
  if(thumbLink.parent().next().size() == 0) { // if there is no next image, disable next button
    $("a#imagenextlink").css({visibility: 'hidden'});
  } else {
    $("a#imagenextlink").css({visibility: 'visible'});
  }
  
  // bind events
  bindImageNavigationEvents();
} // end enableImageNavigation(url)

function bindImageNavigationEvents() {
  $("a#imageprevlink").click(function() {
    var url = $('ul[@class="gallerythumbnaillist"]>li>a[@rel="'+ $("div.galleryimage>img").attr('src') +'"]')
              .parent()
              .prev()
              .find('a')
              .attr('rel');
    loadNewImage(url);
    return false;
  });
  
  $("a#imagenextlink").click(function() {
    var url = $('ul[@class="gallerythumbnaillist"]>li>a[@rel="'+ $("div.galleryimage>img").attr('src') +'"]')
              .parent()
              .next()
              .find('a')
              .attr('rel');
    loadNewImage(url);
    return false;
  });
} // end bindImageNavigationEvents()

/**
* Guestbook
*/
function initGuestbook() {
  var showOnInit = ($("div#gbform ul.error").size() > 0) ? true : false;
  $.data($("div#gbform").get(0), "form", $("div#gbform").html());
  $("div#gbform").html('<a href="#" class="createentry">Eintrag schreiben</a>');
  $("a.createentry").click(showGBForm);
  if(showOnInit > 0) {
    showGBForm();
  }
} // end initGuestbook()

function showGBForm() {
    $("div#gbform").slideUp(GBFORMSPEED/4, function() {
      $("div#gbform").html($.data($("div#gbform").get(0), "form"));
      if($.browser.msie) {
        $("div#gbform").show(GBFORMSPEED, function() {
          $("input#cancel").click(hideGBForm);
        });
      } else {
        $("div#gbform").slideDown(GBFORMSPEED, function() {
          $("input#cancel").click(hideGBForm);
        });
      }
      var targetOffset = $("div#gbform").prev().offset().top;
      $('html,body').animate({scrollTop: targetOffset}, GBFORMSPEED);
      $("input#gbook_name").focus();
    });
    return false;
} // end showGBForm()

function hideGBForm() {
  $("div#gbform").slideUp(GBFORMSPEED, function() {
    $("div#gbform").html('<a href="#" class="createentry">Eintrag schreiben</a>');
    $("a.createentry").click(showGBForm);
    $("div#gbform").slideDown(GBFORMSPEED/4);
  });
  return false;
} // end hideGBForm()

/**
* Player
*/

function insertPlayer() {
  $("body").append('<div>' +
                   '<object class="playerpreview" id="playerflash" type="application/x-shockwave-flash" data="templates/flash/player_mp3_js.swf" width="1" height="1">' +
                   '<param name="movie" value="templates/flash/player_mp3_js.swf" />' +
                   '<param name="AllowScriptAccess" value="always" />' +
                   '<param name="FlashVars" value="listener=myListener&amp;interval=500" />' +
                   '</object>' +
                   '</div>');
} // end insertPlayer()

function initPlayer() {
  // show player for first list item (but don't play at startup)
  showPlayer($("ul.playlist li a:first").get(0), false);
  
  // trigger other list items to show player and start playing on click
  $("ul.playlist li:gt(0) a").click(function() {
    // hide all other players
    $("ul.playlist li").each(function() {
      hidePlayer(this);
    });
    // show player and start playing
    showPlayer(this, true);
    return false;
  });
} // end initPlayer()

function initIEPlayer() {
  // show player for first list item (but don't play at startup)
  showIEPlayer($("ul.playlist li a:first").get(0), false);
  
  // trigger other list items to show player and start playing on click
  $("ul.playlist li:gt(0) a").click(function() {
    // hide all other players
    $("ul.playlist li").each(function() {
      hideIEPlayer(this);
    });
    // show player and start playing
    showIEPlayer(this, true);
    return false;
  });
} // end initIEPlayer()

/*
 * The Player listener
 */
var myListener = new Object();
                
/**
 * Initialisation
 */
myListener.onInit = function() {
  this.position = 0;
};

/**
 * Update
 */
myListener.onUpdate = function() {
  
  // check if sound is playing and set play/pause buttons accordingly
  var isPlaying = (this.isPlaying == "true");
  $("#p1 .play").css({display: (isPlaying)?"none":"block"});
  $("#p1 .pause").css({display: (isPlaying)?"block":"none"});
  
  // set timeline properties
  var timelineWidth = 160;
  
  // set slider properties
  var sliderWidth = 10;
  var sliderPositionMin = 0;
  
  // calculate slider position
  var sliderPositionMax = sliderPositionMin + timelineWidth - sliderWidth;
  var sliderPosition = sliderPositionMin + Math.round((timelineWidth - sliderWidth) * this.position / this.duration);
  
  // avoid overshooting due to rounding errors
  if (sliderPosition < sliderPositionMin) {
      sliderPosition = sliderPositionMin;
  }
  if (sliderPosition > sliderPositionMax) {
      sliderPosition = sliderPositionMax;
  }
  
  // calculate timeline width (loading state)
  var loadingWidth = timelineWidth*this.bytesLoaded/this.bytesTotal;
  
  // set timeline width (indicating loading state)
  $('#p1 .timeline').css({width: loadingWidth+"px"});
  
  // set slider position
  $('#p1 .slider').css({left: sliderPosition+"px"});
};

// player functions
function getFlashObject() {
  return document.getElementById("playerflash");
} // end getFlashObject()

function play() {
  if(typeof arguments[0] == 'string') {
    getFlashObject().SetVariable("method:setUrl", arguments[0]);
  }
  getFlashObject().SetVariable("method:play", "");
  getFlashObject().SetVariable("enabled", "true");
  return false;
} // end play()

function pause() {
  getFlashObject().SetVariable("method:pause", "");
  return false;
} // end pause()

function stop() {
  getFlashObject().SetVariable("method:stop", "");
} // end stop()

function setPosition() {
  var position = document.getElementById("inputPosition").value;
  getFlashObject().SetVariable("method:setPosition", position);
} // end setPosition()

function setVolume() {
  var volume = document.getElementById("inputVolume").value;
  getFlashObject().SetVariable("method:setVolume", volume);
} // end setVolume()

// display player
function showPlayer(aElm, playOnShow) {
  // get li element
  var liElm = $(aElm).parent().get(0);
  // store state in li node
  $.data(liElm, "originalcontent", $(liElm).html());
  $.data(liElm, "mp3url", $(aElm).attr('href'));
  
  // inject html for the player
  $(liElm).html(
    '<div class="player" id="p1">'+
    '  <p>'+ $(aElm).html() +'</p>'+
    '  <div class="button play" title="play"><a href="#"><span>play</span></a></div>'+
    '  <div class="button pause" title="pause"><a href="#"><span>pause</span></a></div>'+
    '  <div class="timeline"><a class="slider" href="#"><span>slider</span></a></div>'+
    '</div>'+
    '<span class="clearleft"></span>'
  );
  
  // trigger buttons
  if(playOnShow) {
    $('#p1 .play').click(play);
  } else {
    $('#p1 .play').click(function() {
      play($.data(liElm, "mp3url"));
      $('#p1 .play').unbind('click');
      $('#p1 .play').click(play);
      return false;
    });
  }
  $('#p1 .pause').click(pause);
  
  // start playback
  if(playOnShow) play($.data(liElm, "mp3url"));
} // showPlayer(aElm, playOnShow)

function hidePlayer(liElm) {
  if($.data(liElm, "originalcontent") != "undefined") {
    $(liElm).html($.data(liElm, "originalcontent"));
    $.removeData(liElm, "originalcontent");
  }
  $(liElm).find("a").click(function() {
    // hide all other players
    $("ul.playlist li").each(function() {
      hidePlayer(this);
    });
    // show player and start playing
    showPlayer(this, true);
    return false;
  });
} // hidePlayer(liElm)

function showIEPlayer(aElm, playOnShow) {
  // get li element
  var liElm = $(aElm).parent().get(0);
  // store state in li node
  $.data(liElm, "originalcontent", $(liElm).html());
  $.data(liElm, "mp3url", $(aElm).attr('href'));
  
  // inject html for the player
  var color = $('body').css('background-color').substring(1);
  $(liElm).html(
     '<div class="player" id="p1">' +
    '  <p>'+ $(aElm).html() +'</p>' +
    '  <object style="margin:0 0 0 10px;" type="application/x-shockwave-flash" data="templates/flash/player_mp3_mini.swf" width="200" height="20">' +
    '    <param name="movie" value="templates/flash/player_mp3_mini.swf" />' +
    '    <param name="bgcolor" value="#ffffff" />' +
    '    <param name="FlashVars" value="mp3=' + $.data(liElm, "mp3url") + '&amp;loadingcolor=' + color + '&amp;buttoncolor=' + color + '&amp;slidercolor=' + color + '" />' +
    '  </object>' +
    '</div>'
  );
  
  // trigger buttons
  if(playOnShow) {
    $('#p1 .play').click(play);
  } else {
    $('#p1 .play').click(function() {
      play($.data(liElm, "mp3url"));
      $('#p1 .play').unbind('click');
      $('#p1 .play').click(play);
      return false;
    });
  }
  $('#p1 .pause').click(pause);
  
  // start playback
  if(playOnShow) play($.data(liElm, "mp3url"));
} // end showIEPlayer(aElm, playOnShow)

function hideIEPlayer(liElm) {
  if($.data(liElm, "originalcontent") != "undefined") {
    $(liElm).html($.data(liElm, "originalcontent"));
    $.removeData(liElm, "originalcontent");
  }
  $(liElm).find("a").click(function() {
    // hide all other players
    $("ul.playlist li").each(function() {
      hidePlayer(this);
    });
    // show player and start playing
    showPlayer(this, true);
    return false;
  });
} // end hideIEPlayer(liElm)