');
}
function prependCharIfItDoesntAlreadyExist(jQueryObject,char) {
if(jQueryObject.text().substring(0,1) != char) {
jQueryObject.prepend(char);
}
}
/* ·
·
· Takes twitter style dates and converts them
·
· @param tdate: date in the form of e.g. 'Mon Aug 05 16:30:22 +0200 2013'
·
· @return user friendly dates ..M_
· W
· Needs global language object window.sL to be populated
·
· · · · · · · · · · · · · */
function parseTwitterDate(tdate) {
var month_names = new Array ();
month_names[month_names.length] = window.sL.shortmonthsJanuary;
month_names[month_names.length] = window.sL.shortmonthsFebruary
month_names[month_names.length] = window.sL.shortmonthsMars
month_names[month_names.length] = window.sL.shortmonthsApril
month_names[month_names.length] = window.sL.shortmonthsMay
month_names[month_names.length] = window.sL.shortmonthsJune
month_names[month_names.length] = window.sL.shortmonthsJuly
month_names[month_names.length] = window.sL.shortmonthsAugust
month_names[month_names.length] = window.sL.shortmonthsSeptember
month_names[month_names.length] = window.sL.shortmonthsOctober
month_names[month_names.length] = window.sL.shortmonthsNovember
month_names[month_names.length] = window.sL.shortmonthsDecember
var system_date = parseDate(tdate);
var user_date = new Date();
var diff = Math.floor((user_date - system_date) / 1000);
if (diff <= 10) {return window.sL.now;}
if (diff < 60) {return window.sL.shortDateFormatSeconds.replace('{seconds}',Math.round(diff/10)*10);}
if (diff <= 3540) {return window.sL.shortDateFormatMinutes.replace('{minutes}',Math.round(diff / 60));}
if (diff <= 86400) {return window.sL.shortDateFormatHours.replace('{hours}',Math.round(diff / 3600));}
if (diff <= 31536000) {return window.sL.shortDateFormatDate.replace('{day}',system_date.getDate()).replace('{month}',month_names[system_date.getMonth()]);}
if (diff > 31536000) {return window.sL.shortDateFormatDateAndY.replace('{day}',system_date.getDate()).replace('{month}',month_names[system_date.getMonth()]).replace('{year}',system_date.getFullYear());}
return system_date;
}
function parseTwitterLongDate(tdate) {
var month_names = new Array ();
month_names[month_names.length] = window.sL.longmonthsJanuary;
month_names[month_names.length] = window.sL.longmonthsFebruary
month_names[month_names.length] = window.sL.longmonthsMars
month_names[month_names.length] = window.sL.longmonthsApril
month_names[month_names.length] = window.sL.longmonthsMay
month_names[month_names.length] = window.sL.longmonthsJune
month_names[month_names.length] = window.sL.longmonthsJuly
month_names[month_names.length] = window.sL.longmonthsAugust
month_names[month_names.length] = window.sL.longmonthsSeptember
month_names[month_names.length] = window.sL.longmonthsOctober
month_names[month_names.length] = window.sL.longmonthsNovember
month_names[month_names.length] = window.sL.longmonthsDecember
var system_date = parseDate(tdate);
var hours = system_date.getHours();
var minutes = ('0'+system_date.getMinutes()).slice(-2);
var ampm = hours >= 12 ? 'pm' : 'am';
var time24hours = hours + ':' + minutes;
var time12hours = hours % 12;
time12hours = time12hours ? time12hours : 12; // the hour '0' should be '12'
if(ampm == 'am') { time12hours = window.sL.time12am.replace('{time}',time12hours + ':' + minutes);}
else { time12hours = window.sL.time12pm.replace('{time}',time12hours + ':' + minutes); }
return window.sL.longDateFormat.replace('{time24}',time24hours).replace('{hours}',hours).replace('{minutes}',minutes).replace('{time12}',time12hours).replace('{day}',system_date.getDate()).replace('{month}',month_names[system_date.getMonth()]).replace('{year}',system_date.getFullYear());
}
function timestampToTwitterDate(timestamp) {
var a = new Date(timestamp*1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var day = days[a.getUTCDay()];
var year = a.getUTCFullYear();
var month = months[a.getUTCMonth()];
var date = (a.getUTCDate()<10?'0':'')+a.getUTCDate();
var hour = (a.getUTCHours()<10?'0':'')+a.getUTCHours();
var min = (a.getUTCMinutes()<10?'0':'')+a.getUTCMinutes();
var sec = (a.getUTCSeconds()<10?'0':'')+a.getUTCSeconds();
return day+' '+month+' '+date+' '+hour+':'+min+':'+sec+' +0000 '+year;
}
function parseDate(str) {
if(typeof str != 'undefined') {
var v=str.split(' ');
return new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" "+v[4]));
}
}
/* ·
·
· If we want to make sure we have empty arrays, not empty objects
·
· · · · · · · · · · */
function convertEmptyObjectToEmptyArray(data) {
// empty object? return empty array instead...
if($.isEmptyObject(data)) {
return [];
}
// leave data unchanged if we don't recognize it
else {
return data;
}
}
/* ·
·
· Functions to show and remove the spinner
·
· · · · · · · · · · · · */
function display_spinner(parent) {
if($('.loader').length<1) {
if(typeof parent == 'undefined') {
$('.global-nav').removeClass('show-logo');
var parent = 'body';
}
$(parent).prepend('\
\
');
}
}
function remove_spinner() {
$('.loader').remove();
$('.global-nav').addClass('show-logo');
}
/* ·
·
· Converts ...-attachment-links to spans
·
· (Attachments are loaded when queets expand)
·
· · · · · · · · · · · · · · · · · */
function convertAttachmentMoreHref() {
$('a.attachment.more').each(function() {
if(typeof $(this).attr('href') != 'undefined') {
var attachment_href = $(this).attr('href');
var attachment_id = attachment_href.substr((~-attachment_href.lastIndexOf("/") >>> 0) + 2);
if(attachment_id.length>0) {
$(this).replaceWith($('…'));
}
}
});
}
/* ·
·
· Saves the user's bookmarks to the server
·
· · · · · · · · · · · · · */
function saveAllBookmarks() {
var i=0;
var bookmarkContainer = new Object();
$.each($('#bookmark-container .stream-selection'), function(key,obj) {
bookmarkContainer[i] = new Object();
bookmarkContainer[i].dataStreamHref = $(obj).attr('href');
bookmarkContainer[i].dataStreamHeader = $(obj).text();
i++;
});
postUpdateBookmarks(bookmarkContainer);
$('#bookmark-container').sortable({delay: 100});
$('#bookmark-container').disableSelection();
}
/* ·
·
· Append all bookmarks to the bookmark container
·
· · · · · · · · · · · · · */
function appendAllBookmarks(bookmarkContainer) {
if(typeof bookmarkContainer != 'undefined' && bookmarkContainer) {
$('#bookmark-container').html('');
var bookmarkContainerParsed = JSON.parse(bookmarkContainer);
$.each(bookmarkContainerParsed, function(key,obj) {
$('#bookmark-container').append('' + obj.dataStreamHeader + '');
});
}
$('#bookmark-container').sortable({delay: 100});
$('#bookmark-container').disableSelection();
}
/* ·
·
· Change the header of an item in the history container by href attribute
·
· · · · · · · · · · · · · */
function updateHistoryContainerItemByHref(href, streamHeader) {
$('#history-container .stream-selection[href="' + href + '"]').html(streamHeader + '');
updateHistoryLocalStorage();
}
/* ·
·
· Remove items in the history container by href attribute
·
· · · · · · · · · · · · · */
function removeHistoryContainerItemByHref(href) {
$('#history-container .stream-selection[href="' + href + '"]').remove();
updateHistoryLocalStorage();
}
/* ·
·
· Updates the browsing history local storage
·
· · · · · · · · · · · · · */
function updateHistoryLocalStorage() {
if(localStorageIsEnabled()) {
var i=0;
var historyContainer = new Object();
$.each($('#history-container .stream-selection'), function(key,obj) {
historyContainer[i] = new Object();
historyContainer[i].dataStreamHref = $(obj).attr('href');
historyContainer[i].dataStreamHeader = $(obj).text();
i++;
});
localStorageObjectCache_STORE('browsingHistory', window.loggedIn.screen_name,historyContainer);
if($('#history-container .stream-selection').length==0) {
$('#history-container').css('display','none');
}
else {
$('#history-container').css('display','block');
}
}
}
/* ·
·
· Loads history from local storage to menu
·
· · · · · · · · · · · · · */
function loadHistoryFromLocalStorage() {
if(localStorageIsEnabled()) {
var cacheData = localStorageObjectCache_GET('browsingHistory', window.loggedIn.screen_name);
if(cacheData) {
$('#history-container').css('display','block');
$('#history-container').html('');
$.each(cacheData, function(key,obj) {
var streamHeader = replaceHtmlSpecialChars(obj.dataStreamHeader); // because we're pulling the header with jQuery.text() before saving in localstorage, which unescapes our escaped html
$('#history-container').append('' + streamHeader + '');
});
}
updateHistoryLocalStorage();
}
}
/* ·
·
· Does stream need a ? or a &
·
· · · · · · · · · · · · · */
function qOrAmp(stream) {
if(stream.substr(-5) == '.json') {
return '?';
}
else {
return '&';
}
}
/* ·
·
· Count chars in queet box
·
· @param src: the queetbox's value
· @param trgt: the counter
· @param btn: the button
·
· · · · · · · · · · · · · */
function countCharsInQueetBox(src,trgt,btn) {
// count linebreaks by converting them to spaces
var $src_txt = $('').append(src.html().replace(/
/g,' '));
$src_txt = $('').append($.trim($src_txt.text().replace(/\n/g,'').replace(/^\s+|\s+$/g, '')));
var numchars = ($src_txt.text()).length;
// check for long urls and disable/enable url shorten button if present
var longurls = 0;
$.each(src.siblings('.syntax-middle').find('span.url'),function(key,obj){
if($.trim($(obj).html().replace(/ /gi,'').replace(/
/gi,'')).length > 20) {
longurls++;
}
});
if(longurls>0) src.siblings('.queet-toolbar').find('button.shorten').removeClass('disabled');
else src.siblings('.queet-toolbar').find('button.shorten').addClass('disabled');
// limited
if(window.textLimit > 0) {
trgt.html(window.textLimit - numchars);
// activate/deactivare button
if(numchars > 0 && numchars < window.textLimit+1) {
btn.removeClass('disabled');
btn.addClass('enabled');
btn.removeClass('too-long');
// deactivate button if it's equal to the start text
var queetBox = btn.closest('.inline-reply-queetbox').children('.queet-box-syntax');
if(typeof queetBox.attr('data-replies-text') != 'undefined') {
var $startText = $('').append(decodeURIComponent(queetBox.attr('data-replies-text')));
if($.trim($startText.text()) == $.trim($src_txt.text())) {
btn.removeClass('enabled');
btn.addClass('disabled');
}
}
}
else if(numchars > window.textLimit){
btn.removeClass('enabled');
btn.addClass('disabled');
btn.addClass('too-long');
}
else {
btn.removeClass('enabled');
btn.addClass('disabled');
btn.removeClass('too-long');
}
// counter color
if((window.textLimit-numchars) < 0) {
trgt.css('color','#D40D12');
}
else {
trgt.removeAttr('style');
}
}
// unlimited
else {
if(numchars > 0) {
btn.removeClass('disabled');
btn.addClass('enabled');
}
else {
btn.removeClass('enabled');
btn.addClass('disabled');
}
}
}
/* ·
·
· Prefill the queet box with cached text, if there is any in an attribute
·
· @param queetBox: jQuery object for the queet box
·
· · · · · · · · · · · · · */
function maybePrefillQueetBoxWithCachedText(queetBox) {
var cachedText = decodeURIComponent(queetBox.attr('data-cached-text'));
var cachedTextText = $('').html(cachedText).text();
if(cachedText != 'undefined' && cachedText != 'false') {
queetBox.click();
queetBox.html(cachedText);
setSelectionRange(queetBox[0], cachedTextText.length, cachedTextText.length);
queetBox.trigger('input');
}
}
/* ·
·
· Remember my scroll position
·
· @param obj: jQuery object which position we want to remember
· @param id: id for position to remember
· @param offset: we might want to offset our remembered scroll, e.g. when stream-item gets margin after expand
·
· · · · · · · · · · · · · */
function rememberMyScrollPos(obj,id,offset) {
if(typeof offset == 'undefined') {
var offset = 0;
}
if(typeof window.scrollpositions == 'undefined') { window.scrollpositions = new Object();}
window.scrollpositions[id] = obj.offset().top - $(window).scrollTop() - offset;
}
/* ·
·
· Go back to my scroll po
·
· @param obj: jQuery object to put in the remebered position
· @param id: id for remembered position
· @param animate: if we want to animate the scroll
· @param callback: function to run when animation stops
·
· · · · · · · · · · · · · */
function backToMyScrollPos(obj,id,animate,callback) {
var pos = obj.offset().top-window.scrollpositions[id];
if(animate) {
if(animate == 'animate' || animate === true) {
animate = 1000;
}
if(typeof callback !== 'undefined'){
$('html, body').animate({ scrollTop: pos}, animate, 'swing',function(){
callback();
});
}
else {
$('html, body').animate({ scrollTop: pos }, animate, 'swing');
}
}
else {
$('html, body').scrollTop(pos);
}
}
/* ·
·
· Scroll to a stream item
·
· @param streamItem: jQuery object to scroll to
·
· · · · · · · · · · · · · */
function scrollToQueet(streamItem) {
var streamItemPos = streamItem.offset().top;
var windowHeight = $(window).height();
var streamItemHeight = streamItem.outerHeight();
// console.log(streamItemHeight);
// console.log(windowHeight);
var newScrollPos = Math.round(streamItemPos - windowHeight/2 + streamItemHeight/2);
$('html, body').scrollTop(newScrollPos);
}
/* ·
·
· Clean up user object, remove null etc
·
· · · · · · · · · · · · · */
function cleanUpUserObject(data) {
data.name = data.name || '';
data.profile_image_url = data.profile_image_url || '';
data.profile_image_url_profile_size = data.profile_image_url_profile_size || '';
data.profile_image_url_original = data.profile_image_url_original || '';
data.screen_name = data.screen_name || '';
data.description = data.description || '';
data.location = data.location || '';
data.url = data.url || '';
data.statusnet_profile_url = data.statusnet_profile_url || '';
data.statuses_count = data.statuses_count || 0;
data.followers_count = data.followers_count || 0;
data.groups_count = data.groups_count || 0;
data.friends_count = data.friends_count || 0;
return data;
}
/* ·
·
· outerHTML
·
· · · · · · · · · · · · · */
jQuery.fn.outerHTML = function(s) {
return s
? this.before(s).remove()
: jQuery("").append(this.eq(0).clone()).html();
};
/* ·
·
· Sort divs by attribute descending
·
· · · · · · · · · · · · · */
jQuery.fn.sortDivsByAttrDesc = function sortDivsByAttrDesc(attr) {
$("> div", this[0]).sort(dec_sort).appendTo(this[0]);
function dec_sort(a, b){ return parseInt($(b).attr(attr),10) > parseInt($(a).attr(attr),10) ? 1 : -1; }
}
/* ·
·
· Stuff to get and set selection/caret in contenteditables
·
· · · · · · · · · · · · · */
function getSelectionInElement(element) {
var caretOffset = Array(0,0);
var doc = element.ownerDocument || element.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
var range = win.getSelection().getRangeAt(0);
var preCaretRangeEnd = range.cloneRange();
preCaretRangeEnd.selectNodeContents(element);
preCaretRangeEnd.setEnd(range.endContainer, range.endOffset);
caretOffset[1] = preCaretRangeEnd.toString().length;
var preCaretRangeStart = range.cloneRange();
preCaretRangeStart.selectNodeContents(element);
preCaretRangeStart.setEnd(range.startContainer, range.startOffset);
caretOffset[0] = preCaretRangeStart.toString().length;
return caretOffset;
}
function getTextNodesIn(node) {
var textNodes = [];
if (node.nodeType == 3) {
textNodes.push(node);
}
else {
var children = node.childNodes;
for (var i = 0, len = children.length; i < len; ++i) {
textNodes.push.apply(textNodes, getTextNodesIn(children[i]));
}
}
return textNodes;
}
function setSelectionRange(el, start, end) {
if (document.createRange && window.getSelection) {
var range = document.createRange();
range.selectNodeContents(el);
var textNodes = getTextNodesIn(el);
var foundStart = false;
var charCount = 0, endCharCount;
for (var i = 0, textNode; textNode = textNodes[i++]; ) {
endCharCount = charCount + textNode.length;
if(endCharCount == start && endCharCount == end) {
endCharCount = endCharCount+1;
}
if (!foundStart && start >= charCount
&& (start < endCharCount ||
(start == endCharCount && i < textNodes.length))) {
range.setStart(textNode, start - charCount);
foundStart = true;
}
if (foundStart && end <= endCharCount) {
range.setEnd(textNode, end - charCount);
break;
}
charCount = endCharCount;
}
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (document.selection && document.body.createTextRange) {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(true);
textRange.moveEnd("character", end);
textRange.moveStart("character", start);
textRange.select();
}
}
function createRangeFromCharacterIndices(containerEl, start, end) {
var charIndex = 0, range = document.createRange(), foundStart = false, stop = {};
range.setStart(containerEl, 0);
range.collapse(true);
function traverseTextNodes(node) {
if (node.nodeType == 3) {
var nextCharIndex = charIndex + node.length;
if (!foundStart && start >= charIndex && start <= nextCharIndex) {
range.setStart(node, start - charIndex);
foundStart = true;
}
if (foundStart && end >= charIndex && end <= nextCharIndex) {
range.setEnd(node, end - charIndex);
throw stop;
}
charIndex = nextCharIndex;
} else {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
traverseTextNodes(node.childNodes[i]);
}
}
}
try {
traverseTextNodes(containerEl);
} catch (ex) {
if (ex == stop) {
return range;
} else {
throw ex;
}
}
}
function deleteBetweenCharacterIndices(el, from, to) {
var range = createRangeFromCharacterIndices(el, from, to);
if(typeof range != 'undefined') {
range.deleteContents();
}
}
/* ·
·
· Shorten urls in a queet-box
·
· · · · · · · · · · · · · */
function shortenUrlsInBox(shortenButton) {
shortenButton.addClass('disabled');
$.each(shortenButton.parent().parent().siblings('.syntax-middle').find('span.url'),function(key,obj){
var url = $.trim($(obj).text());
display_spinner();
$.ajax({ url: window.urlShortenerAPIURL + '?format=' + window.urlshortenerFormat + '&action=shorturl&signature=' + window.urlShortenerSignature + '&url=' + encodeURIComponent(url), type: "GET", dataType: window.urlshortenerFormat,
success: function(data) {
if(typeof data.shorturl != 'undefined') {
shortenButton.closest('.queet-toolbar').siblings('.upload-image-container').children('img[data-shorturl="' + data.url.url + '"]').attr('data-shorturl',data.shorturl);
shortenButton.parent().parent().siblings('.queet-box-syntax').html(shortenButton.parent().parent().siblings('.queet-box-syntax').html().replace($('
').text(data.url.url).html(), data.shorturl));
shortenButton.parent().parent().siblings('.queet-box-syntax').trigger('keyup');
shortenButton.addClass('disabled'); // make sure the button is disabled right after
}
remove_spinner();
},
error: function(data) {
console.log(data);
remove_spinner();
}
});
});
}
/* ·
·
· Youtube ID from Youtube URL
·
· · · · · · · · · · · · · */
function youTubeIDFromYouTubeURL(url) {
return url.replace('https://youtube.com/watch?v=','').replace('http://youtube.com/watch?v=','').replace('http://www.youtube.com/watch?v=','').replace('https://www.youtube.com/watch?v=','').replace('http://youtu.be/','').replace('https://youtu.be/','').substr(0,11);
}
/* ·
·
· Youtube embed link from youtube url
·
· · · · · · · · · · · · · */
function youTubeEmbedLinkFromURL(url, autoplay) {
// get start time hash
var l = document.createElement("a");
l.href = url;
var addStart = '';
if(l.hash.substring(0,3) == '#t=') {
addStart = '&start=' + l.hash.substring(3);
}
var addAutoplay = '';
if(typeof autoplay != 'undefined' && autoplay === true) {
addAutoplay = '&autoplay=1';
}
return '//www.youtube.com/embed/' + youTubeIDFromYouTubeURL(url) + '?enablejsapi=1&version=3&playerapiid=ytplayer' + addStart + addAutoplay;
}
/* ·
·
· Vimeo ID from Vimeo URL
·
· · · · · · · · · · · · · */
function vimeoIDFromVimeoURL(url) {
id = url.replace('http://vimeo.com/','').replace('https://vimeo.com/','');
if(id.indexOf('#') > -1) {
id = id.substring(0,id.indexOf('#'));
}
return id;
}
/* ·
·
· Vimeo embed link from vimeo url
·
· · · · · · · · · · · · · */
function vimeoEmbedLinkFromURL(url, autoplay) {
// get start time hash
var l = document.createElement("a");
l.href = url;
var addStart = '';
if(l.hash.substring(0,3) == '#t=') {
addStart = l.hash;
}
var addAutoplay = '&autoplay=0';
if(typeof autoplay != 'undefined' && autoplay === true) {
addAutoplay = '&autoplay=1';
}
return 'https://player.vimeo.com/video/' + vimeoIDFromVimeoURL(url) + '?api=1' + addAutoplay + addStart;
}
/* ·
·
· CSS class name from URL
·
· · · · · · · · · · · · · */
function CSSclassNameByHostFromURL(url) {
var host = getHost(url);
if(host.indexOf('www.') === 0) {
host = host.substring(4);
}
host = host.toLowerCase().replace(/\./g, "-");
host = host.replace(/[^a-zA-Z0-9-]+/g, "_");
if(host == 'youtu-be') {
host = 'youtube-com';
}
return 'host-' + host;
}
/* ·
·
· String similarity
·
· @params string1, string2:
· @returns (int) percent similarity
·
· · · · · · · · · · · · · */
function stringSimilarity(string1, string2) {
if(typeof string1 != 'string' || typeof string2 != 'string') {
return 0;
}
// trim and strip html tags
string1 = $('').html($.trim(string1)).text();
string2 = $('').html($.trim(string2)).text();
var longestStringLength = string1.length;
if(string2.length>string1.length) {
longestStringLength = string2.length;
}
var distanceArray = levenshteinenator(string1, string2);
var distance = distanceArray[distanceArray.length-1][distanceArray[distanceArray.length-1].length-1];
var percentSimilarity = 100-Math.round(distance/longestStringLength*100);
return percentSimilarity;
}
// from http://andrew.hedges.name/experiments/levenshtein/
var levenshteinenator = (function () {
/**
* @param String a
* @param String b
* @return Array
*/
function levenshteinenator(a, b) {
var cost;
var m = a.length;
var n = b.length;
// make sure a.length >= b.length to use O(min(n,m)) space, whatever that is
if (m < n) {
var c = a; a = b; b = c;
var o = m; m = n; n = o;
}
var r = []; r[0] = [];
for (var c = 0; c < n + 1; ++c) {
r[0][c] = c;
}
for (var i = 1; i < m + 1; ++i) {
r[i] = []; r[i][0] = i;
for ( var j = 1; j < n + 1; ++j ) {
cost = a.charAt( i - 1 ) === b.charAt( j - 1 ) ? 0 : 1;
r[i][j] = minimator( r[i-1][j] + 1, r[i][j-1] + 1, r[i-1][j-1] + cost );
}
}
return r;
}
/**
* Return the smallest of the three numbers passed in
* @param Number x
* @param Number y
* @param Number z
* @return Number
*/
function minimator(x, y, z) {
if (x <= y && x <= z) return x;
if (y <= x && y <= z) return y;
return z;
}
return levenshteinenator;
}());