$(function() {

	// Videos
	$("#videos ol a")
	  .click(function(e) {
			e.preventDefault();

			var $this = $(this),
        href = $this.attr("href"),
        youtubeID = /v=(.+)$/.exec(href)[1];

			selectParentListItem($this, function() {
        $("#video").youtube(youtubeID);
			});
		})

		// Select the first video.
		.filter("li:first-child a")
			.click();

	// Scrolling lists
	$("#more_videos a, #more_events a").click(function(e) {
	  e.preventDefault();

	  var $this = $(this),
	    list = $this.closest("div#videos, div#events").children("ol, ul");

	  // Don't try and scroll if it's still animating.
	  if (list.is(":animated")) {
	    return;
	  }

	  $this.blur();

	  var scroll = ($this.is(".up") ? -1 : 1) * (list.height() - 36),
	    position = Math.max(0, list.scrollTop() + scroll);

	  list.animate({ scrollTop: position }, 500);
	});

	// Artists
  $("#artists li > a")
    .click(function(e) {
      e.preventDefault();
      selectParentListItem($(this));
    })

    // Select the first artist.
    .filter("li:first-child a")
      .click();

  // Contact menu link
  $("#menu a.contact").click(function(e) {
    e.preventDefault();
    $(this).blur();

    $("#contact").modal(modalProperties);
  });

  // About links
  $("#menu a.about, #countdown a.about").click(function(e) {
    e.preventDefault();
    $(this).blur();

    // Play the about video.
    $("#video").youtube("h_7JK0mQ5Wo");

    // Deselected the selected video.
    selectParentListItem($("#videos ol"));
  });

  // New artist link
  $("#menu a.signup").click(function(e) {
    e.preventDefault();
    $(this).blur();

    var newArtist = $("#new_artist");
    newArtist.modal(modalProperties);

    newArtist.find(".networks input[type=text]").each(function() {
      var $this = $(this),
        typeInput = $this.siblings("input[type=hidden]"),
        type = (typeInput.length > 0 ? typeInput.val().toLowerCase() : "web");

      $this.keyup(function() { linkTextChanged($this, type); });
    });
  });

  // Upload video link
  $("#upload").click(function(e) {
    e.preventDefault();
    $(this).blur();

    $("#new_video").modal(modalProperties);
  });

  // Email form
  $("#new_email")
    .ajaxForm({
      success: function() {
        this.parent().addClass("ajax_success");
      }
    })
    .find("#email_email").watermark("Join the mailing list");

  // Contact form
  $("#contact form").submit(function(e) {
    var $this = $(this),
      errors = [];

    if ($this.find("#contact_name").val().length <= 0) {
      errors.push("your name");
    }

    if ($this.find("#contact_email").val().length <= 0) {
      errors.push("your email");
    }

    if ($this.find("#contact_message").val().length <= 0) {
      errors.push("the message you'd like to send");
    }

    showFormErrors($this, errors, e);
  });

  // Create a new video form.
  var createVideo = $("#choose_or_upload_video");
  if (createVideo.length > 0) {
    createVideo.modal();

    createVideo.find("form").submit(function(e) {
      var $this = $(this),
        errors = [];

      if ($this.find("#video_name").val().length <= 0) {
        errors.push("a name for your video");
      }

      showFormErrors($this, errors, e);
    });
  }

  // Upload video form.
  var uploadVideo = $("#upload_video");
  if (uploadVideo.length > 0) {
    uploadVideo.modal();

    uploadVideo.find("form").submit(function(e) {
      var $this = $(this),
        errors = [];

      if ($this.find("#file").val().length <= 0) {
        errors.push("the video you want to upload");
      }

      showFormErrors($this, errors, e);
    });
  }

  // Modals
  $("#news a.modal").click(function(e) {
    e.preventDefault();

    var newsContent = $(this).closest("li").children().clone();
    $("#news_details")

      // Dump in content
      .find("div")
        .empty()
        .append(newsContent)

      .end()
      .modal(modalProperties);
  });

  $("#events ul a").click(function(e) {
    e.preventDefault();

    var eventContent = $(this).closest("li").children().clone();
    $("#event_details")

      // Dump in content
      .find("div")
        .empty()
        .append(eventContent)

      .end()
      .modal(modalProperties);
  });

  // Countdown
  var counter = $("#counter");
  window.setInterval(updateCounter, 1000);
  updateCounter();

  function updateCounter() {
    var seconds = --countdownSecondsRemaining;

    var days = Math.floor(seconds / 86400);
    seconds -= days * 86400;

    var hours = Math.floor(seconds / 3600);
    seconds -= hours * 3600;

    var minutes = Math.floor(seconds / 60);
    seconds -= minutes * 60;

    counter.text([ days, padNumber(hours), padNumber(minutes), padNumber(seconds) ].join(":"));
  }

  function padNumber(value) {
    return (value < 10 ? "0" : "") + value;
  }

  function selectParentListItem(item, callback) {
    var isList = item.is("ol"),
      list = (isList ? item : item.closest("ol"));

    list.find("li.selected")
      .removeClass("selected")
      .children("a")
        .animate({ paddingLeft: 10 }, 100);

    if (!isList) {
      item.blur();
      item
        .animate({ paddingLeft: 20 }, 100, null, callback)
        .closest("li")
          .addClass("selected");
    }
  }

  function showFormErrors(form, errors, e) {
    if (errors.length > 0) {
      e.preventDefault();

      var errorMessage = "We need ";
      if (errors.length > 1) {
        errorMessage += errors.slice(0, errors.length - 1).join(", ") + ", and ";
      }

      errorMessage += errors[errors.length - 1] + ".";

      form
        .addClass("ajax_error")
        .find(".errors p").html(errorMessage);
    }
  }

  var defaultLinkParser = /[^\/@]+$/;
  var linkParsers = {
    web: {
      parser: /\w+:\/\//,
      createUrl: function(value) {
        return (linkParsers.web.parser.test(value) ? value : "http://" + value);
      }
    },

    facebook: {
      parser: /\/?(?:[^\/]*id=(\d+)|([^\/&?.]+))[^\/]*$/,
      createUrl: function(value) {
        var match = value.match(linkParsers.facebook.parser);
        if (!match) {
          return null;
        }

        var username = match[1] || match[2];
        return "http://www.facebook.com/" + (/^\d+$/.test(username) ? "profile.php?id=" : "") + username;
      }
    },

    myspace: {
      parser: defaultLinkParser,
      createUrl: function(value) {
        var match = value.match(linkParsers.myspace.parser);
        return (match ? "http://www.myspace.com/" + match[0] : null);
      }
    },

    twitter: {
      parser: defaultLinkParser,
      createUrl: function(value) {
        var match = value.match(linkParsers.twitter.parser);
        return (match ? "http://twitter.com/" + match[0] : null);
      }
    },

    youtube: {
      parser: defaultLinkParser,
      createUrl: function(value) {
        var match = value.match(linkParsers.youtube.parser);
        return (match ? "http://www.youtube.com/" + match[0] : null);
      }
    }
  };

  function linkTextChanged(input, type) {
    var url = linkParsers[type].createUrl(input.val());
    if (url) {

      // Create a test link. Replace the current test link or add a new one.
      var link = $("<a class='test' target='_blank' href='" + url + "'>Test this link</a>");

      if (input.siblings("a").replaceWith(link).length == 0) {
        input.after(link);
      }
    } else {

      // Remove the test link if the link isn't valid.
      input.siblings("a").remove();
    }
  }

  var modalProperties = {};

  // var modalProperties = {
  //   onOpen: function(dialog) {
  //     dialog.overlay.fadeIn(250, function() {
  //       dialog.data.show();
  //       dialog.container.fadeIn(250);
  //     });
  //   },
  //
  //   onClose: function(dialog) {
  //     dialog.container.fadeOut(250, function() {
  //       dialog.overlay.fadeOut(250, function() {
  //         $.modal.close();
  //       });
  //     });
  //   }
  // };

});
