main();

//
// FUNCTION: main
//
// CONFIGURES THE COMMUNITY SERVER SUBMISSION FORMS.
//
function main ()
{
	$("#Register").bind("click", toggleRegister);
	$("#CommentForm").bind("submit", submitComment);
	$(".commentAction").bind("click", flagOffensive);
	$(".comment").hover(showFlagOffensive, hideFlagOffensive);
	$("#SubmissionForm").bind("submit", submitSubmission);
	$("#CSProjTitle").bind("keypress", suppressTab);
	$("#CSProjTitle").bind("keydown", suppressTab);
	
	//
	// SUBMIT IMAGES
	//
	//$("#ImageSubmissionForm").bind("submit", submitImages);
}


// returns true if the element can be seen
function isInvisible(el)
{
	ancestors = el.parents();
			
	for (var idx = 0; idx < ancestors.length; idx++)
	{
		var a = ancestors[idx];
		
		if ("form" == a.tagName.toLowerCase())
		{
			return false;
		}

		try 
		{
			if ("none" == a.style.display || "hidden" == a.style.visability) {
				return true;
			}
		}
		catch (er)
		{
			// suppress errors for elements that do not have the style object
		}	
	}
}


// returns an encoded string of a array of form name-value pairs
function encodeParams(formData)
{
	var serialData = new Array();
	
	$.each(formData, function (i)
	{
		var param = formData[i];
		if (! isInvisible($("#" + param.name)))
		{
			serialData.push(param.name + "=" + encodeURIComponent(param.value));
		}
	});
	
	return serialData.join("&");
}


// returns the value of the named param in an array of params
function getFormDataValue(formData, name)
{
	var value = null;
	
	$.each(formData, function (i)
	{
		var param = formData[i];
		
		if (name == param.name)
		{
			value = param.value;
		}
	});
	
	return value;
}

// returns a string or null for an elements text()
function getElText(doc, tagName)
{
	var text = null;
	
	var el = doc.getElementsByTagName(tagName);
	
	if (el && el[0])
	{
		text = (el[0].firstChild.nodeValue) ? el[0].firstChild.nodeValue : null;
	}
	
	return text;
}


// returns true when valid or displays messages and returns false
function isValidForm(formData, formTests)
{
	var isFormValid = true;
	
	$.each(formData, function (i) 
	{
		var param = formData[i];		
		var re = formTests[param.name];
		
		if (! re || isInvisible($("#" + param.name)))	
		{
			return;
		}
		
		var isValid;
		
		if ("string" == typeof re) 
		{
			isValid = (param.value == getFormDataValue(formData, re));
		}
		else 
		{
			isValid = re.test(param.value);
		}

		var msgEl = $("#" + param.name + "Msg");
		
		if (! isValid) 
		{
			msgEl.show();
			isFormValid = false;
			
			return;
		}
		
		msgEl.hide();
		
		return;
	});
	
	return isFormValid;
}


/* events section */

// displays/hides the registration block of the form
function toggleRegister() 
{
	$("#commentReg").toggle();
}


// displays report offessive comments link
function showFlagOffensive() 
{
	$(".commentAction", this).show();
}


// hides report offessive comments link
function hideFlagOffensive() 
{
	$(".commentAction", this).hide();
}


// confirm and call the server
function flagOffensive()
{
	var id = this.name.replace("commentid", "");
	
	var flag = confirm("Do you wish to notifiy the editors that you\nbelieve this comment is inappropriate?");
	
	if (flag)
	{
		var encodedData = "op=FlagCommentAsOffensive&CommentId=" + id
		$.ajax({type: "post", url: "ajax.asp", data : encodedData, dataType : "xml" , complete : receiveFlagCommentAsOffensive});
	}
	
	return false;
}


// report the servers status
function receiveFlagCommentAsOffensive(req, desc)
{
	if (200 != req.status)
	{
		alert("There are a problem with the request. Please try again in a few minutes.");
		return;
	}
	
	var doc = req.responseXML;

	// Status codes in the xml indicate what the data contains
	if (200 != $("status", doc).text())
	{
		alert($("description", doc).text());
		return;
	}
	
	alert("Thank you for your assistance.");
	return;
}


