
var blogAjaxObj;
var blogVoteLink;

/**
	This function hijacks the event of clicking on the voting link and
	replaces it with an AJAX reqest
*/
function blogVote(event,elem)
{
	blogVoteLink	= elem;
	url				= elem.href;
	url				+= ((url.indexOf('?') > 0) ? '&':'?')+'ajax=1';
	
	blogInitAjax();
	blogAjaxObj.open('GET',url,true);
	blogAjaxObj.send(null);
	
	blogVoteLink.innerHTML	= '';
	$( '#blogFavoredCount' ).html( 'Contacting server...' );
	
	return false;	// cancel the event (clicking on the link)
}

function blogInitAjax()
{
	try {
		// Firefox, Opera 8.0+, Safari
		blogAjaxObj	= new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			blogAjaxObj	= new ActiveXObject('Msxml2.XMLHTTP');
		} catch (e) {
			try {
				blogAjaxObj	= new ActiveXObject('Microsoft.XMLHTTP');
			} catch (e) {
				alert('Your browser does not support AJAX!');
				return false;
			}
		}
	} // end playing catch
	blogAjaxObj.onreadystatechange	= blogOnStateChange
}

function blogOnStateChange()
{
	if( blogAjaxObj.readyState == 4 )
	{
		if( blogAjaxObj.responseText.match('Success') == null )
		{
			alert('Server returned: '+blogAjaxObj.responseText);
		} else {			
			$( '#blogFavoredCount' ).html( 'Preference recorded.' );
		}
	} // end if the request has been successfull
}

function blogAddSuggestedTag(tag)
{
	elem	= document.getElementById('article_tags');
	if( elem )
	{
		elem.value	+= ((elem.value.length > 0) ? ', ':'')+tag;
	} // if the element exists
}


function blogAutosave( autosaveDelayMs ) {
	var oFCKeditor = FCKeditorAPI.GetInstance( 'article_content' ) ;

	// Copy the contents of the article into the form if the FCK editor is being used.
	if( oFCKeditor ) {
		$('#article_content').attr("value", oFCKeditor.GetHTML() );
	}
	  
	$.ajax({
		url : "/blog/view/savedraft.php",
		type : "POST",
		data : $('#blog_composition_form' ).serialize(),
		dataType : "json",
		error : function (xhr, desc, exception) {
			blogAutosaveResponseError(xhr, desc, exception);
			
		},
		success : function (data) {
			blogAutosaveResponse( data, autosaveDelayMs );
		}
	});
}


function blogAutosaveResponseError( xhr, desc, exception) {
	blogAutosaveUpdateAnchor( xhr.responseText )

	setTimeout( blogAutosave, autosaveDelayMs, autosaveDelayMs );
}


function blogAutosaveResponse( data ) {
	alert( data.articleId );
	if( data ) {
		message = false;
		if( data.error ) {
			message = 'Save error:' + data.error;
		} 
		if( data.timestamp ) {
			message = 'Saved on:' + data.timestamp;
			$( '#article_id' ).attr( 'value', data.articleId );
		}
	} else {
		message = 'Save error: data is null!';
	}
	 
	if( message ) {
		blogAutosaveUpdateAnchor( message );
	}
		
	setTimeout( blogAutosave, autosaveDelayMs, autosaveDelayMs );
}


function createAutosaveAnchor() {
	if( $('#autosaveAnchor' ).length == 0 ) {
		$('#article_content').after( '<div id="autosaveAnchor"></div>' );
	}
	
	return $('#autosaveAnchor' );
}


function blogAutosaveUpdateAnchor( message ) {
	autosaveAnchor = createAutosaveAnchor();
	autosaveAnchor.text( message );
}


/**
 * Inserts a checkbox that allows users to be notified by email when comments
 * are added to a post. When clicked, triggerse clChangeCommentSubscription().
 */
function addSubscribeCheckbox( $subscribed ) {
	$subscribeAnchor = $( '#subscribeAnchor' );
	$subscribeAnchor.empty(); 

	
	$description = jQuery( '<label id="subscribe-description" name="subscribe-description"></label>' );
	
	
	$check = jQuery( '<input type="checkbox" id="subscribe" name="subscribe" />' );
	$check.bind( 'change', blogChangeCommentSubscription );
	
	if( $subscribed ) {
		$description.html( '&nbsp;Click to unsubscribe' );
		$check.attr( 'checked', 'checked' );
	} else {
		$description.html( '&nbsp;Click to subscribe' );
	}

	$check.prependTo( $description );	
	$description.prependTo( $subscribeAnchor );
}


/**
 *	Sends post to server to sub or unsub from email notifications.
 *
 *  this references the checkbox with name/id = 'subscribe'. 
 */
function blogChangeCommentSubscription() {
	$.ajax({
		url : "/blog/view/subscribe.php",
		type : "POST",
		data : 'article_id=' + $('input[name=article_id]' ).attr("value") + '&state=' + this.checked ,
		dataType : "json",
		error : function (xhr, desc, exception) {
			blogVoiceChangeCommentSubscriptionResponseError(xhr, desc, exception);
			
		},
		success : function (data) {
			blogVoiceChangeCommentSubscriptionResponse( data );
		}
	});

	
    new Ajax("/voice/js/functions/subscribe.php",{
        method:'post',
        data:'article_id=' + $('cl_post-comment-form').article_id.value + '&state=' + this.checked ,
        onComplete:clVoiceChangeCommentSubscriptionResponse,
        onFailure:function( response ){ }
    }).request();
    
}

/**
 * Handle a Change Comment Subscribe AJAX request.
 * 
 * Response will be either true or false. By recalling the original draw
 * function with the value of response, the checkbox and text are appropriately
 * updated. 
 */
function blogVoiceChangeCommentSubscriptionResponse( response ) {
	//alert( response.subscribed );
	addSubscribeCheckbox( response.subscribed );
}

/**
 * Handle a Change Comment Subscribe AJAX request.
 * 
 * Response will be either true or false. By recalling the original draw
 * function with the value of response, the checkbox and text are appropriately
 * updated. 
 */
function blogVoiceChangeCommentSubscriptionResponseError( xhr, desc, exception ) {
	alert( 'bad kind of error:' + xhr.responseText );
}


function blogHandleDeleteClick( event ) {
	if( !confirm( 'Click OK to delete this article and all associated comments.' ) ){
		return false;
	}
}
$(document).ready(function () {
/*	autosaveDelayMs = 60000; // 60 Seconds
	
	if( $('#blog_composition_form' ).length > 0 ) {
		setTimeout( blogAutosave, autosaveDelayMs, autosaveDelayMs );
	}
	
	if( $('#subscribeAnchor' ).length > 0 ) {
		addSubscribeCheckbox( 0 < ( $('#subscribeAnchor' ).text().length ));
	}
	*/
	if( $('#deleteArticleButton' ).length > 0 ) {
		$('#deleteArticleButton' ).bind( 'click', blogHandleDeleteClick );
	}

});
