jQuery(function($) {
  
  $('#sub_navigation a').click(function() {
    if ($(this).parent().find('ul').length) {
      $(this).parent().find('ul').first().slideToggle();
      return false;
    }
  });
  
  var boxen = [];
  //find all links w/ rel="lightbox[gallery_name]" or just rel="lightbox" it works both ways
  $('a[rel*=lightbox]').each(function() {
    //push only unique lightbox[gallery_name] into boxen array
    if ($.inArray($(this).attr('rel'),boxen)) boxen.push($(this).attr('rel'));
  });
  //for each unique lightbox group, apply the lightBox
  $(boxen).each(function(i,val) {
    $('a[rel='+val+']').lightBox();
  });
  
  $('table.compare_power tbody tr').click(function(event) {
    event.preventDefault();
    window.location = $(this).find('td.details a').attr('href');
  });
  
  $('.submit-button').click(function(event) {
    event.preventDefault();
    $('#product_request').submit();
  });
  
  $('#product_request').submit(function() {
    $('div.error').remove();
    var params = $(this).serialize();
    $.post($(this).attr('action'), params, function(response, status){
      response = jQuery.parseJSON(response);
      if (response.success) {
        $('#request').slideUp(200, function() {
          $(this).before($('<div class="success"></div>').html(response.success));
        });
      } else {
        $('input, textarea', this).attr('disabled', false);
        if (response.errors.name) {
          $('#rName').parent().after($('<div class="error"></div>').html(response.errors.name));
        }
        if (response.errors.email) {
          $('#rEmail').parent().after($('<div class="error"></div>').html(response.errors.email));
        }
        if (response.errors.request) {
          $('#rRequest').parent().after($('<div class="error"></div>').html(response.errors.request));
        }
        if (response.errors.captcha) {
          $('#recaptcha_widget_div').parent().find('div.clear').first().after($('<div class="error"></div>').html(response.errors.captcha));
        }
      }
    });
    return false;
  });
  
});
