// JavaScript Document
var animating = false;
$(document).ready(function() {
	//Look for the compassion cookies to setup the subscribe messages if they have already subscribed
	if($.cookie('compassionID') != null) {
		var name = $.cookie('compassionName');
		var msg = "Welcome back!";
		if(name != null)
			msg = "Welcome back " + name + "!";
		
		$(".welcomeMessage").text(msg);
		$(".headerForm input").hide();
		$(".headerForm p").show();
		$(".footerForm").hide();
		$("#socialMedia").css("top","33px");
		$("#subscribeBar").hide();
	}
	
	$(".defaultText").focus(function() {
        if ($(this).val() == $(this)[0].title)
        {
            $(this).removeClass("empty");
            $(this).val("");
        }
    });
    $(".defaultText").blur(function() {
        if ($(this).val() == "" || $(this).val() == $(this)[0].title)
        {
            $(this).addClass("empty");
            $(this).val($(this)[0].title);
        }
    });
	$(".defaultText").blur();
	
	$(".logout").click(function() {
		$.cookie('compassionID',"-1", { path: '/' });
		$.cookie('compassionName',null, { path: '/' });
		location.reload(true);
		return false;
	});
	
	$(".subscribeForm").submit(function() {
		$emailField = $(this).find("input:text");
		
		var email = $emailField.val();
		
		var hasError = false;
        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
 
        if(email == '' || email == $emailField.attr("title")) //No email entered
            alert("Please enter your email address.");
        else if(!emailReg.test(email))  //Bad format
            alert("Enter a valid email address.");
        else {
			$subscribeForm = $(this);
			//Clear the first and lastname fields
			$(".defaultText").each(function() {
				if ($(this).val() == $(this)[0].title)
					$(this).val("");
			});
			$.post("/wp-content/themes/wnc/ajax/subscribe.php", {email : email, personID : $("#profilePersonID").val(), 
				firstname : $("#profileFirstName").val(), lastname : $("#profileLastName").val()}, function(data) {
				if(data != "") { //If there wasn't an error in the script

					var userData = $.parseJSON(data);
					
					gaTriggerIndex(userData['UserID'], '1', 'signup.html');
					
					//Reset the email field
					$emailField.val($emailField.attr("title"));
					$("#profileEmail").val(email);
					$("#profileFirstName").val(userData['FirstName']);
					$("#profileLastName").val(userData['LastName']);
					$("#storyEmail").val(email);
					$("#storyFirstName").val(userData['FirstName']);
					$("#storyLastName").val(userData['LastName']);
					$("#profileAddress1").val(userData['Address1']);
					$("#profileAddress2").val(userData['Address2']);
					$("#profileCity").val(userData['City']);
					$("#profileState").val(userData['State']);
					$("#profileZip").val(userData['Zip']);
					$("#profilePhone").val(userData['Phone']);
					$(".defaultText").blur();
					
					$(".subscribeForm").find("input").fadeOut(500, function() {
						$(".headerForm").find("p").fadeIn(500);
					});
					$("#subscribeBar").slideUp(500);
					$(".footerForm").fadeOut(500);
					
					$.cookie('compassionID', userData['UserID'], { expires: 365, path: '/' });
					$.cookie('compassionRefresh', '1', { path: '/' });
					if(userData['FirstName'] != undefined && userData['FirstName'] != "")
						$.cookie('compassionName', userData['FirstName'], { expires: 365, path: '/' });
				}
				
				
			});
			$(".defaultText").blur();
		}
 
        return false;
	});
	
	//Home page slideshow
	$("#billboard a").first().show().addClass("active");
	if($("#billboard a").length > 1)
		setInterval('rotateBillboard()', 5000);
		
	$(".viewProfile, .getStarted").fancybox({ 
		padding:0,  
		margin: 0
	});
	$(".iframe").fancybox({
			padding: 0,
			margin: 0,
			width: 700,
			height: 460
	});
	
	$(".fancybox").fancybox();

	$(".expandAddressContainer").click( function() {
		$(".profileAddressContainer").slideToggle(500, function() {$.fancybox.resize();});
		if($(this).text() == "(Click to expand)")
			$(this).text("(Click to hide)");
		else
			$(this).text("(Click to expand)");
		return false;
	});
	
	$("#profileForm").submit(function() {		
		//Remove the default text
		$(".defaultText").each(function() {
			if ($(this).val() == $(this)[0].title)
				$(this).val("");
		});
		$("#profileError").fadeTo(400, 0);
		
		var userID = $("#profileUserID").val();
		var firstname = $("#profileFirstName").val();
		var lastname = $("#profileLastName").val();
		var email = $("#profileEmail").val();
		
		var address1 = $("#profileAddress1").val();
		var address2 = $("#profileAddress2").val();
		var city = $("#profileCity").val();
		var state = $("#profileState").val();
		var zip = $("#profileZip").val();
		var phone = $("#profilePhone").val();
		var personID = $("#profilePersonID").val();
		$(".defaultText").blur();
		
		var hasError = false;
        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
 
        if(firstname == '') //No firstname entered
            $("#profileError").text("Please enter your first name.").fadeTo(400, 1);
		else if(lastname == '') //No lastname entered
           $("#profileError").text("Please enter your last name.").fadeTo(400, 1);
		else if(email == '') //No email entered
            $("#profileError").text("Please enter your email address.").fadeTo(400, 1);
        else if(!emailReg.test(email))  //Bad format
            $("#profileError").text("Enter a valid email address.").fadeTo(400, 1);
        else {
			$.post("/wp-content/themes/wnc/ajax/profile.php", {userID: userID, firstname: firstname, lastname:lastname, email : email,
				address1: address1, address2: address2, city: city, state:state, zip:zip, phone:phone, personID: personID}, function(data) {

					$.cookie('compassionID', data, { expires: 365, path: '/' });
					$.cookie('compassionName', firstname, { expires: 365, path: '/' });
					$.cookie('compassionRefresh', '1', { path: '/' });
					
					$(".subscribeForm").find("input").fadeOut(500, function() {
						$(".headerForm").find("p").fadeIn(500);
					});
					
					if(userID == "" || parseInt(userID) < 1)
						gaTriggerIndex(data, '1', 'signup.html');
					
					$(".footerForm").fadeOut(500);
					$("#profileGoBack").hide();
					$(".welcomeMessage").text("Welcome back " + firstname + "!");
					$("#profileError").text("Your profile was successfully updated.").fadeTo(400, 1, function() {
						$(".popupHeader p").text("");
						$(".popupHeader h1").text("Modify Your Profile");						
					});
					
					setTimeout("$.fancybox.close();", 1000);
			});
		}
		
		return false;
	});
	
	$("#forwardForm").submit(function() {		
		//Remove the default text
		$(".defaultText").each(function() {
			if ($(this).val() == $(this)[0].title)
				$(this).val("");
		});
		$("#forwardError").fadeTo(400, 0);
		
		var userID = $("#profileUserID").val();
		var personID = $("#profilePersonID").val();
		
		var firstname = $("#forwardFirstName").val();
		var lastname = $("#forwardLastName").val();
		var senderEmail = $("#forwardSenderEmail").val();
		
		var recipEmail = $("#forwardRecipEmail").val();
		var message = $("#forwardMessage").val();
		
		$(".defaultText").blur();
		
		var hasError = false;
        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
 
        if(firstname == '') //No firstname entered
            $("#forwardError").text("Please enter your first name.").fadeTo(400, 1);
		else if(lastname == '') //No lastname entered
           $("#forwardError").text("Please enter your last name.").fadeTo(400, 1);
		else if(senderEmail == '') //No email entered
            $("#forwardError").text("Please enter your email address.").fadeTo(400, 1);
        else if(!emailReg.test(senderEmail))  //Bad format
            $("#forwardError").text("Your email address is not valid.  Please try again.").fadeTo(400, 1);
		else if(recipEmail == '') //No email entered
            $("#forwardError").text("Please enter your friend's email address.").fadeTo(400, 1);
        else if(!emailReg.test(recipEmail))  //Bad format
            $("#forwardError").text("Your friend's email address is not valid.  Please try again.").fadeTo(400, 1);
        else {
			$.post("/wp-content/themes/wnc/ajax/forwardToAFriend.php", {senderUserID: userID, senderFirstname: firstname, senderLastname:lastname, 
				senderEmail : senderEmail, senderPersonID: personID, message: message, recipEmail: recipEmail}, function(data) {
					var userData = $.parseJSON(data);
					$.cookie('compassionID', userData['UserID'], { expires: 365, path: '/' });
					$.cookie('compassionName', firstname, { expires: 365, path: '/' });
					$.cookie('compassionRefresh', '1', { path: '/' });
					
					if(userID == "" || parseInt(userID) < 1)
						gaTriggerIndex(userData['UserID'], '1', 'signup.html');
					
					$(".subscribeForm").find("input").fadeOut(500, function() {
						$(".headerForm").find("p").fadeIn(500);
					});
					
					$(".footerForm").fadeOut(500);
					$("#forwardRecipEmail").val("")
					$(".welcomeMessage").text("Welcome back " + firstname + "!");
					$("#forwardError").text("Your email was successfully sent.").fadeTo(400, 1);
			});
		}
		
		return false;
	});
	
	$(".tooltip").tipTip();
	
	$("#storyTwitterPic").click(function() {
		$("#storySocialUsername").fadeIn(400);
		$("#tiptip_holder").fadeOut(200);
		$(this).toggleClass("active");
		return false;
	});
	$("#storyFacebookPic").click(function() {
		FB.login(function(response) {
			if (response.session) {
				FB.api('/me', function(user) {
			   		if(user != null) {
				   		$("#storyProfileImage").attr("src", "http://graph.facebook.com/" + user.id + "/picture?type=large");
						$("#storyProfileThumb").val("http://graph.facebook.com/" + user.id + "/picture?type=square")
			   		}
			 	});
		  	}
		});
		return false;
	});
	//If they click on the submit button under the upload icons
	$("#storySocialUsername .changeImage").click(function() { SetFacebookTwitterPics(); return false; });
	//If they hit enter on the facebook, twitter username text
	$("#storySocialUsername input").keydown(function(event) {
		if(event.keyCode == 13) {
		  event.preventDefault();
		  SetFacebookTwitterPics();
		  return false;
		}
	});
	
	$("#storyForm").submit(function() {		
		//Remove the default text
		$(".defaultText").each(function() {
			if ($(this).val() == $(this)[0].title)
				$(this).val("");
		});
		$("#storyError").fadeTo(100, 0);
		
		var userID = $("#profileUserID").val();
		var firstname = $("#storyFirstName").val();
		var lastname = $("#storyLastName").val();
		var email = $("#storyEmail").val();
		
		var storyText = $("#storyText").val();
		var title = $("#storyTitle").val();
		var videoEmbed = $("#storyVideo").val();
		
		var profileURL = $("#storyProfileImage").attr("src");
		var profileThumb = $("#storyProfileThumb").val();
		var imageURL = $("#storyPreviewImage").attr("src");
		var imageThumb = $("#storyPreviewThumb").val();
		if(imageURL.indexOf("imgPreview.jpg") != -1)
			imageURL = "";
				
		$(".defaultText").blur();
		
		var hasError = false;
        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
 
        if(firstname == '') //No firstname entered
            $("#storyError").text("Please enter your first name.").fadeTo(100, 1);
		else if(lastname == '') //No lastname entered
           $("#storyError").text("Please enter your last name.").fadeTo(100, 1);
		else if(email == '') //No email entered
            $("#storyError").text("Please enter your email address.").fadeTo(100, 1);
        else if(!emailReg.test(email))  //Bad format
            $("#storyError").text("Enter a valid email address.").fadeTo(100, 1);
		else if(title == '') //No firstname entered
            $("#storyError").text("Please enter the title of your remembrance.").fadeTo(100, 1);
		else if(storyText == "")
			$("#storyError").text("Please enter your story.").fadeTo(100, 1);
        else {
			$(".popupSubmit").attr("disabled", "true");
			$.post("/wp-content/themes/wnc/ajax/story.php", {userID: userID, firstname: firstname, lastname:lastname, email : email,
				title: title, content: storyText, videoEmbed:videoEmbed, profileURL:profileURL, profileThumb:profileThumb,
				imageURL: imageURL, imageThumb: imageThumb}, function(data) {
					$(".popupSubmit").attr("disabled", "false");
					//I threw an error message
					if(isNaN(data))
					{
						$("#storyError").text(data).fadeTo(100, 1);
					}
					else {
						//If they are already subscribed, just update the welcome message with the new name
						if($(".subscribeForm").find("input").css("display") == "none")
							$(".welcomeMessage").text("Welcome back " + firstname + "!");
						else {
							//They basically subscribed so hide the input fields and say hello
							$(".subscribeForm").find("input").hide();
							$(".welcomeMessage").text("Welcome " + firstname + "!");
							$(".headerForm").find("p").show();
							
							gaTriggerIndex($.cookie('compassionID'), '1', 'signup.html');
						}
						
						//Reset the fields
						$("#profileFirstName").val(firstname);
						$("#profileLastName").val(lastname);
						$("#profileEmail").val(email);
						$("#storyText").val("");
						$("#storyTitle").val("");
						$("#storyVideo").val("");
						
						$("#storyProfileImage").attr("src", "/wp-content/themes/wnc/images/imgSharePortrait.jpg");
						$("#storyProfileThumb").val("");
						$("#storyPreviewImage").attr("src", "/wp-content/themes/wnc/images/imgPreview.jpg");
						$("#storyPreviewThumb").val("");
						$(".defaultText").blur();
						
						$.cookie('compassionName', firstname, { expires: 365, path: '/' });
						$.cookie('compassionRefresh', '1', { path: '/' });
						
						//Reassign the blank link on the home page
						$(".transparency img").first().attr("src", profileThumb);
						$(".relational .iframe").first().attr("href", "/wp-content/themes/wnc/story.php?id=" + data);
						//CLick on it to now show the person's newly shared story
						$(".relational .iframe").first().click();
					}
			});
		}
		
		return false;
	});
	
	if($("#shareSlide").length > 0)
		$("#shareSlide").width($("#shareSlide .story").length * $("#shareSlide .story").outerWidth(true));
	$("#shareR").click(function() {
		//If I can move the container to the left
		//8 images are shown at a time
		if(!animating && $("#shareSlide").position().left > 
			-1 * Math.ceil($("#shareSlide .story").length/8 - 1) * 8 * $("#shareSlide .story").outerWidth(true)) {
			animating = true;
			//8 images are shown at a time
			$("#shareSlide").animate({"left": "-=" + $("#shareSlide .story").outerWidth(true) * 8 + "px"}, 1000, function() {
				animating = false;
				//Reset the hover state if I can't move any more to the right
				if($("#shareSlide").position().left <= -1 * Math.ceil($("#shareSlide .story").length/8 - 1) * 8 * $("#shareSlide .story").outerWidth(true)) {
					//Try to get more stories
					if ($("#shareSearchText").val() == $("#shareSearchText")[0].title)
						$("#shareSearchText").val("");
					//Get the next set of stories to add to the area
					$.post("/wp-content/themes/wnc/ajax/searchStories.php", {searchString: $("#shareSearchText").val(), numStories: 8, 
						startPoint: $("#shareSlide .story").length}, function(data) {
						if(data != "") {
							//Parse the stories that were returned to me
							var stories = $.parseJSON(data);
							//If ther are more stories to display
							if(stories.length != 0) {
								//Readjust the width
								$("#shareSlide").width(($("#shareSlide .story").length + stories.length) * $("#shareSlide .story").outerWidth(true));
								//Loop through each story
								$.each(stories, function() {
									//Create the html element that displays the story
									var element = '<div class="story">';
									element += '<a href="/wp-content/themes/wnc/story.php?id=' + this['StoryID'] + '" class="iframe profileImage dynamiciframe">';
									element += '<img src="' + this['ProfileThumb'] + '" alt="" class="colorImage" />';
									element += '<img src="/grayscaleImage.php?path=' + encodeURI(this['ProfileThumb']) + '" alt="" class="grayImage" />';
									element += '</a>';
									element += '<p><a href="/wp-content/themes/wnc/story.php?id=' + this['StoryID'] + '" class="iframe dynamiciframe">' + this['Title'] + '</a></p>';
									element += '</div>';
									//Add it to the list
									$("#shareSlide").append(element);
								});
								$(".dynamiciframe").fancybox({
									padding: 0,
									margin: 0,
									width: 700,
									height: 460
								});

							}
							else
									//No more stories to display
									$("#shareR").css("background-position", "");
						}
						else
							//No more stories to display
							$("#shareR").css("background-position", "");
					});
					
					$(".defaultText").blur();
				}
				
			})
		}
		return false;
	});
	$("#shareL").click(function() {
		//If I can move the container to the left
		if(!animating && $("#shareSlide").position().left < 0) { 
			animating = true;
			//8 images are shown at a time
			$("#shareSlide").animate({"left": "+=" + $("#shareSlide .story").outerWidth(true) * 8 + "px"}, 1000, function() {
				animating = false;
				//Reset the hover state if I can't move any more to the right
				if($("#shareSlide").position().left == 0)
					$("#shareL").css("background-position", "");
			})
		}
		return false;
	});
	//The hover effect of the arrow buttons
	$("#shareR").hover(function() {
		//If I can move the container to the left
		//8 images are shown at a time
		if($("#shareSlide").position().left > -1 * Math.ceil($("#shareSlide .story").length/8 - 1) * 8 * $("#shareSlide .story").outerWidth(true))
			$(this).css("background-position", "100% 0");
	}, function() {
		$(this).css("background-position", "");
	});
	//The hover effect of the arrow buttons
	$("#shareL").hover(function() {
		if($("#shareSlide").position().left < 0)//If I can move the container to the right
			$(this).css("background-position", "0 0");
	}, function() {
		$(this).css("background-position", "");
	});
	
	//The seach feature on the recent posts area 
	$("#shareSearchForm").submit(function() {
		//Clear the past stories
		$("#shareSlide .story").addClass("removeMe");
		$("#shareSlide .story").fadeOut(500);
		//Try to get more stories
		if ($("#shareSearchText").val() == $("#shareSearchText")[0].title)
			$("#shareSearchText").val("");
			
		//Get the next set of stories to add to the area
		$.post("/wp-content/themes/wnc/ajax/searchStories.php", {searchString: $("#shareSearchText").val(), startPoint: 0, numStories: 16}, function(data) {

			if(data != "") {
				//Parse the stories that were returned to me
				var stories = $.parseJSON(data);
				//If ther are more stories to display
				if(stories.length != 0) {
					//Loop through each story
					$.each(stories, function() {
						//Create the html element that displays the story
						var element = '<div class="story" style="display:none">';
						element += '<a href="/wp-content/themes/wnc/story.php?id=' + this['StoryID'] + '" class="iframe profileImage dynamiciframe">';
						element += '<img src="' + this['ProfileThumb'] + '" alt="" class="colorImage" />';
						element += '<img src="/grayscaleImage.php?path=' + encodeURI(this['ProfileThumb']) + '" alt="" class="grayImage" />';
						element += '</a>';
						element += '<p><a href="/wp-content/themes/wnc/story.php?id=' + this['StoryID'] + '" class="iframe dynamiciframe">' + this['Title'] + '</a></p>';
						element += '</div>';
						//Add it to the list
						$("#shareSlide").append(element);
					});
					//Readjust the width
					$("#shareSlide").width(stories.length * $("#shareSlide .story").outerWidth(true));
					$("#shareSlide").css("left", "0px");
					$("#shareSlide .story").fadeIn(500);
					
					$(".dynamiciframe").fancybox({
							padding: 0,
							margin: 0,
							width: 700,
							height: 460
					});
					
				}
				$("#shareSlide .removeMe").remove();
			}
			else
				//No more stories to display
				$("#shareR").css("background-position", "");
		});
		
		$(".defaultText").blur();
		return false;
	});
	
	//The colorization effect on the search recent posts section
	$(".profileImage").live("mouseenter", function() {
		$(this).find(".grayImage").stop().fadeTo(500 * parseFloat($(this).find(".grayImage").css("opacity")), 0)
		
	});
	$(".profileImage").live("mouseleave", function() {
		$(this).find(".grayImage").stop().fadeTo(500 - 500 * parseFloat($(this).find(".grayImage").css("opacity")), 1)
		
	});
	
	$(".relational").hover(function() {
		$img = $("#" + $(this).attr("rel"));
		//Save the default dimensions for the mouseout event below
		if($img.data("left") == undefined) {
			$img.data("left", $img.position().left);
			$img.data("top", $img.position().top)
			$img.data("width", $img.width())
			$img.data("height", $img.height())
		}
		else {
			
		}
		$img.css({zIndex:130});
		$(this).css({zIndex:130});
		//70 is the maximum width/height of the images
		$img.stop().animate({
			opacity: 1,
			left: "-=" + ((70 - $img.width()) /2) + "px",
			top: "-=" + ((70 - $img.height()) /2) + "px",
			width: "70px",
			height: "70px"
			
		}, 1000);
	}, function() {
		$img = $("#" + $(this).attr("rel"));
		$img.css({zIndex:5});
		$(this).css({zIndex:15});
		$img.stop().animate({
			opacity: .2,
			left: $img.data("left") + "px",
			top: $img.data("top") + "px",
			width: $img.data("width") + "px",
			height: $img.data("height") + "px"
		}, 1000);
	});
	
	
	$(".eventList li a").not(".directLink").each(function() {
		$link = $(this);
		$(".contentShow").each(function() {
			if($(this).attr("rel") == $link.attr("rel")) 
				$link.siblings("ul").append('<li><a href="#' + $(this).data("target") + '">' + $(this).find("h1").html() + '</a></li>');
		});
	});
		// Hide and show the content area base on date 
	$(".eventList li a").not(".directLink").click(function(){
		$(".eventList li a").removeClass("active");		
		
		$link = $(this);
		if(!$(this).hasClass("parentLink"))
			$link = $(this).parents(".parentListItem").find(".parentLink");
			
		$link.addClass("active");					
		$(".contentShow").each(function() {
			if($(this).attr("rel") ==$link.attr("rel"))
				$(this).show();	
			else
				$(this).hide();
		});
		
		if(!$(this).hasClass("parentLink"))
			return true;
		else
			return false;
	});
	
	$(".eventList li a").each(function(){
		if($(this).attr("select") == "true"){
			$(this).addClass("active");
			$(this).click();
		}
	});
	
	if($(".sliderContainer a").length > 12) {
		//110 is the width of the image and margin combined
		$(".sliderContainer div").width( Math.ceil($(".sliderContainer a").length/2) * 110);
		$("#leftArrow").click(function() {
			if(!animating) {
				animating = true;
				$("#rightArrow").css("display", "block");
				//Disable the arrow button if necessary
				if($(".sliderContainer div").position().left + $(".sliderContainer").outerWidth(true) >= 0)
					$(this).hide();
				//Move the container
				$(".sliderContainer div").animate({"left": "+=" + $(".sliderContainer").outerWidth(true) + "px"}, 1000, function() { animating = false; });
			}
			return false;
		});
		
		$("#rightArrow").click(function() {
			if(!animating) {
				animating = true;
				$("#leftArrow").css("display", "block");
				//Disable the arrow button if necessary
				if($(".sliderContainer div").position().left - $(".sliderContainer").outerWidth(true)*2 <= -1 * $(".sliderContainer div").width())
					$(this).hide();
				//Move the container
				$(".sliderContainer div").animate({"left": "-=" + $(".sliderContainer").outerWidth(true) + "px"}, 1000, function() { animating = false; });
			}
			return false;			
		});
	}
	else
		$("#rightArrow").hide();
	
	$(".printerVersion").click(function() {
		$( ".contentArea" ).print();
		return false;
	});
});

