/*
 * 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() {

   /*$.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 = '/staatsoper-berlin/';
         $('#TB_ajaxContent').load(DR+'pages/sendafriend.php', params);
      } else
         alert('Bitte füllen Sie alle Formularfelder aus, die mit einem * markiert sind.');
   });
   $('.mb_login').click(function(){
      var id = $(this).attr('title');
      window.open('http://new.heimat.de/culturebase/cb_mdb/cms/login.php?proj='+id, 'mb',
         'width=640,height=480,location=no,menubar=no,status=no,toolbar=no');
      return false;
   });
   $('.mb_edit').click(function(){
      var id = $(this).attr('title');
      window.open('http://new.heimat.de/culturebase/cb_mdb/cms/index.php?mbId='+id, 'mb',
         'width=640,height=480,location=no,menubar=no,status=no,toolbar=no');
      return false;
   });

   var correctSubmenuPosition = function(e) {
      if (!(typeof $(e)[0] == 'undefined' || ($.browser.msie && $.browser.version < 7))) {
         var submenu = $('#sub_'+e.attr('id'));
         $(submenu).css('width', ($(submenu).width()+40)+'px');
         $(submenu).css('position', 'absolute');
         var offsetLeft = parseInt(($(e)[0].offsetLeft + parseInt($(e).css('padding-left'))) - ($(submenu).width() / 2) + ($(e).width() / 2));
         var maxOffset = parseInt($(submenu).parent().parent().width() - $(submenu).width());
         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);
      });
   };
   
   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);
      }
   });

   correctSubmenuPosition($('.mainmenu a.active'));

   /*
    * 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>';

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

            var textWrap = jQuery(markup).appendTo(parent).css({
               zIndex:  0
            }).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);
      }

   }());

});

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