// INIT
var fckInstance;

// Functions
function FCKeditor_OnComplete(editorInstance) {
    fckInstance = FCKeditorAPI.GetInstance('enote_text');
}

var FCK_handler = (function() {
    var config = 
      { is_ajax: false
      , incl_subject: true
      , msg_max_len: 4000
      , attach_key: false
      };
    
    // Submit handler
    function checkMessage() {
        if (fckInstance && jQuery('#enote_text___Frame').length)
            FCK.validate();
        else
            TEXT.validate();
        
        return false;
    }
    
    // Save enote
    function save() {
        if (config.is_ajax) {
            jQuery('#emailcompose #submit_compose').hide();
            jQuery('#emailcompose .button').append("<span id='frm_load'>Sending...</span>");
            jQuery.ajax( {
                type : "POST",
                url : "/enote/send",
                data : jQuery('form[name=postdata]').serialize(),
                success: handleDialog,
                complete : function() {
                    jQuery('#emailcompose #submit_compose').show();
                    jQuery('#emailcompose #frm_load').remove();
                }
            });
        }
        else jQuery('form[name=postdata]').submit();
    }
    
    /* -------------------- FCK Specific -------------------- */
    var FCK = {
        // Validate message (FCK HTML)
        // XXX Use jQuery Validate plugin
        validate: function() { 
            var form_elements = document.forms["emailcompose"].elements;
            var subject = jQuery('form[name=emailcompose] input[name=enote_subject]');
            
            if (config.incl_subject && !jQuery.trim(subject.val()).length) {
                alert("You must type in a subject to send!");
                subject.focus();
            }
            else if (!jQuery.trim(fckInstance.EditorDocument.body.textContent || fckInstance.EditorDocument.body.innerText).length) {
                alert("You must type in a message to send!");
                fckInstance.Focus();
            }
            else if (fckInstance.EditorDocument.body.innerHTML.length > config.msg_max_len) {
                alert("Your Message is too long.\nPlease shorten it and try to send it again.\n\nMax Message Length: "
                        + config.msg_max_len
                        + " characters\nYour Message Length: "
                        + fckInstance.EditorDocument.body.innerHTML.length
                        + " characters");
                fckInstance.Focus();
            }
            else {
                FCK.send();
            }
        },
        // Send message (FCK HTML)
        send: function() {
            var postdata = jQuery('form[name=postdata]'),
                emailcompose = jQuery('form[name=emailcompose]');
            
            // Copy data
            jQuery.each(['enote_recipient_id', 'enote_parent_id', 'enote_type_name'], function(idx, name) { 
                postdata[0][name].value = emailcompose[0][name].value;
            });
            if (config.attach_key && emailcompose[0]["attach_key"].checked)
                postdata[0]["attach_key"].value = 1;
            if (config.incl_subject)
                postdata[0]["enote_subject"].value = emailcompose[0]["enote_subject"].value;
            postdata[0]["enote_text"].value = fckInstance.EditorDocument.body.innerHTML;
            
            // Send!
            save();
        }
    };

    /* -------------------- TEXT Specific -------------------- */
    var TEXT = {
        // Validate message (TEXT)
        // XXX Use jQuery Validate plugin
        validate: function() {
            var enote_subject = jQuery('form[name=emailcompose] input[name=enote_subject]'),
                enote_text = jQuery('form[name=emailcompose] textarea[name=enote_text]');
            
            if (config.incl_subject && !jQuery.trim(enote_subject.val()).length) {
                alert("You must type in a subject to send!");
                enote_subject.focus();
            }
            else if (!jQuery.trim(enote_text.val()).length) {
                alert("You must type in a message to send!");
                enote_text.focus();
            }
            else if (enote_text.val().length > config.msg_max_len) {
                alert("Your Message is too long.\nPlease shorten it and try to send it again.\n\nMax Message Length: "
                        + config.msg_max_len
                        + " characters\nYour Message Length: "
                        + enote_text.val().length + " characters");
                enote_text.focus();
            }
            else {
                TEXT.send();
            }
        },
        // Send message (TEXT)
        send: function() {
            var postdata = jQuery('form[name=postdata]'),
                emailcompose = jQuery('form[name=emailcompose]');
            
            // Copy data
            jQuery.each(['enote_recipient_id', 'enote_parent_id', 'enote_type_name', 'enote_text'], function(idx, name) { 
                postdata[0][name].value = emailcompose[0][name].value;
            });
            if (config.attach_key && emailcompose[0]["attach_key"].checked)
                postdata[0]["attach_key"].value = 1;
            if (config.incl_subject)
                postdata[0]["enote_subject"].value = emailcompose[0]["enote_subject"].value;
            
            // Send!
            save();
        }
    };
    
    // Return
    return {submit: checkMessage, config: config};
})();

// INIT (depends on above)
jQuery(function() { 
    jQuery("form[name='emailcompose']").live('submit', FCK_handler.submit);

    jQuery('#mail_compose a.mode').live('click', function(e) {
            jQuery.ajax( {
                type : "POST",
                url : this.href,
                success : function(data) {
                    jQuery('.ui-dialog-content').html(data);
                    jQuery('#dialog').dialog('option', 'width', 'auto');
                }
        });
        
        return false;
    });
});

