﻿var SchoolRequestBody = {
    ConfirmationTarget: "request_new_school_confirmation_dialog",
    BoxTarget: "request_new_school_dialog",
    FormTarget: "request_new_school_form",
    ValidationTarget: "#request_new_school_validation",
    DialogBox: null,

    Prefix: "",
    Box: null,
    Form: null,
    Confirmation: null,
    HiddenSchoolId: null,

    CreateAction: "/Schools/JSONCreate/",
    FormAction: "/Schools/GetRequestDialog/",

    Init: function(isAfterSchool, parent) {
        this.HiddenSchoolId = parent.HiddenSchoolId;
        this.IsAfterSchool = isAfterSchool;
        this.FormAction += '?is_after_school=' + this.IsAfterSchool;
        if (this.IsAfterSchool == true) {
            this.Prefix = "after_";
        }
        this.FormTarget = this.Prefix + this.FormTarget;
    },
    InitParam: function() {
        var parent = this;
        $(this.Confirmation).dialog({
            autoOpen: false,
            modal: true,
            buttons: { Close: function() { $(this).dialog("close"); } }
        });
        this.Box.dialog({
            autoOpen: false,
            modal: true,
            width: 540,
            buttons: {
                "Create": function() {
                    parent.Create(parent);
                },
                Close: function() {
                    parent.Close();
                }
            }
        });
    },
    Open: function() {
        this.DialogBox = this.Prefix + 'request_dialog';
        var parent = this;
        $('body').append('<div style="display: none;" id="' + this.DialogBox + '"></div>').ready(function() {
            $('#' + parent.DialogBox).load(parent.FormAction, function() {
                parent.Box = $('#' + parent.DialogBox + ' #' + parent.BoxTarget);
                parent.Confirmation = $('#' + parent.ConfirmationTarget);
                parent.Sufix = parent.IsAfterSchool == true ? "_after" : "";

                parent.InitParam();
                parent.Box.dialog("open").ready(function() {
                    parent.Form = $('.' + parent.FormTarget + ':visible');
                });
            });
        });

    },
    Close: function() {
        this.Box.dialog("close");
        $('#' + this.DialogBox).remove();
    },
    Create: function(parent) {
        $('.' + parent.FormTarget + ':visible').parent().parent().append(
            '<div id="processing_loader"><img src="/Images/ajax-loader-blue.gif"/>Please wait...</div>'
        );
        $('.' + parent.FormTarget).parent().parent().parent().find('.ui-dialog-buttonset').find('button').first().hide();


        var ajaxData = $('.' + this.FormTarget + ':visible').parent().find('input, select').serializeArray();
        if (this.IsAfterSchool && ajaxData[0].name == 'is_after_school') {
            ajaxData[0].value = true;
        }
        $.ajax({
            url: parent.CreateAction,
            data: ajaxData,
            dataType: "json",
            type: "POST",
            success: function(msg) {
                var content = msg.content;
                if (msg.type == 'failure') {
                    content += '<br />';
                    $.each(msg.errors, function(i, error) {
                        content += error + '<br />';
                    });
                    Message.Display(parent.ValidationTarget + parent.Sufix, content, msg.type);
                } else if (msg.type == 'success') {
                    var box = $('#' + parent.Prefix + 'school_box');
                    var name = box.find('#selected_school #' + parent.Prefix + 'school_name');
                    var id = box.find('#selected_school #' + parent.Prefix + 'school_id');
                    var address = box.find('#selected_school #' + parent.Prefix + 'school_address');
                    var label = box.find('#selected_school label');
                    var auto = $('#' + parent.Prefix + 'school_auto');

                    id.val(-1);
                    label.html('Requested ' + label.html());
                    name.html(parent.Form.find('#school_name').val());
                    auto.val(parent.Form.find('#school_name').val());
                    auto.blur();
                    address.html(parent.Form.find('#address_1').val() + ', ' + parent.Form.find('#address_2').val());

                    $(parent.HiddenSchoolId).val(0);

                    parent.Box.dialog("close");
                    parent.Confirmation.dialog("open");

                    parent.SetCookie(msg.id);
                }
                $('#processing_loader').remove();
                $('.' + parent.FormTarget).parent().parent().parent().find('.ui-dialog-buttonset').find('button').first().show();
            }
        });
    },
    SetCookie: function(id) {
        $.cookie(this.Prefix + "schoolRequest", id);
    }
};

