// Markup based unobtrusive comprehensive dom ready execution
// http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution/
// Remove these comments and replace meettomarry with the name of the client or site.
var meettomarry = {
    common: {
        init: function () {

            // Newsletter Signup
            // -----------------
            var $newsletterControls = $('.newsletter-signup-control');
            if ($newsletterControls.length) {
                var $checkboxSingle = $newsletterControls.find('div[id$="wCheckboxSingle"] input');
                $checkboxSingle.attr('checked', 'checked');
            }

            // Book Excerpt
            // ------------
            var $excerptControls = $('.bookexcerpt-control-container');
            if ($excerptControls.length) {
                $.each($excerptControls, function (index, value) {
                    var $value = $(value),
                        $excerptData = $value.find('.excerpt-item'),
                        $currentExcerpt = $excerptData.first();

                    $excerptData.hide();
                    $currentExcerpt.show();

                    function cycleNext() {
                        var $next = $currentExcerpt.next();
                        $currentExcerpt = $next.length ? $next : $excerptData.first();
                        $excerptData.hide();
                        $currentExcerpt.show();
                        if ($excerptData.length > 2) {
                            setCycleNextTimeout();
                        }
                    }
                    function setCycleNextTimeout() {
                        setTimeout(function () {
                            cycleNext();
                        }, 10000);
                    }

                    $value.find('.previous-button').click(function (e) {
                        e.preventDefault();
                        var $previous = $currentExcerpt.prev();
                        $currentExcerpt = $previous.length ? $previous : $excerptData.last();
                        $excerptData.hide();
                        $currentExcerpt.show();
                    });
                    $value.find('.next-button').click(function (e) {
                        e.preventDefault();
                        cycleNext();
                    });

                    if ($excerptData.length > 2) {
                        setCycleNextTimeout();
                    }
                    if ($excerptData.length <= 1) {
                        $value.find('.bookexcerpt-control-controls').hide();
                    }
                });
            }

            // Message Bari
            // ------------
            var $messageControls = $('.message-control');
            if ($messageControls.length) {
                $.each($messageControls, function (index, value) {
                    var $value = $(value),
                        $textarea = $value.find('textarea'),
                        $nameInput = $value.find('#message-name'),
                        $emailInput = $value.find('#message-email'),
                        $submitButton = $value.find('.submit-button'),
                        $cancelButton = $value.find('.cancel-button'),
                        $successOutput = $value.find('.success'),
                        $errorOutput = $value.find('.errors'),
                        initialMessageKey = "initialMessage",
                        hasFormSubmitted = false;

                    function disableSubmit() {
                        $submitButton.attr('disabled', 'disabled');
                        $submitButton.addClass('disabled');
                    }
                    function enableSubmit() {
                        $submitButton.removeAttr('disabled');
                        $submitButton.removeClass('disabled');
                    }
                    function resetForm() {
                        $textarea.val($value.data(initialMessageKey));
                        $value.find('input').val('');
                        clearErrors();
                    }
                    function showGenericError() {
                        enableSubmit();
                        $errorOutput.html('There was a problem sending your message. Please try again.');
                        $errorOutput.show();
                    }
                    function clearErrors() {
                        $errorOutput.hide();
                        $errorOutput.html('');
                    }
                    function validateForm() {
                        var errors = [],
                            messageValue = $.trim($textarea.val()),
                            emailValue = $.trim($emailInput.val());

                        // validate user input
                        if (messageValue === "" || messageValue === $value.data(initialMessageKey)) { errors.push("Message is required"); }
                        if ($.trim($nameInput.val()) === "") { errors.push("Name is required"); }
                        if (emailValue === "") {
                            errors.push("Email is required");
                        } else if (!(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/).test(emailValue)) {
                            errors.push("Email is malformed");
                        }

                        // output errors
                        $errorOutput.html(errors.length > 0 ? errors.join("<br />") : '');
                        $errorOutput[errors.length > 0 ? 'show' : 'hide']();

                        return errors.length === 0;
                    }
                    function submitForm() {
                        if (hasFormSubmitted) { return; }
                        disableSubmit();
                        clearErrors();

                        $.ajax({
                            type: "POST",
                            url: '/MessageService.svc/SendMessageSimple',
                            data: JSON.stringify({
                                name: $.trim($nameInput.val()),
                                email: $.trim($emailInput.val()),
                                message: $.trim($textarea.val())
                            }),
                            contentType: "application/json; charset=utf-8",
                            success: function (data, textStatus, request) {
                                var response = ValidationDictionary.GetInstanceFromJSONResponse(data);
                                if (response !== undefined && response.ErrorCount > 0) {
                                    showGenericError();
                                    return;
                                }
                                resetForm();
                                $successOutput.show();
                                hasFormSubmitted = true;
                            },
                            error: function (res, textStatus, errorThrown) {
                                showGenericError();
                            }
                        });
                    }

                    // setup control events
                    $value.data(initialMessageKey, $textarea.val());
                    $textarea.focus(function (e) {
                        if ($.trim($textarea.val()) === $value.data(initialMessageKey)) {
                            $textarea.val('');
                        }
                    });
                    $textarea.blur(function (e) {
                        if ($.trim($textarea.val()) === "") {
                            $textarea.val($value.data(initialMessageKey));
                        }
                    });
                    $submitButton.click(function (e) {
                        e.preventDefault();
                        if (validateForm()) {
                            submitForm();
                        }
                    });
                    $cancelButton.click(function (e) {
                        e.preventDefault();
                        resetForm();
                    });
                });
            }

            // Quote Carousel
            // --------------
            var $quoteControl = $('#quote-control');
            if ($quoteControl.length) {
                var $quoteData = $quoteControl.find('.quote-item'),
                    $currentQuote = $quoteData.first();

                $quoteControl.find('.previous-button').click(function (e) {
                    e.preventDefault();
                    var $previous = $currentQuote.prev();
                    $currentQuote = $previous.length ? $previous : $quoteData.last();
                    $quoteData.hide();
                    $currentQuote.show();
                });
                $quoteControl.find('.next-button').click(function (e) {
                    e.preventDefault();
                    var $next = $currentQuote.next();
                    $currentQuote = $next.length ? $next : $quoteData.first();
                    $quoteData.hide();
                    $currentQuote.show();
                });

                // display initial quote
                $currentQuote.show();
            }
        },
        finalize: function () {
            // Low priority scripts here
        }
    },
    home: {
        init: function () {
            // Page specific script example (for the home page)
        }
    },
    coaching: {
        init: function () {

            var $moreContainers = $('.more-container');
            $moreContainers.hide();
            $.each($moreContainers, function (index, item) {
                var $moreContainer = $(item);
                $moreContainer.data("isOpen", false);
                $moreContainer.closest('.box').find('.read-more').click(function (e) {
                    e.preventDefault();

                    if ($moreContainer.data("isOpen")) {
                        $(e.currentTarget).removeClass("is-open");
                    } else {
                        $(e.currentTarget).addClass("is-open");
                    }

                    $moreContainer.toggle();
                    $moreContainer.data("isOpen", !$moreContainer.data("isOpen"));
                });
            });
        }
    },
    preregister: {
        init: function () {
            // pre-select e-newletter signup checkbox
            var $inputs = $('input[type="checkbox"]');
            $inputs.last().attr("checked", "checked");
        }
    }
};

