jQuery(document).ready( function() {
	jQuery("a.form-control").livequery('click',
		function() {
			
			// Get current ativity ID.
			var aid = cpt_bp_get_element_id(this);
			
			// Get container ID for current activity comment form.
			var container = '#wire-post-new-'+aid;
			
			jQuery(container).toggle("normal");
			jQuery(container+" textarea").val('');
			jQuery(container+" textarea").focus();
			
			jQuery(container+' div#message').removeClass();
			jQuery(container+' div#message').html('');
			
			return false;
		}
	);

	jQuery("form.wire-post-new-form").submit(
		function() {

			// Get current ativity ID.
			var aid = cpt_bp_get_element_id(this);

			jQuery('#ajax-loader-activity-comment-'+aid).toggle();

			jQuery.post( ajaxurl, {
					'action': 'bp_cpt_activity_comments_post',
					'activity-id': aid,
					'wire-post-textarea': jQuery('#wire-post-new-'+aid+' textarea#wire-post-textarea-'+aid).val(),
					'_wpnonce': jQuery("input#_wpnonce_activity_comments_"+aid).val(),
					'cookie': encodeURIComponent(document.cookie)
				},
				function(response) {
					response = response.split('[[SPLIT]]');

					var aid = response[0];
					jQuery('#ajax-loader-activity-comment-'+aid).toggle();
					
					jQuery('div#wire-post-new-'+aid+' div#message').addClass(response[1]);
					jQuery('div#wire-post-new-'+aid+' div#message').html(response[2]);
					
					var newli = response[3].replace(/^\s+|\s+$/g, '');
					if (newli.length>0){
						jQuery('ul#wire-post-list-'+aid).append(response[3]).children(':last').hide().fadeIn(2000);
						// Close comment box
						jQuery('#wire-post-new-'+aid).hide("normal");
					}
				}
			);
			return false;
		}
	);
	
	jQuery("a.cpt-activity-comments-delete").livequery('click',
		function() {
		
			// Get current comment ID.
			var cid = cpt_bp_get_element_id(this);
			
			var nonce = jQuery(this).attr('href');
			nonce = nonce.split('?_wpnonce=');
			nonce = nonce[1].split('&');
			nonce = nonce[0];
			
			jQuery.post( ajaxurl, {
				'action': 'bp_cpt_activity_comments_delete',
				'comment-id': cid,
				'_wpnonce': nonce,
				'cookie': encodeURIComponent(document.cookie)
				},
				function(response) {
					if ( !response ) {
						jQuery('li#cpt-activity-comment-'+cid).hide("normal");
					}
					else {
						jQuery('li#cpt-activity-comment-'+cid+' div#message').html(response).show();
					}
				}
			);
			return false;
		}
	);
});


// Get activity id from ID of an element.
function cpt_bp_get_element_id(element) {
	var id = jQuery(element).attr('id');
	id = id.split('-');
	id = id[id.length-1];
	return id;
}