Shadowbox.init();

// We need to make sure that all webfonts are loaded when calculating the menu.
// Do not put any other new code here unless you have a good reason. Better use
// the DOM-ready event below.
jQuery(window).load(function () {
   
   // navigation ---------------------------------------------------------------
   (function (parent) {
      var
         // Stores all main menu items.
         mainMenuItemElements = $('.main .item a', parent),

         // Stores the container of all submenus.
         subMenuWrapElement = $('.sub', parent),

         // Stores all submenus.
         subMenuElements = $('ul', parent),

         // Stores the height of the submenus.
         subMenuHeight = 0;
      
      // Prepare all submenu items.
      subMenuWrapElement.show();
      
      subMenuElements.show().each(function () {
         var
         self = $(this),
            
         // Stores the associated main menu item.
         mainMenuItemElement = mainMenuItemElements.filter('[rel="' + self.attr('rel') + '"]');
         
         // Determine the highest submenu.
         subMenuHeight = Math.max(subMenuHeight, self.height());
         
         // Adjust the submenu position so that it aligns with its associated
         // main menu item.
         self.css('padding-left', mainMenuItemElement.position().left + 'px');
         
         // Bind main menu item.
         mainMenuItemElement.mouseenter(function () {
            mainMenuItemElements.removeClass('pseudo-active');
            mainMenuItemElement.addClass('pseudo-active');
            subMenuElements.hide();
            self.show();
            subMenuWrapElement.show();
         });
      }).height(subMenuHeight).hide();
      
      subMenuWrapElement.hide();
      
      // Laving the navigation area reverts the menu back to its initial state.
      parent.mouseleave(function () {
         mainMenuItemElements.removeClass('pseudo-active');
         subMenuWrapElement.hide();
      });
   }($('#head .nav')));
});

