
$(function(){
             
  // Placeholder support for non-modern browsers
  if(!Modernizr.input.placeholder){
   $("input").each(function(){
     if($(this).val()=="" && $(this).attr("placeholder")!=""){
       $(this).val($(this).attr("placeholder"));
       $(this).focus(function(){
         if($(this).val()==$(this).attr("placeholder")) $(this).val("");
       });
       $(this).blur(function(){
         if($(this).val()=="") $(this).val($(this).attr("placeholder"));
       });
     }
   });
  }
                 
  // Social - Accordion
  jQuery.fn.initAccordion = function(){
    return this.each(function(){
      var theMenu = $(this).get(0);
      $('.panel', this).hide();
      $('li.expand > .panel', this).show();
      $('li.expand > .panel', this).prev().addClass('active');
      $('li a', this).click(

      function(e){
        e.stopImmediatePropagation();
        var theElement = $(this).next();
        var parent = this.parentNode.parentNode;
        if ($(parent).hasClass('noaccordion')) {
          if (theElement[0] === undefined) {
            window.location.href = this.href;
          }
          $(theElement).slideToggle('normal',function(){
            if ($(this).is(':visible')) {
              $(this).prev().addClass('active');
            } else {
              $(this).prev().removeClass('active');
            }
          });
          return false;
        } else {
          if (theElement.hasClass('panel') && theElement.is(':visible')){
            if ($(parent).hasClass('collapsible')) {
              $('.panel:visible', parent).first().slideUp('fast',function(){
                $(this).prev().removeClass('active');
              });
              return false;
            }
            return false;
          }
          if (theElement.hasClass('panel') && !theElement.is(':visible')) {
            $('.panel:visible', parent).first().slideUp('fast',function(){
              $(this).prev().removeClass('active');
            });
            theElement.slideDown('normal',function(){
              $(this).prev().addClass('active');
            });
            return false;
          }
        }
        $('.share-button .share').removeClass('active');
        $('.share-button .popover').hide();
      });
    });
  };
  $(".accordion").initAccordion();

                        
  // Select value of inputs on click
  $(".autofocus").click(function(){
    $(this).select();
  });
  
             
  // Popover inline buttons :hover effect
  $(".popover .inline li").hover(
    function(){
      $(this).siblings().stop().animate({opacity:.5},200);
    },
    function(){
      $(this).siblings().stop().animate({opacity:1},200);
  });
             
  // Share button toggle
  $('.share').toggle(function(){
    $(this).addClass('active');
    $(this).next('.popover').show();
    return false;
  }, function() {
    $(this).removeClass('active');
    $(this).next('.popover').hide();
    return false;
  });
  $('share-button .popover').click(function() { return false; });

  $(document).click(function(e){ 
    if ($('.share').hasClass('active') && e.target.className != 'panel' && e.target.className != 'autofocus')
    {
      $('.share-button .share').removeClass('active');
      $('.share-button .popover').hide();
    }
  });


  // Featured carousel
  if($("#featured").length){
    var pages = $("#featured .page");
    var showPage = function(page){
      pages.removeClass("active").hide();
      page.fadeIn("slow").addClass("active");
    };
    $("#featured .slider-nav a").click(function(){
      var page = $($(this).attr("href"));
      showPage(page);
      $(".slider-nav li").removeClass("active");
      $(this).parents("li").addClass("active");
      return false;
    });
  }
             
  if ($(".floating-callout .items li").length < 3) 
    $(".floating-callout").find(".carousel-clip").css({height:"auto"}); 
                     
  // Special Scroller
  if($(".navigatorsss").length){
    return;
    var navID = $(".navigator").attr("id");

    var prepareNavigator = function(){
      var itemsList = $(".navigator .items"),
          items = $(".navigator .items li"),
          itemsNum = items.length,
          nav = $("<div />");
      
      nav.addClass("nav");
      itemsList.wrap("<div class=\"navigator-container\"></div>");
      $(".navigator-container").append(nav);
      
      var createNav = function(){
        if(navID == "video-navigator"){
          for(var i = 0; i < items.length; i+=4) {
            items.slice(i, i+4).wrapAll("<div class=\"nav-group\"></div>");
            nav.append("<a href=\"#navigator-"+i+"\" data-index=\""+i+"\" ></a>");
          }
        } else {
          items.each(function(i){
            i = i + 1;
            nav.append("<a href=\"#navigator-"+i+"\" data-index=\""+i+"\" ></a>");
          });
        }
      }();

      nav.prepend("<span class=\"nav-prev\">Left</span>");
      nav.append("<span class=\"nav-next\">Right</span>");

      $(".nav a:first").addClass("active");
    };

    var bindNavigatorEvents = function(carousel){
      var navCircles = $(".nav a"),
          items = $(".items li");

      navCircles.click(function(){
        var href = $(this).attr("href"),
            target = href.split("-")[1];
        carousel.scroll(jQuery.jcarousel.intval(target));
        navCircles.removeClass("active");
        $(this).addClass("active");
        return false;
      });

      var makeActive = function(direction){
        var activeNav = $(".nav a.active"),
            prevActiveNav = activeNav;

        switch(direction){
          case "prev":
            carousel.prev();
            if(activeNav.prev("a").length){
              prevActiveNav.removeClass("active");
              activeNav.prev("a").addClass("active");
            }
            break;
          case "next":
            carousel.next();
            if(activeNav.next("a").length){
              prevActiveNav.removeClass("active");
              activeNav.next("a").addClass("active");
            }
            break;
        }
      };

      $(".nav-next").click(function(){
        makeActive("next");
        return false;
      });

      $(".nav-prev").click(function(){
        makeActive("prev");
        return false;
      });
    };

    var initNavigator = function(){
      $(".navigator:not(.videos-nav) .items").jcarousel({
        vertical: false,
        scroll: 1,
        initCallback: bindNavigatorEvents,
        buttonNextHTML: null,
        buttonPrevHTML: null
      });
      
      // $(".videos-nav .items")
    };

    prepareNavigator();
    initNavigator();
    
  }

  // Up/Down carousels
  $(".scroller:not(.sixbysix,.gallery) .items").jcarousel({
    vertical: true,
    buttonNextHTML: "<span class=\"next\">Down</span>",
    buttonPrevHTML: "<span class=\"prev\">Up</span>"
  });

  // var halfSize = Math.ceil(($(".sixbysix .items li").length)/2);
  // $(".sixbysix .items").jcarousel({
  //   vertical: true,
  //   scroll: 3,
  //   size:halfSize,
  //   buttonNextHTML: "<span class=\"next\">Down</span>",
  //   buttonPrevHTML: "<span class=\"prev\">Up</span>"
  // });
  
  if ($(".floating-callout .items li").length > 3) {
    $(".floating-callout .items").jcarousel({
      vertical: true,
      scroll: 3,
      buttonNextHTML: "<span class=\"next\">Down</span>",
      buttonPrevHTML: "<span class=\"prev\">Up</span>"
    });
  }
  
  
  $('.cg-scroller').cgScroll({per_row:3});

  // Show page series slider
  if ($('#series .episodes').length) {
    (function() {
      var currently_open = $('#series .episodes')[0];
      var has_scroller = {};
      var heights = {};
      $('#series .episodes').each(function() {
        has_scroller[this.id] = $(this).find('span.jcarousel-next').length > 0;
        heights[this.id] = $(this).find('.carousel-container .carousel-clip').height();
      });

      var hide_scroller_btns = function(wrapper) {
        $(wrapper).find('.carousel-container .prev').hide();
        $(wrapper).find('.carousel-container .next').hide();
      }
      var show_scroller_btns = function(wrapper) {
        $(wrapper).find('.carousel-container .prev').show();
        $(wrapper).find('.carousel-container .next').show();
      }
      var open = function(elem, speed) {
        var wrap = $(elem).find('.carousel-container .carousel-clip');
        $(elem).find('.oc-btn').hide();
        wrap.show().animate({height: heights[$(elem).closest('.episodes')[0].id]}, speed);
        if (has_scroller[elem.id])
          show_scroller_btns(elem);
      }
      var close = function(elem, speed) {
        var wrap = $(elem).find('.carousel-container .carousel-clip');
        wrap.animate({height: 1}, speed, function(){wrap.hide();});
        hide_scroller_btns(elem);
        $(elem).find('.oc-btn').show();
      }
      
      // Initially shrink all but the first series and add invisible buttons
      $('#series .episodes').each(function(index) {
        if (this != currently_open)
          close(this, 0);
      });
      // Add event handlers
      $('#series .episodes .oc-btn').click(function() {
        var elem = $(this).parent()[0];
        if (elem == currently_open)
          return false;
        else { close(currently_open, 300); open(elem, 300); currently_open = elem; }
      });
    })();
  }
  
  // Galleries
  (function() {
    var gallery_current_pos = 1;
    
    $('.gallery_main img').click(move_next)
    
    var prev_hash = '';
    watch_hash = function(){
      if (prev_hash == window.location.hash)
        return;

      // trigger off the gallery change based on the url hash
      if ($('.gallery li a').length > 0 && window.location.hash.indexOf("#image=") != -1) {
        var img_num = window.location.hash.replace('#image=', '');
        show_gallery_image(img_num);
      }

      prev_hash = window.location.hash;
    };
    var hash_watcher = setInterval(watch_hash, 50);
    watch_hash();
    
    $('.gallery li a').click(function(e){
      e.preventDefault();
      
      // just update the hash
      var image = $(this).closest('li');
      var pos = image[0].getAttribute('data-image_pos');
      window.location.hash = 'image=' + pos;
      gallery_current_pos = parseInt(pos);
    });


    function show_gallery_image(pos)
    {
      var a = $('.gal-img-' + pos + ' a')[0];

      var gallery_id = $(a).closest('.gallery')[0].getAttribute('data-gallery_id');
      var image_path = a.getAttribute('data-image_path');
    
      var image = $(a).closest('li');
      var pos = image[0].getAttribute('data-image_pos');
      var caption = image.find('.caption').text();
      var description = image.find('.description').html();

      var gallery = $('.gallery_id_' + gallery_id);
    
      gallery.find('img')[0].src = image_path;
      if (caption.length)
        gallery.find('.caption').show().find('span').text(caption).show();
      else
        gallery.find('.caption').hide();

      $('.post-body .image-description').html(description);

      // omniture tracking
      track_image('Galleries: ' + $('.gallery-view h2.title span').text() + ' - #' + pos);
    }


    function move_next()
    {
      var pos = gallery_current_pos + 1;
      if (pos > $('.gallery li').length)
        pos = 1;
      gallery_current_pos = parseInt(pos);
      $('.gal-img-' + pos + ' a').trigger('click');
    }
    function move_prev()
    {
      var pos = gallery_current_pos - 1;
      if (pos < 1)
        pos = $('.gallery li').length;
      gallery_current_pos = parseInt(pos);
      $('.gal-img-' + pos + ' a').trigger('click');
    }
  
    $('.p-next').click(function(e){
      e.preventDefault();
      move_next();
    });
    $('.p-back').click(function(e){
      e.preventDefault();
      move_prev();
    });
  
  })();
  
  
  
  
  
  
  

  // search fields (site main + shows / artists)
  $('.search-form').each(function(){

    var $this = $(this);
    var searchInput = $this.find(".search"),
        clearField = $this.find(".clear");

    searchInput.focus(function(){
      clearField.show();
    });
    searchInput.blur(function(){
      var val  = $(this).val();
      if(val == "" || val == "Search"){
        clearField.hide();
      }
    });
    clearField.click(function(){
      searchInput.val('');
      clearField.hide();
      return false;
    });
  });


  // incremental search
  $("#site-search").autocomplete({
      serviceUrl : '/search/incremental'
    , width      : 280
    , onSelect   : function(title, data, elm)
    {
      window.location = data.url;
      return;
    }
    , fnFormatResult : function(value, data, currentValue)
    {
      var html = '';

      if (data.thumb_path_tiny)
        html += '<div class="img"><img src="'+data.thumb_path_tiny+'" /></div>';
      else
        html += '<div class="img"></div>';

      html += '<span>'+data.title+'</span>';
      
      return '<div class="inc-search-result"><div class="clearfix">'+html+'</div></div>';
    }
  });




  // Load Competition Form Handler
  if($('article.competition-form > form').length)
    competition = new Competition_form($('article.competition-form > form')[0]);
  
  // Competition cookie checker-setter to display appropriate message on thank you page
  if($('article.competition-thanks').length) {
    var cfc = check_for_comp();
    if (cfc && cfc.matches)
      $('article.competition-thanks .once-only').fadeIn(2000);
    else if (cfc)
      document.cookie = 'spmoc=' + cfc.id + '.' + cfc.spmoc + "; expires=Thu, 16 Mar 2034 00:00:00 UTC; path=/"
  }
  //;


  // IE6 + IE7 + IE8
  if($.browser.msie && parseInt($.browser.version.substr(0,1))<9){

    $(".items .preview").each(function(){
      $(this).append("<span class=\"iepreviewtype\"></span>");
    });

    $(".half + .half").each(function(){
      $(this).addClass("ie2nd");
    });

    $("footer section + section").addClass("ie2nd");
    $(".button.double + .double").addClass("ie2nd");
    $("ul.accordion > li:last-child").addClass("ielast");
    $(".latest-news li:last-child").addClass("ielast");

    $(".subnav, .subsubnav").each(function(){
      $(this).append("<span class=\"ieshadowwrap\"></span>");
      $(this).append("<span class=\"ieshadow\"></span>");
    });


  }


  // IE6 + IE7
  if($.browser.msie && parseInt($.browser.version.substr(0,1))<8){
    
    $(".popover").each(function(){
      $(this).append("<span class=\"iebubblearrow\"></span>");
    });

    $(".slider-nav li").each(function(){
      $(this).append("<span class=\"ieactive\"></span>");
    });

    $(".rightarrow").each(function(){
      $(this).append("<span class=\"iearrow\"></span>");
    });

    $(".breadcrumb li").each(function(){
      $(this).append("<span class=\"iebreadcrumb\">/</span>");
    });
    
    $(".subnav").each(function(){
      $(this).append("<span class=\"iebefore\"></span>");
      $(this).append("<span class=\"ieafter\"></span>");
    });

    $(".charts .read-more + .read-more").each(function(){
      $(this).addClass("ielast");
    });

    $("#schedule .items li:first-child").addClass("iefirst");
  }

  // IE6
  if ($.browser.msie && parseInt($.browser.version.substr(0,1)) < 7) {
    $(".primary li").hover(function(){
      $(this).addClass("iehover");
    }, function(){
      $(this).removeClass("iehover");
    });

    // Fix for background flickering on hover

    try {
      document.execCommand("BackgroundImageCache", false, true);
    } catch(err) {}
  }
  
  run_heros();
  
  // deal with lazy loading
  if ($('.load-more').length > 0) {
    
    $('.load-more').live('click', function(e){
      e.preventDefault();

      var btn = $(this);
      var shell = $(this).closest('div');

      $.ajax({url : this.href  + '&naked=1'}).success(function(data) {
        shell.find('ol, ul').append($(data).find('li'));

        var more_link = $(data).find('.load-more');
        if (more_link.length)
          btn.replaceWith(more_link);
        else
          btn.remove();
      });

      return false;
    });
  }
  

  // Drag and drop voting
  function run_voting()
  {
    // thanks page?
    if ($("#chart-thanks").length)
    {
      // track it as voted in
      var inst_id = $("#chart-thanks")[0].getAttribute('data-inst_id');
      var voted_in = $.cookie('cg_vi');
      if (voted_in == null)
        voted_in = '';
      voted_in = voted_in + ' ' + inst_id;
      $.cookie('cg_vi', voted_in, {path:'/', expires:100});
    }

    
    var refreshPositionClasses = function(){
      var items = $("#drop li");
      items.each(function(i){
        $(this).removeClass().addClass("position-"+(i+1));
      });
    };

    if($("#drag").length){
      
      check_voted();

      var dragItems = $("#drag .items, #drop .inner");
      var userAgent = navigator.userAgent.toLowerCase();

      dragItems.sortable({
        placeholder: "ui-state-highlight",
        connectWith: ".sortable",
        helper: "clone",
        start: function(event,ui){
          if(userAgent.match(/firefox/)){
            if(ui.helper !== undefined){
              ui.helper.css('position','absolute').css('margin-top', $(window).scrollTop());
            }
          }
          if(!($("html").hasClass("ie7") || $("html").hasClass("ie6"))){
            $("#drag").find('li:hidden').show().addClass("phantom");
          }
        },
        over: function(event,ui){
          $(".ui-sortable-helper").parents("article").css("z-index","4000");
        },
        beforeStop: function(event,ui){
          if(userAgent.match(/firefox/)){
            if(ui.offset !== undefined){
              ui.helper.css('margin-top',0);
            }
          }
        },
        stop: function(event,ui){
          $("#drag, #drop").css("z-index","200");
          refreshPositionClasses();
          $(".phantom").removeClass("phantom");
        },
        receive: function(event,ui){
          set_vote_btn_state();
          deoverflow();
        }
      });
      dragItems.disableSelection();
    }

    // hide(ish) the submit button until they've added something
    function set_vote_btn_state() {
      if ($('#drop ul.sortable li').length == 0)
        $('.btn_cast_vote').css({opacity:.5});
      else
        $('.btn_cast_vote').css({opacity:1});
    }
    
    function check_voted() {
      var chart = $("#drag")[0];
      var inst_id = chart.getAttribute('data-inst_id');
      var voted_in = $.cookie('cg_vi');
            
      if (voted_in == null)
        return;
      
      voted_in = ' ' + voted_in + ' ';
      
      // be off with you!
      if (voted_in.indexOf(' ' + inst_id + ' ') > -1)
        window.location = window.location + '/thanks-for-voting';
    }
    
    function deoverflow() {
      var upto = 10;
      if ($('#drop').hasClass('twenty'))
        upto = 20;
        
      if ($('#drop ul.sortable li').length > upto) {
        $('#drag ul.sortable').append($('#drop ul.sortable li:last'));
      }
    }

    set_vote_btn_state();
    
    $('#cast_vote_form').submit(function(){
      // sense check to stp wierd hacking around
      if ($('#drop ul.sortable li').length == 0)
        return false;
    });

    // rewire the button to trigger the form
    $('.btn_cast_vote').click(function(){
      $('#cast_vote_form').trigger('submit');
      return false;
    });
  };
  run_voting();

  
  // Hit / Miss
  (function(){
    // casting votes
    $('.hm-vote').click(function(){
      
    });
    
    // showing cast votes
    $.cookie('hm-up');
    // $.cookie('cg_vi', voted_in, {path:'/', expires:100});
  })();

});





