var storyType = location.href.split("/")[6];
if((storyType == "CommentStory") || (storyType == "WBStory")) { var strAlert = "comment"; } else { var strAlert = "review"; }

var xmlhttp, commentid, modLevel;

function showError(type) {
	var commentForm = $("commentForm");
	var commError = $("commentError");
	var objComment = $("comment");
	var commentHole = $("commentHole");
	var sbmtBtn = $("submitComment");
	var txtWarn = d.createTextNode("WARNING: Please be advised that you are approaching the maximum number of characters allowed in a " + strAlert + ". You can submit up to 2,000 characters.");
	var txtLimit = d.createTextNode("ALERT: You are over 2,000 characters. Please shorten your " + strAlert + ".");
	var txtBlank = d.createTextNode("Please enter a " + strAlert + " before submitting for approval.");
	var txtRating = d.createTextNode("Please select a rating for this feature.");
	var txtReviewTitle = d.createTextNode("Please provide your review with a title.");
	var txtRejected = d.createTextNode("Your comment has been rejected by our filters. Your comment did not comply with the conversation guidelines in our Editor\u2019s note.");
		
	if(commError == null) {
		// no error on page so create one
		var errMessage = createElement("p","commentError");
		if(type == "warning") {
			commentHole.className = "default";
			errMessage.appendChild(txtWarn);
		} else if(type == "limit") {
			commentHole.className = "error";
			errMessage.appendChild(txtLimit);
		} else if (type == "blank"){
			commentHole.className = "error";
			errMessage.appendChild(txtBlank);
		} else { 
			// comment has been rejected because it doesn't pass the manners filter
			errMessage.className = "blank";			
			errMessage.appendChild(txtRejected);			
			Element.remove(commentForm);
			while($("comment-remarks").firstChild) {
				$("comment-remarks").removeChild($("comment-remarks").firstChild);
			}
			$("comment-remarks").appendChild(errMessage);
			$("comment-remarks").style.display = "none";
			new Effect.Appear($("comment-remarks"));
			return;
		}
		errMessage.className = type;
		commentForm.insertBefore(errMessage, sbmtBtn);
	} else {
		// an error exists on the page but they are not of the same type
		if(type != commError.className) {
			if( (type == "limit") && (commError.className == "warning") ) {
				commentHole.className = "error";
				commError.replaceChild(txtLimit, commError.childNodes[0]);
			}
			commError.className = type;
			if(type == "warning") {
				commentHole.className = "default";
				commError.replaceChild(txtWarn, commError.childNodes[0]);
			} else if(type == "limit") {
				commentHole.className = "error";
				commError.replaceChild(txtLimit, commError.childNodes[0]);
			} else {
				commentHole.className = "error";
				commError.replaceChild(txtBlank, commError.childNodes[0]);
			}
			commentForm.insertBefore(commError, sbmtBtn);
		} else {
			// the error on the page is the same as the one just made
			return;
		}
	}
}

function countChars(e) {
	e = (!e) ? window.event : e;
	var commentHole = $("commentHole");
	if((commentHole.value.length >= 1950) && (commentHole.value.length <= 2000)) {
		showError("warning");
		$("chars").firstChild.nodeValue = 2000 - commentHole.value.length;
		return;
	}
	if(commentHole.value.length > 2000) {		
			showError("limit");
			$("chars").firstChild.nodeValue = commentHole.value.length - 2000 + " characters over\u2026" ;
			return;
	}
	// hide errors etc on keyup
	if(e.type == "keyup") {
		hideErrors(e);	
	}
	
	$("chars").firstChild.nodeValue = 2000 - commentHole.value.length;
}

function checkCommentsLength(e,text){
	e = (!e) ? window.event : e;
	if(text.length == 0) { 
		showError("blank");
		return false; 
	} else if(text.length > 2000) {
		showError("limit");
		return false; 	
	} else {
		return true;
	}	
}

