// 		  File : if-ajax-comments.js
// Description : JavaScript library for 'iF AJAX Comments for Wordpress'
//     Version : 2.3
//Requirements : jQuery -> [http://jquery.com]
// 		Author : Peter 'Toxane' Michael
// 	Author URI : http://www.flowdrops.com

jQuery.noConflict();

var showForm, disableForm, showLivePreview, compatContentPress, activityImage, activeColor, inactiveColor;
var css_comment, css_commentform, css_commentlist, css_respond;
var textNoName, textNoEmail, textInvalidEmail, textNoComment, textAddingComment, textCommentAdded, textCommentPreview;

var iFACScripts =
{   
	init: function()
	{
		iFACScripts.getVars();
	},
    
    getVars: function()
	{
		var url = iFAC_plugin_path+'ajax/ajaxGetVars.php';
		jQuery.getJSON(url, {reqAction: "getAllSettings"}, iFACScripts.parseVars);
	},
		
	parseVars: function(data)
	{
		showForm = data.showForm;
		disableForm = data.disableForm;
		showLivePreview = data.showLivePreview;
		activityImage = data.activityImagePath;		
		activeColor = data.activeColor;
        inactiveColor = data.inactiveColor;
        css_comment = data.css_comment;
        css_commentform = data.css_commentform;
		css_commentlist = data.css_commentlist;
		css_respond = data.css_respond;
		textNoName = data.textNoName;
        textNoEmail = data.textNoEmail;
		textInvalidEmail = data.textInvalidEmail;
		textNoComment = data.textNoComment;
		textAddingComment = data.textAddingComment;
		textCommentAdded = data.textCommentAdded;
		textCommentPreview = data.textCommentPreview;
		compatContentPress = data.compatContentPress;
		if(showLivePreview == 'checked'){iFACScripts.livePreview();}
		iFACScripts.setColors();
		iFACScripts.bindForm();
	},
			
	livePreview: function()
	{
		if(jQuery("#live-preview").size()) return;
		
		jQuery('#'+css_comment).one('focus',function()
		{	// http://www.learningjquery.com/2006/11/really-simple-live-comment-preview
			jQuery('#'+css_comment).parent().after('<div id="preview-box"><div class="comment-by">'+textCommentPreview+'</div><div id="live-preview"></div></div>');
		});
		var $comment = '';
		jQuery('#'+css_comment).keyup(function()
		{
			$comment = jQuery('#'+css_comment).val();
			$comment = $comment.replace(/\n/g, "<br />").replace(/\n\n+/g, '<br /><br />');
			jQuery('#live-preview').html( $comment );
		});
	},
	
	setColors: function()
	{
		jQuery('#author').focus(function(){jQuery(this).css('background', '#'+activeColor);}).blur(function(){jQuery(this).css('background', '#'+inactiveColor);});
		jQuery('#email').focus(function(){jQuery(this).css('background', '#'+activeColor);}).blur(function(){jQuery(this).css('background', '#'+inactiveColor);});
		jQuery('#url').focus(function(){jQuery(this).css('background', '#'+activeColor);}).blur(function(){jQuery(this).css('background', '#'+inactiveColor);});
		jQuery('#comment').focus(function(){jQuery(this).css('background', '#'+activeColor);}).blur(function(){jQuery(this).css('background', '#'+inactiveColor);});
	},
	
	bindForm: function()
	{
		jQuery('#submit').one("click", function()
		{
			jQuery('#'+css_commentform).before('<div id="activity" class="msgActivity"></div>');
		});

		jQuery('#'+css_commentform).bind("submit", function()
		{
			try
			{
				var xError = '', xFocus = '';
				
				var formInputs= [];
				jQuery(':input', this).each(function()
				{
					if (this.type == 'checkbox')
					{
						if (this.checked)
						{
							this.value = this.value;
						}
						else
						{
							this.value = '';
						}
					}
					formInputs.push(this.name + '=' + encodeURIComponent(this.value));
				});

				
				if(this.author && this.author.value === '' && typeof document.getElementById('fb-user') == 'undefined')
                {
                    xError += '- '+textNoName+'<br />';
                    this.author.focus();
                }
				
				var noMail = false;
				if(this.email && this.email.value === '' && typeof document.getElementById('fb-user') == 'undefined')
                {
                    xError += '- '+textNoEmail+'<br />';
                    this.email.focus();
					noMail = true;
                }

				
				if(this.email && !(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(this.email.value)) && typeof document.getElementById('fb-user') == 'undefined')
                {
					if (! noMail)
					{
						xError += '- '+textInvalidEmail+'<br />';
						this.email.focus();
					}
                }
                
                if(this.comment.value === '' || this.comment.value == this.comment.title)
                {
                    xError += '- '+textNoComment;
                    this.comment.focus();
                }
                
                if(xError !== '')
                {
					jQuery('#'+css_commentform).before('<div id="msgError" class="msgError"></div>');
					jQuery('#msgError').html(xError).show().fadeOut(300).fadeIn().fadeOut(4000);
                    xError = '';
					return false;
                }
				else
				{
					iFACScripts.addActivity();
					jQuery.ajax(
					{
						type: "POST",
						data: formInputs.join('&'),
						url: this.getAttribute('action'),
						success: iFACScripts.parseSuccess,
						error: iFACScripts.ajaxError
					});
				}
				return false;
			}
			catch(e)
			{
				// Normal postback in case of an error
				return true;	
			}
		});
		jQuery('#submit').after('<input type="hidden" id="isComment" name="isComment" value="true" />');
	},
	
	ajaxError: function(XMLHttpRequest, textStatus, errorThrown)
	{
		// alert(XMLHttpRequest+', '+textStatus+', '+errorThrown);
		var errorMessage = 'textStatus: ';
		if (textStatus !== null){errorMessage += textStatus;}
		if (errorThrown !== null){errorMessage += ', errorThrown: ' + errorThrown;}
		iFACScripts.throwError(errorMessage);
	},
	
	parseSuccess: function(data)
	{

		tmpComment = new jQuery('<div>'+data+'</div>');
		
		if(jQuery(tmpComment).find('script').size() > 0)
		{
			// Something went wrong
			jQuery('#'+css_commentform).before('<div id="msgError" class="msgError"></div>').html(data);
			iFACScripts.removeActivity();
			return;
		}
		
		if(jQuery('.'+css_commentlist).length > 0)
		{
			// The commentlist exists i.e. this is not the first comment
			jQuery('.'+css_commentlist).append(jQuery(tmpComment).find('li'));
		}
		else
		{
			// The commentlist doesn't exist, this is the first comment
			
			// Do we need to support the 'Content Press' Theme?
			if(compatContentPress == 'checked')
			{
				jQuery('div.postbox').before(jQuery(tmpComment).find('div.boxcomments'));
			}
			else
			{
				jQuery('#'+css_respond).before(jQuery(tmpComment).find('.'+css_commentlist));
			}
		}
		if ( typeof commentOnFacebook == 'function') {
			commentOnFacebook();
		}
		
		iFACScripts.removeActivity();
		iFACScripts.clearInputs();
		
		if (window.AjaxEditComments)
		{
   			AjaxEditComments.init();
		}
	},
	
	addActivity: function()
	{
		if (disableForm == 'checked')
		{	
			jQuery('form *').attr("disabled","disabled");
		}
		else
		{
			jQuery('#'+css_commentform).fadeOut();
		}
		jQuery('#activity').text(textAddingComment).css('background', 'url('+activityImage+') no-repeat right');
	},
	
	removeActivity: function()
	{
		jQuery('#activity').text(textCommentAdded).css('background', '');
		
		if(showForm == 'checked')
		{
			jQuery('#'+css_commentform).fadeIn();
		}
		jQuery('form *').removeAttr("disabled")
	},
	
	clearInputs: function()
	{
		jQuery('#comment').val('');
		jQuery('#live-preview').html('');
	},
	
	throwError: function(message)
	{
		iFACScripts.removeActivity();
		jQuery('#activity').text(message).css('background', '');
		jQuery('#'+css_commentform).fadeIn();
	}
};
jQuery(document).ready(iFACScripts.init);
