// If the recaptcha key isn't already set, set it now:
if (typeof RECAPTCHA_KEY == "undefined") {
	var RECAPTCHA_KEY="6Lfg_QgAAAAAAP0z1gv1rt4a5BUbmIkHBWUgWpJJ";
}

// Set how many comments to display by default
var COMMENTS_DEFAULT_LIMIT=15;

// Set these to "" if they are not wanted
// Message to display before comment submission
if (typeof COMMENTS_MESSAGE_BEFORE_SUBMISSION == "undefined") {
	var COMMENTS_MESSAGE_BEFORE_SUBMISSION="Comments are moderated and will display after approval, typically within 2 hours. By leaving a comment you are agreeing to our <a href='' target='_new'>Terms</a>.";
}
// Message to display after comment submission
if (typeof COMMENTS_MESSAGE_AFTER_SUBMISSION == "undefined") {
	var COMMENTS_MESSAGE_AFTER_SUBMISSION="Thank you! Your comment will display once approved by the site admin.";
}

// Keep track of whether or not the view all button is clicked.
var viewAllClicked = false;

// Set to true to require users to be logged in to comment, false to allow anyone to comment.
var mustBeLoggedInToComment=false; 

// Set to true to use ReCaptcha if it's available on the site. Set to false if ReCaptcha is available on the site but you don't want it on comments.
var useRecaptchaForCommentsIfAvailable=true;

// Set to true if you want ReCaptcha to generate a new challenge after every successful comment submission. Set to false if you want to let the user keep using the same, already successful, challenge and avoid the hassle.
var resetRecaptchaOnCommentSuccess=true;

/**
 * Once a comment has been successfully added, clear out the data entry for it and display the comments (either the most recent four or all of them, depending on whether view all has been clicked).
 * 
 * @see submitNewComment (called by)
 * @see getComments (calls)
 * @see getAllComments (calls)
 *
 * @author Original: Matthew Ausonio
 * @author Modified/Commented: Nick Davison
 */
function addNewComment() {
	// If recaptcha is desired
	if (useRecaptchaForCommentsIfAvailable) {
		// And if it has been included on the site
		if (typeof Recaptcha != "undefined") {
			// And the setting tells us to reset ReCaptcha
			if (resetRecaptchaOnCommentSuccess) {
				// Clear the response field
				$(".recaptcha_response_field").val("");
				// Load a new captcha
				Recaptcha.reload();
			}
		}
	}
	
	// Clear the comments
	$("#comment").val("");
	
	// Close the comment submission form
	$(".commentFormHidden").hide();
	
	// Redisplay comments for the page
	if(viewAllClicked == true)
		getAllComments();
	else
		getComments(jCore.itemId, 1, 15);
}

/**
 * Process the submit comment form and then make the AJAX request to submit it. Upon success, call addNewComment to update the output and updateRating (as it likely shows the number of comments). Always returns false to stop default form submission.
 *
 * @returns {boolean}
 * param {object} form The form we want to submit. Almost always #commentFormSignup.
 *
 * @see initComments (called by - within the generated HTML form)
 * @see addNewComment (calls)
 * @see updateRating (calls)
 *
 * @author Original: Matthew Ausonio
 * @author Modified/Commented: Nick Davison
 */

