(function($) {
  $(function() {
    // nav dropdown fix
    $("#main-nav li").dropdownHoverFix();
    $("li:first", $("#main-nav .dropdown")).addClass("first");

    // home page: carousel
    $(".home #carousel").carousel();

    // home page: "our solutions" tabs
    $(".home #our-solutions").tabify();

    // home page: news ticker (add a timer)
    var tickerEvents = $.extend({}, $.fn.ticker.baseEvents);
    tickerEvents["ticker:setup"].push(
      function(e, options) {
        var that = this;
        $(this).data("timer", setInterval(function() {
          $(that).trigger("ticker:next");
        }, options.delay));
        return false;
      }
    );
    tickerEvents["ticker:setup"].push(
      function(e, options) {
        var that = this;
        $("a.prev, a.next", this).click(function() {
          clearInterval($(that).data("timer"));
          return false;
        });
        return false;
      }
    );

    $(".home #news").ticker({
      events: tickerEvents,
      delay:  7000
    });


    ////
    // Forms
    var rules = {
      first_name: "required",
      last_name:  "required",
      company:    "required",
      email:      "required",
      phone:      "required",
      industry:   "required",
      '00N40000001rPfC': "required"
    };
    var infoRules = $.extend({
      title: "required"
    }, rules);

    $("#campaign-id, #lead-source, #web-to-lead-topic, #whitepaper-notify").hide();
    $("form#download-whitepapers-form").whitepapersForm(rules);
    $("form#request-info-form").infoForm(infoRules);
    $("form#international-distributors-form").infoForm(infoRules);
  });

  $.fn.infoForm = function(rules) {
    return this.each(function() {
      $(this).validate({
        "rules": rules
      });
    });
  };

  $.fn.whitepapersForm = function(rules) {
    return this.each(function() {
      var returnUrl = $("input[name=retURL]", this),
          baseUrl   = returnUrl.val().match(/^([^?]+)/)[1],
          papers    = $("input[class$=-radio]", this);

      // note: we can't use validate's submitHandler because submitting
      // forms via javascript is broken in chrome
      $("input:submit", this).click(function() {
        var params = $.map(papers.filter(":checked"), function(paper) {
          return $(paper).attr("class").match(/(\S+)-radio/)[1] + "=yes";
        });
        returnUrl.val(baseUrl + "?" + params.join("&"));
      });

      $(this).validate({
        "rules": rules
      });
    });
  };

})(jQuery);


