Shadowbox.init({
   slideshowDelay: 5,
   continuous:     true
});

// image preloader
(function() {
   
   var images = [];
   
   jQuery.preload = function() {
      for (var i = 0; i < arguments.length; i++) {
         var image = document.createElement('img');
         image.src = arguments[i];
         images.push(image);
      }
   }
  
}());

$(window).load(function() {
   if ($.browser.msie && $.browser.version < 7) {
      $('img[src$=".png"], .navigation-wrap .logo').ifixpng();
      $('.navigation-wrap .logo').css({
         'background-position': '180px 0px'
      });
   }
});

$(document).ready(function() {


   /*
    * fancy media wrapper
    */
   (function() {

      var wrapElement = $('.fancy-media-wrap');
      var lastMode = null;

      // generate data
      var data = {
         image: [],
         video: []
      };
      wrapElement.find('.image-data').children().each(function() {
         var imageData = {
            url:   $(this).find('.url').html().replace(/&amp;/g, '&'),
            title: $(this).find('.title').html()
         };
         $.preload(imageData.url);
         data.image.push(imageData);
      });
      wrapElement.find('.video-data').children().each(function() {
         var videoData = {
            id:    $(this).find('.id').html(),
            file:  $(this).find('.file').html(),
            image: $(this).find('.image').html(),
            title: $(this).find('.title').html()
         };
         data.video.push(videoData);
      });

      var setMode = function(mode) {
         wrapElement.find('.selector-wrap').children().remove();
         $.each(data[mode], function(index, content) {
            $(document.createElement('a')).attr('href', '#').addClass('selector').click(function() {
               $(this).addClass('active').siblings().removeClass('active');
               display(mode, content);
               return false;
            }).appendTo(wrapElement.find('.selector-wrap'));
         });
         $(document.createElement('div')).css('clear', 'left').appendTo(wrapElement.find('.selector-wrap'));
         wrapElement.find('.selector-wrap .selector:first').click();
         lastMode = mode;
      };

      var display = function(mode, content) {
         var displayWrap = wrapElement.find('.display-wrap');

         if (mode == 'image') {
            // empty display-wrap if we had a video last time
            if (lastMode == 'video') {
               displayWrap.html('');
            }
            
            var image = $(document.createElement('img')).attr('src', content.url).attr('title', content.title).attr('alt', content.title).css({
               position: 'absolute',
               top:      '0px',
               left:     displayWrap.width()+'px',
               zIndex:   1
            }).appendTo(displayWrap);

            if (image.prev().attr('src') != image.attr('src')) {
               var animationDuration = 1000;
               if (image.prevAll().length == 0) {
                  animationDuration = 0;
               }

               image.animate({
                  left: '0px'
               }, animationDuration, function() {
                  $(this).css({
                     zIndex: 0
                  }).prevAll().stop().remove();
               });
            } else {
               image.remove();
            }
         } else if (mode == 'video') {
            var markup = '<object width="504" height="285" id="player" type="application/x-shockwave-flash" data="http://dev1.heimat.de/player/flash/player.swf">'+
                            '<param value="http://dev1.heimat.de/player/flash/player.swf" name="movie">'+
                            '<param value="true" name="allowfullscreen">'+
                            '<param value="always" name="allowscriptaccess">'+
                            '<param value="controlbar=over&amp;image='+content.image+'&amp;file='+content.file+'&amp;plugins=http://dev1.heimat.de/player/flash/ksplugin&amp;filmdata=http://dev1.heimat.de/player/templates/_default/data.php&amp;skindata=http://dev1.heimat.de/player/templates/_default/skinData.php&amp;language=en_EN&amp;id='+content.id+'&amp;is_embed=true" name="flashvars">'+
                         '</object>'+content.title;

            displayWrap.html(markup);
         }
      };

      // bind controls
      wrapElement.find('.controls .image-button').click(function() {
         $(this).addClass('active').siblings().removeClass('active');
         setMode('image');
         return false;
      });
      wrapElement.find('.controls .video-button').click(function() {
         $(this).addClass('active').siblings().removeClass('active');
         setMode('video');
         return false;
      });

      // initialize
      if (data.video.length == 0 && data.image.length > 0) {
         wrapElement.find('.controls .image-button').click();
      } else {
         wrapElement.find('.controls .video-button').click();
      }
      
   }());

   /*
    * navigation scrolling
    */
   (function() {

      var naviElement = $('.navigation-wrap .navigation');

      naviElement.find('.image').css({
         'margin-top': naviElement.find('.link-wrap').height()+'px'
      });

      var options = {
         animationDuration: 1000,
         minHeight:         parseInt(naviElement.css('top')),
         topPadding:        20
      };

      var getDocumentScrollOffsetY = function() {
        var scrollPos = 0;
        if (typeof(window.pageYOffset) == 'number') {
          scrollPos = window.pageYOffset;
        } else if (document.body && document.body.scrollTop) {
          scrollPos = document.body.scrollTop;
        } else if (document.documentElement && document.documentElement.scrollTop) {
          scrollPos = document.documentElement.scrollTop;
        }
        return scrollPos;
      };

      var lastPos = 0;
      $(window).scroll(function() {
         var targetPos = getDocumentScrollOffsetY() + options.topPadding;

         var naviElementHeight = naviElement.height();
         var mainWrapHeight = $('.main-wrap').height();

         if (targetPos + naviElementHeight <= mainWrapHeight || lastPos != targetPos) {
            lastPos = targetPos;

            if (targetPos + naviElementHeight > mainWrapHeight) {
               targetPos = mainWrapHeight - naviElementHeight;
            }

            if (targetPos > options.minHeight) {
               naviElement.stop().animate({
                  top: targetPos+'px'
               }, options.animationDuration, 'easeOutCubic');
            } else {
               naviElement.stop().animate({
                  top: options.minHeight+'px'
               }, options.animationDuration, 'easeOutCubic');
            }

         }
      }).scroll();

   }());

/* jqForm jQuery form validation */
    $('.jqForm').jqForm();
});

