(function($) {
  // set cookies for iphone site
  $(function() {
    $("a#regular-site-link").click(function() {
      setCookie("showIphone", "no");
    });

    $("a#iphone-link").click(function() {
      setCookie("showIphone", "yes");
    });
  });


  ////
  // Apply events to this object
  $.fn.applyEvents = function(events, options) {
    return $(this).each(function() {
      var self = this;
      for (e in events) {
        $.each(events[e], function() {
          $(self).bind(e, this);
        });
      }
    });
  };

  ////
  // News ticker
  $.fn.ticker = function(options) {
    return this.each(function() {
      options = $.extend({
        delay:           7000,
        events:          $.fn.ticker.baseEvents,
        container:       "ul",
        item:            "li",
        buttonContainer: null
      }, options);

      var items = $(options.container, this);

      $(this).data({
        container: items,
        width:     items.width(),
        size:      $(options.item, items).size(),
        current:   0
      });

      // setup
      $(this)
        .applyEvents(options.events, options)
        .trigger("ticker:setup", options);
    });
  };

  $.fn.ticker.baseEvents = {
    // initial setup
    "ticker:setup": [
      // set the size of the container
      function(e, options) {
        $(this).data("container").width(
          $(this).data("width") * $(this).data("size")
        );
        return false;
      },
      // create the prev/next buttons
      function(e, options) {
        var container = options.buttonContainer == null ? $(this) : $(options.buttonContainer, this);

        container.append(
          $('<a href="#" class="prev" />')
        ).append(
          $('<a href="#" class="next" />')
        );
        $("a.prev, a.next", this).data("ticker", $(this));
        return false;
      },
      // prev/next click handlers
      function(e, options) {
        $("a.prev", this).click(function() {
          $(this).data("ticker").trigger("ticker:prev");
          return false;
        });
        $("a.next", this).click(function() {
          $(this).data("ticker").trigger("ticker:next");
          return false;
        });
      }
    ],

    // go back one
    "ticker:prev": [
      function() {
        var current = $(this).data("current") - 1;
        if (current < 0) {
          current = $(this).data("size") - 1;
        }
        $(this).data("current", current);
        $(this).trigger("ticker:animate", -($(this).data("width") * current));
      }
    ],

    // go forward one
    "ticker:next": [
      function() {
        var current = ($(this).data("current") + 1) % $(this).data("size");
        $(this).data("current", current);
        $(this).trigger("ticker:animate", -($(this).data("width") * current));
      }
    ],

    // how to animate
    "ticker:animate": [
      function(e, newLeftMargin) {
        $(this).data("container").animate({ "margin-left": newLeftMargin });
        return false;
      }
    ]
  };


  ////
  // Hover fix (IE only)
  $.fn.dropdownHoverFix = function() {
    return this.each(function() {
      if (document.all) {
        $(this).hover(
          function() { $(this).addClass("hover"); },
          function() { $(this).removeClass("hover"); }
        );
      }
    });
  };


  ////
  // Tabs
  $.fn.tabify = function() {
    return $(this).each(function() {
      var sections = $(".section", this),
          nav      = $('<ul class="clearfix" />'),
          current;

      // add the link for each section
      $.each(sections, function() {
        var h3   = $("h3", this),
            link = $('<a />');

        link
          .attr("href", "#" + $(this).attr("id"))
          .text(h3.text());

        nav.append(
          $('<li />').append(link)
        );
        h3.hide();
      });

      // insert nav
      nav.insertAfter($(".hgroup", this));
      // nav click handler
      $("a", nav).click(function () {
        current.removeClass("current");
        current = $(this).parent().addClass("current");
        sections.hide().filter("#" + this.href.split("#")[1]).show();
        return false;
      });
      // initial state
      current = $("li:first-child", nav).addClass("current");
      sections.hide().eq(0).show();
    });
  };


  ////
  // Nav accordion
  $.fn.navAccordion = function() {
    $(this).each(function() {
      var subUls = $("ul ul", this),
          open;

      // switch click handler
      $("> ul li a", this).click(function() {
        // do nothing if there are no sub-nav items
        if ($(this).parent().find("li").size() == 0) {
          return;
        }

        // if it's closed, open it
        if (!$(this).parent().hasClass("open")) {
          open.trigger("nav:close");
          open = $(this).parent();
          open.trigger("nav:open");
        }
        return false;
      });

      // open/close events
      $("> ul li", this)
        .bind("nav:open", function() {
          $(this).addClass("open");
          $("ul", this).slideDown();
        })
        .bind("nav:close", function() {
          $(this).removeClass("open");
          $("ul", this).slideUp();
        });

      // initial state
      subUls.hide().eq(0).show();
      open = $("> ul li:first", this);
      open.addClass("open");
    });
    return $(this);
  };


  ////
  // Carousel
  $.fn.carousel = function(delay) {
    delay = delay || 11000;

    $(this).each(function() {
      var nav       = $('<ul class="nav" />'),
          container = $("#features", this),
          features  = $("div.section", this),
          count     = features.size(),
          width     = $(this).width(),
          navLis,
          currentLi,
          current,
          timer;

      // insert nav
      features.each(function(i) {
        nav.append(
          $("<li />").data("index", i).append(
            $('<a href="#' + $(this).attr("id") + '" />')
          )
        );
      });
      $(this).prepend(nav);
      navLis = $("li", nav);

      // container moveTo
      container.bind("carousel:moveTo", function(e, index) {
        // reset current
        currentLi.removeClass("current");
        currentLi = navLis.eq(index).addClass("current");
        current = index;
        // animate
        container.animate({ "margin-left": -1 * width * index });
      })
      // advance by one (loop to beginning from end)
      .bind("carousel:advance", function(e) {
        $(this).trigger("carousel:moveTo", (current + 1) % count);
      });

      // click handler
      $("a", nav).click(function() {
        container.trigger("carousel:moveTo", $(this).parent().data("index"));
        // stop the timer
        clearInterval(timer);
        return false;
      });

      // setup
      container.css("width", (width * count) + "px");
      current   = 0;
      currentLi = navLis.eq(0).addClass("current");
      timer     = setInterval(function() {
        container.trigger("carousel:advance");
      }, delay);
    });

    return $(this);
  };

  function setCookie(name, value, days) {
    if (days) {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
    } else {
      var expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
  }
})(jQuery);

