jQuery(function($) {
  $('body').addClass('js');

  initSlideShow();
  externalLinks();
  imageAlt2Title();
  initRemoveConfirmation();
  initDatepickerEvent();
  initDisplayToggle();
  initURLinput();
});


/**
 * Slideshow functions and transitions. 
 **/ 
function initSlideShow ()
{
  if ( $('#slideShow').length === 0 ) return;
  
  var slideShow = $('#slideShow');
  var slides = slideShow.children('div').hide();
  var current = slides.eq(0).show();
  var playing = true;
  
  // Constants
  var FADE_TIME = 1500;
  var SHOW_TIME = 6000;
  var EASING = 'cubicEaseInOut';
  
  // Add Pause / Fwd / Back Buttons
  slideShow.append('<div id="slideShowControls"><a id="slideShowBack" href="#"><span class="hidden">Zurück</span></a> <a id="slideShowPlay" href="#"><span class="hidden">Pause</span></a> <a id="slideShowFwd" href="#"><span class="hidden">Weiter</span></a></div>');
  var slideBack = $('#slideShowBack').click(prev);
  var slidePlay = $('#slideShowPlay').click(playpause);
  var slideFwd = $('#slideShowFwd').click(next);
  
  // Start the slideshow in an interval
  var interval = setInterval(changeSlide, SHOW_TIME);
  
  // Find out the next slide, animate the change
  // and then make the next slide the current one
  function changeSlide (back) {
    var back = back != true ? false : true;
    var next = back ? current.prev(':not(#slideShowControls)') : current.next(':not(#slideShowControls)');
    
    if (! next.length ) {
      next = back ? slides.eq(slides.length-1) : slides.eq(0);
    }
    
    current.fadeOut({duration: FADE_TIME, easing: EASING});
    next.fadeIn({duration: FADE_TIME, easing: EASING});
    current = next;
  }
  
  // Stop Playing and change to the next slide
  function next () {
    pause();
    changeSlide();
    return false;
  }
  
  // Stop Playing and change to the previous slide
  function prev () {
    pause();
    changeSlide(true);
    return false;
  }
  
  function play () {
    changeSlide();
    interval = setInterval(changeSlide, SHOW_TIME);
    slidePlay
      .removeClass('paused')
      .children('span').text('Pause');
    playing = true;
  }
  
  function pause () {
    clearInterval(interval);
    slidePlay
      .addClass('paused')
      .children('span').text('Play');
    playing = false;
  }
  
  // Either Start or Pause Playing
  function playpause () {
    if ( playing ) pause(); // we are playing right now
    else play();            // we are paused
    
    return false;
  }
}


/**
 * Open external links in a new window and set the title accordingly. 
 **/ 
function externalLinks ()
{
  $('a.extern').attr({
    'title': 'Link öffnet in neuem Fenster',
    'target': '_blank'
  });
}


/**
 * For content-images, copy the text from the alt-attribut to the title . 
 **/ 
function imageAlt2Title ()
{
  $('#content img').each(function(index) {
    if ($(this).attr('title').length > 0) return;
    $(this).attr('title',$(this).attr('alt'));
  });
}


/**
 * Display confirmation alert when an item is about to be removed
 **/ 
function initRemoveConfirmation ()
{
  if ( $('.removeItem').length === 0 ) return;
  $('.removeItem').click(function()
  {
    return confirm("Wollen Sie diesen Eintrag wirklich löschen?");
  });
}


/**
 * This function adds a datepicker to the given date input fields 
 */ 
function initDatepickerEvent()
{
  if (! $('#projectform,#eventform').length ) return;
  
  $("#projectform .datepicker,#eventform .datepicker").datepicker({
    changeYear: true,
    changeMonth: true,
    dateFormat: 'd.m.yy',
    dayNames: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
    dayNamesMin: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
    firstDay: 1,
    monthNames: ['Jänner','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
    monthNamesShort: ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
    yearRange: '2010:2030'
  });
}


/**
 * This function toggles the visibility of elements marked with the class "toggle". 
 */ 
function initDisplayToggle()
{
  if (! $('.toggle').length ) return;
  
  /* Hide contents and add toggle switch */
  $('.toggle').hide().each(function(){
    //alert("children: "+$(this).children().size());
    if ($(this).children().size() === 0) return;
    $(this).next('.actionLinks').prepend('[<a class="toggleSwitch" href="#">Details anzeigen</a>]');
  });
  
  /* Map toggle */
  $('.toggleSwitch').click(function()
  {
    var toggleSwitch = $(this);
    var toggleElement = toggleSwitch.parent().prev(".toggle");
    
    if (toggleElement.is(':visible'))
    {
      toggleElement.slideUp(300);
      toggleSwitch.html("Details anzeigen");
    }
    else
    {
      toggleElement.slideDown(300);
      toggleSwitch.html("Details ausblenden");
    }
    return false;
  });
}


/**
 * This function adds the text "http://" to empty URL fields and removes the text onSubmit.
 */ 
function initURLinput()
{
  if (! $('.url').length ) return;
  
  $('.url').each(function()
  {
    if ($(this).val() == "")
    {
      $(this).val("http://")
    }
  });
  
  $('.url').parents("form").submit(function()
  {
    $(this).find('.url').each(function()
    {
      if ($(this).val() == "http://")
      {
        $(this).val("")
      }
    });
  });
}

