function zeroPad(num,count) {
	var numZeropad = num + '';
	while(numZeropad.length < count) {
		numZeropad = "0" + numZeropad;
	}
	return numZeropad;
}

function isValidDate(d) {
  if ( Object.prototype.toString.call(d) !== "[object Date]" )
    return false;
  return !isNaN(d.getTime());
}

function fixDate(toFix) {
	var theDate = new Date(toFix.value);
	if ( isValidDate(theDate) ) {
		toFix.value = zeroPad((theDate.getMonth()+1),2) + "/" + zeroPad(theDate.getDate(),2) + "/" + theDate.getFullYear();
	}
}

function loadAttendeeData() {
	$.ajax({
		url: "attendeecount.cgi",
		success: function (data) {
			$("#recentlydeceased").html(data.MEMBERLIST);
			$("#recentlydeceasedcaption").html("The Recently Deceased<small>(" + data.TOTALCOUNT + " of 1500 tickets sold)</small>");
			if (data.MEMBERCOUNT < 16) {
				$("#recentlydeceased + .more").hide();
			}
		}
	});
}

function loadAttendeeData_all() {
	$.ajax({
		url: "attendeecount.cgi?all=1",
		success: function (data) {
			$("#recentlydeceased").fadeTo('fast', .01, function() {
				$("#recentlydeceased").html(data.MEMBERLIST);
				$("#recentlydeceased + .more").hide();
				$("#recentlydeceased").fadeTo('fast', 1);
			});
		}
	});
}

function DST(theDate){
	var yr = theDate.getFullYear();
	var dst_start = new Date("March 14, "+yr+" 02:00:00");
	var dst_end = new Date("November 07, "+yr+" 02:00:00");
	dst_start.setDate(14-dst_start.getDay());
	dst_end.setDate(7-dst_end.getDay());
	return (theDate >= dst_start && theDate < dst_end)
}

function convertToEST(theDate) {
	if (DST(new Date) != DST(theDate)) {
		return new Date(theDate.getTime() + (theDate.getTimezoneOffset() * 60000) + (3600000 * -4))
	} else {
		return new Date(theDate.getTime() + (theDate.getTimezoneOffset() * 60000) + (3600000 * -5))
	}
}

