Skip to content

Instantly share code, notes, and snippets.

@valex
Created April 1, 2015 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valex/9064d9223f9306459766 to your computer and use it in GitHub Desktop.
Save valex/9064d9223f9306459766 to your computer and use it in GitHub Desktop.
function getBaseUrl(){
if (!window.location.origin)
window.location.origin = window.location.protocol+"//"+window.location.host;
return window.location.origin;
}
function showNotices(msgs, options){
if(!$.isArray(msgs))
return;
msgs.forEach(function(msg) {
showNotice($.extend(options, {text:msg}));
});
}
function isInt(x) {
var y=parseInt(x);
if (isNaN(y)) return false;
return x==y && x.toString()==y.toString();
}
function isArray(object)
{
if (object.constructor === Array) return true;
else return false;
}
function empty(obj) {
if(!isset(obj))
return true;
if(obj == null)
return true;
return false;
}
function isset(obj) {
if(typeof obj == 'undefined')
return false;
return true;
}
function ask_confirm(msg){
msg = typeof msg !== 'undefined' ? msg : 'а’б‹ бƒаВаЕб€аЕаНб‹?';
if (confirm(msg)) {
return true;
} else {
return false;
}
}
function showNotice(options){
var defaults = {
//layout: 'bottomLeft',
layout: 'center',
type: 'success',
timeout: 2000 // delay for closing event. Set false for sticky notifications
};
// http://ned.im/noty/#options
options = $.extend(defaults, options);
return noty(options);
}
// -------------------------------------------------------
if ( Object.prototype.hasOwnProperty ) {
var hasOwnProperty = function(obj, prop) {
return obj.hasOwnProperty(prop);
}
}
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
// -------------------------------------------------------
function ajaxResponseHandler(response){
//var r = JSON.parse(response);
var r = response;
if ( hasOwnProperty(r, 'refresh'))
{
location.reload(r.refresh);
return {
success: false
}
}
if ( !hasOwnProperty(r, 'success')){
return {
success: false,
msgs: ['some strange error']
};
}
return r;
}
function addNotice(content)
{
if(!content)
return;
}
Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
jQuery.fn.extend({
insertAtCaret: function(myValue, myValueE){
return this.each(function(i) {
if (document.selection) {
//For browsers like Internet Explorer
this.focus();
sel = document.selection.createRange();
sel.text = myValue + myValueE;
this.focus();
}
else if (this.selectionStart || this.selectionStart == '0') {
//For browsers like Firefox and Webkit based
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos)+myValue+this.value.substring(startPos,endPos)+myValueE+this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = ((startPos + myValue.length) + this.value.substring(startPos,endPos).length);
this.scrollTop = scrollTop;
} else {
this.value += myValue;
this.focus();
}
})
}
});
jQuery.fn.extend({
htmlspecialchars: function(str){
str = document.createElement( 'a' ).appendChild(
document.createTextNode( str ) ).parentNode.innerHTML;
str = str.replace(/\"/g, """);
return str;
}
});
RegExp.escape= function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
window.onerror = function (message, filename, linenumber) {
var strLine = "JS error: " + message + " on line " + linenumber + " for " + filename + ' Browser: '+ get_browser() + ' version: '+ get_browser_version();
var request={
content:strLine
};
$.post(getBaseUrl() + '/createNotice',request).done(
function(response){
var r = ajaxResponseHandler(response);
switch(r.success){
case true:
if ( hasOwnProperty(r, 'msgs'))
{
showNotices(r.msgs);
}
break;
case false:
if ( hasOwnProperty(r, 'msgs'))
{
showNotices(r.msgs, {timeout: false, type: 'error'});
}
break;
}
}
);
};
window.addEventListener("focus",function(event) {
if(!isset(AUTH) || AUTH != '1')
return;
if(event.target!==window)
return;
if(typeof getCookie('logged') == "undefined"){
location.reload();
}
});
function get_browser(){
var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem=/\brv[ :]+(\d+)/g.exec(ua) || [];
return 'IE '+(tem[1]||'');
}
if(M[1]==='Chrome'){
tem=ua.match(/\bOPR\/(\d+)/)
if(tem!=null) {return 'Opera '+tem[1];}
}
M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}
return M[0];
}
function get_browser_version(){
var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem=/\brv[ :]+(\d+)/g.exec(ua) || [];
return 'IE '+(tem[1]||'');
}
if(M[1]==='Chrome'){
tem=ua.match(/\bOPR\/(\d+)/)
if(tem!=null) {return 'Opera '+tem[1];}
}
M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}
return M[1];
}
// аВаОаЗаВб€аАб‰аАаЕб‚ cookie б аИаМаЕаНаЕаМ name, аЕбаЛаИ аЕбб‚бŒ, аЕбаЛаИ аНаЕб‚, б‚аО undefined
function getCookie(name) {
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
}
function setCookie(name, value, options) {
options = options || {};
var expires = options.expires;
if (typeof expires == "number" && expires) {
var d = new Date();
d.setTime(d.getTime() + expires*1000);
expires = options.expires = d;
}
if (expires && expires.toUTCString) {
options.expires = expires.toUTCString();
}
value = encodeURIComponent(value);
var updatedCookie = name + "=" + value;
for(var propName in options) {
updatedCookie += "; " + propName;
var propValue = options[propName];
if (propValue !== true) {
updatedCookie += "=" + propValue;
}
}
document.cookie = updatedCookie;
}
function deleteCookie(name) {
setCookie(name, "", { expires: -1 });
}
function initCaptionJs($el){
$el.captionjs({
'class_name' : 'captionjs img-responsive',
'mode' : 'stacked', // default | static | animated | hide
//'debug_mode' : true, // Output debug info to the JS console
'force_dimensions': true // Force the dimensions in case they can't be detected (e.g., image is not yet painted to viewport)
});
}
$(document).ready(function(){
// Disable auto discover for all elements:
Dropzone.autoDiscover = false;
// This will automatically grab the 'title' attribute and replace
// the regular browser tooltips for all <a> elements with a title attribute!
$('[data-tooltip!=""]').qtip({ // Grab all elements with a non-blank data-tooltip attr.
content: {
attr: 'data-tooltip', // Tell qTip2 to look inside this attr for its content
//button: 'Close',
title: function(event, api) {
// Retrieve content from data-title attribute of the $('.selector') element
return $(this).attr('data-title');
}
},
position: {
my: 'bottom center', // Position my top left...
at: 'top center', // at the bottom right of...
target: this, // my target
viewport: $(window),
adjust: {
method: 'shift'
}
},
style: { classes: 'qtip-bootstrap' },
hide: {
fixed: true,
delay: 200
}
});
$('img.caption').each(function() {
initCaptionJs($(this));
});
/*
$('img.caption').captionjs({
'class_name' : 'captionjs img-responsive',
'mode' : 'stacked', // default | static | animated | hide
//'debug_mode' : true, // Output debug info to the JS console
'force_dimensions': true // Force the dimensions in case they can't be detected (e.g., image is not yet painted to viewport)
});
*/
$('body').on('hover', '.has-controls', function() {
$( this ).find('.row_controls').css('display', 'block');
});
$('body').on('mouseleave', '.has-controls', function() {
$( this ).find('.row_controls').css('display', 'none');
});
$("div.comments").each(function(){
var commentsBlockEl = this;
while(commentsBlockEl.getAttribute('class') != 'comments'){
commentsBlockEl = commentsBlockEl.parentNode;
}
var commentBlockID = commentsBlockEl.getAttribute('id');
var commentsBlock = new CommentsBlock({
comment_owner_model: $(commentsBlockEl).data('model'),
comment_owner_model_id: $(commentsBlockEl).data('id'),
blockID: commentBlockID
});
commentsBlock.init();
});
if($('#search').length > 0)
{
$('#search').autocomplete({
delay: 500,
source: function( request, autocomplete_response ) {
var term = $.trim(request.term);
if(term == '')
return;
$.post(getBaseUrl() + '/searchAutocomlete',
{
term: term
},
function(response){
var r = ajaxResponseHandler(response);
switch(r.success){
case true:
$.map(r.result, function(obj) {
var score = LiquidMetal.score(obj.username, term);
//if(score < 0.5) {
// return null; // jQuery.map compacts null values
//}
return obj.score = score;
});
r.result.sort(function(a,b) { return a['score'] < b['score'] }) ;
autocomplete_response(r.result );
break;
case false:
if ( hasOwnProperty(r, 'msgs'))
{
showNotices(r.msgs, {timeout: false, type: 'error'});
}
break;
}
}
);
},
select: function( event, ui ) {
$( "#search" ).val( ui.item.username );
window.location.href = BASE+'/id'+ui.item.id;
return false;
}
}).data('ui-autocomplete')._renderItem=function(ul, item ) {
return $( "<li>" )
.append('<a>'+item.username+'</a>')
.appendTo( ul );
};
$('#search').keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
var request = $(this).val();
window.location.href = "/search?q="+decodeURIComponent(request);
//console.log(decodeURIComponent(request));
//event.preventDefault();
//$("form").submit();
}
});
}
});
/* Paginator */
var Paginator = function(total_items){
this._total_items = total_items;
this._page_show_moreEl = document.getElementById('page_show_more');
this._wall_posts_counterEl = document.getElementById('wall_posts_counter');
var numPageItems = this.countPageItems();
if(numPageItems == 0)
this.placeNoItemsEl();
else if(numPageItems < this._total_items)
this.placeShowMoreButton();
};
Paginator.prototype = {
countPageItems:function(){
return $("#wall_posts .wall_post").length;
},
placeNoItemsEl:function(){
$(this._page_show_moreEl).append('<div class="well well-sm" role="alert">ааЕб‚ аЗаАаПаИбаЕаЙ</div>');
},
placeShowMoreButton:function(){
$(this._page_show_moreEl).append('<button class="show_more_btn btn btn-primary btn-block btn-sm">аŸаОаКаАаЗаАб‚бŒ аЕб‰аЕ</button>');
},
clearShowMore:function(){
$(this._page_show_moreEl).empty();
},
checkShowMoreBtnNeeded:function(){
if(this.countPageItems() >= this._total_items)
this.clearShowMore();
},
incrementItems:function(){
this._total_items = parseInt(this._total_items) + 1;
},
decrementItems:function(){
if(parseInt(this._total_items) > 0)
this._total_items = parseInt(this._total_items) - 1;
},
updateItemsCounter:function(){
$(this._wall_posts_counterEl).text(this._total_items);
}
};
/* Wall Class */
var Wall = function(wall_owner_model, wall_owner_model_id, total_items, auth_id){
this._user_id = parseInt(auth_id),
this._wall_owner_model = wall_owner_model,
this._wall_owner_model_id = parseInt(wall_owner_model_id),
this.wallForm = new WallForm();
if(this.wallForm._submit_post_boxEl != null){
this.wallForm.init();
}
this.paginator = new Paginator(total_items);
this._wall_postsEl = document.getElementById('wall_posts');
this.initMagnificGalleries();
};
Wall.prototype = {
initMagnificGallery:function(el){
return $(el).magnificPopup({
delegate: 'div.wallpost-image', // the selector for gallery item
type: 'image',
gallery: {
enabled:true
}
});
},
initMagnificGalleries:function(){
$('.wall_post').each(function() { // the containers for all your galleries
$(this).magnificPopup({
delegate: 'div.wallpost-image', // the selector for gallery item
type: 'image',
gallery: {
enabled:true
}
});
});
},
getMorePosts:function(last_wallpost_id){
$.post(getBaseUrl() + '/wallpost/showmore',
{
last_wallpost_id: last_wallpost_id
},
$.proxy(function(response){
var r = ajaxResponseHandler(response);
switch(r.success){
case true:
this.placeMorePosts(r.htmls);
this.paginator.checkShowMoreBtnNeeded();
break;
case false:
if ( hasOwnProperty(r, 'msgs'))
{
showNotices(r.msgs, {timeout: false, type: 'error'});
}
break;
}
this.wallForm.afterResponse();
},this));
},
placeMorePosts:function(more_posts){
if(!$.isArray(more_posts))
return;
more_posts.forEach($.proxy(function(html) {
$(this._wall_postsEl).append(this.initMagnificGallery(html));
},this));
},
showMorePosts:function(last_wallpost_id){
var more_posts = this.getMorePosts(last_wallpost_id);
},
getLastChildId:function(){
var $last_post = $('.wall_post').last();
if($last_post)
return $last_post.data('id');
return 0;
},
afterSuccessWallPostCreated:function(){
if(this.paginator._total_items==0)
this.paginator.clearShowMore();
this.paginator.incrementItems();
this.paginator.updateItemsCounter();
},
createNewPost:function(content){
if(!isInt(this._user_id))
return;
if(this.wallForm.isPostEmpty() && ! this.wallForm.isAttachedImagesExists())
return;
this.wallForm.disablePostBtn();
this.wallForm.showSpinner();
this.wallForm.clearErrors();
$.post(getBaseUrl() + '/wallpost/create',
{
user_id: this._user_id,
wall_owner_model: this._wall_owner_model,
wall_owner_model_id: this._wall_owner_model_id,
images: this.wallForm.getAttachedImagesIds(),
content: this.wallForm.getPost()
},
$.proxy(function(response){
var r = ajaxResponseHandler(response);
switch(r.success){
case true:
$(this._wall_postsEl).prepend(this.initMagnificGallery(r.html));
this.wallForm.afterSuccessWallPostCreated();
this.afterSuccessWallPostCreated();
break;
case false:
if ( hasOwnProperty(r, 'msgs'))
{
this.wallForm.showErrors(r.msgs);
}
break;
}
this.wallForm.afterResponse();
},this));
}
};
/* WallPost Class */
var WallPost = function(id){
this.id = parseInt(id);
this.wallPostContainer = document.getElementById('wall_post'+this.id);
this.onWallPostDelete = function(){};
this.onWallPostRestore = function(){};
};
WallPost.prototype = {
remove:function(){
this.hideRemoveButton();
this.showMask();
$.when(this.ajaxRemove()).done($.proxy(function(response){
var r = ajaxResponseHandler(response);
switch(r.success){
case true:
var $wrapper = $('<div></div>').addClass('wrapper').css('display', 'none');
$(this.wallPostContainer).find('.post_table').wrap($wrapper);
this.onWallPostDelete();
this.showAfterRemoveMessage();
break;
case false:
if ( hasOwnProperty(r, 'msgs'))
{
showNotices(r.msgs, {timeout: false, type: 'error'});
}
break;
}
this.hideMask();
},this));
},
ajaxRemove:function(){
return $.post(getBaseUrl() + '/wallpost/delete',
{
wallpost_id: this.id
});
},
restore:function(){
this.showMask();
$.when(this.ajaxRestore()).done($.proxy(function(response){
var r = ajaxResponseHandler(response);
switch(r.success){
case true:
$(this.wallPostContainer).find('.wrapper').children().unwrap();
this.onWallPostRestore();
this.hideAfterRemoveMessage();
this.showRemoveButton();
break;
case false:
if ( hasOwnProperty(r, 'msgs'))
{
showNotices(r.msgs, {timeout: false, type: 'error'});
}
break;
}
this.hideMask();
},this));
//$(this.wallPostContainer).find("div.after_post_destroy").remove();
//$(this.wallPostContainer).children().each(function( index ) {
// $( this ).css('display', 'block');
//});
},
ajaxRestore:function(){
return $.post(getBaseUrl() + '/wallpost/restore',
{
wallpost_id: this.id
});
},
hideRemoveButton:function(){
$(this.wallPostContainer).find("button.destroy").css('display', 'none');
},
showRemoveButton:function(){
$(this.wallPostContainer).find("button.destroy").css('display', 'block');
},
hideMask:function(){
$(this.wallPostContainer).css('backgroundColor', 'transparent');
},
showMask:function(){
$(this.wallPostContainer).css('backgroundColor', '#EEE');
//var $mask = $(this.wallPostContainer).find('div.mask');
//if($mask.length <= 0){
// $mask = $("div.mask:last");
// $mask = $mask.clone().css('display', 'block').css('position', 'relative');
// $(this.wallPostContainer).append($mask);
//}else{
// $mask.css('display', 'block');
//}
},
showAfterRemoveMessage:function(){
var $after_post_destroyEl = $(this.wallPostContainer).find('div.after_post_destroy');
if($after_post_destroyEl.length <= 0){
$after_post_destroyEl = $("div.after_post_destroy:last").clone();
//$for_replaceEl.find("a.restore").attr('data-id', this.id);
$(this.wallPostContainer).on( "click", "div.after_post_destroy a.restore", $.proxy(function() {
this.restore();
},this));
$after_post_destroyEl.css('display', 'block');
$(this.wallPostContainer).append($after_post_destroyEl.get(0).outerHTML);
}else{
$after_post_destroyEl.css('display', 'block');
}
//$("#wall_post"+this.id).html($for_replaceEl.get(0).outerHTML);
},
hideAfterRemoveMessage:function(){
var $after_post_destroyEl = $(this.wallPostContainer).find('div.after_post_destroy');
$after_post_destroyEl.css('display', 'none');
}
};
/* WallForm Class */
var WallForm = function(){
this._submit_post_boxEl = document.getElementById('submit_post_box');
this._submit_post_errorsEl = document.getElementById('submit_post_errors');
this._wall_post_fieldEl = document.getElementById('wall_post_field');
this._submit_postEl = document.getElementById('submit_post');
this._submit_post_btnEl = document.getElementById('submit_post_btn');
this._submit_post_spinnerEl = document.getElementById('submit_post_spinner');
this.attachedImages = {};
};
WallForm.prototype = {
init:function(){
$(this._wall_post_fieldEl).autosize();
$(this._wall_post_fieldEl).on('focusin', $.proxy(function(){
this.focusinState();
}, this));
//$(this._wall_post_fieldEl).on('focusout', function(){
// WallForm.focusoutState();
//});
$(document).on('click', $.proxy(function(e){
// hide only if click out of the box
if($(this._submit_post_boxEl).has(e.target).length <= 0){
if(this.isPostEmpty() && ! this.isAttachedImagesExists()){
this.clearErrors();
this.focusoutState();
}
}
},this));
},
attachImage:function(id, file){
this.attachedImages[id] = file;
},
detachImage:function(file){
for (var id in this.attachedImages) {
if ( ! this.attachedImages.hasOwnProperty(id))
continue;
if(this.attachedImages[id].lastModified == file.lastModified)
delete this.attachedImages[id];
}
},
isAttachedImagesExists:function(){
return ! jQuery.isEmptyObject(this.attachedImages);
},
getAttachedImagesIds:function(){
var arr=[];
for (var id in this.attachedImages) {
if ( ! this.attachedImages.hasOwnProperty(id))
continue;
arr.push(id);
}
return arr;
},
showErrors:function(msgs){
if( ! $.isArray(msgs))
return;
msgs.forEach($.proxy(function(msg) {
$(this._submit_post_errorsEl).append('<p>'+msg+'</p>');
},this));
},
clearTextarea:function(){
this._wall_post_fieldEl.value = '';
},
clearImagesPreview:function(){
window.wallpostDropzone.removeAllFiles();
},
afterSuccessWallPostCreated: function(){
this.clearTextarea();
this.clearImagesPreview();
$(this._wall_post_fieldEl).trigger('autosize.resize');
},
afterResponse: function(){
this.allowPostBtn();
this.hideSpinner();
},
showSpinner:function(){
$(this._submit_post_spinnerEl).css('display', 'inline-block');
},
hideSpinner:function(){
$(this._submit_post_spinnerEl).css('display', 'none');
},
disablePostBtn:function(){
$(this._submit_post_btnEl).attr('disabled', true);
},
allowPostBtn:function(){
$(this._submit_post_btnEl).removeAttr('disabled');
},
getPost:function(){
return this._wall_post_fieldEl.value.trim();
},
isPostEmpty:function(){
if(this.getPost()=='')
return true;
return false;
},
clearErrors:function(){
this._submit_post_errorsEl.innerHTML = '';
},
focusinState: function(){
$(this._wall_post_fieldEl).trigger('autosize.resize');
this.showSubmitPost();
},
focusoutState: function(){
$(this._wall_post_fieldEl).css('height', '41px');
this.hideSubmitPost();
},
hideSubmitPost: function(){
$(this._submit_postEl).css('display', 'none');
},
showSubmitPost: function(){
$(this._submit_postEl).css('display', 'block');
}
};// end WallForm Class
// CommentPaginator class
var CommentPaginator = function(ob){
this.counterElement = null;
this.itemSelector = null;
this.showMoreElement = null;
this.total_items = 0;
$.extend(this, ob);
};
CommentPaginator.prototype = {
init:function(){
this.total_items = parseInt(this.counterElement.innerHTML);
var numItems = this.countItems();
if(numItems < parseInt(this.total_items))
this.placeShowMoreButton();
},
getLastItemId:function(){
return $(this.itemSelector).first().data('id');
},
countItems:function(){
return $(this.itemSelector).length;
},
placeShowMoreButton:function(){
$(this.showMoreElement).append('<button class="show_more_btn btn btn-primary btn-block btn-sm">аŸаОаКаАаЗаАб‚бŒ аЕб‰аЕ</button>');
},
incrementItems:function(){
this.total_items += 1;
$(this.counterElement).text(this.total_items);
},
decrementItems:function(){
this.total_items -= 1;
$(this.counterElement).text(this.total_items);
},
clearShowMore:function(){
$(this.showMoreElement).empty();
}
};
// end CommentPaginator
// CommentsBlock Class
var CommentsBlock = function(ob){
this.comment_owner_model = null;
this.comment_owner_model_id = null;
this.blockID = null;
this.showMoreElement = null;
this.commentForm = null;
this.paginator = null;
this.comments = new Object;
$.extend(this, ob);
};
CommentsBlock.prototype = {
init: function(){
if(!this.blockID)
return;
this.showMoreElement = $('#'+this.blockID+' div.show_more').get(0);
this.paginator = new CommentPaginator({
counterElement:$('#'+this.blockID+' span.comment_posts_counter').get(0),
itemSelector:'#'+this.blockID+' div.comment',
showMoreElement:this.showMoreElement
});
this.paginator.init();
var self=this;
$('#'+this.blockID+' div.comment').each(function(){
var id = parseInt($(this).data('id'));
if(!isInt(id))
return;
self.addCommentInstance(id);
});
$('#'+this.blockID).on('click', 'div.row_icon_delete', function(){
var id = parseInt($(this).data('id'));
if(!isInt(id))
return;
if(typeof self.comments[id] == 'undefined')
return;
self.comments[id].delete();
});
$('#'+this.blockID).on('click', 'button.show_more_btn', $.proxy(function(){
this.showMore(this.paginator.getLastItemId());
},this));
$('#'+this.blockID+' input.comment_fakeinput').focusin($.proxy(function(){
if(!this.commentForm){
this.commentForm = new CommentForm({blockID: this.blockID});
this.commentForm.init();
$(this.commentForm.submit_comment_btn).on('click', $.proxy(function(){
if(this.commentForm.isInputEmpty()==true)
return;
this.commentForm.showSpinner();
this.commentForm.disableSubmitBtn();
this.commentForm.clearErrors();
$.when(this.sendNewComment()).done($.proxy(function(response){
this.commentForm.hideSpinner();
this.commentForm.allowSubmitBtn();
}, this));
}, this));
}
this.commentForm.turnOn();
}, this));
},
addCommentInstance:function(id){
var comment = new CommentItem(id);
var self=this;
comment.onCommentDelete = function(){
self.paginator.decrementItems();
};
comment.onCommentRestore = function(){
self.paginator.incrementItems();
};
this.comments[id] = comment;
},
showMore:function(last_item_id){
return $.post(BASE + '/comment/showmore',
{
last_item_id: last_item_id
},
$.proxy(function(response){
var r = ajaxResponseHandler(response);
switch(r.success){
case true:
if(!$.isArray(r.htmls))
return;
this.placeMoreItems(r.htmls);
if(r.show_more_btn_needed == 0)
this.paginator.clearShowMore();
r.htmls.forEach($.proxy(function(html) {
var self=this;
$(html).filter('div.comment').each(function(){
var id = parseInt($(this).data('id'));
if(!isInt(id))
return;
self.addCommentInstance(id);
});
},this));
break;
case false:
if ( hasOwnProperty(r, 'msgs'))
{
showNotices(r.msgs, {timeout: false, type: 'error'});
}
break;
}
//this.wallForm.afterResponse();
},this));
},
placeMoreItems:function(more_items){
if(!$.isArray(more_items))
return;
more_items.forEach($.proxy(function(html) {
$(this.showMoreElement).after(html);
},this));
},
sendNewComment:function(){
return $.post(getBaseUrl() + '/comment/create',
{
comment_owner_model: this.comment_owner_model,
comment_owner_model_id: this.comment_owner_model_id,
content: this.commentForm.getInput()
},
$.proxy(function(response){
var r = ajaxResponseHandler(response);
switch(r.success){
case true:
this.commentForm.clearInput();
$(this.commentForm.comment_form_box).before(r.html);
var self=this;
$(r.html).filter('div.comment').each(function(){
var id = parseInt($(this).data('id'));
if(!isInt(id))
return;
self.addCommentInstance(id);
});
this.paginator.incrementItems();
this.commentForm.turnOff();
break;
case false:
if ( hasOwnProperty(r, 'msgs'))
{
this.commentForm.showErrors(r.msgs);
}
break;
}
}, this));
}
};
// end CommentsBlock Class
// CommentItem Class
var CommentItem = function(id){
this.id = parseInt(id);
this.commentContainer = document.getElementById('comment_'+this.id);
this.removeBtn = $('#comment_'+this.id+' div.row_controls').get(0);
$(this.commentContainer).on( "click", "a.restore", $.proxy(function() {
this.restore();
},this));
this.onCommentDelete = function(){};
this.onCommentRestore = function(){};
}
CommentItem.prototype = {
delete:function(){
if(!this.id)
return;
$(this.removeBtn).remove();
this.showMask();
$.when(this.ajaxDelete()).done($.proxy(function(response){
var r = ajaxResponseHandler(response);
switch(r.success){
case true:
var $wrapper = $('<div></div>').addClass('wrapper').hide();
$(this.commentContainer).find('.post_table').wrap($wrapper);
this.onCommentDelete();
this.showAfterDeleteMsg();
break;
case false:
if ( hasOwnProperty(r, 'msgs'))
{
showNotices(r.msgs, {timeout: false, type: 'error'});
}
break;
}
this.hideMask();
},this));
},
ajaxDelete:function(){
return $.post(getBaseUrl() + '/comment/delete',
{
comment_id: this.id
});
},
restore:function(){
this.showMask();
$.when(this.ajaxRestore()).done($.proxy(function(response){
var r = ajaxResponseHandler(response);
switch(r.success){
case true:
this.onCommentRestore();
this.hideAfterDeleteMsg();
$(this.commentContainer).find('.wrapper').children().unwrap();
$(this.commentContainer).append(this.removeBtn);
break;
case false:
if ( hasOwnProperty(r, 'msgs'))
{
showNotices(r.msgs, {timeout: false, type: 'error'});
}
break;
}
this.hideMask();
},this));
},
ajaxRestore:function(){
return $.post(getBaseUrl() + '/comment/restore',
{
comment_id: this.id
});
},
showMask:function(){
$(this.commentContainer).css('backgroundColor', '#EFEFEF');
},
hideMask:function(){
$(this.commentContainer).css('backgroundColor', 'transparent');
},
showAfterDeleteMsg:function(){
var $after_comment_removeEl = $(this.commentContainer).find('div.after_comment_remove');
if($after_comment_removeEl.length <= 0){
$after_comment_removeEl = $(this.commentContainer).parent().find('div.after_comment_remove').clone();
$after_comment_removeEl.show();
$(this.commentContainer).append($after_comment_removeEl.get(0).outerHTML);
}else{
$after_comment_removeEl.show();
}
},
hideAfterDeleteMsg:function(){
var $after_comment_removeEl = $(this.commentContainer).find('div.after_comment_remove');
$after_comment_removeEl.hide();
}
}
// end CommentItem class
// CommentForm Class
var CommentForm = function(ob){
this.blockID = null;
this.comment_form_box = null;
this.fakeinput = null;
this.input = null;
this.submit_comment_box = null;
this.submit_comment_spinner = null;
this.comment_form_errors = null;
$.extend(this, ob);
};
CommentForm.prototype = {
init:function(){
if(!this.blockID)
return;
this.comment_form_box = $('#'+this.blockID+' div.comment_form_box').get(0);
this.fakeinput = $('#'+this.blockID+' input.comment_fakeinput').get(0);
this.input = $('#'+this.blockID+' textarea.comment_input').get(0);
this.submit_comment_box = $('#'+this.blockID+' div.submit_comment_box').get(0);
this.submit_comment_spinner = $('#'+this.blockID+' i.submit_comment_spinner').get(0);
this.submit_comment_btn = $('#'+this.blockID+' button.submit_comment_btn').get(0);
this.comment_form_errors = $('#'+this.blockID+' div.comment_form_errors').get(0);
$(this.input).autosize();
$(document).on('click', $.proxy(function(e){
// hide only if click out of the box
if($(this.comment_form_box).has(e.target).length <= 0){
if(this.isInputEmpty()){
this.turnOff();
}
}
},this));
},
turnOn:function(){
$(this.fakeinput).hide();
this.showTextarea();
$(this.submit_comment_box).show();
},
turnOff:function(){
this.hideTextarea();
$(this.fakeinput).show();
$(this.submit_comment_box).hide();
},
showErrors:function(msgs){
if(!$.isArray(msgs))
return;
msgs.forEach($.proxy(function(msg) {
$(this.comment_form_errors).append('<p>'+msg+'</p>');
},this));
},
clearErrors:function(){
this.comment_form_errors.innerHTML = '';
},
showTextarea:function(){
$(this.input).show().focus();
},
hideTextarea:function(){
$(this.input).hide();
},
getInput:function(){
return this.input.value.trim();
},
isInputEmpty:function(){
if(this.getInput()=='')
return true;
return false;
},
clearInput:function(){
this.input.value = '';
},
showSpinner:function(){
$(this.submit_comment_spinner).css('display', 'inline-block');
},
hideSpinner:function(){
$(this.submit_comment_spinner).hide();
},
disableSubmitBtn:function(){
$(this.submit_comment_btn).attr('disabled', true);
},
allowSubmitBtn:function(){
$(this.submit_comment_btn).removeAttr('disabled');
}
};
// end CommentForm Class
/* GoogleMap Class */
var GoogleMap = function(lat, lng){
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(lat, lng),
mapTypeId: google.maps.MapTypeId.ROADMAP //set map type to road map
};
this.map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
this.homeLatlng = new google.maps.LatLng(lat, lng); //set default coordinates
this.homeMarker = new google.maps.Marker({ //set marker
position: this.homeLatlng, //set marker position equal to the default coordinates
map: this.map, //set map to be used by the marker
draggable: true //make the marker draggable
});
};
GoogleMap.prototype = {
initAutocomplete:function(){
// https://developers.google.com/maps/documentation/javascript/places-autocomplete?hl=ru
var input = document.getElementById('gmap_autocomplete'); //get element to use as input for autocomplete
$(input).on('click',function(){ this.select(); });
var autocompleteOptions = {
componentRestrictions: {country: 'ua'}
};
this.autocomplete = new google.maps.places.Autocomplete(input, autocompleteOptions); //set it as the input for autocomplete
this.autocomplete.bindTo('bounds', this.map); //bias the results to the maps viewport
//executed when a place is selected from the search field
google.maps.event.addListener(this.autocomplete, 'place_changed', $.proxy(function(){
//get information about the selected place in the autocomplete text field
var place = this.autocomplete.getPlace();
if (place.geometry.viewport){ //for places within the default view port (continents, countries)
this.map.fitBounds(place.geometry.viewport); //set map center to the coordinates of the location
} else { //for places that are not on the default view port (cities, streets)
this.map.setCenter(place.geometry.location); //set map center to the coordinates of the location
this.map.setZoom(17); //set a custom zoom level of 8
}
this.homeMarker.setMap(this.map); //set the map to be used by the marker
this.homeMarker.setPosition(place.geometry.location); //plot marker into the coordinates of the location
},this));
},
// http://stackoverflow.com/questions/4537164/google-maps-v3-set-single-marker-point-on-map-click
placeMarker:function(location) {
// first remove all markers if there are any
this.deleteOverlays();
this.homeMarker = new google.maps.Marker({
position: location,
map: this.map
});
// add marker in markers array
// markersArray.push(marker);
//map.setCenter(location);
},
// Deletes all markers in the array by removing references to them
deleteOverlays: function() {
this.homeMarker.setMap(null);
},
getGeocode:function (lat, lng){
return $.get('http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+lng+'&sensor=false&language=ru');
}
};// end GoogleMap Class
// Place class
var Place = function(lat, lng, description, owner_model, owner_model_id){
this.lat = lat;
this.lng = lng;
this.description = description;
this.owner_model = owner_model;
this.owner_model_id = parseInt(owner_model_id);
};
Place.prototype = {
ajaxCreate:function(){
return $.post(BASE + '/place/create',
{
owner_model: this.owner_model,
owner_model_id: this.owner_model_id,
description: this.description,
lat: this.lat,
lng: this.lng
});
}
};// end Place class
// SearchPageController class
var SearchPageController = function(ob){
this.show_more_btn_el = null;
this.items_container_el = null;
this.item_selector = null;
this.total_items = null;
this.total_items_el = null;
$.extend(this, ob);
this.last_timestamp = 0;
this.init();
};
SearchPageController.prototype = {
init: function () {
this.updateShowMoreBtnVisible();
},
postQuery:function(data){
return $.ajax({
type: "POST",
url: getBaseUrl() + '/search',
data: data
}).done($.proxy(function(response){
var r = ajaxResponseHandler(response);
switch(r.success){
case true:
this.onQuerySuccess(r);
break;
case false:
if ( hasOwnProperty(r, 'msgs'))
{
showNotices(r.msgs, {timeout: 15000, type: 'error'});
}
break;
}
},this));
},
onQuerySuccess:function(r){
if(parseInt(r.timestamp) < this.getLastTimestamp()){
return;
}
else
this.setLastTimestamp(parseInt(r.timestamp));
if(r.type == 'new_search'){
this.clear();
this.hideShowMore();
}
if(isset(r.totalItems))
{
this.setTotal(r.totalItems);
this.updateTotalItems();
}
if(isArray(r.views))
this.placeItems(r.views);
else
this.placeItems([]);
},
updateTotalItems:function(){
$(this.total_items_el).text(this.total_items);
},
placeItems:function(arr){
jQuery.each(arr, $.proxy(function(index, value) {
this.placeItem(value);
}, this));
this.updateShowMoreBtnVisible();
},
placeItem:function(item){
$(this.items_container_el).append(item);
},
updateShowMoreBtnVisible:function(){
if(this.countItems() < this.total_items)
this.showShowMore();
else
this.hideShowMore();
},
countItems:function(){
return $(this.item_selector).length;
},
clear:function(){
$(this.item_selector).remove();
},
showShowMore:function(){
$(this.show_more_btn_el).show();
},
hideShowMore:function(){
$(this.show_more_btn_el).hide();
},
setTotal:function(num){
this.total_items = num;
},
setLastTimestamp:function(num){
this.last_timestamp = num;
},
getLastTimestamp:function(){
return this.last_timestamp;
}
};
// end SearchPageController class
// SearchRequest
var SearchRequest = function(ob){
this.type = 'new_search'; // show_more
this.alreadyShown = 0;
this.timestamp = new Date().getTime();
this.params = {};
$.extend(this, ob);
this.init();
};
SearchRequest.prototype = {
init: function () {
},
getObj:function(){
return {
type: this.type,
alreadyShown: this.alreadyShown,
timestamp: this.timestamp,
params:JSON.stringify(this.params)
}
}
}
// end SearchRequest
var SiteHelper = {
ajaxPost:function(url, params, success_callback, fail_callback){
$.when( SiteHelper.sendPostAjax(url, params) ).done($.proxy(
function(response){
var r = ajaxResponseHandler(response);
switch(r.success){
case true:
if(typeof success_callback != 'undefined' && typeof success_callback === "function"){
success_callback(r);
}else{
}
break;
case false:
if(typeof fail_callback != 'undefined' && typeof fail_callback === "function"){
fail_callback(r);
}else{
// default when fail
if ( hasOwnProperty(r, 'msgs'))
{
showNotices(r.msgs, {timeout: 15000, type: 'error'});
}
}
break;
}
},this));
},
sendPostAjax:function(url, params){
return $.post(getBaseUrl() + url, params);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment