// Make use of ECMAScript 5 if available.
if (!String.prototype.trim) {
   String.prototype.trim = function () {
      return this.replace(/^\s+/g, '').replace(/\s+$/g, '');
   };
}

$(document).ready(function () {
   $.ajaxSetup({
      cache: false
   });

   /*
    * Fix IE
    */
   if ($.browser.msie) {
      // IE 6 and lower
      if ($.browser.version < 7) {
         $('img[src$=".png"], #slideshow .logo').ifixpng();
      }

      // IE 7 and lower
      if ($.browser.version < 8) {
         (function (e) {
            e.height(e.height() - 2);
         }($('.side .search input')));
      }
   }

   /*
    * Style fixes
    */
   $('#slideshow .info, .fancy-layer .fancy-shader').css('opacity', 0.92);
   
   /*
    * E-Paper
    */
   $('.epaperSelect select').change(function () {
      var url = document.location.href,
         year = $('option:selected', this).val();
      
      // Try to replace any existing "year"-parameter.
      url = url.replace(/([\?&])year=\d+/g, '$1year='+year);
      
      // Add parameter to the end if there is no existing "year"-parameter.
      if (url == document.location.href) {
         // Use '?' instead of '&' if there are no other parameters.
         url += (url.match(/[&]/) ? '&' : '?')+'year='+year;
      }
      
      // Redirect to new URL if needed.
      if (url != document.location.href) {
         document.location.href = url;
      }
   });
   
   /*
    * Search
    */
   (function () {
      var input; // const

      input = $('input[name="search"]');

      input.defaultValuedInput(input.attr('title')).keypress(function (e) {
         var query; // const

         query = input.val();

         if (query.length > 0 && e.which == 13) { // enter
            document.location.href = LINK_ROOT+'/search/'+encodeURIComponent(query);
         }
      });
   }());

   /*
    * Slideshow
    */
   (function (parent, info, controls, items) {
      var preloadImage, // const
         createItem, // const
         createItemController; // const

      /**
       * Queues an image for loading.
       *
       * @param <string> url Location of the image.
       */
      preloadImage = (function () {
         var images;

         images = [];

         return function (url) {
            var image; // const

            image = new Image();
            images.push(image);
            image.src = url;
         };
      }());

      /**
       * Creates new item and populates it.
       *
       * @param <object> data Data to be inserted.
       * @return <object> Item element.
       */
      createItem = (function () {
         var prototype; // const

         prototype = $(document.createElement('img')).addClass('item');

         return function (data) {
            var item;

            item = prototype.clone();

            item.attr('src', data.url);
            item.attr('title', data.copyright);
            item.attr('alt', data.copyright);

            return item;
         };
      }());

      /**
       * Item controller factory.
       *
       * @return <object> Item controller element.
       */
      createItemController = (function () {
         var prototype; // const

         prototype = $(document.createElement('a')).attr('href', '#').addClass('item').text('\u25cf');

         return function (index) {
            return prototype.clone();
         };
      }());

      /*
       * Initialization
       */
      (function () {
         var currentItem,
            currentItemController,
            itemPointer,
            interval,
            automaticallyInvoked,
            setItemPointer, // const
            applyItem; // const

         if (items.length > 0) {
            itemPointer = 0;

            /**
             * Sets the item pointer to a given position
             *
             * @param <integer> position Pointer position index.
             */
            setItemPointer = function (position) {
               itemPointer = position;
               applyItem();
            };

            /**
             * Swaps the current item against the new one.
             */
            applyItem = function () {
               var item;

               // Create new item.
               item = createItem(items[itemPointer]).appendTo(parent);

               // Do we need to replace an existing item?
               if (currentItem) {
                  item.stop().css({
                     'z-index': 1,
                     'opacity': 1
                  });
                  currentItem.stop().css({
                     'z-index': 2,
                     'opacity': 1
                  }).fadeOut(1000, function () {
                     currentItem.remove();
                     currentItem = item;
                  });
               } else {
                  currentItem = item;
               }
            };

            $.each(items, function (index, data) {
               preloadImage(data.url);
               createItemController().click(function () {
                  if (automaticallyInvoked !== true && interval) {
                     clearInterval(interval);
                  }

                  if (!$(this).hasClass('active')) {
                     setItemPointer(index);
                     $(this).addClass('active').siblings().removeClass('active');
                  }

                  setTimeout(function () {
                     info.attr('href', data.link.length > 0 ? data.link : '#');
                     info.find('.title').text(data.title);
                     
                     if (data.subtitle) {
                        info.find('.subtitle').show().text(data.subtitle);
                     } else {
                        info.find('.subtitle').hide();
                     }
                     
                  }, 500);
                  
                  return false;
               }).appendTo(controls);
            });
            
            currentItemController = controls.find(':first').click();
            
            interval = setInterval(function () {
               currentItemController = currentItemController.next();

               if (currentItemController.length == 0) {
                  currentItemController = controls.find(':first');
               }
               
               automaticallyInvoked = true;
               currentItemController.click();
               automaticallyInvoked = false;
            }, 6000);
         }
      }());

   }($('#slideshow .image'), $('#slideshow .info'), $('#slideshow-controls'), SLIDESHOW_ITEMS));

   /*
    * Article detail paging
    */
   if (!PRINT) {
      (function () {
         var parent,
            chunks,
            chunksParent;

         parent = $('.articleDetailText');
         chunksParent = $('.articleDetailTextChunkPaging');

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

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

               chunksParent.find('.item:first').click();
            }
         }
      }());
   }

   /*
    * Info article detail paging
    */
   if (!PRINT) {
      (function () {
         var parent,
            chunks,
            chunksParent;

         parent = $('.infoDetailText');
         chunksParent = $('.infoDetailTextChunkPaging');

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

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

               chunksParent.find('.item:first').click();
            }
         }
      }());
   }

   /*
    * Older article entries paging
    */
   if (!PRINT) {
      (function () {
         var parent,
            chunks,
            chunksParent;

         parent = $('.olderEntries');
         chunksParent = $('.olderArticleEntriesChunkPaging');

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

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

               chunksParent.find('.item:first').click();
            }
         }
      }());
   }

   /*
    * Comment entries paging
    */
   if (!PRINT) {
      (function () {
         var parent,
            chunks,
            chunksParent;

         parent = $('.commentsEntries');
         chunksParent = $('.commentPaging');

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

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

               chunksParent.find('.item:first').click();
            }
         }
      }());
   }

   /**
    * Links paging
    */
   if (!PRINT) {
      $('.linkCategories .linkCategory').click(function () {
         var category = $(this).attr('href').replace(/^.*#/, '');

         $(this).closest('.linkCategories').find('.linkCategory').removeClass('active');
         $(this).addClass('active');

         $('.linkCategory-'+category).show().siblings('.linkCategory').hide();

         return false;
      }).eq(0).click();
   }

   /**
    * Language switch.
    */
   $('.menu .language a').click(function () {
      var locale, // const
         url;

      // Determine new language.
      locale = $(this).attr('href').replace(/^.*#/, '');

      // Do we need to change anything?
      if (locale != CURRENT_LANGUAGE) {
         // Replace old language with new one.
         url = document.location.href.replace('/'+CURRENT_LANGUAGE+'/', '/'+locale+'/');

         // Check if the new language is still not set (e.g. the url is the
         // standalone domain name).
         if (document.location.href == url) {
            url += locale+'/index';
         }

         // Load new url.
         document.location.href = url;
      }

      return false;
   });

   /**
    * Send a friend.
    */
   $('.sendAFriendButton').click((function () {
      var windowObject, // const
         layerElement, // const
         shaderElement, // const
         closeElement, // const
         inputElements, // const
         messageElement, // const
         submitElement, // const
         errorsElement, // const
         errorElements, // const
         open, // const
         close, // const
         isRequestActive;

      windowObject = $(window);
      layerElement = $('.saf.fancy-layer');
      shaderElement = layerElement.find('.fancy-shader');
      closeElement = layerElement.find('.fancy-close');
      inputElements = layerElement.find(':input');
      messageElement = layerElement.find('[name="saf-message"]');
      submitElement = layerElement.find('.fancy-submit');
      errorsElement = layerElement.find('.fancy-error-wrap');
      errorElements = errorsElement.find('li');
      isRequestActive = false;

      open = function () {
         windowObject.scrollTop(0);
         shaderElement.height($('html, body').height());
         layerElement.fadeIn(500);
      };

      close = function () {
         layerElement.fadeOut(500);
      };

      closeElement.add(shaderElement).click(function () {
         close();
         return false;
      });

      submitElement.click(function () {
         var isValid,
            params;

         isValid = true;
         params = {};

         errorsElement.hide();
         errorElements.hide();

         inputElements.filter('.fancy-required').removeClass('fancy-invalid').each(function () {
            var value, // const
               name; // const

            value = $(this).val().trim();
            name = $(this).attr('name').replace(/^saf-/, '');

            if (value.length === 0 || ($(this).hasClass('fancy-validate-mail') && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value))) {
               isValid = false;
               $(this).addClass('fancy-invalid');
               errorsElement.show();
               errorElements.filter('.saf-error-'+name).show();
            }
         });

         if (isValid && !isRequestActive) {
            isRequestActive = true;

            inputElements.each(function () {
               var value,
                  name;

               value = $(this).val().trim();
               name = $(this).attr('name').replace(/^saf-/, '');

               params[name] = value;
            });

            $.post(DOC_ROOT+'/ajax.php?action=sendAFriend', params, function (data) {
               isRequestActive = false;

               if (data.status === 'success') {
                  close();
               } else {
                  errorsElement.show();
                  errorElements.filter('.saf-error-internal').show();
               }
            }, 'json');
         }

         return false;
      });

      return function () {
         var titleText,
            teaserText;

         $('#content .subHeadline, #content .articleImgDetail .yellowTitle, #content .title').each(function () {
            titleText = $(this).text().trim();
            return titleText.length === 0;
         });

         teaserText = $('#content .text').clone().children('div').not('.articleDetailText').remove().end().text().trim();

         if (teaserText.length > 300) {
            teaserText = teaserText.substr(0, 300).trim()+'...';
         }

         inputElements.val('');
         messageElement.val(titleText+"\n\n"+teaserText+"\n\n"+document.location.href);

         open();

         return false;
      }
   }()));

   /**
    * Post a comment.
    */
   $('.postAComment').click((function () {
      var windowObject, // const
         layerElement, // const
         shaderElement, // const
         closeElement, // const
         inputElements, // const
         submitElement, // const
         errorsElement, // const
         errorElements, // const
         open, // const
         close, // const
         isRequestActive;

      windowObject = $(window);
      layerElement = $('.pac.fancy-layer');
      shaderElement = layerElement.find('.fancy-shader');
      closeElement = layerElement.find('.fancy-close');
      inputElements = layerElement.find(':input');
      submitElement = layerElement.find('.fancy-submit');
      errorsElement = layerElement.find('.fancy-error-wrap');
      errorElements = errorsElement.find('li');
      isRequestActive = false;

      open = function () {
         windowObject.scrollTop(0);
         shaderElement.height($('html, body').height());
         layerElement.fadeIn(500);
      };

      close = function () {
         layerElement.fadeOut(500);
      };

      closeElement.add(shaderElement).click(function () {
         close();
         return false;
      });

      submitElement.click(function () {
         var isValid,
            params;

         isValid = true;
         params = {};

         errorsElement.hide();
         errorElements.hide();

         inputElements.filter('.fancy-required').removeClass('fancy-invalid').each(function () {
            var value, // const
               name; // const

            value = $(this).val().trim();
            name = $(this).attr('name').replace(/^pac-/, '');

            if (value.length === 0 || ($(this).hasClass('fancy-validate-mail') && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value))) {
               isValid = false;
               $(this).addClass('fancy-invalid');
               errorsElement.show();
               errorElements.filter('.pac-error-'+name).show();
            }
         });

         if (isValid && !isRequestActive) {
            isRequestActive = true;

            inputElements.each(function () {
               var value,
                  name;

               value = $(this).val().trim();
               name = $(this).attr('name').replace(/^pac-/, '');

               params[name] = value;
            });

            $.post(DOC_ROOT+'/ajax.php?action=postAComment', params, function (data) {
               isRequestActive = false;

               if (data.status === 'success') {
                  close();
               } else {
                  errorsElement.show();
                  errorElements.filter('.pac-error-internal').show();
               }
            }, 'json');
         }

         return false;
      });

      return function () {
         inputElements.not(':input:hidden').val('');
         open();

         return false;
      }
   }()));
   
   $('#form-comment-theme select').change(function () {
      $('#form-comment-theme').submit();
   });
});