// validates and posts the comment form
function submitComment()
{
	if (! this.postBack)
	{
		this.postBack = this.action;
		this.action = "javascript:void(0)";
	}
	
	$("#CommentFormMsg").hide();
	
	var formData = $(this).serialize();
	
	if (! isValidForm(formData, CommentFormTests)) {
		return false;
	}
	
	var op = "CreateComment";
	var encodedData = encodeParams(formData) + "&Op=" + op;
	
	$("#OpSubmitComment").get(0).disable = true;
	
	$("#CommentFormMsg").get(0).innerHTML = "Submitting Comment.";
	$("#CommentFormMsg").fadeIn(500);
	$.ajax({type: this.method, url: this.postBack, data : encodedData, dataType : "xml" , complete : receiveComment});
	
	return false;
}


// fade in a message
function fadeInMsg(selector, msg)
{
	$(selector).hide();
	$(selector).get(0).innerHTML = msg;
	$(selector).fadeIn(1500);
}


// handles to server response to submitComment
function receiveComment(req, desc)
{
	$("#OpSubmitComment").get(0).disable = false;
	
	if (200 != req.status)
	{
		fadeInMsg("#CommentFormMsg", "Failed to submit the comment. There was a problem with the request from the server");
		return;
	}
	
	var doc = req.responseXML.documentElement;
	
	// Status codes in the xml indicate what the data contains
	if (200 != getElText(doc, "status"))
	{
		fadeInMsg("#CommentFormMsg", getElText(doc, "description"));
		return;
	}
	
	var comment = doc.getElementsByTagName("comment");
	
	if (! comment)
	{
		fadeInMsg("#CommentFormMsg", "Your comment was not returned. There may be an error.");
		return;
	}
	
	$("#CommentFormMsg").hide();
	$("#FirstComment").hide();
	$("#Comment").get(0).value = "";
	
	// confirm registration if that also happened
	var reg = getElText(doc, "Registration");
	if (reg)
	{
		$("#commentReg").hide();
		fadeInMsg("#RegFormMsg", reg);	
	}
	
	var html;
	
	for (var i = 0, it; null != (it = comment[0].childNodes[i]); i++)
	{
		if (4 == it.nodeType) {
			html = it.nodeValue;
			break;
		}
	}
	
	fadeInMsg("#CommentFormMsg", "There may be a delay before your comment is published.");
	$("#CommentList").append('<div class="fadeIn" style="display: none">' + html + '<hr /></div>');
	$(".fadeIn").fadeIn(1500);
	$(".fadeIn").removeClass("fadeIn");
}


// 
// FUNCTION: submitSubmission
//
// VALIDATES AND SUBMITS THE "SUBMIT YOUR OWN" PROJECT FORM.
//
function submitSubmission()
{
	if (!this.postBack)
	{
		this.postBack = this.action;
		this.action = "javascript:void(0)";
	}
	
	$("#SubmissionFormMsg").hide();
	
	tinyMCE.triggerSave();
	var formData = $(this).serialize();
	
	if (! isValidForm(formData, SubmissionFormTests)) {
		$("#SubmitErrors").show();
		return false;
	}
	
	var op = "CreateSubmission";
	var encodedData = encodeParams(formData) + "&Op=" + op;
	
	$("#OpSubmitSubmission").get(0).disable = true;

	$("#SubmissionFormMsg").get(0).innerHTML = "Submitting Your Information."
	$("#SubmissionFormMsg").fadeIn(500);
	$.ajax({type: this.method, url: this.postBack, data : encodedData, dataType : "xml" , complete : receiveSubmission});
	
	return false;
}


function receiveSubmission(req, desc)
{
	if (200 != req.status)
	{
		fadeInMsg("#SubmissionFormMsg", "Failed to submit your information. There was a problem with the request from the server");
		return;
	}
	
	var doc = req.responseXML;

	// Status codes in the xml indicate what the data contains
	if (200 != $("status", doc).text())
	{
		fadeInMsg("#SubmissionFormMsg", $("description", doc).text());
		return;
	}

	var projId = $("projectid", doc).text();

	if (! projId)
	{
		fadeInMsg("#SubmissionFormMsg", "Your Submission was not returned. There may be an error.");
		return;
	}
	
	$("#CSPostId").get(0).value = projId;
	$("#CSUsername").get(0).value = $("#Username").get(0).value;
	$("#CSPassword").get(0).value = $("#Password").get(0).value;
	
	$("#OpSubmitSubmission").get(0).disable = false;
	$("#SubmissionForm").fadeOut(1500);
	window.setTimeout('$("#ImageSubmissionForm").fadeIn(1500);', 1000);
}


