function clVoiceFavoriteClickResponse( response ){
    var results;
    eval( response );
    if( results ){
        if( $('jsStatus') ){
            $('jsStatus').empty();
            $('jsStatus').innerHTML = results.html;
            if( !results.error ){
                switch( results.action ){
                    case 'delete':
                    if( $(results.target) ){
                        $(results.target).innerHTML = '<img height="10" alt="Favorite Icon" src="/theme/connectorlocal/i/icons/heart.gif"/> Favorite';
                    }
                    break;
                    case 'insert':
                    if( $(results.target) ){
                        $(results.target).innerHTML = '<img height="10" alt="Favorite Icon" src="/theme/connectorlocal/i/icons/heart.gif"/> unFavorite';
                    }
                    break;
                }
            }
        }
    }
}

function clVoiceFavoriteClick( event ){

    new Event( event ).stop();

    new Ajax("/voice/js/functions/favorite.php",{
        method:'post',
        data:'id=' + this.id ,
        onComplete:clVoiceFavoriteClickResponse,
        onFailure:function( response ){ }
    }).request();
}


function clVoiceDeleteClick( event ) {
	if( !confirm( 'Click OK to delete this article and all associated comments.' ) ){
		new Event( event ).stop();
	}
}

function clOptionalBoxClick( event ){

    new Event( event ).stop();

    if( this.parentNode.parentNode.className == 'optional-container' ){
        this.parentNode.parentNode.className = 'optional-container hidden';
        this.innerHTML = '+ Optional';
    }else {
        this.parentNode.parentNode.className = 'optional-container';
        this.innerHTML = '- Optional';
    }

}

/**
 * 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 = new Element( 'label', {
		'id' : 'subscribe-description',
		'name' : 'subscribe-description'
	});
	
	$check = new Element( 'input', {
		'type' : 'checkbox',
		'id' : 'subscribe',
		'name' : 'subscribe'
	});
	$check.addEvent( 'change', clChangeCommentSubscription );

	if( $subscribed ) {
		$description.setHTML( '&nbsp;Click to unsubscribe' );
		$check.set( { 'checked' : 'checked' } );		
	} else {
		$description.setHTML( '&nbsp;Click to subscribe' );
	} 
	
	$subscribeAnchor.adopt( [$check, $description] );
}


/**
 *	Sends post to server to sub or unsub from email notifications.
 *
 *  this references the checkbox with name/id = 'subscribe'. 
 */
function clChangeCommentSubscription() {
    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 clVoiceChangeCommentSubscriptionResponse( response ) {
	addSubscribeCheckbox( response );
}


/**
 * Setup any AJAX functionality required while editing articles.
 * 
 * - Autosave the article being edited.
  */
function clArticleEditing() {
	var oFCKeditor = FCKeditorAPI.GetInstance( 'cl_article_content' ) ;

	if( oFCKeditor ) {
		$( 'cl_article_content' ).value = oFCKeditor.GetHTML();
	} 

    new Ajax("/voice/js/functions/savedraft.php",{
        method:'post',
        data: $( 'write-article-form' ).toQueryString(),
        onComplete:clSaveDraftResponse,
        onFailure:function( response ){ }
    }).request();
}

/**
 * Handle article autosave response.
 *
 * Update the interface to indicate whether the article has been saved or not.
 */
var kSaveDraftDelay = 60000;
function clSaveDraftResponse( response ) {
	eval( response );
	
	if( results ) {
		if( results.timestamp ) {
			$('lastSave' ).setHTML( 'Last updated: ' + results.timestamp );	
			clArticleEditing.delay( kSaveDraftDelay );
			return;
		}
		if( results.errorNumber ) {
		
			// If the article is not yet valid, don't save.
			if( results.errorNumber == -1 ) {
				clArticleEditing.delay( kSaveDraftDelay );
				return;
			}
		}
	}
	
	$('lastSave' ).setHTML( 'Auto-saving has failed. Please save your draft manually.' );
}

window.addEvent( 'domready', function() {
	
    clShare = new ConnectorShare( 'share', 'voice' );

    var clVoiceFavoriteButtons = $$( 'a.favorite' );

    if( clVoiceFavoriteButtons ){
        for( var i = 0; i < clVoiceFavoriteButtons.length; i++ ){
            clVoiceFavoriteButtons[i].addEvent( 'click', clVoiceFavoriteClick );
        }
    }

    var clVoiceOptionalBoxes = $$( 'div.optional-container' );

    if( clVoiceOptionalBoxes ){
        for( var i = 0; i < clVoiceOptionalBoxes.length; i++ ){
            clVoiceOptionalBoxes[i].getElement('h4').getElement('a').addEvent( 'click', clOptionalBoxClick );
        }
    }

	
    if( $( 'cl_article_content' ) ){
        var oFCKeditor = new FCKeditor( 'cl_article_content' ) ;
        oFCKeditor.BasePath = "/lib/fckeditor/" ;
        oFCKeditor.Config["CustomConfigurationsPath"] = "/voice/lib/fck/fckconfig.js"  ;
        oFCKeditor.Config["StylesXmlPath"] = "/voice/lib/fck/fckstyles.xml"  ;
        oFCKeditor.ReplaceTextarea() ;
    }

	if( $( 'deleteArticleButton' ) ) {
		$( 'deleteArticleButton' ).addEvent( 'click', clVoiceDeleteClick);
	}
	
	if( $( 'subscribeAnchor' ) ) { 
		addSubscribeCheckbox( 0 < ( $( 'subscribeAnchor' ).getText().length ) );
	}

	if( $( 'write-article-form' ) ) {
		clArticleEditing.delay( kSaveDraftDelay );
	}

});
