$(document).ready(function(){

  // track mailto link activity with analytics
  $( 'a[href^=mailto]' ).click( function(){
    if ( typeof pageTracker == 'object' ) { pageTracker._trackPageview( 'email_Link' ) };
    $.get( 'http://www.googleadservices.com/pagead/conversion/1070617237/?label=yRbmCMPHlAIQlaXB_gM&amp;guid=ON&amp;script=0' );
  } );

  // add to enquiry list
  $('tr.act .button.add, tr.act .button.remove').live('click',function(e){
    var $button = $(this),
        href = $button.attr('href')
    ;
    $.get(href,{
      'success' : function(){ handle_enquiry_list_submission($button); }
    });
    e.preventDefault();
  });

  fade_notification = function() {
    $('.notify').fadeOut('slow',function(){$(this).remove()});
  }

  handle_enquiry_list_submission = function(button) {
    var $button       = $(button),
        title         = $button.attr('title'),
        href          = $button.attr('href'),
        $enquiry      = $('#header_utility .enquiry_list a[href=/enquiry]'),
        enquiry_text  = $enquiry.html(),
        count         = enquiry_text.match(/\((\d)\)/),
        current_count = (count.length > 0) ? parseInt(count[1]) : 0;
    ;
    if ($button.hasClass('remove')) {
      title = title.replace(/^Remove (.+) from My Enquiry List$/, 'Add $1 to My Enquiry List');
      href = href.replace(/\?remove=/, '?add=');
      notification = 'removed from';
      new_count = (current_count > 0) ? current_count - 1 : 0;
    }
    else if ($button.hasClass('add')) {
      title = title.replace(/^Add (.+) to My Enquiry List$/,'Remove $1 from My Enquiry List');
      href = href.replace(/\?add=/, '?remove=');
      notification = 'added to';
      new_count = current_count + 1;
    }
    $button
      .toggleClass('add remove')
      .attr('title',title)
      .attr('href',href)
      .html(title)
    ;
    $enquiry
      .html(
        enquiry_text.replace(/\((\d)\)/,'('+new_count+')')
      )
    ;
    $('#header_utility')
      .find('.notify')
        .remove()
      .end()
      .append(
        $('<div class="notify"><p>Act was ' +
          notification +
          ' <a href="/enquiry" title="My Enquiry List">My Enquiry List</a></p></div>'
        )
        .hide()
        .fadeIn('fast')
      )
    ;
    setTimeout(fade_notification, 3000);
  }
  
  // show errors on 500 page
  $('#content.user_message>h1').each(function(){
    $('.hidden_error').toggle(
      $(this).html() == 'Error'
    );
  })
    
  // notification fade
  setTimeout(fade_notification, 4000);
    
  // sidebar accordion
  $("#accordion").accordion({ autoHeight: false });
  $('#about_fc_content').hide().before('<div class="show_all"><a title="Read more about Function Central" href="#more_about_us"><span>Read more about Function Central</span></a></div>');
  $('.show_all a').click( function() {
    $('#about_fc_content').toggle();
  });
  
  // hide everything but the first two paras on longer header content
  if ($('div.header_content > p').size() >= 3)  {
    $('div.header_content > p:gt('+1+')').hide();
    $('div.header_content').append('<p class="read_more"><a title="Read more" href="#"><span>Read more&hellip;</span></a></p>');
    $('div.header_content p.read_more').click(function(){
      $('div.header_content > p:gt('+1+')').toggle();
    })
  }
    
  // SAEF address adding
  $('#quick_find_form #qf_address').attr('value',window.location.href);
  $('#quick_find_form').find('fieldset').hide().end().addClass('invisible').find('h1, input.cancel').click(function(){
    $('#quick_find_form fieldset').slideToggle();
    $('#quick_find_form').toggleClass('invisible');
    return false;
  });
    
  // zebrastriping
  $("table.zebra tr:nth-child(even)").addClass("alt");
  
  // testimonials
  $('.testimonials blockquote p').append("&rdquo;").prepend("&ldquo;");
    
    
  // enquiry form validation
  $('#enquiry_form').listenForChange().submit(function(e){
    has_error = false;
    $(this).find('div.required input').each(function(e){
      value = $.trim($(this).val());
      if (value == '') {
        has_error = true;
        $(this).parents('div.required').addClass('error');
      }
      else  {
        $(this).parents('div.required').removeClass('error');
      }
    })
    
    $(this).find('p.errors').remove();
    if (has_error) {
        $(this).find('h1').after('<p class="errors">Oops! We\'ve highlighted errors in the form below, please correct these to send the form.</p>');
        $.scrollTo('#enquiry_form',500);
    }
    
    return !has_error;
  });
  // enquiry form email checking
  $('#enquiry_form input[name=email]').change(function(e){
    email = $(this).val();
    $('div.email_verify').remove();
    if ($.trim(email) != '') {
      $('div.textarea.fld_extra').after('<div class="email_verify"></div>');
      
      $('div.email_verify').html('<p>Please make sure your email address is correct:</p>'
        +'<span>'
        +email
        +' (<a href="#enquiry_email_container" title="Edit your email address">Edit</a>)</span></p>'
      ).find('a[href=#enquiry_email_container]').click(function(e){
        e.preventDefault();
        $('input#enquiry_email').focus().select();
      });
    };
    // <div class="email_verify">
    //  <p>Please make sure your email address is correct: <span>robbie@robbiemanson.com (<a href="#" title="Edit your email address">Edit</a>)</span></p>
    // </div>
  });
  
  // add middots to footer nav
  $('.utility_links li:gt(0)').prepend(' &middot; ')
  
  // make search results clickable
  $('li.result').click(function(e){
    window.location = $(this).find('h2 a').attr('href');
  }).addClass('clickable');
  
  // xfade home images
  $('.masthead_images ul').xfade({duration: 3000, speed: 2000});
  
  // show more songs, testimonials, prices 
  // TODO refactor the below
  songlist_threshold = 15;
  testimonials_threshold = 3;
  prices_threshold = 1;
  
  // if($('.songlist li').length > songlist_threshold) {
  //   $('.songlist li:gt('+(songlist_threshold-1)+')').hide();
  //   $('.songlist').after('<div class="show_all" id="show_songlist"><a href="#" title="Show whole repertoire"><span>Show whole repertoire</span></a></div>');
  //   $('#show_songlist a').click(function(e){
  //     $('.songlist li:gt('+(songlist_threshold-1)+')').show();
  //     e.preventDefault();
  //     var $target = $(e.target);
  //     $target.parent().hide();
  //   });
  // }
  if($('.widget .testimonials li').length > testimonials_threshold) {
    $('.widget .testimonials li:gt('+(testimonials_threshold-1)+')').hide();
    $('.widget .testimonials').after('<div class="show_all" id="show_testimonials"><a href="#" title="Show all testimonials"><span>Show all testimonials</span></a></div>');
    $('#show_testimonials a').click(function(e){
      $('.widget .testimonials li:gt('+(testimonials_threshold-1)+')').show();
      e.preventDefault();
      var $target = $(e.target);
      $target.parent().hide();
    });
  }
  if($('.prices li').length > prices_threshold) {
    $('.prices li:gt('+(prices_threshold-1)+')').addClass('more').hide();
    $('.prices li.local').removeClass('more').show();
    $('.prices ul').after('<div class="show_all" id="show_prices"><a href="#" title="Show/hide prices for all regions"><span>Show/hide prices for all regions</span></a></div>');
    $('#show_prices a').click(function(e){
      $('.prices li.more').toggle();
      e.preventDefault();
    });
  }
  
  // add parser for prices
  $.tablesorter.addParser({ 
    // set a unique id 
    id: 'price',
    is: function(s) { 
      // return false so this parser is not auto detected 
      return false; 
    }, 
    format: function(s) { 
      // format your data for normalization
      format = s.toLowerCase().replace(/(<div>)*<span>from <\/span>£/,'').replace(/<\/div>.*/, '');
      return format;
    }, 
    // set type, either numeric or text 
    type: 'numeric'
  }); 
  // add parser for titles
  $.tablesorter.addParser({ 
    // set a unique id 
    id: 'priority',
    is: function(s) { 
      // return false so this parser is not auto detected 
      return false; 
    }, 
    format: function(s) { 
      // format your data for normalization
      format = s;
      var title = /<a [^>]+>(.+?) »<\/a>/i.exec(s);
      var priority = /priority_([0-9]+)/i.exec(s);
      if (priority) {
        format = priority[1]+' '+format;
      } else
      if (title)  {
        format = title[1];
      }
      return format;
    }, 
    // set type, either numeric or text 
    type: 'text'
  }); 
     

  
  // tablesorting for act listings
  var landing_page = (window.location.hash.match(/^#page/)) ? Math.max(parseInt(window.location.hash.substr(5)-1),0) : 0;
  var page_size = 13;
  var paginator_html = '<div id="pager" class="pagination">'+
  '<div class="result_count">Page <span class="pagedisplay"> </span></div>'+
  '<input type="hidden" class="pagesize" value="'+page_size+'"/>'+
  '<span class="prev"> &laquo; Prev</span>'+
  '<div class="pages"></div>'+
  '<span class="next">Next &raquo;</span>'+
  '</div>';
  
  $(".sortable").tablesorter({
    cssAsc:         'ascending',
    cssDesc:        'descending',
    cssHeader:      'sorter',
    sortList:       [[1,1]],
    headers:        {
      0: {sorter: false},
      1: {sorter: 'price'}
    }
  }).filter('.paged').after(
    paginator_html
  ).tablesorterPager({
    container:      $("#pager"),
    size:           page_size,
    positionFixed:  false,
    seperator:      " of ",
    page:           landing_page
  });
  
  $(".browse_search_listings").prepend('<thead style="display:none;"><tr><th></th><th></th></tr></thead>').tablesorter({
    sortList:      [[1,0]],
    headers:        {
      1: {sorter: 'priority'}
    }
  });
  
  $(".featured .browse_search_listings").prepend('<thead style="display:none;"><tr><th></th><th></th></tr></thead>').tablesorter({
    sortList:      [[1,0]],
    headers:        {
      1: {sorter: 'priority'}
    }
  });
  
});

