$(document).ready(function () {

	var inputs = [];
	$("input[alt]").each(function () { inputs.push($(this).val()); });

	//REMOVE DEFAULT VALUE FOR FORM INPUTS
	$('input[alt]').focus(function () {
		var defaultValue = inputs[$("input[alt]").index(this)];

		if ($(this).attr("value") == defaultValue) {
			$(this).attr("value", '');
		}
	});
	$('input[alt]').blur(function () {
		if ($(this).attr("value") == '') {
			var defaultValue = inputs[$("input[alt]").index(this)];
			$(this).attr("value", defaultValue);
		}
	});

	


	//TABLE ACCORDION
	$("td.accordion > table > tbody").hide();
	$("td.accordion > table > thead").live("click", function () {
		$(this).toggleClass("expanded").next("tbody").toggle();
	});


	//CONTENT ACCORDION
	$(".content-accordion .content, .content-accordion .close").hide();
	$(".content-accordion > .button").click(function () {
		$(this).parents(".content-accordion").find(".introduction, .content, .open, .close").toggle();
		return false;
	});


	// FILTERS
	$("#filters .hide").hide();
	$("#filters h4").click(function () {
		$(this).parents("fieldset").find("ol, hr").toggle();
		$(this).find("a").toggleClass("open");
		return false;
	});

	$(".filter-list .filters li:last").css({ "border-bottom": "0" });
	$(".filters .checked").parents("li").addClass("active");
	$(".filters input").change(function () {
		$(this).parents("li").toggleClass("active");
	});

	$("input:checkbox, select").uniform();

	// Show option lists on page load if they are not in a default state.
	if ($("#game-type-set input:checked").length) {
		$("#game-type-set ol").show();
	}
	if ($("#buy-in-from option:selected").index() > 0 ||
      $("#buy-in-to option:selected").index() > 0) {
		$("#buy-in-set ol").show();
	}
	if ($("#date-preset option:selected").index() > 0 ||
      $("#date-time option:selected").index() > 0 ||
      $("#date-from").val() != "" ||
      $("#date-to").val() != "") {
		$("#date-range-set ol").show();
	}

	$("#date-preset").change(function () {
		if ($(this).val() == "") {
			$("#date-from, #date-to").val("");
		} else {
			var today = new Date,
          start = new Date,
          end = new Date;

			if ($(this).val() == "1") {
				start.setDate(start.getDate() + 1);
				end.setDate(end.getDate() + 1);
			} else if ($(this).val() == "2") {
				var dow = start.getDay();
				var offset = (dow === 0) ? 7 : (7 - dow);

				start.setDate(start.getDate() + offset);
				end.setDate(start.getDate() + 7);
			} else if ($(this).val() == "3") {
				start.setMonth(start.getMonth() + 1);
				end.setMonth(end.getMonth() + 2);
				start.setDate(1)
				end.setDate(-1)
			}
		}

		$("#date-from").datepicker("setDate", start);
		$("#date-to").datepicker("setDate", end);
	});

	//COLORBOX POPUPS

	$(".colorbox").colorbox({ inline: true });
	$(".colorbox-video-gallery").colorbox({ inline: true, rel: 'video-gallery' });
	$(".colorbox-image-gallery").colorbox({ inline: true, rel: 'image-gallery' });
	$("#live-feed #photo-gallery ul a").colorbox();

	// AUTO OPEN PATHWAYS POPUP ON LOAD
	if (window.location.hash == "#pathways") {
		$.fn.colorbox({ href: "#pathways", open: true, inline: true });
	}

	$("#subscribe form").submit(function () {
		$.fn.colorbox({
			open: true,
			href: $('#subscribe form').attr('action'),
			iframe: true,
			height: "720px",
			width: "740px"
		});
		return false;
	});

	$(".subscribe-link").click().colorbox({
		iframe: true,
		height: "720px",
		width: "740px"
	});

	// Returns the content for a new satellite/schedule row.
	function new_satellite(data) {
		var register_btn = (data.HasOnlineBookings) ? "<a href=\"" + data.RegisterUrl + "\" class=\"button\">Register</a>" : "Book at Venue";

		function header() {
			return "<thead>" +
             "  <th class=\"event-number\">" + data.EventNumber + "</th>" +
             "  <th class=\"event-name\">" + data.Name + "</th>" +
             "  <th class=\"event-date\">" + data.StartDateString + "</th>" +
             "  <th class=\"event-cost\">" + data.CostInfo + "</th>" +
             "  <th class=\"event-register\">" + register_btn + "</th>" +
             "  <th class=\"arrow\"><span>Expand</span></th>" +
             "</thead>";
		}

		function share() {
			return "<ul class=\"share\">" +
             "  <li><h4>Share</h4></li>" +
             "  <li><span st_url=\"" + data.ShareUrl + "\" class=\"st_facebook\"></span></li>" +
             "  <li><span st_url=\"" + data.ShareUrl + "\" class=\"st_twitter\"></span></li>" +
             "  <li><span st_url=\"" + data.ShareUrl + "\" class=\"st_google\"></span></li>" +
             "  <li><span st_url=\"" + data.ShareUrl + "\" class=\"st_email\"></span></li>" +
             "  <li><span st_url=\"" + data.ShareUrl + "\" class=\"st_sharethis\"></span></li>" +
             "</ul>";
		}

		function buttons() {
			var buttonHtml = "<ul class=\"buttons\">";
			if (data.StructureAssetUrl != "") {
				buttonHtml += "  <li><a href=\"" + data.StructureAssetUrl + "\" class=\"button\">Structure</a></li>";
			}
			buttonHtml += "  <li><a href=\"#\" class=\"button\">Print</a></li>";
			if (register_btn != "Book at Venue") {
				buttonHtml += "  <li>" + register_btn + "</li>";
			}
			buttonHtml += "</ul>";
			return buttonHtml;
		}

		return "<tr>" +
           "  <td colspan=\"6\" class=\"accordion\">" +
           "    <table class=\"event\">" +
           header() +
           "      <tbody>" +
           "        <tr>" +
           "          <td colspan=\"6\">" +
           "            <div class=\"content\">" +
           "              <p>Game Type: <strong>" + data.GameType + "</strong></p>" +
           "              <p>" + data.Description + "</p>" +
           "            </div>" +
           "            <div class=\"extras clearfix\">" +
           share() +
           buttons() +
           "            </div>" +
           "          </td>" +
           "        </tr>" +
           "      </tbody>" +
           "    </table>" +
           "  </td>" +
           "</tr>";
	}

	// Load more for Satellites page.
	$("#events .load-more a").click(function () {
		var offset = $("#events table.event").length;
		var page_id = $("#events .load-more a").attr("SchedulePageID");

		$("#load-more-button, .loader").toggle();

		$.getJSON("/schedule-more/" + page_id + "/" + offset, function (data) {

			// Append all the rows
			$.each(data, function (i, row) {
				$("#events>tbody").append(new_satellite(row))
          .find("td.accordion>table>tbody").hide()
				stButtons.locateElements();
			});

			// Update the current count and hide the show more button if we've got everything
			$("#CurrentCount").html($("#events table.event").length);
			$("#load-more-button, .loader").toggle();
			if ($("#events table.event").length >= parseInt($("#TotalCount").html())) {
				$("#events .load-more a").hide();
			}
		});

		return false;
	});

	//LIVE FEED

	$("#events-list span").click(function () {
		$("#events-list ul").fadeToggle(200);
	});

	//FOOTER SEARCH

	$("#search-link, #footer-search-close").click(function () {
		$("#footer .extras").fadeToggle();
		$("#footer-search").fadeToggle();
		return false;
	});

	// MONEY FORMATTER

	Number.prototype.formatMoney = function (c, d, t) {
		var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
		return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
	};

	// OPEN EXTERNAL LINK IN NEW TAB/WINDOW (wait a sec before doing this to catch twitter URLs
	setTimeout("tweakLinkTargets();", 1500);
});

function tweakLinkTargets() {
	$("a[href*='http://']:not([href*='" + location.hostname + "'])").each(function () {
		$(this).attr("target", "_blank");
	});
}
