/* HealthAdvisor Comment Control */

// Global Variables
var charCounterScript = null;
var commentControlScript = null;

jQuery(document).ready(function(){
	// Comment/Login Form Dropdowns
	jQuery('#signin').live('click', function(){
		jQuery("#signupForm").slideUp("slow", function(){ if (jQuery("#signupForm").css('display') == 'none') jQuery("#signinForm").slideToggle("slow"); });
	});	
	jQuery('#signup').live('click', function(){
		jQuery("#signinForm").slideUp("slow", function(){
			if (jQuery("#signinForm").css('display') == 'none') jQuery("#signupForm").slideToggle("slow");
		});
	});
	
	// Add A Comment
	jQuery('#addComment').live('click', function(){
		if (charCounterScript == null)
			jQuery.getScript(scripts + 'jquery.charcounter.js', function(){
				charCounterScript = true;
				// Count Characters for Comments
				jQuery("#commentBox").charCounter(255, {container: "#commentCount" });
			});

		jQuery("#commentForm").slideToggle("slow", function(){
			if (jQuery("#commentForm").css('display') == "none")
			{
				jQuery("#addComment").text('ADD A COMMENT');
				jQuery("#commentBox").val('')
				jQuery("#commentCount").text('(255 characters remaining)');
			}
			else
			{
				jQuery("#addComment").text('CANCEL COMMENT');
				jQuery("#commentBox").trigger('focus');
			}
		});
	});	
	
	// Subscribe to Thread
	jQuery('#subscribe').live('click', function(){ jQuery.post(ajax + 'healthAdvisor.php', { 'subscribe':id }, function(data){ if(data == 1) { jQuery("#subscribe").attr('id', 'unsubscribe').text("UNSUBSCRIBE"); alert('You are now subscribed to this discussion thread!'); } }); });
	jQuery('#unsubscribe').live('click', function(){ jQuery.post(ajax + 'healthAdvisor.php', { 'unsubscribe':id }, function(data){ if(data == 1) { jQuery("#unsubscribe").attr('id', 'subscribe').text("SUBSCRIBE TO THREAD"); alert('You are no longer subscribed to this discussion thread.'); } }); });
	
	// Report Abuse
	jQuery(".commentAbuse").live('click', function(){
		var element = jQuery(this);
		jQuery.post(ajax + 'healthAdvisor.php', { 'abuse': type, 'id': jQuery(this).attr('alt') }, function(data){
			jQuery(element).remove();
			alert('Thank you for reporting inappropriate content!');
		});
	});
	
	// Remove Comment
	jQuery(".commentRemove").live('click', function(){
		var element = jQuery(this);
		jQuery.post(ajax + 'healthAdvisor.php', { 'remove': type, 'id': jQuery(this).attr('alt') }, function(data){
			jQuery(element).parent().parent().remove();
			alert('Comment has been removed.');
		});
	});
	
	// Login
	jQuery("#RexallLogin").live('click', function(){ login(); });
	jQuery("#frmLogin #email, #frmLogin #displayName").live('keydown', function(event){
		if (event.keyCode == 13)
			login();
	});


	// Submit Comment
	jQuery("#submitComment").live('click', function(){
		if (jQuery("#commentBox").val() == '')
			alert("You can't submit an empty comment");
		else
			jQuery.post(ajax + 'healthAdvisor.php', { 'addComment': jQuery("#commentBox").val(), 'type':type, 'id':localid },function(data){
				if (data == 1 || data == 'swear')
				{
					jQuery("#addComment").trigger("click");
					setTimeout(function(){
						jQuery("#count span, #contentOptions span").text(Number(jQuery("#count span").text()) + 1);
						commentCount = Number(commentCount) + 1;
						loadComments();
					}, 400);
					
					if (data == 'swear')
						alert('Thanks! Your post has been sent for moderation and may appear shortly!');
				}
				else
					alert("Unable to submit your comment at this time");
			});
	});

	
	// Newsletter Signup
	jQuery("#signupNL").live('click', function(){ jQuery("#newsletterContainer").slideToggle('slow'); });

	jQuery("#signupStoreOtherVal").live('focus', function(){ if (jQuery(this).val() == 'Other') jQuery(this).val(''); }).live('blur', function(){	if (jQuery(this).val() == '') jQuery(this).val('Other'); });

	jQuery("#frmSignup input[type='checkbox']").live('click', function(){ if (jQuery(this).attr('checked') == true) jQuery(this).attr('alt', '1'); else jQuery(this).removeAttr('alt'); });
	
	jQuery("#frmSignup .submit").live('click', function(){ if (jQuery("#signupPrivacy").attr('checked') == true) registration(); else alert('Please confirm that you have read and agree to the Privacy Policy.'); });
	jQuery("#frmSignup input").live('keydown', function(event){
		if (event.keyCode == 13)
			if (jQuery("#signupPrivacy").attr('checked') == true) registration(); else alert('Please confirm that you have read and agree to the Privacy Policy.');
	});
});
// Register User
function registration(){
	jQuery.post(ajax + 'healthAdvisor.php', {
			'registration':jQuery("#signupDisplay").val(),
			'email':jQuery("#signupEmail").val(),
			'newsletter':jQuery("#signupNL").attr('checked'),
			'firstname':jQuery("#signupFirstname").val(),
			'lastname':jQuery("#signupLastname").val(),
			'city':jQuery("#signupCity").val(),
			'province':jQuery("#signupProvince").val(),
			'postal':jQuery("#signupPostal").val(),
			'age':jQuery("#signupAge").val(),
			'storeRexall':jQuery("#signupStoreRexall").attr('alt'),
			'storeRexallPharmaPlus':jQuery("#signupStoreRexallPharmaPlus").attr('alt'),
			'storeIDA':jQuery("#signupStoreIDA").attr('alt'),
			'storeGuardian':jQuery("#signupStoreGuardian").attr('alt'),
			'storeMedicine':jQuery("#signupStoreMedicine").attr('alt'),
			'storeOther':jQuery("#signupStoreOther").attr('alt'),
			'storeOtherAnswer':jQuery("#signupStoreOtherVal").val().replace('Other', ''),
			'women':jQuery("#signupInfoWomen").attr('alt'),
			'men':jQuery("#signupInfoMen").attr('alt'),
			'seniors':jQuery("#signupInfoSeniors").attr('alt'),
			'kids':jQuery("#signupInfoKids").attr('alt'),
			'teens':jQuery("#signupInfoTeens").attr('alt'),
			'cosmetics':jQuery("#signupInfoCosmetics").attr('alt')
		}, function(data){
			data = data.replace(/\|\|\|/g, '\n');
			if (data == 1)
				jQuery.post(ajax + 'users.php', { 'login':'login', 'email':jQuery("#signupEmail").val(), 'displayname':jQuery("#signupDisplay").val() }, function(data){ jQuery("#signupForm").slideUp("slow", function(){ commentControlScript = null; loadCommentControl(); setTimeout(function(){ jQuery("#addComment").trigger('click'); }, 150); }); });	
			else
				alert(data);
		});
}
function login()
{
	if (jQuery("#frmLogin #email").val() == '' || jQuery("#frmLogin #displayName").val() == '')
		alert('One or more of the login fields was left blank. Please try again');
	else
	// Log the User In:
		// Verify User Data
		// If accurate, Reload comment control
		// Otherwise, Respond with an error
		jQuery.post(ajax + 'users.php', { 'login':'login', 'email':jQuery("#frmLogin #email").val(), 'displayname':jQuery("#frmLogin #displayName").val() }, function(data){
			if (data == 1)
				jQuery("#signinForm").slideUp("slow", function(){ commentControlScript = null; loadCommentControl(); });
			else
				alert("Sorry, that email and display name do not correspond with a user in our system.");
		});
}