function submitNewComment(form) {
	// Assuming the comment wasn't blank
	if($("#comment").val() != "") {
		// Get the url from the form's action
		var submitURL = $(form).attr("action");
		// Get the comment itself and URL encode it
		var commentString = $("#comment").val();
		var commentStringEncoded = escape(commentString);
		
		// Build up the basic list of data fields
		var dataFields="id="+jCore.itemId+"&comment="+commentStringEncoded;
		
		// Tack on the userid if users have to be logged in, or the username they enter if they don't.
		if (mustBeLoggedInToComment) {
			dataFields=dataFields+"&userid="+jCore.itemStats.userId;
		} else {
			// Get the username from the field.
			var username=$('#commentUsername').val();
			var useremail=$('#commentUserEmail').val();
			// Catch blank usernames and exit.
			if (typeof username == "undefined") username="";
			if (username=="") return false;
			if (typeof useremail == "undefined") useremail="";
			if (useremail=="") return false;
			
			dataFields=dataFields+"&username="+escape(username+"|"+useremail);
		}
		
		// If we're using ReCaptcha
		if (useRecaptchaForCommentsIfAvailable) {
			// Grab the recaptcha fields
			var rcf=$('#recaptcha_challenge_field').val();
			var rrf=$('#recaptcha_response_field').val();
			// Bail if they didn't enter a recaptcha response
			if (rrf=="") return false; 
			// Tack the data on to the end of the request.
			dataFields=dataFields+"&recaptcha_challenge_field="+rcf;
			dataFields=dataFields+"&recaptcha_response_field="+rrf;
		}
		
		$.ajax({
			type: "POST", 
			url: submitURL, 
			data: dataFields,
			dataType:"json",
			cache:false,
			success: function(commentResponse){
				//CAPTCHA ERRORS
				if (typeof commentResponse.recaptchaVerified != "undefined") {
					if (commentResponse.recaptchaVerified == false) {
						alert("Please check your ReCaptcha entry and try again.");
						return false;
					}
				}
				
				// If the comment was successfully processed.
				if(commentResponse.processed == true) {
					// Update the comments list
					addNewComment();
					
					if (COMMENTS_MESSAGE_AFTER_SUBMISSION!="") {
						$('.commentsMessageAfterSubmission').html(COMMENTS_MESSAGE_AFTER_SUBMISSION).show();
					}
					
					// If the updateRating function is available, call it too.
					if (typeof updateRating != "undefined") {
						updateRating();
					}
				} else {
					alert("We are sorry, there was a problem writing to the database. Please try again later.");
				}
			}
		});
	}
	return false;
}

/**
 * Displays the comments that come back from the AJAX call to /Handlers/Comments.aspx in getComments.
 * <p>
 * Go through all of the comments, generating the HTML.
 * Write the html to ul.commentContainer.
 * If there are less than five comments in the system, hide the view more link, otherwise show it.
 * </p>
 *
 * @returns {void}
 * param {object} requestedCommentsObj The requested comments object, as passed back from the AJAX JSON call.
 *
 * @see getComments (called by after AJAX response)
 *
 * @author Original: Matthew Ausonio
 * @author Modified/Commented: Nick Davison
 */
function outputComments(requestedCommentsObj) {
	// Store the HTML we're building
	var commentsSource = new Array;
	
	// If the #comments element has the commentBubbleLarge class, set styles up appropriately.
	if($("#comments").hasClass("commentBubbleLarge")){
		inner = "commentItemInnerLarge";
		outer =  "commentItemOuterLarge";
	}else{
		inner = "commentItemInner";
		outer =  "commentItemOuter";
	}
	
	// Move through all of the comments
	for(i=0;i<requestedCommentsObj.comments.length;i++) {
		// Store an "odd"/"even" class name for striping
		if (i%2 == 0)
			striper = "even"
		else
			striper = "odd"

		// Write the HTML for the comment
        commentsSource.push('<li class="' + striper + '">\n');
		commentsSource.push('   <div class="' + outer + '">\n');
		commentsSource.push('      <div class="' + inner + '">');
		commentsSource.push('         <p>' + requestedCommentsObj.comments[i].comment + '</p>\n');
		commentsSource.push('         <div class="commentContent">\n');
		commentsSource.push('            <span class="commentDate">' + requestedCommentsObj.comments[i].date + '</span><span style="color:#ccc;font-size:15px;margin:0 10px;">&bull;</span>');
		commentsSource.push('            <a href="'+$('#addCommentLink').attr('rel')+encodeURI(requestedCommentsObj.comments[i].username)+'" class="commentUser">' + requestedCommentsObj.comments[i].username + '</a>\n');
		commentsSource.push('         </div>\n');
		commentsSource.push('      </div>\n');
		commentsSource.push('   </div>\n');
		commentsSource.push('</li>');
	}
	
	/*	Sample source:
		<li>
			<div class="commentItemOuter">
				<div class="commentItemInner">
					<p>Donec congue suscipit sem, id imperdiet ligula dapibus non. Pellentesque congue justo id eros volutpat ut sodales mauris lacinia. Ut pretium, metus sed hendrerit tempus, quam lectus fringilla dolor, vel congue diam orci vitae arcu. Sed eget velit volutpat felis laoreet mollis. Vivamus ac tellus ligula, a vestibulum risus.</p>
					<span class="commentDate">April 16 2009</span><a href="" class="commentUser">Usernamehere</a>
				</div>
			</div>
		</li>
	*/
	
	// Bind all the content together and write it to the ul.commentContainer 
	$("ul.commentContainer").html(commentsSource.join(""));
	
	// If the backend is registering that the item has comments (it should be)
	if(jCore.itemStats.comments) {
		// If the backend reports less comments than the limit
		if (parseInt(jCore.itemStats.comments, 10) < COMMENTS_DEFAULT_LIMIT) {
			// Hide the show all button as there aren't any more to show
			$("#commentsViewAllButton").hide();
		} else {
			// If the backend was reporting more comments than the limit
			// BUT we're also showing more than the limit
			if (requestedCommentsObj.comments.length>COMMENTS_DEFAULT_LIMIT) {
				// We know show all comments must be active
				// And therefore should hide it.
				$("#commentsViewAllButton").hide();
			} else {
				// We're not showing all of them, therefore we need the show all button shown
				$("#commentsViewAllButton").show();
			}
		}
	} else {
		// Something went wrong. Hide the show all comments button to reduce confusion
		$("#commentsViewAllButton").hide();
	}
	
	//--------------------------------------------
	// SWIM NETWORK SPECIFIC CODE
	//--------------------------------------------
	// IE 7 and below fix
	// For some stupid reason, IE 7 loses the height of the #comments area when it's dynamically populated.
	// Hiding and then redisplaying the page forces IE to recalculate.
	var appString=navigator.appVersion.toString();
	if (appString.indexOf('MSIE')!=-1) {
		var appVer=parseInt(appString.substring(appString.indexOf("MSIE")+5), 10);
		if (appVer<8) {
			$('#body2').hide();
			$('#body2').show();
		}
	}
}


