/* ----------------------------------------------------------------------------
 * Easy!Appointments - Open Source Web Scheduler
 *
 * @package     EasyAppointments
 * @author      A.Tselegidis <alextselegidis@gmail.com>
 * @copyright   Copyright (c) 2013 - 2018, Alex Tselegidis
 * @license     http://opensource.org/licenses/GPL-3.0 - GPLv3
 * @link        http://easyappointments.org
 * @since       v1.0.0
 * ---------------------------------------------------------------------------- */

(function () {

    'use strict';

    /**
     * FormDirectoryHelper
     *
     * This class contains the methods that will be used by the "forms" tab of the page.
     *
     * @class FormDirectoryHelper
     */
    function FormDirectoryHelper() {
        this.filterResults = {};

    }

    FormDirectoryHelper.prototype.bindEventHandlers = function () {
        var instance = this;

        /**
         * Event: Filter formss Form "Submit"
         *
         * @param {jQuery.Event} event
         */



        $('#filter-forms form').submit(function (event) {
            var key = $('#filter-formss .key').val();
            $('#filter-forms .selected').removeClass('selected');
            instance.resetForm();
            instance.filter(key);
            return false;
        });

        /**
         * Event: Filter forms Cancel Button "Click"
         */
        $('#filter-forms .clear').click(function () {
            $('#filter-forms .key').val('');
            instance.filter('');
            instance.resetForm();
        });

        /**
         * Event: Filter Forms Row "Click"
         *
         * Display the selected Forms data to the user.
         */
        $(document).on('click', '.forms-row', function () {
            if ($('#filter-forms .filter').prop('disabled')) {
                $('#filter-forms .results').css('color', '#AAA');
                return; // exit because we are on edit mode
            }

            var formsId = $(this).attr('data-id');
            var forms = {};
            $.each(instance.filterResults, function (index, item) {
                if (item.id === formsId) {
                    forms = item;
                    return false;
                }
            });

            // Add dedicated provider link.
            var dedicatedUrl = GlobalVariables.baseUrl + '/index.php?forms=' + encodeURIComponent(forms.hash_id)+'|'+encodeURIComponent(forms.id);
            var linkHtml = '<a href="' + dedicatedUrl + '"><span class="glyphicon glyphicon-link"></span></a>';
            $('#formss .record-details h3')
                .find('a')
                .remove()
                .end()
                .append(linkHtml);

            instance.display(forms);
            $('#filter-forms .selected').removeClass('selected');
            $(this).addClass('selected');
            $('#edit-forms, #delete-forms').prop('disabled', false);

        });

        /**
         * Event: Add New forms Button "Click"
         */
        $('#add-forms').click(function () {
            instance.resetForm();
            $('#forms .add-edit-delete-group').hide();
            $('#forms .save-cancel-group').show();
            $('#forms .record-details').find('input, textarea').prop('readonly', false);
            $('#forms .record-details').find('select').prop('disabled', false);
            $('#filter-forms button').prop('disabled', true);
            $('#filter-forms .results').css('color', '#AAA');
        });

        /**
         * Event: Cancel forms Button "Click"
         *
         * Cancel add or edit of a forms record.
         */
        $('#cancel-forms').click(function () {
            var id = $('#globalcompanysetting-id').val();
            instance.resetForm();
            if (id !== '') {
                instance.select(id, true);
            }
        });

        /**
         * Event: Save forms Button "Click"
         */
        $('#save-forms').click(function () {
            var forms = {
                companyfirst_name: $('#globalcompanysetting-first-name').val(),
                companylast_name: $('#globalcompanysetting-last-name').val(),
                companymobile_number: $('#globalcompanysetting-mobile-number').val(),
                companyphone_number: $('#globalcompanysetting-phone-number').val(),
                companyaddress: $('#globalcompanysetting-address').val(),
                companycity: $('#globalcompanysetting-city').val(),
                companystate: $('#globalcompanysetting-state').val(),
                companyzip_code: $('#globalcompanysetting-zip-code').val(),
                companynotes: $('#globalcompanysetting-notes').val(),
                companybackgroundcolor: $('#globalcompanysetting-backgroundcolor').val(),
                companytopheader: $('#globalcompanysetting-topheader').val(),
                companylogolink: $('#globalcompanysetting-logolink').val(),
                companywidth: $('#globalcompanysetting-width').val(),
                companyleng: $('#globalcompanysetting-leng').val()

            };


            if ($('#globalcompanysetting-id').val() !== '') {
                forms.id = $('#globalcompanysetting-id').val();
            }

            if (!instance.validate()) {
                return;
            }

            instance.save(forms);
        });

        /**
         * Event: Edit forms Button "Click"
         */
        $('#edit-forms').click(function () {
            $('#forms .add-edit-delete-group').hide();
            $('#forms .save-cancel-group').show();
            $('#forms .record-details').find('input, textarea').prop('readonly', false);
            $('#forms .record-details select').prop('disabled', false);

            $('#filter-forms button').prop('disabled', true);
            $('#filter-forms .results').css('color', '#AAA');
        });

        /**
         * Event: Delete forms Button "Click"
         */
        $('#delete-forms').click(function () {
            var formsId = $('#globalcompanysetting-id').val();
            var buttons = [
                {
                    text: EALang.delete,
                    click: function () {
                        instance.delete(formsId);
                        $('#message_box').dialog('close');
                    }
                },
                {
                    text: EALang.cancel,
                    click: function () {
                        $('#message_box').dialog('close');
                    }
                }
            ];

            GeneralFunctions.displayMessageBox(EALang.delete,
                EALang.delete_record_prompt, buttons);
        });
    };


    /**
     * Save forms record to database.
     *
     * @param {Object} forms Contains the forms record data. If an 'id' value is provided
     * then the update operation is going to be executed.
     */
    FormDirectoryHelper.prototype.save = function (forms) {
        var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_globalcompanysettings';
        var postData = {
            csrfToken: GlobalVariables.csrfToken,
            forms: JSON.stringify(forms)
        };

        $.post(postUrl, postData, function (response) {
            if (!GeneralFunctions.handleAjaxExceptions(response)) {
                return;
            }

            Backend.displayNotification(EALang.services_saved);
            this.resetForm();
            $('#filter-forms .key').val('');
            this.filter('', response.id, true);
        }.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler);
    };

    /**
     * Delete a forms record from database.
     *
     * @param {Number} id Record ID to be deleted.
     */

    FormDirectoryHelper.prototype.delete = function (formsId) {
        var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_globalcompanysettings';
        var postData = {
            csrfToken: GlobalVariables.csrfToken,
            form_id: formsId
        };

        $.post(postUrl, postData, function (response) {
            if (!GeneralFunctions.handleAjaxExceptions(response)) {
                return;
            }

            Backend.displayNotification(EALang.forms_deleted);

            this.resetForm();
            this.filter($('#filter-forms .key').val());
        }.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler);
    };

    /**
     * Validates a forms record.
     *
     * @return {Boolean} Returns the validation result.
     */
    FormDirectoryHelper.prototype.validate = function () {
        $('#forms .has-error').removeClass('has-error');

        try {
            // validate required fields.
            var missingRequired = false;

            $('#formss .required').each(function () {
                if ($(this).val() == '' || $(this).val() == undefined) {
                    $(this).closest('.form-group').addClass('has-error');
                    missingRequired = true;
                }
            });

            if (missingRequired) {
                throw EALang.fields_are_required;
            }


            return true;
        } catch (exc) {
            return false;
        }
    };

    /**
     * Resets the forms tab form back to its initial state.
     */
    FormDirectoryHelper.prototype.resetForm = function () {
        $('#forms .record-details').find('input, textarea').val('');
        $('#forms .add-edit-delete-group').show();
        $('#forms .save-cancel-group').hide();
        $('#edit-forms, #delete-forms').prop('disabled', true);
        $('#forms .record-details').find('input, textarea').prop('readonly', true);
        $('#forms .record-details').find('select').prop('disabled', true);
        $('#filter-forms .selected').removeClass('selected');
        $('#filter-forms button').prop('disabled', false);
        $('#filter-forms .results').css('color', '');
    };

    /**
     * Display a forms record into the forms form.
     *
     * @param {Object} forms Contains the forms record data.
     */
    FormDirectoryHelper.prototype.display = function (forms) {
        $('#globalcompanysetting-id').val(forms.id);
        $('#globalcompanysetting-first-name').val(forms.companyfirst_name);
        $('#globalcompanysetting-last-name').val(forms.companylast_name);
        $('#globalcompanysetting-mobile-number').val(forms.companymobile_number);
        $('#globalcompanysetting-phone-number').val(forms.companyphone_number);
        $('#globalcompanysetting-address').val(forms.companyaddress);
        $('#globalcompanysetting-city').val(forms.companycity);
        $('#globalcompanysetting-state').val(forms.companystate);
         $('#globalcompanysetting-zip-code').val(forms.companyzip_code);
         $('#globalcompanysetting-notes').val(forms.companynotes);
         $('#globalcompanysetting-backgroundcolor').val(forms.companybackgroundcolor);
         $('#globalcompanysetting-topheader').val(forms.companytopheader);
         $('#globalcompanysetting-logolink').val(forms.companylogolink);
          $('#globalcompanysetting-width').val(forms.companywidth);
          $('#globalcompanysetting-leng').val(forms.companyleng);
    };

    /**
     * Filters forms records depending a string key.
     *
     * @param {String} key This is used to filter the forms records of the database.
     * @param {Number} selectId Optional, if set then after the filter operation the record with this
     * ID will be selected (but not displayed).
     * @param {Boolean} display Optional (false), if true then the selected record will be displayed on the form.
     */
    FormDirectoryHelper.prototype.filter = function (key, selectId, display) {
        display = display || false;

        var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_globalcompanysettings';
        var postData = {
            csrfToken: GlobalVariables.csrfToken,
            key: key
        };

        $.post(postUrl, postData, function (response) {
            if (!GeneralFunctions.handleAjaxExceptions(response)) {
                return;
            }

            this.filterResults = response;

            $('#filter-forms .results').html('');
            $.each(response, function (index, forms) {
                var html = FormDirectoryHelper.prototype.getFilterHtml(forms);
                $('#filter-forms .results').append(html);
            });

            if (response.length === 0) {
                $('#filter-forms .results').html('<em>' + EALang.no_records_found + '</em>');
            }

            if (selectId !== undefined) {
                this.select(selectId, display);
            }
        }.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler);
    };

    /**
     * Get Filter HTML
     *
     * Get a forms row HTML code that is going to be displayed on the filter results list.
     *
     * @param {Object} forms Contains the forms record data.
     *
     * @return {String} The HTML code that represents the record on the filter results list.
     */
    FormDirectoryHelper.prototype.getFilterHtml = function (forms) {
        var html =
            '<div class="forms-row entry" data-id="' + forms.id + '">' +
            '<strong>' + forms.companyfirst_name+' '+forms.companylast_name + '</strong><br>' +
            forms.companyaddress + '<br>' +
            '</div><hr>';

        return html;
    };

    /**
     * Select a specific record from the current filter results. If the forms id does not exist
     * in the list then no record will be selected.
     *
     * @param {Number} id The record id to be selected from the filter results.
     * @param {Boolean} display Optional (false), if true then the method will display the record on the form.
     */
    FormDirectoryHelper.prototype.select = function (id, display) {
        display = display || false;

        $('#filter-forms .selected').removeClass('selected');

        $('#filter-forms .forms-row').each(function () {
            if ($(this).attr('data-id') == id) {
                $(this).addClass('selected');
                return false;
            }
        });

        if (display) {
            $.each(this.filterResults, function (index, forms) {
                if (forms.id == id) {
                    this.display(forms);
                    $('#edit-forms, #delete-forms').prop('disabled', false);
                    return false;
                }
            }.bind(this));
        }
    };

    window.FormDirectoryHelper = FormDirectoryHelper;
})();
