/*
 * Author: Andre Mohren, Johannes Wüller, Philipp Kübler
 * Last Modified: 24.07.2009
 */
function validateForm(req)
{
   for (var i=0; i<req.length; i++)
   {
      if ($(req[i]).val() == '')
         return false;
   }
   return 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].replace(/&amp;/g, '&');
         images.push(image);
      }
   }

}());

$(document).ready(function() {
   // intro banner -------------------------------------------------------------
   (function (parent) {
      var items = parent.find('.intro-banner-item').hide(),
         position = 0;
      
      items.eq(position).show();
      
      if (items.length > 1) {
         setInterval(function () {
            items.eq(position).css('z-index', 2).fadeOut(500);
            position = (position + 1) % items.length;
            items.eq(position).css('z-index', 1).show();
         }, 5000);
      }
   }($('.intro-banner')));
   
   // faq ----------------------------------------------------------------------
   (function () {
      var faqListElement = $('#faq ul'),
         faqTitleElements = faqListElement.find('li p'),
         faqTextElements = faqListElement.find('li blockquote').hide();

      faqListElement.delegate('li p', 'click', function () {
         var element = $(this),
            thisFaqTextElement = element.closest('li').find('blockquote');

         faqTitleElements.not(element).removeClass('active');
         element.toggleClass('active');
         faqTextElements.not(thisFaqTextElement).hide();
         thisFaqTextElement.toggle();
      });
   }());
   
   // --------------------------------------------------------------------------

   /*$.get('ajax.php?method=jsonLabels', function($return) {
      //ToDo: parse this to a working json
      jQuery.ml_labels = $return;
      jQuery.ml = function(label) {
         if (typeof(jQuery.ml_labels[label] != 'undefined')
            return jQuery.ml_labels[label];
         return label;
      };
   });*/
   
   var getMl = function(label) {
      //do never do this! maybe load here a ml-json and save it, but dont write unneeded stuff into the dom.
      //that looks very wierd when using a non-css browser.
      //look at incomplete func above
      //---
      //non-css browsers won't be able to show this page anyway
      //json is a nice idea but getting it via ajax is not that good.
      //parse json via JSON.parse(json_string) by the way
      return $('#js_ml_labels').children('.'+label).html();
   };

   $('#textareaText').val(document.location.href);
   $('#sendaFriend .sendButton').click(function() {
      var params = $('#sendaFriend').serializeArray();
      if(validateForm($('#sendaFriend .required'))) {
         $('#sendaFriendForm').html($('#TB_ajaxContent').html());
         var DR = '/';
         if (document.location.href.match(/heimat\.de/))
            var DR = '/staatsoperberlin_schillertheater/';
         $('#TB_ajaxContent').load(DR+'pages/sendafriend.php', params);
      } else
         alert('Bitte füllen Sie alle Formularfelder aus, die mit einem * markiert sind.');
   });
   var correctSubmenuPosition = function(e) {
      if (!(typeof $(e)[0] == 'undefined' || ($.browser.msie && $.browser.version < 7))) {
         var submenu = $('#sub_'+e.attr('id'));

         if (!$(submenu).hasClass('corrected')) {
            $(submenu).addClass('corrected').width($(submenu).width() + 40);
         }
         
         $(submenu).css('position', 'absolute');
         var offsetLeft = parseInt(($(e)[0].offsetLeft + parseInt($(e).css('padding-left'))) - (($(submenu).width() - 40) / 2) + ($(e).width() / 2));
         var maxOffset = parseInt($(submenu).parent().parent().width() - ($(submenu).width() - 40));
         if (offsetLeft < 0) offsetLeft = 0;
         if (offsetLeft > maxOffset) offsetLeft = maxOffset;
         $(submenu).css('left', offsetLeft+'px');
      }
   };

   var bindMenu = function() {
      var timeOut = '';
      var old = $('.active').attr('id');
      $('.mainmenu a').mouseover(function() {
         var e = $(this);
         timeOut = window.setTimeout(function() {
            $('#sub_'+e.attr('id')).show().siblings().hide();
            
            correctSubmenuPosition(e);
         }, 250, this);
      }).mouseout(function() {
         clearTimeout(timeOut);
      });
      $('#allnavi').hover(function(){
         clearTimeout(timeOut);
      }, function() {
         timeOut = window.setTimeout(function() {
            $('#sub_'+old).show().siblings().hide();
       
         }, 250);
      });
   };

   correctSubmenuPosition($('.mainmenu a.active'));
   
   var buildCalendar = function(month, year) {
      /*$('.calendar').load(document.location.href.replace(/([a-z]{2}_[A-Z]{2})\/.*$/, '')+'ajax.php?method=createCalendar'+
         '&month='+month+'&year='+year+'&language='+document.location.href.match(/\/([a-z]{2}_[A-Z]{2})\//)[1], function() {
            bindCalendar();
         });*/

      // IE does not support jQuery.html() (which is used in jQuery.load())
      // dirty workaround:
      $.post(document.location.href.replace(/([a-z]{2}_[A-Z]{2})\/.*$/, '')+'ajax.php?method=createCalendar'+'&month='+
         month+'&year='+year+'&language='+document.location.href.match(/\/([a-z]{2}_[A-Z]{2})\//)[1], {}, function(data) {
            // this should be $('div.calendar').html(data) but IE does not support this properly.
            $('div.calendar').children().remove().end().append(data);
            bindCalendar();
         }
      );
   };
   var bindCalendar = function() {
      $('.calendar .monthLeft, .calendar .monthRight').click(function() {
         var date = $(this).attr('id').split(/_/);
         buildCalendar(date[1], date[2]);
      });
      $('.calendar td').click(function() {
         $('#dateFrom, #dateTo').val($(this).attr('id').split(/_/)[1]);
         submitCalendar();
      });
      $('.calendar .month').click(function() {
         $('#dateFrom').val($(this).attr('id').split(/_/)[1]);
         $('#dateTo').val($(this).attr('id').split(/_/)[2]);
         submitCalendar();
      });
   };
   var submitCalendar = function() {
      var params = {
         'startDate':        $('#dateFrom').val(),
         'endDate':          $('#dateTo').val()
      };
      //TODO schöner machen
      if ($('#dateFrom').val() == '')
         $('#dateFrom').val(0);
      if ($('#dateTo').val() == '')
         $('#dateTo').val(0);

      // URL wird gesetzt.
      document.location.href = document.location.href.replace(/([a-z]{2}_[A-Z]{2})\/.*$/, '$1')+'/calendar/'+$('#dateFrom').val()+'-'+$('#dateTo').val();
   };
   bindCalendar();
   bindMenu();

   $('.presseverteiler').submit(function () {
      for (var i = 0; i < $('.presseverteiler label').length; i++){
         var obj = $('.presseverteiler label')[i];
         var id = $(obj).attr('for');
         if ($(obj).html().match(/\*/) && $('#'+id).val() == '')
            $('#'+id).addClass('formError');
         else
            $('#'+id).removeClass('formError');
      }
      if ($('.formError').length > 0)
         return false;
   });
   $('#journalist').change(function() {
      $('#journalist_text').slideToggle();
   });

   $('.expandable').each(function(){
      if ($(this).height() > 7 * parseInt($(this).css('line-height'))) {
         $(this).css({
            'height': 7 * parseInt($(this).css('line-height'))+ 'px',
            'overflow': 'hidden'
         })
         $('<div class="moreExpandable">&gt;&gt; <span class="text_red">'+getMl('more_text')+'</span></div>').css({
            'cursor': 'pointer'
         }).click(function() {
            if ($(this).find('span').html() == getMl('less_text')) {
               $(this).parent().find('.expandable').animate({
                  'height': 7 * parseInt($(this).css('line-height'))+ 'px'
               });
               $(window).scrollTo('0px', 500); // scroll up
               $(this).find('span').html(getMl('more_text'));
            } else {
               $(this).parent().find('.expandable').animate({
                  'height': $('.expandable')[0].scrollHeight + 'px'
               });
               $(this).find('span').html(getMl('less_text'));
            }
         }).insertAfter(this);
      }
   });

   /*
    * fading slideshow
    */
   (function() {

      if (typeof indexSlideshowData != 'undefined') {
         var data = indexSlideshowData;

         var parent = jQuery('.iGotTheFadingSlideshow');
         var position = 0;

         var imageFiles = [];
         jQuery.each(data, function(index, row) {
            imageFiles.push(row.image);
         });

         jQuery.preload.apply(this, imageFiles);

         var display = function() {
            var activeData = data[position];
            var markup = '<div class="slideshowEntry">'
                           +'<a class="image" href="'+activeData.target+'">'
                              +'<img src="'+activeData.image+'" alt="'+activeData.imageTitle+'" title="'+activeData.imageTitle+'" />'
                           +'</a>'
                           +'<div class="textWrap">'
                              +'<a class="title" href="'+activeData.target+'">'
                                 +activeData.title
                              +'</a>'
                              +'<div class="text">'
                                 +activeData.text
                              +'</div>'
                           +'</div>'
                        +'</div>';
            
            markup = jQuery(markup).css({
               zIndex:  0
            });
            
            if (activeData.playerLink) {
               tb2_init($('<a class="playButton" href="http://dev1.heimat.de/player/'+activeData.language+'/'+activeData.playerLink.replace(/^http:\/\/cb-player.de\/(\d+)/g, '$1')+'/schillertheater/?KeepThis=true&TB2_iframe=true&height=540&width=780"></a>').appendTo(markup));
            }

            parent.find('.slideshowEntry').css({
               zIndex:  1,
               opacity: 1.0
            }).animate({
               opacity: 0.0
            }, 1000, function() {
               jQuery(this).remove();
            });
            
            markup.appendTo(parent);

            var textWrap = markup.find('.textWrap');

            textWrap.css({
               top: parseInt((parent.height() / 2) - (textWrap.height() / 2))+'px'
            });
         };

         display();

         window.setInterval(function() {
            position++;
            if (position >= data.length) {
               position = 0;
            }
            display();
         }, 8000);
      }

   }());

   // toggle for youth content texts
   $('.toggleContent span').click(function(){
      $('.furtherContent').slideToggle();
      $('.furtherContentIndicator').toggle();
      $('.toggleContent #elapse').toggle();
      $('.toggleContent #colapse').toggle();
   });

}); // end doc ready

function closeThickbox() {
 jQuery("body, html").css("overflow","");
   $('#TB2_overlay, #TB2_window').remove();
   $('#TB2_overlay, #TB2_window, #TB2_HideSelect').remove();
}

