$(document).ready(function() {
  // set up drop-down menus
  if($('#nav ul.sf-menu').length) {
    $('#nav ul.sf-menu').superfish({
      delay:        800,
      autoArrows:   false,
      dropShadows:  false
    });
  }

  // activate cycle on homepage
  if($('#featured-slideshow').length) {
    $('#featured-slideshow').cycle({
      fx:       'fade',
      speed:    500,
      timeout:  8000,
      pager:    '#featured-project-nav'
    });
  }

  // open links with class "popup" in a fancybox
  $("a.popup").fancybox({
      'width'     : '75%',
      'height'    : '75%',
      'autoScale' : false,
      'type'      : 'iframe'
  });

  // open support videos in a fancybox
  if ($(".video-lightbox").length) {
    $(".video-lightbox").fancybox({'title': this.title});
  };

  // open images in links with class of 'lightbox' in a fancybox
  $("a.lightbox").fancybox();

  // make ALL external links open in a new tab/window
  $("a[href^='http']:not(a[href*='singerco.com'])").attr("target", "_blank");

  // hide the slideshow nav on homepage is there is only one slide
  if ($('#featured-project-nav').is(':empty')) {
    $('#featured-project-nav').hide();
  };

  // set up tabs for product details page
  if($("ul.tabs").length) {
    $("ul.tabs").tabs("div.panes > div");
  }

  // fade flash messages out after 5 seconds
  if ($(".flash").length) {
    setTimeout(function() { $('.flash').fadeOut(); }, 5000);
  };

  if ($("#user_product_reg_model_no").length) {
    // show the "other" field on page load if required
    if ($("#user_product_reg_model_no").val() == 'other') {
      $("#model_no_other").show();
      if ($("#model_no_other input").val() == '' || $("#model_no_other input").val() == 'model number') {
        $("#model_no_other input").val('model number').css('color', '#999');
      }
    }

    // show/hide "other" model no field on registration forms
    $("#user_product_reg_model_no").change(function() {
      if ($(this).val() == 'other') {
        $("#model_no_other").show();
        $("#model_no_other input").val('model number').css('color', '#999');
      } else {
        $("#model_no_other").hide();
        $("#model_no_other input").val('');
      }
    });

    // set/unset value of "other" model no field on registration forms
    $("#model_no_other input").focus(function() {
      if ($(this).val() == 'model number') {
        $(this).val('').css('color', '#000');
      }
    });
    $("#model_no_other input").blur(function() {
      if ($(this).val() == '') {
        $(this).val('model number').css('color', '#999');
      }
    });
  };

  // auto-select email preferences boxes for a new registration
  if ($("#email_pref_table").length > 0 && $("#user_product_reg_user_profile_email").length > 0) {
    if ($("#user_product_reg_user_profile_email").val() == '') {
      $("#email_pref_table input").attr('checked', 'checked');
    }
  }

  // make sure they only pick two reasons on sewing registration form
  $('#reason_checkboxes input:checkbox').click(function() {
    if($(this).is(':checked') && $('#reason_checkboxes input:checked').length > 2) {
      alert('Please choose only 2 reasons.');
      return false;
    }
  });

  // make warranty center select form submit on change
  $('#warranty_center_form select').change(function() {
    $(this).parent().submit();
  });

  // show and hide for faqs
  $('.faq_question a').click(function() {
    var target = this.rel;
    $('#' + target).slideToggle();
    return false;
  });

  // copy over address fields on checkout form
  $("#same-billing").click(function() {
    if ($(this).attr('checked')) {
      $("#singerco_transaction_fname").val($("#singerco_transaction_b_fname").val());
      $("#singerco_transaction_lname").val($("#singerco_transaction_b_lname").val());
      $("#singerco_transaction_company").val($("#singerco_transaction_b_company").val());
      $("#singerco_transaction_address1").val($("#singerco_transaction_b_address1").val());
      $("#singerco_transaction_address2").val($("#singerco_transaction_b_address2").val());
      $("#singerco_transaction_city").val($("#singerco_transaction_b_city").val());
      $("#singerco_transaction_state").val($("#singerco_transaction_b_state").val());
      $("#singerco_transaction_zip").val($("#singerco_transaction_b_zip").val());
      $("#singerco_transaction_country").val($("#singerco_transaction_b_country").val());
    }
  });

  // validate payment form
  $("#payment-form").validate({
    groups: {
      expiration_date: "cc_expmonth cc_expyear"
    },
    errorPlacement: function(error, element) {
      if (element.attr("name") == "cc_expmonth" || element.attr("name") == "cc_expyear" )
        error.insertAfter("#cc_expyear");
      else
        error.insertAfter(element);
    }
  });

  // set username for registration form (if it's blank)
  $("#registration-form").submit(function() {
    if ($("#user_product_reg_user_username").val() == '') {
      $("#user-info-table").hide();
      date = new Date();
      username = 'user-' + date.strftime('%Y-%m-%d-%H-%M-%S');
      $("#user_product_reg_user_username").val(username);
    }
  });

  // hide the user account box on form if username is auto-generated
  if ($("#user_product_reg_user_username").length && $("#user_product_reg_user_username").val().match(/user\-\d+\-\d+\-\d+\-\d+\-\d+\-\d+/) != null) {
    $("#user-info-table").hide();
  };

  // make "popular accessories" scrollable
  if ($("#related-accessories").length) {
    $("#related-accessories").scrollable({
      speed: 600,
      next: '.accNextPage',
      prev: '.accPrevPage'
    });

    // set height of scrollable container to fit tallest element
    if ($('.related-accessory').length) {
      var heights = [];
      $(".related-accessory").each(function(index, el) {
        heights.push($(el).height());
      });
      var maxHeight = Math.max.apply(Math, heights);
      $("#related-accessories").css('height', maxHeight);
    }
  }

  // Submit refurbished product add to cart
  $('#add-to-cart').click(function() {
    $('form#purchase-refurbished').submit();
  });

  // Add another pro to a review
  $(".custom-field input:checkbox").live('click', function() {
    if ($(this).attr('checked') == true) {
      var input = $(this).parent().find('input:text');
      if (input.val() == input.get(0).defaultValue) {
        input.val('');
        input.removeClass('default-value');
      } else {
        $(this).val(input.val());
      }
      input.focus();
    } else {
      $(this).val('');
    }
  });

  // monitor the custom pro/con fields so we can copy value over to checkbox
  // $(".custom-field input:text").live('keyup', function() {
  //   var checkbox = $(this).prev();
  //   var value = $(this).val();
  //   checkbox.val(value);
  // });

  // link to add another pro/con
  $('.add-another-attr a').click(function() {
    var container = $(this).parents('ul');
    var el = container.find('.custom-field:first').clone();
    var num = container.find('.custom-field').length;
    var checked_class = el.find('input:checkbox').attr('name').replace('0', num);
    var value_class = el.find('input:text').attr('name').replace('0', num);
    el.insertBefore($(this).parent());
    el.find('input:checkbox').attr('name', checked_class).attr('checked', true);
    el.find('input:text').attr('name', value_class).val('').focus();

    return false;
  });

  // submit review rating via ajax
  $(".review-rating a").live('click', function(e) {
    var url = $(this).attr('data-url');
    var container = $(this).parent();
    $.post(url, function(){
      container.fadeOut(300, function() {
        container.html("Thanks for your input!");
      }).fadeIn(300);
    });
    e.preventDefault();
  });

  // filter ratings by stars
  $("#filter-reviews select").change(function() {
    var url = $(this).attr('data-url');
    var value = $(this).val();

    if (value != "") {
      window.location = url + "?rating=" + value;
    } else {
      window.location = url;
    }
  });

  // Setup cycle for new product pages
  /*$('#product-gallery').cycle({
    fx: 'fade',
    timeout: 0,
    pager: '#product-gallery-nav',

    // callback fn that creates a thumbnail to use as pager anchor
    pagerAnchorBuilder: function(idx, slide) {
      return '<li><a href="#"><img src="' + slide.src + '" width="75" height="70" /></a></li>';
    }
  });*/
});

function submit_category_filter(url) {
  if(url != '') { window.location = url; }
  return false;
}