UTIL = {
    fire: function (func, funcname, args) {
        var namespace = meettomarry;

        funcname = (funcname === undefined) ? 'init' : funcname;
        if (func !== '' && namespace[func] && typeof namespace[func][funcname] == 'function') {
            namespace[func][funcname](args);
        }
    },
    loadEvents: function () {
        var bodyId = document.body.id;

        // Fire common scripts first.
        UTIL.fire('common');

        // Fire scripts based on body class and id.
        $.each(document.body.className.replace(/(-)([a-z])/g, function (a, b, c) { return c.toUpperCase() }).split(/\s+/), function (i, classnm) {
            UTIL.fire(classnm);
            UTIL.fire(classnm, bodyId);
        });

        // Fire low priority scripts last.
        UTIL.fire('common', 'finalize');
    }
};

$(function () { UTIL.loadEvents() });

// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function () {
    log.history = log.history || [];   // store logs to an array for reference
    log.history.push(arguments);
    if (this.console) {
        console.log(Array.prototype.slice.call(arguments));
    }
};

// catch all document.write() calls
(function (doc) {
    var write = doc.write;
    doc.write = function (q) {
        log('document.write(): ', arguments);
        if (/docwriteregexwhitelist/.test(q)) write.apply(doc, arguments);
    };
})(document);