// The DOM is ready.
jQuery(function ($) {
   
   // history back helper ------------------------------------------------------
   (function (parent) {
      // Hide the back button if the user does not have a place to go to.
      if (window.history.length === 1) {
         parent.hide();
      } else {
         // Issue a step back in the browser history.
         parent.click(function (e) {
            e.preventDefault();
            window.history.back();
         });
      }
   }($('a.history-back')));
   
   // search -------------------------------------------------------------------
   (function (parent) {
      var queryInputElement = $('.query', parent),
         defaultValue = queryInputElement.attr('title');
      
      // Apply default value.
      queryInputElement.defaultValuedInput(defaultValue);
      
      // Look out for submit attempts.
      parent.submit(function () {
         var query = queryInputElement.val();
         
         // It does not make sense to submit an empty query or the default
         // value. Do nothing in that case, continue otherwise.
         return query && query !== defaultValue;
      });
   }($('#head .search')));
   
   // special home mediabox (cleaner, smarter, faster, shorter, better! :D
   $('.mediabox_auto').each(function() {
      var children = $(this).children();
      children.css('position', 'absolute');
      $(this).css({
         position: 'relative',
         height: children.eq(0).height()
      });
      var position = 0;
      children.eq(position).show();
      window.setInterval(function() {
         var now = children.eq(position);
         position++;
         if (position == children.length) {
            position = 0;
         }
         var next = children.eq(position);
         now.css('z-index', 0);
         next.css('z-index', 1).fadeIn(function() {
            now.hide();
         });
      }, 5000);
   });
   
   // mediabox -----------------------------------------------------------------
   $.each(getData('mediabox'), function (uuid, mediabox) {
      $('.mediabox[rel="' + uuid + '"]').each(function () {
         var
            self = $(this),

            // Stores the link that wraps the image.
            linkElement = $(document.createElement('a')).click(function (e) {
               if (linkElement.attr('href') === '#') {
                  e.preventDefault();
               }
            }),

            // Stores the actual image.
            imageElement = $(document.createElement('img')).appendTo(linkElement),

            // These are the actual slider component elements.
            sliderWrapElement = $(document.createElement('div')).addClass('slider-wrap'),
            leftButtonElement = $(document.createElement('div')).addClass('left-button'),
            rightButtonElement = $(document.createElement('div')).addClass('right-button'),
            sliderElement = $(document.createElement('div')).addClass('slider'),
            sliderContentElement = $(document.createElement('div')).addClass('slider-content'),

            // Holds the width of the slider contents.
            sliderContentWidth = 0,

            /**
             * Populates the viewport.
             */
            populate = (function () {
               var
               // Stores the URL of an image until it is loaded to detect
               // interfering load processes.
               currentUrl = null;

               return function (item) {
                  var
                  // Stores the URL of the resized image.
                  url = 'http://data.heimat.de/transform.php?file=' + encodeURIComponent(item.pic) + '&width=630&height=400&do=cropOut',

                  // Stores an image object for loading detection.
                  imgObj = new Image();

                  // If the current URL is still the one of this item, we can
                  // safely show it without destroying another image being
                  // loaded currently.
                  currentUrl = item.pic;

                  // Hide the image until it is loaded.
                  imageElement.hide();

                  // Wait for the image to load.
                  $(imgObj).load(function () {
                     // Only show this image if there is no other one being
                     // loaded instead.
                     if (currentUrl === item.pic) {
                        imageElement
                           .attr('alt', item.title || '')
                           .attr('src', url)
                           .attr('title', item.title + " - " + item.copyright_value)
                           .show();

                        currentUrl = null;
                     }
                  });

                  // Apply URL.
                  imgObj.src = url;
                  
                  // Apply link URL.
                  linkElement.toggleClass('empty-link', !item.url).attr('href', item.url ? item.url : '#');
               };
            }()),

            /**
             * Manages the horizontal slider scroll position.
             */
            move = (function () {
               var
               // Holds the animation interval.
               animationTimer = null,

               // Holds the current horizontal velocity.
               velocity = 0,

               // Holds some constants for easy tweaking.
               options = {
                  force:       0.5, // pixels to add per acceleration step
                  friction:    0.5, // pixels to substract per deceleration step
                  maxVelocity: 8    // maximum pixels to move per step (regardless of direction)
               },

               /**
                * Ensures that the animation timer is not running and resets
                * the handle.
                */
               clearTimer = function () {
                  if (animationTimer !== null) {
                     clearInterval(animationTimer);
                     animationTimer = null;
                  }
               };

               return function(direction) {
                  clearTimer();

                  animationTimer = setInterval(function() {
                     if (direction < 0) { // left
                        velocity = Math.max(velocity - options.force, -options.maxVelocity);
                     } else if (direction > 0) { // right
                        velocity = Math.min(velocity + options.force, options.maxVelocity);
                     } else if (velocity < 0) { // stop
                        velocity = Math.min(velocity + options.friction, 0);
                     } else if (velocity > 0) { // stop
                        velocity = Math.max(velocity - options.friction, 0);
                     } else {
                        clearTimer();
                     }

                     sliderElement.scrollLeft(sliderElement.scrollLeft() + Math.round(velocity));
                  }, 16);
               };
            }());
         
         // Create viewport.
         $(document.createElement('div'))
            .addClass('viewport')
            .append(linkElement)
            .appendTo(self);
         
         // Check if a slider is required.
         if (mediabox.length > 1) {
            sliderWrapElement
               .append(leftButtonElement)
               .append(rightButtonElement)
               .append(sliderElement)
               .appendTo(self);
                
            // Reset slider and add the slider to the system.
            sliderElement.scrollLeft(0).append(sliderContentElement);
            
            // Create all slider items.
            $.each(mediabox, function (index, item) {
               var
               // Stores the clickable thumbnail image.
               thumbnailElement = $(document.createElement('img'))
               .attr('src','http://data.heimat.de/transform.php?file=' + encodeURIComponent(item.pic) + '&width=100&height=60&do=cropOut')
               .click(function () {
                  populate(item);
               });
               
               // We need to add separators between all items.
               if (index > 0) {
                  $(document.createElement('div'))
                  .addClass('separator')
                  .appendTo(sliderContentElement);
               }
               
               // Add the thumbnail to the slider.
               thumbnailElement.appendTo(sliderContentElement);
            });
            
            // Determine slider content width.
            sliderContentElement.children().each(function () {
               sliderContentWidth += $(this).outerWidth();
            });
            
            // Check if there is enough space for the slider.
            if (sliderElement.width() >= sliderContentWidth) {
               // Hide buttons if there is no sliding needed.
               leftButtonElement.hide();
               rightButtonElement.hide();
            } else {
               // Bind buttons.
               $().add(leftButtonElement).add(rightButtonElement).css('opacity', 0.8).mouseleave(function (e) {
                  e.preventDefault();
                  move(0);
               });
               
               leftButtonElement.mouseenter(function (e) {
                  e.preventDefault();
                  move(-1);
               });
               
               rightButtonElement.mouseenter(function (e) {
                  e.preventDefault();
                  move(1);
               });
            }
            
            sliderContentElement.width(sliderContentWidth);
         }

         // Initialize with the first item.
         populate(mediabox[0]);
      });
   });
   
   // collapsible --------------------------------------------------------------
   $('.collapsible').each(function () {
      var
      // Stores the triggered element.
      contentElement = $('.collapsible-content', this),

      // Stores the element that triggers opening the content.
      openTriggerElement = $('.collapsible-trigger-open', this),

      // Stores the element that triggers closing the content.
      closeTriggerElement = $('.collapsible-trigger-close', this);

      // Hide the content initially. We are doing this in JavaScript so that a
      // user without it is still able to see all the content.
      contentElement.hide();
      closeTriggerElement.hide();

      // Toggle the visibility of the content in a fancy way.
      openTriggerElement.click(function (e) {
         e.preventDefault();
         contentElement.stop().slideDown(1000);
         openTriggerElement.hide();
         closeTriggerElement.show();
      });
      
      closeTriggerElement.click(function (e) {
         e.preventDefault();
         contentElement.stop().slideUp(1000);
         openTriggerElement.show();
         closeTriggerElement.hide();
      });
   });
   
   $('.toggleable').each(function () {
      var
      // Stores the detailed element.
      openContentElement = $('.toggleable-content-open', this),
         
      // Stores the summary element.
      closedContentElement = $('.toggleable-content-closed', this),

      // Stores the element that triggers opening the content.
      openTriggerElement = $('.toggleable-trigger-open', this),

      // Stores the element that triggers closing the content.
      closeTriggerElement = $('.toggleable-trigger-close', this);

      // Hide the content initially. We are doing this in JavaScript so that a
      // user without it is still able to see all the content.
      openContentElement.hide();
      closeTriggerElement.hide();

      // Toggle the visibility of the content in a fancy way.
      openTriggerElement.click(function (e) {
         e.preventDefault();
         openContentElement.show();
         closedContentElement.hide();
         openTriggerElement.hide();
         closeTriggerElement.show();
      });
      
      closeTriggerElement.click(function (e) {
         e.preventDefault();
         openContentElement.hide();
         closedContentElement.show();
         openTriggerElement.show();
         closeTriggerElement.hide();
      });
   });

   // comment paging
   
   (function () {
      var parent,
      chunks,
      chunksParent;

      parent = $('.comment-entries-container');
      chunksParent = $('.comment-paging');

      // Are we on the correct page?
      if (parent.length > 0) {
         chunks = parent.find('.comment-entry-chunk');

         // Is paging needed?
         if (chunks.length > 1) {
            chunks.each(function (index, chunk) {
               $('<a class="item" href="#">'+(index + 1)+'</a>').appendTo(chunksParent).click(function () {
                  $(this).addClass('active').siblings().removeClass('active');
                  chunks.hide();
                  $(chunk).show();
               });
            });

            chunksParent.find('.item:first').click();
         }
      }
   }());
      
   // gaestebuch
      
   $('.gaestebuch-form-toggle').click(function(){
      $('.comment-inserted').hide();
      $('#gaestebuch-form').toggle();
   });
      
   $('#gaestebuch-form').submit(function(){
      var t = $(this);
      var valid = true;
      $('#gaestebuch-form .input-required').removeClass('input-error');
      $('#gaestebuch-form .input-required').each(function(){
         if($(this).val() == '') {
            $(this).addClass('input-error');
            valid = false;
         }
      });
      if(valid) {
         $.post(getData('document_root')+'/ajax.php?action=gaestebuch_submit', t.serializeArray(), function (data) {
            if (data.status === 'success') {
               t.hide();
               $('.comment-inserted').show();
            }
            else
               alert('insert failed!');
         }, 'json');
      }
      return false;
   });
      
   $('.mitgehzentrale-form-toggle').click(function(){
      $('.comment-inserted').hide();
      $('#mitgehzentrale-form').toggle();
   });
      
   $('#mitgehzentrale-form').submit(function(){
      var t = $(this);
      var valid = true;
      $('#mitgehzentrale-form .input-required').removeClass('input-error');
      $('#mitgehzentrale-form .input-required').each(function(){
         if($(this).val() == '') {
            $(this).addClass('input-error');
            valid = false;
         }
      });
      if(valid) {
         $.post(getData('document_root')+'/ajax.php?action=mitgehzentrale_submit', t.serializeArray(), function (data) {
            console.info(data);
            if (data.status === 'success') {
               t.hide();
               $('.comment-inserted').show();
            }
            else
               alert('insert failed!');
         }, 'json');
      }
      return false;
   });
      
   $('.mitgehzentrale-form-unsubscribe-toggle').click(function(){
      $('.form-unsubscribe-sent').hide();
      $('#mitgehzentrale-form-unsubscribe').toggle();
   });
      
   $('#mitgehzentrale-form-unsubscribe').submit(function(){
      var t = $(this);
      var valid = true;
      $('#mitgehzentrale-form-unsubscribe .input-required').removeClass('input-error');
      $('#mitgehzentrale-form-unsubscribe .input-required').each(function(){
         if($(this).val() == '') {
            $(this).addClass('input-error');
            valid = false;
         }
      });
      if(valid) {
         $.post(getData('document_root')+'/ajax.php?action=mitgehzentrale_unsubscribe', t.serializeArray(), function (data) {
            if (data.status === 'success') {
               t.hide();
               $('.form-unsubscribe-sent').show();
            }
            else
               alert('form error!');
         }, 'json');
      }
      return false;
   });

   //different margins for fixed images, also in case of existing headlines
   $('.content > img').addClass('fixed-img');
   $('.content > h3 + img,.content > h4 + img').removeClass('fixed-img').addClass('fixed-img-headline');

   //styling sitzplan numbers
   $('#karten .content strong').each(function(){
      if($(this).html()=='1') {
         $(this).addClass('group_1').addClass('number_plan');
      }
      else if($(this).html()=='2') {
         $(this).addClass('group_2').addClass('number_plan');
      }
      else if($(this).html()=='3') {
         $(this).addClass('group_3').addClass('number_plan');
      }
      else if($(this).html()=='4') {
         $(this).addClass('group_4').addClass('number_plan');
      }
      else if($(this).html()=='5') {
         $(this).addClass('group_5').addClass('number_plan');
      }
   });
   // styling comment-paging, delete border on last item
   $('.comment-paging').each(function(){
      $(this).children('.item:last').css('border','none');
   });
   //styling entries, delete border on last item
   $('.comment-entry-chunk').each(function(){
      $(this).children('.comment-entry:last').css('border','none');
   });
   //fake ticket buttons please delete this after relaunch
   $('.sidebar a').each(function() {
      if($(this).html()=="Ticket") {
         $(this).addClass('icon-ticket').attr('alt', $(this).html()).html('');
      }
   });
    
   $('.iGotMetaText a').click(function (e) {
      var self = $(this),
      parent = self.closest('.iGotMetaText');
       
      e.preventDefault();
       
      self.hide();
      parent.find('.teaser').hide();
      parent.find('.text').show();
   });
    
   //detail image slideshow stuff thing something
   $('.innerContent img').click(function() {
      var text = $(this).parents('.videoEntryBox').find('.metaInfo').html();
       
      var descr = $(this).parents('.videoEntryBox').find('.metaText').html();
      $('.iGotMetaInfo').html(text);
       
      $('.iGotMetaText .teaser').show();
      $('.iGotMetaText .text').hide();
       
      if (descr && descr.length > 0) {
         $('.iGotMetaText a').show();
         $('.iGotMetaText .teaser').html(descr.substr(0, 200) + '...');
         $('.iGotMetaText .text').html(descr);
      } else {
         $('.iGotMetaText a').hide();
         $('.iGotMetaText .teaser').html('');
         $('.iGotMetaText .text').html('');
      }
      if ($(this).hasClass('video')) {
         $('.largeImage').html('<div class="__CbUiPlayer"></div>');
         CbPlayerWindow.create($('.largeImage'), {
            "callback": "/player40/",
            "config": "theaterbremen",
            "movie_id": $(this).attr('alt').split('.').pop()
         });
      } else {
         var src = $(this).attr('src');
         src = src.replace('width=100', 'width=630');
         src = src.replace('height=50', 'height=400');
         var image = $(document.createElement('img'));
         image.attr('src', src)
         $('.largeImage').html(image);
      }
   }).each(function() {
      //preload
      var src = $(this).attr('src');
      src = src.replace('width=100', 'width=630');
      src = src.replace('height=50', 'height=400');
      var image = $(document.createElement('img'));
      image.attr('src', src)
   //we have the first item...
   }).eq(0).each(function() {
      //save the info we need
      if ($(this).hasClass('video')) {
         var timestamp = $(this).attr('alt').split('.').shift();
         var possibles = $(this).parents('.innerContent').find('img[alt^='+timestamp+']');
         var random = Math.floor(Math.random() * possibles.length);
         $(possibles).eq(random).click();
      } else {
         $(this).click();
      }
   });

   var isSliding = false;
   $('.scrollRight').click(function() {
      if (!isSliding) {
         isSliding = true;
         var right = 630;
         if ((parseInt($(this).siblings('.innerContent').css('left'))-right) <= (-1 * ($(this).siblings('.innerContent').width() - $(this).parent().width()))) {
            right = -1* (-1 * ($(this).siblings('.innerContent').width() - $(this).parent().width()) - parseInt($(this).siblings('.innerContent').css('left')));
            $(this).hide();
         }
         $(this).siblings('.scrollLeft').show();
         $(this).siblings('.innerContent').animate({
            'left': '-='+right+'px'
         }, 500, 'linear', function() {
            isSliding = false;
         });
      }
   }).siblings('.scrollLeft').click(function() {
      if (!isSliding) {
         isSliding = true;
         var right = 630;
         if (parseInt($(this).siblings('.innerContent').css('left'))+right >= 0) {
            right = -1 * parseInt($(this).siblings('.innerContent').css('left'));
            $(this).hide();
         }
         $(this).siblings('.scrollRight').show();
         $(this).siblings('.innerContent').animate({
            'left': '+='+right+'px'
         }, 500, 'linear', function() {
            isSliding = false;
         });
      }
   });
   $('.playIcon').click(function() {
      $(this).siblings('img').click();
   });
});

