﻿$(document).ready(function() {
    var modalContainter = null

    //Create an array for all form fields - handy for allField.xxx operations for resetting form fields
    var emailTo = $('#SMJemailTo'),
			emailFrom = $('#SMJemailFrom'),
			emailSubject = $('#SMJemailSubject'),
			emailMessage = $('#SMJemailMessage'),
			allFields = $([]).add(emailTo).add(emailFrom).add(emailSubject).add(emailMessage),
			baseValidationMessage = "<span class='title'>The Following Errors Occurred:</span>";
    tips = $('.validateTips');
    tips.html(baseValidationMessage);
    var responseValidationMessage = baseValidationMessage;
    tips.hide();

    //Add instructions to form
    function updateTips(t) {
        validationString = tips.html();
        validationString = validationString + t + "<br />";
        tips.html(validationString);
    }
    //Handle ajax (.post and .get errors
    $.ajaxSetup({
        error: function(x, e) {
            responseValidationMessage = baseValidationMessage;
            if (x.status == 0) {
                responseValidationMessage = responseValidationMessage + 'Problem processing your request: Please check your network connection.';
            } else if (x.status == 500) {
                responseValidationMessage = responseValidationMessage + 'Problem processing your request: Please enable your browser cookies.';
            } else {
                responseValidationMessage = responseValidationMessage + 'Problem processing your request: Please enable your browser cookies.';
            }

            if (modalContainter != null) {
                tips.html(responseValidationMessage);
                tips.addClass('error');
                tips.show();
                modalContainter.unblock({ fadeOut: 500 });
            }
        }
    });


    //Simple validation function - we should look at the JQuery validation framework for better ways to do this
    function checkLength(o, n, min, max) {
        if (o.val().length > max || o.val().length < min) {
            //o.addClass('ui-state-error');
            updateTips("Length of " + n + " must be between " + min + " and " + max + ".");
            return false;
        } else {
            return true;
        }
    }

    function removeScriptTag(o) {
        if (o.valueOf().length > 0) {
            var __text = o.val().replace(/\</g, '('); //RegEx for replace all "<" with "("
            __text = __text.replace(/\>/g, ')'); //RegEx for replace all ">" with ")"
            o.val(__text);
        }
        return o
    }

    //Overlay the form with the JQuery UI Dialog
    $('#SendMessageJobDialog').dialog({
        autoOpen: false,
        height: 'auto',
        width: 640, //Warning: 'auto' does not with IE 6
        modal: true,
        buttons: {
            Cancel: function() {
                $(this).dialog('close');
            },
            'Send': function() {

                var bValid = true;
                tips.html(baseValidationMessage);
                //allFields.removeClass('ui-state-error');
                tips.removeClass('error');
                tips.hide();

                bValid = checkLength(emailTo, "email 'To'", 1, 200) && bValid;
                bValid = checkLength(emailFrom, "email 'From'", 1, 200) && bValid;

                if (bValid) {
                    modalContainter = $(this).parent();
                    modalContainter.block({
                        theme: true,
                        title: 'Forward',
                        message: '<p>Updating...</p>',
                        timeout: 10000
                    });
                    removeScriptTag(emailTo);
                    removeScriptTag(emailFrom);

                    $.post('/Message/SendJob/', $('#SendMessageJobDialog').serialize(), function(data) {
                        responseValidationMessage = baseValidationMessage;
                        if (data.result) {
                            //If return status is TRUE Reload parent (clears the dialog - autoOpen: false)
                            location.reload(true);
                        } else {
                            $.each(data.errorList, function(i, error) {
                                responseValidationMessage = responseValidationMessage + (error + "<br />");
                            });
                            tips.html(responseValidationMessage);
                            tips.addClass('error');
                            tips.show();
                            modalContainter.unblock({ fadeOut: 500 });
                        }
                    }, 'json');
                } else {
                    tips.addClass('error');
                    tips.show();
                }

            }

        },
        close: function() {
            //allFields.val('').removeClass('ui-state-error');
            tips.html(baseValidationMessage);
            tips.removeClass('error');
            tips.hide();
        }
    });

    $('[data-dialog="SendMessageJobEntry"]').click(function($e) {
        //Block the default acttion for the (href) element - otherwise opens the no_javascript page 
        $e.preventDefault();

        // Set the Dialog Title
        $('#SendMessageJobDialog').dialog({ title: 'Forward' });

        // Update the instructions
        var __instructions = "<strong>Complete this form to send the '";
        // '" & gEmail.title & "
        __instructions = __instructions + $(this).attr('data-jobTitle');
        __instructions = __instructions + "' job by email</strong>. A copy of the position will follow any message that you enter below.";

        $('#SendMessageJobDialog .instructions').html(__instructions);

        // Update the Job id hidden field
        var __jobId = $(this).attr('data-jobId');
        $('#SMJjobId').val(__jobId)

        // Open the dialog
        $('#SendMessageJobDialog').dialog('open');
    });
});
