// replace #lt;, #rt;, and #amp; with <, >, and & after a transmission over ajax
function unpackageHTMLString(text) {
	return text.replace(/#lt;/g, "<").replace(/#rt;/g, ">").replace(/#amp;/g, "&");
}

// helper function to automatically check a radio button
function checkRadio(radioName, value) {
	var radios = $('input:radio[name=' + radioName + ']');
	var radioButton = radios.filter('[value=' + value + ']').attr('checked', true).click();
}

// helper function to automatically check a checkbox
function checkCheckBox(checkBoxName, value) {
	$('input[name=' + checkBoxName + ']').attr('checked', (value ? true : false));
}

// parses mysql datetime string and returns javascript Date object
// input string has to be in this format: 2007-06-05 15:26:02
function mysqlTimeStampToDate(timestamp) {    
	var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
	var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
	return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}

// retrieves an event over ajax and populates the form with its data
// eventID: the ID of the event
// formEventTable: the name of the table element that the event data form resides in
// formFillType: the context of the event form
function ajaxGetEvent(eventID, formEventTable, formFillType) {
	$(document).ready(function() {
		// if the event is null, then hide the form
		if(eventID == "!null") {
			$(formEventTable).css('display', 'none');
		} else {
			// otherwise, post to ajax to get the event data
			$.post("ajax.php", {request: "event.get", event: eventID}, function(xml) {
				// show the table
				$(formEventTable).css('display', 'inline');	
				
				// if updating, fill in the event title
				if(formFillType == "update") {
			                $("#Title").val($("title", xml).text());$("#ID").val(eventID);
				}
				
				// get the start time
				start = mysqlTimeStampToDate($("start", xml).text());
				// if updating, fill in the start date
				if(formFillType == "update") {
					startMonth = start.getMonth()+1;
					startDay = start.getDate();
					startYear = start.getFullYear();
					$("#StartDate").val("" + startMonth + "/" + startDay + "/" + startYear);
				}
				// process the start time (it is stored in military time; gets converted to common time)
				startHour = start.getHours();
				startMinute = start.getMinutes();
				startAMPM = "AM";
				if(startHour > 11)
					startAMPM = "PM";
				if(startHour > 12)
					startHour -= 12;
				else if(startHour == 0)
					startHour = 12;
				$("#StartHour").val("" + startHour);
				$("#StartMinute").val("" + startMinute);
				$("#StartAMPM").val(startAMPM).change();
				
				// do the same thing for end date/time
				end = mysqlTimeStampToDate($("end", xml).text());
				if(formFillType == "update") {
					endMonth = end.getMonth()+1;
					endDay = end.getDate();
					endYear = end.getFullYear();
					$("#EndDate").val("" + endMonth + "/" + endDay + "/" + endYear);
				}
				endHour = end.getHours();
				endMinute = end.getMinutes();
				endAMPM = "AM";
				if(endHour > 11)
					endAMPM = "PM";
				if(endHour > 12)
					endHour -= 12;
				else if(endHour == 0)
					endHour = 12;
				$("#EndHour").val("" + endHour);
				$("#EndMinute").val("" + endMinute);
				$("#EndAMPM").val(endAMPM).change();
				
				// if updating, set whether the event is featured (default for new is 'N')
				if(formFillType == "update") {
					featured = $("featured", xml).text();
			                checkRadio("Featured", featured);
				}
				// copy the image
				$("#Image").val("" + $("image", xml).text());
				handleImageCombo("resources/events", "Image_IMAGE");
				
				// copy the main and sub descriptions
				$("#MainDescription").html(unpackageHTMLString($("maindescription", xml).text()));
				$("#SubDescription").html(unpackageHTMLString($("subdescription", xml).text()));
				
				// copy the location type
				locationType = parseInt($("locationtype", xml).text());
				checkRadio("LocationType", locationType);
				
				// process the individual fields depending on the location type
				if(locationType == 1) { // member
					$("#LocationHost").val($("locationhost", xml).text()).change();
				} else if(locationType == 2) { // other place
					$("#LocationName").val($("locationname",xml).text());
					$("#LocationAddress").val($("locationaddress",xml).text());
					$("#LocationCity").val($("locationcity",xml).text());
					$("#LocationState").val($("locationstate",xml).text());
					$("#LocationZipcode").val($("locationzipcode",xml).text());
					$("#LocationPhone").val($("locationphone",xml).text());
				}
				try {
					// try to restart the image upload tool
					startOver();
				} catch(err) {}
				// snap the image upload flash box to its label
				snapOverlay();
			});
		}
	});
}

// flags a photo from the photo's page
function ajaxFlagPhoto(photoID, flagPhotoContainer) {
	$(document).ready(function() {
		// get the reason for the flag
		flagReason = $("#FlagReason").val();
		// update the status (so there isn't a double submission)
		$(flagPhotoContainer).html("Submitting flag report...");
		
		$.post("ajax.php", {request: "photo.flag", photo: photoID, reason: flagReason}, function(xml) {
			// update with the message from ajax.php
			$(flagPhotoContainer).html($("message", xml).text());
		});
	});
}

// removes the flag for a photo
function ajaxRemoveFlag(photoID) {
	$.post("ajax.php", {request: "photo.unflag", photo: photoID}, function(xml) {
		// remove the flag photo field from the form.
		$("#flag_" + photoID).html($("message", xml).text());
	});
}

// places an RSVP for an event
// eventID: the ID of the event
// numGuests: the number of guests the user intends to bring (including himself)
// rsvpForm: the form that holds the control for RSVP
// guestListForm: the form that holds the guest list
// rsvpValue: 'Y', 'M', or 'N'
function ajaxRSVP(eventID, numGuests, rsvpForm, guestListForm, rsvpValue) {
	if(parseInt(numGuests) < 1) {
		// error
	} else {
		$(rsvpForm).html("Submitting RSVP...");
		$.post("ajax.php", {request: "event.rsvp", event: eventID, guests: parseInt(numGuests), rsvp: rsvpValue}, function(xml) {
			$(rsvpForm).html($("message", xml).text());
			$(guestListForm).html(unpackageHTMLString($("guestlist", xml).text()));
		});
	}
}

// places an RSVP for an event
// eventID: the ID of the event
// userAlias: the name that the user gave himself on the RSVP form
// numGuests: the number of guests the user intends to bring (including himself)
// rsvpForm: the form that holds the control for RSVP
// guestListForm: the form that holds the guest list
// rsvpValue: 'Y', 'M', or 'N'
function ajaxRSVPAlias(eventID, userAlias, numGuests, rsvpForm, guestListForm, rsvpValue) {
	if(parseInt(numGuests) < 1) {
		// error
	} else if(userAlias == "") {
		// error
	} else {
		$(rsvpForm).html("Submitting RSVP...");
		$.post("ajax.php", {request: "event.rsvpalias", event: eventID, alias: userAlias, guests: parseInt(numGuests), rsvp: rsvpValue}, function(xml) {
			$(rsvpForm).html($("message", xml).text());
			$(guestListForm).html(unpackageHTMLString($("guestlist", xml).text()));
		});
	}
}

// places an RSVP for an event
// eventID: the ID of the event
// userCode: the UserSHA/code in the e-mail link for the event invitation
// numGuests: the number of guests the user intends to bring (including himself)
// rsvpForm: the form that holds the control for RSVP
// guestListForm: the form that holds the guest list
// rsvpValue: 'Y', 'M', or 'N'
function ajaxRSVPCode(eventID, userCode, numGuests, rsvpForm, guestListForm, rsvpValue) {
	if(parseInt(numGuests) < 1) {
		// error
	} else if(userCode == "") {
		// error
	} else {
		$(rsvpForm).html("Submitting RSVP...");
		$.post("ajax.php", {request: "event.rsvpcode", event: eventID, code: userCode, guests: parseInt(numGuests), rsvp: rsvpValue}, function(xml) {
			$(rsvpForm).html($("message", xml).text());
			$(guestListForm).html(unpackageHTMLString($("guestlist", xml).text()));
		});
	}
}

// submit a photo comment (soon to be deprecated)
function ajaxPhotoComment(photoID, commentText) {
	if(commentText == "") {
		// error
	} else {
		$.post("ajax.php", {request: "photo.comment", photo: photoID, comment: commentText}, function(xml) {
			// enter the comment box text into the comment box on the page
			$("#commentBox").html(unpackageHTMLString($("commentbox", xml).text()));
		});
	}
}

// submits a suggestion from the suggestion box
function ajaxSuggestionBox(suggestionText) {
	if(suggestionText == "") { // maybe do better?
		// error
	} else {
		$.post("ajax.php", {request: "misc.suggestion", suggestion: suggestionText}, function(xml) {
			// update the suggestion form with the message from ajax.php
			$("#suggestionForm").html($("message",xml).text());
		});
	}
}

// moves a page in sysadmin.pages
// pageNumber: the number of the page to move
// direction: the direction to move (+1 = farther down, -1 = farther up)
function ajaxMovePage(pageNumber, direction) {
	$.post("ajax.php", {request: "sysadmin.movepage", page: pageNumber, value: direction}, function(xml) {
		// once the change is made in ajax.php, its just a matter of animating the fields and updating their values
		
		fromID = $(xml).find("from").find("id").text();
		fromLabel = $(xml).find("from").find("label").text();
		fromPageName = $(xml).find("from").find("pagename").text();
		fromPermission = $(xml).find("from").find("permission").text();
		
		toID = $(xml).find("to").find("id").text();
		toLabel = $(xml).find("to").find("label").text();
		toPageName = $(xml).find("to").find("pagename").text();
		toPermission = $(xml).find("to").find("permission").text();
		
		// animate divs at fromID and toID
		$("#link" + fromID).animate({opacity: 0}, 400);
		$("#name" + fromID).animate({opacity: 0}, 400);
		$("#up" + fromID).animate({opacity: 0}, 400);
		$("#down" + fromID).animate({opacity: 0}, 400);
		$("#chk0_" + fromID).animate({opacity: 0}, 400);
		
		$("#link" + toID).animate({opacity: 0}, 600);
		$("#name" + toID).animate({opacity: 0}, 600);
		$("#up" + toID).animate({opacity: 0}, 600);
		$("#down" + toID).animate({opacity: 0}, 600);
		$("#chk0_" + toID).animate({opacity: 0}, 600, function() {
			// now that all items are hidden, change the values
			$("#link" + fromID).html("<a href=" + toPageName + ">" + toLabel + "</a>");
			$("#name" + fromID).html(toPageName);

			$("#link" + toID).html("<a href=" + fromPageName + ">" + fromLabel + "</a>");
		    $("#name" + toID).html(fromPageName);	 		
		    
		    for(i = 0; i < 3; ++i) {
				checkCheckBox("chk0_" + i + "_" + fromID, !!(toPermission & (1 << i))); 
				checkCheckBox("chk0_" + i + "_" + toID, !!(fromPermission & (1 << i)));
			}
			
			// now, reshow all items
			$("#link" + fromID).animate({opacity: 1}, 400);
		    $("#name" + fromID).animate({opacity: 1}, 400);
		    $("#up" + fromID).animate({opacity: 1}, 400);
		    $("#down" + fromID).animate({opacity: 1}, 400);
		    $("#chk0_" + fromID).animate({opacity: 1}, 400);
        	
		    $("#link" + toID).animate({opacity: 1}, 600);
		    $("#name" + toID).animate({opacity: 1}, 600);
		    $("#up" + toID).animate({opacity: 1}, 600);
		    $("#down" + toID).animate({opacity: 1}, 600);
		    $("#chk0_" + toID).animate({opacity: 1}, 600);
		});
	});
}

// update the page permisson for a specific page (in sysadmin.pages)
function ajaxPagePermission(pageID, sectionID, permissionLevel) {
	// figure out if the selected box is checked already
	pageName = "";
	checkName = 'chk0_' + permissionLevel + '_' + pageID + '';
	checked = $('input[name=' + checkName + ']').is(':checked');
	if(sectionID == 0) {
		pageName = $("#name" + pageID).text();
	} else {
		pageName = $("#static" + pageID).text();
	}
	
	// post the page name, the permissionLevel, and Y/N
	$.post("ajax.php", {request: "sysadmin.pagepermission", name: pageName, level: permissionLevel, set: (checked ? 1 : 0)}, function(xml) {
		checkCheckBox(checkName, checked);
	});
}

// set an album's thumbnail image
function ajaxSetAlbumThumbnail(albumID, thumbID) {
	$.post("ajax.php", {request: "photo.thumbnail", album: albumID, thumb: thumbID}, function(xml) {
		$("#albumThumbnailContainer").css("display", "block");
		$("#thumbnailLink").css("display", "none");
		
		if($("message", xml).text() == "Success")
			$("#albumThumbnailContainer").html("This photo is now the album thumbnail");
		else
			$("#albumThumbnailContainer").html("An error occured.");
	});
}