function run_heros()
{
  var hh = $('#home-hero');

  if (hh.length == 0)
    return;

  // extra display elements
  create_blockers();
  
  // initial state
  // hh.find('#page-2 .caption, #page-3 .caption, #page-4 .caption').hide();
  // hh.find('#page-1 .title-rot').hide();
  hh.find('#page-1 .blocker').hide();
  hh.append('<div id="animate-control"></div>');
  shuffle_page_backgrounds();
  
  hh.find("#page-1 .sub-page").removeClass("active").hide();
  hh.find("#page-1 #page-11").fadeIn("fast").addClass("active");

  control_pages();
  
  start_scrolling();

  var current_hero = 1;
  var scroll_timer = null;
  var scroll_timer_halted = false;


  function control_pages()
  {
    var pages = hh.find("#page-1 .sub-page");

    var showPage = function(page){
      pages.removeClass("active").hide();
      page.fadeIn("slow").addClass("active");
      page.find('.title-rot').hide();
    };

    hh.find('#page-1 .sliding-panel a').click(function(){
      kill_auto_scroll();
      var page = $($(this).attr("href"));
      showPage(page);
      hh.find(".sliding-panel li").removeClass("active");
      $(this).parents("li").addClass("active");
      return false;
    });
  }

  function start_scrolling()
  {
    scroll_timer = setTimeout(auto_scroll_next, 4000);
  }
  
  function auto_scroll_next()
  {
    if (scroll_timer_halted)
      return;
    
    var next_hero = current_hero + 1;
    if (next_hero == 5)
      next_hero = 1;
    else
      scroll_timer = setTimeout(auto_scroll_next, 4000);
    
    move_to_hero(next_hero);
  }
  
  function kill_auto_scroll()
  {
    clearTimeout(scroll_timer);
    scroll_timer = null;
    scroll_timer_halted = true;
  }


  function create_blockers()
  {
    // blockers to obscure non-active items
    var i = 1;
    hh.find('.page').each(function(){
      $(this).append('<div class="blocker" data-hero_num="'+i+'"></div>').find('.blocker').css('opacity', 0);
      $(this).find('.blocker').click(function(){
        kill_auto_scroll();
        move_to_hero(this.getAttribute('data-hero_num'));
      });
      
      i++;
    })
  }

  function move_to_hero(new_hero)
  {
    if (current_hero == new_hero)
      return;

    var states = [
        [570,135,64,64]
      , [64,570,135,64]
      , [64,64,570,135]
      , [64,64,135,570]
    ];
    var duration = 400;

    prepare_to_hide(current_hero, 400);
    prepare_to_show(new_hero, 400);
    animate_heros(states[current_hero-1], states[new_hero-1], duration);

    current_hero = new_hero;
  }

  function animate_heros(from, to, duration)
  {
    var options = {
        duration : duration
      , step     : function(percent) {
          $([0,1,2,3]).each(function() {
            var diff = Math.abs((to[this] - from[this]) * percent/100);
            new_width = from[this] + diff;

            if (to[this] < from[this])
              new_width = from[this] - diff;
                        
            hh.find('#page-' + (this+1)).width(new_width);
          });
          shuffle_page_backgrounds()
        }
    };
    
    // the heights are just a hack to get a percentage
    hh.find('#animate-control').css({height:0}).animate({height:100}, options);
  }

  function shuffle_page_backgrounds()
  {
    hh.find('.sub-page').each(function(){
      var img = $(this).find('img.big-back');

      var fx = this.getAttribute('data-focus_x');
      var display_width = $(this).closest('.page').width();
      var offset = (img.width() * fx / 100) - display_width/2;

      if (offset + display_width > img.width())
        offset = img.width() - display_width;
      if (offset < 0)
        offset = 0;

      img.css('left', -parseInt(offset, 10)+'px')
    });
  }

  function prepare_to_hide(hero, duration)
  {
    hh.find('#page-' + hero + ' .sliding-panel').fadeOut(duration/2);
    hh.find('#page-' + hero + ' .caption').fadeOut(duration/2);
    setTimeout(function(){hh.find('#page-' + hero + ' .title-rot').fadeIn(duration/2)}, duration/2);
    hh.find('#page-' + hero + ' .blocker').show();
  }

  function prepare_to_show(hero, duration)
  {
    setTimeout(function(){hh.find('#page-' + hero + ' .sliding-panel').fadeIn(duration/2)}, duration/2);
    setTimeout(function(){hh.find('#page-' + hero + ' .caption').fadeIn(duration/2)}, duration/2);
    hh.find('#page-' + hero + ' .title-rot').fadeOut(duration/2);
    hh.find('#page-' + hero + ' .blocker').hide();
  }

}


/* 
 * Events and Processing for competition forms
 */
function Competition_form(elm) {
  this.form = $(elm);
  this.messages = this.form.find('.submit-messages');
  this.border_color = { neutral:{}, good:{}, bad:{} };

  // Set the default border colors -- from those on the form if we can, else use hard-coded defaults
  var tw = this.form.find('.text-input-wrapper').length ? $(this.form.find('.text-input-wrapper')[0]) : null;
  this.border_color.neutral.inner = tw.children('input').length ? tw.children('input').css('border-top-color') : '#d7d7d7';
  this.border_color.neutral.outer = tw ? tw.css('border-top-color') : '#ebebeb';
  this.border_color.good.inner = '#799e50';
  this.border_color.good.outer = '#b3cd86';
  this.border_color.bad.inner = '#af5e55';
  this.border_color.bad.outer = '#de877e';

  // Temp values for the birthday input fields
  this.birth_values = { birth_day:'DD', birth_month:'MM', birth_year:'YYYY'};
  var cf = this
  this.form.find('.birthday input').each(function() { this.value = cf.birth_values[this.name] });

  this.verifier = {
    answer:             {valid: false, message:'Please choose an answer'},
    first_name:         {valid: false, message:'Please enter a first name'},
    last_name:          {valid: false, message:'Please enter a last name'},
    email:              {valid: false, message:'Please enter a valid email address'},
    email_confirm:      {valid: false, message:'Please ensure your email addresses match'},
    birth_day:          {valid: true, message:'Please enter a valid numeric birth day, like 24 (or nothing if you\'d prefer)'},
    birth_month:        {valid: true, message:'Please enter a valid numeric birth month, like 03 (or nothing if you\'d prefer)'},
    birth_year:         {valid: true, message:'Please enter a valid numeric birth year, like 1973 (or nothing if you\'d prefer)'},
    accept_terms:       {valid: false, message:'Please read and agree to the terms and conditions and privacy policy'}
  };
  
  // Register event handlers
  this.form.find('input').change($.proxy(this.input_changed, this));
  this.form.find('input').keyup($.proxy(this.input_changed, this));
  this.form.find('.birthday input').focusin($.proxy(this.birthday_focus_in, this));
  this.form.find('.birthday input').focusout($.proxy(this.birthday_focus_out, this));
  this.form.submit($.proxy(this.form_submit, this));
}

