/* ----------------------------------------------------------------------------
 * 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 = $('#globalservicesettings-id').val();
            instance.resetForm();
            if (id !== '') {
                instance.select(id, true);
            }
        });

        /**
         * Event: Save forms Button "Click"
         */
        $('#save-forms').click(function () {
            var forms = {
                name_of_setting: $('#globalservicesettings-nameofsetting').val(),
                servicename: $('#globalservicesettings-servicename').val(),
                serviceduration: $('#globalservicesettings-serviceduration').val(),
                serviceprice: null,
                servicecurrency: null,
                servicedescription: $('#globalservicesettings-servicedescription').val(),
                serviceavailabilities_type: $('#globalservicesettings-serviceavailabilities_type').val(),
                serviceattendants_number: $('#globalservicesettings-serviceattendants_number').val(),
                servicecheckbox: $('#globalservicesettings-servicecheckbox').val(),
                servicewaitlistonofffunction: $('#globalservicesettings-servicewaitlistonofffunction').val(),
                servicewaitlist_confirm_email_header: $('#globalservicesettings-servicewaitlist_confirm_email_header').val(),
                servicewaitlist_confirm_email_desc: $('#globalservicesettings-servicewaitlist_confirm_email_desc').val(),
                servicewaitlist_reminder_email_header: $('#globalservicesettings-servicewaitlist_reminder_email_header').val(),
                servicewaitlist_reminder_email_desc: $('#globalservicesettings-servicewaitlist_reminder_email_desc').val(),
                servicewaitlist_doses: $('#globalservicesettings-servicewaitlist_doses').val(),
                servicewaitlist_percentage: $('#globalservicesettings-servicewaitlist_doses_percentage').val(),
                servicewaitlist_timetobook: $('#globalservicesettings-servicewaitlist_time_to_book').val(),
                servicewaitlist_doses_date: $('#globalservicesettings-servicewaitlist_doses_date').val(),
                servicesmsonoff: $('#globalservicesettings-servicesmsonoff').val(),
                servicesms_confirmation_message: $('#globalservicesettings-servicesms_confirmation_message').val(),
                servicesms_delete_message: $('#globalservicesettings-servicesms_delete_message').val(),
                serviceprovider_subject_email: $('#globalservicesettings-serviceprovider_subject_email').val(),
                serviceprovider_description_email: $('#globalservicesettings-serviceprovider_description_email').val(),
                servicecustomer_subject_email: $('#globalservicesettings-servicecustomer_subject_email').val(),
                servicecustomer_description_email: $('#globalservicesettings-servicecustomer_description_email').val(),
                servicereminder_on_off: $('#globalservicesettings-servicereminder_on_off').val(),
                serviceemail_reminder_subject: $('#globalservicesettings-serviceemail_reminder_subject').val(),
                serviceemail_reminder_description: $('#globalservicesettings-serviceemail_reminder_description').val(),
                servicetext_reminder_description: $('#globalservicesettings-servicetext_reminder_description').val(),
                servicereminder_on_off_two: $('#globalservicesettings-servicereminder_on_off_two').val(),
                serviceemail_reminder_subject_two: $('#globalservicesettings-serviceemail_reminder_subject_two').val(),
                serviceemail_reminder_description_two: $('#globalservicesettings-serviceemail_reminder_description_two').val(),
                servicetext_reminder_description_two: $('#globalservicesettings-servicetext_reminder_description_two').val(),
                servicereminder_on_off_three: $('#globalservicesettings-servicereminder_on_off_three').val(),
                serviceemail_reminder_subject_three: $('#globalservicesettings-serviceemail_reminder_subject_three').val(),
                serviceemail_reminder_description_three: $('#globalservicesettings-serviceemail_reminder_description_three').val(),
                servicetext_reminder_description_three: $('#globalservicesettings-servicetext_reminder_description_three').val(),
                form: $('#globalservicesettings-selectform').val(),
                minimummaxonoff: $('#globalservicesettings-minmax').val(),
                minimum: $('#globalservicesettings-minimum').val(),
                maximum: $('#globalservicesettings-maximum').val(),
                
                openclosed: $('#globalservicesettings-openclosed').val(),

            };

 if($('#globalservicesettings-category').val()===''){
                forms.servicecategory = null; 
 }else{
                     forms.servicecategory = $('#globalservicesettings-category').val(); 

 }
                
            if ($('#globalservicesettings-id').val() !== '') {
                forms.id = $('#globalservicesettings-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 = $('#globalservicesettings-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_globalservicesettings';
        var postData = {
            csrfToken: GlobalVariables.csrfToken,
            forms: JSON.stringify(forms)
        };

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

            Backend.displayNotification('Service Global Setting 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_globalservicesettings';
        var postData = {
            csrfToken: GlobalVariables.csrfToken,
            form_id: formsId
        };

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

            Backend.displayNotification('Global Setting 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) {
        $('#globalservicesettings-id').val(forms.id);
        $('#globalservicesettings-nameofsetting').val(forms.name_of_setting);
        $('#globalservicesettings-servicename').val(forms.servicename);
            $('#globalservicesettings-serviceduration').val(forms.serviceduration);

            $('#globalservicesettings-servicedescription').val(forms.servicedescription);
            $('#globalservicesettings-serviceavailabilities_type').val(forms.serviceavailabilities_type);
            $('#globalservicesettings-serviceattendants_number').val(forms.serviceattendants_number);
       $('#globalservicesettings-servicecheckbox').val(forms.servicecheckbox);

            $('#globalservicesettings-servicewaitlistonofffunction').val(forms.servicewaitlistonofffunction);
            $('#globalservicesettings-servicewaitlist_reminder_email_header').val(forms.servicewaitlist_reminder_email_header);
            $('#globalservicesettings-servicewaitlist_reminder_email_desc').val(forms.servicewaitlist_reminder_email_desc);
         $('#globalservicesettings-servicewaitlist_doses_date').val(forms.servicewaitlist_doses_date);
            $('#globalservicesettings-servicewaitlist_doses').val(forms.servicewaitlist_doses);
            $('#globalservicesettings-servicewaitlist_doses_percentage').val(forms.servicewaitlist_percentage);
            $('#globalservicesettings-servicewaitlist_time_to_book').val(forms.servicewaitlist_timetobook);

            $('#globalservicesettings-servicesmsonoff').val(forms.servicesmsonoff);
            $('#globalservicesettings-servicesms_confirmation_message').val(forms.servicesms_confirmation_message);
            $('#globalservicesettings-servicesms_delete_message').val(forms.servicesms_delete_message);
            $('#globalservicesettings-serviceprovider_subject_email').val(forms.serviceprovider_subject_email);
            $('#globalservicesettings-serviceprovider_description_email').val(forms.serviceprovider_description_email);
            $('#globalservicesettings-servicecustomer_subject_email').val(forms.servicecustomer_subject_email);
            $('#globalservicesettings-servicecustomer_description_email').val(forms.servicecustomer_description_email);
            $('#globalservicesettings-servicereminder_on_off').val(forms.servicereminder_on_off);
            $('#globalservicesettings-serviceemail_reminder_subject').val(forms.serviceemail_reminder_subject);
            $('#globalservicesettings-serviceemail_reminder_description').val(forms.serviceemail_reminder_description);
            $('#globalservicesettings-servicetext_reminder_description').val(forms.servicetext_reminder_description);
            $('#globalservicesettings-servicereminder_on_off_two').val(forms.servicereminder_on_off_two);
            $('#globalservicesettings-serviceemail_reminder_subject_two').val(forms.serviceemail_reminder_subject_two);
            $('#globalservicesettings-serviceemail_reminder_description_two').val(forms.serviceemail_reminder_description_two);
            $('#globalservicesettings-servicetext_reminder_description_two').val(forms.servicetext_reminder_description_two);
            $('#globalservicesettings-servicereminder_on_off_three').val(forms.servicereminder_on_off_three);
            $('#globalservicesettings-serviceemail_reminder_subject_three').val(forms.serviceemail_reminder_subject_three);
            $('#globalservicesettings-serviceemail_reminder_description_three').val(forms.serviceemail_reminder_description_three);
            $('#globalservicesettings-servicetext_reminder_description_three').val(forms.servicetext_reminder_description_three);
        $('#globalservicesettings-selectform').val(forms.form);
           $('#globalservicesettings-minmax').val(forms.minimummaxonoff);
            $('#globalservicesettings-minimum').val(forms.minimum);
            $('#globalservicesettings-maximum').val(forms.maximum);
        $('#globalservicesettings-category').val(forms.servicecategory);
        $('#globalservicesettings-openclosed').val(forms.openclosed);


    };

    /**
     * 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_globalservicesettings';
        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.name_of_setting + '</strong><br>' +
            'Name: '+forms.servicename + '<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;
})();
