// document root
var DR = '/';
if (document.location.href.match(/\/efa\//)) {
   DR += 'efa/';
}

// iphone detection
$.browser.iphone = navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i);

$(document).ready(function() {
   
   /*
    * functions
    */
   var show_media_loader = function(callback) {
      $('.media-container .loader-layer').addClass('visible').stop()
         .css('opacity','0').show().animate({'opacity':'1'}, 250, callback);
   };
   var hide_media_loader = function(callback) {
      var element = $('.media-container .loader-layer');
      element.removeClass('visible').animate({'opacity':'0'}, 250, function() {
         element.hide();
         if (callback) {
            callback();
         }
      });
   };
   var loadPlayer = function(file, image, id, autostart) {
      var autostart = autostart || false;
      // file docroot
      var FDR = 'http://dev1.heimat.de/playertest/new_player/';
      // params: swfFile, id, width, height, flashVersion, ?
      var so = new SWFObject(FDR+'player-viral.swf', 'player-object', '720', '405', '9', '#ffffff');
	   so.addParam('allowfullscreen', 'true');
	   so.addParam('allowscriptaccess', 'always');
	   so.addParam('wmode', 'opaque');
	   so.addVariable('icons', 'false');
	   so.addVariable('controlbar', 'none');
	   so.addVariable('repeat', 'list');
	   so.addVariable('image', image);
	   so.addVariable('plugins', FDR+'player_style02.swf');
	   so.addVariable('skindata', FDR+'style02_skindata.xml');
	   so.addVariable('filmdata', escape(DR+'ajax.php?method=getFilmXML&id='+id));
	   so.addVariable('moduldir', FDR+'mod');
	   so.addVariable('file', file);
	   if (autostart) {
	      so.addVariable('autostart', true);
	   }
      so.write('player');
   };
   var getJSON = function(string) {
      if (string != '') {
         return eval('('+string+')');
      } else {
         return null;
      }
   };
   var openVideo = function(id, autostart) {
      $.post(DR+'ajax.php?method=getFilm', {id:id}, function(data) {
         data = getJSON(data);
         loadPlayer(data.file, data.image, id, autostart);
         $('.player').show();
         hide_media_loader();
      });
   };
   var initSlideshow = function() {
      $('.player').hide();
      $('.media-container .slideshow').show().find('.controlbar-background').css('opacity','0.8');
   };
   var openSlideshow = function(id, method, startimage) {
      method = method || 'getMediaSeriesByImageId';
      $.post(DR+'ajax.php?method='+method, {id:id}, function(data) {
         data = getJSON(data);
         var contents = $('.media-container .slideshow .contents').html('');
         $('.media-container .slideshow .content').html('');
         $(data).each(function() {
            var url = $('<div class="url"></div>').html(this.url.replace('&amp;', '&'));
            var title = $('<div class="title"></div>').html(this.title);
            var description = $('<div class="description"></div>').html(this.description);
            var content = $('<div></div>').append(url).append(title).append(description);
            $(content).appendTo(contents);
         });
         if (startimage) {
            var copy;
            contents.children().each(function() {
               if ($(this).find('.url').html().replace(/\&.*$/, '') == startimage) {
                  copy = $(this).clone();
                  $(this).remove();
                  return true;
               }
            });
            if (copy) {
               contents.prepend(copy);
            }
         }
         $.slideshowDisplayImage();
         hide_media_loader();
      });
   };
   var addNavigationHover = function(element, navitype) {
      $('<div class="'+navitype+'navigation-hover navigation-hover"></div>').css({
         'opacity': 0.3,
         'background-color': '#000000',
         'z-index': 1,
         'position': 'absolute',
         'top': $(element).offset().top,
         'left': $(element).offset().left,
         'width': $(element).outerWidth(),
         'height': $(element).outerHeight()
      }).appendTo('body');
   };
   var removeNavigationHover = function(navitype) {
      navitype = navitype || '';
      $('.'+navitype+'navigation-hover').remove();
   };
   var checkSubnavigation = function(sub) {
      var hasActive = false;
      sub.children().each(function() {
         if ($(this).hasClass('active')) {
            sub.show();
            addNavigationHover(this, 'sub-active');
            hasActive = true;
         }
      });
      return hasActive;
   };
   var getSubnavigation = function(element) {
      var name = $(element).children('.name').html();
      return $('.subnavigation > .'+name);
   };
   
   /*
    * media controls
    */
   $('.media-container .slider .entry .image, .gallery-entry .image').click(function() {
      if (($('#player-object').length > 0 || $('.media-container .slideshow').css('display') != 'none') && $('html, body')[0].scrollTop > $('.media-container').offset().top) {
         $('html, body').animate({'scrollTop':($('.media-container').offset().top - 75)+'px'}, 500);
      }
      var element = $(this);
      initSlideshow();
      show_media_loader(function() {
         var type = element.parent().children('.type').html();
         if (type == 'image') {
            var id = parseInt(element.parent().children('.id').html());
            var image = element.find('img').attr('src').replace(/\&.*$/, '');
            openSlideshow(id, 'getMediaSeriesByImageId', image);
         } else if (type == 'video') {
            $('.media-container .slideshow').hide();
            var id = parseInt(element.parent().children('.id').html());
            
            // autostart video if it's not the first one (e.g. clicked in gallery or mediaslider)
            var autostart = false;
            if ($('#player-object').length > 0) {
               autostart = true;
            }
            
            openVideo(id, autostart);
         }
      });
   });
   $('a.cb-player').click(function() {
      var id = parseInt($(this).children('.id').html());
      show_media_loader(function() {
         openVideo(id);
      });
      return false;
   });
   
   /*
    * link helpers
    */
   $('.magazine-entry-box').click(function() {
      document.location.href = $(this).children('.target').html();
   });
   
   /*
    * navigation helpers
    */
   $('.navigation a').each(function() {
      // center all subnavigations above their parent navigation-point
      var sub = getSubnavigation(this);
      if ($(sub).length > 0) {
         sub.show();
         var pos = $(this).offset().left - $('.navigation').offset().left + ($(this).width() / 2) + parseInt($(this).css('padding-left').replace('px', ''));
         pos = parseInt(pos - ($(sub).width() / 2));
         if (pos < 0) {
            pos = 0;
         }
         sub.css({'padding-left':pos+'px'}).hide();
      }
   }).each(function() {
      var sub = getSubnavigation(this);
      checkSubnavigation(sub);
      if ($(this).hasClass('active')) {
         addNavigationHover(this, 'main-active');
      }
   }).hover(function() {
      removeNavigationHover('sub');
      removeNavigationHover('sub-active');
      removeNavigationHover('main');
      addNavigationHover(this, 'main');
      var sub = getSubnavigation(this);
      $('.subnavigation').children().hide();
      sub.show();
      checkSubnavigation(sub);
   }, function() {
      removeNavigationHover('sub');
      removeNavigationHover('main');
   });
   $('.subnavigation a').hover(function() {
      removeNavigationHover('sub');
      removeNavigationHover('main');
      addNavigationHover(this, 'sub');
      var parentName = $(this).parent().attr('class').replace(/\s*hidden\s*/, '');
      addNavigationHover($('.navigation > a.'+parentName), 'main');
   }, function() {
      removeNavigationHover('sub');
   });
   
   $('.magazine-entry-box, .nominations-entry-box').click(function() {
      document.location.href = $(this).children('.target').html();
   });
   $('a').each(function() {
      var matches = $(this).attr('href').match(/(\#.+)$/);
      if (matches) {
         $(this).click(function() {
            var pos = $(matches[1]).offset().top;
            $('html, body').animate({'scrollTop':pos+'px'}, 500);
            return false;
         });
      }
   });
   
   /*
    * newsletter
    */
   $('.sidebar-newsletter').click(function() {
      $('.sidebar-newsletter-container').html($('.sidebar-newsletter-content').html()).removeClass('sidebar-box-hover');
      $('.sidebar-newsletter-container input').each(function() {
         var defaultValue = $(this).parent().parent().children('.sidebar-newsletter-default-value').html();
         $(this).focus(function() {
            if ($(this).val() == defaultValue) {
               $(this).val('');
            }
         }).blur(function() {
            if ($(this).val() == '') {
               $(this).val(defaultValue);
            }
         }).val(defaultValue);
      }).keypress(function(e) {
         if (e.which == 13) {
            $('.sidebar-newsletter-container .sidebar-newsletter-submit-button').click();
         }
      });
      $('.sidebar-newsletter-container .sidebar-newsletter-submit-button').click(function() {
         $.getJSON('http://cb-news.de/subscribe.php?user=58810&newsletter=314&callback=?', {
            subscribeaction: 'subscribe',
            FIRSTNAME:       $('.sidebar-newsletter-container input[name=firstname]').val(),
            SURNAME:         $('.sidebar-newsletter-container input[name=surname]').val(),
            EMAIL:           $('.sidebar-newsletter-container input[name=email]').val()
         }, function(data) {
            if (data.status == 'success') {
               var content = $('<div class="sidebar-newsletter-description"></div>').html($('.sidebar-newsletter-success-test').html());
               $('.sidebar-newsletter-container').html(content);
            } else {
               $('.sidebar-newsletter-description').html(data.message);
            }
         });
      });
      $('.sidebar-newsletter-container').addClass('sidebar-newsletter-container-expanded').siblings().remove();
      return false;
   });
   
   /*
    * style helpers (mainly because of IE's :hover bug)
    */
   $('a').click(function() {
      this.blur();
   });
   $('.content-box-hover-enabled').hover(function() {
      $(this).addClass('content-box-hover');
   }, function() {
      $(this).removeClass('content-box-hover');
   });
   $('.slider-content .entry .image').hover(function() {
      $(this).addClass('slider-entry-hover');
   }, function() {
      $(this).removeClass('slider-entry-hover');
   });
   $('.gallery-entry .image').hover(function() {
      $(this).addClass('gallery-entry-hover');
   }, function() {
      $(this).removeClass('gallery-entry-hover');
   });
   $('.media-container .slideshow .controlbar-content .buttons .prev').hover(function() {
      $(this).addClass('prev-hover');
   }, function() {
      $(this).removeClass('prev-hover');
   });
   $('.media-container .slideshow .controlbar-content .buttons .next').hover(function() {
      $(this).addClass('next-hover');
   }, function() {
      $(this).removeClass('next-hover');
   });
   $('.media-container .slideshow .controlbar-content .advanced-controls div').hover(function() {
      $(this).addClass('hover');
   }, function() {
      $(this).removeClass('hover');
   });
   $('.nominations-entry-block').each(function() {
      $(this).find('.nominations-entry-box:even').css('margin-right','10px');
   });
   
   /*
    * iPhone style fixes
    */
   if ($.browser.iphone) {
      $('.magazine-entry-box .text').css({
         'font-size':   '7px',
         'line-height': '9px'
      });
   }
   
   /*
    * sliders
    */
   $('.media-container .slider .slider-content').slider({
      leftButton:  '.slider-button-left',
      rightButton: '.slider-button-right',
      leftArea:    '.slider-area-left',
      rightArea:   '.slider-area-right',
      buttonSpeed: 5
   });
   $('.footer .slider .slider-content').slider({
      leftArea:   '.sponsors-slider-area-left',
      rightArea:  '.sponsors-slider-area-right',
      entry:      '.entry',
      continuous: true,
      autoScroll: true
   });
   
   /*
    * slideshow
    */
   $.slideshow({
      mainContainer:    '.slideshow',
      nextButton:       '.slideshow .controlbar-content .buttons .next',
      prevButton:       '.slideshow .controlbar-content .buttons .prev',
      imagesContainer:  '.slideshow .contents',
      displayContainer: '.slideshow .content',
      titleContainer:   '.slideshow .controlbar-content .description .title',
      descContainer:    '.slideshow .controlbar-content .description .text',
      controlbar:       '.slideshow .controlbar-content, .slideshow .controlbar-background',
      diashowButton:    '.slideshow .controlbar-content .adv-slideshow',
      numberContainer:  '.slideshow .controlbar-content .adv-number',
      continuous:       true
   });
   
   // load third element in slideshow at page ready
   $($('.media-container .slider .entry .image')[2]).click();
   
   // load first element in gallery at page ready
   $($('.gallery-entry .image')[0]).click();
   
   // autoloads for pages
   if ($('.media-container-open-video').length == 1) {
      openVideo(parseInt($('.media-container-open-video').html()));
      if ($('.media-container-custom-slideshow').length == 1) {
         $('.media-container .slideshow .contents').html($('.media-container-custom-slideshow').html());
      }
   } else {
      if ($('.media-container-open-slideshow').length == 1) {
         initSlideshow();
         openSlideshow(parseInt($('.media-container-open-slideshow').html()), 'getMediaSeries');
      }
      if ($('.media-container-custom-slideshow').length == 1) {
         $('.media-container .slideshow .contents').html($('.media-container-custom-slideshow').html());
         initSlideshow();
         $.slideshowDisplayImage();
      }
   }
   
   /*
    * search
    */
   var searchDefaultValue = $('.search-container .search-input-container .search-default-value').html();
   var searchInputElement = $('.search-container .search-input-container input');
   searchInputElement.focus(function() {
      if (searchInputElement.val() == searchDefaultValue) {
         searchInputElement.val('');
      }
   }).blur(function() {
      if (searchInputElement.val() == '') {
         searchInputElement.val(searchDefaultValue);
      }
   }).val(searchDefaultValue);
   
   $('.search-container .search-submit-button').click(function() {
      var query = searchInputElement.val();
      query = escape(query.replace(/[\'\"\#\%]+/, ' '));
      document.location.href = $('.search-container .search-submit-target').html()+query;
   });
   searchInputElement.keypress(function(e) {
      if (e.which == 13) { // enter
         $('.search-container .search-submit-button').click();
      }
   });
   
   /*
    * gallery
    */
   $('.gallery-chooser').change(function() {
      var target = $(this).parent().find('.target').html();
      if ($(this).val() == '') {
         target = target.replace(/\/$/, '');
      }
      target += $(this).val();
      document.location.href = target;
   });
   
   /*
    * admin layer
    */
   $('.admin-layer-open-button').click(function() {
      $('.admin-layer .admin-layer-background').css({
         'opacity': '0.7'
      });
      $('.admin-layer').stop().animate({
         'height': '32px'
      }, 300);
   });
   $('.admin-layer-close-button').click(function() {
      $('.admin-layer').stop().animate({
         'height': '0px'
      }, 300);
   });
   /*$('.admin-layer').mouseleave(function() {
      if (!$(this).hasClass('admin-layer-authed')) {
         $('.admin-layer-close-button').click();
      }
   });*/
   $('.admin-layer input').focus(function() {
      if (!$(this).hasClass('custom-value')) {
         $(this).css('color','#ffffff').val('').addClass('custom-value');
      }
   });
   $('.admin-layer .loginbutton').click(function() {
      $.getJSON('http://new.heimat.de/culturebase/cb_mdb/cms/login.php?proj=44&callback=?', {
         proj:    '44',
         todo:    'login',
         account: $('.admin-layer-login input[name=username]').val(),
         kenn:    $('.admin-layer-login input[name=password]').val()
      }, function(data) {
         if (data.status == 'success') {
            $.post(DR+'ajax.php?method=establishExternalSession');
            switchAdminLayerContent();
         } else if (data.status == 'failure') {
            alert('Your login attempt failed. Please check accountname and password and try again.');
         } else {
            alert('An unknown error occurred. Please try again.');
         }
      });
   });
   var switchAdminLayerContent = function() {
      $('.admin-layer').addClass('admin-layer-authed');
      $('.admin-layer-login').hide();
      $('.admin-layer-box, .admin-layer-separator').css({
         'display': 'inline'
      });
   };
   if ($('.admin-layer').hasClass('admin-layer-authed')) {
      switchAdminLayerContent();
   }
   $('.admin-layer-login input').keypress(function(e) {
      if (e.which == 13) { // enter
         $('.admin-layer .loginbutton').click();
      }
   });
   
   /*
    * layer
    */
   $('.is-person-indicator').each(function() {
      var element = $(this);
      var titleElement = $(this).parent().find('.sidebar-box-title');
      titleElement.css({
         'position': 'absolute',
         'left': '6px',
         'right': '6px',
         'bottom': '4px',
         'width': '196px',
         'z-index': '1'
      });
      var bgLayer = function() {
         $('.sidebar-box-title-background').remove();
         $('<span class="sidebar-box-title-background"></span>').css({
            'position': 'absolute',
            'left': '4px',
            'right': '4px',
            'bottom': '4px',
            'width': '200px',
            'height': titleElement.height(),
            'background-color': '#000000',
            'opacity': '0.65',
            'z-index': '0'
         }).appendTo(titleElement.parent());
      };
      bgLayer();
      titleElement.parent().click(function() {
         if ($('.active-content-type').html() == 'promo-box-person-indicator') {
            $('.active-content-type').html('default');
         }
         if ($('.active-content-type').html() != 'default') {
            $('.swap-player-with-slideshow').click();
         }
         var gallery = $(this).find('.person-portrait-gallery').html();
         if ($('#player-object').length > 0) {
            if ($('.player').css('display') == 'none') {
               $('.player').show();
               $('.media-container .slideshow').hide();
               $(this).find('.sidebar-box-title').html($($('.media-container .slideshow .contents').children()[0]).find('.title').html());
               bgLayer();
               $(this).find('img').attr('src', $(this).find('.original-image').html().replace(/\&amp;/g, '&'));
            } else {
               if (!$('.media-container .slideshow').hasClass('initialized')) {
                  $('.media-container .slideshow').addClass('initialized');
                  $('.media-container .slideshow .contents').html(gallery);
                  $('<span class="hidden original-image"></span>').html($(this).find('img').attr('src')).appendTo($(this));
                  initSlideshow();
                  $.slideshowDisplayImage();
               } else {
                  $('.player').hide();
                  $('.media-container .slideshow').show();
               }
               $(this).find('.sidebar-box-title').html('European Film Awards');
               bgLayer();
               $(this).find('img').attr('src', $('#player-object').attr('flashvars').replace(/^.*\&image=/, '').replace(/cropIn.*$/, 'cropOut').replace('width=720', 'width=200').replace('height=405', 'height=150'));
            }
         } else {
            $(this).find('.sidebar-box-title').html($($('.media-container .slideshow .contents').children()[0]).find('.title').html());
            bgLayer();
            $(this).find('img').attr('src', $($('.media-container .slideshow .contents').children()[0]).find('.url').html().replace(/\&amp;/g, '&').replace('cropIn', 'cropOut').replace('width=720', 'width=200').replace('height=405', 'height=150'));
            $(this).find('.person-portrait-gallery').html($('.media-container .slideshow .contents').html());
            $('.media-container .slideshow .contents').html(gallery);
            initSlideshow();
            $.slideshowDisplayImage();
         }
         return false;
      });
   });
   $('.swap-player-with-slideshow').click(function() {
      if ($('.active-content-type').html() == 'player-swapped-with-slideshow') {
         $('.active-content-type').html('default');
      }
      if ($('.active-content-type').html() != 'default') {
         $('.is-person-indicator').parent().click();
      }
      if ($('.player').css('display') == 'none') {
         $('.player').show();
         $('.media-container .slideshow').hide();
         $(this).html($('.ml_label_sidebar_gallery_slideshow').html());
      } else {
         if (!$(this).hasClass('initialized')) {
            $(this).addClass('initialized');
            initSlideshow();
            $.slideshowDisplayImage();
         }
         $('.player').hide();
         $('.media-container .slideshow').show();
         $(this).html($('.ml_label_sidebar_gallery_video').html());
      }
      return false;
   });
   
   if (document.location.href.match(/europeanactor/) || document.location.href.match(/europeanactress/)) {
      window.setTimeout(function() {
         $('.person-portrait-gallery').parent().click();
      }, 1000);
   }
   
});