/* jqForm jQuery form validation plugin */
$.fn.jqForm = function() {
    var jqForm = this;
    $(jqForm).each(function() {
        var inputs = $('input[type="text"], select, textarea');
        var checkboxes = $('input[type="checkbox"]');
        
        var inputsRequiredOnce = $('input[name="publications[]"], input[name="articles[]"], input[name="accountcard"]');

        /* show preview when clicking on send button. 
         * in case a field value is missing, show error otherwise clear error 
         */
        $('.formSendPrepare').click(function(){
            var valid;

            $('.formError').hide();
            /* iterate inputs and check required fields */
            inputs.each(function(){
                $(this).next('span').remove();
                if($(this).hasClass('required')){
                    if($(this).val() == '')
                        valid = false;
                    else if($(this).attr('name') == 'email' && !$(this).val().match(/^[\w._%+-]+@[\w._%+-]+\.\w{2,4}$/i))
                        valid = false;
                    else
                        valid = true;

                    if(valid)
                        $(this).removeClass('formErrorInput');
                    else
                        $(this).addClass('formErrorInput');
                }
            });
            
            /* iterate inputs that are required just once */
            valid = inputsRequiredOnce.filter(':checked').length?true:false;
            inputsRequiredOnce.each(function(){
                /* special case: shop */
                var closestDiv = $(this).attr('name') == 'articles[]'?'.shopEntry':'div';
                if(valid)
                    $(this).closest(closestDiv).removeClass('formErrorInput');
                else
                    $(this).closest(closestDiv).addClass('formErrorInput');
            });

            /* if no input error found, continue with preview div.
             * hide empty input (or related div) and show input with value
             */
            if(!$('.formErrorInput').length){
                inputs.each(function(){
                    if($(this).val() != ''){
                        $(this).hide().after(function(){
                            return '<span>'+$(this).val()+'</span>';
                        });
                    }
                    else
                        $(this).closest('tr').hide();
                });

                inputsRequiredOnce.filter(':not(:checked)').each(function(){
                    /* special case: shop */
                    var closestDiv = $(this).attr('name') == 'articles[]'?'.shopEntry':'div';
                    $(this).closest(closestDiv).hide();
                });

                $('.formSendPrepare').hide();
                $('.formSend, .formValidate, .formValidateBack').show();
                /* scroll to top of jqForm */
                $('html, body').animate({ scrollTop: $(jqForm).offset().top }, 1000);
            }
            else
                $('.formError').show();
        });
        
        /* click on the back button in the preview restores the original form */
        $('.formValidateBack').click(function(){
            inputs.each(function(){
                $(this).closest('tr').show();
                $(this).next('span').remove();
                $(this).show();
            });
            inputsRequiredOnce.each(function(){
                // special case: shop
                var closestDiv = $(this).attr('name') == 'articles[]'?'.shopEntry':'div';
                $(this).closest(closestDiv).show();
            });
            $('.formValidate, .formValidateBack, .formSend').hide();
            $('.formSendPrepare').show();
        });
    });
}


