$(function() { var paginationSelectorClass = 'profile-pagination-link'; var postsTabId = 'us_post'; //Для области видимости внутри анонимных функций var ajaxUserPosts = ''; var ajaxUserComments = ''; $(document).on('click', "." + paginationSelectorClass, function (e) { e.preventDefault(); var userId = $(this).attr('data-user'); var page = $(this).attr('data-page-number'); var target = $(this).attr('data-target'); var url = 'index.php'; if (userId && page) { userId = parseInt(userId, 10); // Идентификатор пользователя page = parseInt(page, 10); //Для сдвига выборки из базы данных if (userId > 0 && page > 0) { switch(target){ case 'favourite-posts': url += '?getUserFavouritePosts'; break; case 'comments': url += '?getUserComments'; break; default: url += '?getUserPosts'; break; } $('#' + postsTabId).load(url +'='+ userId + '&page=' + page + '&API'); } } }); //Добавление элементов в избранное $(document).on('click', ".add-to-favourite", function(){ var target = $(this).attr('data-target'); var targetId = $(this).attr('data-target-id'); var link = $(this); var url = '/index.php'; if(targetId<=0){ popUpWindow('Не указан идентификатор. Несанкционированное действие', 'warning'); } $.ajax({ url: url, method: "GET", data: {"API":'',"api-action":"addToFavourite", "target": target, "targetId": targetId}, dataType: "HTML", success: function(response){ if(response == 'success'){ popUpWindow('Успешно добавлено в избранное', 'success'); link.text('Убрать из избранного'); link.attr('class', 'remove-from-favourite'); } else{ popUpWindow('Произошла ошибка добавления', 'danger'); } }, error: function(){popUpWindow('Произошла ошибка добавления', 'danger');} }); }); $(".but.change-photo").on('click', function(e){ e.preventDefault(); $("#avatar-image-input").trigger('click'); }); $(".del_photo").on('click', function(e){ e.preventDefault(); $.ajax({ url: '/index.php', method: "GET", data: {"API":'',"api-action":"deleteProfileAvatar"}, dataType: "HTML", success: function(response){ if(response != ''){ popUpWindow('Ваш аватар удален', 'notice'); $("#user-profile-avatar").attr("src", response+"?"+(new Date()).getTime()); } else{ popUpWindow('Не удалось удалить аватар', 'error'); } }, error: function(){popUpWindow('Не удалось удалить аватар', 'error');} }); }); $("#avatar-image-input").on('change',function(){ $("#avatar-image-form").trigger('submit'); }); $("#avatar-image-source").on("change", function() { $("#user-profile-avatar").attr("src", $(this).val()+"?"+(new Date()).getTime()); popUpWindow('Ваш аватар успешно изменен', 'success'); }); //Удаление элементов из избранного $(document).on('click', ".remove-from-favourite", function(){ var target = $(this).attr('data-target'); var targetId = $(this).attr('data-target-id'); var link = $(this); var url = '/index.php'; if(targetId<=0){ popUpWindow('Не указан идентификатор. Несанкционированное действие', 'warning'); } $.ajax({ url: url, method: "GET", data: {"API":'',"api-action":"removeFromFavourite", "target": target, "targetId": targetId}, dataType: "HTML", success: function(response){ if(response == 'success') { popUpWindow('Успешно удалено из избранного', 'notice'); link.text('Добавить в избранное'); link.attr('class', 'add-to-favourite'); } else{ popUpWindow('Произошла ошибка удаления', 'error'); } }, error: function(){popUpWindow('Произошла ошибка удаления', 'error');} }); }); $(document).on('click', ".close-popup", function(){ $(this).parent("div.alert").hide(); }); $("form#user-profile-form :input").change(function(){ $(this).val($(this).val().replace(/^(https?|ftp):\/\//, '')) }); }); function popUpWindow(message, messageType) { if (typeof messageType == 'undefined' || message == '') { return; } var popUp = document.createElement('div'); var closePopUp = document.createElement('span'); closePopUp.style = 'position: absolute; top:0; right:5px; font-size:18px; font-weight:bold; cursor:pointer;'; closePopUp.className = 'close-popup'; closePopUp.innerHTML = '×'; closePopUp.title = 'Закрыть'; popUp.className = 'alert alert' + messageType; popUp.style = 'font-size:14px; position:fixed; z-index:100000; top:20px; right: 20px;-webkit-transition: top 1s ease-out 0.5s; -moz-transition: top 1s ease-out 0.5s;-o-transition: top 1s ease-out 0.5s;transition: top 1s ease-out 0.5s;padding: 15px;margin-bottom: 20px;border: 1px solid transparent;border-radius: 4px;'; popUp.innerHTML = message; switch (messageType) { case 'notice': popUp.style.color = '#31708F'; popUp.style.backgroundColor = '#D9EDF7'; popUp.style.borderColor = '#BCE8F1'; break; case 'warning': popUp.style.color = '#8A6D3B'; popUp.style.backgroundColor = '#FCF8E3'; popUp.style.borderColor = '#FAEBCC'; break; case 'error': popUp.style.color = '#A94442'; popUp.style.backgroundColor = '#F2DEDE'; popUp.style.borderColor = '#EBCCD1'; break; default: popUp.style.color = '#3C763D'; popUp.style.backgroundColor = '#DFF0D8'; popUp.style.borderColor = '#D6E9C6'; break; } popUp.appendChild(closePopUp); document.body.appendChild(popUp); setTimeout(function () { document.body.removeChild(popUp) }, 5000); } function UploadFile(type, formName, inputName, progressElem, showPopupStatus){ this.showStatus = typeof showPopupStatus == 'undefined'; this.file = null; //Загружаемый файл this.fileType = type; //Тип загружаемого файла this.fileSize = 0; //Размер файла this.uploadProgress = 0; //Прогресс загрузки файла от 0 до 100 this.uploadedFileName = ''; //Имя файла, загруженного на сервер this.uploaded = false; //Информация о том, загружен ли файл this.form = document.forms[formName]; //Имя формы, с которой ведется загрузка this.input = inputName; this.progressElem = document.getElementById(progressElem); //Блок, в котором будет выводиться прогресс загрузки var _this = this; //При подтверждении загрузки по форме this.form.onsubmit = function(e){ e.preventDefault(); _this.file = _this.form.elements[_this.input].files[0]; if(_this.file){ _this.progressElem.style.display = 'block'; _this.tryUpload(); } }; this.tryUpload = function(){ var proc = new XMLHttpRequest(); var formData = new FormData(); formData.append(this.input, _this.file); proc.onload = function() { _this.progressElem.style.display = 'none'; _this.progressElem.innerHTML = ''; console.log(this.responseText); if (this.responseText == ''){ popUpWindow('Ошибка загрузки', 'error'); } else { _this.form.elements[1].value = this.responseText; if(_this.showStatus) { popUpWindow('Успешно загружено', 'success'); } $("#"+_this.form.elements[1].id).trigger('change'); } }; proc.onerror = function(){ popUpWindow('Ошибка загрузки', 'error'); }; proc.upload.onprogress = function(event) { var percent = Number(event.total/102400).toFixed(0); var current = Number((event.loaded/1024)/percent).toFixed(0); if(current>=100){ current = 100; } _this.progressElem.innerHTML = current + '% из 100'; }; if(_this.fileType == 'image'){ proc.open("POST", '/index.php?API', true); } proc.send(formData); }; }