$(document).ready(function () {

// Utility Functions
    $('body').removeClass('noscript');
    $('textarea').addClass('ta');
    $(':text').addClass('ti');
    $(':file').addClass('fi');
    // $(':password').addClass('ti').addClass('pw');
    // $(':checkbox').addClass('cb');
    // $(':radio').addClass('fi');

    // hide messaging on click
    $('.close-me').click(function() {
        $(this).parent().hide();
        return false;
    });

    // Object Converter
    function oc(a) {var o={};for(var i=0;i<a.length;i++){o[a[i]]='';};return o;}

    // Set Field Defaults
    formFieldFocus();

    // Sign-in auth tab switcher - auth_types is defined in the login page.
    $('#auth-options li').click(function(){
        authID = $(this).attr('id').replace("signin_option_", "");
        authOption = $("#signin_option_" + authID);
        if (authOption) {
            for (var i = 0; i < auth_types.length; i++) {
                var auth_type = auth_types[i];
                if (auth_type == authID) {
                    $('#signin_with_' + auth_type).show();
                    $('#signin_option_' + auth_type).addClass('selected');
                } else {
                    $('#signin_with_' + auth_type).hide();
                    $('#signin_option_' + auth_type).removeClass('selected');
                }
            }
        };
    })

    // Condition to only apply rules when #compose is present
    if ($('#compose').size()) {

        function fileExtensionCheck(filename, types) {
            var ext = filename.match(/[^\.]+$/);
            if (!ext) return false;
            ext = ext.toString();
            var hash = {};
            for (var i = 0; i < types.length; i++)
                hash[types[i]] = true;
            return hash[ext.toLowerCase()];
        }

    // Entry Field Manager
        // Field types
        var fieldTypes = ['title','body','url',"photo",'audio','embed','tags'];
        // Entry Editor
        var entryTypes = {
            "entry-text": ['title','body','tags'],
            "entry-photo": ['title','body','tags','photo'],
            "entry-link": ['title','body','tags','url'],
            "entry-embed": ['title','body','tags','embed'],
            "entry-audio": ['title','body','tags','audio']
        };
        var entryClasses = {
            "entry-link":  "link",
            "entry-photo": "photo",
            "entry-audio": "audio",
            "entry-embed": "embed"
        };
        function updateEntryFields(entryType, speed) {
            if (!entryType.length) return;
            var speed = (speed) ? speed : '';
            $(entryType).addClass('active').siblings().removeClass('active');
            var parentID = $(entryType).attr("id");

            var entryClass = entryClasses[parentID] || 'entry';
            $('#compose-class').val(entryClass);

            for (var i in fieldTypes) {
                var fieldName = "#field-" + fieldTypes[i];
                if (fieldTypes[i] in oc(entryTypes[parentID])) {
                    $(fieldName).fadeIn(speed);
                    $(':input', fieldName).removeAttr('disabled');
                } else {
                    $(fieldName).hide();
                    $(':input', fieldName).attr('disabled','disabled');
                }
            }
        }
        // Enable default entry fields
        updateEntryFields($('#entry-text'));
        // Change entry fields
        $('#entry-types li a').click(function() {
            updateEntryFields($(this).parent(), 250);
            return false;
        })
        $('.more-options').click(function() {
            $('#entry-fields-optional').fadeIn(450);
            $(this).hide();
        });

    // Compose Submission Handler
        // Create container for new entry
        $('.actions').before('<ul id="response-handler"></ul>');
        if ($('.actions ul').size() == 0)
            $('.actions').append('<ul></ul>');

        // Create containers for status messaging
        $('#compose').append('<div id="spinner"></div><div id="spinner-status"></div>');

        // Entry Submission
        $('#homepage-compose').submit(function(){
            var f = $("#homepage-compose").get(0);

            var post_type = f.customfield_post_type.value;

            // clear any default labels
            $("#homepage-compose .default-value").each(function() {
                $(this).val('');
            });

            // form validation; check for required fields and valid file
            // extensions...
            if (post_type == 'audio') {
                var file_name = f.file_customfield_audio.value;
                if (!file_name) {
                    alert(mt.blog.phrase.fileRequired);
                    return false;
                } else if (!fileExtensionCheck(file_name, ['mp3'])) {
                    alert(mt.blog.phrase.invalidFileType);
                    return false;
                }
            } else if (post_type == 'photo') {
                var file_name = f.file_customfield_photo.value;
                if (!file_name) {
                    alert(mt.blog.phrase.fileRequired);
                    return false;
                } else if (!fileExtensionCheck(file_name, ['gif', 'png', 'jpg', 'jpeg'])) {
                    alert(mt.blog.phrase.invalidFileType);
                    return false;
                }
            }

            // file-based posts do not use ajax
            if (post_type == 'audio') {
                f.type_customfield_audio.value = 'audio';
                f.ajax.value = '';
                return true;
            } else if (post_type == 'photo') {
                f.type_customfield_photo.value = 'image';
                f.ajax.value = '';
                return true;
            }

            // flag this as an ajax request
            f.ajax.value = '1';
            $(this).ajaxSubmit({
                target: '#response-handler',
                beforeSubmit: beforeSubmit,
                // ajax request is always encoded in utf-8 no matter 
                // what charset the actual page is encoded, isn't it?
                // file-based posts do not use ajax so the type should be ok.
                contentType: 'application/x-www-form-urlencoded; charset=utf-8',
                success: displayEntry
            });
            return false;
        });

        function beforeSubmit(){
            $('#quickpost-error').fadeOut().remove();
            $('#spinner, #spinner-status').fadeIn('fast').css('height',$('#compose').height());
        }

        // response function
        function displayEntry(){
            if ($('#response-handler #quickpost-error').size() == 0)
                $('#homepage-compose').clearForm();
            // hide new entry, move to main listing.
            $('#response-handler > li').hide().insertBefore('.actions ul:first li');
            // slide to show.
            $('.actions li:first').slideDown();
            $('#spinner, #spinner-status').fadeOut();
            formFieldFocus(); // FIXME: is this necessary?
            // Initiate Entry Hover behavior
            initEntryHover();
        }
    };


// Userpic Flyouts
    var flyOut;
    // Flyout Hover/Unhover
    $(".userpic").hover(function () {
        // Hide all with class user-info
        $('.user-info').hide();
        // Show flyout after timeout
        var userInfo = $(this).children('.user-info');
        flyOut = $.timeout(function() { $(userInfo).fadeIn(200); }, 500);
    },function () {
        // Clear flyout timeout
        $.clear(flyOut);
        // Hide flyout
        $(this).children('.user-info').fadeOut(200);
    });
    // Hide flyouts if click event in flyout
    $(".userpic *").click(function () {
        $.clear(flyOut);
        $('.user-info').fadeOut(250);
    })

// Commenting
    var commentDefaultVal = $('#comment-preview-comment .comment-content div').text();
    var authorDefaultVal = $("#comment-author").attr('title');
    var authorVal = $("#comment-author").val();
    var emailVal = $("#comment-email").val();
    var urlVal = $("#comment-url").val();
    if (mtGetUser()) {
        authorVal = mtGetUser().name;
        emailVal = mtGetUser().email;
        urlVal = mtGetUser().url;
    }

    // set default value for Author
    $('#comment-preview-comment .author a').text(authorDefaultVal);

    // hide: comment preview, comment preview button, comment tip
    $('#comment-preview, #comment-preview-comment, #comments-open-text .tip').hide();
    // hide: all comment form labels except the last
    $('#comments-open-data label:not(:last)').hide();
    // hide: reply text
    $('.reply-comment-link').hide();
    // disable all links in comment preview
    $('#comment-preview-comment a').click(function(){ return false }); // disable links
    // show preview upon focusing on textarea of input
    $('#comments-form textarea, #comments-form input').focus(function(){
        showPreview();
    });
    // update preview comment text
    $('#comment-text').keyup(function() {
        updatePreview($(this), $('#comment-preview-comment .comment-content-inner'), commentDefaultVal);
    });
    // update preview comment author
    $('#comment-author').keyup(function() {
        updatePreview($(this), $('#comment-preview-comment .author a'), authorDefaultVal);
    });

    // If comments accepted, add reply links
    if (mt.blog.comments.accepted)
        $('#comments-list .comment').each(function(){
            parentID = $(this).attr('id').replace("comment-", "");
            $('.byline', this).append(' | <a href="#comment-' + parentID + '" title="Reply">菴