function loadCommentControl(initialize) {
	if (commentControlScript == null)
		jQuery("#commentControl").load(ajax + 'commentControl.php?print=' + optPrint + '&share=' + optShare + '&type=' + type + '&id=' + id, function(){
			commentControlScript = true;
			loadControl(initialize);
		});
	else
		loadControl(initialize);
}

function loadControl (initialize){
	// Load Comments
	if (commentCount > 0)
		if (initialize == 'initialize')
			initializePagination(1);
		else
			loadComments();
	else
		jQuery("#commentList").html('');
		jQuery("#pagination").html('');
	
	jQuery("#count span").text(commentCount + ' ');
		
	if (jQuery("#comments").attr('alt') == 'locked')
	{
		jQuery("#signinForm, #signupForm, #addComment, #signin, #signup, #commentForm").remove();
		jQuery("<div id='locked'><img src='" + images + "iconLock.gif' /> THIS DISCUSSION IS LOCKED</div>").insertAfter("#count");
	}
}

function loadComments(pagination)
{
	if (Number(pagination) > 0)
		currentPage = Number(pagination);
	else
		currentPage = 1;

	// Call Results via JSON
	jQuery.ajax({
		type: "POST",
		url: ajax + "healthAdvisor.php",
		data: "comments=" + type + "&id=" + id + "&page=" + currentPage,
		processData: true,
		dataType: "json",
		success: function(data){
			commentsJson(data, ajax + "healthAdvisor.php", "POST", images + "loading.gif");
		}
	});
}

function commentsJson(data, url, method, busy)
{
	var html = new String();
	var currentPage = new String();
	var numPages = Math.floor(commentCount / 5) + Math.ceil(Math.floor(commentCount % 5) / 5);
	var current = data.crr
	var record = 5;
	var j = 0;
	if (commentCount > 0)
		jQuery.each(data.items, function(i, item){
			html += '<tr ' + (item.displayname.toLowerCase() == 'irene' ? 'class="irene"' : '') + '><td class="commentDetails" valign="top"><div class="commentName">' + item.displayname + '</div><div class="commentDate">' + item.date + '</div><div class="' + (displayname == 'irene' ? 'commentRemove' : 'commentAbuse') + ' rolloverContainer" alt="' + item.id + '"><img src="' + images + 'iconAbuse.gif">' + (displayname == 'irene' ? 'Remove Comment' : 'Report Abuse') + '</img></div></td><td class="commentBody" valign="top">' + item.comment + '</td></tr>';
			j++;
		});
	
	jQuery("#commentList").html('<table id="tbComments" cellspacing="0">' + html + '</table>');		
	
	if (j > 0)
		initializePagination(current);
}

// Initialize Pagination 
function initializePagination(page)
{
	if (typeof commentCount != 'undefined')
	{
		jQuery("#pagination").html('<div id="pagi-wrapper">'+Pagination(5, Math.floor(commentCount / 5) + Math.ceil(Math.floor(commentCount % 5) / 5), page)+'</div>');
		jQuery(".pagi li a").click(function(){ loadComments(jQuery(this).attr("name").substr(4)); });
	}
}