var AjaxSchoolSearchBody = {
    AfterSchool: false,

    Prefix: "school_",
    UserTypeId: "",
    UserTypeName: "",

    SearchBox: "",
    HiddenSchoolId: "",
    ResultsBox: "",
    Targets: null,
    ClearValue: false,

    NewRequestDialog: null,

    RequestNewSchoolEnabled: true,
    RemoveAfterSchoolEnabled: true,
    PullChangeTriggerEnabled: true,

    Init: function(isAfterSchool, typeId) {
        this.AfterSchool = isAfterSchool;
        this.UserTypeId = typeId;

        this.Prefix = (this.AfterSchool == true ? "after_" : "") + this.Prefix;
        this.ResultsBox = "#" + this.Prefix + "results";
        this.Targets = { name: "#" + this.Prefix + "name", address: "#" + this.Prefix + "address", remove: "#" + this.Prefix + "remove" };
        this.RemoveAfterSchoolEnabled = this.AfterSchool;
        this.HiddenSchoolId = '#' + this.Prefix + "id";
        if (this.UserTypeId != null && this.UserTypeId != "")
            this.HiddenSchoolId = "#" + this.UserTypeId + (this.AfterSchool ? "After" : "") + "SchoolId";
        else this.HiddenSchoolId = "#" + this.Prefix + "id";

        if (this.RequestNewSchoolEnabled == true) {
            this.NewRequestDialog = new SchoolRequestDialog();
            this.NewRequestDialog.Init(this.AfterSchool, this);
        }

        this.SearchBox = 'input#' + this.UserTypeId + this.Prefix + 'auto';
        this.InitSearch();
    },
    InitSearch: function() {
        var parent = this;
        $(this.SearchBox).autocomplete({
            source: function(req, callbacks) {
                parent._Source(req, callbacks, parent);
            },
            select: function(event, ui) {
                parent._Select(event, ui, parent);
            },
            close: function() {
                if (parent.ClearValue == true) {
                    $(parent.SearchBox).val("");
                    parent.ClearValue = false;
                }
            },
            minLength: 2,
            appendTo: parent.ResultsBox
        });
    },
    _Source: function(req, callbacks, parent) {
        var search_afterschool = parent.AfterSchool;
        $.ajax({
            url: "/Schools/FindJson",
            dataType: "json",
            data: { "search.term": req.term, "search.afterschool": search_afterschool },
            success: function(data) {
                if (parent.RequestNewSchoolEnabled) {
                    data.push({
                        id: "-1",
                        value: "Can\'t find your school? Click here.",
                        label: "Can\'t find your school? Click here.",
                        address: null
                    });
                }
                callbacks(data);
            }
        });

    },
    _Select: function(event, ui, parent) {
        if (ui.item.id == '-1' && parent.RequestNewSchoolEnabled == true) {
            parent.NewRequestDialog.Open();
            parent.ClearValue = true;
            return false;
        } else {
            $(parent.HiddenSchoolId).val(ui.item.id)
            $(parent.Targets.name).html(ui.item.value);
            $(parent.Targets.address).html(ui.item.address);

            if (parent.PullChangeTriggerEnabled == true) $(parent.HiddenSchoolId).trigger('change');
            if (parent.RemoveAfterSchoolEnabled == true) $(parent.Targets.remove).show();
        }
    }
}

function AjaxSchoolSearch() { }
AjaxSchoolSearch.prototype = AjaxSchoolSearchBody;
function SchoolRequestDialog() { }
SchoolRequestDialog.prototype = SchoolRequestBody;