function hideErrors(e) {
	e = (!e) ? window.event : e;	
	var commError = $("commentError");
	var commentHole = $("commentHole");
	if(commError != null) {
		if(commentHole.value.length < 2000 && ((commError.className == "blank") || (commError.className=="limit"))) {
			commentHole.className = "default";		
		}
		$("commentForm").removeChild(commError);	
	}	
}

function checkComments(e){
	e = (!e) ? window.event : e;
	var regex = new RegExp("<[^>]+>", "g");
	var commentForm = $("commentForm");	
	
	var city = commentForm.city.value;
	city = city.replace(regex, " ");
	commentForm.city.value = city;
	setCookie("TGAM-city",escape(city));

	var firstname = commentForm.firstname.value;
	commentForm.firstname.value = (firstname!="First Name") ? firstname : "";
	firstname = firstname.replace(regex, " ");
	
	var lastname = commentForm.lastname.value;
	commentForm.lastname.value = (lastname!="Last Name") ? lastname : "";
	lastname = lastname.replace(regex, " ");	
		
	var comL = checkCommentsLength(e, commentForm.commentHole.value);
	if(checkCommentsLength(e, commentForm.commentHole.value)==false) {
		return comL;
	} else {
		submitComment();
		return false;
	}
}

function submitComment() {
	var commentForm = $("commentForm");
	//filter
	var manners = missManners("b",1,"",commentForm.commentHole.value);

    //if(manners != true) {
    //   showError("reject");
    //   return false;
    //}
	
	//handle validation for ReviewStory first
	if(storyType == "ReviewStory") {
		if(commentForm.reviewTitle.value == "") {
			commentForm.reviewTitle.className = "error";
			return false;
		}
		if(commentForm.rating.value == "") {
			if(commentForm.reviewTitle.className == "error") {
				commentForm.reviewTitle.className = "default";
			}
			$("ratings").className = "error";
			return false;
		}		
	}
	
	if (validateSortAndSlug($F("create_date"), $F("create_slug")) && manners == true) {
		var url = commentForm.action;	
		var showUserId;
		if($("showUsername")) { ($("showUsername").checked == true) ? showUserId = "yes" : showUserId = "no"; }
		// "Join the conversation and win" thing
		if($("userContest")) {
			var comment_contest_entry;
			if($("userContest").checked == true) {
				comment_contest_entry = "true";
			} else {
				comment_contest_entry = "false";
			} 
		}
		//clean fname, lname, city
		var userFields = cleanUserFields([commentForm.firstname.value, commentForm.lastname.value, commentForm.city.value]);	
		url += '?firstname=' + encodeURI(userFields[0]) + '\u0026lastname=' + encodeURI(userFields[1]) + '\u0026displayUserName=' + encodeURI(showUserId);
		url += '\u0026email=' + encodeURI($F("email")) + '\u0026city=' + encodeURI(userFields[2]) + '\u0026user_country=' + encodeURI($F("user_country"));
		url += '\u0026userid=' + encodeURI(commentForm.userid.value) + '\u0026account=' + encodeURI(commentForm.account.value) + '\u0026create_date=' + encodeURI($F("create_date"));
		url += '\u0026create_slug=' + encodeURI($F("create_slug"));
		url += '\u0026bozo=' + encodeURI($F("bozo"));
		if(storyType != "ReviewStory") {
			url += '\u0026commentHole=' + encodeURI(cleanComment($F("commentHole")));
		} else {	
			var featureTitle = "[FEATURE_TITLE]" + cleanComment(commentForm.featureTitle.value) + "[/FEATURE_TITLE]";
			var reviewTitle = "[REVIEW_TITLE]" + cleanComment(commentForm.reviewTitle.value) + "[/REVIEW_TITLE]";
			var stars = "[RATING]" + commentForm.rating.value + "[/RATING]";
			var review = reviewTitle + stars + "[REVIEW_BODY]" + cleanComment(commentForm.commentHole.value) + "[/REVIEW_BODY]";
			url += '\u0026commentHole=' + encodeURI(review);
		}
		// "Join the conversation and win" thing
		if($("userContest")) {
			url += '\u0026comment_contest_entry=' + comment_contest_entry;
		}
		url += '\u0026save=true';
		
		xmlhttp = hector();

		xmlhttp.open("POST", url, true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {
				if(xmlhttp.status == 200) {
					thankYou();
				}
			} 	
		}
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send('');
		$("comment").removeChild(commentForm);
		while($("comment-remarks").firstChild) {
			$("comment-remarks").removeChild($("comment-remarks").firstChild);
		}
		$("post").firstChild.nodeValue = "Submitting your " + strAlert + " for approval\u2026";
		YFTinit(5,"comment-remarks");		
		
	} else {		
		$("comment").removeChild(commentForm);
		while($("comment-remarks").firstChild) {
			$("comment-remarks").removeChild($("comment-remarks").firstChild);
		}
		$("post").firstChild.nodeValue = "Submitting your " + strAlert + " for approval\u2026";
		YFTinit(5,"comment-remarks");
		thankYou();
	}
} 

