(function ($) {
  
  $(function () {

    var body = $(document.body);

    if (window.takeovers) {
      $.each(window.takeovers, function(takeover_class, takeover_url) {
        if (body.hasClass('takeover') && body.hasClass(takeover_class)) {
          var takeover_links = $('<a class="takeover-link" href="' + takeover_url + '">&nbsp;</a><a class="takeover-link" href="' + takeover_url + '">&nbsp;</a>');
          
          takeover_links.bind('click', function (event) {
            event.preventDefault();
            window.open($(this).attr('href'));
          });
          
          body.prepend(takeover_links);
          
          $(window).bind('resize takeover', function () {
            var x = (body.width() - 1260) / 2;
            takeover_links.eq(0).css('left', x);
            takeover_links.eq(1).css('left', x + 1125);
          }).triggerHandler('takeover');
          
        }
        
      });
      
    }

  });

  $.fn.extend({

    // Make elements have the same height
    evenflow: function() {
      var flowheight = 0;
      $(this).each(function() {
        flowheight = (flowheight >= $(this).height()) ? flowheight: $(this).height();
      });
      $(this).each(function() {
        $(this).height(flowheight);
      });
    },

    // Create Feature Box
    FeatureBox: function() {

      var duration = 6; // Number of seconds between timed change
      var transition = 1;

      var list = $(this).find('ul:eq(1) li');
      var panels = $(this).find('ul:eq(0) li');

      list.evenflow();

      panels.filter(':not(.active)').children('img').hide();
      panels.filter(':not(.active)').children('span').each(function() {
        $(this).css('bottom', (-1 * $(this).outerHeight()) + 'px');
      });

      var activatePanel = function(i) {
        list.filter('.active').animate({
          color: '#fff'
        }, transition * 1000).removeClass('active');
        list.eq(i).animate({
          color: '#f8dc00'
        }, transition * 1000).addClass('active');
        panels.filter('.active').children('img').fadeOut(transition * 1000);
        panels.eq(i).children('img').fadeIn(transition * 1000);
        panels.filter('.active').children('span').animate({
          bottom: (-1 * panels.filter('.active').children('span').outerHeight() + 'px')
        }, transition * 500, function() {
          panels.eq(i).children('span').animate({
            bottom: 0
          }, transition * 500, function() {
            panels.filter('.active').removeClass('active');
            panels.eq(i).addClass('active');
          });
        });
      };

      $(panels).bind('click', function(event){
        window.location = $(this).find('a').attr('href');
      });

      $(list).each(function(i) {
        $(this).bind('click', function(event) {
          if (typeof featureSlide !== 'undefined') {
            window.clearInterval(featureSlide);
          }
          activatePanel(i);
        });
      });

      featureSlide = window.setInterval(function() {
        if (typeof featureSlideI === 'undefined') {
          featureSlideI = 1;
        } else if (featureSlideI == 4) {
          featureSlideI = 0;
        }
        activatePanel(featureSlideI);
        featureSlideI = featureSlideI + 1;
      }, duration * 1000);

    }

  });

  $(document).ready(function($) {

    /**
     *
     *  Accordian
     *
     **/
    $('.drawer-handle').each(function() {
      $(this).bind('click',
        function() {
          var myParent = $(this).parent();
          $('.drawer .inner:visible, .inner li p:visible').slideUp();
          if (myParent.hasClass('expand')) {
            myParent.removeClass('expand');
          } else {
            $('li.expand').removeClass('expand');
            myParent.addClass('expand');
            $(this).next().slideDown();
          }
          return false;
        });
    });

    $('.inner .session').each(function() {

      $(this).bind('click',
        function() {
          if ($(this).next().is(':visible')) {
            $(this).next().slideUp();
          } else {
            $(this).next().slideDown();
          }
          return false;
        });

    });

    /**
     *
     *  Navigation drop menu
     *
     **/
    $('.header .navigation').superfish();
//    $('ul.sub-nav.dropdown').superfish();


 /*** Genre box ***/

  var genreBox = '.genres-box';
  $('ul.sub-nav li.genre a.genre').bind('click', function() {
    if($(genreBox).is(":visible"))
    {
      $(genreBox).slideUp();
    }
    else
    {
      $(genreBox).slideDown();
    }
    return false;
  });

  $('ul.sub-nav li.genre a.genre').hover(
    function()
    {
      // Focus
      if($(genreBox).is(":hidden"))
      {
      $(genreBox).slideDown();
      }
    },
    function()
    {
      // Blur
    }
  );

  $(genreBox).hover(
    function ()
    {
      // Focus
    },
    function ()
    {
      // Blur
      if(!$('ul.sub-nav li.genre a.genre').hasClass('selected'))
      {
        $(genreBox).slideUp();
      }
    }
  );

    /**
     * Trailer Player
     *
     **/
    $('.trailer-links a:not([rel=external])').bind('click', function(event) {
      event.preventDefault();
      var link = $(event.target);

      if (typeof _gaq !== 'undefined') {
        _gaq.push(['_trackEvent', 'Trailers', 'Popup', $('.movie-title').attr('title') + ' - ' + link.attr('title')]); // Google Analytics
      }

      var trailerId = $(this).attr('ref');
      var is_idevice = navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPad/i);
      var is_flash = trailers[trailerId].file.match(/.flv$/);
      if (is_flash )
      {
        if(is_idevice) {
          alert("Hi. You've got a device that doesn't play Flash video. All new videos on Flicks will work, but older ones may not. Pobody's nerfect.");

          $('#TB_overlay').remove();
          $('#TB_window').remove();
          return false;
        }
      }
      embedTrailer(trailers[trailerId], 'trailerContainer');

    });


    /**
     *
     *  Tabs
     *
     **/
    var tabSettings = {
      fx: {
        opacity: 'toggle',
        duration: 'fast'
      }
    };

    var tabSettingsCinemas = {
      fx: {
        opacity: 'toggle',
        duration: 'fast'
      },
      disabled: [3]
    };
    // tabs for search
    var $tabs;
    $tabs = $('.search-nav').tabs(tabSettings);
    $('.search-nav a').each(function(el) {
      $(this).click(function() {
        $('.search-nav a').each(function(el) {
          $(this).removeClass('selected');
        });
        $(this).addClass('selected');

        return false;
      });
    });

    // Cinema & Session time sidebar
    $('.session-selector, .session-time .drawers-selector').tabs(tabSettings);
    $tabs = $('.cinema-nav').tabs(tabSettingsCinemas);
    $('.cinema-nav .session-times a').click(function() {
      var pos = $('h2.session').offset().top;
      $('html,body').animate({
        scrollTop: pos
      },
      1000);
    //window.scrollTo(0,pos);
    });

    // Cinema page nav & map loading
    $('body.cinemas ul.sub-nav li a').bind('click', function () {
        $('ul.sub-nav li a').removeClass('selected');
        $(this).addClass('selected');
        if($(this).attr('href') == '#map') {
          displayMap();
        }
        return false;
    });

    /**
     *
     * Ajax handler for Trailer rating
     *
     **/
    $('#trailer-rating .submit').bind('click',
      function(e) {
        e.preventDefault();
        var rate = 0;
        $('#trailer-rating *:checked').each(function() {
          rate = $(this).attr('value');
        });
        if (rate !== 0) {
          $.post('/trailers/rate/', {
            rating: rate,
            trailerId: $('#trailer-id').attr('value'),
            movieName: $('#movie-name').attr('value')
          },
          function(data) {
            $('#trailer-rating').html("<p>Thanks for your rating</p>").hide().fadeIn('slow');
            $('.trailer-score').hide().replaceWith(data).fadeIn('slow');
          });
        }
      });

    $('.featurebox').FeatureBox();

    $('.blacklists div').evenflow();

    $('a[rel="external"]').bind('click', function(event) {
      event.preventDefault();
      window.open($(this).attr('href'));
      return false;
    });

    var trim = function(input) {
      return input.replace(/^([\s]+)/g,'').replace(/([\s]+)$/g,'');
    };

    $('.session-booking-link, a.onsite').bind('click', function() {
      if (typeof _gaq !== 'undefined') {
        _gaq.push(['_trackEvent', 'Cinema Bookings', trim($(this).parents('li').children('.session').html()), trim($('h1.movie-title').html())]); // Google Analytics
      }
    });

    $('.movie-session-times a').bind('click', function() {
      if (typeof _gaq !== 'undefined') {
        _gaq.push(['_trackEvent', 'Cinema Bookings', trim($('.cinema-info h3').html()), trim($(this).parents('tr').find('td.title a').html())]); // Google Analytics
      }
    });

    $('.profile-field .send-preference').click(function(){
      var checkboxField = $(this).parent().find('input.checkbox');
      if (checkboxField.attr('checked')) {
        checkboxField.attr('checked', false);
        $(this).addClass('disabled');
      } else {
        checkboxField.attr('checked', true);
        $(this).removeClass('disabled');
      }
    });

    $('.profile-field .checkbox').click(function() {
      if ($(this).attr('checked')) {
        $(this).parent().find('p').removeClass('disabled');
      } else {
        $(this).parent().find('p').addClass('disabled');
      }
    });

    if ($(".new-search input[name=q]").length > 0) {
        $('.top_bar .search_text').val($(".new-search input[name=q]").val());
    }

    $('.top_bar .search_text').focus(function() {
        if ($(this).val() == "Search Flicks.co.nz") {
            $(this).val("");
        }
    }).blur(function() {
        if ($(this).val() === '') {
            $(this).val("Search Flicks.co.nz");
        }
    }).blur();

    $(".top_bar .search_button").click(function() {
        if ($('.top_bar .search_text').val() == "Search Flicks.co.nz") {
            $('.top_bar .search_text').val("");
        }
    });


    /**
     *
     *  Ajax handler for Review form
     *
     **/

    $('#news-review-form form').submit(function(e) {
      e.preventDefault();
      var postVars = {};

      $(this).find(':hidden').each(function() {
        postVars[$(this).attr('name')] = $(this).val();
      });
      $(this).find(':text, :checked, textarea').each(function() {
        postVars[$(this).attr('name')] = $(this).val();
        var err = $(this).attr('id') + '_error';
        $('.' + err).hide();
      });


      $.post($(this).attr('action'), postVars,
        function(data, textStatus) {
          if (data.success) {
            $('#message p.red').hide().parent().children('p.green').show().parent().fadeIn('fast');


            // Remove the script tag from the div as when we re-insert it, OpenX will try and reinitialise the ad and screw up
            if ($('.openx-island-script').length > 0) {
              $('.openx-island-script').remove();
            }


            // Clone the island element that is attached to the current 1st peoples review
            var island = $('.island-wrapper').clone(true);

            // Remove any javascript from the clone, else it will not insert correctly, or worse, break the DOM completely (flash ads)
            $(island).find('script').remove();

            // Now that we have safely cloned the ad, remove the current island ad div
            $('.island-wrapper').remove();

            // Check to see what this review form is for as the html is slightly different
            var pos = 0;


            if (data.type == 'movie') {
              // Add the new review to the top of the list
              $('.people').prepend(data.html).fadeIn('slow');

              // Replace the empty island div we passed through, with the one we cloned
              $('.people .island-wrapper:first').replaceWith(island);

              // Figure out the pos of the peoples voice header
              pos = $('h2.peoplesvoice').offset().top;

            } else if (data.type == 'news') {
              // Add the new review to the top of the list
              $('#spray-back').prepend(data.html).fadeIn('slow');

              // Replace the empty island div we passed through, with the one we cloned
              $('#spray-back .island-wrapper:first').replaceWith(island);

              // Figure out the pos of the peoples voice header
              pos = $('h3.spray-back').offset().top;
            }


            // Animate nicely to the position
            $('html,body').animate({
              scrollTop: pos
            },
            1000);

            // Reset the review form
            document.getElementById('review-form').reset();
          }
          else if (data.submission_error)
          {
            $('#message p.green').hide().parent().children('p.red').text(data.submission_error).show().parent().fadeIn('fast');
          }
          else
          {
            $.each(data.error,
              function(key, value) {
                // IE 7 issues
                var err = $('.' + key + '_error');
                var val = err.html(value);
                val.fadeIn('fast');
              });
          }
        },
        'json');

    });

  });

})(jQuery);