/**
 * Makes an AJAX request to /Handlers/Comments.aspx to get the JSON comments back. When successful, it calls outputComments to display them.
 *
 * @returns {void}
 * @param {string} id Required. The jCore.itemId for the page/element we want the related comments for.
 * @param {number} from Required. The number of the first comment. 1 indexed, not zero indexed so 1 is the first comment.
 * @param {number} count Optional. The maximum number of comments to return. If "" or undefined, it'll return all comments.
 *
 * @see initComments (called by)
 * @see getAllComments (called by)
 * @see addNewComment (called by)
 * @see outputComments (calls)
 *
 * @author Original: Matthew Ausonio
 * @author Modified/Commented: Nick Davison
 */
function getComments(id, from, count) {
	// Make sure the count is set to "" if undefined.
	if ((typeof count == "undefined") || (count == null)) { count=""; }
	
	// Set the jCore.itemId to the requested id - that way, if there's an external change happening, jCore still knows what we're pointing to.
	jCore.itemId = id;
	
	var submitURL="/Handlers/Comments.aspx";
	// Allow dummy data to be forced for testing
	if (document.location.toString().toLowerCase().indexOf("usedummyjson")!=-1) {
		submitURL="/Html/Handlers/LongComments.html";
	}
	
	// Make the AJAX request
	$.ajax({type: "GET", url: submitURL, data:"id="+id+"&from="+from+"&count="+count,dataType:"json",cache:false,
		success: function(requestedComments){
			// If firebug's console is available, log jCore and the requested comments out to it.
			if (typeof console != "undefined") {
				if (typeof console.log != "undefined") {
					console.log("Comments successfully received.");
					console.log(jCore);
					console.log(requestedComments);
				}
			}
			// Display the comments.
			outputComments(requestedComments);
		}
	});
}

/**
 * Convenience function for getComments - gets all comments.
 *
 * @returns {void}
 *
 * @see initComments (called by when clicking View All)
 * @see addNewComment (called by)
 * @see getComments (calls)
 *
 * @author Original: Matthew Ausonio
 * @author Modified/Commented: Nick Davison
 */

function getAllComments() {
	getComments(jCore.itemId, 1, "");
}

/**
 * Create the commenting form.
 * 
 * @returns {void}
 *
 * @see initComments (called by)
 *
 * @author Nick Davison
 */