function cleanUserFields(fields) {
	var tmp = [];
	var fields = $A(fields);
	fields.each(function(field) {
		field = field.replace(/\u0009/g,''); // replace tabs
		field = field.replace(/\u000B/g,''); // replace vertical tab
		field = field.replace(/\u000C/g,''); // replace form feed
		field = field.replace(/\u000A/g,''); // replace line feed
		field = field.replace(/\u000D/g,''); // replace carriage return	
		tmp.push(field);
	});
	return tmp;
}		

function thankYou(){
	var txtThanks;
	var nObj = $("comment-remarks");
	nObj.className = "submitted";
	hObj = ($("post")) ? $("post") : $("postComment");
	hObj.firstChild.nodeValue = "Thank you for your " + strAlert;
	var pObj = createElement("p", "thank-you");
	if (modLevel == "fully") {
		txtThanks = d.createTextNode("Your " + strAlert + " has been submitted for approval. An editor will review your " + strAlert + " before posting it to the website. The review process could take up to 24 hours, but you will be notified by e-mail when it appears. Thanks for joining the conversation!");
	} else {
		txtThanks = d.createTextNode("Your comment has been submitted and will appear on the website in a few minutes. Thanks for joining the conversation!");
	}
	pObj.appendChild(txtThanks);
	nObj.appendChild(pObj);
}


