var DR = '/';
if (document.location.href.match(/\/planetariumbochum\//)) {
   DR += 'planetariumbochum/';
}

$(document).ready(function() {

   var doSiteSearch = function() {
      document.location.href = DR+$('#ml2_locale').val()+'/search/'+
         $('.search input').val()
   };
   $('.search img').click(function() {
      doSiteSearch();
   });
   $('.search input').keypress(function(key) {
      if (key.which == 13) {
         doSiteSearch();
      }
   });
   $('.search input').focus(function(){
      if (!$(this).hasClass('active')) {
         $(this).attr('class', 'active').val('');
      }
   });
   var buildCalendar = function(month, year) {
      $('.calendar').load(DR+'ajax.php?method=createCalendar'+
         '&month='+month+'&year='+year, function() {
            bindCalendar();
      });
   };
   var bindCalendar = function() {
      $('.calendar .left, .calendar .right').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();
      });
   };
   $('.calendarSearch a').click(function() {
      $('#dateFrom').val($(this).attr('id').split(/_/)[1]);
      $('#dateTo').val($(this).attr('id').split(/_/)[2]);
      submitCalendar();
      return false;
   });
   var submitCalendar = function() {
      var params = {
         'event_category':   $('.cal_cat').val(),
         'startDate':        $('#dateFrom').val(),
         'endDate':          $('#dateTo').val(),
         'language':         $('#ml2_locale').val()
      };
      //TODO schöner machen

      if ($('.cal_cat').val() == '')
         $('.cal_cat').val(0);
      if ($('#dateFrom').val() == '')
         $('#dateFrom').val(0);
      if ($('#dateTo').val() == '')
         $('#dateTo').val(0);
      document.location.href = DR+$('#ml2_locale').val()+'/calendar/'+
         'category/'+$('.cal_cat').val()+
         '/from/'+$('#dateFrom').val()+'/to/'+$('#dateTo').val();
   };
   $('.cal_area').change(function() {
      $('.cal_area_target').load(DR+'ajax.php?method=createCities&region='+
         $(this).val()
      );
   });
   $('.header select').change(function() {
      var val = $(this).val();
      var href = document.location.href;
      if (!href.match(/\/[a-z]{2}_[A-Z]{2}\//)) {
         document.location.href = href+val+'/home';
      } else {
         href = href.replace(/\/[a-z]{2}_[A-Z]{2}\//, '/'+val+'/');
         document.location.href = href;
      }
   });
   $('.daterange a').click(function() {
      submitCalendar();
      return false;
   });
   $('#letterBox input').keypress(function(e){
      if (e.which == 13) {
         $('#letterBox .lb_search img').click();
      }
   }).focus(function(){
      $(this).val('');
   });
   $('#letterBox .lb_search img').click(function() {
      window.document.location.href = window.document.location.href.replace(
         /\/presale.*$/, '/presale/'+$('#letterBox input').val());
   });
   bindCalendar();

   /*
    * navigation
    */
   jQuery(".mainMenu > a").each(function() {
      var parentOffset = {
         top:  jQuery(this).offset().top -= jQuery(".headerImg").offset().top,
         left: jQuery(this).offset().left -= jQuery(".headerImg").offset().left
      };
      var matches = jQuery(this).attr('class').match(/topMenuItem_(\w+)/);
      if (matches) {
         var submenu = jQuery(".topSubMenu > .topSubMenuItem_"+matches[1]);
         if (submenu.length > 0) {
            jQuery(this).mouseenter(function() {
               jQuery(".headerImg > .topSubMenuItem").mouseleave();
               submenu = submenu.clone().appendTo(".headerImg").show();
               submenu.css({
                  position: "absolute",
                  top:      (parentOffset.top - submenu.outerHeight())+'px',
                  left:     (parentOffset.left)+'px',
                  zIndex:   2
               }).mouseleave(function() {
                  jQuery(".headerImg > .topSubMenuItemBG").remove();
                  jQuery(this).remove();
               }).find("a").hover(function() {
                  jQuery(this).addClass("hover-ie");
               }, function() {
                  jQuery(this).removeClass("hover-ie");
               });;
               var background = jQuery("<div></div>").addClass("topSubMenuItemBG").appendTo(".headerImg").css({
                  position: "absolute",
                  top:      (parentOffset.top - submenu.outerHeight())+'px',
                  left:     (parentOffset.left)+'px',
                  opacity:  0.8,
                  zIndex:   1
               }).width(submenu.outerWidth()).height(submenu.outerHeight());
            });
         }
      }
   });
   jQuery(".headerImg").mouseleave(function() {
      jQuery(".headerImg > .topSubMenuItem").mouseleave();
   });

   /**
    * Mail validation (for general)
    **/
   var isMailValid = function(address){
      return Boolean(address.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/));
   }

   /**
    * Validation of Required fields: Color fields which are required and return if all Fields were filled by the user
    *
    * @param jqueryObject the jquery Object, selected via $('') ...
    *
    * @return Boolean true or false wether the form got user-inputs in every required field
    **/
   var isInputsProperlyFilled = function(jqueryObject){
      var unfilledFields = 0; // for later
      jqueryObject.each(function(){ // iterate over every input field
         $(this).css('border', '1px solid black'); // color its border (for if this loop is called a second time due a user correction)
         if($(this).val() === ''){ // do the following if input is not filled
            $(this).css('border', '2px solid red'); // color its border red
            unfilledFields++; // increase a failure-counter for later usage
         }
      });
      return !Boolean(unfilledFields);
   }

   /**
    * Newsletter
    **/

   // Subscribe
   $('#newsletter #subscribe-newsletter-submit').click(function(){
      if(!isMailValid($('#email').val())){
         alert($('#msg_invalid_mail_format').val());
         return false;
      }
      return isInputsProperlyFilled($('#newsletter #subscribe-form .req'));
   });

   // Unsubscribe
   $('#newsletter #unsubscribe-newsletter-submit').click(function(){ // make sure the user knows what he's doing when he trys to unsubscribe his mail
      if(isMailValid($('#u-email').val()))
         return confirm($(this).data('confirmationtext'));
      else{
         alert($('#msg_invalid_mail_format').val());
         return false;
      }
      return isInputsProperlyFilled($('#newsletter #unsubscribe-form .req'));
   });

   /**
    * Groupregistration
    **/

   $('#groupregistration #submit').click(function(){
      // Check if mail is valid
      if(!isMailValid($('#mail').val())){
         $('#mail').css('border', '4px solid red');
         alert($('#email-ml').val());
         return false;
      }

      // Validate the rest
      return isInputsProperlyFilled($('#groupregistration .req'));
   });

}); // END DOC READY