//Depending on the button clicked, it updates the image to the twitter or facebook profile pic
function SetFacebookTwitterPics() {
	if($("#storyFacebookPic").hasClass("active")) {
		$("#storyProfileImage").attr("src", "http://graph.facebook.com/" + $("#storySocialUsername input").val() + "/picture?type=large");
		$("#storyProfileThumb").val("http://graph.facebook.com/" + $("#storySocialUsername input").val() + "/picture?type=square")
	}
	else if($("#storyTwitterPic").hasClass("active"))  {
		$("#storyProfileImage").attr("src", "http://api.twitter.com/1/users/profile_image/"+$("#storySocialUsername input").val()+"?size=original");
		$("#storyProfileThumb").val("http://api.twitter.com/1/users/profile_image/"+$("#storySocialUsername input").val()+"?size=bigger")
	}

	$("#storySocialUsername input").val("Enter username");
	
	//Revert back to the original view of all upload icon options showing
	$(".shareUploadLink").removeClass("active");
	$("#storySocialUsername").fadeOut(400);
	
}

function rotateBillboard() {
	//If there is another image after the current one
	if($("#billboard a.active").next().length > 0) 
		$("#billboard a.active").next().fadeIn(500, function() { $(this).addClass("active") });
	else //Just make the first one fade in
		$("#billboard a").first().fadeIn(500, function() { $(this).addClass("active") });
		
	//Fade out the active one
	$("#billboard a.active").fadeOut(500, function() {$(this).removeClass("active") });
};