Competition_form.prototype.form_submit = function(e) {
  try {
    this.messages.hide();
    this.messages.html('');

    // Run the validation step
    var cf = this;
    this.form.find('input').each(function(){ 
      this.value = $.trim(this.value);
      $(this).focusin();
      cf.validate(this);
    });

    var is_valid = true;

    for (var v in this.verifier) {
      if (!this.verifier[v].valid) {
        is_valid = false;
        this.change_border_color(this.form.find('input[name='+ v + ']'), 'bad');
        this.add_message(this.verifier[v].message);
      }
      else {
        this.change_border_color(this.form.find('input[name='+ v + ']'), 'good');
      }
    }

    // Not ready for submission
    if (!is_valid) {
      this.messages.show();
      this.form.find('.birthday input').each(function(){ $(this).focusout() });
      return false;
    }
    // Can be submitted
    else {
      return true;
    }
    return false; // obviously frivolous
  }
  catch(err) {
    //handle it
    this.add_message('Sorry, we had some problems trying to process your entry');
    return false;
  }
}

Competition_form.prototype.input_changed = function(e) {
  var target = e.currentTarget;
  this.validate(target);
}

// Change the border color of the given text input element (type should be 'neutral', 'good', or 'bad')
Competition_form.prototype.change_border_color = function(element, type) {
  if (!element || !element.length || !element.is(':text'))
    return;

  var wrapper_element = element.parent();
  element.css('border-color', this.border_color[type].inner);
  wrapper_element.css('border-color', this.border_color[type].outer);
}

