 jQuery.extend(jQuery.fn, {
	validate: function () {
		if (jQuery(this).val().length < 3) {jQuery(this).addClass('error');return false} else {jQuery(this).removeClass('error');return true}
	},
	validateEmail: function () {
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/,
		    emailToValidate = jQuery(this).val();
		if (!emailReg.test( emailToValidate ) || emailToValidate == "") {
			jQuery(this).addClass('error');return false
		} else {
			jQuery(this).removeClass('error');return true
		}
	},
});
 
jQuery(function($){

	$( '#commentform' ).submit(function(){
		var button = $('#submit'),
		    respond = $('#respond'), 
		    commentlist = $('.comment-list'), 
		    cancelreplylink = $('#cancel-comment-reply-link');
		if( $( '#author' ).length )
			$( '#author' ).validate();
		if( $( '#email' ).length )
			$( '#email' ).validateEmail();
		$( '#comment' ).validate();
		if ( !button.hasClass( 'loadingform' ) && !$( '#author' ).hasClass( 'error' ) && !$( '#email' ).hasClass( 'error' ) && !$( '#comment' ).hasClass( 'error' ) ){
			$.ajax({
				type : 'POST',
				url : qaleb_ajax_comment_params.ajaxurl, 
				data: $(this).serialize() + '&action=ajaxcomments', 
				beforeSend: function(xhr){
					button.addClass('loadingform').val('در حال ارسال...');
				},
				error: function (request, status, error) {
					if( status == 500 ){
						alert( 'Error while adding comment' );
					} else if( status == 'timeout' ){
						alert('Error: Server doesn\'t respond.');
					} else {
						var wpErrorHtml = request.responseText.split("<p>"),
							wpErrorStr = wpErrorHtml[1].split("</p>");
						alert( wpErrorStr[0] );
					}
				},
				success: function ( addedCommentHTML ) {
					// if this post already has comments
					if( commentlist.length > 0 ){
						// if in reply to another comment
						if( respond.parent().hasClass( 'comment' ) ){
							// if the other replies exist
							if( respond.parent().children( '.children' ).length ){	
								respond.parent().children( '.children' ).append( addedCommentHTML );
							} else {
								// if no replies, add <ol class="children">
								addedCommentHTML = '<ol class="children">' + addedCommentHTML + '</ol>';
								respond.parent().append( addedCommentHTML );
							}
							// close respond form
							cancelreplylink.trigger("click");
						} else {
							// simple comment
							commentlist.append( addedCommentHTML );
						}
					}else{
						// if no comments yet
						addedCommentHTML = '<ol class="comment-list">' + addedCommentHTML + '</ol>';
						respond.before( $(addedCommentHTML) );
					}
					// clear textarea field
					$('#comment').val('');
				},
				complete: function(){
					// what to do after a comment has been added
					button.removeClass( 'loadingform' ).val( 'ارسال دیدگاه' );
				}
			});
		}
		return false;
	});
});