function filterPath(string) {
	return string
		.replace(/^\//,'')
		.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
		.replace(/\/$/,'');
}

function scrollableElement(els) {
	for (var i = 0, argLength = arguments.length; i <argLength; i++) {
		var el = arguments[i],
		$scrollElement = $(el);
		if ($scrollElement.scrollTop()> 0) {
			return el;
		} else {
			$scrollElement.scrollTop(1);
			var isScrollable = $scrollElement.scrollTop()> 0;
			$scrollElement.scrollTop(0);
			if (isScrollable) {
				return el;
			}
		}
	}
	return [];
}

function validEmail(toCheck) {
	var atpos=toCheck.indexOf("@");
	var dotpos=toCheck.lastIndexOf(".");
	return  !(atpos<1 || dotpos<atpos+2 || dotpos+2>=toCheck.length)
}

function checkRequired(toCheck) {
	var toReturn = true;
	var missing = "";
	toCheck.find(".required+input, .required+textarea, .required+div input, .required+div textarea").each( function() {
		if (this.value == "" || (this.type == "email" && !validEmail(this.value))) {
			var messagetext = "<b>" + this.name + "</b> " + (this.value == "" ?  "must be filled out." : "is not a valid email address.");
			$(this).closest(".clearfix").addClass("error");
			if (missing=="") { missing = messagetext; } else { missing += "<br>" + messagetext; }
			toReturn = false;
		} else {
			$(this).closest(".clearfix").removeClass("error");
		}
	});

	if (toReturn == false) {
		var toalert = toCheck.find(".alert-message");
		toalert.addClass("error");
		if (toalert.html() != "<p>Please fill out the following required fields:</p><p><strong>" + missing + "</strong></p>") {
			toalert.fadeOut(500, function() {
				toalert.html("<p>Please fill out the following required fields:</p><p><strong>" + missing + "</strong></p>");
			});
			toalert.fadeIn(500);
		}
	} else {
		var toalert = toCheck.find(".alert-message");
		toalert.fadeOut(500, function() { toalert.html("") });
	}

	return toReturn;
}

function clearRequired(toCheck) {
		var toalert = toCheck.find(".alert-message");
		toalert.fadeOut(500, function() { toalert.html("") });
	toCheck.find(".required+input, .required+textarea, .required+div input, .required+div textarea").each( function() {
		$(this).closest(".clearfix").removeClass("error");
	});
}

$(function() {
	$(".jsonly").removeClass("jsonly");
	$.waypoints.settings.scrollThrottle = 25;
	$("nav#mainnav").waypoint(function(event, direction) {
	   if (direction === 'down') {
		  $("header").css({paddingBottom: $(this).outerHeight()});
		  $(this).css({position: "fixed", top: 0, left: 0, right: 0, boxShadow: "0 0 10px #000"});
		  $("#top").addClass("show");
	   }
	   else if (direction === 'up') {
		  $(this).css({position: "relative", boxShadow: "none"});
		  $("header").css({paddingBottom: 0});
		  $("#top").removeClass("show");
	   }
	});
	
	$("#top").click(function() {
		$('html').animate({ scrollTop: 0 }, window.scrollY/2, function() {
			if ("pushState" in history)
				history.pushState("", document.title, window.location.pathname);
			else
				window.location.hash = "";
		});
		return false;
	});
	
	$('#counter').countdown({
		until: convertToEST(new Date("October 26, 2012 9:00 AM"))
	});

	$("body").bind("click", function (e) {
		$('nav#mainnav li.menu').removeClass("open");
	});

	$("nav#mainnav > ul > li.menu").bind("click", function (e) {
		var $li = $(this);
		if ($($li).is(".open")) {
			$('nav#mainnav li.menu').removeClass("open");
		} else {
			$('nav#mainnav li.menu').removeClass("open");
			$($li).addClass("open");
		}
		return false;
	});
	$("nav#mainnav > ul > li.menu li").click(function (e) {
		$('nav#mainnav li.menu').removeClass("open");
		e.stopPropagation();
	});
	$("nav#mainnav > ul > li.menu").bind("mouseenter", function (e) {
		var $li = $(this);
		if ($('nav#mainnav li.menu.open').length > 0 && !$($li).is(".open")) {
			$('nav#mainnav li.menu').removeClass("open");
			$($li).addClass("open");
		}
		return false;
	});

	var locationPath = filterPath(location.pathname);
	var scrollElem = scrollableElement('html', 'body');

	$('a[href*=#]').each(function() {
		var thisPath = filterPath(this.pathname) || locationPath;
		if (  locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/,'') ) {
			var $target = $(this.hash), target = this.hash;
			if (target) {
				var targetOffset = $target.offset().top;
				$(this).click(function(event) {
					event.preventDefault();
					$(scrollElem).animate({scrollTop: targetOffset}, (targetOffset - window.scrollY) / 2, function() {
						location.hash = target;
					});
				});
			}
		}
	});

	$("form").each(function() {
		var theForm = $(this);
		theForm.find("input[type='submit']").each(function() {
			$(this).bind("click", function() {
				return checkRequired(theForm);
			});
		});
		theForm.find("button[type='reset']").each(function() {
			$(this).bind("click", function() {
				return clearRequired(theForm);
			});
		});
	});

	if ($(".alert-message").length > 0) {$(".alert-message").hide(); }
	var search = $("select:not([data-search='no-search'])");
	if (search.length > 0) {search.chosen({disable_search_threshold:6});}
	search = $("select[data-search='no-search']");
	if (search.length > 0) {search.chosen({disable_search_threshold:-1});}
	
	if ($("#tweet").length > 0) {
		$("#tweet").tweet({
			username: "furfright",
			avatar_size: 32,
			count: 5,
			loading_text: "Please wait, Loading..."
		});
	}

	$("#dob").each(function() {
		var theField = this;
		$(this).bind("blur", function() {
			fixDate(theField);
		});
	});

	loadAttendeeData();
	
	$("#recentlydeceased + .more").bind("click", function() {
		loadAttendeeData_all();
		return false;
	});
	
});