Competition_form.prototype.validate = function(input) {
  if(typeof(this.verifier[input.name]) == 'object')
    var v = this.verifier[input.name];
  else
    return;

  // Clean up a bit
  var value = $.trim(input.value);

  // Generic required fields
  if (/^first_name|last_name|email$/.test(input.name)) {
    v.valid = (input.value != '');
  }
  else if (/^accept_terms$/.test(input.name)) {
    v.valid = input.checked;
  }
  else if (/^answer$/.test(input.name)) {
    if (this.form.find('input[name=is_freetext]').val() == 1)
    {
      if (this.form.find('input[name=answer]').val().length)
        v.valid = true;
      else
        v.valid = false;
    }
    else
    {
      if (this.form.find('input[name=answer]:checked').length)
        v.valid = true;
      else
        v.valid = false;
    }
  }
  // Email, weak validation
  if (/^email$/.test(input.name)) {
    v.valid = /.+@.+\..+/.test(input.value);
  }
  // Confirm email
  else if (/^email_confirm$/.test(input.name)) {
    v.valid = (value == this.form.find('input[name=email]')[0].value);
  }
  // Birthday
  else if (/^birth_day|birth_month|birth_year$/.test(input.name)) {
    if (input.value != '') {
      var num = parseInt(input.value, 10);
      if (isNaN(num) || num < 1)
        v.valid = false;
      else if (input.name == 'birth_day' && (num > 31))
        v.valid = false;
      else if (input.name == 'birth_month' && (num > 12))
        v.valid = false;
      else if (input.name == 'birth_year' && ((num < 1800) || (num > 2800)))
        v.valid = false;
      else
        v.valid = true;
    }
  }

  if (v.valid)
    this.change_border_color(this.form.find('input[name='+ input.name + ']'), 'good');
  else
    this.change_border_color(this.form.find('input[name='+ input.name + ']'), 'bad');
}

