/*
// Necessary variables defined elsewhere. Noted here for reference
var captchaImgAttempts
var allowAnonComments
var jsonURL
var captchaSrc
var alertCommentCannotBeBlank
var alertAuthorCannotBeBlank
var alertEmailCannotBeBlank
var alertEmailIsInvalid
var alertUnauthorizedAction
var entryPermalink
var commentFooterLinks
var commentHeader
var commentReplyXID
var commentReplyAuthor
var commentReplyComplete
*/

atpComments = {
    is_loaded: true,

    isAuthenticated: function() {
        return getCookie( 'VID' ) ? true : false;
    },

    previewOnly: function(commentFormNum, e) {
        // e = 1 - comment-confirmation
        // e = 2 - only show comment form

        var cForm = document.forms[commentFormNum];

        // If we're just showing form.. do only that
        if(e == 2) {
            // Hide preview comment, show form
            YAHOO.util.Dom.addClass('comment-preview', 'hiddenBox');
            YAHOO.util.Dom.addClass('header-preview-comment', 'hiddenBox');
            YAHOO.util.Dom.addClass('comment-preview-confirmation', 'hiddenBox');
            // if reply..
            if(commentReplyXID) {
                YAHOO.util.Dom.removeClass('primary-comment-form', 'hiddenBox');
                YAHOO.util.Dom.removeClass('comment-preview-confirmation', 'lessBoxMargin');
            } else
                YAHOO.util.Dom.removeClass('primary-comment-form', 'hiddenBox');
            if(commentHeader)
                document.getElementById('comment-title').innerHTML = commentHeader;
                
            if( cForm.email && this.checkForDefaultValue(cForm.email) && cForm.email.getAttribute('at:default') ){
                cForm.email.value = cForm.email.getAttribute('at:default');
                YAHOO.util.Dom.addClass(cForm.email, 'grayText');
            }
            if( cForm.url && this.checkForDefaultValue(cForm.url) && cForm.url.getAttribute('at:default') ){
                cForm.url.value = cForm.url.getAttribute('at:default');
                YAHOO.util.Dom.addClass(cForm.url, 'grayText');                
            }

            return false;
        }

        this.clearErrors();

        if(! this.validateInput(commentFormNum)) 
            return false;

        atpComments.disableButtons();
        YAHOO.util.Dom.removeClass('commentEntryFormSpinner', 'hiddenBox');
        YAHOO.util.Dom.removeClass('previewFormSpinner', 'hiddenBox');

        // JSON RPC Magic
        var jsonClient = new TC.JSONRPCClient( jsonURL );
        if( this.isAuthenticated() ) {
            var jsonParamValues = { 
                text: cForm.text.value }        
        } else {
            var jsonParamValues = {
                author: cForm.author.value,
                email: cForm.email ? cForm.email.value : '',
                url: cForm.url ? cForm.url.value : '',
                text: cForm.text.value }
        }
        
        jsonParamValues['entry_xid'] = xid; 

        if(commentReplyXID) 
            jsonParamValues['reply_xid'] = commentReplyXID;

        jsonClient.request( {
            method: 'Comments.Preview',
            params: jsonParamValues,
            callback: function( r ) {
                
                if( r.error ){
                    if( r.error == "URL is invalid"){
                        alert( r.error );
                    }else if( r.error == "ArcheType::Error::API::Feedback::Empty" ){
                        alert(alertCommentCannotBeBlank);
                    }else
                        atpComments.showErrorMessages(r.error);
                }else{
                    atpComments.populateCommentPreview(r);
                    YAHOO.util.Dom.removeClass('comment-preview', 'hiddenBox');
                    YAHOO.util.Dom.removeClass('header-preview-comment', 'hiddenBox');

                    if(e == 1) {
                        YAHOO.util.Dom.removeClass('comment-preview-confirmation', 'hiddenBox');
                    }

                    if(commentReplyXID) {
                        document.getElementById('comment-preview-replyto').innerHTML = " in reply to <a href=\"#\">"+commentReplyAuthor+"</a>";
                        YAHOO.util.Dom.addClass('comment-preview-confirmation', 'lessBoxMargin');
                        YAHOO.util.Dom.addClass('primary-comment-form', 'hiddenBox');
                    } else {
                        //document.getElementById('comment-preview-replyto').innerHTML = "";
                        YAHOO.util.Dom.addClass('primary-comment-form', 'hiddenBox');
                    }                    
                }

                atpComments.enableButtons();
                YAHOO.util.Dom.addClass('commentEntryFormSpinner', 'hiddenBox');
                YAHOO.util.Dom.addClass('previewFormSpinner', 'hiddenBox');

                if(commentReplyXID)
                    window.location.hash = "comment-" + commentReplyXID;
            }
        } );
        
        if(e == 1) 
            return false;
        else
            return true;
    },
    interceptPost: function(commentFormNum) {

        var cForm = document.forms[commentFormNum];
        this.clearErrors();

        // validation..
        if(! this.validateInput(commentFormNum)) {
            return false;
        }

        var now = new Date();
        now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
        if( cForm.author && cForm.author.value != '' && cForm.author.value != cForm.author.getAttribute('at:default') )
        	setCookie('typepadauthor', cForm.author.value, now);
        if( cForm.email && cForm.email.value != '' && cForm.email.value != cForm.email.getAttribute('at:default') )
        	setCookie('typepademail', cForm.email.value, now);
        if( cForm.url && cForm.url.value != '' && cForm.url.value != cForm.url.getAttribute('at:default') )
        	setCookie('typepadurl', cForm.url.value, now);        
        
        atpComments.disableButtons();
        YAHOO.util.Dom.removeClass('commentEntryFormSpinner', 'hiddenBox');
        YAHOO.util.Dom.removeClass('previewFormSpinner', 'hiddenBox');
       
        // JSON Magic
        var jsonClient = new TC.JSONRPCClient( jsonURL );
        if( this.isAuthenticated() ) {
            var jsonParamValues = { 
                text: cForm.text.value } 
                
            // Are we pushing this comment out to the tweeterbookafeederverse?
            if( cForm.publicize ) {
                
                var pubAccs = this.publicizeComment(cForm.publicize);

                // This is now either an empty array or the list of accounts to update
                jsonParamValues['publicize'] = pubAccs;
            }       

        } else {
            var jsonParamValues = {
                author: cForm.author.value,
                email: cForm.email ? cForm.email.value : '',
                url: cForm.url ? cForm.url.value : '',
                text: cForm.text.value }
        }

        jsonParamValues['entry_xid'] = xid; 
        
        if(commentReplyXID) 
            jsonParamValues['reply_xid'] = commentReplyXID;
        jsonParamValues['token'] = tp_comment_token;
        
        jsonClient.request( {
            method: 'Comments.Create',
            params: jsonParamValues,
            callback: function( r ) {
                
                // in case we're coming from previewing a comment
                YAHOO.util.Dom.addClass('comment-preview-confirmation', 'hiddenBox'); 
                if ( r.error ) {
                    if( r.error == "ArcheType::Error::CaptchaRequired" || r.error == "ArcheType::Error::API::Feedback::Suspected" ) {
                        atpComments.generateCaptcha(commentFormNum, 0);
                    }else if( r.error == "TypeCore::Error::Unauthorized" ) {
                        alert(alertUnauthorizedAction);
                    }else if( r.error == "Name and email address are both required!" ){
                        alert(alertAuthorAndEmailCannotBeBlank);
                    }else if( r.error == "ArcheType::Error::API::Feedback::Empty" ){
                        alert(alertCommentCannotBeBlank);
                    }else{
                        YAHOO.util.Dom.removeClass('primary-comment-form', 'hiddenBox');
                        YAHOO.util.Dom.addClass('commentEntryFormSpinner', 'hiddenBox');
                        alert(r.error);
                    }
                    YAHOO.util.Dom.addClass('commentEntryFormSpinner', 'hiddenBox');
                    atpComments.enableButtons();
                } else { 
                    atpComments.enableButtons();
                    YAHOO.util.Dom.addClass('commentEntryFormSpinner', 'hiddenBox');
                    YAHOO.util.Dom.addClass('previewFormSpinner', 'hiddenBox');
                    atpComments.commentComplete(r);
                }
            }
        } );


        return false;
    },
    submitWithCaptcha: function(commentFormNum) {
        cForm = document.forms[commentFormNum];
        document.getElementById('captcha-continue').disabled = true;
        YAHOO.util.Dom.removeClass('captchaFormSpinner', 'hiddenBox');

        var jsonClient = new TC.JSONRPCClient( jsonURL );

        if( this.isAuthenticated() ) {
            var jsonParamValues = { 
                text: cForm.text.value,
                captcha_code: document.getElementById('comment-captcha-text').value,
                captcha_chal: document.getElementById('comment-captcha-chal').value }                   

            // Are we pushing this comment out to the tweeterbookafeederverse?
            if( cForm.publicize ) {
                
                var pubAccs = this.publicizeComment(cForm.publicize);

                // This is now either an empty array or the list of accounts to update
                jsonParamValues['publicize'] = pubAccs;
            }

        } else {
            var jsonParamValues = { 
                author: cForm.author.value,
                email: cForm.email ? cForm.email.value : '',
                url: cForm.url ? cForm.url.value : '',
                text: cForm.text.value,
                captcha_code: document.getElementById('comment-captcha-text').value,
                captcha_chal: document.getElementById('comment-captcha-chal').value }
        }

        jsonParamValues['entry_xid'] = xid; 
        jsonParamValues['no_editor'] = '1';

        if(commentReplyXID) 
            jsonParamValues['reply_xid'] = commentReplyXID;
        jsonParamValues['token'] = tp_comment_token;

        jsonClient.request( {
            method: 'Comments.Create',
            params: jsonParamValues,
            callback: function( r ) {

                YAHOO.util.Dom.addClass('captchaFormSpinner', 'hiddenBox');
                document.getElementById('captcha-continue').disabled = false;

                if ( r.error ) {
                    if(r.error == "ArcheType::Error::CaptchaFailed") {
                        atpComments.generateCaptcha(commentFormNum, 1);
                    } else if(r.error == "ArcheType::Error::CaptchaRequired") {
                        atpComments.generateCaptcha(commentFormNum, 1);
                    } else {
                        /* alert(r.error); */
                        atpComments.showErrorMessages(r.error);
                    }
                } else {
                    atpComments.commentComplete(r);
                }
            }
        } );
    },
    generateCaptcha: function(commentFormNum, failedAttempt) {
        captchaImgAttempts++;
        if(captchaImgAttempts > 1)
            YAHOO.util.Dom.removeClass('captchaFailMsg', 'hiddenBox');

        YAHOO.util.Dom.addClass('comment-captcha', 'redBox');
        YAHOO.util.Dom.removeClass('comment-captcha', 'yellowBox');
        document.getElementById('comment-captcha-text').value = "";

        var jsonParamValues = { entry_xid: xid };

        var jsonCaptcha = new TC.JSONRPCClient( jsonURL );
        var data = jsonCaptcha.request( {
            method: 'Comments.CreateCaptcha',
            params: jsonParamValues,
            callback: function(r) {
                if(atpComments.previewOnly(commentFormNum,3)) {

                    YAHOO.util.Dom.removeClass('comment-captcha', 'hiddenBox');
                    //YAHOO.util.Dom.removeClass('comment-preview', 'hiddenBox');
                    //YAHOO.util.Dom.removeClass('header-preview-comment', 'hiddenBox');
                    YAHOO.util.Dom.addClass('primary-comment-form', 'hiddenBox');
                }
                //window.location = window.location.hash = "#comment-captcha";

                newCaptchaSrc = captchaSrc + r.result.code_encrypted;
                document.getElementById('captchaImg').src = newCaptchaSrc;
                document.getElementById('comment-captcha-chal').value = r.result.challenge;

            }
        } );
        
        if(captchaImgAttempts > 2) {
            YAHOO.util.Dom.addClass('comment-captcha-viewalt', 'hiddenBox');
        }       
    },
    validateInput: function(commentFormNum) {
        var cForm = document.forms[commentFormNum];
        var cAuthor = cForm.author; 
        var cEmail = cForm.email;
        var cUrl = cForm.url;
        var cText = cForm.text;
        var validEmailForm = /^[\w\+.'-]+@[\w-]+\.[\w.-]+$/;
        // validate comment text
        if(cText.value == "" || cText.value.match(/^\s*$/i)) {
            alert(alertCommentCannotBeBlank);
            return false;
        }   

        // if logged in with typekey then front end author / email  validation isn't necessary
        if( this.isAuthenticated() )
            return true;    

        // validate author
        if(this.checkForDefaultValue(cAuthor)) {
            alert(alertAuthorCannotBeBlank);
            YAHOO.util.Dom.addClass('comment-author', 'errorBG');
            YAHOO.util.Dom.removeClass('comment-author-error', 'hiddenBox');
            return false;
        }

        // validate email
        if(this.checkForDefaultValue(cEmail) && ! allowAnonComments) {
            YAHOO.util.Dom.addClass('comment-email', 'errorBG');
            alert(alertEmailCannotBeBlank);
            YAHOO.util.Dom.removeClass('comment-email-error', 'hiddenBox');     
            return false;
        } else if(this.checkForDefaultValue(cEmail) && allowAnonComments) {
            if ( cEmail ) {
                // set to blank
                cEmail.value = "";
            }
        } else if(cEmail && ((cEmail.value && ! cEmail.value.match(validEmailForm)) || (! allowAnonComments && cEmail.value == ""))) {
            YAHOO.util.Dom.addClass('comment-email', 'errorBG');
            alert(alertEmailIsInvalid); 
            YAHOO.util.Dom.removeClass('comment-email-error', 'hiddenBox');         
            return false;
        }

        // validate URL
        if(this.checkForDefaultValue(cUrl)) {
            // set to blank
            cUrl.value = "";
        }

        return true;        
    },
    clearErrors: function() {
        YAHOO.util.Dom.removeClass('comment-author', 'errorBG');
        YAHOO.util.Dom.removeClass('comment-email', 'errorBG');
        YAHOO.util.Dom.removeClass('comment-url', 'errorBG');

        YAHOO.util.Dom.addClass('comment-author-error', 'hiddenBox');
        YAHOO.util.Dom.addClass('comment-email-error', 'hiddenBox');
        YAHOO.util.Dom.addClass('comment-url-error', 'hiddenBox');      

        YAHOO.util.Dom.addClass('comment-error', 'hiddenBox');

    },
    commentComplete: function(r) {
        var commentCompleteDiv = YAHOO.util.Dom.get('comment-complete');
        YAHOO.util.Dom.removeClass('comment-preview', 'hiddenBox');
        YAHOO.util.Dom.removeClass(commentCompleteDiv, 'hiddenBox');
        YAHOO.util.Dom.addClass('header-verify-comment', 'hiddenBox');
        YAHOO.util.Dom.addClass('header-preview-comment', 'hiddenBox');
        YAHOO.util.Dom.addClass('primary-comment-form', 'hiddenBox');
        YAHOO.util.Dom.addClass('comment-captcha', 'hiddenBox');

        document.getElementById('comment-complete').href = xidToCommentPermalink(entryPermalink, r.result.comment_xid);
        var postAnotherLink = YAHOO.util.Dom.getChildrenBy( commentCompleteDiv, function( el ){ if( el.tagName == "A" ) return 1; } );
        postAnotherLink[ 0 ].href = "?cid="+r.result.comment_xid+"#comment-form";

        atpComments.populateCommentPreview(r);

        document.getElementById('comment-text').value = "";
        document.getElementById('comment-captcha-text').value = "";

        atpComments.populateCommentPreview(r);   


    },
    populateCommentPreview: function(r) {
        var previewAuthor = "";
        var cPreviewText = document.getElementById('comment-preview-content');
        
        // Set Avatar
        if( useAvatars && r.result.userpic ){
            var p = cPreviewText.parentNode;
            
            if( !YAHOO.util.Dom.get( 'comment-preview-avatar' ) ){
                makeAvatar = document.createElement('DIV');
                makeAvatar.className = 'comment-avatar';
                makeAvatar.id = 'comment-preview-avatar';
                YAHOO.util.Dom.insertBefore( makeAvatar, cPreviewText );
            }
            
            var avatar = YAHOO.util.Dom.get( 'comment-preview-avatar' );
            avatar.innerHTML = "<img width='50' height='50' alt='"+r.result.author+"' src='"+r.result.userpic+"' />";
            
        }

        // Set Comment Text
        cPreviewText.innerHTML = "<p>"+r.result.text+"</p>";

            if(r.result.url) {
                previewAuthor = '<a href="' + r.result.url + '">' + r.result.author + '</a>';
            } else {
                previewAuthor = r.result.author;
            }
        document.getElementById('comment-preview-author').innerHTML = previewAuthor;
        if(r.result.post_date) {
            document.getElementById('comment-preview-datetime').innerHTML = '<a href="' + xidToCommentPermalink(entryPermalink, r.result.comment_xid) + '">' + r.result.post_date + '</a>';
        }       
    },
    postAnotherComment: function() {
       document.getElementById('comment-text').value = "";

        YAHOO.util.Dom.addClass('comment-complete', 'hiddenBox');
        YAHOO.util.Dom.removeClass('primary-comment-form', 'hiddenBox');        
    },
    checkForDefaultValue: function(o) {
        if ( !o ) {
            return false;
        }
        if((o.value ==  o.getAttribute('at:default')) || (o.value.match(/^\s*$/i))) {
            return true;
        }   
        return false;       
    },
    maxTextArea: function(limit_field, limit_num) {
        if( limit_field.value.length > limit_num )
            limit_field.value = limit_field.value.substring( 0, limit_num );
    },
    toggleButtons: function() {
        if( commenterName ){
            if(document.getElementById('comment-text').value.length >= 1)
                atpComments.enableButtons();
            else
                atpComments.disableButtons();
        }else{
            if( emailRequired ){
                if( document.getElementById('comment-text').value.length >= 1 && document.getElementById('comment-author').value != document.getElementById('comment-author').getAttribute('at:default') && document.getElementById('comment-author').value.length >= 1 && document.getElementById('comment-email').value != document.getElementById('comment-email').getAttribute('at:default') && document.getElementById('comment-email').value.length >= 1 )
                    atpComments.enableButtons();
                else
                    atpComments.disableButtons();                
            }else{
                if( document.getElementById('comment-text').value.length >= 1 && document.getElementById('comment-author').value != document.getElementById('comment-author').getAttribute('at:default') && document.getElementById('comment-author').value.length >= 1 )
                    atpComments.enableButtons();
                else
                    atpComments.disableButtons();                
            }
        }
    },
    enableButtons: function() {
        if( document.getElementById('comment-preview-button') )
            document.getElementById('comment-preview-button').disabled = false;
        if( document.getElementById('comment-post-button') )
            document.getElementById('comment-post-button').disabled = false;        
    },
    disableButtons: function() {
        if( document.getElementById('comment-preview-button') )
            document.getElementById('comment-preview-button').disabled = true;
        if( document.getElementById('comment-post-button') )
            document.getElementById('comment-post-button').disabled = true;        
    },
    showErrorMessages: function(errorMsg) {
        var splitErrorMsg = errorMsg.split("::");
        var lastIndex = splitErrorMsg.length;
        document.getElementById('comment-error-msg').innerHTML = splitErrorMsg[lastIndex-2] + " " + splitErrorMsg[lastIndex-1];        
        YAHOO.util.Dom.removeClass('comment-error', 'hiddenBox');
        YAHOO.util.Dom.addClass('comment-captcha', 'hiddenBox');
        if(commentReplyXID)
            YAHOO.util.Dom.removeClass('primary-comment-form', 'hiddenBox');
        else
            YAHOO.util.Dom.removeClass('primary-comment-form', 'hiddenBox');
        
        YAHOO.util.Dom.removeClass('primary-comment-form', 'hiddenBox');
    },
    moveForm: function(e, replyAuthor) {

        if(commentReplyXID)
            atpComments.moveFormBack(commentReplyXID);
        else {
            YAHOO.util.Dom.removeClass('primary-comment-form', 'hiddenBox');
            atpComments.resetCommentForm();
        }
        
        YAHOO.util.Dom.insertAfter(document.getElementById('atp-comments'), document.getElementById('comment-'+e));
        YAHOO.util.Dom.removeClass(document.getElementById('comment-'+e+'-cancelreply'), 'hiddenBox');   
        
        commentHeader = msgPostReplyTo + document.getElementById('comment-'+e+'-author').innerHTML;
        document.getElementById('comment-title').innerHTML = commentHeader;
        YAHOO.util.Dom.addClass(document.getElementById('comment-'+e+'-replylink'), 'hiddenBox');

        commentReplyXID = e;
        commentReplyAuthor = replyAuthor;

        // "In reply to <author name> at <comment date>" snippet (removed for now)
        // <div id="in-reply-to" class="hiddenBox"></div>
        // YAHOO.util.Dom.removeClass('in-reply-to', 'hiddenBox');
        // document.getElementById('in-reply-to').innerHTML = msgInReplyTo + "<a href=\"#comment-"+commentReplyXID+"\">"+commentReplyAuthor+" at "+document.getElementById('comment-'+commentReplyXID+'-datetime').innerHTML+"</a>.";

        // jump to the comment-form
        window.location.hash = "comment-" + e;

    },
    moveFormBack: function(e) {
        YAHOO.util.Dom.insertAfter(document.getElementById('atp-comments'), document.getElementById('all-comments')); 
        YAHOO.util.Dom.addClass(document.getElementById('comment-'+commentReplyXID+'-cancelreply'), 'hiddenBox');   
        commentHeader = msgPostAComment;
        document.getElementById('comment-title').innerHTML = commentHeader;

        // Not hiding these right now..
        //YAHOO.util.Dom.addClass('comment-complete', 'hiddenBox');
        //YAHOO.util.Dom.addClass('in-reply-to', 'hiddenBox');
        atpComments.resetCommentForm();

        YAHOO.util.Dom.removeClass(document.getElementById('comment-'+commentReplyXID+'-replylink'), 'hiddenBox');

        commentReplyXID = null;
        commentReplyAuthor = null;
        commentReplyComplete = null;
    },
    resetCommentForm: function() {
        YAHOO.util.Dom.addClass('comment-preview', 'hiddenBox');
        YAHOO.util.Dom.addClass('comment-preview-confirmation', 'hiddenBox');
        YAHOO.util.Dom.addClass('comment-error', 'hiddenBox');
        YAHOO.util.Dom.addClass('comment-captcha', 'hiddenBox');
        YAHOO.util.Dom.removeClass('primary-comment-form', 'hiddenBox');
        YAHOO.util.Dom.removeClass('primary-comment-form', 'hiddenBox');
    },
    publicizeComment: function(publicize) {

        var pubAccs = new Array();

        // Do we have multiple accounts we need to check?
        if(publicize.length) {
            for(var i = 0; i < publicize.length; i++) {
                // If the box is checked, add it to the list of accounts we'll be pushing updates to
                if(publicize[i].checked) {
                    pubAccs.push(publicize[i].value);
                }
            }
        } else { // Else, there's only one account to check
            if(publicize.checked) {
                // Make sure it's checked, then push it to the list     
                pubAccs.push(publicize.value);                   
            }
        }

        return pubAccs;

    }
 };

YAHOO.register("atpcomments",
               atpComments,
               {version: "0.0.1", build: "1337"});