function MediaUploaded(fileName, target) {
	var img = "http://wncimages.s3.amazonaws.com/" + uploadDir.replace("${filename}", fileName);
	$("#" + target).attr("src", img);
	
	$.ajax({
  		url:"/wp-content/themes/wnc/ajax/createThumb.php",
		data: {src_url: img}, 
		success: function(data) {
			if(target == "storyProfileImage") {
				$("#storyProfileThumb").val(data);
				$("#storySocialProcessing").hide();	
			}
			else {
				$("#storyPreviewThumb").val(data);
				$("#storyUploadProcessing").hide();
			}
		}
	});
}

//Removes all links to the given story 
function MarkAsInappropriate(storyID) {
	//Loop through the mosaic stories
	$("#mosaic a").each(function() {
		if($(this).attr("href").indexOf("story.php?id=" + storyID) != -1 ) {
			//Remove the image
			$("#" + $(this).parent().attr("rel")).remove();
			//Then remove the actual link	
			$(this).parent().remove();
		}
	});
	//Remove the searched stories
	$("#shareWindow a").each(function() {
		if($(this).attr("href").indexOf("story.php?id=" + storyID) != -1) 
			//Remove the actual link	
			$(this).remove();
		
	});
	$.fancybox.close();
	alert("Thank you for helping us keep this as a true memorial for the events of 9/11.  This story will be review immediately" +
		" and will be removed if it is found to be inappropriate.");
}

function gaTriggerIndex(code, charge, page) {
	_gaq.push(['_trackPageview', page]);
	_gaq.push(['_addTrans', code, '', charge, '', '', '', '', '']);
	_gaq.push(['_trackTrans']);
}

function RefreshComments(postID) {
	var lastCommentID = null;
	if($(".commentHolder p").length > 0)
		lastCommentID = $(".commentHolder p").first().data("id")
	$.post("/wp-content/themes/wnc/ajax/eventComments.php", {postID: postID, lastCommentID: lastCommentID}, function(data) {
		var comments = $.parseJSON(data);
		for(var i = 0; comments != null && i < comments.length; i++) {
			var now = Date.parse(comments[i]['DateAdded']);
			//lastRefreshTime = now.format();

			var element = '<p style="display:none;" data-id="'+comments[i]['EventCommentID']+'"><span class="blue">' + 
				dateFormat(now, "mm/dd/yyyy h:MM TT") + '</span> - '+comments[i]['Comment']+'</p>';
			$(".commentHolder").prepend(element);
			$(".commentHolder p").first().slideDown(500);
		}
		
	});
}

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

