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

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

$(document).ready(function () {

   // Touch-devices get an additional padding for the whole page to make it look
   // a bit nicer. We do this up here, because other calculations are based on
   // this.
   if ($.browser.ipad || $.browser.iphone) {
      $('html, body, body > .background').width(1050);
      $('body > .background .shadow').css('top', '-=2px');
   }
   if ($.browser.iphone) {
      $('.navigation a, .subnavigation a').css('font-size', '9px');
   }

   /*
    * 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 container = $('#player');

      // Make sure the player is fully visible.
      container.stop().css({
         opacity: 1.0
      }).show();

      // Remove everything in the container and add a player element.
      container.empty();
      $(document.createElement('div')).addClass('__CbUiPlayer').appendTo(container);

      // Fire it up!
      CbPlayerWindow.create(container, {
         config:   id == 0 ? 'live' : 'efa',
         movie_id: id,
         image:    image,
         width:    720,
         height:   400,
         modal:    false
      }, 'CbSimplePlayerWindow');
   };
   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').text());
            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').text());

            // 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').live('click', function () {
      var id = parseInt($(this).children('.id').text());
      show_media_loader(function () {
         openVideo(id);
      });
      return false;
   });

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

      // This required for touch devices, because they trigger a hover effect
      // instead of following the link at the first tap. We only do this for
      // menu items without a sub-navigation, because sub-menus would not be
      // accessible otherwise.
      if ($.browser.ipad && sub.length === 0) {
         window.location.assign(this.href);
      }
   }, 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');

      // This required for touch devices, because they trigger a hover effect
      // instead of following the link at the first tap.
      if ($.browser.ipad) {
         window.location.assign(this.href);
      }
   }, function () {
      removeNavigationHover('sub');
   });

   $('a').each(function () {
      var href = $(this).attr('href');
      if (href) {
         var matches = href.match(/(\#.+)$/);
         if (matches) {
            $(this).live('click', function () {
               var pos = $(matches[1]).offset().top;
               $('html, body').animate({'scrollTop':pos+'px'}, 500);
               return false;
            });
         }
      }
   });

   // Touch-devices do not need print buttons, etc. We simply hide them.
   if ($.browser.ipad) {
      $('.contentnavigation-box-right').hide();
   }

   /*
    * newsletter
    */
   $('.sidebar-newsletter').click(function () {
      $('.sidebar-newsletter-content').clone().removeClass('hidden sidebar-newsletter-content').addClass('sidebar-box sidebar-newsletter-container sidebar-newsletter-container-expanded').prependTo('.media-container .sidebar');
      $('.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-close-button').click(function () {
         $('.sidebar-newsletter-container').eq(0).remove();
         return false;
      });
      return false;
   });

   /*
    * style helpers (mainly because of IE's :hover bug)
    */
   $('a').live('click', function () {
      this.blur();
   });
   $('.content-box-hover-enabled').live('mouseenter', function () {
      $(this).addClass('content-box-hover');
   }).live('mouseleave', 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 .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').stepSlider({
      leftButton:     '.media-container .slider-button-left',
      rightButton:    '.media-container .slider-button-right',
      visibleEntries: 5,
      entrySelector:  '.entry'
   });
   $('.footer .slider .slider-content').mediaSlider({
      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,
      hideControlsDelay: 500
   });

   // 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').find('.video-id').html(), 10), $('.media-container-open-video').find('.video-autostart').html() == 'true' ? true : false);
      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').text(), 10), 'getMediaSeries');
      }
      if ($('.media-container-custom-slideshow').length == 1) {
         $('.media-container .slideshow .contents').html($('.media-container-custom-slideshow').html());
         initSlideshow();
         $.slideshowDisplayImage();
      }
      if ($('.media-container-custom-image').length == 1) {
         $('.media-container .player-container').append('<div class="custom-image">'
                                                          +'<img src="http://data.heimat.de/transform.php?file='+encodeURIComponent($('.media-container-custom-image').html())+'&amp;width=720&amp;height=405&amp;do=cropOut" alt="" />'
                                                       +'</div>');
      }
   }

   /*
    * 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').text();

      if ($(this).val() == '') {
         target = target.replace(/\/$/, '');
      }

      document.location.href = target+$(this).val();
   });

   /*
    * layer
    */
   $('.is-person-indicator').each(function () {
      var titleElement = $(this).parent().find('.sidebar-box-title').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();
      $(this).parent().click(function () {
         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;
      });

      if ($(this).text() == 'instant') {
         $(this).parent().click();
      }
   });
   $('.swap-player-with-slideshow').click(function () {
      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();
         $('#player-object').get(0).sendEvent('STOP');
         $('.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);
   }

   /*
    * voting
    */
   $('.peopleschoiceaward-entry-box .detail-link').click(function(e) {
      e.stopImmediatePropagation();
      document.location.href = $(this).attr('href');
   });
   $('.peopleschoiceaward-entry-box').click((function () {
      var translated = false;
      var background = $('<div class="vote-layer-background"></div>').css('opacity', 0.9);
      var layer = $('<div class="vote-layer">'
                      +'<a href="#close" class="close-button cb-ml">close_button</a>'
                      +'<div class="vote-padding enter-page">'
                         +'<div class="title cb-ml">headline_title</div>'
                         +'<div class="subtitle cb-ml">headline_subtitle</div>'
                         +'<div class="form">'
                            +'<div class="details-title cb-ml">personal_details_title</div>'
                            +'<input type="hidden" name="id" value="" />'
                            +'<div>'
                               +'<input name="surname" class="full-width required cb-ml" value="form_surname" tabindex="1" />'
                            +'</div>'
                            +'<div>'
                               +'<input name="forename" class="full-width required cb-ml" value="form_forename" tabindex="2" />'
                            +'</div>'
                            +'<div>'
                               +'<input name="email" class="full-width required cb-ml" value="form_email" tabindex="3" />'
                            +'</div>'
                            +'<div>'
                               +'<input name="zip" class="zip required cb-ml" class="cb-ml" value="form_zip" tabindex="5" />'
                               +'<input name="city" class="city required cb-ml" class="cb-ml" value="form_city" tabindex="4" />'
                            +'</div>'
                            +'<div>'
                               +'<input name="country" class="full-width required cb-ml" value="form_country" tabindex="6" />'
                            +'</div>'
                            +'<div>'
                               +'<input type="checkbox" name="subscribe" class="subscribe" tabindex="7" />'
                               +'<span class="subscribe-title cb-ml">subscribe</span>'
                            +'</div>'
                            +'<div class="nomination-headline cb-ml">nomination_title</div>'
                            +'<div class="nomination">'
                               +'<img src="" alt="" />'
                               +'<div class="nomination-title">'
                                  +'<div class="film-title"></div>'
                                  +'<div class="film-subtitle"></div>'
                               +'</div>'
                            +'</div>'
                            +'<a href="#vote" class="vote-button">'
                               +'<span class="vote-headline">'
                                  +'<span class="vote-title cb-ml">you_selected</span>'
                                  +'<span class="vote-name"></span>'
                               +'</span>'
                               +'<span class="vote-subtitle cb-ml">submit_vote</span>'
                            +'</a>'
                         +'</div>'
                      +'</div>'
                      +'<div class="vote-padding confirm-page">'
                         +'<div class="title cb-ml">headline_confirm_title</div>'
                         +'<div class="subtitle cb-ml">headline_confirm_subtitle</div>'
                         +'<div class="text cb-ml">text_confirm</div>'
                      +'</div>'
                      +'<div class="vote-padding already-voted-page">'
                         +'<div class="title cb-ml">headline_already_voted_title</div>'
                         +'<div class="subtitle cb-ml">headline_already_voted_subtitle</div>'
                         +'<div class="text cb-ml">text_already_voted</div>'
                      +'</div>'
                   +'</div>');

      if ($.browser.msie) {
         background.css('position', 'absolute');

         layer.css({
            position: 'absolute',
            margin:   '0px'
         });

         layer.find('input[type="text"]').height(34);
         layer.find('input.full-width').width(720);
         layer.find('input.city').width(605);
         layer.find('input.zip').width(110).css('margin-top', '1px');

         var resizeAndRepositionLayer = function () {
            var top = $(window).scrollTop();
            var left = $(window).scrollLeft();
            var windowWidth = $(window).width();
            var windowHeight = $(window).height();

            background.css({
               top:    top+'px',
               left:   left+'px',
               width:  windowWidth+'px',
               height: windowHeight+'px'
            });

            layer.css({
               top:  Math.round(top + windowHeight / 2 - layer.height() / 2)+'px',
               left: Math.round(left + windowWidth / 2 - layer.width() / 2)+'px'
            });
         };

         $(window).resize(resizeAndRepositionLayer);
         $(window).scroll(resizeAndRepositionLayer);
      }

      var close = function () {
         background.fadeOut(250, function () {
            $(this).detach();
         });
         layer.fadeOut(250, function () {
            $(this).detach();
         });
      };

      var open = function(film) {
         $('body').append(background).append(layer);

         background.fadeIn(250, function () {
            var initLayer = function () {
               layer.find('.vote-padding').hide();
               layer.find('.vote-padding.enter-page').show();

               layer.find('.nomination .film-title, a.vote-button .vote-name').text(film.title);
               layer.find('.nomination .film-subtitle').text(film.subtitle);
               layer.find('.nomination img').attr('src', film.image.replace(/width=\d+/, 'width=95').replace(/height=\d+/, 'height=66'));
               layer.find('.form input[name="id"]').val(film.id);

               if (resizeAndRepositionLayer) {
                  resizeAndRepositionLayer();
               }

               layer.fadeIn(250);
            };

            if (translated) {
               // Show layer.
               initLayer();
            } else {
               // Collect all used ML-bricks.
               var labelsRequestString = '';
               layer.find('.cb-ml').each(function () {
                  var text;

                  if ($(this).is('input')) {
                     text = $(this).val();
                  } else {
                     text = $(this).text();
                  }

                  labelsRequestString += '&labels[]=vote_layer_'+text;
               });

               // Additional ML-bricks.
               $.each(['fields_empty', 'terms_not_accepted'], function(index, label) {
                  labelsRequestString += '&labels[]=vote_layer_'+label;
               });

               // Recieve all used ML-bricks.
               $.getJSON(DR+'ajax.php?method=getMlBricks'+labelsRequestString, function(labels) {
                  var ml = function(label) {
                     return labels['vote_layer_'+label];
                  };

                  // Translate all ML-containing elements.
                  layer.find('.cb-ml').each(function () {
                     if ($(this).is('input')) {
                        var text = ml($(this).val());
                        $(this).val('').defaultValuedInput(text);
                     } else {
                        $(this).text(ml($(this).text()));
                     }
                  });
                  translated = true;

                  // Bind stuff.
                  layer.find('a.close-button').click(function () {
                     if (!$(this).hasClass('disabled')) {
                        close();
                     }
                     return false;
                  });
                  layer.find('a.vote-button').click(function () {
                     if (!$(this).hasClass('submitting')) {
                        // Check for required fields.
                        var requiredFieldsEmpty = false;
                        layer.find('input.required').removeClass('highlight').each(function () {
                           if (!$(this).hasClass('active') || ($(this).attr('name') == 'email' && !$(this).val().match(/^\s*[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\s*$/i))) {
                              $(this).filter('[type="text"]').addClass('highlight');
                              requiredFieldsEmpty = true;
                           }
                        });

                        if (requiredFieldsEmpty) {
                           // Notify user.
                           alert(ml('fields_empty'));
                        } else {
                           // Check for terms of use.
                           //if (layer.find('input.accept-terms').attr('checked')) {
                              // Collect data.
                              var data = {
                                 surname:   layer.find('.form input[name="surname"]').val(),
                                 firstname: layer.find('.form input[name="forename"]').val(),
                                 email:     layer.find('.form input[name="email"]').val(),
                                 city:      layer.find('.form input[name="city"]').val(),
                                 zip:       layer.find('.form input[name="zip"]').val(),
                                 country:   layer.find('.form input[name="country"]').val(),
                                 filmId:    layer.find('.form input[name="id"]').val(),
                                 subscribe: layer.find('.form input[name="subscribe"]:checked').val()
                              };

                              // Disable buttons to prevent another invocation
                              // or closing the layer.
                              layer.find('a.vote-button').addClass('submitting');
                              layer.find('a.close-button').addClass('disabled');

                              // Submit vote.
                              $.get(DR+'ajax.php?method=vote', data, function(status) {
                                 layer.find('a.vote-button').removeClass('submitting');
                                 layer.find('a.close-button').removeClass('disabled');
                                 layer.find('.vote-padding').hide();

                                 if (status.match(/^\s*ok\s*$/)) {
                                    layer.find('.vote-padding.confirm-page').show();
                                 } else {
                                    layer.find('.vote-padding.already-voted-page').show();
                                 }
                              });
                           //} else {
                              // Notify user.
                              //alert(ml('terms_not_accepted'));
                           //}
                        }
                     }

                     return false;
                  });

                  // Show layer.
                  initLayer();
               });
            }
         });
      };

      return function () {
         var parent = $(this).closest('.peopleschoiceaward-entry-box');

         open({
            id:       parent.find('.vote-icon').attr('class').match(/id-(\d+)/)[1],
            title:    parent.find('.title > div:first').text(),
            subtitle: parent.find('.title > div.subtitle').text(),
            image:    parent.find('img').attr('src')
         });

         return false;
      }
   }()));

});