function cleanComment(v){
	var regex = new RegExp("<[^>]+>", "g");
	v = v.replace(regex, "");
	v = v.replace(/\u201A/g,'&#8218;');
	v = v.replace(/\u201A/g,'&#8218;');
	v = v.replace(/\u0192/g,'&#402;');
	v = v.replace(/\u201E/g,'&#8222;');
	v = v.replace(/\u2026/g,'&#8230;');
	v = v.replace(/\u2020/g,'&#8224;');
	v = v.replace(/\u2021/g,'&#8225;');
	v = v.replace(/\u02C6/g,'&#710;');
	v = v.replace(/\u2030/g,'&#8240;');
	v = v.replace(/\u0160/g,'&#352;');
	v = v.replace(/\u2039/g,'&#8249;');
	v = v.replace(/\u0152/g,'&#338;');
	v = v.replace(/\u2018/g,'&#8216;');
	v = v.replace(/\u2019/g,'&#8217;');
	v = v.replace(/\u201C/g,'&#8220;');
	v = v.replace(/\u201D/g,'&#8221;');
	v = v.replace(/\u2022/g,'&#8226;');
	v = v.replace(/\u2013/g,'&#8211;');
	v = v.replace(/(\u2014)|(\u2015)/g,'&#8212;');
	v = v.replace(/\u20DC/g,'~');
	v = v.replace(/\u2122/g,'&#8482;');
	v = v.replace(/\u0161/g,'&#353;');
	v = v.replace(/\u203A/g,'&#8250;');
	v = v.replace(/\u0153/g,'&#339;');
	v = v.replace(/\u0178/g,'&#376;');
	v = v.replace(/\\/g,'&#92;');
	v = v.replace(/[&]/g,'\u0026');
	v = v.replace(/\u0026/g,'[AMP;]');
	v = v.replace(/(\r\n\r\n)|(\r\r)|(\n\n)|(\f\f)/g,'<br>\r');
	v = v.replace(/(\r\n)|(\n)|(\f)/g,'\r');
	v = v.replace(/(\r)+/g,'<br>');
	v = v.replace(/(<br>){2,}/g,'<br><br>');
	v = v.replace(/(<br>)+$/,'');
	v = v.replace(/\*(.[^_]+)\*/g,'<span style="font-weight: bold">$1</span>');
	v = v.replace(/_(.[^_]+)_/g,'<span style="font-style: italic">$1</span>');
	v = v.replace(/\[(#)([0-9]+)\]/g,'<a href="$1no$2" title="Skip to comment number $2">$1$2</a>');
	v = v.replace(/(|http:\/\/)(|[w]{3}\.)(globeandmail\.c|theglobeandmail\.c|globeauto\.c|globeinvestor\.c|globefund\.c)(a|om)([\w/\.]+)/g,'<a href="http://$2$3$4$5">$3$4</a>');
	return v;
}

function charCountInit() {
	if($("charCount")) {
		$("charCount").style.display = "block";
		var txtLimit = d.createTextNode("2000");
		$("chars").appendChild(txtLimit);
	}	
}

function alertInit() {
	var alertLinks = getElementsByClassName($("comments"), "A", "flag-comment");
	if(alertLinks.length == 0) { 
		return;
	} else {
		for(var i=0; i<alertLinks.length; i++) {
			addEvent(alertLinks[i], "click", alertEditor);
		}
	}
	//keep the "other" text input hidden until a user clicks other reason
	addEvent($("alertReason-other"), "click", function() {
		Element.removeClassName($("otherReason"), "hide");
	});
	// and when something other than other is clicked make sure the text input is disabled
	var reasons = $A([$("alertReason-inflammatory"), $("alertReason-offensive"), $("alertReason-advertising")]);
	reasons.each(function(reason) {
		addEvent(reason, "click", function() {
			$("otherReason").value = "";
			Element.addClassName($("otherReason"), "hide");
		});
	});
}

function alertEditor(e) {
	e = (!e) ? window.event : e;
	commentid = this.id.split("-")[1];
	var pos = getElPos(this);
	var left = pos[0];
	var top = pos[1];
	showAlertForm(commentid, left, top);
	return false;
}

function showAlertForm(commentId, leftX, topY) {
	
	var alertForm = $("alert-form");
	var closeForm = $("alert-close");
	var hiddenField = $("commentid");
	
	hiddenField.value = commentId;
	alertForm.style.top = (topY + 15) + "px";
	alertForm.style.left = (leftX + 15) + "px";
	
	addEvent(closeForm, "click", function() {
		clearAlertFormAndReturnSelectedReason();
		alertForm.style.top = "-937em";
		alertForm.style.left = "-937em";
		return false;
	});
	
	addEvent($("alertForm"), "submit", validateAlertForm);
}

function validateAlertForm(e) {
	e = (!e) ? window.event : e;
	
	var arrRadio = new Array();
	var arrCkRadios = new Array();
	var objAlert = $("alert-form"); /* the div */
	var alertForm = $("alertForm"); /* the form */
	var inputs = $A(alertForm.getElementsByTagName("INPUT"));
	
	inputs.each(function(input) {
		input.type == "radio" ? arrRadio.push(input) : "";	
	}); 

	arrRadio.each(function(rad) {
		rad.checked == true ? arrCkRadios.push(rad) : "";
	});
	
	if(arrCkRadios.length != 1) {
		createError("Please select a reason for alerting us to this " + strAlert);
		return false;
	} else {
		if(arrCkRadios[0].id == "alertReason-other") {
			if($("otherReason").value == "") {
				createError("Please supply a reason for alerting us to this " + strAlert);
				return false;
			}
		}
		if($("errorMessage")) {
			$("errorMessage").parentNode.removeChild($("errorMessage"));
		}
		submitAlert();
		return false;
	}
}

function validateSortAndSlug(sortdate, slug) {
	var slugReg = new RegExp(/^[a-zA-Z0-9_-]+$/);
	var dateReg = new RegExp(/[0-9]{8}/);
	if (sortdate.match(dateReg) && slug.match(slugReg)) {
		return true;
	} else {
		return false;
	}
}

function submitAlert() {
	// commentid is defined in the alertEditor function
	var objAlert = $("alert-form"); /* containing div */
	var alertForm = $("alertForm");
	var url = alertForm.action;
	var reason = clearAlertFormAndReturnSelectedReason();
	var userid; 	
	//userid is either that of a a logged in user or "anonymous"
	$F("userid") == "" ? userid = "anonymous" : userid = $F("userid");		
	xmlhttp = hector();
	
	/* clean up */
	var reasonReg = new RegExp("<[^>]+>", "g");
	reason = reason.replace(reasonReg, "");
	
	var spammerString = "American National Origin".toUpperCase();
	
	if (validateSortAndSlug($F("sortdate"), $F("slug")) && (reason.toUpperCase().indexOf(spammerString) == -1)) {
		url += '?reason=' + encodeURI(reason);
		url += '\u0026commentid=' + commentid + '\u0026userid=' + encodeURI(userid);
		url += '\u0026sortdate=' +  encodeURI($F("sortdate")) + '\u0026slug=' +  encodeURI($F("slug"));
		url += '\u0026save=true';
		xmlhttp.open("POST", url, true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {
				if (xmlhttp.status == 200) {
					alertPosted(objAlert);
				}
			}
		}
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send('');			
	} else {
		alertPosted(objAlert);
	}
}

function alertPosted(obj) {
	obj.style.top = "-937em";
	obj.style.left = "-937em";
	var objSpan = $("commAlertHolder-" + $F("commentid"));
	objSpan.className = "alertSubmitted";
	Element.remove(objSpan.childNodes[0]); // get rid of the anchor
	var txt = document.createTextNode("An editor has been alerted to this " + strAlert);
	objSpan.appendChild(txt);
	//objSpan.childNodes[1].style.display = "none"; the !
	YFTinit(5,"commAlertHolder-" + $F("commentid"));
}

function clearAlertFormAndReturnSelectedReason() {
	var inputs = $A($("alertForm").getElementsByTagName("INPUT"));
	var sRadio;
	/* get rid of selected radio and input text if it's there */	
	inputs.each(function(input) {
		if((input.type == "radio") && (input.checked == true)) {
			if (input.id == "alertReason-other") {
				sRadio = $F("otherReason");
				// clear text field
				$("otherReason").clear();
			} else {
				sRadio = $F(input);
			}
			input.checked = false;
		}	
	});
	
	if ($("errorMessage")) {
		Element.remove($("errorMessage"));
	}
	return sRadio;
}
	
function createError(msg) {
	if($("errorMessage")) {
		$("errorMessage").firstChild.nodeValue = msg;
	} else {
		var objError = createElement("p", "errorMessage");
		pMsg = d.createTextNode(msg);
		objError.appendChild(pMsg);
		var objForm = $("alertForm");
		objForm.parentNode.insertBefore(objError, objForm);
	}
}

function userInfoInit() {
	var objUsers = getElementsByClassName($("comments"), "SPAN", "user-fname-lname");
	if(objUsers.length == 0) { return; }
	for(var i=0; i<objUsers.length; i++) {
		if((objUsers[i].nextSibling.nextSibling.nodeType == "1") && (objUsers[i].nextSibling.nextSibling.className == "user-detail")) {
			/* if user-details span exists -- user wants to show their details */
			objUsers[i].className += " show-details";
			addEvent(objUsers[i],"mouseover", showUserInfo);
			addEvent(objUsers[i],"mouseout", hideUserInfo);
		}
	}
}

function showUserInfo() {
	/* make sure the tooltip only appears once */
	if(this.hasChildNodes && this.childNodes.length > 1) {
		if(this.childNodes[1].nodeType == "1" && this.childNodes[1].className == "userInfoBox") {
			return;
		}
	}
	var pos = getElPos(this);
	var left = pos[0];
	var top = pos[1];
	var objHolder = createElement("span","","userInfoBox");
	var objDetails = this.nextSibling.nextSibling.firstChild.nodeValue; /* user-details span */
	var nObjDetails = [objDetails.split(";")[0], objDetails.split(";")[1], objDetails.split(";")[2]]; 
	for(var i=0; i<nObjDetails.length; i++) {
		objHolder.appendChild(d.createTextNode(nObjDetails[i]));
		if(i<(nObjDetails.length -1)) {
			objHolder.appendChild(d.createElement("br"));
		}
	}
	objHolder.style.top = (top + 20) + "px";
	objHolder.style.left = (left + 20) + "px";
	this.appendChild(objHolder);
	this.title = "";
}

function hideUserInfo() {
	this.removeChild(this.childNodes[1]);
}

function customLogin() {
	location.replace(location.href);
}

function commentInit() {
	if($("commentForm")) { 
		addEvent($("commentForm"), "submit", checkComments); 
		addEvent($("submitComment"), "focus", countChars);
		addEvent($("commentHole"), "keyup", countChars);
		if($("usernamePref")) {
			addEvent($("usernamePref"), "click", function() {
				return showHelp("showUsernameHelp",this,"switch","close-showUsernameHelp","","","",20);
			});
		}
	}
	if($("whyMyEmail") && $("showWhyEmail")) {
		addEvent($("whyMyEmail"), "click", function() {
			return showHelp("showWhyEmail",this,"switch","close-showWhyEmail","","",40,10);
		});
	}
	if($("showWhatAreTags") && $("whatAreTags")) {
		addEvent($("showWhatAreTags"), "click", function() {
			return showHelp("whatAreTags",this,"switch","close-whatAreTags","","","",20);
		});	
	}
	if(storyType == "ReviewStory") {
		if($("showStarsHelp") && $("starsHelp")) {
			addEvent($("showStarsHelp"), "click", function() {
				return showHelp("starsHelp",this,"switch","close-starsHelp","","","",20);
			});
		}		
	}
	
	// collect various help links for mod/alert & attach handlers 
	var helpLinks = ["how-report", "mod-explain"];
	var show;
	helpLinks.each(function(type) {
		var refs = $A(getElementsByClassName($("chewy"), "A", type));
		if (refs.length > 0) {
			refs.each(function(ref) {
				addEvent(ref, "click", function() {
					ref.className == "how-report" ? show = ["showHowToReport", "close-showHowToReport"] : show = ["showWhatIsModeration", "close-showWhatIsModeration"];
					return showHelp(show[0],this,"switch",show[1],"","","",20);
				});
			});
		}
	})
	
	if(storyType != "ReviewStory") {
		var bodyClassNames = Element.classNames(document.getElementsByTagName("BODY")[0]).toArray();
		//storyType == "CommentStory" ? modLevel = bodyClassNames[3] : modLevel = bodyClassNames[4];
		bodyClassNames.each(function(klass) {
			if (klass == "fully") {
				modLevel = "fully";
				return;
			} else if (klass == "semi") {
				modLevel = "semi";
				return;
			} else if (klass == "closed") {
				modLevel = "closed";
				return;
			} else {
				return;
			} 		
		});
	}
	
	/*
	if($("loginAccess")) { 
		addEvent($("loginAccess"),"click",chkER);
		addEvent($("loginAccess"),"click",createLoginFrame); 
	}
	function chkER(){
		if(getCookie("ERIGHTS")!=null){
			location.replace(location.href);
		} else {
			setTimeout(chkER,50);
		}
	}
	*/
	
	if ($("userCity")) {	
		getCookie("TGAM-city") ? $("userCity").value = unescape(getCookie("TGAM-city")) : $("userCity").value = "";
	}
	if (modLevel == "semi") { alertInit(); }
	//userInfoInit();
	
	// terms and conditions from comment form
	if ($("tac")) {
		addEvent($("tac"), "click", function() {
			_open_popup_window("500", "600", this.href);
			return false;
		})
	}
	
}

addEvent(window, "load", commentInit);
addEvent(window, "load", charCountInit);
