Skip to content

Instantly share code, notes, and snippets.

@victorpavlenko
Created March 26, 2015 09:32
Show Gist options
  • Save victorpavlenko/2e124773b99895e3926e to your computer and use it in GitHub Desktop.
Save victorpavlenko/2e124773b99895e3926e to your computer and use it in GitHub Desktop.
function initViewPostEvents() {
var addedCommentCount = 0;
var $postCommentMessage = $('#postCommentMessage');
$postCommentMessage.autosize();
$('.clearTextArea').off('click').on('click', function () {
$postCommentMessage.val('').trigger('autosize.resize');
});
$('#submitPostComment').off('click').on('click', function () {
if ($postCommentMessage.val() == '') {
alert('Введите сообщение!');
return;
}
var id = $('#postViewPopup').attr('data-id');
var $boxes = $('.box[data-id="' + id + '"]').find('.ico-comment');
dispatchAction({action: 'addPostComment', id: id, message: $postCommentMessage.val()});
$('#postCommentJustAdded p').html($postCommentMessage.val());
$postCommentMessage.val('');
addedCommentCount++;
$('#postCommentsContainer').prepend('<div style="display:none;" id="postCommentJustAdded' + addedCommentCount + '"' + $('#postCommentJustAdded').html() + '</div>')
$('#postCommentJustAdded' + addedCommentCount).fadeIn('slow');
$('#reviews h2 sup').html(parseInt($('#reviews h2 sup').html()) + 1);
$('.comment').find('span').html(parseInt($('.comment').find('span').html()) + 1);
$boxes.find('em').html(parseInt($boxes.find('em').html()) + 1);
});
$(".post-menu [dropdown-source]").off().dropdown();
}
$(document).off('click.like').on('click.like', '[data-likepost]', function () {
var id = $(this).closest('.box').attr('data-id');
var action = 'like';
var delta = 1;
var $boxes = $('.box[data-id="' + id + '"]');
if ($(this).parent().hasClass('active')) {
action = 'dislike';
delta = -1;
$boxes.find('.ico-fav').removeClass('active');
} else {
$boxes.find('.ico-fav').addClass('active');
}
$boxes.find('.ico-fav').find('em').html(parseInt($(this).contents('em').html()) + delta);
dispatchAction({action: action, id: id});
});
$(document).off('click.likeIn').on('click.likeIn', '.favorite', function () {
var id = $('#postViewPopup').attr('data-id');
var $boxes = $('.box[data-id="' + id + '"]');
var action = 'like';
var delta = 1;
if ($(this).hasClass('active')) {
action = 'dislike';
delta = -1;
$(this).removeClass('active');
$boxes.find('.ico-fav').removeClass('active');
} else {
$(this).addClass('active');
$boxes.find('.ico-fav').addClass('active');
}
$boxes.find('.ico-fav').find('em').html(parseInt($boxes.find('.ico-fav').find('em').html()) + delta);
$(this).find('span').html(parseInt($(this).find('span').html()) + delta);
dispatchAction({action: action, id: id});
});
function initFeedEvents() {
$('.jsDeletePost').off('click').on('click', function () {
var el = $(this).closest('.box');
dispatchAction({action: 'deletePost', id: el.attr('data-id')});
el.fadeOut('slow');
});
$('.jsEditPost').off('click').on('click', function () {
var id = $(this).closest('.box').attr('data-id');
dispatchAction(
{action: 'getPost', id: id},
function (data) {
//data = JSON.parse(data);
$('#postEditorContent').attr('data-post-id', id);
$('#postEditorContent .drag-block').parent().remove();
$('#postEditorContent [name="title"]').val(data['title']);
if (data['draft'] == '1') {
$('input[name="draft"]').prop('checked', true);
$('input[name="draft"]').parent().addClass('checked');
} else {
console.log(data['draft']);
$('#jsDraft').hide();
}
data = data['data'];
var c = 1;
for (var i = 0; i < data.length; i++) {
b = data[i];
var dataType = b['data_type'];
if (dataType == 'text') {
addPostEditBlock('postTemplateText');
$('#postBlock' + c + ' textarea').val(b['post_data'][0]);
c++;
}
if (dataType == 'photo') {
$('#postTemplateImage img').attr('src', b['post_data'][0]);
addPostEditBlock('postTemplatePhoto');
$('#postEditorContent .jsNewPhoto .upload-image').replaceWith($('#postTemplateImage').html());
$('#postEditorContent .jsNewPhoto input').addClass('jsDataPhotoComment');
$('#postEditorContent .jsNewPhoto').removeClass('jsNewPhoto');
$('#postBlock' + c + ' input').val(b['post_data'][1]);
c++;
}
if (dataType == 'video') {
addPostEditBlock('postTemplateVideo');
$('#postBlock' + c + ' .jsVideoUrl').val('http://youtu.be/' + b['post_data'][0]);
$('#postBlock' + c + ' .jsVideoDescr').val(b['post_data'][1]);
c++;
}
}
loadPopup('postEditPopup', '', false);
}
);
});
if ($("#postsList [dropdown-source], #postsList [data-dropdown-source]").length>0) {
$("#postsList [dropdown-source], #postsList [data-dropdown-source]").dropdown();
}
}
var relationOperationInProgress = false;
function initRelationsEvents() {
$('.jsRelationButton').off('click').on('click', function () {
if (relationOperationInProgress) {
alert("Операция уже выполняется");
return;
}
relationOperationInProgress = true;
var el = $(this).closest('div');
var relation = el.attr('data-relation-type');
var status = el.attr('data-relation-status');
dispatchAction({
action: relation,
user_id: el.attr('data-user-id')
}, function () {
var newStatus = 0;
if (status == 0) {
if (el.attr('data-awaiting') == 1) {
newStatus = 2;
} else {
newStatus = 1;
}
}
el.attr('data-awaiting', '0');
el.attr('data-relation-status', newStatus);
el.removeClass('js' + relation + status);
el.addClass('js' + relation + newStatus);
relationOperationInProgress = false;
});
});
}
function initProfileEvents() {
$('#sendChatMessage').off('click').on('click', function () {
dispatchAction({
action: 'sendChatMessage',
user_id_t: $('#chatMessageForm [name="user_id_t"]').val(),
message: $('#chatMessageForm [name="message"]').val()
});
$('#chatMessageTemplate p').html($('#chatMessageForm [name="message"]').val());
$('#chatCurrentMessages').append($('#chatMessageTemplate').html());
$('#chatMessageForm [name="message"]').val('');
});
initRelationsEvents();
}
function updateUserProfile() {
$('#popupsContainer').addClass('popup-dimmed');
$("#editProfileForm").ajaxForm({
success: function (data) {
$('#userProfilePopup').fadeOut(1000);
window.location.href=$('#userProfilePopup').attr('data-back-url');
}
}).submit();
}
function uploadAvatar() {
$("#uploadAvatarForm").ajaxForm({
success: function (data) {
var oldAvatar = $('input[name="oldAvatar"]').val();
$('img[src="' + oldAvatar + '"]').attr('src', data);
}
}).submit();
}
function uploadWallpaper() {
$('#myBlogWallpaper').attr('src', '');
$("#uploadWallpaperForm").ajaxForm({
success: function (data) {
$('#myBlogWallpaper').attr('src', data + '?' + Math.random());
}
}).submit();
}
function getYTCode(url) {
if (url.indexOf('youtube.com') > 0) {
var idx = url.indexOf('v=') + 2;
} else if (url.indexOf('youtu.be') > 0) {
var idx = url.indexOf('/', url.indexOf('youtu.be') + 1) + 1;
} else {
sysPopup('Ссылка на видео неверная', $('#attention-popup'))
}
var idx2 = url.indexOf('&', idx);
if (idx2 < 0) idx2 = url.indexOf('#', idx);
if (idx2 < 0) idx2 = url.length;
return url.slice(idx, idx2)
}
function embedPostVideo(el) {
var url;
el = el.closest('.drag-block');
if(el.find('.jsVideoUrl').val()){
url = getYTCode(el.find('.jsVideoUrl').val());
}else{
clearInput(el, url);
return false;
}
if(url){
clearInput(el, url);
}
}
function clearInput(el, url){
var clear = el.find('.btn-submit-video').hasClass('clear');
if(clear){
el.find('.jsPreviewVideo').addClass('add-video-preview').html('');
el.find('.jsVideoUrl').show();
el.find('.jsVideoUrl').next().remove()
el.find('.jsVideoUrl').val('');
el.find('.btn-submit-video').text('Загрузить');
el.find('.btn-submit-video').removeClass('clear');
}else{
if(!url){
sysPopup('Ссылка на видео неверная', $('#attention-popup'));
return false
}
var val = $('.jsVideoUrl').val();
console.log(val.indexOf('http') );
console.log(val.indexOf('http') < 0);
if (val.indexOf('http') > 0) {
$('.jsVideoUrl').val('http://' + val);
}
el.find('.jsPreviewVideo').removeClass('add-video-preview').html('<iframe width="560" height="400" src="' + 'http://www.youtube.com/embed/' + url + '" frameborder="0" allowfullscreen></iframe>');
el.find('.jsVideoUrl').hide();
el.find('.jsVideoUrl').after("<div id=" + $('.jsVideoUrl').attr('id') + " class='text jsVideoUtl'>" + $('.jsVideoUrl').val() + "</div>");
el.find('.btn-submit-video').text('Очистить');
el.find('.btn-submit-video').addClass('clear');
}
};
function initPostBlockEvents() {
$('#postEditorContent .btn-del').off('click').click(function () {
$(this).closest('.drag-block').parent().remove();
postBlockEnumerate();
});
$('#postEditorContent .btn-up').off('click').click(function () {
postBlockMove($(this), -1);
//$postBlock.commentWysiwyg();
postBlockEnumerate()
});
$('#postEditorContent .btn-down').off('click').click(function () {
postBlockMove($(this), 1);
postBlockEnumerate()
});
$('#postEditorContent .btn-submit-video').on('click', function () {
embedPostVideo($(this));
});
}
function postBlockEnumerate() {
var c = 1;
$('#postEditorContent .drag-block').each(function () {
var $this = $(this);
var $postBlock = $this.parent();
$postBlock.commentWysiwyg();
$postBlock.attr({
'id' : 'postBlock' + c,
'data-order': c,
'class' : 'init'
});
if ($this.attr('data-type') == 'text') {
var el=$(this).find('textarea');
el.addClass('jsPostMessage');
}
c++;
});
$('#postEditorContent').attr('data-block-count', c - 1);
$('#postEditorContent textarea, #postEditorContent input').each(function () {
var $this = $(this);
c++;
$this.attr('id', 'postField' + c, 'class');
if ($this.prop('tagName') === 'TEXTAREA') {
$this.autosize().trigger('autosize.resize');
}
});
initPostBlockEvents();
return c - 1;
}
function postBlockMove(el, direction) {
var count = parseInt($('#postEditorContent').attr('data-block-count'));
var idx = parseInt(el.closest('.drag-block').parent().attr('data-order'));
if (direction < 0 && idx <= 1) return;
if (direction > 0 && idx >= count) return;
var idx2 = idx + direction;
$("#postBlock" + idx).swap({
target: "postBlock" + idx2,
opacity: "0.5",
speed: 500,
callback: function () {
var savedFileds = new Array();
$('#postEditorContent textarea, #postEditorContent input').each(function () {
savedFileds.push([$(this).attr('id'), $(this).val()]);
});
html = $("#postBlock" + idx).html();
$("#postBlock" + idx).html($("#postBlock" + idx2).html());
$("#postBlock" + idx2).html(html);
for (var i = 0; i < savedFileds.length; i++) {
$('#' + savedFileds[i][0]).val(savedFileds[i][1]);
}
$("#postBlock" + idx).attr('style', '');
$("#postBlock" + idx2).attr('style', '');
postBlockEnumerate();
}
});
}
function addPostEditBlock(tpl) {
var $input = $('<div>' + $('#' + tpl).html() + '</div>');
$input.find('textarea').autosize();
$('#postEditorContent').append($input);
$('body').animate({ scrollTop: $input.offset().top }, 'slow');
postBlockEnumerate();
}
function uploadPostPhoto() {
addPostEditBlock('postTemplatePhoto');
$("#uploadPostPhotoForm").ajaxForm({
success: function (data) {
data=JSON.parse(data);
if (data['status']!='0') {
alert(data['message']);
$('#postEditorContent .jsNewPhoto').parent().remove();
return;
}
$('#postTemplateImage img').attr('src', data['file']);
$('#postEditorContent .jsNewPhoto .upload-image').replaceWith($('#postTemplateImage').html());
$('#postEditorContent .jsNewPhoto input').addClass('jsDataPhotoComment');
$('#postEditorContent .jsNewPhoto').removeClass('jsNewPhoto');
$('#uploadPostPhotoForm input[type=file]').val('');
}
}).submit();
}
function initReviewBlock(productId) {
var product = shopHistoryItems[productId];
var $editor = $('#postEditorContent');
var $itemId = $editor.find('input[name="itemId"]');
$itemId.val(product.ID);
if (product.reviewed) {
$editor.find('[name=action]').val('addReviewPhoto');
return;
}
$editor.prepend($('#postTemplateReview').html());
var $titleInput = $editor.find('.title-input');
var $reviewBlock = $editor.find('.review-block');
var $productTitle = $editor.find('.review-block__title-link');
$productTitle.html(product.NAME);
$titleInput.hide();
$editor.find('[name=action]').val('addReview');
var $rating = $reviewBlock.find('.rating');
var $outlines = $rating.find('.rating__outlines');
var $filled = $rating.find('.rating__filled');
var $ratingHover = $rating.find('.rating__hover');
var $input = $rating.find('.rating__input');
var $stars = $outlines.children('.rating__star');
var offsets = [];
var rating = 0;
var savedRating = 0;
$.each($stars.get(), function(index, el) {
offsets.push(el.offsetLeft);
});
offsets.push($filled.outerWidth());
$ratingHover.on('mousemove', function(event) {
for (var i = 0; i < offsets.length - 1; i++) {
if (event.offsetX >= offsets[i] && event.offsetX <= offsets[i + 1]) {
break;
}
}
rating = (i + 1);
redrawRating();
});
$ratingHover.on('click', function() {
if (rating === savedRating) {
savedRating = 0;
} else {
savedRating = rating;
}
$input.val(savedRating);
});
$ratingHover.on('mouseleave', function() {
rating = savedRating;
redrawRating();
});
function getRatingFill(rating) {
var index = Math.ceil(rating);
return offsets[index];
}
function redrawRating() {
$filled.css('clip', 'rect(0, ' + getRatingFill(rating) + 'px, auto, 0)');
}
}
function initPostEditorPopup(type, force, productId) {
var $editor = $('#postEditorContent');
type = type || 'text';
$editor.find('.title-input').show();
$editor.find('[name=action]').val('addPost');
$editor.children('.review-block').remove();
if (force === true) {
$editor.children('.init').remove();
}
if (productId) {
initReviewBlock(productId);
}
if ($('#postBlock1').length == 0) {
switch(type) {
case 'photo':
//addPostEditBlock('postTemplatePhoto');
document.uploadPostPhotoForm.imagefile.click();
break;
case 'video':
addPostEditBlock('postTemplateVideo');
break;
default:
addPostEditBlock('postTemplateText');
break;
}
}
}
function updateRating($el, rating) {
var $stars = $el.find('.item-rating__star');
$stars.each(function(index) {
var $star = $(this);
if (index < rating) {
$star.addClass('item-rating__star_filled');
} else {
$star.removeClass('item-rating__star_filled');
}
});
}
function updateRatingMob($el, rating) {
var $stars = $el.find('.rating__star');
$stars.each(function(index) {
var $star = $(this);
if (index < rating) {
$star.addClass('rating__star_on');
} else {
$star.removeClass('rating__star_on');
}
});
}
$(document).ready(function () {
/*
$(document).on('click', '#addPostButtonM', function () {
var draft = 0;
var postId = $('#postEditorContentM').attr('data-post-id');
$('#postEditorContentM').attr('data-post-id', 0);
if ($('input[name="draft"]').prop('checked')) draft = 1;
$('#postEditPopup').fadeOut('slow');
dispatchAction({
action: 'addPost',
title: $('#postEditorContentM [name="title"]').val(),
data: JSON.stringify(json),
draft: draft,
postId: postId
}, function () {
window.location.reload();
});
});*/
$('#addPostButton').off('click').on('click', function () {
$('#popupsContainer').addClass('popup-dimmed');
//tinymce.triggerSave();
var json = [];
$('#postEditorContent').find('.drag-block').each(function () {
var dataType = $(this).attr('data-type');
var data = '';
var $this = $(this);
if (dataType == 'text') {
data = $this.find('textarea').val();
}
if (dataType == 'photo') {
data = $this.find('img').attr('src') + '|||' + $(this).find('input').val();
}
if (dataType == 'video') {
data = getYTCode($this.find('.jsVideoUrl').val()) + '|||' + $this.find('.jsVideoDescr').val();
}
json.push([dataType, data]);
});
var action = $('#postEditorContent').find('input[name="action"]').val();
var rating = $('#postEditorContent').find('input[name="rating"]').val();
var draft = 0;
var postId = $('#postEditorContent').attr('data-post-id');
var itemId = $('#postEditorContent').find('input[name="itemId"]').val();
$('#postEditorContent').attr('data-post-id', 0);
if ($('input[name="draft"]').prop('checked')) draft = 1;
$('#postEditPopup').fadeOut('slow');
switch (action) {
case 'addPost':
dispatchAction({
action: action,
title: $('#postEditorContent').find('input[name="title"]').val(),
data: JSON.stringify(json),
draft: draft,
postId: postId
}, function () {
window.location.reload();
});
break;
case 'addReview':
case 'addReviewPhoto':
dispatchAction({
action: action,
data: JSON.stringify(json),
draft: draft,
postId: postId,
itemId: itemId
}, function () {
var $reviewItem = $('.history-item[data-id="' + itemId + '"]');
var $rating = $reviewItem.find('.item-your-rating');
shopHistoryItems[itemId].reviewed = true;
updateRating($rating, rating);
$rating.removeClass('hide');
$reviewItem.find('.rating-button').addClass('hide');
hidePopup();
});
break;
}
});
$(document).on('click', '#dismissAllNotifications', function () {
var $alertListCount = $('#alertListCount');
var $alertList = $('#alertList');
dispatchAction({
action: 'dismissAllNotifications'
});
$alertListCount
.one('hide.dropdown', function() {
$alertListCount.html('').addClass('disabled').removeClass('has-data');
$alertList.find('li').remove();
})
.trigger('click')
;
$('.js-notification-count').html('');
});
$(document).on('click', '.js-dismiss-notification', function() {
var $dismissLink = $(this);
var id = $dismissLink.data('id');
var $notification = $dismissLink.closest('.js-notification');
var $alertListCount = $('#alertListCount');
var $alertCount = $alertListCount.find('.number');
var alertCount = +$alertCount.html();
dispatchAction({
action: 'dismissNotification',
id: id
});
if (alertCount > 1) {
$notification.slideUp(function() {
$notification.remove();
});
$alertCount.html(--alertCount);
} else {
$alertListCount
.one('hide.dropdown', function() {
$alertListCount.html('').addClass('disabled').removeClass('has-data');
$notification.remove();
})
.trigger('click')
;
}
});
// Репост
$(document).on('click', '.confirmRepost', function(e) {
loadPopup('popup-shadow');
dispatchAction({
action: 'addRepost',
id: $(this).parents('.box').data('repost-id'),
message: $(this).siblings('textarea').val()
},
function (fromServer) {
location.reload();
});
});
$(document).on('click', '.confirmRepostIn', function(e) {
var self = this;
var loc = location.href;
dispatchAction({
action: 'addRepost',
id: $('#postViewPopup').data('id'),
message: $(this).siblings('textarea').val()
},
function (fromServer) {
$('.repost-dropdown').slideUp();
$(self).parents('.repost-dropdown').siblings('.repost.active').hide().siblings('.reposting').show();
});
});
$(document).off('click.comment').on('click.comment', '.comment', function () {
var scrollTo = $('.popupContentSection');
$(window).scrollTop(scrollTo.offset().top);
})
$(document).on('click', '.confirmRepostM', function(e) {
//loadPopup('popup-shadow');
dispatchAction({
action: 'addRepost',
id: $(this).attr('data-id'),
message: $('#postEditorContentM').val()
},
function (fromServer) {
$('.btn-close').trigger('click');
});
});
$(document).on('click', '#addPostButtonM', function () {
$('#addPostButton').hide();
var title = $('#postEditForm [name="title"]').val();
var data = [['text', $('#postEditForm [name="message"]').val()]];
var action = $('.var-block').find('input[name="action"]').val();
$('#uploadedPostPhotos img').each(function () {
data.push(['photo', $(this).attr('src')]);
});
app.overlay.show({ loader: true });
switch (action) {
case 'addPost':
dispatchAction({
action: 'addPost',
title: title,
data: JSON.stringify(data),
mobile: 1
}, function () {
window.location.href = '/mobile/';
});
break;
case 'addReview':
case 'addReviewPhoto':
var itemId = $('.var-block').find('input[name="itemId"]').val();
var $reviewItem = $('.shop-history__item[data-id="' + itemId + '"]');
var $rating = $reviewItem.find('.shop-history__item-rating-wrapper');
var rating = $('.rating__input').val();
dispatchAction({
action: action,
data: JSON.stringify(data),
rating: rating,
itemId: itemId,
title: '',
mobile: 1
}, function (callback) {
console.log(callback);
shopHistoryItems[itemId].reviewed = true;
updateRatingMob($rating, rating);
$rating.removeClass('hide');
$reviewItem.find('.shop-history__item-review-button').addClass('hide');
app.overlay.hide();
$('.btn-close').click();
//app.popup.close();
});
break;
}
});
$('#cancelPostButton').on('click', function(){
$('#popupsContainer .jsClosePopup').click();
});
$('.btn-sort').on('click', function(event){
event.preventDefault();
if ($(this).hasClass('btn-sort-up')){
sortList('shopHistory', 1);
$('.sort a span').addClass('sort-arrow-u').removeClass('sort-arrow-d');
}else {
sortList('shopHistory', 0);
$('.sort a span').addClass('sort-arrow-d').removeClass('sort-arrow-u');
}
$('.sort-box-button em').html($(this).find('em').html());
$('.dropdown').hide();
});
if (useNotifications) {
fetchNotifications();
setInterval(fetchNotifications, 15000);
}
initRelationsEvents();
postBlockEnumerate();
});
function fetchNotifications() {
var $mobile = +(typeof mobile !== 'undefined');
$.ajax({
url: '/sodabox_resources/php/actions.php',
data: {
action: 'getNotifications',
mobile: $mobile
},
success: function (data) {
var c = $(data).filter('li').length;
if (c > 0) {
$('#alertListCount').html('<span class="number museo300">' + c + '</span>');
$('#alertList').html(data);
$('.js-notification-count').html(c).removeClass('hide');
if (typeof initPopupEvents === 'function') initPopupEvents('#alertList');
} else {
$('#alertListCount').html('');
$('#alertList').html('');
$('.js-notification-count').html('').addClass('hide');
}
}
});
}
function sortList(container, direction) {
var mylist = $('#'+container);
var listitems = mylist.children('div');
listitems.sort(function (a, b) {
var compA = $(a).find('.buy-date').attr('timestamp');
var compB = $(b).find('.buy-date').attr('timestamp');
if (direction)
return compA-compB;
else
return compB-compA;
});
$.each(listitems, function (idx, itm) {
mylist.append(itm);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment