DR = '';
if (document.location.href.match(/\/maximgorki\//)) {
   DR = '/maximgorki';
}

Shadowbox.init();

// 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);
      }
   }

}());

$(document).ready(function() {
	/*
	 * fix IE6 png
	 */
	if ($.browser.msie && $.browser.version < 7) {
		$('img[src$=".png"], .media-wrap .left-button, .media-wrap .right-button').ifixpng();
	}
   /*
    * navigation
    */
   $('.contentNavi .naviLink').each(function() {
      if ($(this).hasClass('active')) {
         $(this).parent().addClass('active');
      }
   });
   $('.contentNavi .naviLinkWrap').hover(function() {
      $(this).addClass('hover');
   }, function() {
      $(this).removeClass('hover');
   });

   /*
    * tickets booking
    */
     $('select.cluster').change(function(){
         $('.defaultPrice').show();
         $('.eventSelect, .lastStep, .dateSelect').hide();
         $('select.date').val('');
         $('.cluster_'+$(this).val()).show();
      });
      $('select.date').change(function(){
         if ($(this).val() == '0')
            $('.defaultPrice').show();
         else
            $('.defaultPrice').hide();
         $('.dateSelect input').val('');
         $('.dateSelect').hide();
         $('.date_'+$(this).val()+'[class$=fromcluster_'+
            $('select.cluster').val()+'], .lastStep').show();
      });
      $('a.reservieren').click(function(){
         var cluster = $('select.cluster').val();
         var date = $('.cluster_'+cluster+' select').val();
         if (cluster != 0 && date != 0)
         {
            var prices = $('.date_'+date+'[class$=fromcluster_'+cluster+']').find('input');
            var error = true;
            for (var i = 0; i < prices.length; i++)
            {
               if ($($(prices)[i]).val() != "")
               {
                  error = false;
               }
            }
            if (!error)
            {
               var selected = $('select.cluster').val();
               var value = $('select.cluster').find('option[value='+selected+']').html();
               $('select.cluster').hide().after(value);
               var cluster = selected;
               var selected = $('.cluster_'+cluster+' select').val();
               var value = $('.cluster_'+cluster+' select').find('option[value='+selected+']').html();
               $('.cluster_'+cluster+' select').hide().after(value);
               
               var prices = $('.date_'+date+'[class$=fromcluster_'+cluster+'] input').
                  each(function(){
                     if ($(this).val() == "")
                        $(this).parents('.priceRow').css('display','none');
                     $(this).attr('readonly','readonly');
                     $(this).css('border','0px').css('color','#000000').
                        css('background-color','transparent').css('width','20px');
                  });
               $('.oldUser').hide();
               $('.newUser').show();
            }
         }
         if (cluster == 0)
         {
            alert($('.ticketerror_cluster').html());
         }
         else if (date == 0)
         {
            alert($('.ticketerror_date').html());
         }
         else if (error)
         {
            alert($('.ticketerror_price').html());
         }
         return false;
      });
      if ($('.requestClusterId').html() != "" && $('.requestClusterId').html() != null)
      {
         $('select.cluster').val(
            $('select.cluster option[value$='+
            $('.requestClusterId').html()+']').val()).change();
         if ($('.requestDateId').html() != "")
         {
            $('.cluster_'+$('.requestClusterId').html()+' select.date').val(
               $('.cluster_'+$('.requestClusterId').html()+' select.date option[value$='+
               $('.requestDateId').html()+']').val()).change();
         }
      }
      $('.reservieren').click(function(){
         if ($('.cluster').val() != "0")
         {
            var cluster = $('.cluster').val();
            if ($('.cluster_'+cluster+' select').val() != "0")
            {
               var title = $('.cluster option:selected').html();
               var date = $('.cluster_'+cluster+' select').val();
               pricesBox = $('.date_'+date+'[class$=fromcluster_'+
                  cluster+'] input');
               prices = $(pricesBox).serialize();
               var registerType = 'oldUser';
               if ($('.oldUser').css('display') == "none")
               {
                  registerType = 'newUser';
               }
               var values = $('.'+registerType).find('input, textarea')
                  .serialize();
               $.get(
                  DR+'/tickets.php?'+values+'&'+prices,
                  function(msg)
                  {
                     if (msg == "ALL OK")
                     {
                        document.location.href = LINK_ROOT+'/tickets/bookingmail/?' + values + '&' + prices + '&date=' + date + '&cluster=' + cluster + '&title=' + title; 
                     }
                     else
                     {
                        alert(msg);
                     }
                  }
               );
            }
            else
            {
               alert($('.ticketerror_date').html());
            }
         }
         else
         {
            alert($('.ticketerror_cluster').html());
         }
         return false;
      });
      
      
      var required = new Array();
      required['date']   = true;
      required['mail']   = true;
      required['name']   = true;
      required['class']  = true;
      required['phone']  = true;
      required['title']  = true;
      required['school'] = true;
      if ($('.anmeldeformular a').length > 0)
         $('.anmeldeformular a').attr('onclick','');
      $('.anmeldeformular a').click(function(){
         var error = '';
         for (var i = 0; i < $('.anmeldeformular input').length; i++)
         {
            var element = $($('.anmeldeformular input')[i]);
            if (typeof(required[$(element).attr('name')]) == "boolean")
            {
               if ($(element).val() == "")
               {
                  error += $(element).attr('title')+"\n";
                  $(element).css('border','1px solid #ff0000');
               }
               else
                  $(element).css('border','1px solid #000000');
            }
         }
         if (error == '')
            $('form').submit();
         else
            alert(error);
         return false;
      });
   /*** datepicker ***/

   /* click on month header */
   Date.format = 'mm/dd/yyyy';
   $('.date_input').datepick({
      dateFormat: 'dd-mm-yyyy',
      minDate: new Date(2006, 9-1, 1), // new Date(<year>, <month>-1, <day>)
      maxDate: '+1y', // also see pages/calendar_calendar.php
      changeMonth: false,
      prevText: '<img src="'+DR+'/media/png/arrow_cal_prev.png" alt="prev" />',
      nextText: '<img src="'+DR+'/media/png/arrow_cal_next.png" alt="next" />',
      onShow: function() {
          // hack to set month on the same level as arrows
          $('.datepick-cmd-prev').after($('.datepick-month .datepick-month-header'));
      },
      onSelect: function(date) {
         date = $.datepick.formatDate('dd.mm.yyyy', date[0]);
         window.location.href = LINK_ROOT+'/calendar/calendar/'+date;
      },
      onChangeMonthYear:function(year, month){
        $('.datepick-month-header').live('click', function(){
            var date = typeof year == 'number' && typeof month == 'number' ? $.datepick.newDate(year, month, 1) : $.datepick.today();
            window.location.href = LINK_ROOT+'/calendar/calendar/01' + $.datepick.formatDate('.mm.yyyy', date) + '/' + $.datepick.daysInMonth(year, month) + $.datepick.formatDate('.mm.yyyy', date);
        });
        $('.datepick-cmd-next, .datepick-cmd-prev').live('click', function(){
            var date = $.datepick.newDate(year, month, 1);
            window.location.href = LINK_ROOT+'/calendar/calendar/01' + $.datepick.formatDate('.mm.yyyy', date) + '/' + $.datepick.daysInMonth(year, month) + $.datepick.formatDate('.mm.yyyy', date);
        });
      }
   });

   // set default date if date request is set
   var date = document.location.href.split('/').pop().match(/\d+\.\d+\.\d+/);
   if(date)
   {
    var dateSplit = date[0].split('.');
    $(".date_input").datepick( "option", "defaultDate", new Date(dateSplit[2], dateSplit[1]-1, dateSplit[0]));
   }
   
});

