$(document).ready(function(){
  
  // suppliers tabs
  $('.suppliers, .promotional_events').accordion({active: -1, autoHeight: false})
  
  // make search results clickable
  $('li.result').click(function(e){
    window.location = $(this).find('h2 a').attr('href');
  }).addClass('clickable');
  
  // embellish required form fields
  $('form label:contains(" *")').parent('li').addClass('required');
  
  // enable "other" fields
  $('form input.other').each(function(){
    name = $(this).attr('name');
    other_name = name.substring(6);
    if($('select[name='+other_name+']').size() == 1)  {
      $(this).hide();
      $('select[name='+other_name+']').change(function(e){
        other_name = $(this).attr('name');
        if ($(this).val() == 'Other') {
          $('input.other[name=other_'+other_name+']').show().select();
        }
        else  {
          $('input.other[name=other_'+other_name+']').hide().val('');
        }
      });
    }
  })
  
  // enquiry form validation
  $('form.validates').listenForChange().submit(function(e){
    has_error = false;
    $(this).find('.required input, .required textarea').each(function(e){
      value = $.trim($(this).val());
      if (value == '') {
        has_error = true;
        $(this).parents('.required').addClass('error');
      }
      else if ($(this).attr('name').match(/email/) && !value.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i)) {
        has_error = true;
        $(this).parents('.required').addClass('error');
      }
      else  {
        $(this).parents('.required').removeClass('error');
      }
    })
    
    if (has_error) {
      $(this).find('p.information').html('We\'ve highlighted errors in the form below, please correct these to send the form.</p>').addClass('error');
    }
    
    return !has_error;
  });
  
  // prettyPhoto
  $("a[rel^='prettyPhoto']").prettyPhoto({
    theme: 'facebook' /* light_rounded / dark_rounded / light_square / dark_square / facebook */
	});
	
  // panel links
  $('.panel ul li>a').prepend('&raquo; ');
  
  // sort tables
  var landing_page = (window.location.hash.match(/^#page/)) ? Math.max(parseInt(window.location.hash.substr(5)-1),0) : 0;
  var page_size = 20;
  $('table.sortable').tablesorter({
    textExtraction: function(node)  {
      return $(node).attr('title');
    },
    widgets: ['zebra'],
    sortList: [[0,0]],
    widthFixed: true
  }).filter('.paged').after(
  '<div id="pager" class="pagination">'+
  '<div class="results">Page <span class="pagedisplay"></span></div>'+
  '<input type="hidden" class="pagesize" value="'+page_size+'"/>'+
  '<div class="nav"><span class="prev"> &laquo; Prev</span>'+
  '<span class="pages"></span>'+
  '<span class="next">Next &raquo;</span></div>'+
  '</div>'
  ).tablesorterPager({
    container:      $("#pager"),
    size:           page_size,
    positionFixed:  false,
    seperator:      " of ",
    page:           landing_page
  });
  
})