// -- Movable Type Motion Functions: motion.js -- //

jQuery(document).ready(function () {

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

    // hide messaging on click
    jQuery('.close-me').click(function() {
        jQuery(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;}


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

    // Condition to only apply rules when #compose is present
    if (jQuery('#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 : '';
            jQuery(entryType).addClass('active').siblings().removeClass('active');
            var parentID = jQuery(entryType).attr("id");

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

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

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

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

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

            var post_type = f.customfield_post_type.value;

            // clear any default labels
            jQuery("#homepage-compose .default-value").each(function() {
                jQuery(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';
            jQuery(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(){
            jQuery('#quickpost-error').fadeOut().remove();
            jQuery('#spinner, #spinner-status').fadeIn('fast').css('height',jQuery('#compose').height());
        }

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


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

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

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

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

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

    // Reply link click function
    jQuery('[title="Reply"]').click(function(){
        // if registration required (ie. no anonymous comments)
        if (mt.blog.registration.required){
            var u = mtGetUser();
            var loggedin = u && u.is_authenticated;
            if (!loggedin)
                mtSignInOnClick('comment-greeting');
        }

        // add comment parent author to comment preview
        replyAuthor = jQuery(this).parent().find('.author').html();
        jQuery('#comment-preview-comment .reply-comment-link a span').html(replyAuthor);

        // update preview comment author
        jQuery('#comment-author').keyup(function() {
            updatePreview(jQuery(this), jQuery('#comment-preview-comment .author a'), authorDefaultVal);
        });

        // show comment preview reply text
        jQuery('#comment-preview-comment .reply-comment-link').show();

        // get id from reply link
        parent_id = this.hash.replace("#comment-", "");

        // show reply form field, set focus to comment form
        mtReplyCommentOnClick(parent_id, replyAuthor);

        return false;
    });

    // toggle reply text when reply checkbox is checked
    jQuery('#comment-reply').click(function(){ jQuery('.reply-comment-link').toggle() });

    // Comment Submit
    jQuery("#comment-submit").click(function(){
        // hide comment preview
        jQuery('#comment-preview-comment').fadeOut(1000);
        // Set Commenter
        // setCommenter();
        // disable comment and submit button
        jQuery("#comment-submit, #comment-text").attr("disabled","disabled");
        // Set armor
        if (jQuery('[name="armor"]')) {
           jQuery('[name="armor"]').val(mt.blog.comments.armor);
        }

        // Bake Cookies
        // mtCommentOnSubmit(jQuery("#comments-form"));

        jQuery("#comments-form .default-value").each(function() {
            jQuery(this).val('');
        });

        // Get form data and post
        var staticVal = jQuery('[name="static"]').val();
        var entryIdVal = jQuery('[name="entry_id"]').val();
        var langVal = jQuery('[name="lang"]').val();
        var parentIdVal = jQuery('[name="comment_reply"]').val();
        var armorVal = jQuery('[name="armor"]').val();
        var previewVal = jQuery('[name="prev"]').val();
        var sidVal = jQuery('[name="sid"]').val();
        var capthchaVal;
        var tokenVal;
        if(jQuery("#captcha_code")) {
            capthchaVal = jQuery('#captcha_code').val();
            tokenVal = jQuery('input[name="token"]').val();
        }
        var replyVal = jQuery("#comment-reply").val();

        var textVal = jQuery("#comment-text").val();
        var authorVal = jQuery("#comment-author").val();
        var emailVal = jQuery("#comment-email").val();
        var urlVal = jQuery("#comment-url").val();
        if (mtGetUser()) {
            authorVal = mtGetUser().name;
            emailVal = mtGetUser().email;
            if (emailVal == undefined) emailVal = '';
            urlVal = mtGetUser().url;
            if (urlVal == undefined) urlVal = '';
        }

        var postData = { static: staticVal, entry_id: entryIdVal, parent_id: parentIdVal, armor: armorVal, comment_reply: replyVal, author: authorVal, email: emailVal, url: urlVal, text: textVal, captcha_code: capthchaVal, token: tokenVal};
        jQuery.ajax({
            type: "POST",
            url: mt.blog.comments.script,
            data: postData,
            contentType: 'application/x-www-form-urlencoded; charset=utf-8',
            success: function(data){
                jQuery("#comments-list").html(data);
                jQuery("#comment-submit, #comment-text").removeAttr("disabled");
                if (jQuery('#comments-list #comment-error').size() > 0) {
                    jQuery("#comment-preview-comment").fadeIn(1000);
                } else if (jQuery('#comments-list #comment-exclamation').size() > 0) {
                    jQuery("#comment-text").val('');
                    jQuery("#comment-preview-comment").fadeIn(1000);
                    mtFireEvent('commentposted', postData);
                } else {
                    jQuery('#comment-preview-comment .comment-content-inner').html(commentDefaultVal);
                    jQuery("#comment-text").val('');
                    mtFireEvent('commentposted', postData);
                };
            }
        });
        return false;
    });


// Gallery Widget
    jQuery("#gall-prev").click(function(){
        var gall_position = jQuery("#photo-gallery").position();
        if (gall_position.left < 0) {
            if ((currentItem - 1) >= 1) {
                jQuery("#photo-gallery").animate({"left": "+=120px"}, "slow", "swing", function() {
                    var gall_position_new = jQuery("#photo-gallery").position();
                    if (gall_position_new.left == 0) {
                        jQuery("#gall-prev").addClass("disabled");
                    }
                });
                currentItem--;
            };
            jQuery("#gall-next").removeClass("disabled");
        }
    });
    jQuery("#gall-next").click(function(){
        if (lastItem >= (currentItem + 1)) {
            currentItem++;
            jQuery("#photo-gallery").animate({"left": "-=120px"}, "slow");
            jQuery("#gall-prev").removeClass("disabled");
        }
        if ((currentItem) == lastItem) {
            jQuery("#gall-next").addClass("disabled");
        }
    });


// Change/Remove Userpic
    // define userpic
    var changeUserpic = jQuery('#userpic-field .field-content #change-userpic');
    var removeUserpic = jQuery('#userpic-field .field-content #remove-userpic');
    // hide input change link present
    jQuery(changeUserpic).siblings("input").hide();
    // onclick: hide link, img. show input
    if (changeUserpic.size()) {
        jQuery(changeUserpic).click(function() {
            var speed = 500;
            jQuery(this).hide(speed).siblings("img").hide(speed).siblings("input").show(speed);
            removeUserpic.hide(speed);
            return false;
        })
    };
    if (removeUserpic.size()) {
        jQuery(removeUserpic).click(function() {
            var id = jQuery('[name="id"]').val();
            var token = jQuery('[name="magic_token"]').val();
            var postData = { __mode: 'remove_userpic', user_id: id, magic_token: token  };
            jQuery.post(mt.blog.community.script, postData,
                function(data){
                    var speed = 500;
                    jQuery(removeUserpic).hide(speed).siblings("img").hide(speed).siblings("input").show(speed);
                    changeUserpic.hide(speed);
                }
            );
            return false;
        })
    };

    // Initiate Entry Hover behavior
    initEntryHover();

    // Initiate page load functions
    composeMagic();
    personalizeEditor();
    personalizeCommentForm();

}); // End Ready Function

// Hover on Entry or actions
function initEntryHover(){
    jQuery(".asset, .actions > ul > li").hover(function(){
            jQuery(this).addClass('hover');
        },function(){
            jQuery(this).removeClass('hover');
        }
    );
}

// Commenting Functions

var commentDefaultVal, authorDefaultVal, authorVal, emailVal, urlVal;
function updatePreviewTime(){
    jQuery('#comment-preview-comment .byline a .published').html( jQuery.PHPDate("M d, Y g:i A", new Date())); // set date
    // jQuery('#comment-preview-comment .byline abbr').attr('title',jQuery.PHPDate("c", new Date())); // set iso 8601 date (optional)
}
function showPreview(){
    var u = mtGetUser();
    var loggedin = u && u.is_authenticated;
    if (loggedin) {
        var fooname = mtGetUser().name;
        jQuery('#comment-preview-comment .byline .author a').html(fooname); // set comment author value
    } else {
        jQuery('#comment-preview-comment .byline .author a').html(authorVal); // set comment author value
    }
    jQuery("#comment-preview-comment, #comments-open-text .tip").fadeIn(1000); // hide comment preview
    updatePreviewTime();
}
function updatePreview(id, target, defaultVal){
    v = jQuery(id).val();
    v = (v.length? v : defaultVal)
    v = v.replace(/\n/g, "<br />").replace(/\n\n+/g, '<br /><br />').replace(/(<\/?)script/g,"$1noscript");
    jQuery(target).html(v);
    updatePreviewTime();
}


// Utility Functions

// Authentication Functions (need to be merged. search for all instances of "mtGetUser" above and merge)

function ifLoggedIn(){
    var u = mtGetUser();
    if (u && u.is_authenticated && u.is_author)
        return true;
}

function setCommenter(){
    if (mtGetUser()) {

        // Set Commenting Values
        var authorVal = mtGetUser().name;
        var emailVal = mtGetUser().email;
        var urlVal = mtGetUser().url;
    // } else {
    //     var authorVal = jQuery("#comment-author").val();
    //     var emailVal = jQuery("#comment-email").val();
    //     var urlVal = jQuery("#comment-url").val();
    }
}

function personalizeEditor() {
    var u = mtGetUser();
    if ( u && u.is_authenticated ) {
        // Set Compose Userpic
        if (u.userpic) {
            jQuery("#compose-userpic img").attr({
                src: u.userpic,
                alt: u.name
            });
        } else {
            jQuery("#compose-userpic img").wrap('<a href="' + mt.blog.community.script + '?__mode=edit&blog_id=' + mt.blog.id + '&return_to=' + encodeURIComponent(document.URL) + '"></a>');
            jQuery('#compose-userpic a').append('<span>Add userpic</span>');
        };
    };
}
function personalizeCommentForm() {
    var u = mtGetUser();
    if ( u && u.is_authenticated ) {
        // Set Commenter Userpic
        if (u.userpic) {
            jQuery("#commenter-userpic").attr({
                src: u.userpic,
                alt: u.name
            });
        };
    };
}
function composeMagic() {
    var u = mtGetUser();
    if (ifLoggedIn()) {
      if ( u.can_post ) {
        jQuery('#authenticate').fadeOut('fast');
        jQuery('#compose').show(); // .slideDown();
        jQuery('#compose-magic').val(u.sid);
        jQuery('#cannot-post').hide();
      } else if ( u.can_comment ) {
        jQuery('#authenticate').hide();
        jQuery('#compose').hide();
        jQuery('#cannot-post').hide();
      } else {
        jQuery('#authenticate').show();
        jQuery('#compose').hide();
        jQuery('#cannot-post').show();
      }
    } else if ( !u ) {
        jQuery('#authenticate').show();
        jQuery('#cannot-post').hide();
    } else {
        jQuery('#authenticate').hide();
        jQuery('#compose').hide();
        jQuery('#cannot-post').hide();
    }
}

// Added from community.js for follow functionality to work

function conditional_block(cond, id) {
    var true_block = document.getElementById(id);
    var false_block = document.getElementById(id + '_else');
    if (cond) {
        if (true_block) {
            var display = true_block.getAttribute('mt:display_style');
            if (!display && false_block)
                display = false_block.getAttribute('mt:display_style');
            if (!display) display = '';
            true_block.style.display = display;
            DOM.removeClassName(true_block, 'hidden');
        }
        if (false_block) {
            false_block.style.display = 'none';
            DOM.addClassName(false_block, 'hidden');
        }
    }
    else {
        if (true_block) {
            true_block.style.display = 'none';
            DOM.addClassName(true_block, 'hidden');
        }
        if (false_block) {
            var display = false_block.getAttribute('mt:display_style');
            if (!display && true_block)
                display = false_block.getAttribute('mt:display_style');
            if (!display) display = '';
            false_block.style.display = display;
            DOM.removeClassName(false_block, 'hidden');
        }
    }
}

mtAttachEvent('usersignin', composeMagic);
mtAttachEvent('usersignin', showPreview);


// Browser Hacks
jQuery(document).ready(function() {
    // if Mozilla
    if (jQuery.browser.mozilla){
        // on unload event, clear text values so that they are not cached
        jQuery(window).unload(function(){
            jQuery(':text, textarea').val('');
        });
    }
});

// Debug Functions
// jQuery(document).ready(function() {
//     Object dumper
//     jQuery('#alpha').prepend("<pre>" + jQuery(jQuery.browser).dump() + "</pre>");
// });

