//Home work copy

function PersonalSettings() {

    var self = {};

    self.verifyUserPeriodInput = function () {
        //var currentToConfirm = $('#settings_current').val();
        var currentPastToConfirm = $('#settings_current_past').val();
        var currentFutureToConfirm = $('#settings_current_future').val();
        var recentToConfirm = $('#settings_recent').val();
        var futureToConfirm = $('#settings_future').val();

        var rx = new RegExp(/^\d+$/);
        var inputCheckValid = false;
        inputCheckValid = ((rx.test(currentPastToConfirm)) && (rx.test(currentFutureToConfirm)) && (rx.test(recentToConfirm)) && (rx.test(futureToConfirm)));
        return inputCheckValid;
    }

    self.storePersonalSettings = function () {
        //$.cookie("timeperiod_current", $('#settings_current').val(), { expires: 365 });
        $.cookie("timeperiod_current_past", $('#settings_current_past').val(), { expires: 365 });
        $.cookie("timeperiod_current_future", $('#settings_current_future').val(), { expires: 365 });
        $.cookie("timeperiod_recent", $('#settings_recent').val(), { expires: 365 });
        $.cookie("timeperiod_future", $('#settings_future').val(), { expires: 365 });
        $.cookie("default_sp_store", $('#settings_availablestores :selected').val(), { expires: 365 });
        $.cookie("default_replenishmentreason", $('#settings_replenishmentreason :selected').val(), { expires: 365 });
        $.cookie("default_adjustmentreason", $('#settings_adjustmentreason :selected').val(), { expires: 365 });
        $.cookie("default_account", $('#settings_defaultaccountselection :selected').val(), { expires: 365 });
        $.cookie("joblist_sorting_direction", $('#personal_settings_job_list_sorting_section :selected').val(), { expires: 365 });
        $.cookie("remember_personal_filter_settings", $('#personal_job_list_remember_filter').prop('checked'), { expires: 365 });

        DATERANGE_RECENT = ($.cookie("timeperiod_recent")) * (-1);
        //DATERANGE_CURRENT = $.cookie("timeperiod_current");
        if ($.cookie("timeperiod_current_past") == 0) {
            DATERANGE_CURRENT_PAST = $.cookie("timeperiod_current_past");
        }
        else {
            DATERANGE_CURRENT_PAST = $.cookie("timeperiod_current_past") * (-1);
        }
        DATERANGE_CURRENT_FUTURE = $.cookie("timeperiod_current_future");
        DATERANGE_UPCOMING = $.cookie("timeperiod_future");
        DEFAULT_SELECTED_STORE = $.cookie("default_sp_store");
        DEFAULT_REPLENISHMENT_STOCK_CHANGE_REASON = $.cookie("default_replenishmentreason");
        DEFAULT_ADJUSTMENT_STOCK_CHANGE_REASON = $.cookie("default_adjustmentreason");
        DEFAULT_ACCOUNT = $.cookie("default_account");
        JOB_LIST_SORTING_ORDER = $.cookie("joblist_sorting_direction");
        REMEMBER_PERSONAL_FILTER_BETWEEN_SESSIONS = $.cookie("remember_personal_filter_settings");


    }


    self.requestStoreList = function () {
        var requester = new AjaxRequest({
            data: {}, // This is for the json request
            success: self.requestStoreListSuccess,
            error: self.requestStoreListFailure,
            url: "RequestCompleteStoreList"
        });
        requester.ExecuteRequest();

    }

    self.requestStoreListSuccess = function (data, status, xhr) {
        self.updateStoreList(data.d.StoreList);
    }



    self.requestStoreListFailure = function (request, status, error) {
        c1('personalsettings row 69: Unable to retrieve spare part store list from database.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.updateStoreList = function (storeListElements) {

        var sparePartStoreElements = '';

        //Adding element for no store selection
        sparePartStoreElements += '<option value="-1">';
        sparePartStoreElements += ReturnPhraseOnKey("settings_nostoreselected");
        sparePartStoreElements += '</option>';

        jQuery.each(storeListElements, function () {
            sparePartStoreElements += '<option value="'
            sparePartStoreElements += this.StoreId;
            sparePartStoreElements += '">';
            sparePartStoreElements += this.StoreName;
            sparePartStoreElements += '</option>';
        });

        $("#settings_availablestores").html(sparePartStoreElements);
        $("#settings_availablestores").selectmenu().selectmenu("refresh");

        var exists = false;
        $('#settings_availablestores  option').each(function () {

            if (this.value == DEFAULT_SELECTED_STORE) {
                exists = true;
            }
        });


        if (exists) {
            $('#settings_availablestores').val(DEFAULT_SELECTED_STORE).selectmenu('refresh');
        }
        else {
            $('#settings_availablestores').val(-1).selectmenu('refresh');
        }
    }

    self.initializeJobListSortingSelection = function () {
        var sortSelectorElements = '';
        sortSelectorElements += '<option value = "0">';
        sortSelectorElements += ReturnPhraseOnKey('settings_personal_joblist_sorting_ascending');
        sortSelectorElements += '</option>';
        sortSelectorElements += '<option value = "1">';
        sortSelectorElements += ReturnPhraseOnKey('settings_personal_joblist_sorting_descending');
        sortSelectorElements += '</option>';


        $("#personal_job_list_sort_order").html(sortSelectorElements);

        $("#personal_job_list_sort_order").selectmenu().val(JOB_LIST_SORTING_ORDER).selectmenu("refresh");


        //$('#settings_availablestores').val(JOB_LIST_SORTING_ORDER).selectmenu('refresh');
    }

    self.initializeRememberPersonalFilterSettingsState = function () {
        if (REMEMBER_PERSONAL_FILTER_BETWEEN_SESSIONS == "true") {
            c1('remember flag is true');
            $("#personal_job_list_remember_filter").prop("checked", true).checkboxradio("refresh");
        }
        else {
            c1('remember flag is false');
            $("#personal_job_list_remember_filter").prop("checked", false).checkboxradio("refresh");
        }
    }

    self.requestStockChangeReasonList = function () {
        var requester = new AjaxRequest({
            data: {}, // This is for the json request
            success: self.requestStockChangeReasonListSuccess,
            error: self.requestStockChangeReasonListFailure,
            url: "RequestStockChangeReasons"
        });
        requester.ExecuteRequest();

    }

    self.requestStockChangeReasonListSuccess = function (data, status, xhr) {
        self.updateStockChangeReasonLists(data.d.StockChangeReasonList);
    }

    self.requestStockChangeReasonListFailure = function (request, status, error) {
        c1('personalsettings row 126: Unable to retrieve stock change reason list from database.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.updateStockChangeReasonLists = function (stockChangeReasonsElements) {

        var reasonComboboxElements = '';

        //Adding element for no store selection
        reasonComboboxElements += '<option value="-1">';
        reasonComboboxElements += ReturnPhraseOnKey("settings_nostockchangereasonselected");
        reasonComboboxElements += '</option>';

        jQuery.each(stockChangeReasonsElements, function () {
            reasonComboboxElements += '<option value="'
            reasonComboboxElements += this.StockChangeReasonIndex;
            reasonComboboxElements += '">';
            reasonComboboxElements += this.StockChangeReasonName;
            reasonComboboxElements += '</option>';
        });


        //Update replenishment reason combobox

        $("#settings_replenishmentreason").html(reasonComboboxElements);
        $("#settings_replenishmentreason").selectmenu().selectmenu("refresh");

        var exists = false;
        $('#settings_replenishmentreason option').each(function () {

            if (this.value == DEFAULT_REPLENISHMENT_STOCK_CHANGE_REASON) {
                exists = true;
            }
        });


        if (exists) {
            $('#settings_replenishmentreason').val(DEFAULT_REPLENISHMENT_STOCK_CHANGE_REASON).selectmenu('refresh');
        }
        else {
            $('#settings_replenishmentreason').val(-1).selectmenu('refresh');
        }

        //Update adjustment reason combobox

        $("#settings_adjustmentreason").html(reasonComboboxElements);
        $("#settings_adjustmentreason").selectmenu().selectmenu("refresh");

        var exists = false;
        $('#settings_adjustmentreason option').each(function () {

            if (this.value == DEFAULT_ADJUSTMENT_STOCK_CHANGE_REASON) {
                exists = true;
            }
        });

        if (exists) {
            $('#settings_adjustmentreason').val(DEFAULT_ADJUSTMENT_STOCK_CHANGE_REASON).selectmenu('refresh');
        }
        else {
            $('#settings_adjustmentreason').val(-1).selectmenu('refresh');
        }
    };


    self.requestAccountList = function () {
        var requester = new AjaxRequest({
            data: {}, // This is for the json request
            success: self.requestAccountListSuccess,
            error: self.requestAccountListFailure,
            url: "RequestAccountList"
        });
        requester.ExecuteRequest();

    };

    self.requestAccountListSuccess = function (data, status, xhr) {
        self.updateAccountList(data.d.AccountsList);
    };

    self.requestAccountListFailure = function (request, status, error) {
        c1('personalsettings row 207: Unable to retrieve stock change reason list from database.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    };

    self.updateAccountList = function (accountsInSystem) {

        var reasonComboboxElements = '';

        //Adding element for no store selection
        reasonComboboxElements += '<option value="-1">';
        reasonComboboxElements += ReturnPhraseOnKey("settings_no_account_selected");
        reasonComboboxElements += '</option>';

        jQuery.each(accountsInSystem, function () {
            reasonComboboxElements += '<option value="'
            reasonComboboxElements += this.AccountID;
            reasonComboboxElements += '">';
            reasonComboboxElements += this.AccountName;
            reasonComboboxElements += '</option>';
        });


        //Update replenishment reason combobox

        $("#settings_defaultaccountselection").html(reasonComboboxElements);
        $("#settings_defaultaccountselection").selectmenu().selectmenu("refresh");

        var exists = false;
        $('#settings_defaultaccountselection option').each(function () {

            if (this.value == DEFAULT_ACCOUNT) {
                exists = true;
            }
        });


        if (exists) {
            $('#settings_defaultaccountselection').val(DEFAULT_ACCOUNT).selectmenu('refresh');
        }
        else {
            $('#settings_defaultaccountselection').val(-1).selectmenu('refresh');
        }

    };


    return self;

}

var personalSettings = PersonalSettings();

$(document).one("pageshow", "#page_personalsettings", function (e) {

    $("#settings_mainmenu_button").click(function (event) {

        if (personalSettings.verifyUserPeriodInput()) {

            personalSettings.storePersonalSettings();
            if ($('settings_errormessage').is(":visible")) {
                $('settings_errormessage').hide();
                $('settings_errormessage').html('');
            }

            $(":mobile-pagecontainer").pagecontainer("change", "#page_mainmenu", { role: "page", reverse: false, changeHash: true });
            e3('personalsetting row 272');
        }
        else {
            var errormessage = ReturnPhraseOnKey("settings_errormessage_inputnotvalid_1") + '<br>' + ReturnPhraseOnKey("settings_errormessage_inputnotvalid_2");
            $("#settings_errormessage").html(errormessage);
            if ($('#settings_errormessage').is(":hidden")) {
                $('#settings_errormessage').show();
            }

        }
    })
});


$(document).on("pageshow", "#page_personalsettings", function (e) {

    //$('#settings_current').hide();

    if (SessionTokenStatus == true) {
        $("#settings_errormessage").hide();

        //$('#settings_current').val(DATERANGE_CURRENT);

        if (DATERANGE_CURRENT_PAST == 0) {
            $('#settings_current_past').val(DATERANGE_CURRENT_PAST);
        }
        else {
            $('#settings_current_past').val(DATERANGE_CURRENT_PAST * (-1));
        }

        $('#settings_current_future').val(DATERANGE_CURRENT_FUTURE);
        $('#settings_recent').val(DATERANGE_RECENT * (-1));
        $('#settings_future').val(DATERANGE_UPCOMING);

        personalSettings.requestStoreList();
        personalSettings.requestStockChangeReasonList();
        personalSettings.requestAccountList();
        personalSettings.initializeJobListSortingSelection();
        personalSettings.initializeRememberPersonalFilterSettingsState();
    }
    else {
        helper.ForcedLogout();
    }

}
  );