//
// FUNCTION: submitImages
//
// INVOKED WHEN THE USER UPLOADS AN IMAGE.
//
function submitImages() 
{
	alert("FUNCTION: submitImages()")

	//
	// DISABLE THE FORM SUBMIT BUTTON (OpImageSubmissionForm) WHILE THE IMAGES UPLOAD SO THE USER DOES NOT SUBMIT THE TWICE.
	//
	$("#OpImageSubmissionForm").disable = true;

	//
	// DISPLAY A ROTATING ARROW ANIMATED GIF WHILE THE IMAGES UPLOAD.
	//
	var loadingGif = document.createElement('img');
	loadingGif.id = "loadIcon";
	$(loadingGif).attr({src: "images/rotating_arrow.gif"});
	$(loadingGif).css("float", "right");
	$(loadingGif).insertBefore("#ImageSubmissionFormMsg");
	
	//
	// DISPLAY A MESSAGE TO THE USER WHILE THE IMAGES UPLOAD.
	//
	$("#ImageSubmissionFormMsg").css("color", "#f47e37");
	$("#ImageSubmissionFormMsg").html("Your images are uploading...");
	$("#ImageSubmissionFormMsg").show();
	
	//
	//
	//
	//$.ajax({type: this.method, url: this.postBack, data : encodedData, dataType : "xml" , complete : receiveImages});
	
	return false;
}


//
// FUNCTION: isSuccessFadeForm
//
// FADES IN THE IMAGE UPLOAD SUCCESS MESSAGE TO THE USER.
//
function isSuccessFadeForm()
{
	$("#ImageSubmissionForm").hide();
	$("#successMsg").html("<div class='centerwellCalloutBody' style='height: 400px;'><h4>You have successfully uploaded your project!</h4><p>Thank your for your submission. Please continue to browse our <a href='http://www.architectmagazine.com/details.asp?sectionID=1020'>Details Gallery</a>.</p><div>").fadeIn(4000);
}


//
// FUNCTION: receiveImages
//
// INVOKED AFTER IMAGE SUBMISSION.  DISPLAYS ERROR OR SUCCESS MESSAGES.
//
function receiveImages(doc) 
{
	var statusCode = "";
	var description = "";

	if (!$.browser.msie)
	{
		statusCode = $("status", doc).text().toString();
		description = $("description", doc).text().toString();
	}
	else
	{
		doc = doc.ownerDocument;
		
		for (var i = 0; i < doc.childNodes[0].childNodes[1].childNodes.length; i++)
		{
			var node = doc.childNodes[0].childNodes[1].childNodes[i];
			
			if (node.tagName != null)
			{
				var nodeTagName = node.tagName.toString().toUpperCase();
			
				//if (i == 2 || i == 6) debugger
			
				if (nodeTagName == "STATUS")
				{
					statusCode = node.nextSibling.data; // usually [3]
				}
				else if (nodeTagName == "DESCRIPTION")
				{
					description = node.nextSibling.data; // usually [7]
				}
			}
			
			if (statusCode != "" && description != "") break;
		}
	}
	
	statusCode = $.trim(statusCode);
	description = $.trim(description);
	
	$("#ImageSubmissionFormMsg").text(description).show();
	
	if (statusCode == "200") setTimeout('isSuccessFadeForm()', 3000);
} 



function suppressTab(e)
{
	if (! e) {e = window.event;}
	
	var key = (e.keyCode) ? e.keyCode : e.which;

	if (9 == key) {return false;}
}


function suppressFocus(e)
{
	this.blur();
	$("#CSProjTitle").focus();
}




var CommentFormTests = 
{
	Username : /^.{6,32}$/,
	Password : /^.{6,32}$/,
	Comment : /[\w-]+/,
	FullName : /^.{4,64}$/,
	CSEmail : /^[\w-\.]+@([\w-]+\.)+[\w-]{2,9}$/,
	ConfUsername : "Username",
	ConfPassword : "Password"
}


var SubmissionFormTests = 
{
	Username : /^.{6,32}$/,
	Password : /^.{6,32}$/,
	ConfUsername : "Username",
	ConfPassword : "Password",	
	FullName : /^.{4,64}$/,
	CSTitle : /^.{2,50}$/,
	CSEmail : /^[\w-\.\_\-]+@([\w-]+\.)+[\w-]{2,9}$/,
	CSFirm : /^.{2,50}$/,
	CSAddress : /^.{5,100}$/,
	CSPhoneNumber : /^.*[\d]{3}[-. )(]*[\d]{3}[-. )(]*[\d]{4}.*$/,
	CSProjTitle : /^.{1,50}$/
}
