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

var isEmail = function(str) {
    return str.match(/^[\w._%+-]+@[\w._%+-]+\.\w{2,4}$/i, str);
};

jQuery(document).ready(function() {
   
   /*
    * slideshow
    */
   jQuery('.slideshow').slideshow({
      imageControlLabel: ml('slideshow_image_control_button'),
      videoControlLabel: ml('slideshow_video_control_button'),
      prevControlImage:  DR+'/media/gif/arrow_left.gif',
      nextControlImage:  DR+'/media/gif/arrow_right.gif'
   });
   
   /*
    * navigation
    */
   jQuery('.head .navi-item .subnavi').before('<div class="subnavi-pos subnavi-bg"></div>').find('a').each(function() {
      if (jQuery(this).hasClass('active')) {
         jQuery(this).parent().parent().parent().children('.main-link').addClass('active');
      }
   });
   jQuery('.head .navi-item a').each(function() {
      var subnavi = jQuery(this).parent().children('.subnavi');
      var overlay = jQuery(this).parent().children('.subnavi-bg');
      jQuery(this).mouseenter(function() {
         var position = {
            top: '-185px',
            left: jQuery(this).offset().left - jQuery('.head .navi').offset().left
         };
         subnavi.css(position).show();
         overlay.css(position).css({
            opacity: 0.7
         }).show();
      }).parent().mouseleave(function() {
         subnavi.hide();
         overlay.hide();
      });
   });
   
   /*
    * sidebar lines
    */
   jQuery('.main .sidebar .line').css({
      opacity: 0.7
   });
   
   /*
    * archive search
    */
   if (!jQuery('.main .sidebar .archive').hasClass('open')) {
      jQuery('.main .sidebar .archive .detail-wrap').hide();
   }
   jQuery('.main .sidebar .archive .detail-wrap').parent().children('.button').click(function() {
      jQuery(this).parent().children('.detail-wrap').slideToggle();
   });
   jQuery('.main .sidebar .archive-search .submit-button').click(function() {
      var container = jQuery('.main .sidebar .archive-search');
      var query = container.find('.query-wrap input').val();
      if (query == ml('archive_search_default_value')) {
         query = '';
      }
      if (query.length > 0) {
         var searchTitle = container.find('.checkbox-wrap input[name=search_title]')[0].checked ? 1 : 0;
         var searchSubtitle = container.find('.checkbox-wrap input[name=search_subtitle]')[0].checked ? 1 : 0;
         var searchText = container.find('.checkbox-wrap input[name=search_text]')[0].checked ? 1 : 0;

         var url = DR+'/'+ml_getCurrentLanguage()+'/archive/'+escape(query)+'/'+searchTitle+'/'+searchSubtitle+'/'+searchText+'/1';
         document.location.href = url;
      }
      return false;
   });
   jQuery('.main .sidebar .archive-search .query-wrap input').defaultValuedInput(ml('archive_search_default_value')).keypress(function(e) {
      if (e.which == 13) {
         jQuery('.main .sidebar .archive-search .submit-button').click();
      }
   });

   /*
    * contentboxes
    */
   var highestContentBoxHeight = 0;
   jQuery('.main .contentbox-wrap .contentbox').each(function() {
      var height = jQuery(this).height();
      if (height > highestContentBoxHeight) {
         highestContentBoxHeight = height;
      }
   }).height(highestContentBoxHeight);
   
   /*
    * background
    */
   jQuery('<div class="content-bg"></div>').css({
      opacity: 0.7
   }).insertBefore('.main .content-wrap');
   jQuery('.main .content-wrap, .main .sidebar .magazine-entry > .content').css({
      'background-color': 'transparent'
   });
   var ajustBackgroundSize = function() {
      var window_height = jQuery(window).height();
      var wrap_height = jQuery('body > .wrap').outerHeight(true);
      jQuery('body > .wrap-bg').height(window_height > wrap_height ? window_height : wrap_height);
      jQuery('.main .body .content-bg').height(jQuery('.main .content-wrap').outerHeight());
   };
   jQuery(window).load(ajustBackgroundSize).resize(ajustBackgroundSize).resize();
   window.setInterval(ajustBackgroundSize, 500);

   jQuery('.main .sidebar .magazine-entry').each(function() {
      jQuery('<div class="content-bg"></div>').css({
         opacity: 0.7
      }).prependTo(this).height($(this).outerHeight(true));
   });
   
   /*
    * slideable
    */
   jQuery('.main .content-wrap .slideable').each(function() {
      jQuery(this).children('.title').children('.trigger_close').click(function() {
         jQuery(this).hide().parent().children('.trigger_open').show().parent().parent().children('.text').hide();
      }).click().end().children('.trigger_open').click(function() {
         jQuery(this).hide().parent().children('.trigger_close').show().parent().parent().children('.text').show();
      });
   });
   
   /*
    * login
    */
   jQuery('.main .content-wrap .loginform .submitbutton').click(function() {
      var form = jQuery('.main .content-wrap .loginform');
      var username = form.find('input[name=user]').val();
      var password = form.find('input[name=pass]').val();

      jQuery.getJSON(DR+'/ajax.php', {
         'action': 'login',
         'user':   username,
         'pass':   password
      }, function(data) {
         if (data.status == 'success') {
            document.location.href = document.location.href; // simple reload
         } else {
            var errmsg = form.find('.errormessage');
            errmsg.slideDown();
            window.setTimeout(function() {
               errmsg.slideUp();
            }, 3000);
         }
      });
      
      // login at cb-print
      jQuery.getJSON('http://new.heimat.de/regieguide/admin/login_handbuch.php3?callback=?', {
         'account': username,
         'kenn':    password
      }, function(data) {
         if (data.status == 'success') {
            jQuery.getJSON(DR+'/ajax.php', {
               action: 'set_cb_print_sid',
               sid:    data.sid
            });
         }
      });

      // login at cb-film
      jQuery.getJSON('http://new.heimat.de/culturebase/cb_film/login.php?callback=?', {
         'id_language': '1',
         'name':        username,
         'pass':        password,
         'login':       '1'
      }, function(data) {
         if (data.status == 'success') {
            jQuery.getJSON(DR+'/ajax.php', {
               action: 'set_cb_film_auth'
            });
         }
      });

      return false;
   });
   jQuery('.main .content-wrap .loginform input[name=pass]').keypress(function(e) {
      if (e.which == 13) { // enter
         jQuery('.main .content-wrap .loginform .submitbutton').click();
      }
   });

   /**
    * logout
    */
   jQuery('.main .sidebar .logout').click(function() {
      jQuery.getJSON(DR+'/ajax.php', {
         'action': 'logout'
      }, function() { // TODO: maybe logout from cb_film and handbuch (not obvious how ...)
         document.location.href = document.location.href;
      });
   });

   /*
    * print
    */
   jQuery('a[href$=?print]').click(function() {
      window.print();
      return false;
   });
   
   /*
    * popups
    */
   jQuery('a.popup').click(function() {
      window.open(jQuery(this).attr('href'), '', 'width=740,height=560');
      return false;
   });
   
   /*
    * film search
    */
   jQuery('.main .sidebar .film-search .submit-button').click(function() {
      var container = jQuery('.main .sidebar .film-search');
      var baseUrl = DR+'/'+ml_getCurrentLanguage()+'/guide/films/';

      // determine values
      var values = {
         query:    container.find('input[name=query]').val(),
         category: container.find('select[name=category]').val(),
         yearFrom: container.find('input[name=year_from]').val(),
         yearTo:   container.find('input[name=year_to]').val()
      };

      if (values.query == ml('film_search_query_default')) {
         values.query = '';
      }
      if (values.yearFrom == '' || values.yearFrom.match(/[^\d]/)) {
         values.yearFrom = 0;
      }
      if (values.yearTo == '' || values.yearTo.match(/[^\d]/)) {
         values.yearTo = 0;
      }

      var isEmpty = values.query.length == 0 && values.category == 0
                    && values.yearFrom == 0 && values.yearTo == 0;

      // load url
      if (isEmpty) {
         document.location.href = baseUrl+'all';
      } else {
         document.location.href = baseUrl+escape(values.query)+'/'
                                  +values.category+'/'+values.yearFrom+'/'
                                  +values.yearTo+'/1';
      }
      
      // prevent default
      return false;
   });
   
   jQuery('.main .sidebar .film-search input').keypress(function(e) {
      if (e.which == 13) { // return
         jQuery('.main .sidebar .film-search .submit-button').click();
      }
   });

   jQuery('.main .sidebar .film-search input').each(function() {
      var name = jQuery(this).attr('name');
      var title = jQuery(this).attr('title');
      jQuery(this).defaultValuedInput(ml('film_search_'+name+'_default'))
      if (title.length > 0) {
         jQuery(this).val(title).addClass('active');
      }
   });

   jQuery('.main .sidebar .film-search select').change(function() {
      if (jQuery(this).val() == 0) {
         jQuery(this).removeClass('active');
      } else {
         jQuery(this).addClass('active');
      }
      jQuery(this).blur();
   }).change();

   /*
    * contact form
    */
   jQuery('.main .content-wrap .contact-form .submit-button').click(function() {
      var element = this;
      if (!jQuery(this).hasClass('submitting')) {
         jQuery(this).addClass('submitting');
         
         var fields = {};
         var requiredFieldsNotEmpty = true;
         jQuery('.main .content-wrap .contact-form').find('input, textarea').each(function() {
            fields[jQuery(this).attr('name')] = jQuery(this).val();
            if ((jQuery(this).hasClass('required') && jQuery(this).val() == '') ||
                (jQuery(this).attr('name') == 'email' && !isEmail(jQuery(this).val()))
                ) {
               requiredFieldsNotEmpty = false;
            }
         });

         if (requiredFieldsNotEmpty) {
            jQuery.getJSON(DR+'/ajax.php', jQuery.extend({
               action: 'submit_contact_form'
            }, fields), function(data) {
               if (data.status == 'success') {
                  // reset "form"
                  jQuery('.main .content-wrap .contact-form').find('input, textarea').each(function() {
                     jQuery(this).val('');
                  });
                  alert(ml('contact_form_completed_notice'));
               } 
               else {
                  alert(ml('contact_form_delivery_error'));
               }
               jQuery(element).removeClass('submitting');
            });
         } else {
            alert(ml('contact_form_incomplete_notice'));
            jQuery(this).removeClass('submitting');
         }
      }
      return false;
   });

   jQuery('.main .content-wrap .contact-form input').keypress(function(e) {
      if (e.which == 13) { // return
         jQuery('.main .content-wrap .contact-form .submit-button').click();
      }
   });

   /*
    * indexed search
    */
   jQuery('.head .search').hover(function() {
      jQuery(this).addClass('active');
   }, function() {
      if (!jQuery(this).find('input').hasClass('active')) {
         jQuery(this).removeClass('active');
      }
   }).find('input').defaultValuedInput(ml('indexed_search_default_value')).blur(function() {
      jQuery('.head .search').mouseleave();
   }).keypress(function(e) {
      if (e.which == 13) {
         jQuery('.head .search a').click();
      }
   });

   jQuery('.head .search a').click(function() {
      var query = jQuery('.head .search input').val();
      if (query != ml('indexed_search_default_value')) {
         document.location.href = DR+'/'+ml_getCurrentLanguage()+'/search/'+escape(query)+'/1';
      }
      return false;
   });

   /*
    * admin layer
    */
   jQuery('.admin-layer-opener').click(function() {
      jQuery('.admin-layer').slideDown();
   });

   /*
    * checkboxes
    */
   jQuery('input[type=checkbox]').checkbox();
   
});