$(window).load(function() {
   /*
    * media wrap
    */
   if ($(".media-wrap .slideshow .slider").children().length == 1) {
      $(".media-wrap .slideshow").hide();
   }

   $(".media-wrap .slideshow .picture-wrap").each(function() {
      var videoId = $(this).find('.video-id').html();
      var videoFile = $(this).find('.video-file').html();
      var imageSrc = 'http://data.heimat.de/transform.php?file='+$(this).find('.image-file').html()+'&width=463&height=300&do=cropOut';
      var imageInfo = $(this).find('.image-info').html();
      $.preload(imageSrc);

      var markup = '';
      if (videoId) {
         markup = '<object width="463" height="300" 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="http://dev1.heimat.de/player/templates/maximgorki/data.php" name="filmdata">'+
                     '<param value="controlbar=over&amp;image='+imageSrc+'&amp;file='+videoFile+'&amp;plugins=http://dev1.heimat.de/player/flash/ksplugin&amp;filmdata=http://dev1.heimat.de/player/templates/maximgorki/data.php&amp;skindata=http://dev1.heimat.de/player/templates/maximgorki/skinData.php&amp;language=en_EN&amp;id='+videoId+'&amp;is_embed=true&amp;stretching=fill" name="flashvars">'+
                  '</object>';
      } else {
         markup = '<img src="'+imageSrc+'" alt="'+imageInfo+'" title="'+imageInfo+'" />';
      }

      $(this).click(function() {
         $(".media-wrap .display").html(markup);
      });
   }).eq(0).click();

   $(".media-wrap .slideshow .left-button, .media-wrap .slideshow .right-button").hover(function() {
      $(this).stop().animate({opacity: 0.8}, 200);
   }, function() {
      $(this).stop().animate({opacity: 0}, 500);
   }).animate({opacity: 0.8}, 2000, function() {
      $(this).animate({opacity: 0}, 2000);
   });
   $(".media-wrap .slideshow .slider > *:last").css('margin-right', '0px');

   // slideshow
   $(".media-wrap .slideshow").each(function() {
      var options = {
         acceleration:    0.5, // how fast the slider gains speed (more means faster)
         friction:        0.5, // how fast the slider looses speed (more means faster)
         pixelsPerSecond: 500  // maximum movement speed
      };

      // movement
      var animationInterval = null;
      var currentVelocity = 0;
      var sliderWrap = $(this).find('.slider-wrap');
      options.maximumVelocity = options.pixelsPerSecond / 60;

      // prepare
      var sliderWidth = 0;
      $(this).find('.slider').children().each(function() {
         sliderWidth += $(this).outerWidth(true);
      })
      $(this).find('.slider').width(sliderWidth);

      // remove buttons if there is nothing to scroll
      if (sliderWidth <= sliderWrap) {
         $(this).find('.left-button, .right-button').remove();
      }

      // add player icons
      var slider = $(this).find('.slider');
      $(this).find('.slider .picture-wrap .video-id').each(function() {
         $('<img src="'+DR+'/media/png/icon_play.png" alt="" />').css({
            position: 'absolute',
            top:      '6px',
            left:     '20px',
            zIndex:  '5'
         }).appendTo($(this).parent());
      });

      // animation routine
      var move = function(direction) {
         if (animationInterval !== null) {
            window.clearInterval(animationInterval);
         }

         animationInterval = window.setInterval(function() {
            if (direction < 0) { // left
               currentVelocity -= options.acceleration;
               if (currentVelocity < -options.maximumVelocity) {
                  currentVelocity = -options.maximumVelocity;
               }
            } else if (direction > 0) { // right
               currentVelocity += options.acceleration;
               if (currentVelocity > options.maximumVelocity) {
                  currentVelocity = options.maximumVelocity;
               }
            } else if (currentVelocity < 0) { // stop
               currentVelocity += options.friction;
               if (currentVelocity > 0) {
                  currentVelocity = 0;
               }
            } else if (currentVelocity > 0) { // stop
               currentVelocity -= options.friction;
               if (currentVelocity < 0) {
                  currentVelocity = 0;
               }
            } else {
               window.clearInterval(animationInterval);
            }

            // everything calculcated? okay, lets get ready to rumble.
            sliderWrap[0].scrollLeft += parseInt(currentVelocity);
         }, 16);
      };

      // bindings
      $(this).find('.left-button').mousedown(function() {
         move(-1);
         return false;
      });
      $(this).find('.right-button').mousedown(function() {
         move(1);
         return false;
      });
      $(this).find('.left-button, .right-button').mouseup(function() {
         move(0);
         return false;
      }).mouseleave(function() {
         $(this).mouseup();
         return false;
      });

   });
});