function createAddCommentsForm() {
	output=[];
	
	output.push('<form action="/Handlers/Comment.aspx" method="post" id="commentFormInput" onsubmit="return submitNewComment(this);">');
	
	// Display the before submission message
	if (COMMENTS_MESSAGE_BEFORE_SUBMISSION!="") {
		output.push('   <div class="commentsMessageBeforeSubmission">'+COMMENTS_MESSAGE_BEFORE_SUBMISSION+'</div>');
	}
	
	// If users aren't required to be logged in, add the username field.
	if (!mustBeLoggedInToComment) {
		output.push('   <p>');
		output.push('   	<label for="commentUsername" id="commentUsernameLabel">Your Name</label>');
		output.push('   	<input type="text" class="text" name="commentUsername" id="commentUsername" />');
		output.push('   </p>');
		output.push('   <p>');
		output.push('   	<label for="commentUserEmail" id="commentUserEmailLabel">Your Email (will not be displayed)</label>');
		output.push('   	<input type="text" class="text" name="commentUserEmail" id="commentUserEmail" />');
		output.push('   </p>');
		output.push('   <label for="commentRECAPTCHA" id="commentRECAPTCHALabel">Enter the captcha</label>');
	}
	
	// If recaptcha is desired
	if (useRecaptchaForCommentsIfAvailable) {
		// And if it has been included on the site
		if (typeof Recaptcha != "undefined") {
			// Generate the HTML for the recaptcha
			output.push('   <div id="recaptcha_container">');
			output.push('   	<div class="captchaContainer">');
			output.push('   		<div id="recaptcha_image"></div>');
			output.push('   	</div>');
			output.push('   </div>');
			// output.push('   	<div class="captchaResponseContainer">');
			// output.push('   		<label for="recaptcha_response_field">Please type the words in the box above.</label>');
			// output.push('   		<input type="text" id="recaptcha_response_field" name="recaptcha_response_field" class="text" />');
			// output.push('   	</div>');
		}
	}
	
	output.push('   	<label for="commentTextarea" id="commentTextareaLabel">Add your comment (limit 500 words)</label>');
	output.push('   	<textarea name="comment" id="comment"></textarea>');
	output.push('   <div class="clear"></div>');

	output.push('   <button type="submit" class="submit">Submit</button>');
	output.push('   <button type="reset" class="clearButton">Clear</button>');
	output.push('   <div class="clear"></div>');
	output.push('</form>');
	
	$("#commentFormSignup").html(output.join('\n'));
	
	// If recaptcha is desired and present
	if (useRecaptchaForCommentsIfAvailable) {
		if (typeof Recaptcha != "undefined") {
			Recaptcha.create(RECAPTCHA_KEY,
			"recaptcha_container", {
			   callback: Recaptcha.focus_response_field
			});

		}
	}
}

/**
 * Initialize the commenting system.
 * <p>
 * Only call the AJAX comments if there is a #comments element on the page.
 * Hide the signup form (also used to add comments) until it's needed.
 * Bind the add comments link and the show all comments link.
 * If the user's logged in (or login isn't required), rewrite the signup form to add comments instead.
 * </p>
 *
 * @returns {void}
 *
 * @see Page Initialization (called by)
 * @see getComments (calls)
 * @see getAllComments (calls)
 * @see jCore.readCookie (calls)
 * @see createAddCommentsForm (calls)
 *
 * @author Original: Matthew Ausonio
 * @author Modified/Commented: Nick Davison
 */
function initComments() {
	// Only bother hitting the server IF there is an element with the id "comments" on the page
	if(document.getElementById("comments")) {
		// If so, get the first four comments for the current jCore.itemId
		getComments(jCore.itemId,1,COMMENTS_DEFAULT_LIMIT);
	}
	
	// Hide the comment form signup
	$("#commentFormSignup").hide();
	
	// Bind the add comment link
	$("#addCommentLink").click(function() {
		// Hide any prior update messages								
		$('.commentsMessageAfterSubmission').hide();
		
		// Show/hide the signup area
		$("#commentFormSignup").toggle();
		return false;
	});
	
	// Bind the view all comments link
	$("#commentsViewAllButton").click(function() {
		// Hide any prior update messages								
		$('.commentsMessageAfterSubmission').hide();
											   
		viewAllClicked = true;
		getAllComments();
		return false;
	});
	
	// This will check if there is a username.
	// If there is, we assume they are logged in and show the comment form
	// Also let them comment if mustBeLoggedInToComment is false.
	$("#commentFormSignup").each(function() {
		if( (!mustBeLoggedInToComment) || (jCore.readCookie("userName")) ) {
			createAddCommentsForm();
		}
	});
}