Competition_form.prototype.birthday_focus_in = function(e) {
  input = e.currentTarget;
  if (input.value == this.birth_values[input.name])
    input.value = '';
}
Competition_form.prototype.birthday_focus_out = function(e) {
  input = e.currentTarget;

  if (this.verifier[input.name].valid)
    input.value = !isNaN(parseInt(input.value, 10)) ? (parseInt(input.value, 10)) : input.value;
  if ($.trim(input.value) == '') {
    input.value = this.birth_values[input.name];
    this.change_border_color($(input), 'neutral');
    this.verifier[input.name].valid = true;
  }
}

Competition_form.prototype.add_message = function(message) {
  this.messages.append('<li>' + message + '</li>');
}


check_for_comp = function() {
  var id = window.location.pathname.match(/^\/competitions\/(\d)+(\/|$)/i);
  if (!id || id.length != 3)
    return null;
  id = id[1];
  var comps = document.cookie.match(/(^\s*|;\s*)spmoc=([^;]*)/i);
  comps = (!comps || comps.length != 3) ? '' : comps[2];
  var re = new RegExp('(^|\\.)'+id+'(\\.|$)', 'i');
  var matches = (re.test(comps));
  return {matches:matches, id:id, spmoc:comps};
}
run_check_for_comp = function() {
  var cfc = check_for_comp();
  if (cfc && cfc.matches && !(/^\/competitions\/\d+.*\/(thanks|sorry)\/?$/.test(window.location.pathname)))
    window.location.replace(window.location.pathname.replace(/\/?$/, '/thanks') + window.location.search + window.location.hash);
}
// Try doing this straight away -- if it fails, wait till jquery ready event
try { run_check_for_comp() }
catch(e) { $(function() { run_check_for_comp() }); }



