const STEP_FINISHED = 1000; const MIN_INPUT_LENGTH = 5; const MIN_PHONE_LENGTH = 9; const MIN_WEB_SITE_LENGTH = 5; const MIN_YOUTUBE_LENGTH = 10; const MIN_FACEBOOK_LENGTH = 10; const MIN_LONG_DESCRIPTION_LENGTH = 20; const MAX_ACTION_BUTTON_LENGTH = 75; const CHECK_ERRORS = true; const BUSINESS_STATUS_ACTIVE = 1; function BusinessAddWizard(json_content) { object = this; this.supportedLanguages = ["ru", "ua", "en", "fr", "he"]; var urlParams = new URLSearchParams(window.location.search); this.category_id = VarAsInt(urlParams.get('category_id')); this.root_category_id = VarAsInt(urlParams.get('root_category_id')); this.show_errors = false; this.urls_manager = null; this.phones_manager = null; this.validation_error = ""; // this.cities_manager = null; this.uploaded_file = null; this.save_validating = false; this.first_unfilled_control = null; this.steps_containers_array = []; if (this.SupportsCategoryContainers()) this.steps_containers_array = this.steps_containers_array.concat(["business-root-category-container", "business-sub-category-container"]); for (let i = 0; i < this.supportedLanguages.length; i++) { this.steps_containers_array = this.steps_containers_array.concat([ "business-title-container-" + this.supportedLanguages[i], "business-description-container-" + this.supportedLanguages[i]]); } this.steps_containers_array = this.steps_containers_array.concat([ "business-unique-id-container", "business-phones-container", "business-phone-visibility-container", "business-address-container", "business-urls-container", "business-action-button-container", "business-cities-container"]); this.UpdateCoverVisibility(false); this.business_id = VarAsInt($("#business_id").val()); // this.initializeDescriptionCKEditor('business-desc-ru'); this.Initialize(json_content); this.initializeCKEditorForLangRecursively(0); } BusinessAddWizard.prototype.initializeCKEditorForLangRecursively = function(langIndex) { let _this = this; this.initializeDescriptionCKEditor('business-desc-' + this.supportedLanguages[langIndex], function() { if (langIndex == (_this.supportedLanguages.length - 1)) _this.InitializeInterface(); else _this.initializeCKEditorForLangRecursively(langIndex + 1); }); } BusinessAddWizard.prototype.initializeDescriptionCKEditor = function(elementID, callback) { let ckeditor = CKEDITOR.replace(elementID, {height: "400px"}); ckeditor.on('change', function(evt) { var data = ckeditor.getData(); $("#" + elementID).val(data); object.InitializeInterface(); }); ckeditor.on('instanceReady', function() { if (callback) callback(); }); } BusinessAddWizard.prototype.IsEditing = function() { return (this.business_id > 0); } BusinessAddWizard.prototype.IsAdding = function() { return (!this.IsEditing()); } BusinessAddWizard.prototype.IsCategoryFilled = function() { var result = (this.category_id > 0); result = result || (this.root_category_id > 0); result = result && (this.IsAdding()); return result; } BusinessAddWizard.prototype.IsMandatoryControl = function(control) { return (!$(control).hasClass("not-mandatory-field")) } BusinessAddWizard.prototype.InitializeURLsManager = function() { var object = this; var on_change_urls = function (sender){ object.InitializeInterface(); }; this.urls_manager = new PrototypeMultiManager("#business-urls-container-parent", "#business-urls-prototype", "#business-url-add", "#business-url-remove", "#business-url-caption", "#business-url"); this.urls_manager.AddItem(); this.urls_manager.OnAdd(on_change_urls); this.urls_manager.OnRemove(on_change_urls); } BusinessAddWizard.prototype.AddURLEntry = function() { this.urls_manager.AddItem(); } BusinessAddWizard.prototype.InitializePhonesManager = function() { var object = this; var on_change_phones = function (sender){ object.InitializeInterface(); }; this.phones_manager = new PrototypeMultiManager("#business-phones-container-parent", "#business-phones-prototype", "#business-phone-add", "#business-phone-remove", "#business-phone-caption", "#business-phone"); this.phones_manager.AddItem(); this.phones_manager.OnAdd(on_change_phones); this.phones_manager.OnRemove(on_change_phones); } BusinessAddWizard.prototype.InitializeCitiesManager = function() { /* var object = this; var on_change_cities = function (sender){ object.InitializeInterface(); }; this.cities_manager = new PrototypeMultiManager("#business-cities-parent", "#business-cities-prototype", "", "", "", ""); this.cities_manager.AddItem(); this.cities_manager.OnAdd(on_change_cities); this.cities_manager.OnRemove(on_change_cities); */ } BusinessAddWizard.prototype.AddPhoneEntry = function() { this.phones_manager.AddItem(); } BusinessAddWizard.prototype.AddSelectBoxOption = function(selectBox, item_caption, item_value) { var newOption = document.createElement('option'); var optionText = document.createTextNode(item_caption); newOption.appendChild(optionText); newOption.setAttribute('value', item_value); selectBox.appendChild(newOption); } BusinessAddWizard.prototype.AddCityEntry = function() { // this.cities_manager.AddItem(); } BusinessAddWizard.prototype.FillSubCategoriesOptionsList = function() { var object = this; var selectBox = document.querySelector('#items-sub-category'); $(selectBox).empty(); object.AddSelectBoxOption(selectBox, "Выберите значение из списка...", ""); var root_category = GetSelectBoxValue("#items-root-category"); if (root_category > 0) { var url = GetBaseURL() + "?mode=sub_categories_list_ajax" + "&parent_category=" + root_category + '&rand=' + Math.random(); $.ajax({ url: url, async: false, type: "GET" }).done(function(response) { if (response) { var subcategories_tests = JSON.parse(response); for (var i = 0; i < subcategories_tests.length; i++) { object.AddSelectBoxOption(selectBox, subcategories_tests[i].title, subcategories_tests[i].id); } object.InitializeInterface(); } }); } } BusinessAddWizard.prototype.AddSelectOptions = function(select_control, option_text, option_value) { var option = document.createElement("option"); option.text = option_text; option.value = option_value; $(select_control)[0].appendChild(option); } BusinessAddWizard.prototype.UpdateVisibility = function(control, is_visible) { if (control) { if (is_visible) $(control).show(); else $(control).hide(); } } BusinessAddWizard.prototype.DoShowContainer = function(step) { this.UpdateVisibility("#" + step, this.IsStepVisible(step)); } BusinessAddWizard.prototype.DoHideContainer = function(step) { this.UpdateVisibility("#" + step, this.IsStepVisible(step)); } BusinessAddWizard.prototype.UpdateValidationError = function(error_text, force) { if ((force) || (this.validation_error == "")) { this.validation_error = error_text; } // $("#validation-error-label").html(this.validation_error); if ((this.validation_error != "") && (this.save_validating)) { if (this.show_errors) { // alert(this.validation_error); UniversalModalDialog.showModalDialog("Ошибка!", this.validation_error, "Закрыть"); } } } BusinessAddWizard.prototype.AddControlCssClass = function(control, css_class) { $(control).addClass(css_class); var control_id = $(control).attr("id"); if ((control_id) && (control_id.indexOf("business-desc") >= 0)) { if ((CKEDITOR.instances[control_id]) && (CKEDITOR.instances[control_id].document)) { var elem = document.querySelector('.' + css_class); var style = getComputedStyle(elem); CKEDITOR.instances[control_id].document.getBody().setStyle('background-color', style["background-color"]); } } } BusinessAddWizard.prototype.ChangeControlBackgroundColorInternal = function(control, is_filled, is_error) { $(control).removeClass("error-control-value"); $(control).removeClass("filled-control-value"); $(control).removeClass("unknown-control-value"); if (is_filled) this.AddControlCssClass(control, 'filled-control-value'); else if (is_error) this.AddControlCssClass(control, 'error-control-value'); else this.AddControlCssClass(control, 'unknown-control-value'); } BusinessAddWizard.prototype.ChangeControlBackgroundColor = function(control) { var is_filled = this.IsStepElementFilled(control); var is_valid = this.StepElementCanBeSaved(control); this.ChangeControlBackgroundColorInternal(control, (is_filled) && (is_valid), (!is_valid) && (this.save_validating) && (this.show_errors)); } BusinessAddWizard.prototype.ChangeInputControlStyle = function() { var object = this; $("#business-info select, #business-info textarea, #business-info input, .btn-group-member").each(function() { if (!$(this).hasClass("skip-background")) object.ChangeControlBackgroundColor(this); }); } BusinessAddWizard.prototype.IsStepVisible = function(step) { var result = true; return result; } BusinessAddWizard.prototype.AnalyzeSupportedLanguageAndShowError = function(isSupported, messageText) { if (!isSupported) { this.first_unfilled_control = "#languageTabsList"; UniversalModalDialog.showModalDialog("Ошибка!", messageText, "Закрыть"); } return isSupported; } BusinessAddWizard.prototype.AnalyzeAnySupportedLanguage = function() { return this.AnalyzeSupportedLanguageAndShowError(this.IsAnyLanguageSupported(), "Вы должны указать хотя бы один язык, на котором вы оказываете услуги"); } BusinessAddWizard.prototype.AnalyzeRussianSupportedLanguage = function() { return this.AnalyzeSupportedLanguageAndShowError(this.IsLanguageSupported("ru"), "Вы должны подтвердить, что оказываете услуги на русском языке. На данный момент мы добавляем только русскоязычные услуги"); } BusinessAddWizard.prototype.AnalyzeActionButtonCaption = function() { let result = this.IsActionButtonCaptionValid(); if (!result) { this.first_unfilled_control = "#action-button-caption"; UniversalModalDialog.showModalDialog("Ошибка!", "Длинна текста кнопки действия не может быть больше {0} символов".format(MAX_ACTION_BUTTON_LENGTH), "Закрыть"); } return result; } BusinessAddWizard.prototype.IsSaveAvailable = function() { let current_step = this.GetCurrentStepIndex(); let result = (current_step == STEP_FINISHED); result = result && (this.AnalyzeRussianSupportedLanguage()); result = result && (this.AnalyzeAnySupportedLanguage()); result = result && (this.AnalyzeActionButtonCaption()); return result; } BusinessAddWizard.prototype.CheckElementLength = function(element, error_text, min_length) { var element_value = GetTextBoxValue(element); if ((element_value) && (element_value != "") && (element_value.length < min_length)) { this.UpdateValidationError(error_text, false); return false; } return true; } BusinessAddWizard.prototype.CheckElementExistingText = function(element, error_text, text) { var element_value = GetTextBoxValue(element); if (element_value != "") { text = text.toLowerCase(); element_value = element_value.toLowerCase(); var n = element_value.indexOf(text); if (n < 0) { this.UpdateValidationError(error_text, false); return false; } } return true; } BusinessAddWizard.prototype.CheckBusinessName = function(element, checkElement) { if ($(checkElement).is(":checked")) return this.CheckElementLength(element, "Слишком короткое название услуги", MIN_INPUT_LENGTH); return true; } BusinessAddWizard.prototype.CheckBusinessLongDescription = function(element, checkElement) { if ($(checkElement).is(":checked")) { return this.CheckElementLength(element, "Слишком короткое детальное описание услуги", MIN_LONG_DESCRIPTION_LENGTH); } return true; } BusinessAddWizard.prototype.CheckBusinessPhone = function(element) { var result = this.CheckElementLength(element, "Слишком короткий номер телефона", MIN_PHONE_LENGTH); if (result == true) { var phone_validation_status = ValidatePhoneNumber(GetTextBoxValue(element)); if (phone_validation_status != PHONE_OK) { this.UpdateValidationError(PhoneValidationStatusToDescription(phone_validation_status), false); result = false; } } return result; } BusinessAddWizard.prototype.CheckBusinessWebsiteURL = function(element) { var result = this.CheckElementLength(element, "Cсылка на сайт указана не верно", MIN_WEB_SITE_LENGTH); return result; } BusinessAddWizard.prototype.ModifyElementIDForAnalyzingByPrototypeManager = function(element_id, prototype_manager, prototype_name) { if (element_id) { var prototype_pos = element_id.indexOf(prototype_name); if (prototype_pos == 0) { prototype_pos += prototype_name.length; var index_str = element_id.substring(prototype_pos, element_id.length); if ((isNumber(index_str)) && (prototype_manager.HasElementWithIndex(parseInt(index_str)))) { return prototype_name; } return ""; } } return element_id; } BusinessAddWizard.prototype.GetElementIDForAnalyzing = function(element_id) { var result = element_id; if (result) { result = this.ModifyElementIDForAnalyzingByPrototypeManager(result, this.phones_manager, "business-phone"); result = this.ModifyElementIDForAnalyzingByPrototypeManager(result, this.urls_manager, "business-url"); } return result; } BusinessAddWizard.prototype.IsElementValid = function(element) { if (CHECK_ERRORS) { var element_id = $(element).attr("id"); element_id = this.GetElementIDForAnalyzing(element_id); if (element_id) { // console.log(element_id); switch (element_id) { case "action-button-caption": return this.IsActionButtonCaptionValid(); // case "business-title": return this.CheckBusinessName(element); case "business-title-ru": return this.CheckBusinessName(element, "#business-is-language-supported-ru"); case "business-title-ua": return this.CheckBusinessName(element, "#business-is-language-supported-ua"); case "business-title-en": return this.CheckBusinessName(element, "#business-is-language-supported-en"); case "business-title-fr": return this.CheckBusinessName(element, "#business-is-language-supported-fr"); case "business-title-he": return this.CheckBusinessName(element, "#business-is-language-supported-he"); case "business-phone": return this.CheckBusinessPhone(element); case "business-url": return this.CheckBusinessWebsiteURL(element); // case "business-desc": return this.CheckBusinessLongDescription(element); case "business-desc-ru": return this.CheckBusinessLongDescription(element, "#business-is-language-supported-ru"); case "business-desc-ua": return this.CheckBusinessLongDescription(element, "#business-is-language-supported-ua"); case "business-desc-en": return this.CheckBusinessLongDescription(element, "#business-is-language-supported-en"); case "business-desc-fr": return this.CheckBusinessLongDescription(element, "#business-is-language-supported-fr"); case "business-desc-he": return this.CheckBusinessLongDescription(element, "#business-is-language-supported-he"); default: return true; } } } return true; } BusinessAddWizard.prototype.IsStepElementFilled = function(element) { // check is input/select really filled if (IsButtonGroupMember(element)) { return IsButtonGroupSelected($(element).parent()); } if (element.tagName) { if (element.tagName.toLowerCase() == "select") { return IsSelectBoxFilled(element); } if (element.tagName.toLowerCase() == "textarea") { return IsTextBoxFilled(element); } if (element.tagName.toLowerCase() == "input") { return IsInputFilled(element); } } return true; } BusinessAddWizard.prototype.StepElementCanBeSaved = function(element) { // check is input/select really filled var result = true; if (this.IsMandatoryControl(element)) result = this.IsStepElementFilled(element); if (this.save_validating) result &= this.IsElementValid(element); return result; } BusinessAddWizard.prototype.IsVirtualContainer = function(element) { return ($(element).hasClass("virtual-container")); } BusinessAddWizard.prototype.EnumerateStepElementsParent = function(step, element, check_parent) { var result = true; var object = this; var is_virtual_container = false; if (check_parent) is_virtual_container = this.IsVirtualContainer(element); var is_protype = ($(element).hasClass("prototype")); if (!is_protype) { // enumerate all nesting divs of given step $(element).children().each(function (child_div_index, child_div) { var is_hidden = $(child_div).hasClass("hidden-container"); var is_child_virtual_container = object.IsVirtualContainer(child_div); if (!is_hidden) { if (is_virtual_container) { result &= object.EnumerateStepElementsParent(step, child_div, true); } else if (is_child_virtual_container) { result &= object.EnumerateStepElementsParent(step, child_div, false); } else { result &= object.EnumerateStepElements(step, child_div); } if (!result) return; } }); } return result; } BusinessAddWizard.prototype.EnumerateStepElements = function(step, element) { var result = true; var object = this; $(element).children().each(function (index, child) { var dom_element = $(child).get(0); result = result && (object.StepElementCanBeSaved(dom_element)); if (!result) { if (object.first_unfilled_control == null) object.first_unfilled_control = dom_element; return result; } }); return result; } BusinessAddWizard.prototype.IsStepFilled = function(step) { if (this.IsStepVisible(step)) { var children_containers_selector = "#" + step; var result = this.EnumerateStepElementsParent(step, children_containers_selector, true); return result; } return true; } BusinessAddWizard.prototype.GetCurrentStepIndex = function() { this.first_unfilled_control = null; for (var i = 0; i < this.steps_containers_array.length; i++) { // console.log("current step: " + this.steps_containers_array[i] + "; is Filled: " + this.IsStepFilled(this.steps_containers_array[i])); if (!this.IsStepFilled(this.steps_containers_array[i])) return i; } return STEP_FINISHED; } BusinessAddWizard.prototype.UpdateBusinessControlBackgroundColor = function(control) { $(control).removeClass("error-control-value"); $(control).removeClass("filled-control-value"); (this.GetBusinessStatus() == BUSINESS_STATUS_ACTIVE) ? $(control).addClass("filled-control-value") : $(control).addClass("error-control-value"); } BusinessAddWizard.prototype.GetBusinessStatus = function() { return GetSelectBoxValue("#business-status"); } BusinessAddWizard.prototype.UpdateBusinessVisibilityStatus = function() { var object = this; this.UpdateBusinessControlBackgroundColor("#business-status"); (this.GetBusinessStatus() == BUSINESS_STATUS_ACTIVE) ? $("#business-status-visible").hide() : $("#business-status-visible").show(); $("#business-status > option").each(function() { object.UpdateBusinessControlBackgroundColor(this); }); } BusinessAddWizard.prototype.InitializeInterface = function() { var current_step = this.GetCurrentStepIndex(); var is_save_visible = (current_step == STEP_FINISHED); this.save_validating = false; this.UpdateValidationError("", true); this.ChangeInputControlStyle(); this.UpdateBusinessVisibilityStatus(); this.changeVisibility("#preview-business-btn", this.IsEditing()); this.InitializeLanguageControls(); for (var i = 0; i < this.steps_containers_array.length; i++) { if (i <= current_step) { this.DoShowContainer(this.steps_containers_array[i]); } else { this.DoHideContainer(this.steps_containers_array[i]); } } } BusinessAddWizard.prototype.AppendObjectsArrayToFormData = function(form_data, array, title) { for (i = 0; i < array.length; i++) { for (var propertyName in array[i]) { form_data.append(title + '[' + i + '][' + propertyName + ']', array[i][propertyName]); } } } BusinessAddWizard.prototype.SerializeCitiesFields = function(form_data) { let object_info = {}; let business_cities = []; object_info.city = GetSelectBoxValue("#business-city"); business_cities[0] = object_info; this.AppendObjectsArrayToFormData(form_data, business_cities, "business-cities"); } BusinessAddWizard.prototype.SerializeURLSFields = function(form_data) { var business_urls = []; for (i = 0; i < this.urls_manager.items_list.length; i++) { var object_info = {}; object_info.url = this.urls_manager.items_list[i].GetInputValue("business-url"); business_urls[i] = object_info; } this.AppendObjectsArrayToFormData(form_data, business_urls, "business-urls"); } BusinessAddWizard.prototype.SerializePhonesFields = function(form_data) { var business_phones = []; for (i = 0; i < this.phones_manager.items_list.length; i++) { var object_info = {}; object_info.phone = this.phones_manager.items_list[i].GetInputValue("business-phone"); business_phones[i] = object_info; } this.AppendObjectsArrayToFormData(form_data, business_phones, "business-phones"); } BusinessAddWizard.prototype.SerializeBusinessContent = function(form_data) { /* var data = CKEDITOR.instances["business-desc"].getData(); form_data.append("business-desc", data); */ for (let i = 0; i < this.supportedLanguages.length; i++) { var data = CKEDITOR.instances["business-desc-" + this.supportedLanguages[i]].getData(); form_data.append("business-desc-" + this.supportedLanguages[i], data); } } BusinessAddWizard.prototype.SerializeAdditionalFields = function(form_data) { this.SerializeURLSFields(form_data); this.SerializePhonesFields(form_data); this.SerializeCitiesFields(form_data); this.SerializeBusinessContent(form_data); // business is recomended var is_business_recommended = $("#business-is-recommended").prop("checked"); form_data.append("business-is-recommended", is_business_recommended); // show unique business-id on business page var show_unique_id = GetButtonGroupValue("#business-show-unique-id"); form_data.append("business-show-unique-id", show_unique_id); } BusinessAddWizard.prototype.ChangePageTab = function(languageCode) { ChangeLanguageTab(languageCode); $(".language-tab").removeClass("active") $(".language-tab-" + languageCode).addClass("active") } BusinessAddWizard.prototype.ChangeLanguageTabByControlID = function(controlID) { if (controlID) { for (let i = 0; i < this.supportedLanguages.length; i++) { if (controlID.indexOf("-" + this.supportedLanguages[i]) >= 0) this.ChangePageTab(this.supportedLanguages[i]); } } } BusinessAddWizard.prototype.IsLanguageSupported = function(languageCode) { return $("#business-is-language-supported-" + languageCode).is(":checked"); } BusinessAddWizard.prototype.IsAnyLanguageSupported = function() { let result = false; for (let i = 0; i < this.supportedLanguages.length; i++) result = result || this.IsLanguageSupported(this.supportedLanguages[i]); return result; } BusinessAddWizard.prototype.OpenFirstSupportedLanguageTab = function() { for (let i = 0; i < this.supportedLanguages.length; i++) { if ($("#business-is-language-supported-" + this.supportedLanguages[i]).is(":checked")) { // console.log(this.supportedLanguages[i]); this.ChangePageTab(this.supportedLanguages[i]); return; } } } BusinessAddWizard.prototype.CheckSaveAvailability = function(isSilentMode) { this.save_validating = true; this.show_errors = (!isSilentMode); this.UpdateValidationError("", true); this.ChangeInputControlStyle(); var result = this.IsSaveAvailable(); if ((!isSilentMode) && (this.first_unfilled_control != null)) { var parent = $(this.first_unfilled_control).parent(); var controlID = $(this.first_unfilled_control).attr("id"); this.ChangeLanguageTabByControlID(controlID); $(parent)[0].scrollIntoView({ behavior: 'smooth'}); } this.show_errors = false; this.save_validating = false; return result; } BusinessAddWizard.prototype.ChangeInputsEnabledState = function(is_disabled) { $(".prototype-item").attr("disabled", is_disabled); } BusinessAddWizard.prototype.SendProfileToServer = function(isSilentMode) { if (this.CheckSaveAvailability(isSilentMode)) { this.SendProfileToServerInternal(isSilentMode); } } BusinessAddWizard.prototype.SubmitForm = function() { this.SendProfileToServer(); } BusinessAddWizard.prototype.LoadCategoriesFromURLParams = function() { if (this.IsCategoryFilled()) { SetSelectBoxValue("#items-root-category", this.root_category_id); this.FillSubCategoriesOptionsList(); if (this.category_id > 0) SetSelectBoxValue("#items-sub-category", this.category_id); } } BusinessAddWizard.prototype.LoadCategoriesFromJSON = function(json) { SetSelectBoxValue("#items-root-category", json["items-root-category"]); this.FillSubCategoriesOptionsList(); SetSelectBoxValue("#items-sub-category", json["items-sub-category"]); } BusinessAddWizard.prototype.changeVisibility = function(selector, visible) { (visible) ? $(selector).show() : $(selector).hide(); } BusinessAddWizard.prototype.UpdateCoverVisibility = function(visible) { this.hasCover = visible; this.changeVisibility("#cover_preview", visible); this.changeVisibility("#box_p", !visible); this.changeVisibility("#delete-cover-btn", visible); } BusinessAddWizard.prototype.ClearImageTTX = function() { $("#business-cover-ttx").html(""); } BusinessAddWizard.prototype.UpdateImageTTX = function(image_url) { var request; request = $.ajax({ type: "GET", url: image_url, success: function (response) { if (response.length > 0) { var img = new Image(); img.onload = function() { let file_size = response.length / 1024; let ttxInfo = img.width + "x" + img.height; if (file_size > 0) ttxInfo += ", " + file_size.toFixed(2) + " Kb"; $("#business-cover-ttx").html(ttxInfo); } img.src = image_url; } } }); } BusinessAddWizard.prototype.ShowCoverPreview = function(url) { $("#cover_preview").attr("src", url); this.UpdateImageTTX(url); this.UpdateCoverVisibility(true); } BusinessAddWizard.prototype.ClearCoverPreview = function() { $("#cover_preview").attr("src", ""); this.ClearImageTTX(); this.UpdateCoverVisibility(false); } BusinessAddWizard.prototype.LoadBusinessImageFromJSON = function(json) { if (json["business-image"]) { this.ShowCoverPreview(json["business-image"]); } } BusinessAddWizard.prototype.LoadCitiesFromJSON = function(json) { if (json["business-cities"]) { if (json["business-cities"].length > 0) SetSelectBoxValue("#business-city", json["business-cities"][0].city); } } BusinessAddWizard.prototype.LoadURLsFromJSON = function(json) { if (json["business-urls"]) { var business_urls = json["business-urls"]; if (business_urls.length > 0) { for (var i = 0; i < business_urls.length; i++) { var current_item = this.urls_manager.current_item; current_item.SetInputValue("business-url", business_urls[i].url); if (i != (business_urls.length - 1)) this.urls_manager.AddItem(); } } } } BusinessAddWizard.prototype.LoadPhonesFromJSON = function(json) { if (json["business-phones"]) { var business_phones = json["business-phones"]; if (business_phones.length > 0) { for (var i = 0; i < business_phones.length; i++) { var current_item = this.phones_manager.current_item; current_item.SetInputValue("business-phone", business_phones[i].phone); if (i != (business_phones.length - 1)) this.phones_manager.AddItem(); } } } } BusinessAddWizard.prototype.LoadControlsFromJSON = function(json) { for (var propertyName in json) { var jquery_name = "#" + propertyName; if (IsCheckBox(jquery_name)) { if ((json[propertyName] == "true") || ((json[propertyName] == "1"))) $(jquery_name).attr('checked', 'checked'); else $(jquery_name).removeAttr('checked'); } if (IsCheckBox(jquery_name)) { if (json[propertyName] == "true") $(jquery_name).attr('checked', 'checked'); } else if (IsInputBox(jquery_name)) { $(jquery_name).val(json[propertyName]); } else if (IsSelectBox(jquery_name)) { // alert(jquery_name + ": " + json[propertyName]); SetSelectBoxValue(jquery_name, json[propertyName]); } } // $("#business-desc").val(json["business-desc"]); for (let i = 0; i < this.supportedLanguages.length; i++) $("#business-desc-" + this.supportedLanguages[i]).val(json["business-desc-" + this.supportedLanguages[i]]); $("#business-is-recommended").prop("checked", json["business-is-recommended"]); SetButtonGroupCheckBoxValue("#business-show-unique-id", json["business-show-unique-id"]); this.LoadCategoriesFromJSON(json); this.LoadBusinessImageFromJSON(json); this.LoadPhonesFromJSON(json); this.LoadCitiesFromJSON(json); this.LoadURLsFromJSON(json); } BusinessAddWizard.prototype.LoadControlsFromJSONContent = function(json_content) { if (json_content) { var json = JSON.parse(json_content); this.LoadControlsFromJSON(json); } } BusinessAddWizard.prototype.SupportsCategoryContainers = function() { return true; } BusinessAddWizard.prototype.IsSupportedDragTarget = function(event) { var result = (event.target === $('#box').get(0)); result = result || (event.target === $('#box_p').get(0)); result = result || (event.target === $('#cover_preview').get(0)); return result; } BusinessAddWizard.prototype.ProcessDragEvent = function(event) { if (this.IsSupportedDragTarget(event)) { event.preventDefault(); event.stopPropagation(); return true; } return false; } BusinessAddWizard.prototype.DeleteBusinessCover = function() { var object = this; this.uploaded_file = null; var formData = new FormData(); if (this.IsEditing) formData.append('business_id', this.business_id); $.ajax({ url: GetBaseURL() + '?mode=delete_cover_ajax', type: 'POST', data: formData, processData: false, contentType: false, success : function(response) { object.ClearCoverPreview(); $("#image-error-container").html(""); } }); } BusinessAddWizard.prototype.ShowBusinessPreviewPage = function() { if (this.IsEditing()) { var url = "/business.php?mode=show_business&business_id=" + this.business_id; window.open(url, "_blank"); return true; } alert("Вы должны сначала сохранить услугу"); } BusinessAddWizard.prototype.DeleteBusiness = function() { if (this.IsEditing()) { let deleteBusinessURL = this.GetDeleteBusinessURL(); if (deleteBusinessURL) { var should_delete = confirm("Вы действительно хотите удалить данную услугу?\n\nВнимание! Данная операция необратима"); if (should_delete == true) { deleteBusinessURL += "&cp=" + CreateUniqueString(); window.location.href = deleteBusinessURL; return true; } } } } BusinessAddWizard.prototype.GetDeleteBusinessURL = function() { return ""; } BusinessAddWizard.prototype.UploadCoverFile = function(file) { var object = this; this.uploaded_file = file; var formData = new FormData(); formData.append('cover_file', file); $.ajax({ url: GetBaseURL() + '?mode=upload_cover_ajax', type: 'POST', data: formData, processData: false, contentType: false, success : function(response) { var serverAnswer = JSON.parse(response); if (serverAnswer.status == "ok") { $("#image-error-container").html(""); object.ShowCoverPreview(serverAnswer.url); if (serverAnswer.warning_ru) alert(serverAnswer.warning_ru); } else if (serverAnswer.status == "error") { // console.log(serverAnswer); $("#image-error-container").html(serverAnswer.error_desc); // alert(serveserverAnswer_answer.error_desc); UniversalModalDialog.showModalDialog("Ошибка!", serverAnswer.error_desc, "Закрыть"); } } }); } BusinessAddWizard.prototype.ShowCoverInDifferentPage = function() { var url = $("#cover_preview").attr("src"); if (url) { window.open(url, '_blank'); } } BusinessAddWizard.prototype.SelectBusinessCover = function() { var file = $("#file-upload").get(0).files[0]; this.UploadCoverFile(file); } BusinessAddWizard.prototype.InitializeDragAndDropObjects = function() { var object = this; $(document).on('drag dragstart', function(e) { object.ProcessDragEvent(e); }); $(document).on('dragover dragenter', function(e) { if (object.ProcessDragEvent(e)) $('#box').addClass('is-dragover'); }); $(document).on('dragleave dragend', function(e) { if (object.ProcessDragEvent(e)) { $('#box').removeClass('is-dragover'); } }); $(document).on('drop', function(e) { if (object.ProcessDragEvent(e)) { $('#box').removeClass('is-dragover'); var droppedFiles = e.originalEvent.dataTransfer.files; object.UploadCoverFile(droppedFiles[0]); } }); } BusinessAddWizard.prototype.InitializeInternalObjects = function() { this.InitializeDragAndDropObjects(); this.InitializeCitiesManager(); this.InitializeURLsManager(); this.InitializePhonesManager(); this.InitializeBusinessCities(); } BusinessAddWizard.prototype.AnalyzeServerAnswerPhones = function(serverAnswer) { if (serverAnswer.phones_corrected) { for (var i = 0; i < serverAnswer.phones_corrected.length; i++) { var phone_old = serverAnswer.phones_corrected[i].phone_old; var phone_new = serverAnswer.phones_corrected[i].phone_new; var phone_item = this.phones_manager.SearchItemByValue(phone_old); if (phone_item) phone_item.SetValue(phone_new) } } } BusinessAddWizard.prototype.AnalyzeServerAnswerWarning = function(serverAnswer) { if (serverAnswer.warning) this.AnalyzeServerAnswerPhones(serverAnswer); } BusinessAddWizard.prototype.ExecuteSendProfileToServerAjaxRequest = function(mode, callback) { // prototype items var form = $("#business-info"); this.ChangeInputsEnabledState(true); var formData = new FormData(form[0]); if (this.uploaded_file) formData.append('cover_file', this.uploaded_file); var post_url = form.attr("action"); post_url = AddURLParameter(post_url, "mode", mode); // console.log(post_url); var request_method = form.attr("method"); this.SerializeAdditionalFields(formData); this.ChangeInputsEnabledState(false); $.ajax({ url: post_url, type: request_method, data: formData, contentType: false, processData: false }).done(function(response) { var serverAnswer = JSON.parse(response); if (callback) callback(serverAnswer); }); } BusinessAddWizard.prototype.ScrollToInvalidControlOnSaving = function(controlID) { if (controlID) { controlID = "#" + controlID; this.ChangeControlBackgroundColorInternal(controlID, false, true); var parent = $(controlID).parent(); if (parent) { $(parent)[0].scrollIntoView({ behavior: 'smooth'}); } } } BusinessAddWizard.prototype.FillFormControlsOnSaving = function(serverAnswer, isSilentMode) { if (serverAnswer.business_id) { this.business_id = serverAnswer.business_id; $("#business_id").val(this.business_id); this.InitializeInterface(); if (!isSilentMode) this.AnalyzeServerAnswerWarning(serverAnswer); } } BusinessAddWizard.prototype.SendProfileToServerInternal = function(isSilentMode) { var object = this; this.ExecuteSendProfileToServerAjaxRequest("save_business_ajax", function(serverAnswer) { if (serverAnswer.status == "ok") { object.FillFormControlsOnSaving(serverAnswer, isSilentMode); if ((serverAnswer.redirect_url) && (!isSilentMode)) window.location.href = serverAnswer.redirect_url; } else if ((serverAnswer.status == "error") && (!isSilentMode)) { object.UpdateValidationError(serverAnswer.error_desc, true); object.ScrollToInvalidControlOnSaving(serverAnswer.html_control_id); UniversalModalDialog.showModalDialog("Ошибка!", serverAnswer.error_desc, "Закрыть"); } }); } BusinessAddWizard.prototype.ChangeBusinessStatus = function() { this.InitializeInterface(); } BusinessAddWizard.prototype.GenerateCitiesOptionsListHTML = function(countryInfo) { let result = ""; for (let i = 0; i < countryInfo.cities.length; i++) { const cityInfo = countryInfo.cities[i]; result += "\n"; } return result; } BusinessAddWizard.prototype.InitializeBusinessCities = function() { const countryID = GetSelectBoxValue("#business-country"); const countryInfo = wizardCountriesJS["country" + countryID]; if (countryInfo) { let citiesHTML = "\n"; citiesHTML += this.GenerateCitiesOptionsListHTML(countryInfo); $("#business-city").html(citiesHTML); } } BusinessAddWizard.prototype.InitializeLanguageControls = function() { // skip main language // console.log('InitializeLanguageControls'); for (let i = 0; i < this.supportedLanguages.length; i++) { let isSupported = $("#business-is-language-supported-" + this.supportedLanguages[i]).prop("checked"); if (isSupported) { $("#business-title-" + this.supportedLanguages[i]).removeClass("not-mandatory-field"); $("#business-desc-" + this.supportedLanguages[i]).removeClass("not-mandatory-field"); } else { $("#business-title-" + this.supportedLanguages[i]).addClass("not-mandatory-field"); $("#business-desc-" + this.supportedLanguages[i]).addClass("not-mandatory-field"); // console.log("#business-title-" + this.supportedLanguages[i] + ": " + $("#business-title-" + this.supportedLanguages[i]).hasClass("not-mandatory-field")) } } } BusinessAddWizard.prototype.IsActionButtonCaptionValid = function() { return ($("#action-button-caption").val().length <= MAX_ACTION_BUTTON_LENGTH); } BusinessAddWizard.prototype.ChangeActionButtonCaption = function() { $("#action-button-error").changeVisibility(!this.IsActionButtonCaptionValid()); $("#action-button-error").html("Длинна текста кнопки действия не может быть больше {0} символов".format(MAX_ACTION_BUTTON_LENGTH)); this.InitializeInterface(); } BusinessAddWizard.prototype.ShowURLEntry = function(element) { let urlValue = $(element).parent().find("[name='business-url']").val(); if (urlValue) window.open(urlValue); } function decodeHtml(html) { var txt = document.createElement("textarea"); txt.innerHTML = html; return txt.value; } BusinessAddWizard.prototype.OnClearBusiness = function() { this.InitializeInterface(); } BusinessAddWizard.prototype.Initialize = function(json_content) { // $("#business-is-language-supported-ru").attr('checked', 'checked'); // console.log(json_content); this.InitializeInternalObjects(); this.LoadControlsFromJSONContent(json_content); this.LoadCategoriesFromURLParams(); this.InitializeInterface(); let _this = this; setTimeout(function() { _this.OpenFirstSupportedLanguageTab(); }, 200); // console.log(json_content); }