You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

678 lines
23 KiB

'use strict';
function sendForm (show_modal) {
var show_modal = show_modal || false,
$form = $('#mailing_settings_form');
$form.find('.field_error').removeClass('field_error');
$form.find('.text_error').remove();
var form_data = $form.serializeArray();
if (show_modal) {
form_data.push({
name: 'save',
value: true
})
}
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: form_data,
success: function(response){
console.log(response);
if (response.hasOwnProperty('redirect_url')){
window.location.pathname = response.redirect_url;
}
},
error: function (error) {
var form_errors = error.responseJSON.form_errors;
if (show_modal){
var $error_list = $('<ol></ol>', {class: 'errorlist'});
$.each(form_errors, function (field, err) {
$error_list.append('<li>' + err + '</li>');
});
$('#error_messages').html($error_list);
$.fancybox.open({
href: '#error_modal'
})
} else {
$.each(form_errors, function (field, err) {
var $field = $form.find('#id_' + field);
$field.addClass('field_error');
$field.parent('.pr-input').prepend('<span class="text_error">' + err + '</span>');
});
}
}
});
}
// Выбор тем
(function () {
var $themes_modal = $('.popup-window.themes'),
$autocomplete = $('#autocomplete_themes', $themes_modal),
$autocomplete_results = $('#autocomplete_themes_results', $themes_modal),
$selected_themes = $('.selected_themes', $themes_modal),
timer,
themes_data = {},
// template for mustache.js
tag_tpl = '{{#tags}}<li>' +
'<label>' +
'<input type="checkbox" class="hidden_checkbox" name="tg" id="id_tg_{{ id }}" value="{{ id }}" {{#checked}}checked{{/checked}} />' +
'<span class="custom_checkbox"></span>' +
'<span class="label">{{ text }}</span>' +
'</label>' +
'</li>{{/tags}}',
renderSublist = function (theme_id, $sub_list) {
var theme_tags = themes_data[theme_id]['tags'],
tags = Mustache.to_html(tag_tpl, {tags: theme_tags});
$sub_list
.html(tags)
.addClass('has_items')
.slideDown(100);
},
getAutocompleteResults = function () {
var term = $autocomplete.val();
if ($.trim(term).length >= 3){
$.get(
$autocomplete.data('url'),
{
form: $autocomplete.data('form'),
term: term
},
function (response) {
if (response.length > 0){
var results = '';
response.forEach(function (obj) {
results += '<li data-type="' + obj.name + '"' +
'data-id="' + obj.id + '"' +
'data-text="' + obj.text + '"' +
'data-parent="' + obj.theme_id + '">' + obj.text +
' <span>(' + obj.cat + ')</span>' +
'</li>'
});
$autocomplete_results
.html(results)
.show();
}
}
)
}
};
$.get($themes_modal.data('url'), function (response) {
response['data'].forEach(function(obj){
themes_data[obj.id] = obj;
if (themes_data[obj.id].checked) {
themes_data[obj.id].tags.forEach(function (tag) {
tag.checked = true;
})
}
});
});
// открываем список тегов в теме
$themes_modal.on('click', '.trigger', function (e) {
e.preventDefault();
var $link = $(this),
theme_id = $link.parents('.theme_item').data('id'),
$sub_list = $link.next('.sub');
// если теги подгружены, то открываем(закрываем) список
// если нет, то подгружаем аяксом теги
if ($sub_list.hasClass('has_items')){
$sub_list.slideToggle(100);
} else {
renderSublist(theme_id, $sub_list);
}
});
function changeThemeData (theme_id, checked, set_tags) {
var set_tags = set_tags || false;
themes_data[theme_id].checked = checked;
if (set_tags){
themes_data[theme_id].tags.forEach(function (tag) {
tag.checked = checked;
});
}
}
function changeTagData (theme_id, tag_id, checked) {
themes_data[theme_id].tags.forEach(function (tag) {
if (tag.id == tag_id){
tag.checked = checked;
}
});
}
function isAllTagsChecked (theme_id) {
return themes_data[theme_id].tags.every(function (obj) {
return obj.checked;
});
}
function renderTheme (theme_id) {
var tpl = '<li class="unsaved theme_{{ id }}" data-type="th" data-id="{{ id }}">' +
'<input type="hidden" name="th" value="{{ id }}"> {{ text }}' +
'<a href="#">×</a>' +
'</li>';
var themes = themes_data[theme_id];
return Mustache.to_html(tpl, themes);
}
function renderTag (theme_id, tag_id) {
var tpl = '<li class="unsaved tag_{{ id }}" data-type="tg" data-parent="' + theme_id + '" data-id="{{ id }}">' +
'<input type="hidden" name="tg" value="{{ id }}"> {{ text }}' +
'<a href="#">×</a>' +
'</li>';
var tag_data = themes_data[theme_id]['tags'].filter(function(tag){
return tag.id == tag_id;
});
return Mustache.to_html(tpl, tag_data[0]);
}
function renderTags (theme_id, tag_id) {
var tpl = '{{#tags}}<li class="unsaved tag_{{ id }}" data-type="tg" data-parent="' + theme_id + '" data-id="{{ id }}">' +
'<input type="hidden" name="tg" value="{{ id }}"> {{ text }}' +
'<a href="#">×</a>' +
'</li>{{/tags}}';
var tag_data = themes_data[theme_id]['tags'].filter(function(tag){
return tag.id != tag_id;
});
return Mustache.to_html(tpl, { tags: tag_data });
}
function removeSelectedItem (type, id) {
$selected_themes
.find('li[data-type="' + type + '"][data-id="' + id + '"]')
.remove();
}
function checkSelected () {
if ($selected_themes.children('li').length > 0){
$selected_themes.addClass('visible');
} else {
$selected_themes.removeClass('visible');
}
}
$themes_modal.on('change', 'input[type="checkbox"]', function (e) {
e.preventDefault();
// sendForm();
var $checkbox = $(this);
// Изменили чекбокс темы
if ($checkbox.attr('name') == 'th'){
var $sub_list = $checkbox.parents('.theme_item').find('.sub');
// Поставили чекбокс темы
if ($checkbox.is(':checked')) {
changeThemeData($checkbox.val(), true, true);
$sub_list.find('input[name="tg"]').each(function (i, checkbox) {
$(checkbox).prop('checked', true);
});
$selected_themes
.find('[data-parent="' + $checkbox.val() + '"]')
.remove();
var rendered_theme = renderTheme($checkbox.val());
$selected_themes.append(rendered_theme);
// Сняли чекбокс темы
} else {
changeThemeData($checkbox.val(), false, true);
$sub_list.find('input[name="tg"]').each(function (i, checkbox) {
$(checkbox).prop('checked', false);
});
removeSelectedItem($checkbox.attr('name'), $checkbox.val());
}
// Изменили чекбокс тега
} else {
var $theme_item = $checkbox.parents('.theme_item'),
theme_id = $theme_item.data('id'),
tag_id = $checkbox.val();
// Поставили чекбокс тега
if ($checkbox.is(':checked')) {
changeTagData(theme_id, tag_id, true);
// Все теги в теме выбраны
if (isAllTagsChecked(theme_id)){
$theme_item
.find('input[name="th"][value="' + theme_id + '"]')
.prop('checked', true);
changeThemeData(theme_id, true, false);
$selected_themes.find('[data-parent="' + theme_id + '"]').remove();
var rendered_theme = renderTheme(theme_id);
$selected_themes.append(rendered_theme);
} else {
var rendered_tag = renderTag(theme_id, tag_id);
$selected_themes.append(rendered_tag);
}
// Сняли чекбокс тега
} else {
changeTagData(theme_id, tag_id, false);
// Родительская тема выбрана
if (themes_data[theme_id].checked) {
changeThemeData(theme_id, false);
$theme_item
.find('input[name="th"][value="' + theme_id + '"]')
.prop('checked', false);
removeSelectedItem('th', theme_id);
var rendered_tags = renderTags(theme_id, tag_id);
$selected_themes.append(rendered_tags);
// Родительская тема не выбрана
} else {
removeSelectedItem($checkbox.attr('name'), tag_id);
}
}
}
checkSelected();
});
// Input автокомплита
$autocomplete.on('keyup', function () {
$autocomplete_results.hide();
clearTimeout(timer);
timer = setTimeout(getAutocompleteResults, 500);
});
// Выбор из автокомплита
$autocomplete_results.on('click', 'li', function () {
var $this = $(this);
if ($this.data('type') == 'th') {
var $chosen = $themes_modal.find('#id_th_' + $this.data('id'));
if (!$chosen.is(':checked')){
$chosen.trigger('click');
}
} else {
var $chosen = $themes_modal.find('#id_tg_' + $this.data('id')),
parent_id = $this.data('parent'),
$theme_tags = $('.theme_item[data-id="' + parent_id + '"]').find('.sub');
if ($theme_tags.is('visible')) {
$chosen.trigger('click');
} else {
$theme_tags.prev('.trigger').trigger('click');
$themes_modal.find('#id_tg_' + $this.data('id')).trigger('click');
}
}
$autocomplete_results
.html('')
.hide();
$autocomplete.val('');
});
function deleteSelected() {
event.preventDefault();
var $this = $(this),
delete_class = $this.parents('li').attr('class'),
id = $this.parents('li').data('id'),
type = $this.parents('li').data('type'),
$deleted_checkbox = $('#id_' + type + '_' + id);
if ($deleted_checkbox.length) {
$deleted_checkbox.trigger('click');
} else {
var parent_id = $(this).parents('li').data('parent');
themes_data[parent_id]['tags'].forEach(function (tag) {
if (tag['id'] == id){
tag['checked'] = false;
}
});
}
/* TODO: find other solution of saving form */
// Если удаляем со страницы а не с модального окна
var saveForm = event.path.some(function (item) {
return $(item).attr('id') == 'selected_themes';
});
if (saveForm){
$('.' + delete_class).remove();
sendForm();
} else {
$this.parents('li').remove();
}
checkSelected();
}
// Удаление выбранной темы
$selected_themes.on('click', 'a', deleteSelected);
$('#selected_themes').on('click', 'a', deleteSelected);
$('body').on('click', function (e) {
if ($autocomplete_results.is(':visible') && $(e.target).parents('.autocomplete_block').length == 0){
$autocomplete_results
.html('')
.hide();
}
});
$themes_modal.on('click', '.modal-approve', function () {
var $selected = $selected_themes.find('li').removeClass('unsaved').clone();
if ($('#pr-promo').length){
if (!$('#id_moscow').is(':checked') && !$('#id_russia').is(':checked') && $selected_themes.children().length && !$('#selected_themes').children().length){
$('#id_moscow').prop('checked', true);
$('#id_russia').prop('checked', true);
}
}
$('#selected_themes').html($selected);
sendForm();
$.fancybox.close();
});
$themes_modal.on('click', '.modal-clear', function () {
$selected_themes.find('a').trigger('click');
});
$('#mailing_settings_form button').on('click', function (event) {
event.preventDefault();
var show_modal = true;
sendForm(show_modal);
});
})();
// Выбор городов
(function () {
var $cities_modal = $('.popup-window.r_cities'),
$selected_cities = $('#selected_cities'),
$cities_select = $('#id_r_cities'),
selected_cities = {},
renderSelectedCountry = function (id, text) {
return '<li>' +
'<input type="hidden" name="r_cities" value="' + id + '">' +
text +
'<a href="#">&times;</a>' +
'</li>'
},
renderSelectedCities = function () {
$selected_cities.html('');
for (var city_id in selected_cities) {
var $city = $(renderSelectedCountry(city_id, selected_cities[city_id]));
$selected_cities.append($city);
}
sendForm();
};
// Записываем данные в selected_cities при инициализации
$cities_select.find('option').each(function () {
$cities_modal.find('input[name="r_cities"][value="' + $(this).val() + '"]').prop('checked', true);
selected_cities[$(this).val()] = $(this).text();
var $city = $(renderSelectedCountry($(this).val(), $(this).text()));
$selected_cities.append($city);
});
$cities_modal.on('change', 'input[type="checkbox"]', function (e) {
e.preventDefault();
var $checkbox = $(this);
// записываем(удаляем) в объект selected_cities отмеченные темы(теги)
if($checkbox.is(':checked')){
selected_cities[$checkbox.val()] = $checkbox.parent().find('.label').text();
} else {
delete selected_cities[$checkbox.val()];
$('#id_' + $checkbox.attr('name')).find('option[value="' + $checkbox.val() + '"]').remove();
}
renderSelectedCities();
});
// Удаление выбранного тега
$selected_cities.on('click', 'a', function (event) {
event.preventDefault();
var $input = $(this).siblings('input');
delete selected_cities[$input.val()];
$('.modal_checkboxes').find('input[name="' + $input.attr('name') + '"][value="' + $input.val() + '"]').prop('checked', false);
$('#id_' + $input.attr('name')).find('option[value="' + $input.val() + '"]').remove();
$(this).parent('li').remove();
sendForm();
});
$cities_modal.on('click', '.modal-approve', $.fancybox.close);
$cities_modal.on('click', '.modal-clear', function () {
$cities_modal.find('input:checked').prop('checked', false);
$selected_cities.html('');
$cities_select.html('');
sendForm();
});
})();
// Выбор стран
(function () {
var $countries_modal = $('.popup-window.countries'),
$areas_select = $('#id_area'),
$co_select = $('#id_co'),
$selected_areas = $('#selected_areas'),
$selected_co = $('#selected_countries'),
user_countries = {
area: {},
co: {}
},
renderSublistItem = function (data) {
return '<li>' +
'<label>' +
'<input type="checkbox" class="hidden_checkbox" name="' + data.name + '" value="' + data.id + '" />' +
'<span class="custom_checkbox"></span>' +
'<span class="label">' + data.text + '</span>' +
'</label>' +
'</li>';
},
renderSublist = function (url, $sub_list) {
var $loader = $countries_modal.find('.wait-ajax').show();
$.getJSON(url, function (data, status) {
if (status == 'success'){
$.each(data, function (i) {
var $sub_item = $(renderSublistItem( data[i] ));
if (data[i]['id'] in user_countries['co']){
$sub_item.find('input').prop('checked', true);
}
$sub_list
.addClass('has_items')
.append($sub_item);
});
$loader.hide();
}
});
},
renderSelectedCountry = function (id, name, text) {
return '<li>' +
'<input type="hidden" name="' + name + '" value="' + id + '">' +
text +
'<a href="#">&times;</a>' +
'</li>'
},
renderSelectedCountries = function () {
$selected_co.html('');
$selected_areas.html('');
for (var area_id in user_countries['area']) {
var $area = $(renderSelectedCountry(area_id, 'area', user_countries['area'][area_id]));
$selected_areas.append($area);
}
for (var co_id in user_countries['co']) {
var $co = $(renderSelectedCountry(co_id, 'co', user_countries['co'][co_id]));
$selected_co.append($co);
}
sendForm();
},
removeCheckbox = function (type, id) {
delete user_countries[type][id];
$('.modal_checkboxes').find('input[name="' + type + '"][value="' + id + '"]').prop('checked', false);
$('#id_' + type).find('option[value="' + id + '"]').removeAttr('selected');
};
// Записываем данные в user_countries при инициализации
$areas_select.find('option[selected]').each(function () {
$countries_modal.find('input[name="area"][value="' + $(this).val() + '"]').prop('checked', true);
user_countries['area'][$(this).val()] = $(this).text();
var $area = $(renderSelectedCountry($(this).val(), 'area', $(this).text()));
$selected_areas.append($area);
});
$co_select.find('option[selected]').each(function () {
user_countries['co'][$(this).val()] = $(this).text();
var $co = $(renderSelectedCountry($(this).val(), 'co', $(this).text()));
$selected_co.append($co);
});
// открываем список тегов в теме
$countries_modal.on('click', '.trigger', function (e) {
e.preventDefault();
var $link = $(this),
$sub_list = $link.next('.sub');
// если теги подгружены, то открываем(закрываем) список
// если нет, то подгружаем аяксом теги
if ($sub_list.hasClass('has_items')){
$sub_list.slideToggle(100);
} else {
renderSublist($link.attr('href'), $sub_list);
}
});
$countries_modal.on('change', 'input[type="checkbox"]', function (e) {
e.preventDefault();
var $checkbox = $(this);
// записываем(удаляем) в объект user_choice отмеченные темы(теги)
if($checkbox.is(':checked')){
user_countries[$checkbox.attr('name')][$checkbox.val()] = $checkbox.parent().find('.label').text();
} else {
delete user_countries[$checkbox.attr('name')][$checkbox.val()];
$('#id_' + $checkbox.attr('name')).find('option[value="' + $checkbox.val() + '"]').removeAttr('selected');
}
renderSelectedCountries();
});
// Удаление выбранного континента
$selected_areas.on('click', 'a', function (event) {
event.preventDefault();
var $input = $(this).siblings('input');
removeCheckbox($input.attr('name'), $input.val());
$(this).parent('li').remove();
sendForm();
});
// Удаление выбранной страны
$selected_co.find('a').on('click', function (event) {
event.preventDefault();
var $input = $(this).siblings('input');
removeCheckbox($input.attr('name'), $input.val());
$(this).parent('li').remove();
sendForm();
});
$countries_modal.on('click', '.modal-approve', $.fancybox.close);
$countries_modal.on('click', '.modal-clear', function () {
$countries_modal.find('input:checked').prop('checked', false);
$selected_areas.html('');
$selected_co.html('');
$areas_select.html('');
$co_select.html('');
sendForm();
});
})();
$(function () {
$('.modal_trigger').fancybox({
padding: 0
});
$('.scroll-container').mCustomScrollbar();
if ($('#unsibscribed').length)
$.fancybox.open({href: '#unsibscribed'});
});