(function ($) {

  $.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();

    /**
	 * 
	 * Trailer Player
	 * 
	 **/
	
    var getTrailer = function(trailer, element) {
      trailer.swfobject = swfobject.createSWF({
        data: '/flash/player.swf',
        height: trailer.height,
        'class': 'trailer-' + trailer.id,
        width: trailer.width
      },
      {
        allowfullscreen: true,
        allowscriptaccess: 'always',
        bgcolor: '#000000',
        flashvars: 'stretching=uniform&autostart=1&bufferlength=5&volume=80&skin=/flash/flicksSkin/flicksSkin.xml&file=' + trailer.file,
        quality: 'high',
        wmode: 'transparent'
      }, element);
      return trailer;
    };
	
    var ageCheck = function(is_restricted, trailer, height) {
      if (is_restricted) {
        $('#container:not(div)').replaceWith($('<div id="container"></div>'));
        $('#container').html($('.date-check').clone().height(height).show());
        $('.age-submit').bind('click', function() {
          var today = new Date();
          var R18 = new Date(today.toDateString().replace(today.getFullYear(), today.getFullYear() - 18));
          var birthday = new Date($('.age-day').val() + ' ' + $('.age-month').val() + ' ' + $('.age-year').val());
          if (birthday <= R18) {
            trailer.call(this);
          }
        });
      } else {
        trailer.call(this);
      }
    };

    $('.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 trailer = function() {
        getTrailer(movie_trailers[link.attr('title')], 'container');
        $('#trailer-rating-form').bind('submit', function(event) {
          event.preventDefault();
          var rate = false;
          $('#trailer-rating-form *:checked').each(function() {
            rate = $(this).attr('value');
          });
          if (rate) {
            $.post('/trailers/rate/', {
              rating: rate,
              trailerId: movie_trailers[link.attr('title')].id,
              movieName: $('.movie-title').attr('title')
            },
            function(data) {
              $('#trailer-rating').html(data).hide().fadeIn('slow');
            });
          }
          return false;
        });
      };
      ageCheck.call(this, movie_trailers[link.attr('title')].restricted, trailer, movie_trailers[link.attr('title')].height);
      return false;
    });
	
    (function() {
      if ($('body.trailers #container noscript').length > 0) {
        var trailer = function() {
          getTrailer(movie_trailer, 'container');
        };
        ageCheck.call(this, movie_trailer.restricted, trailer, movie_trailer.height);
      }
    })();

    // trailer search button

    /**
     *
     *  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);
    });
    /**
     *
     * maps
     *
     **/
    if (document.getElementById('map')) {

      //if ($.browser.msie && ($.browser.version != "6.0")) {
      //    load();
      if ($.browser.msie && ($.browser.version == "6.0")) {
      // nothing
      } else {
        $('.cinema-nav').bind('tabsshow',
          function(event, ui) {
            if (ui.panel.id == 'map') {
              load();
              $('body').unload(function() {
                GUnload();
              });
            }

          });
      }

      // set selected
      $('.sub-nav a').each(function(el) {
        $(this).click(function() {
          $('.sub-nav a').each(function(el) {
            // remove selected classes
            $(this).removeClass('selected');
          });
          $(this).addClass('selected');

          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');
          });
        }
      });

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

    $('#review-form').bind('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();
          err = $(this).attr('id') + '_error';
          $('.' + err).hide();
        //PIXELFUSION: Not sure why this was done?
        });


        $.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 = $('.ad-island').clone(true);
              // Now that we have safely cloned the ad, remove the current island ad div
              $('.ad-island').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 .ad-island:first').replaceWith(island);
                // Figure out the pos of the peoples voice header
                pos = $('h2.peoples-voice').offset().top;
              // Animate nicely to the position
              } 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 .ad-island: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');
      });
    
    $('.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');
      }
    });

  });

})(jQuery);