
//AJAX http://docs.jquery.com/Ajax/jQuery.ajax#options
//Version: 0.1


jQuery.noConflict();

var commentform,
url_location = location.href,
flag_processing=false,
activity_image = 'http://www.thefat.tv/wp-content/plugins/celebrity-captcha/images_activity/activity1.gif',
preload_images = new Array();
//alert(activity_image);
preload_images.push(activity_image);

/*
jQuery.preloadImages = function(){
 for(var i = 0; i<arguments.length; i++) jQuery("<img>").attr("src", arguments[i]);
};
*/


jQuery('document').ready(function($){
	commentform=$('form[action$=wp-comments-post.php]');
	$('#submit').after('<span id="antispam000-info"></span>');
	$('#antispam000-info').after('<div id="debug"></div>');
	
	commentform.submit(function() {
		if(!flag_processing){
			flag_processing=true;
		 	antispam_post(this);
			Cc.show_activity();
			}
	   return false; 
		});
		
	//preload_images
	for(var i = 0; i<arguments.length; i++) jQuery("<img>").attr("src", arguments[i]);	
});

var Cc = {
	ajax_error: function(XMLHttpRequest, textStatus, errorThrown){
		_dbg('ajax_error textStatus: '+textStatus+' errorThrown: '+errorThrown);
		flag_processing=false; //enable posing
			
		var errorMessage = '';		
		if(textStatus != 'timeout'){
			var http_code=XMLHttpRequest.status;
			var html = XMLHttpRequest.responseText;
			switch(true){
/*
				case http_code==500:
					errorMessage = antispam_get_error500(html);
					break;
				case http_code==403:
					errorMessage='Stop!! You are posting comments too quickly.';
					break;
				case textStatus=='timeout':
					errorMessage='Server timeout error. Try again.';
					break;
*/
				case textStatus=='parsererror' ||  textStatus=='notmodified' || textStatus=='error' :
					errorMessage=XMLHttpRequest.responseText;
					break;
				default:
					errorMessage='Не получилось, ты все сломал!';
				}
			}else{
			errorMessage='Сервер не отвечает. Вышел покурить наверное...';
			}
		Cc.throw_error(errorMessage);
		},
	ajax_success: function(data,textStatus){
		_dbg('ajax_success: '+textStatus);
		flag_processing=false; //enable posing
		
		if ( // validate server response
			typeof(data.comment_type) == 'undefined' ||
			typeof(data.comment_ID) == 'undefined' ||
			typeof(data.comments_template) == 'undefined' ||
			!data.comments_template
			) { // if response is not as expected...
				errorMessage = data;
				Cc.throw_error(errorMessage);
				this.error({responseText:''}, '', ''); // display unknown error
				return; // abort
				}

			var wrapper = jQuery(commentform).parents('div#ajax_comments_wrapper'),
				commentlist = jQuery('.commentlist', wrapper),
				new_wrapper = jQuery(data.comments_template),
				new_comment = jQuery('#comment-'+ data.comment_ID +', .commentlist *:last', new_wrapper).eq(0).hide();

			if (data.comment_type == 'conventional' && commentlist.length > 0) {
				commentlist.append(new_comment); // append new comment to existing wrapper
				jQuery('#comments', wrapper).after(jQuery('#comments', new_wrapper)).remove(); // replace comment count element
				} else { // flexible
				var new_comment_form = jQuery('textarea[name=comment]', new_wrapper).parents('form');
				if (new_comment_form.length) {
					new_comment_form.after(commentform).remove(); // replace comment form in new wrapper
					} else {
					new_wrapper.append(commentform); // append comment form to new wrapper
					}
				wrapper.after(new_wrapper).remove(); // replace old wrapper with new
				}
			new_comment.fadeIn('slow'); // show new comment using nice effect

			// WP Ajax Edit Comments compatibility
			if (typeof(AjaxEditComments) != 'undefined') {
				AjaxEditComments.init();
				}
			Cc.comment_success();
			jQuery('textarea#comment', commentform).val(''); // clear comment
			jQuery('input#antispam000_input', commentform).val(''); // clear comment
		},
	
	comment_success: function(){
		Cc.write_message('Ура, коммент добавлен!','antispam000-success');
		},
	throw_error: function(message){
		Cc.write_message(message , 'antispam000-error',1000);
		},
	show_activity: function(){
		Cc.write_message('Сохраняю, момент...','antispam000-loading',1000);
		//Cc.write_message(,'antispam000-loading',1000);
		},
	write_message: function(s,class,fade){
		if(typeof fade == 'undefined') fade=1000;
		jQuery('#antispam000-info').html('').append('<span class='+class+'>'+s+'</span>');
		jQuery('#antispam000-info').find('span').css('display','none').html(s).fadeIn();
		}
	
};

function antispam_post(form){
//alert(form.innerHTML); //return false;
//serialize and store form data in a variable
var formdata=jQuery(form).serialize();
//alert(formdata); return false;

//Extract action URL from commentform
var formurl=jQuery(form).attr('action');

_dbg('url: '+formurl+'<br />formdata: '+formdata);

var obj = jQuery.ajax({
	timeout: 5000,
	url: 'http://www.thefat.tv/wp-content/plugins/celebrity-captcha/ajax-comments-post.php',
	data: formdata,
	dataType: 'json',
	cache: false,
	type: 'post',	
	complete: function(){flag_processing=false;},
	error:Cc.ajax_error,
	success:Cc.ajax_success
	});
}

function antispam_get_error500(s){
var 
err='Почему-то не получилось =(',
arr=new Array(),
pat= /<p>(.+?)<\/p>/i;

arr = s.match(pat);
if(typeof arr != 'undefined') err=arr[1];
return err;
}

function _dbg(s){
return '';
var dd,ds,
o=document.getElementById('debug');

dd = new Date();
ds = dd.getMinutes()+':'+dd.getSeconds()+'.'+dd.getMilliseconds();
ds = '<font color=silver>'+ds+'</font> ';
o.innerHTML+=ds+s+'<br /><br />';
}