// execute when all page contents (e.g. images) are fully loaded
$(window).load(function() {
   $(".slideshow").slideshow({
      // override defaults
      interval:      3000,
      slideDuration: 1000,
      minItems:      3
   });
});

function showTicketBox(url, w, h, title, close, header) {
   /*
    * workaround for flash colliding with layers
    */
   jQuery('.tx-rlmpflashdetection-pi1').hide();
   
   var overlay = jQuery('<div class="__layer"></div>').appendTo('body').css({
      'opacity': '0.3',
      'background-color': 'white',
      'top': '0px',
      'left': '0px',
      'position': 'fixed',
      'z-index': '1337',
      'height': '100%',
      'width': '100%'
   });
   if ($.browser.msie) {
      overlay.css({
         'position': 'absolute',
         left: document.body.scrollLeft + 'px',
         top:  document.body.scrollTop + 'px'
      });
   }
   var layer = jQuery('<div class="__layer"></div>').appendTo('body').css({
      'border': '2px solid #887d64',
      'border-radius': '26px',
      '-moz-border-radius': '26px',
      '-webkit-border-radius': '26px',
      'background-color': 'white',
      'top': '50%',
      'position': 'fixed',
      'left': '50%',
      'margin-left': '-'+w/2+'px',
      'margin-top': '-'+h/2+'px',
      'z-index': '1338',
      'height': h+'px',
      'width': w+'px'
   });
   if ($.browser.msie) {
      layer.css({
         'position': 'absolute',
         'margin': '0px',
         left: ((document.body.clientWidth/2)-w/2)+document.body.scrollLeft + 'px',
         top:  ((document.body.clientHeight/2)-h/2)+document.body.scrollTop + 'px'
      });
      var putWindowRight = function() {
         layer.css({
            left: ((document.body.clientWidth/2)-w/2)+document.body.scrollLeft + 'px',
            top:  ((document.body.clientHeight/2)-h/2)+document.body.scrollTop + 'px'
         });
         overlay.css({
            left: document.body.scrollLeft + 'px',
            top:  document.body.scrollTop + 'px'
         });
      };
      window.onresize = function() {
         putWindowRight();
      };
      window.onscroll = function() {
         putWindowRight();
      };
   }
   var header = jQuery('<div class="__layer_header"></div>').css({
      'position': 'absolute',
      'bottom': (h+2)+'px',
      'width': w+'px'
   }).append(header).appendTo(layer);
   var top = jQuery('<div class="ticketwindow_top">'+title+'</div>').appendTo(layer).css({
      'height': '32px',
      'line-height': '32px',
      'color': '#af2a26',
      'font-weight': 'bold',
      'padding-left': '27px',
      'position': 'relative',
      'z-index': '10',
      'border-radius-topleft': '26px',
      'border-radius-topright': '26px',
      '-moz-border-radius-topleft': '26px',
      '-moz-border-radius-topright': '26px',
      '-webkit-border-top-left-radius': '26px',
      '-webkit-border-top-right-radius': '26px'
   });
   jQuery('<iframe frameborder="0"></iframe>').appendTo(layer).css({
      'border': '0px',
      'display': 'block',
      'height': (h-62)+'px',
      'width': w+'px'
   }).attr('src', url);
   var bottom = jQuery('<div class="ticketwindow_bottom"></div>').appendTo(layer).css({
      'height': '30px',
      'line-height': '30px',
      'font-weight': 'bold',
      'vertical-align': 'middle',
      'line-height': '20px',
      'text-align': 'right',
      'padding-right': '40px',
      'position': 'relative',
      'z-index': '10',
      'border-radius-bottomleft': '26px',
      'border-radius-bottomright': '26px',
      '-moz-border-radius-bottomleft': '26px',
      '-moz-border-radius-bottomright': '26px',
      '-webkit-border-bottom-left-radius': '26px',
      '-webkit-border-bottom-right-radius': '26px'
   }).html('<a href="#" onclick="jQuery(\'.__layer\').remove();return false;" style="font-weight: bold;">'+close+'</a>');
   if (!$.browser.msie) {
      addShadow(layer);
   }
   if ($.browser.mozilla && $.browser.version.split('.')[2] == 0) {
      layer.css('-moz-border-radius','20px');
      top.css('-moz-border-radius-topright','17px');
      top.css('-moz-border-radius-topleft','17px');
      bottom.css('-moz-border-radius-bottomright','17px');
      bottom.css('-moz-border-radius-bottomleft','17px');
   }
   return false;
}

