﻿$(document).ready(function() {
    //Create an array for all form fields to ne validated - handy for allField.xxx operations for resetting form fields

    //Declare Entry Form Globals
    var feedbackTypeId = $('#SJFfeedbackTypeId'),
			feedbackSubject = $('#SJFfeedbackSubject'),
			feedbackComments = $('#SJFfeedbackComments'),
			entryAllFields = $([]).add(feedbackTypeId).add(feedbackSubject).add(feedbackComments);

    var entryfeedbackTypeId = $('#SJFfeedbackTypeId');

    //Entry Dialog Vars - Form One
    entryBaseValidationMessage = "<span class='title'>The Following Errors Occurred:</span>";
    entryTips = $('#SendJobFeedbackForm .validateTips');
    entryTips.html(entryBaseValidationMessage);
    entryTips.hide();

    //Add instructions to error form 
    function addValidattionMessage(t, valMsg, valField) {
        //        validationString = validationString + "<br />" + t;
        valMsg = valField.html();
        valMsg = valMsg + t + "<br />";
        valField.html(valMsg);
    }

    //Simple validation function - we should look at the JQuery validation framework for better ways to do this
    function checkLength(o, n, min, max, valMsg, valField) {
        if (o.val().length > max || o.val().length < min) {
            errorTxt = "Length of " + n + " must be between " + min + " and " + max + "."
            addValidattionMessage(errorTxt, valMsg, valField);
            return false;
        } else {
            return true;
        }
    }


    //Overlay the form with the JQuery UI Dialog
    $('#SendJobFeedbackForm').dialog({
        autoOpen: false,
        height: 'auto',
        width: 640, //Warning: 'auto' for width does not with IE 6
        modal: true,
        buttons: {
            Cancel: function() {
                $(this).dialog('close');
            },
            'Submit': function() {
                var bValid = true;
                entryValidationString = entryBaseValidationMessage;
                entryTips.html(entryValidationString);
                entryTips.removeClass('error');
                entryTips.hide();


                bValid = checkLength(feedbackSubject, 'Feedback Subject', 1, 50, entryValidationString, entryTips) && bValid;
                bValid = checkLength(feedbackComments, 'Comments', 1, 650, entryValidationString, entryTips) && bValid;

                if (bValid) {
                    var modalContainter = $(this).parent();
                    modalContainter.block({
                        theme: true,
                        cursor: 'default',
                        title: 'Send Feedback',
                        message: '<p>Updating...</p>',
                        timeout: 10000
                    });

                    $.post('/Message/SendJobFeedback/',
                           $('#SendJobFeedbackForm').serialize(),
                           function(data) {
                               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) {
                                       addValidattionMessage(error, entryValidationString, entryTips)
                                   });
                                   entryTips.addClass('error');
                                   entryTips.show();
                                   modalContainter.unblock({ fadeOut: 500 });
                               }
                           },
                          'json');
                } else {
                    entryTips.addClass('error');
                    entryTips.show();
                }
            }

        },
        close: function() {
            entryTips.html(entryBaseValidationMessage);
            entryTips.removeClass('error');
            entryTips.hide();
            entryAllFields.each(function() {
                switch (this.type) {
                    case 'password':
                    case 'select-multiple':
                    case 'select-one':
                    case 'text':
                    case 'textarea':
                        $(this).val('');
                        break;
                    case 'checkbox':
                    case 'radio':
                        this.checked = false;
                }
            });

        }
    });

    //Add the callback for the Add Authorized User
    $('[data-dialog="SendJobFeedback"]').click(function($e) {
        //Block the default acttion for the (href) element - otherwise opens the no_javascript page 
        $e.preventDefault();

        //set the form hidden values
        var __jobId = $(this).attr('data-jobId');
        $('#SJFjobId').val(__jobId);
        var __jobTitle = $(this).attr('data-jobTitle');
        $('#SJFjobTitle').val(__jobTitle);
        var __companyName = $(this).attr('data-companyName');
        $('#SJFcompanyName').val(__companyName);
        
        //Set the visible form values
        $('#SJFcompanyNameDisplay').text(__companyName);
        $('#SJFjobTitleDisplay').text(__jobTitle);
        
        // Set the Dialog Title
        $('#SendJobFeedbackForm').dialog({ title: 'Send Feedback' });
        
        
        //Build Dropdown List for UserRoleTypes
        // - First, set up the data to be posted
        var __antiforgeryTokenValue = $('#antiForgeryToken').attr('value'); //Comes from input form
        var __antiforgeryTokenName = $('#antiForgeryToken').attr('name'); //Comes from input form
        var __jsonInputString = '{ "' + __antiforgeryTokenName + '":"' + __antiforgeryTokenValue + '" }';
        var __tempJson = $.parseJSON(__jsonInputString); //Turn the string into a JSON object
        // - Second, clear the list
        $('#SJFfeedbackTypeId').empty();

        // - Third, Get the list data and bind it to the select element
        $.post('/Message/GetFeedbackTypeList/', __tempJson, function(json) {
            $.each(json, function(index, optionData) {
            //$("<option/>").attr("value", optionData.Value.toString()).text(optionData.Text.toString).appendTo('#SJFfeedbackTypeId');
                $("<option/>").val(optionData.Value).text(optionData.Text).appendTo('#SJFfeedbackTypeId');
            });
            // Open the dialog
            $('#SendJobFeedbackForm').dialog('open');
        });

    });

});