Cufon.replace('.brandfont', { fontFamily:'Monoline'});
Cufon.replace('.hnfont', { fontFamily:'Helvetica Neue'});







// ** omniture tracking **


// brightcove tracking
var cg_bc_media_started = {};
var cg_bc_to = null;

function onTemplateLoaded(experienceID)
{
  var bcExp = brightcove.getExperience(experienceID);
  var modVP = bcExp.getModule(APIModules.VIDEO_PLAYER);

  modVP.addEventListener(BCMediaEvent.PLAY, onBrightCoveEvent);
  modVP.addEventListener(BCMediaEvent.STOP, onBrightCoveEvent);
  modVP.addEventListener(BCMediaEvent.COMPLETE, onBrightCoveEvent);
}

function onBrightCoveEvent(e)
{
  var media_id = e.media.id;
  var duration = Math.round(e.duration);
  var position = Math.round(e.position);
  var title    = 'Brightcove Player: ' + e.media.displayName.replace(';', '');
  var player   = 'Brightcove Player';

  var s = track_video_thing(title, player, duration);

  switch (e.type)
  {
    case BCMediaEvent.PLAY:
      // need to do this way because media.begin event arrives too late
      if (!cg_bc_media_started[ media_id]) {
        cg_bc_media_started[media_id] = true;
        // first click play
        s.Media.open(title, duration, player);
        s.Media.play(title, 0);
      }
      else
      {
        // resume
        s.products=s.prop2=s.eVar2=s.eVar16=s.prop17=s.eVar17=s.prop21=s.prop23=s.eVar23=s.hier2="";
        s.Media.trackEvents = s.events = '';
        s.Media.play(title, 0);
      }
      break;
      
    case BCMediaEvent.STOP:
      // we defer this because of the race condition wih the stop and complete events triggering at the same time
      cg_bc_to = setTimeout(function () {
        s.products=s.prop2=s.eVar2=s.eVar16=s.prop17=s.eVar17=s.prop21=s.prop23=s.eVar23=s.hier2="";
        s.Media.trackEvents = s.events = '';
        s.Media.stop(title, position);
        s_static = null;
      }, 80);
      break;
      
    case BCMediaEvent.COMPLETE:
      if (cg_bc_to != null)
      {
        clearTimeout(cg_bc_to);
        cg_bc_to = null;
      }

      s.Media.trackVars = 'events,';
      s.Media.trackEvents = 'event14';
      s.events = 'event14';
      s.linkTrackEvents = 'event14';
      
      s.Media.stop(title, position);
      s.Media.close(title);
      s_static = null;
      break;
  }
}


// used by muzu and brightcove
var s_static = null;
function track_video_thing(title, player, duration)
{
  if (s_static != null)
    return s_static;
    
  var s = s_gi(window.tracking_data.account);
  s.usePlugins=false;

  s.Media.trackVars         = 'products,prop17,prop21,prop23,hier2,eVar16,eVar17,eVar23,events';
  s.Media.trackEvents       = 'event4,event19,event11,event12';
  s.Media.autoTrack         = false;
  s.Media.trackWhilePlaying = false;
  s.products                = "Video;" + title + ";;;event19=" + duration;
  s.prop17                  = title;
  s.eVar16                  = s.prop17;
  s.prop21                  = player;
  s.eVar17                  = s.prop21;
  s.prop23                  = 'Video Visit';
  s.eVar23                  = s.prop23;
  var clean_title = s.prop17.replace('Brightcove Player: ', '');
  clean_title = clean_title.replace('Muzu Player: ', '');
  s.hier2                   = s.prop23 + '|' + s.prop21 + '|' + clean_title;
  s.events                  = 'event4,event11,event12,event19';
  
  s_static = s;
  return s_static;
}



// muzu tracking

function getFlashObject(playerId)
{
  if (window.document[playerId])
    return window.document[playerId];

  if (navigator.appName.indexOf("Microsoft Internet")==-1)
  {
    if (document.embeds && document.embeds[playerId])
      return document.embeds[playerId];
  }
  else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
    return document.getElementById(playerId);
}


function muzuPlayerReady2(playerId)
{
  if (playerId == undefined)
    return;

  var obj = getFlashObject(playerId);
  obj.addEventListener("videoStarted", "onVideoStart");
  obj.addEventListener("videoResumed", "onVideoResume");
  obj.addEventListener("videoPaused", "onVideoPause");
  obj.addEventListener("videoStopped", "onVideoStop");
  obj.addEventListener("videoComplete", "onVideoComplete");
}
function muzuPlayerReady4Music()
{
  return muzuPlayerReady2('muzuplayer');
}
try
{
  muzutv.player.events.addEventListener("playerInit", "muzuPlayerReady4Music");
} catch (e)
{
  window.muzuPlayerReady = muzuPlayerReady2;
}


function getVideoPlayer(videoId)
{
  var player = getFlashObject('muzu-' + videoId);
  if (player == undefined)
    player = getFlashObject('muzuplayer');
  return player;
}
function getVideoDetails(videoId)
{
  var player = getVideoPlayer(videoId);
  return eval('(' + unescape(player.getCurrentVideo()) + ')');
}


var muzu_playing = {};

function track_muzu_thing()
{
  return track_video_thing(muzu_playing.title, muzu_playing.player, muzu_playing.duration);
}

function onVideoStart(channelId, videoId, playlistId, embedCode, shareCode, trackName)
{
  var data = getVideoDetails(videoId);
  
  // store everything while we have the chance
  muzu_playing = {
      vidData  : data
    , duration : Math.round(data.duration/1000)
    , videoId  : videoId
    , title    : 'Muzu Player: ' + data.artistName + ' - ' + data.title
    , player   : 'Muzu Player'
    , obj      : getVideoPlayer(videoId)
  };
  muzu_playing.position = function() {
    return Math.round(this.obj.getCurrentTime());
  }
  
  var s = track_muzu_thing();
  s.Media.open(muzu_playing.title, muzu_playing.duration, muzu_playing.player);
  s.Media.play(muzu_playing.title, 0);
}

function onVideoPause()
{
  var s = track_muzu_thing();
  s.Media.trackEvents = s.events = '';
  s.products=s.prop2=s.eVar2=s.eVar16=s.prop17=s.eVar17=s.prop21=s.prop23=s.eVar23=s.hier2="";
  s.Media.stop(muzu_playing.title, muzu_playing.position());
}

function onVideoResume()
{
  var s = track_muzu_thing();
  s.Media.trackEvents = s.events = '';
  s.products=s.prop2=s.eVar2=s.eVar16=s.prop17=s.eVar17=s.prop21=s.prop23=s.eVar23=s.hier2="";
  s.Media.play(muzu_playing.title, muzu_playing.position());
}

function onVideoStop()
{
  var s = track_muzu_thing();
  s.Media.trackEvents = s.events = '';
  s.products=s.prop2=s.eVar2=s.eVar16=s.prop17=s.eVar17=s.prop21=s.prop23=s.eVar23=s.hier2="";
  s.Media.stop(muzu_playing.title, muzu_playing.position());
}

function onVideoComplete()
{
  var s = track_muzu_thing();

  s.Media.trackVars = 'events,';
  s.Media.trackEvents = 'event14';
  s.events = 'event14';
  s.linkTrackEvents = 'event14';
  
  s.Media.stop(muzu_playing.title, muzu_playing.position());
  s.Media.close(muzu_playing.title);
  s_static = null;
}


function track_image(name)
{
  var s = s_gi(window.tracking_data.account);
  s.events="";
  s.prop26="";
  s.prop26=s.events="event31";
  s.eVar31 = name;
  s.linkTrackEvents = s.events;
  s.linkTrackVars = 'eVar26,eVar31,events,prop26';
  
  s.tl($('#t-link')[0],'o',s.eVar31);
}

// called from the comments_list (disqus)
function track_comment()
{
  var s = s_gi(window.tracking_data.account);
  s.events="";
  s.prop26="";
  s.prop26=s.events="event26,event31";
  s.eVar31 = 'Comment';
  s.eVar33 = 'Comment';
  s.linkTrackEvents = s.events;
  s.linkTrackVars = 'eVar26,eVar31,eVar33,events,prop26';

  s.tl($('#t-link')[0],'o',s.eVar31);
}

