/*
	COMMENTS
*/
var isFacebookLogin = false;
function submitComment(commentForm) {
	var fields = new Array();
	var action = "/library/comments/comment_submit.php"; //commentForm.attr("action");
	
	fields["author"] = $("#commentForm *[name='comment_data[author]']");
	fields["email"] = $("#commentForm *[name='comment_data[email]']");
	fields["comment"] = $("#commentForm *[name='comment_data[comment]']");
	fields["captcha_code"] = $("#commentForm *[name='comment_data[captcha_code]']");
	fields["story_id"] = $("#commentForm *[name=story_id]");
	fields['fb_connect'] =  $("#commentForm *[name=fb_connect]");
	fields["section"] = $("#commentForm *[name=section]");
	fields["channel"] = $("#commentForm *[name=channel]");
	
	if(fields["author"].val()=="") {
		var facebookUserName = $("#commentUser .facebookUserName a").text();
		if(facebookUserName != "")	
			$("#commentForm input[name='comment_data[author]']").val(facebookUserName);
	}
	
	var parameters = {
		"comment_data[author]": fields["author"].val(),
		"comment_data[email]": fields["email"].val(),
		"comment_data[comment]": fields["comment"].val(),
		"comment_data[captcha_code]": fields["captcha_code"].val(),
		story_id: fields["story_id"].val(),
                fb_connect: fields['fb_connect'].val(),
		section: fields["section"].val(),
		channel: fields["channel"].val(),
		js_enabled: "true"
	};
	if(formValidate(fields)) {
		$("#commentForm .submitBtn").attr("disabled","disabled"); //don't allow people to submit twice or the crazies to do it three times.
		$.post(action,parameters,
			function(data) {
				$("#commentForm .submitBtn").removeAttr("disabled");
				var commentid = postValidate(data, fields)
				if(commentid != false) {
					$("p.formError").remove();
					commentSuccess(parameters.story_id,commentid,fields["comment"].val());
				}
				return false;
			}
		);
	}
	return false;
}

function formError(message) {
	if($("p.formError").size()==0) {
		$("p#commentInstructions").after('<p class="formError"><span>'+message+'</span></p>');
		$("p.formError").slideDown(500);
	} else {
		$("p.formError span").fadeOut(500,function(){
			$("p.formError span").html(message);
			$("p.formError span").fadeIn(500)
		});
	}
}

function formValidate(fields) {
	var mistake = false;
	for ( var i in fields ) {
		if(fields[i].val()=="") {
			fields[i].addClass("formFail");
			mistake = true;
		} else {
			fields[i].removeClass("formFail");
		}
	}
	if(mistake) {
		formError('Please complete all fields before submitting.');
	}
		
	return !mistake;
}

function postValidate(data,fields) {
	var errors = eval('(' + data + ')');
	var errorMessage = "";
	if (errors.comment_id == undefined) { //comment_id is only true when there are no errors
		$.each(errors, function(field,error) {
			fields[field].addClass("formFail");
			errorMessage += error+"<br />";
		});
		formError(errorMessage.slice(0,errorMessage.length-6)); //remove last <br />
		return false;
	} else {
		createCookie("last_comment",errors.comment_id,365);
		return errors.comment_id;
	}
}

function commentSuccess(id,commentid,currentComment) {
	$(".formContainer p.formError").remove();
	$("#commentInstructions").hide();
	var container = $(".formContainer");
	container.css("height",container.height()+"px");
	container.html("<div class=\"formResult\"><p class=\"bold\">Thank you for your contribution to "+location.host+".</p><p>Your comment is highlighted below.</p></div>");
	container.animate({height: '7em'}, 1000);
	$("div.formResult").fadeIn(1500,function(){
		commentPageGoto(id,0,false,1);
	});
	
//	if(isFacebookLogin)
//		facebookCommentPost(currentComment);
}

//Ajax calls for switching comment pages.
function bindCommentPages() {
	commentHighlight();
	$("#comments ul.pages a").unbind().bind("click",function(){
		commentPage($(this));
		return false;
	});
}

//Code that runs after the comments switch pages
function commentPageFinish() {
	bindCommentPages();
	bindOverlay();
	refreshAd("#bigbox","bigbox");
	refreshAd("#skyscraper","skyscraper");
}

function commentPage(linkElement) {
	var linkOptions = (linkElement.attr("href")).replace(/(.*?)\?(.*)/i,"?$2");
	var isScroll = linkElement.parent().parents("ul.marginTop").size() == 1; //if clicked from bottom scroll to top
	var page = linkOptions.replace(/(.*?)comments_page=(\d+)(.*)/,"$2");
	var id = linkOptions.replace(/(.*?)id=(\d+)(.*)/,"$2");
	var lastCommentId = readCookie("last_comment"); //highlight their last comment
	commentPageGoto(id,page,isScroll);
}

function commentPageGoto(id,page,isScroll,refreshCache) {
	refreshCache = defaultValue(refreshCache,0);
	var replaceDiv = $("#commentListing");
	replaceDiv.css("height",replaceDiv.height()+"px");
	replaceDiv.html('<div class="ajaxLoader">Loading</div>');
	$.get("/library/comments.php?comments_page="+page+"&id="+id+"&nc="+refreshCache+ajaxNoCache(), function(data){
		replaceDiv.html(data).css("height","auto");
		commentHighlight();
		facebookNewWin();
		if(isScroll) {
			$('html,body').animate({scrollTop: replaceDiv.offset().top}, 1000, function(){
				commentPageFinish();
			});
		} else {
			commentPageFinish();
		}
	});	
}

function commentHighlight() { //highlights the last comment by the current user.
	var lastCommentId = readCookie("last_comment"); //highlight their last comment
	if(lastCommentId != null) {
		$("dl#comment_"+lastCommentId).addClass("active");
	} else {
		return false;
	}
}

function refreshCaptcha() {
	$("#captcha_code").val("");
	document.getElementById('captcha').src = '/library/comments/securimage/securimage_show.php?' + Math.random();
}

function facebookNewWin() {
	$("a.FB_Link").attr("target","_blank");
}

function facebookRefreshXFBML(id) {
	FB_RequireFeatures(["XFBML"], function() { 
			FB.XFBML.Host.parseDomElement(document.getElementById(id));	
			setTimeout("facebookNewWin()",2500);
		}
	);
}

function facebookCommentLogin() {
	var fbml =	"<input type='hidden' name='comment_data[email]' value='facebook@facebook.com' />" +
				"<input type='hidden' name='comment_data[author]' value='fb_uid:" + FB.Facebook.apiClient.get_session().uid + "' />" +
				"<div class='facebookUser clearIt'>" +
				"<span class='facebookProfilePic'><fb:profile-pic uid='loggedinuser' size='square' facebook-logo='true'></fb:profile-pic></span>" +
				"<strong class='facebookUserName'>Welcome, <fb:name uid='loggedinuser' useyou='false' firstnameonly='false'></fb:name></strong><br />" +
				"You are signed in with your Facebook account." +
				"</div>";
	$("#commentUser").html(fbml);
	
	facebookRefreshXFBML("commentUser");
	
	isFacebookLogin = true;
}

function facebookCommentPost(currentComment) {
	currentComment = (currentComment + '').replace(/([^>]?)\n/g, '$1<br />\n');
	FB.Connect.showFeedDialog(
		127935962328,
		{
			"site_name":facebookConnectComment.site_name,
			"link":facebookConnectComment.link,
			"headline":facebookConnectComment.headline,
			"comment":currentComment
		},
		null,
		null
	);
}
