var includeDues = false; var username; var password; var privs = {}; //var localUpdates = []; var onLogin = []; var onReady = []; var hols = []; var yroptionlist = ""; var editableSelectCreated = false; var abgcolor = '#4488bb'; var showLoginDivOnAutoLoginFail = false; function setYrOptionList() { var yr = (new Date()).getFullYear(); for (var y=0; y < 5; y++) { yroptionlist += ''; } } setYrOptionList(); function encodeBase64(data) { var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc = "", tmp_arr = []; if (!data) { return data; } do { // pack three octets into four hexets o1 = data.charCodeAt(i++); o2 = data.charCodeAt(i++); o3 = data.charCodeAt(i++); bits = o1 << 16 | o2 << 8 | o3; h1 = bits >> 18 & 0x3f; h2 = bits >> 12 & 0x3f; h3 = bits >> 6 & 0x3f; h4 = bits & 0x3f; // use hexets to index into b64, and append result to encoded string tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); } while (i < data.length); enc = tmp_arr.join(''); var r = data.length % 3; return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3); } /* & --> & < --> < > --> > " --> " ' --> ' ' is not recommended / --> / forward slash is included as it helps end an HTML entity */ function htmlEscape(html){ return html.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'").replace(/\//g, "/"); } function htmlUnescape(html){ return html.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, "\"").replace(/'/g, "'").replace(///g, "/"); } var monthNames = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var monthNumbers = {}; for (var m=0; m < 12; m++) monthNumbers[monthNames[m]] = (m < 9) ? "0" + (m+1) : (m+1); var dayNames = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ]; //var monthNumbers = { monthNames[0]: '01', monthNames[0] : '02', 'March' : '03', 'April' : '04', 'May' : '05', 'June' : '06', 'July' : '07', 'August' : '08', // 'September' : '09', 'October' : '10', 'November' : '11', 'December' : '12' }; function addlang(url) { // Insert the language qualifier retval = '/' + lang + url; return retval; } function authenticatedAjax(href, cb) { var u = getCookie(rootBlogTopicId + '-username'); var p = getCookie(rootBlogTopicId + '-password'); var url = addlang(href); //console.log("authenticatedAjax: " + url); $.ajax({ url: url, success: cb, beforeSend: function(xhr) { xhr.setRequestHeader ("Authorization", "Basic " + encodeBase64(u + ":" + p)); } }); } function authenticatedPost(href, data, cb) { var u = getCookie(rootBlogTopicId + '-username'); var p = getCookie(rootBlogTopicId + '-password'); $.ajax({ url: addlang(href), type: 'POST', data: JSON.stringify(data), dataType: 'JSON', success: cb, beforeSend: function(xhr) { xhr.setRequestHeader ("Authorization", "Basic " + encodeBase64(u + ":" + p)); } }); } function fixup() { if (screwtopDb.isFunction(window.prettyPrint)) { $('pre.prettyprint').each(function(n,o) { var jo = $(o); jo.html(jo.html().replace(/= 12) { h = hh-12; dd = "PM"; } if (h == 0) { h = 12; } m = m<10?"0"+m:m; s = s<10?"0"+s:s; /* if you want 2 digit hours: h = h<10?"0"+h:h; */ return h + ':' + m + ' ' + dd; } function dateDisplayString(d) { return [ //"Posted on ", d.toLocaleDateString(), " ", formatDate(d) ].join(' '); } RegExp.escape = function(text){ return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); } var caseBlindMatch = function (str1, str2){ if (str2 == undefined || str1 == undefined) return false; var re = new RegExp(RegExp.escape(str1), "i"); return str2.match(re); } function localize8601Dates() { $('.ISO8601Date').each(function(arr, elem) { var d = new Date(); var e = $(elem); d.setISO8601(e.html()); e.html(dateDisplayString(d)); }); } function generateToken(len) { var tok = ''; var t = (Math.floor(Math.random() * 1000000)).toString(36); while (t.length < len) { t += (Math.floor(Math.random() * 1000000)).toString(36); } return t.slice(0,len); } function setSingleUseToken(cb) { var tokstr = generateToken(32); screwtopDb().url(DBURL) .topicByName(username) .addTags('singleUseTokens',tokstr/*, {private:true}*/) .end(function() { cb(tokstr); }); } function hasLocalStorage() { return 'localStorage' in window && window['localStorage'] !== null;; } function hasSessionStorage() { return 'sessionStorage' in window && window['sessionStorage'] !== null;; } function setSessionStorage(name,value) { sessionStorage.setItem(name,value); } function getSessionStorage(name) { return sessionStorage.getItem(name); } function setLocalStorage(name,value) { //console.log("set " + name + "=" + value); localStorage.setItem(name,value); } function getLocalStorage(name) { //console.log("get " + name + "=" + localStorage.getItem(name)); return localStorage.getItem(name); } function deleteLocalStorage(name) { //console.log("del " + name); localStorage.removeItem(name); } function setCookie(name,value,days) { if (hasLocalStorage()) { document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; setLocalStorage(name,value); } else { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } } function getCookie(name) { if (hasLocalStorage()) { document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; return getLocalStorage(name); } else { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } } function deleteCookie(name) { if (hasLocalStorage()) deleteLocalStorage(name); document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; } function cookiesSet() { var u = getCookie(rootBlogTopicId + '-username'); var p = getCookie(rootBlogTopicId + '-password'); return (!screwtopDb.isEmpty(u) /* && !screwtopDb.isNull */); } var spinnerCount = 0; function showSpinner() { if (++spinnerCount == 1) $('#spinner').fadeIn('fast'); //console.log('show spinnerCount='+spinnerCount); } function hideSpinner() { if (--spinnerCount == 0) $('#spinner').stop().hide(); //console.log('hide spinnerCount='+spinnerCount); } function isBlogPoster() { var retval = false; for (var k=0; k < blogPosters.length; k++) { if (caseBlindMatch(blogPosters[k], username)) { retval = true; break; } } return retval; //return caseBlindMatch(blogOwner, username); } function isLoggedIn() { return !screwtopDb.isEmpty(username); } function addHolidays() { var today = new Date(); getHolidays(function(arr) { arr.forEach(function(ev) { //console.log(ev.date + ': ' + ev.name); schedev = { id: 0, infolink: '#', location: 'US', duration: 24*60, owner: 'pdclub', //title: ev.name, start: ev.date, color:'white', valueId: 0, textColor: '#c00' }; schedev["title"] = ev.name; $('#calendardiv').fullCalendar('renderEvent',schedev,true); }); addRecurringEvents(); }); } function getHolidaysForYear(fullyr,cb) { $.ajax(location.protocol + '//' + location.host + '/holidata.net/en-US/'+fullyr+'.json',{ dataType: 'text', error: function(data,textStatus,errorThrown) { $('#log').append('Error: ' + textStatus + ' ' + errorThrown + '

'); } }).done(function(data) { var hols = []; var lines = data.split('\n'); lines.forEach(function(line) { if (line.trim().length > 0) { var obj = JSON.parse(line); var date = new Date(); date.setDate(obj.date.split('-')[2]); date.setMonth(obj.date.split('-')[1]-1); date.setFullYear(obj.date.split('-')[0]); date.setMinutes(0); date.setHours(0); date.setSeconds(0); hols.push({ date: date, name: obj.description }); } }); cb(hols); }).fail(function() { cb([]); }); } function getHolidays(cb) { if (hols.length > 0) cb(hols); else { var dt = new Date(); getHolidaysForYear(dt.getFullYear()-1, function(arr) { hols = hols.concat(arr); getHolidaysForYear(dt.getFullYear(), function(arr) { hols = hols.concat(arr) getHolidaysForYear(dt.getFullYear()+1, function(arr) { hols = hols.concat(arr) cb(hols); }); }); }); } } // n is 1-based, xday and month are 0-based. function getNthXDayOfMonth(n, xday, month, year) { var dt; for ( var d = 1; d <= 7; ++d ) { var dt = new Date( year, month, d ); if ( dt.getDay() == xday ) break; } dt.setDate( d + 7 * (n-1) ); if ( dt.getMonth() != month ) dt = null; //console.log('getNthXDayOfMonth(' + n + ',' + xday + ',' + month + ',' + year + ') = ' + dt); return dt; } function addRecurringEvents() { var arr = getRecurringEvents(); arr.forEach(function(ev) { $('#calendardiv').fullCalendar('renderEvent',ev,true); }); } function getRecurringEvents(months) { var enddt = null; if (!screwtopDb.isEmpty(months)) { var dt = new Date(); var newMo = dt.getMonth() + months; if (newMo > 11) { dt.setFullYear(dt.getFullYear() + 1) newMo %= 12; } dt.setMonth(newMo); enddt = dt; } var retval = []; recurSpecs.forEach(function(recurSpec) { var dt = new Date(); dt.setTime(recurSpec.start); if (screwtopDb.isEmpty(months)) enddt = parseFloat(recurSpec.end); while (dt.getTime() < enddt) { skip = false; if (!screwtopDb.isEmpty(recurSpec.exceptions)) { skip = (recurSpec.exceptions.indexOf('' + dt.getMonth()) >= 0) } /* for (var e = 0; e < recurExceptions.length; e++) { var rex = recurExceptions[e]; // Skip deleted months if (rex.id == recurSpec.id && rex.month == dt.getMonth()) { skip = true; break; } } */ if (!skip) { var evdt = getNthXDayOfMonth(recurSpec.nth, recurSpec.recurwkday, dt.getMonth(), dt.getFullYear()); evdt.setHours(recurSpec.startHr); evdt.setMinutes(recurSpec.startMin); schedev = { id: recurSpec.id, //location: recurSpec.location, duration: recurSpec.duration, owner: recurSpec.owner, //title: recurSpec["title"], start: evdt, color:recurSpec.color, valueId: recurSpec.valueId, textColor: recurSpec.textColor, recur: true }; schedev["title"] = recurSpec["title"]; schedev["location"] = recurSpec["location"]; if (recurSpec.infolink) schedev.infolink = recurSpec.infolink; if (recurSpec.articleTopicId) schedev.articleTopicId = recurSpec.articleTopicId; retval.push(schedev); } var mo = dt.getMonth(); dt.setDate(1); if (++mo < 12) dt.setMonth(mo); else { mo = 0; dt.setMonth(0); dt.setFullYear(dt.getFullYear() + 1); } } }); return retval; } function utcToLocal(utcms) { var dt = new Date(); var ms = utcms; if (screwtopDb.isObject(utcms)) ms = utcms.getTime(); dt.setTime(ms); // Necessary if the target date is past a daylight savings time change. return new Date(ms - dt.getTimezoneOffset() * 60 * 1000); } function updateCalendar() { showSpinner(); $('#calendar').fullCalendar('removeEventSource'); $('#calendar').fullCalendar('removeEvents'); //events = null; if (events == null) { var evArray = []; var valueIdsByTopicIds = {}; screwtopDb().url(DBURL) .appName(APPNAME) .topicByName('schedule') .tags(/.*\/events$/) .values() .each(function(v) { valueIdsByTopicIds[v.topicId] = v.valueId; }) .topics({elide:true}) .sort(function(a,b) { if (a.startTime[0] < b.startTime[0]) return -1; else if (a.startTime[0] > b.startTime[0]) return 1; else return 0; }) .each(function(ev) { var schedev; //console.log(JSON.stringify(ev,null,' ')); //console.log("lang=" + lang); if (screwtopDb.isEmpty(ev.infolink)) { schedev = { id: ev.id, articleTopicId: ev.articleTopicId, //location: ev.location, duration: ev.duration[0], //title: ev.title[0], owner: screwtopDb.isEmpty(ev.owner) ? '':ev.owner[0], valueId: valueIdsByTopicIds[ev.topicId], start: utcToLocal(ev.startTime[0]) }; schedev["title"] = ev["title-" + lang][0]; schedev["location"] = ev["location-" + lang][0]; } else { schedev = { id: ev.id, infolink: ev.infolink, //location: ev.location, duration: ev.duration[0], //title: ev.title[0], owner: screwtopDb.isEmpty(ev.owner) ? '':ev.owner[0], valueId: valueIdsByTopicIds[ev.topicId], start: utcToLocal(ev.startTime[0]) }; schedev["title"] = ev["title-" + lang][0]; schedev["location"] = ev["location-" + lang][0]; } evArray.push(schedev); }) /* .fn(function() { var today = new Date(); getHolidays(function(arr) { arr.forEach(function(ev) { schedev = { id: 0, infolink: '#', location: 'US', duration: 24*60, owner: 'pdclub', title: ev.name, start: ev.date, background:white, valueId: 0, color: red }; evArray.push(schedev); }); screwtopDb().resume(); }) }) .wait() */ .end(function() { //console.log('evArray: ' + JSON.stringify(evArray,null,' ')); populateEventsList(evArray); $('#calendardiv').fullCalendar('addEventSource', evArray); $('.rnd').corner('6px'); hideSpinner(); }); } else { if (screwtopDb.isEmpty(events[0]) || screwtopDb.isEmpty(events[0].start)) { for (var i=0; i < events.length; i++) { events[i].start = utcToLocal(events[i].startTime); } //populateEventsList(events); //console.log("events:" + JSON.stringify(events,null,' ')); populateEventsList(mergeEventLists(events,getRecurringEvents(3))); $('#calendardiv').fullCalendar('addEventSource', events); $('.rnd').corner('6px'); hideSpinner(); } } } function mergeEventLists(arr1, arr2) { //console.log(JSON.stringify(arr1,null,' ')); //console.log(JSON.stringify(arr2,null,' ')); var arr = arr1.concat(arr2); arr.sort(function(a,b) { if (a.start < b.start) return -1; else if (a.start > b.start) return 1; else return 0; }); //console.log(JSON.stringify(arr,null,' ')); return arr; } function populateEventsList(arr) { //console.log(JSON.stringify(arr,null,' ')); $('.evlist').html('

Upcoming Events
'); var now = (new Date()).getTime(); screwtopDb.forEach(arr, function(ev) { if (ev.start.getTime() >= now && ev.start.getTime() - now < 1000*60*60*24*42) { if (!screwtopDb.isEmpty(ev.articleTopicId)) { $('.evlist').append( '
' + '
'+ ' ' + ev.title + '' + '
' + '
' + ' ' + $.fullCalendar.formatDate(ev.start, 'MMMM d, h:mm TT') + '
' + ev.location + '
' + '
' + '
'); } else if (!screwtopDb.isEmpty(ev.infolink)) { $('.evlist').append( '
' + '
'+ ' ' + ev.title + '' + '
' + '
' + ' ' + $.fullCalendar.formatDate(ev.start, 'MMMM d, h:mm TT') + '
' + ev.location + '
' + '
' + '
'); } else { $('.evlist').append( '
' + '
'+ ' ' + ev.title + '' + '
' + '
' + ' ' + $.fullCalendar.formatDate(ev.start, 'MMMM d, h:mm TT') + '
' + ev.location + '
' + '
' + '
'); } } }); bindLinks(); $('.scheditem, #eventstitle, .evtdetail').corner('6px'); } function bindLinks() { //console.log('bindLinks'); $('.recentbtn, .articletitle, .morebtn, .newcommentbtn2, .articletitlesmall, .recentbtn, .categorybtn, .archivebtn, .articlecategorybutton, .linka, .subitem a') .unbind() .click(function(ev) { var href = $(ev.target).attr('href'); showArticle(href); //var articleId = $(ev.target).attr('articleId'); return false; }); $('.recentbtn2, .subitem2') .unbind() .click(function(ev) { var href = $(ev.target).attr('href'); showContent(href); //var articleId = $(ev.target).find('a').attr('articleId'); return false; }); $('#forgotusernamebtn').unbind().click(function() { var em = prompt('Enter your email address.'); if (em.trim() != '') screwtopDb().url(DBURL) .appName(APPNAME) .sendUsernameReminder(em) .end(function(msg) { alert(msg); }); }); $('#forgotpasswordbtn').unbind().click(function() { var u = prompt('Enter your username.'); if (u.trim() != '') screwtopDb().url(DBURL) .appName(APPNAME) .sendPasswordReminder(u) .end(function(msg) { alert(msg); }); }); bindConfig(); } function extractSection(href) { var retval = href.replace(/^\/(.*?)[\/].*$/,"$1").replace(/\//g,""); return retval; } function selectSection(txt) { if (txt == rootBlogTopicTitle) txt = "Home"; $('.infoitem').removeClass('selected'); $('.infoitem a').each(function(i) { if ($(this).html() == txt) { $(this).parent().addClass("selected"); } }); } function showArticle(href) { window.scrollTo(0,0); showSpinner(); /* setTimeout(function() { if (showSpinner) { $('#spinner').fadeIn('fast'); } }, 1000); */ // Select the section selectSection(extractSection(href)); authenticatedAjax(href + '?embed=1', function(html) { hideSpinner(); $('#articles').html(html); $('#articles').fadeIn('fast', function() { fixup(); processFormDescriptors($('.blogcontent')); bindLinks(); $('.rnd').corner('6px'); localize8601Dates(); setAuthorActions(); initCalendar(); updateCalendar(); }); try { history.pushState(html, null, addlang(href)); } catch(e) {} }); $('#articles').fadeOut('fast'); } function setAuthorActions() { if (isLoggedIn()) { $('.commentlogin').hide(); if (isBlogOwner()) { $('.authoractions').show(); $('.commentactions').show(); } if ($('.formdiv').length > 0 && privs.privform) { $('.editformbtn').show(); bindEditFormBtn(); } //alert(JSON.stringify(privs,null,' ')); if (privs.privform) $('#insertformbtn').show(); else $('#insertformbtn').hide(); if (privs.privcalendar) $('#articleeventbtn').show(); else $('#articleeventbtn').hide(); if (privs.privnosanitize) $('#nosandiv').show(); else $('#nosandiv').hide(); if (blogTopicTitle == "Calendar") { $('#addarticlebtn').hide(); if (privs.privcalendar) { $('#scheduleeventbtn').show(); $('#newshow').show(); $('.showdelbtn').show(); } else { $('#newshow').hide() $('.showdelbtn').hide(); } } /**/ if (blogTopicId == rootBlogTopicId && blogOptions.indexOf('pitch') >= 0) { // Home page( if ($('#articles .articletitle a').attr("href") != null) $('#addarticlebtn').hide(); } /**/ $('.user-' + username.replace(/ /g,'-')).show(); $('.loggedinactions,.afterlogin').show(); bindDeleteButtons(); bindEmailButtons(); bindEditButtons(); if (blogOptions.indexOf('pitch') >= 0) { // Hide priority and category fields. $('.nopitch').hide(); } else $('.nopitch').show(); } else { $('.commentlogin').show(); $('.authoractions').hide(); $('.commentactions').hide(); $('.loggedinactions').hide(); $('.afterlogin').hide(); } bindForms(); } function bindDeleteButtons() { $('.deletebtn').unbind().click(function(ev) { var topicType = $(ev.target).attr("itemtype"); var topicId = $(ev.target).attr('data'); if (confirm("Delete this " + topicType + ".\n\nAre you sure?")) { //TODO: Change this to delete the value, not the topic $('#spinner').show(); $('#articles').hide(); if (topicType == "article") { screwtopDb().url(DBURL) .topicById(topicId) .tag('./eventTopicId') .values() .each(function(v) { eventValueId(v.text, function(valueId) { screwtopDb().url(DBURL) .deleteValues(valueId) .end(); }); }) .end(function() { articleValueId(topicId, function(valueId) { screwtopDb().url(DBURL) .deleteValues(valueId) .end(function() { document.location = '/' + lang + '/'; }); }); }); } else { var articleId = $(ev.target).attr('parentArticleId'); commentValueId(topicId, function(valueId) { screwtopDb().url(DBURL) .deleteValues(valueId) .end(function() { showArticle('/' + blogTopicTitle + '/article/id/' + articleId); }); }); } } }); } function bindEmailButtons() { $('.emailbtn').unbind().click(function(ev) { var goahead = confirm("This will email a copy of the article to all members.\n\n" + "Are you sure you want to do this?"); if (goahead) { var topicId = $(ev.target).attr('data'); $('#spinner').show(); setSingleUseToken(function(tok) { $.ajax({ url: addlang('/email?articleId=' + topicId + '&token=' + tok), success: function(html) { $('#spinner').hide(); alert("The article has been emailed.") }, complete: function() { $('#spinner').hide(); } }); }) } }) } function isBlogOwner() { return caseBlindMatch(blogOwner, username); } function bindEditButtons() { $('.editbtn').unbind().click(function(ev) { topicId = $(ev.target).attr("data"); $('#articleeventdiv').hide(); $('#newarticle').show("blind", 500, function() { $('#main').hide(); $('#newtitle').val(""); $('#priority').val(blogOptions.indexOf('pitch') >= 0 ? "100":""); $('#nosanitizecb').prop("checked",false); $('#newcategories').val("").attr('selectBoxOptions',categories); $('#newdate').val(new Date().getISO8601()); $('#newarticle').show("blind", 500, function() { setHtmlArea(); }); $('#expdate').val(''); $('#startdate').val(''); $('#enddate').val(''); $('#starttime').val(''); $('#endtime').val(''); $('#location').val(''); $('#newcontent').children().remove(); $('#newcontent').append(""); showSpinner(); screwtopDb().url(DBURL) .topicById(topicId) .each(function(topic) { $('#newtitle').val(topic["title-" + lang] ? topic["title-" + lang][0] : ''); $('#priority').val(topic.priority ? topic.priority[0] : ''); if (!screwtopDb.isEmpty(topic.expdate)) { $('#expdate').datepicker('setDate',utcToLocal(topic.expdate[0])); } //$('#expdate').datepicker('setDate',utcToLocal(screwtopDb.isEmpty(topic.expdate) ? /*addDays(new Date(), 30)*/ "" :topic.expdate[0])); $('#nosanitizecb').prop('checked',(topic.articleOptions && topic.articleOptions[0] == "nosanitize")); $('#newcontentarea').val(clean(topic["content-" + lang] ? topic["content-" + lang][0] : '')); $('#newdate').val(new Date().getISO8601()); var categoriesString = ""; //alert(blogTopicText +'/category' + ': ' + topic[blogTopicText +'/category']); screwtopDb.forEach(topic[blogTopicText +'/category'], function(cat, i) { if (i > 0) categoriesString += ", "; categoriesString += cat; }); $('#newcategories').val(categoriesString); setHtmlArea(); if (!editableSelectCreated) { createEditableSelect($('#newcategories')[0], 'catSelectBox'); editableSelectCreated = true; $('#catSelectBox').css('float','left'); } if (topic.eventTopicId) { screwtopDb().url(DBURL) .topicById(topic.eventTopicId[0]) .each(function(evTopic) { $('#articleeventdiv').show(); //var startDt = new Date(); var startDt = utcToLocal(screwtopDb.isEmpty(evTopic.startTime) ? evTopic.start[0] : evTopic.startTime[0]); //startDt = utcToLocal(evTopic.startTime[0]); var endDt = new Date(startDt.getTime() + (evTopic.duration[0] * 60 * 1000)); $('#startdate').datepicker('setDate', startDt.toLocaleDateString()); $('#starttime').timepicker('setTime', startDt.toLocaleTimeString()); $('#enddate').datepicker('setDate', endDt); $('#endtime').timepicker('setTime',endDt); //alert(lang + "\n" + JSON.stringify(evTopic,null,' ')); $('#location').val(evTopic["location-" + lang] ? evTopic["location-" + lang][0] : ""); $('.acolor').css('background-color',evTopic.color[0]); $.farbtastic('#acolorpicker').setColor(evTopic.color[0]); if (!screwtopDb.isEmpty(evTopic.recurwkday)) { $('#recur').prop('checked',true); $('#nth').val(evTopic.nth[0]); $('#xday').val(evTopic.recurwkday[0]); var edt = new Date(); edt.setTime(evTopic.end[0]); $('#endmo').val(edt.getMonth()); $('#endyr').val(edt.getFullYear()); } }) .end(); } }) .end(function() { hideSpinner(); bindEditArticleButtons(topicId); }); }); }); bindCommentButtons(); bindEditCommentButtons(); } function bindEditArticleButtons(topicId) { $('#delesbtn,#delenbtn').show(); $('#newarticlecancelbtn').unbind(); $('#newarticlecancelbtn').click(function() { $('#main').show(); $('#newarticle').hide("blind"); }); $('#delesbtn').unbind().click(function() { var ok = confirm("Really replace the Spanish translation?"); if (ok) { showSpinner(); screwtopDb().url(DBURL) .topicById(topicId) .tags() .select(/.*-es$/) .deleteTags() .end(hideSpinner); } }); $('#delenbtn').unbind().click(function() { var ok = confirm("Really replace the English translation?"); if (ok) { showSpinner(); screwtopDb().url(DBURL) .topicById(topicId) .tags() .select(/.*-en$/) .deleteTags() .end(hideSpinner); } }); $('#articleeventbtn').unbind().click(function() { if ($('#articleeventdiv').is(':visible')) { $('#articleeventdiv').hide('blind'); $('#startdate').val(''); $('#enddate').val(''); $('#starttime').val(''); $('#endtime').val(''); $('#location').val(''); } else { $('#articleeventdiv').show('blind'); } }); $('#newarticlesubmitbtn').unbind().click(function() { var date = new Date(); var datetime = date.getISO8601(); var title = $('#newtitle').val(); var content = clean($('#newcontentarea').htmlarea("toHtmlString")); var priority = $('#priority').val(); var expdate = $('#expdate').val(); var articleOptions = $('#nosanitizecb').is(':checked') ? "nosanitize" : "sanitize"; if (/class="formsrc"/.test(content)) articleOptions = "nosanitize"; var categories = screwtopDb.collect($('#newcategories').val().split(','), function(s) { return $.trim(s) }); var author = username; var st = $('#starttime').timepicker('getTime'); var sd = new Date(Date.parse($('#startdate').val())); var et = $('#endtime').timepicker('getTime'); var ed = new Date(Date.parse($('#enddate').val())); var startdt = Date.parse(sd.toLocaleDateString() + ' ' + st.toLocaleTimeString()); var enddt = Date.parse(ed.toLocaleDateString() + ' ' + et.toLocaleTimeString()); var dur = (enddt - startdt) / (1000 * 60); var loc = $('#location').val(); if (!validateArticleEvent()) return; var eventinfo = null; if (parseInt(dur) > 0) { eventinfo = { start: new Date(startdt), duration: dur, location: loc }; } updateArticle(topicId, title, content, date, categories, priority, expdate, articleOptions, eventinfo, function(ids) { $('#main').show(); $('#newarticle').hide("blind"); showArticle('/' + blogTopicTitle + '/article/id/' + topicId); putArticleEvent(topicId); }); }); $('#uploadimagebtn').unbind().click(function(ev) { $('#uploadimagebtn').hide(); uploadImage(function(upload,positioning) { var obj = { text: 'user:' + username, 'blog images': { text: '', deletehash: upload.image.deletehash, type: upload.image.type, animated: upload.image.animated, width: upload.image.width, height: upload.image.height, size: upload.image.size, links: upload.links } }; screwtopDb().url(DBURL) .addTopics(obj) .end(function() { var link = upload.links.large_thumbnail; var html = ''; //$('#newcontentarea').htmlarea("image", link); $('#uploadimagebtn').show(); $('#uploader').hide('blind'); $('#newcontentarea').htmlarea("pasteHTML", html); }); },ev); }); bindInsertFormBtn(); } function bindInsertFormBtn() { $('#insertformbtn').unbind().click(function() { var formname = prompt('Enter a name for the table in which the data collected with this form is to be saved.'); formname = formname.trim(); if (formname.trim() != "") { var html = '\n\n
\n' + //'\n' + '
\n' + '
\n' + ' \n' + '
\n'; $('#newcontentarea').htmlarea("pasteHTML", html); $('#newarticlesubmitbtn').click(); } }); } function bindForms() { $('.formdiv').unbind().keyup(function() { validateForms(); }); $('.formdiv select').unbind().change(function() { validateForms(); }); $('.form-cancel').unbind().click(function() { $(this).closest('form').find('.form-input').val('').removeAttr('checked'); validateForms(); }); $('.form-submit').unbind().click(function() { var collection = $(this).closest('form').attr('data-collection'); var notify = $(this).closest('form').attr('data-notify'); var formdata = { "_collectionName_": collection, "_notify_": notify.split(',') }; var key = ""; $(this).closest('form').find('.form-input').each(function() { var skip = false; var trialkey = $(this).closest('tr').find('.form-label').text(); if (trialkey.trim() != "") key = trialkey; var val; switch ($(this).attr('type')) { case 'checkbox': val = $(this).prop('checked') ? "yes" : "no"; break; case 'radio': if ($(this).prop('checked')) { val = $(this).val(); } else skip = true; break; default: val = $(this).val(); break; } if (!skip) formdata[key] = val; }); var that = this; $.post(addlang('/formdata'),JSON.stringify(formdata), function(data, txtStatus) { $(that).closest('form').find('.form-input').val(''); $(that).closest('form').find('.form-btns').html('
Information sent. Thank you.
'); }); return false; }); validateForms(); } function bindEditFormBtn() { $('.editformbtn').unbind().click(function() { if ($(this).closest('.articlediv').find('.formdiv').find('.form-addbtn').length > 0) { $('.form-delbtn,.form-upbtn,.form-downbtn,.form-addbtn,.form-table-row').remove(); } else { $(this).closest('.articlediv').find('.formdiv').find('.form-input').each(function() { if ($(this).closest('tr').find('td').first().text() != "") { $(this).parent().append(''); $(this).parent().append(''); $(this).parent().append(''); $(this).parent().append(''); } }); $(this).closest('.articlediv').find('.formdiv').find('.new-form-input').each(function() { $(this).parent().append(''); }); $('.form-upbtn').unbind().click(function() { var i = parseInt($(this).closest('tr').attr('data-fieldindex')); if (moveFieldUp(i)) curForm.div.find('.editformbtn').click(); }); $('.form-downbtn').unbind().click(function() { var i = parseInt($(this).closest('tr').attr('data-fieldindex')); if (moveFieldDown(i)) curForm.div.find('.editformbtn').click(); }); $('.form-addbtn').unbind().click(function() { var i = parseInt($(this).closest('tr').attr('data-fieldindex')); showNewFieldDlg(i); }); $('.form-delbtn').unbind().click(function() { var i = $(this).closest('tr').attr('data-fieldindex'); if (deleteField(i)) curForm.div.find('.editformbtn').click(); }); $(this).closest('.articlediv').find('.formdiv').find('table').prepend(' '); $(this).closest('.articlediv').find('.formdiv').find('table').prepend( '
Form table
' + '
' + $(this).closest('.articlediv').find('form').attr('data-collection') + '
' + ''); var notif = $(this).closest('.articlediv').find('form').attr('data-notify'); if (screwtopDb.isEmpty(notif)) notif = ""; var str = '
Notification usernames
' + '' + ''; $(this).closest('.articlediv').find('.formdiv').find('table').prepend(str); if (notif != 'undefined') $('#form-emaillist').val(notif); $('#form-emaillist-btn').click(function() { curForm.fdesc["_notify_"] = $('#form-emaillist').val(); updateFormDisplay(); saveForm(); }); } }); } function saveForm() { var $formdesc = curForm.div.find('.formdesc') $formdesc.find('.form-delbtn,.form-upbtn,.form-downbtn,.form-addbtn,.form-table-row').remove(); var topicId = $formdesc.closest('.articlediv').find('.editbtn').attr('data'); var content = $formdesc.closest('.blogcontent').html(); if (topicId) { screwtopDb().url(DBURL) .topicById(topicId) .each(function(t) { screwtopDb(t) .tag('./content-' + lang) .values() .ifNone(function() { if (!screwtopDb.isEmpty(content)) { screwtopDb().url(DBURL) .postTopic({ valueText: content }, val.valueId) .end(); } }) .each(function(val) { if (val.text != content) { screwtopDb().url(DBURL) .postTopic({ valueText: content }, val.valueId) .end(); } }) .end(); }) .end(function() { $('.editformbtn').click(); }); } } var curForm = {}; function processFormDescriptors($div) { //alert("processFormDescriptors"); $div.find('.formdesc').each(function() { found = true; var json = $(this).find('.formsrc').html(); if (!screwtopDb.isEmpty(json)) { curForm.fdesc = JSON.parse(json); curForm.div = $div; var vframeHtml = buildFormFromDescriptor(curForm.fdesc); //alert(vframeHtml); $(this).find('.formdiv').html(vframeHtml); } }); } function updateFormDisplay() { curForm.div.find('.formdesc').each(function() { $(this).find('.formdiv').html(buildFormFromDescriptor(curForm.fdesc)); $(this).find('.formsrc').html(JSON.stringify(curForm.fdesc)); }); //$('.editformbtn').click(); } Array.prototype.move = function (old_index, new_index) { while (old_index < 0) { old_index += this.length; } while (new_index < 0) { new_index += this.length; } if (new_index >= this.length) { var k = new_index - this.length; while ((k--) + 1) { this.push(undefined); } } this.splice(new_index, 0, this.splice(old_index, 1)[0]); return this; // for testing purposes }; function moveFieldUp(i) { if (i > 0) { curForm.fdesc.inputFields.move(i,i-1); updateFormDisplay(); saveForm(); return true; } else return false; } function moveFieldDown(i) { if (i < curForm.fdesc.inputFields.length - 1) { curForm.fdesc.inputFields.move(i,i+1); updateFormDisplay(); saveForm(); return true; } else return false; } function deleteField(i) { curForm.fdesc.inputFields.splice(i,1); updateFormDisplay(); saveForm(); return true; } var dialog; var fieldIndex; function showNewFieldDlg(i) { fieldIndex = i; if (!dialog) { dialog = $( "#newfielddlg" ).dialog({ autoOpen: false, height: 400, width: 600, modal: true, buttons: { "Add New Field": function() { //console.log(fieldIndex); var lab = $('#newfieldlabel').val(); var typ = $('#newfieldtype').val(); var req = $('#newfieldreq').attr('checked') == 'checked'; var opt = []; $('.newfieldoption').each(function() { var o = $(this).val().trim(); if (o != "") { opt.push(o); } }); var newField = { label: lab, required: req, type: typ }; switch (typ) { case 'radio': case 'selectOne': newField.options = opt; break; default: break; }; curForm.fdesc.inputFields.splice(fieldIndex,0,newField); updateFormDisplay(); saveForm(); dialog.dialog( "close" ); }, Cancel: function() { dialog.dialog('close'); } }, close: function() { } }); } dialog.find('input').val(''); dialog.find('.newfieldoptionsrow').html('
Items
' + '
'); dialog.find('#newfieldtype').val('text'); dialog.find('#req').removeAttr('checked'); $('#newfieldtype').unbind().change(function() { switch ($(this).val()) { case 'selectOne': $('#newfieldoptionsrow').show(); $('#newfieldreqrow').show(); break; case 'radio': $('#newfieldreqrow').hide(); $('#newfieldoptionsrow').show(); break; case 'checkbox': $('#newfieldoptionsrow').hide(); $('#newfieldreqrow').hide(); break; case 'textarea': case 'text': $('#newfieldreqrow').show(); $('#newfieldoptionsrow').hide(); break; } }); bindNewFieldOption(); dialog.dialog('open'); } function bindNewFieldOption() { $('.newfieldoption').unbind().keypress(function() { if ($(this).val().trim() != "") { var opts = $(this).parent().find('.newfieldoption'); var mtCount = 0; opts.each(function() { if ($(this).val().trim() == "") mtCount++; }); if (mtCount == 0) { $(this).parent().append('
'); //$(this).parent().find('.newfieldoption').last().focus(); bindNewFieldOption(); } } }); } bindNewFieldOption(); function buildFormFromDescriptor(desc) { var vf = ' \n' + '
\n' + ' \n'; var index = 0; desc.inputFields.forEach(function(f) { vf += ' \n'; switch (f.type) { case 'text': vf += '\n'; break; case 'textarea': vf += '\n'; break; case 'selectOne': vf += '\n'; break; case 'checkbox': vf += '\n'; break; case 'radio': var radioname = f.label + "" + Math.floor(Math.random() * 10000); var cnt = 0; f.options.forEach(function(o) { cnt++; if (cnt == 1) { vf += '\n'; } else { vf += '\n ' + '' + '\n'; } }); vf += '\n'; break; } }); vf += ' \n'; //vf += '\n'; vf += ' \n'; vf += ' \n'; vf += ' \n'; vf += '
' + f.label + '
 ' : '">') + '
 ' : '">') + '
'; if (f.required) vf += ' '; vf += '
' + o + '
' + o + '
 
 
\n'; vf += '
\n'; vf += ' \n'; vf += '
\n
\n
\n'; return vf; } function validateForms() { $('.formdiv').each(function() { var valid = true; $(this).find('.form-req').each(function() { switch ($(this).attr('type')) { case 'checkbox': break; case 'radio': break; default: if ($(this).val().trim() == "") { valid = false; } break; } }); if (valid) $(this).find('input[type="submit"]').removeAttr('disabled'); else $(this).find('input[type="submit"]').attr('disabled','disabled'); }); } $('#newfieldtype').unbind().change(function() { switch ($(this).val()) { case 'selectOne': $('#newfieldoptionsrow').show(); $('#newfieldreqrow').show(); break; case 'radio': $('#newfieldreqrow').hide(); $('#newfieldoptionsrow').show(); break; case 'checkbox': $('#newfieldoptionsrow').hide(); $('#newfieldreqrow').hide(); break; case 'textarea': case 'text': $('#newfieldreqrow').show(); $('#newfieldoptionsrow').hide(); break; } }); function bindNewFieldOption() { $('.newfieldoption').unbind().keypress(function() { if ($(this).val().trim() != "") { var opts = $(this).parent().find('.newfieldoption'); var mtCount = 0; opts.each(function() { if ($(this).val().trim() == "") mtCount++; }); if (mtCount == 0) { $(this).parent().append('
'); //$(this).parent().find('.newfieldoption').last().focus(); bindNewFieldOption(); } } }); } //TODO: Use createValue after createValue is changed to handle empty values function updateIfChanged(topicId, tag, newValue) { //console.log("updateIfChanged(" + topicId + "," + tag + "," + newValue + ")"); screwtopDb().url(DBURL) .topicById(topicId) .each(function(topic) { screwtopDb(topic).url(DBURL) .tag('./' + tag) .values() .ifNone(function() { if (!screwtopDb.isEmpty(newValue.trim())) { screwtopDb(topic).url(DBURL) .addTags(tag,newValue.trim()) .end(); } }, function(vals) { if (vals[0].text != newValue.trim()) { if ((tag == "priority" || tag == "articleOptions" || tag == "expdate") && screwtopDb.isEmpty(newValue)) { screwtopDb().url(DBURL) .topicById(topicId, {elide:true}) .tag('./' + tag) .deleteTags() .end(); } else { screwtopDb(vals).url(DBURL) .each(function(v) { screwtopDb(v).url(DBURL) .updateValue(newValue.trim()) .end(); }) .end(); } } }) .end(); }) .end() } function updateArticle(topicId, title, content, date, categories, prio, expdate, articleOptions, eventinfo, func) { showSpinner(); var datetime = date.getISO8601(); var month = date.getMonth(); var year = date.getFullYear(); var dt = new Date(expdate); var utcms = dt.getTime() + (dt.getTimezoneOffset() * 60 * 1000); if (expdate.trim() == "") { utcms = ""; } updateIfChanged(topicId, 'title-' + lang, title); updateIfChanged(topicId, 'content-' + lang, content); updateIfChanged(topicId, 'priority', prio); updateIfChanged(topicId, 'articleOptions', articleOptions); updateIfChanged(topicId, 'expdate', utcms + ""); screwtopDb().url(DBURL) .topicById(topicId) // Update the title if it has changed .push() // Update categories if they have changed .each(function(t) { screwtopDb(t).url(DBURL) .tag('./' + blogTopicText + "/category-" + lang) .values() .func(function(categoryValues) { // Add or delete categories as necessary. It might be better to just delete and re-create // the whole tag, but this is a better exercise of the API. var valuesToAdd = screwtopDb.select(categories, function(cat) { return (screwtopDb.detect(categoryValues, function(val) { return (val.text == cat); })) == null; }); var valuesToDelete = screwtopDb.reject(categoryValues, function(val) { return screwtopDb.includes(categories, val.text); }); //alert("Delete:\n" + JSON.stringify(valuesToDelete) + "\n\nAdd:\n" + JSON.stringify(valuesToAdd)); if (valuesToAdd.length + valuesToDelete.length > 0) { screwtopDb.forEach(valuesToDelete, function(val) { screwtopDb().url(DBURL) .deleteValues(val.valueId) .end(); }); screwtopDb.forEach(valuesToAdd, function(txt) { if ($.trim(txt) != "") { screwtopDb(t) .addTags(blogTopicText + "/category-" + lang, txt) .end(); } }); } }) .end(); //var tag = t.tag(blogOwner + "/" + blogTopicText + "/category"); //var categoryValues = tag != null ? tag.values : []; }) //TODO: Don't add a timestamp if nothing is changed. // Add modified timestamp .pop() .each(function(t) { //screwtopDb(t.tag(blogOwner + "/creation-date-and-time")) screwtopDb(t).url(DBURL) .tag('./creation-date-and-time') .addValues(datetime) .func(function(result) { func(result.ids); }) .end(); }) .end(hideSpinner); }; function bindCommentButtons() { $('.newcommentbtn') .unbind() .click(function(ev) { var articleTopicId = $(this).attr("data"); $(this).parent().parent().append($('#newcomment')); $(this).hide(); $('#newcommentarea').val(''); $('#newcomment').show("blind"); $("html, body").animate({ scrollTop: $('#newcomment').height() }, "slow"); bindNewCommentDlgButtons(articleTopicId); }); } function bindNewCommentDlgButtons(articleTopicId) { $('#newcommentcancelbtn').unbind(); $('#newcommentcancelbtn').click(function() { $('#newcomment').hide().appendTo($('body')); $('.newcommentbtn').show(); }); $('#newcommentsubmitbtn').unbind(); $('#newcommentsubmitbtn').click(function() { var date = new Date(); //var content = Wiky.toHtml($('#newcommentarea').val()); var content = $('#newcommentarea').val(); var author = username; $('#spinner').show(); $('#articles').hide(); putComment(articleTopicId, content, date, function() { $('#newcomment').hide().appendTo($('body')); showArticle('/' + blogTopicTitle + '/article/id/' + articleTopicId); }); }); } function bindEditCommentButtons() { $('.editcommentbtn').unbind().click(function(ev) { var commentTopicId = $(ev.target).attr("data"); var articleTopicId = $(ev.target).attr("parentArticleId"); $(this).parent().parent().append($('#newcomment')); $('#newcomment').show("blind", 500, function() { var content = $(this).parent().next().html(); //$('#newcommentarea').val(Wiky.toWiki(content)); $('#newcommentarea').val(content); $('.' + commentTopicId).hide(); $("html, body").animate({ scrollTop: $(document).height() }, "slow"); bindEditCommentDlgButtons(commentTopicId, articleTopicId); }) }); } function bindEditCommentDlgButtons(commentTopicId, articleTopicId) { $('#newcommentcancelbtn').unbind(); $('#newcommentcancelbtn').click(function() { $('#newcomment').hide().appendTo($('body')); $('.' + commentTopicId).show(); }); $('#newcommentsubmitbtn').unbind(); $('#newcommentsubmitbtn').click(function() { var date = new Date(); //var content = Wiky.toHtml($('#newcommentarea').val()); var content = $('#newcommentarea').val(); var author = username; $('#spinner').show(); $('#articles').hide(); updateComment(commentTopicId, content, date, function(ids) { $('#newcomment').hide().appendTo($('body')); showArticle('/' + blogTopicTitle + '/article/id/' + articleTopicId); }); }); } function putComment(articleTopicId, content, date, func) { var datetime = date.getISO8601(); var month = date.getMonth(); var year = date.getFullYear(); //var newData = { // tagText: 'comment', // valueText: "comment", // options: [ "uniqueValue" ] //}; screwtopDb().url(DBURL) .topicById(articleTopicId, {elide:true}) .each(function(topic) { var commentObj = { text: 'comment' + screwtopDb.guid(), 'creation-date-and-time': datetime, author: username }; commentObj["content-" + lang] = content; var data = { text:topic.text, }; data["comment-" + lang] = [commentObj]; /* var data = { text: topic.text, comment: [{ text: 'comment' + screwtopDb.guid(), content: content, 'creation-date-and-time': datetime, author: username }] }; */ screwtopDb().url(DBURL) .addTopics(data) .end(); }) .end(func); } function updateComment(topicId, content, date, func) { var datetime = date.getISO8601(); var month = date.getMonth(); var year = date.getFullYear(); screwtopDb().url(DBURL) .topicById(topicId,{elide:true}) // Update content if it has changed .each(function(t) { screwtopDb(t) .tag(username + "/content-" + lang) .values() .each(function(val) { if (val.text != content) { screwtopDb(val) .updateValue(content) .end(); } }) .end(); }) //TODO: Don't add a timestamp if nothing is changed. // Add modified timestamp .each(function(t) { screwtopDb(t) .tag(username + "/creation-date-and-time") .addValues(datetime) .func(function(result) { func(result.ids); }) .end(); }) .end(func); }; function setHtmlArea() { var st = $('body').scrollTop(); $('#newcontentarea').htmlarea("dispose"); $('#newcontentarea').htmlarea({ //css: "/js/jHtmlArea/style/jHtmlArea.css", css: "/css/jhtmlarea.css", toolbar: [ ["html"], ["bold", "italic", "underline", "strikethrough", "|", "subscript", "superscript"], ["forecolor"], ["increasefontsize", "decreasefontsize"], ["orderedlist", "unorderedlist"], ["indent", "outdent"], ["justifyleft", "justifycenter", "justifyright"], ["link", "unlink", "image", "horizontalrule"], ["p", "h1", "h2", "h3", "h4", "h5", "h6"], ["cut", "copy", "paste"] ] }); $('body').animate({scrollTop:st}, 0); //$("iframe").attr("id", "txtText"); //$("#txtText").contents().find('body').css({"backgroundColor" : "white", "font-size" : "11pt", "line-height" : "1.4em", "color" : "#444", "font-family" : "sans-serif" }); } function replaceArticleEvent(se, eventTopicText) { var tid = screwtopDb.isEmpty(se.events) ? se.specifications.articleTopicId : se.events.articleTopicId; //console.log('tid=' + tid); //console.log(JSON.stringify(se,null,' ')); showSpinner(); screwtopDb().url(DBURL) .topicById(tid) .tag('./eventTopicId') .values() .each(function(v) { eventValueId(v.text, function(valueId) { screwtopDb().url(DBURL) .deleteValues(valueId) .end(); }); }) .addTopics(se) .topicByName(eventTopicText) .each(function(topic) { screwtopDb().url(DBURL) .beginServerExecution() .topicById(tid,{elide:true}) .tag('./eventTopicId') .deleteTags() .topicById(tid, {elide:true}) .addTags('eventTopicId',topic.topicId) .endServerExecution() .end(); }) .invalidateCache() .func(function() { events = null; hideSpinner(); }) .end(updateCalendar); } function validateArticleEvent() { var st = $('#starttime').timepicker('getTime'); var sd = new Date(Date.parse($('#startdate').val())); var et = $('#endtime').timepicker('getTime'); var ed = new Date(Date.parse($('#enddate').val())); var loc = $('#location').val(); if (st.getHours() == 0 && et.getHours() == 0) return true; // Event not specified var startdt = Date.parse(sd.toLocaleDateString() + ' ' + st.toLocaleTimeString()); var enddt = Date.parse(ed.toLocaleDateString() + ' ' + et.toLocaleTimeString()); var dur = (enddt - startdt) / (1000 * 60); if (sd < ed) { alert("The event end date is before the start date."); return false; } if (dur <= 0) { alert("The event's end time is equal to or earlier than its start time."); return false; } if ($('#recur').is(':checked')) { var nth = $('#nth').val(); var xDay = $('#xday').val(); var endmo = $('#endmo').val(); var endyr = $('#endyr').val(); var enddt = new Date(); var stdt = new Date(startdt); enddt.setFullYear(endyr); enddt.setMonth(endmo); if (enddt.getTime()<= stdt.getTime()) { alert("The recurring event's end date is earlier than its start date.") return false; } } return true; } function putArticleEvent(articleTopicId) { var title = $('#newtitle').val(); var st = $('#starttime').timepicker('getTime'); var sd = new Date(Date.parse($('#startdate').val())); var et = $('#endtime').timepicker('getTime'); var ed = new Date(Date.parse($('#enddate').val())); var startdt = Date.parse(sd.toLocaleDateString() + ' ' + st.toLocaleTimeString()); var enddt = Date.parse(ed.toLocaleDateString() + ' ' + et.toLocaleTimeString()); var dur = (enddt - startdt) / (1000 * 60); var loc = $('#location').val(); if (!screwtopDb.isEmpty(loc) && !screwtopDb.isEmpty(sd) && !screwtopDb.isEmpty(ed) && !screwtopDb.isEmpty(st) && !screwtopDb.isEmpty(et)) { if ($('#recur').is(':checked')) { var ev = schedEvent(startdt, dur, title, loc, articleTopicId, abgcolor).events; var nth = $('#nth').val(); var xDay = $('#xday').val(); var endmo = $('#endmo').val(); var endyr = $('#endyr').val(); var enddt = new Date(); var stdt = new Date(startdt); enddt.setFullYear(endyr); enddt.setMonth(endmo); if (enddt.getTime()<= stdt.getTime()) { alert("The recurring event end date is earlier than its start date.") return; } var se = recurEvent(ev, nth, xDay, endmo, endyr, abgcolor); replaceArticleEvent(se, se.specifications.text); } else { var se = schedEvent(startdt, dur, title, loc, articleTopicId, abgcolor); replaceArticleEvent(se, se.events.text); } } } function bindNewArticleButtons() { $('#delesbtn,#delenbtn').hide(); $('#newarticlecancelbtn').unbind(); $('#newarticlecancelbtn').click(function() { $('#main').show(); $('#newarticle').hide("blind", function() { }); }); $('#articleeventdiv').hide(); $('#articleeventbtn').unbind().click(function() { $('#startdate').val(''); $('#enddate').val(''); $('#starttime').val(''); $('#endtime').val(''); $('#location').val(''); if ($('#articleeventdiv').is(':visible')) { $('#articleeventdiv').hide('blind'); } else { $('#articleeventdiv').show('blind'); } $('#nth,#xday,#endmo,#endyr').change(function() { $('#recur').prop('checked',true); }) }); $('#newarticlesubmitbtn').unbind().click(function() { var date = new Date().setISO8601($('#newdate').val()); var title = $('#newtitle').val(); var cats = $('#newcategories').val().trim(); if (screwtopDb.isEmpty(cats)) cats = "Uncategorized" var categories = screwtopDb.collect(cats.split(','), function(s) { return $.trim(s) }); var content = $('#newcontentarea').htmlarea("toHtmlString"); var priority = $('#priority').val(); var expdate = $('#expdate').val(); var articleOptions = $('#nosanitizecb').is(':checked') ? "nosanitize" : "sanitize"; if (/class="formsrc"/.test(content)) articleOptions = "nosanitize"; var author = username; if (screwtopDb.isEmpty(title.trim())) title = "Untitled article"; if (!validateArticleEvent()) return; putArticle(title, content, date, categories, priority, expdate, articleOptions, function(article) { $('#main').show(); $('#newarticle').hide("blind"); showArticle('/' + blogTopicTitle + '/article/id/' + article.topicId); putArticleEvent(article.topicId); /* setSingleUseToken(function(tok) { $.ajax({ url: 'email?articleId=' + topicId + '&token=' + tok, success: function(html) { //alert("The article has been emailed.") } }); }); */ }); }); $('#uploadimagebtn').unbind().click(function(ev) { $('#uploadimagebtn').hide(); uploadImage(function(upload, positioning) { var obj = { text: 'user:' + username, 'blog images': { text: '', deletehash: upload.image.deletehash, type: upload.image.type, animated: upload.image.animated, width: upload.image.width, height: upload.image.height, size: upload.image.size, links: upload.links } }; //alert(JSON.stringify(upload,null,' ')); //alert(JSON.stringify(obj,null,' ')); screwtopDb().url(DBURL) .addTopics(obj) .end(function() { var link = upload.links.large_thumbnail; var html = ''; //$('#newcontentarea').htmlarea("image", link); $('#uploadimagebtn').show(); $('#uploader').hide('blind'); $('#newcontentarea').htmlarea("pasteHTML", html); }); }, ev); }); bindInsertFormBtn(); } var uploaderCallback = null; function uploadImage(cb, ev) { uploaderCallback = cb; $('#uploader').show('blind'); $('.iuploadbtn').attr('disabled','disabled'); //$('#radio').buttonset(); $('#image').unbind().change(function() { if ($(this).val().length > 0) { $('.iuploadbtn').removeAttr('disabled'); $('.rename').show(); } else { $('.iuploadbtn').attr('disabled','disabled'); $('.rename').hide(); } }); var progressbar = $( "#iprogressbar" ), progressLabel = $( ".iprogress-label" ); //progressbar.progressbar("destroy"); progressbar.progressbar({ value: false, change: function() { progressLabel.text( progressbar.progressbar( "value" ) + "%" ); }, complete: function() { progressLabel.text( "Done." ); } }); function progress(val) { progressbar.progressbar("value", val); } progressLabel.text("Initializing..."); $('#iuploadform').unbind().submit(function() { progressbar.show(); var imagefloat = $('input[name="ipos"]:checked', '#iuploadform').attr("ipos").trim(); $.ajax(location.protocol + '//i.screwtopdb.com/token.php?domain=' + APPNAME).done(function(data) { uploadToken = data.singleUseToken; $.upload( location.protocol + "//i.screwtopdb.com/appuploader", new FormData($('#iuploadform')[0]),null,null,{ headers: { 'ScrewtopDb-Upload-Token': uploadToken, 'ScrewtopDb-Upload-Domain': APPNAME } }) .progress( function( progressEvent, uploading) { if( progressEvent.lengthComputable) { var percent = Math.round( progressEvent.loaded * 100 / progressEvent.total); progress(percent); } }) .done( function(responseText) { progressLabel.text('Upload complete.'); if (screwtopDb.isString(responseText)) { uploaderCallback(JSON.parse(responseText).upload,imagefloat); } else { uploaderCallback(responseText.upload,imagefloat); } setTimeout(function() { progressbar.progressbar("destroy"); progressbar.hide(); $('#uploadedfile').val(""); $('.rename').val('').hide(); }, 1000) }); }); return false; }); $('#uploadcancelbtn').unbind().click(function() { $('#uploader').hide('blind'); $('#uploadimagebtn').show(); }); } function clean(text) { content=text.replace(/“/g,'"'); content=content.replace(/”/g,'"'); content=content.replace(/’/g,"'"); content=content.replace(/–/g,"-"); content=content.replace(/©/g,"©"); content=content.replace(/®/g,"®"); content=content.replace(/°/g,"°"); content=content.replace(/¶/g,"

"); content=content.replace(/¿/g,"¿"); content=content.replace(/¡/g,'¡'); content=content.replace(/¢/g,'¢'); content=content.replace(/£/g,'£'); content=content.replace(/¥/g,'¥'); content=content.replace(//g,''); //console.log(content) return content; } function putArticle(title, content, date, categories, prio, expdate, articleOptions, func) { showSpinner(); var datetime = date.getISO8601(); var month = date.getMonth(); var year = date.getFullYear(); var articleId = "blog article" + screwtopDb.guid(); var articleTag = 'article-month/' + monthNames[month] + " " + year; var updObj = { text: blogTopicText } articleObj = { text: articleId, //title: title, priority: prio, articleOptions: articleOptions, //content: clean(content), "creation-date-and-time": datetime, author: username } if (expdate.trim() != "") { var dt = new Date(Date.parse(expdate)); var utcms = dt.getTime() + (dt.getTimezoneOffset() * 60 * 1000); articleObj.expdate = utcms + ""; } articleObj['title-' + lang] = title; articleObj['content-' + lang] = clean(content); //Add any categories if (categories.length > 0) { vals = []; for (var i = 0; i < categories.length; i++) { if ($.trim(categories[i]) != "") vals.push($.trim(categories[i])); } if (vals.length > 0) { articleObj[blogTopicText + "/category-" + lang ] = categories; } } updObj[articleTag] = articleObj; screwtopDb().url(DBURL) .addTopics(updObj) .topicByName(articleId) .func(function(articles) { func(articles[0]); }) .end(hideSpinner); } /* function isLoggedIn() { return !screwtopDb.isEmpty(username); } */ // Find the valueId for a topic using a reverse tag matching the // provided regular expression function valueForTopicInTagMatching(topicId, re, func) { screwtopDb().url(DBURL) .invalidateCache() .topicById(topicId, {include: "inbound",elide:true}) .tags() .select(re) .values() .topics({elide:true}) .tags() .select(re) .values() .select(function(val) { return !screwtopDb.isEmpty(val) && val.topicId == topicId }) .ifAny(function(val) { func(val[0].valueId); },function() { func(null); }) .end(); } function articleValueId(articleTopicId, func) { return valueForTopicInTagMatching(articleTopicId, /^.*\/article-month\/.*$/, func); } function commentValueId(commentTopicId, func) { var r = RegExp("^.*\\/comment-" + lang + "$"); return valueForTopicInTagMatching(commentTopicId, r, func); } function eventValueId(eventTopicId, func) { return valueForTopicInTagMatching(eventTopicId, /^.*\/specifications$|.*\/events$/, func); } function showhideSidebar() { if (blogOptions.indexOf('upcoming') < 0) $('.evlist').hide(); else $('.evlist').show(); if (blogOptions.indexOf("nosidebar") < 0) $('#sidebar-container').show(); else $('#sidebar-container').hide(); } function showContent(href) { var showSpinner = true; //$('#sidebar-container').hide(); window.scrollTo(0,0); setTimeout(function() { if (showSpinner) { $('#spinner').fadeIn('fast'); } }, 1000); authenticatedAjax(href + '?embed=1', function(html) { showSpinner = false; $('#spinner').stop().hide(); $('#articles').html(html); showhideSidebar(); $('#articles').fadeIn('fast', function() { initCalendar(); updateCalendar(); }); try { history.pushState(html, null, addlang(href)); } catch(e) {} setAuthorActions(); $('.rnd').corner('6px'); }); if (href != '/Calendar' && href != '/Files' && href != '/Discussions') { var roothref = href.replace(/^\/.+?(\/.+$)/,""); if (roothref == "") roothref = href; //console.log(roothref); authenticatedAjax(roothref + '/sidebar?embed=1', function(html) { $('#sidebar').html(html); //if (rootBlogOptions.indexOf('nologin') >= 0) $('#topsidebar').css('margin-top','-16px'); }); } $('#articles').fadeOut('fast'); } var configActive = false; function bindConfig() { var configpass = null; function adjustImg(starth, h, y, imgOffset) { var imgw = $('#imagediv img').width(); var bannerw = $('#bannerdiv').width(); var pct = (h+y)/h; //console.log(Math.round(pct*100) + '% y=' + y + ', h=' + h + ', imgw=' + imgw + ', bannerw=' + bannerw); $('#bannerdiv').height(h * pct); var newh = $('#bannerdiv').height(); if (newh > starth) { $('#imagediv img').height(h * pct); var newimgw = $('#imagediv img').width(); var offs = { top: imgOffset.top, left: imgOffset.left - ((newimgw - bannerw) / 2)}; $('#imagediv img').offset(offs); //console.log(JSON.stringify(offs)); } else { var offs = { top: imgOffset.top - (starth - newh)/2, left: imgOffset.left}; $('#imagediv img').offset(offs); //console.log(JSON.stringify(offs)); } } function enableBannerCropping() { $('#bannerbtndiv').remove(); $('#bannerdiv').append( '

' + '' + '' + '' + '
'); var starth = $('#bannerdiv').height(); var h; $('#bannersize').draggable({ cursor: 'move', start: function() { h = $('#bannerdiv').height(); //imgOffset = $('#imagediv img').offset(); //console.log('imgOffset: ' + JSON.stringify(imgOffset)); return configActive; }, drag: function(ev, ui) { var y = parseInt( ui.position.top ); //adjustImg(starth, h,y, imgOffset); //var imgw = $('#imagediv img').width(); var bannerw = $('#bannerdiv').width(); var pct = (h+y)/h; $('#bannerdiv').height(h * pct); ui.position.top -= y; }, stop: function(ev, ui) { getCssObj("bannerCss-" + lang, blogTopicId, function(cssObj) { cssObj.height = $('#bannerdiv').height() + "px;"; updateCss("bannerCss-" + lang, cssStrFromObj(cssObj), blogTopicId); /* background-image: url('https://i.screwtopdb.com/fx25b30uq.jpg'); height:33%; background-size: 100%; background-position: 0% 25% */ }); resetcnt = 0; } }); var startx,starty; var xpos,ypos; $('#imagemove').draggable({ cursor: 'move', revert:true, start: function(ev, ui) { startx = parseInt( ui.position.left ); starty = parseInt( ui.position.top ); var xy = $('#bannerdiv').css('background-position').trim().split(' '); xpos = parseInt(xy[0]); ypos = parseInt(xy[1]); return configActive; }, drag: function(ev, ui) { var x = parseInt( ui.position.left ); var y = parseInt( ui.position.top ); $('#bannerdiv').css('background-position',(xpos+(x-startx)) + "px " + (ypos+(y-starty)) + "px"); }, stop: function(ev, ui) { getCssObj("bannerCss-" + lang, blogTopicId, function(cssObj) { cssObj["background-position"] = $('#bannerdiv').css('background-position'); updateCss("bannerCss-" + lang, cssStrFromObj(cssObj), blogTopicId); }); resetcnt = 0; } }); function imgLeft() { return parseInt($('#imagediv img').css('left')); } function imgTop() { return parseInt($('#imagediv img').css('top')); } var isiz; $('#imagesize').draggable({ cursor: 'move', revert:true, start: function() { isiz = parseInt($('#bannerdiv').css('background-size').split(' ')[1]); return configActive; }, drag: function(ev, ui) { var y = ui.position.top; var pct = (200-y)/200; var newisiz = isiz * pct; $('#bannerdiv').css('background-size', "auto " + newisiz + "%"); }, stop: function(ev, ui) { getCssObj("bannerCss-" + lang, blogTopicId, function(cssObj) { cssObj["background-size"] = $('#bannerdiv').css('background-size'); updateCss("bannerCss-" + lang, cssStrFromObj(cssObj), blogTopicId); }); resetcnt = 0; } }); var resetcnt = 0; $('#bannerreset').unbind().click(function() { if (resetcnt == 1) { //$('#imagediv img').css('height','').css('left','').css('top',''); //$('#bannerdiv').height($('#imagediv img').height()); deleteCss("bannerCss-" + lang, blogTopicId); deleteCss("imageCss-" + lang, blogTopicId); } else if (resetcnt == 0) { $('#header').css('left','0').css('top','-' + $('#bannerdiv').height() + 'px'); $('#blogsubtitle').css('left','0').css('top','-' + ($('#bannerdiv').height() - 50) + 'px'); deleteCss("titleCss-" + lang, blogTopicId); deleteCss("subtitleCss-" + lang, blogTopicId); } resetcnt++; if (resetcnt > 1) { resetcnt = 0; window.location.reload(); } }); } function deleteCss(tag,id) { screwtopDb().url(DBURL) .invalidateCache() .logout() .login(APPNAME,APPNAME,configpass,60,true) .beginServerExecution() .topicById(id,{tagfilter: APPNAME + '/' + tag, elide:true}) .values() .deleteValues() .endServerExecution() .logout() .authentication(APPNAME,username,password) .end(); } function getCssObj(tag,id,cb) { var retval = {}; screwtopDb().url(DBURL) .invalidateCache() .login(APPNAME,APPNAME,configpass,60,true) .topicById(id,{tagfilter: APPNAME + '/' + tag, elide:true}) .values() .text() .each(function(css) { var arr = css.split(";"); arr.forEach(function(nv) { var n = nv.replace(/^(.+?):.*$/,"$1").trim(); var v = nv.replace(/^.+?:(.+)$/,"$1").trim(); retval[n] = v; }) }) .end(function() { cb(retval); }); } function cssStrFromObj(obj) { var str = ""; for (m in obj) { if (m.trim().length > 0) str += m + ":" + obj[m] + "; "; } return str; } function updateCss(tag,css,id) { if (css == undefined) return; screwtopDb().url(DBURL) .invalidateCache() .login(APPNAME,APPNAME,configpass,60,true) .topicById(id,{tagfilter: APPNAME + '/' + tag, elide:true}) .each(function(topic) { screwtopDb().url(DBURL) .createValue(topic.text, APPNAME + '/' + tag, css) .end(); }) /* .values() .ifNone(function() { screwtopDb().url(DBURL) .topicById(id,{elide:true}) .addTags(tag, css) .end(); }, function(vals) { screwtopDb(vals).url(DBURL) .updateValue(css) .end(); }) */ .logout() .authentication(APPNAME,username,password) .end(); } function enableTitlePositioning() { $('#header').draggable({ cursor: 'move', start: function() { return configActive; }, stop: function(ev, ui) { var offsetXPos = parseInt( ui.position.left ); var offsetYPos = parseInt( ui.position.top ); var w = $('#header').parent().width(); var offsetXPct = offsetXPos*100/w; var css = 'top:' + offsetYPos + 'px;left:' + Math.round(offsetXPct) + '%;'; updateCss('titleCss-' + lang, css, blogTopicId); } }); $('#blogsubtitle').css('cursor','pointer').draggable({ cursor: 'move', start: function() { return configActive; }, stop: function(ev, ui) { var offsetXPos = parseInt( ui.position.left ); var offsetYPos = parseInt( ui.position.top ); var w = $('#blogsubtitle').parent().width(); var offsetXPct = offsetXPos*100/w; var css = 'top:' + offsetYPos + 'px;left:' + Math.round(offsetXPct) + '%;'; updateCss('subtitleCss-' + lang, css, blogTopicId); } }); } function showConfigTools() { $('.configtools').remove(); $('#infoline, #main').css("position","relative").css("top","60px"); var ctstyle = "margin-top: -26px; margin-left:-16px;"; if (rootBlogOptions.indexOf('layoutpitch') < 0) { $('#infoline').css('margin-top','40px'); if (rootBlogOptions.indexOf('layoutpitch') < 0) { ctstyle = "margin-top: 0px; text-align:left;display:inline;" } } $('.infoitem:not(#homebtn) a:not([href="/Calendar"])').prepend( '
' + '' + '' + //'' + '' + '
'); $('.infoitem:not(#homebtn) a[href="/Calendar"]').prepend( '
' + '' + '' + '' + '
'); var items = $('.infoitem:not(#homebtn)'); var len = items.length; $(items[0]).find('a div .ilfr').remove(); $(items[len - 1]).find('a div .irtr').remove(); $('.subitem:not(.sect) a').prepend( '
' + '' + '' + //'' + '
'); items = $('.subitem'); len = items.length; if (items.length == 1) items.find('.configtools').remove(); $(items[0]).find('a div .silf').remove(); $(items[len - 1]).find('a div .sirt').remove(); $('.subitem2:not(.blink):not(.sect) a').prepend( '
' + '' + '' + //'' + '' + '
'); items = $('.subitem2'); len = items.length; if (items.length == 1) items.find('.ilf,.irt').remove(); $(items[0]).find('a div .ilf').remove(); $(items[len - 1]).find('a div .irt').remove(); $('#homebtn a').prepend( '' + '' + ''); $('.sect a').prepend( '
' + '' + '' + '
'); $('body').prepend( '
' + '' + '
'); $('#articles .articlediv').first().prepend( '
' + '' + '
'); $('.fc-header-center').html( '
' + '' + '
'); $('.td-commentdiv').first().prepend( '
' + '' + '
'); $('.config').show(); } function bindConfigTools() { $('.iplus').unbind().click(function(e) { var newTopicName; var targetTopicId; //e.preventDefault(); if ($(this).parent().parent().parent('#homebtn').length > 0) { targetTopicId = rootBlogTopicId; newTopicName = prompt('Enter the name for the new top-level section.'); } else { targetTopicId = blogTopicId; newTopicName = prompt('Enter the subsection to create inside the section "' + blogTopicTitle + '".'); } if (!newTopicName) return false; newTopicName = newTopicName.trim(); var isDiscussion = (newTopicName.toLowerCase() == "discuss"); var options = []; var guid = screwtopDb.guid(); screwtopDb().url(DBURL) .invalidateCache() .logout() .login(APPNAME,APPNAME,configpass,60,true) .topicById(targetTopicId,{elide: true}) .push() .tag('./options') .values() .text() .fn(function(opts) { options = opts; }) .pop() .each(function(topic) { var obj = { text: newTopicName + guid, options: options }; obj['title-' + lang] = newTopicName; obj['subtitle-' + lang] = topic["title-" + lang][0]; if (isDiscussion) obj['options'] = ["nonewbutton", "afterlogin"]; //alert(JSON.stringify(obj)); screwtopDb(topic).url(DBURL) .addTags('subblogs',newTopicName + guid) .addTopics(obj) .end(); }) .logout() .authentication(APPNAME,username,password) .end(function() { window.location.reload(); }); return false; }); $('.icpy').unbind().click(function(e) { var newTopicName; var targetTopicId; var srcTopicTitle = $(this).parent().parent().attr('href').substr(1); //e.preventDefault(); /* if ($(this).parent().parent().parent('#homebtn').length > 0) { targetTopicId = rootBlogTopicId; newTopicTitle = prompt('Enter the name for the copy of ' + srcTopicTitle + '.'); } else { targetTopicId = blogTopicId; newTopicTitle = prompt('Enter the name for the copy of ' + srcTopicTitle + '.'); } if (!newTopicTitle) return false; newTopicTitle = newTopicTitle.trim(); newTopicName = newTopicTitle + screwtopDb.guid(); //alert(srcTopicTitle + '\n\n' + newTopicTitle + '\n\n' + newTopicName); */ screwtopDb().url(DBURL) /* .invalidateCache() .logout() .login(APPNAME,APPNAME,configpass) .topicByName(srcTopicTitle,{include: 'inbound'}) .tags() .tag('./title-' + lang) .values() .topics({include: 'inbound'}) // this is the subblog topic .tag('./subblogs') .values() .topics() // this is the owning blog topic .addTags('subblogs',newTopicName) .tag('./subblogs') .values() .select("text = '" + srcTopicName + "'") //.deleteValues(oldVid) .topicByName(srcTopicName,{include: 'outbound'}) .tags() .each(function(tag) { var owner = tag.text.replace(/^(.+?)\/.*$/,"$1"); var tagtext = tag.tagText(true); var topic = {}; screwtopDb().url(DBURL) .login(APPNAME,owner,'') .fn(function() { topic.text = newTopicName; screwtopDb(tag).url(DBURL) .values() .text() .fn(function(textarr) { topic[tagtext] = textarr; }) .addTopics(topic) .end(); }) .login(APPNAME,APPNAME,configpass) .end(); }) .logout() .authentication(APPNAME,username,password) */ .end(function() { alert("This function is not yet available."); //alert(window.location); //window.location.reload(); }); return false; }); $('.idel').unbind().click(function(e) { $('#spinner').fadeIn('fast'); var topicname = $(this).closest('a').attr('href'); topicname = topicname.replace(/\/(.*)$/,"$1"); var cur = $(this).closest('.subitem2,.infoitem'); if (confirm(topicname + ': Are you sure you want to delete the section and all its content?')) { var topicId; screwtopDb().url(DBURL) .invalidateCache() .logout() .login(APPNAME,APPNAME,configpass) //.beginServerExecution() .topicByName(topicname,{include: 'inbound'}) .tag('./title-' + lang) .values() .topics({include: 'inbound'}) .each(function(topic) { var valId = ""; screwtopDb(topic).url(DBURL) .tag('./subblogs') .values() .topics({elide:true, tagfilter: APPNAME + '/subblogs'}) .tags() .values() .each(function(v) { if (valId == "") { screwtopDb(v).url(DBURL) .topics() .select('text = /^' + topic.text + '/') .ifAny(function() { valId = v.valueId; }) .end(); } }) .fn(function() { screwtopDb().url(DBURL) .valueById(valId) .push() .topics() .values() .deleteValues() .pop() .deleteValues() .end(); }) .end(); }) .logout() .authentication(APPNAME,username,password) .end(function() { cur.remove(); $('#spinner').stop().hide(); }); } return false; }); var spec = '.ilf, .irtr'; if (rootBlogOptions.indexOf('layoutpitch') < 0) { spec = '.irt, .ilfr'; } $(spec).unbind().click(function(e) { $('#spinner').fadeIn('fast'); var topicname = $(this).closest('a').attr('href'); topicname = topicname.replace(/\/(.*)$/,"$1"); var cur = $(this).closest('.subitem2,.infoitem'); var nxt = cur.prev().closest('.subitem2,.infoitem'); var subblogName; screwtopDb().url(DBURL) .invalidateCache() .logout() .login(APPNAME,APPNAME,configpass,3600,true) .topicByName(topicname,{include: 'inbound'}) .tag('./title-' + lang) .values() .each(function(v) { subblogName = v.text; }) .topics({elide:true, include: "inbound"}) .tag('./subblogs') .values() .topics({elide:true, tagfilter: APPNAME + '/subblogs'}) .values() .fn(function(vals) { var prev = null; vals.forEach(function(v) { if (v.text != subblogName) { prev = v; } else if (prev != null) { screwtopDb().url(DBURL) .moveValue(prev.valueId, v.valueId) .end(); prev = null; } }) }) .logout() .authentication(APPNAME,username,password) .end(function() { cur.insertBefore(nxt); bindConfig(); $('#spinner').stop().hide(); }); return false; }); spec = '.irt, .ilfr'; if (rootBlogOptions.indexOf('layoutpitch') < 0) { spec = '.ilf, .irtr'; } $(spec).unbind().click(function(e) { $('#spinner').fadeIn('fast'); var topicname = $(this).closest('a').attr('href'); topicname = topicname.replace(/\/(.*)$/,"$1"); var cur = $(this).closest('.subitem2,.infoitem'); var nxt = cur.next().closest('.subitem2,.infoitem'); var subblogName; screwtopDb().url(DBURL) .invalidateCache() .logout() .login(APPNAME,APPNAME,configpass,3600,true) .topicByName(topicname,{include: 'inbound'}) .tag('./title-' + lang) .values() .each(function(v) { subblogName = v.text; }) .topics({elide:true, include: "inbound"}) .tag('./subblogs') .values() .topics({elide:true, tagfilter: APPNAME + '/subblogs'}) .values() .fn(function(vals) { var targ = null; vals.forEach(function(v) { if (v.text == subblogName) { targ = v; } else if (targ != null) { screwtopDb().url(DBURL) .moveValue(targ.valueId,v.valueId) .end(); targ = null; } }) }) .logout() .authentication(APPNAME,username,password) .end(function() { cur.insertAfter(nxt); bindConfig(); $('#spinner').stop().hide(); }); return false; }); spec = '.silf'; //if (rootBlogOptions.indexOf('layoutpitch') < 0) { // spec = '.sirt'; //} $(spec).unbind().click(function(e) { $('#spinner').fadeIn('fast'); var topicid = $(this).closest('a').attr('href'); topicid = topicid.replace(/.*\/(.*)$/,"$1"); var cur = $(this).closest('.subitem'); var prv = cur.prev().closest('.subitem'); screwtopDb().url(DBURL) .invalidateCache() .logout() .login(APPNAME,APPNAME,configpass, 3600, true) .topicById(topicid,{elide:true, include:'inbound'}) .tags() .select('text = /^.*?\\/article-month\\/.*$/') .values() .topics({elide:true}) .tags() .select('text = /^.*?\\/article-month\\/.*$/') .values() // This is the article list .topics({elide:true}) .sort(function(a,b) { var af = parseFloat(screwtopDb.isDefined(a.priority) ? a.priority[0] : 100); var bf = parseFloat(screwtopDb.isDefined(b.priority) ? b.priority[0] : 100); if (af < bf) return -1; else if (af > bf) return 1; else return 0; }) .fn(function(topics) { var i = 100; screwtopDb(topics).url(DBURL) .each(function(t) { var p = i++; if (t.topicId == topicid) { p -= 1.5; } //"New priority: " + p); screwtopDb(t).url(DBURL) .tags() .select('text = /.*\\/priority$/') .values() .ifNone(function() { screwtopDb(t).url(DBURL) .addTags('priority',p) .end(); }, function(vals) { screwtopDb(vals).url(DBURL) .updateValue(p) .end() }) .end(); }) .end(); }) .logout() .authentication(APPNAME,username,password) .end(function() { cur.insertBefore(prv); bindConfig(); $('#spinner').stop().hide(); }); return false; }); spec = '.sirt'; //if (rootBlogOptions.indexOf('layoutpitch') < 0) { // spec = '.silf'; //} $(spec).unbind().click(function(e) { $('#spinner').fadeIn('fast'); var topicid = $(this).closest('a').attr('href'); topicid = topicid.replace(/.*\/(.*)$/,"$1"); var cur = $(this).closest('.subitem'); var nxt = cur.next().closest('.subitem'); screwtopDb().url(DBURL) .invalidateCache() .logout() .login(APPNAME,APPNAME,configpass,3600,true) .beginServerExecution() .topicById(topicid,{elide:true, include:'inbound'}) .tags() .select('text = /^.*?\\/article-month\\/.*$/') .values() .topics({elide:true}) .tags() .select('text = /^.*?\\/article-month\\/.*$/') .values() // This is the article list .topics({elide:true}) .endServerExecution() .sort(function(a,b) { var af = parseFloat(screwtopDb.isDefined(a.priority) ? a.priority[0] : 100); var bf = parseFloat(screwtopDb.isDefined(b.priority) ? b.priority[0] : 100); if (af < bf) return -1; else if (af > bf) return 1; else return 0; }) .fn(function(topics) { var i = 100; screwtopDb(topics).url(DBURL) .each(function(t) { var p = i++; if (t.topicId == topicid) { p += 1.5; } //console.log("New priority: " + p); screwtopDb(t).url(DBURL) .tags() .select('text = /.*\\/priority$/') .values() .ifNone(function() { screwtopDb(t).url(DBURL) .addTags('priority',p) .end(); }, function(vals) { screwtopDb(vals).url(DBURL) .updateValue(p) .end() }) .end(); }) .end(); }) .logout() .authentication(APPNAME,username,password) .end(function() { cur.insertAfter(nxt); $('#subblogs .subitem').removeClass('sect'); $('#subblogs .subitem').first().addClass('sect'); bindConfig(); $('#spinner').stop().hide(); }); return false; }); function showhidehome() { if (blogTopicId == rootBlogTopicId) { $('.homepageonly').show(); $('.nohome').hide(); } else { $('.homepageonly').hide(); $('.nohome').show(); } } var configScriptLoaded = false; $('.igearmain').unbind().click(function() { var dialog = $("#igearmaindlg").dialog({ autoOpen: false, height: 800, width: 800, modal: true, buttons: { Close: function() { dialog.dialog( "close" ); } }, close: function() { //form[ 0 ].reset(); //allFields.removeClass( "ui-state-error" ); } }); if (!configScriptLoaded) { $.getScript('/js/colorpicker/js/colorpicker.js'); $.getScript('xl/js/configure.js').done(function(data, textStatus) { populateConfig(configpass); showhidehome(); dialog.dialog('open'); configScriptLoaded = true; }) .fail(function(jqxhr, settings, e) { console.log(e); }) } else { populateConfig(configpass); showhidehome(); dialog.dialog('open'); } }); $('.igear').unbind().click(function() { var dialog = $("#igearsectdlg").dialog({ autoOpen: false, height: 800, width: 800, modal: true, buttons: { Close: function() { dialog.dialog( "close" ); } }, close: function() { //form[ 0 ].reset(); //allFields.removeClass( "ui-state-error" ); } }); if (!configScriptLoaded) { $.getScript('/js/colorpicker/js/colorpicker.js'); $.getScript('xl/js/configure.js').done(function(data, textStatus) { populateConfig(configpass); dialog.dialog('open'); configScriptLoaded = true; }) .fail(function(jqxhr, settings, e) { console.log(e); }) } else { populateConfig(configpass); dialog.dialog('open'); } }); } $('#config').unbind().click(function() { if (hasSessionStorage()) configActive = getSessionStorage(APPNAME + '-configActive') == 'true'; if (configActive) { configActive = false; setSessionStorage(APPNAME + '-configActive','false'); $('.configtools').remove(); $('.config').hide(); $('#infoline, #main').css('position','').css("top", "0"); if (rootBlogOptions.indexOf('layoutpitch') < 0) { $('#infoline').css('margin-top','0px'); } $('#bannerbtndiv').remove(); if (isBlogPoster()) { $('.authoractions').show(); $('.commentactions').show(); $('#addarticlebtn').show(); } return false; } else { $('#addarticlebtn, .authoractions, .commentactions').hide(); } if (hasSessionStorage()) configpass = getSessionStorage(APPNAME + '-configpass'); if (!configpass || configpass == "false") { var pswd = prompt("Password"); if (pswd != null && pswd.trim().length > 0) { screwtopDb().url(DBURL) .onError(function() { alert('Invalid password.'); screwtopDb().abort().end(); }) .login(APPNAME,APPNAME,pswd) .onError() .logout() .authentication(APPNAME,username,password) .end(function() { configpass = pswd; configActive = 'true'; if (hasSessionStorage()) { setSessionStorage(APPNAME + '-configpass',pswd); setSessionStorage(APPNAME + '-configActive','true'); } showConfigTools(); bindConfigTools(); enableTitlePositioning(); enableBannerCropping(); }); } } else { configActive = 'true'; if (hasSessionStorage()) { setSessionStorage(APPNAME + '-configActive','true'); } showConfigTools(); bindConfigTools(); enableTitlePositioning(); enableBannerCropping(); } // ##### TODO: DISABLE ADD, EDIT, AND DELETE ARTICLES WHILE CONFIG TOOLS ARE SHOWN (BECAUSE THEY ARE // LOGGED IN AS THE SUPERUSER.) -- Check to see if this is really needed now. }); if (hasSessionStorage()) configActive = getSessionStorage(APPNAME + '-configActive') == 'true'; if (configActive) { configpass = getSessionStorage(APPNAME + '-configpass'); showConfigTools(); bindConfigTools(); enableTitlePositioning(); enableBannerCropping(); } } function bindSettings() { $('#settings').unbind().click(function() { $('#settings').unbind().click(function() { $('#settingscancelbtn').click(); }); var showSpinner = true; setTimeout(function() { if (showSpinner) { $('#spinner').fadeIn('fast'); } }, 1000); //$('.wrapper, .commentdiv, #nominatediv, #logindiv, #regdiv, #faqdiv').hide(); $('#settingsstreet').val(''); $('#settingscity').val(''); $('#settingsstate').val(''); $('#settingszip').val(''); $('#settingsphone').val(''); $('#settingsemail').val(''); if (includeDues) $('#settingsduespaid').val(''); $('#settingspassword').val(''); $('#settingsconfirmpassword').val(''); $('.container').hide(); $('#settingsdiv').show('blind', 500); screwtopDb().url(DBURL) .session(function(s) { if (!screwtopDb.isEmpty(getCookie(rootBlogTopicId + '-impersonating'))) { $('#settingsusername').val(getCookie(rootBlogTopicId + '-impersonating')); screwtopDb().url(DBURL) .logout() .login(APPNAME, getCookie(rootBlogTopicId + '-username'), getCookie(rootBlogTopicId + '-password')) .login(APPNAME, getCookie(rootBlogTopicId + '-impersonating'), '') .attributes() // Login is required to get attributes with an empty password (don't know why…) //.login(APPNAME,username, password) .func(function(arr) { screwtopDb.forEach(arr, function(pair) { if (pair.name == "street") $('#settingsstreet').val(pair.value); else if (pair.name == "city") $('#settingscity').val(pair.value); else if (pair.name == "state") $('#settingsstate').val(pair.value); else if (pair.name == "zip") $('#settingszip').val(pair.value); else if (pair.name == "phone") $('#settingsphone').val(pair.value); else if (pair.name == "email") $('#settingsemail').val(pair.value); else if (includeDues && pair.name == "Year Paid") $('#settingsduespaid').val(pair.value); }); if (includeDues) { // Highlight unpaid dues var dt = new Date(); var thisYr = dt.getFullYear(); if ($('#settingsduespaid').val() < thisYr) $('#duespaidlabel').css('color', 'red'); } }) .end(); } else { $('#settingsusername').val(s.username); screwtopDb().url(DBURL) .login(APPNAME,username, password) .attributes() // Login is required to get attributes with an empty password (don't know why…) //.login(APPNAME,username, password) .func(function(arr) { screwtopDb.forEach(arr, function(pair) { if (pair.name == "street") $('#settingsstreet').val(pair.value); else if (pair.name == "city") $('#settingscity').val(pair.value); else if (pair.name == "state") $('#settingsstate').val(pair.value); else if (pair.name == "zip") $('#settingszip').val(pair.value); else if (pair.name == "phone") $('#settingsphone').val(pair.value); else if (pair.name == "email") $('#settingsemail').val(pair.value); else if (includeDues && pair.name == "Year Paid") $('#settingsduespaid').val(pair.value); }); if (includeDues) { // Highlight unpaid dues var dt = new Date(); var thisYr = dt.getFullYear(); if ($('#settingsduespaid').val() < thisYr) $('#duespaidlabel').css('color', 'red'); } }) .end(); } }) /* // Login is required to get attributes with an empty password (don't know why…) //.login(APPNAME,username, password) .func(function(arr) { screwtopDb.forEach(arr, function(pair) { if (pair.name == "street") $('#settingsstreet').val(pair.value); else if (pair.name == "city") $('#settingscity').val(pair.value); else if (pair.name == "state") $('#settingsstate').val(pair.value); else if (pair.name == "zip") $('#settingszip').val(pair.value); else if (pair.name == "phone") $('#settingsphone').val(pair.value); else if (pair.name == "email") $('#settingsemail').val(pair.value); }); }) //.attributes('email') */ .end(function() { //$('#settingsemail').val(em[0].value); showSpinner = false; $('#spinner').stop().hide(); }); $('#settingscancelbtn').unbind().click(function() { $('#settingsstreet').val(''); $('#settingscity').val(''); $('#settingsstate').val(''); $('#settingszip').val(''); $('#settingsphone').val(''); $('#settingsemail').val(''); if (includeDues) $('#settingsduespaid').val(''); $('#settingspassword').val(''); $('#settingsconfirmpassword').val(''); $('#settingsdiv').hide('blind', 500); bindSettings(); }) $('#settingsbutton').unbind().click(function() { var p = ''; if ($('#settingspassword').val() == $('#settingsconfirmpassword').val()) { p = $('#settingspassword').val().trim(); } else { alert('Password and confirm password do not match.'); return; } var e = $('#settingsemail').val().trim(); var obj = {}; var doIt = false; if (e != '') { obj["email"] = e; doIt = true; } if (p != '') { obj["password"] = p; doIt = true; } obj["street"] = $('#settingsstreet').val().trim(); obj["city"] = $('#settingscity').val().trim(); obj["state"] = $('#settingsstate').val().trim(); obj["zip"] = $('#settingszip').val().trim(); obj["phone"] = $('#settingsphone').val().trim(); if (doIt) { var showSpinner = true; setTimeout(function() { if (showSpinner) { $('#spinner').fadeIn('fast'); } }, 1000); screwtopDb().url(DBURL) .updateUser(obj) .end(function() { showSpinner = false; $('#spinner').stop().hide(); $('#settingsstreet').val(''); $('#settingscity').val(''); $('#settingsstate').val(''); $('#settingszip').val(''); $('#settingsphone').val(''); $('#settingsemail').val(''); $('#settingspassword').val(''); $('#settingsconfirmpassword').val(''); $('#settingsdiv').hide('blind', 500); setSingleUseToken(function(tok) { $.ajax(addlang('attr?token=' + tok)); }) alert('Account settings successfully updated.'); }); } }); $('#deleteaccountbtn').unbind().click(function() { var delpswd = prompt("All your contributions to this website will be removed.\n\n" + "Enter your password below to delete your account.\n\n"); //if (!screwtopDb.isEmpty(delpswd)) { $('#spinner').fadeIn('fast'); screwtopDb().url(DBURL) .logout() .onError(function() { $('#spinner').stop().hide(); alert('Password match error.') screwtopDb().url(DBURL).onError().abort().end(); }) .login(APPNAME, username, delpswd) .onError() .func(function() { $('#settingsemail').val(''); $('#settingspassword').val(''); $('#settingsconfirmpassword').val(''); $('#settingsdiv').hide('blind', 500); }) .deleteUser(username) .func(localLogout) .invalidateCache() .end(function() { $('#spinner').stop().hide(); location = '/'; }); //} }) }); } var shifted = false; $(document).on('keyup keydown', function(e){shifted = e.shiftKey} ); function bindMenuLinks() { $('#touchdiv').unbind().click(function() { showLoginForm(); }); $('.infoitem') .unbind() .click(function(ev) { $('.infoitem.selected').removeClass('selected'); $(this).addClass('selected'); if (shifted && !isLoggedIn()) { showLoginForm(); return false; } else { $('#main').show(); $('#newarticle').hide("blind"); var href = $(ev.target).find('a').attr('href'); showContent(href); //var articleId = $(ev.target).attr('articleId'); } return false; }); $('.infoitem a').unbind().click(function() { $(this).parent().click(); return false; }); } function schedEvent(localms, dur, title, loc, topicId, color) { // Event times stored as UTC var dt = new Date(localms); var utcms = dt.getTime() + (dt.getTimezoneOffset() * 60 * 1000); var event = { text: screwtopDb.guid(), startTime: utcms, duration: dur, //title: title, //location: loc, textColor: 'white', color: color, owner: username, articleTopicId: topicId }; event["title-" + lang] = title; event["location-" + lang] = loc; //console.log(JSON.stringify(event,null,' ')); return { text: 'schedule', events: event }; } function schedEvent2(localms, dur, title, loc, link, color) { // Event times stored as UTC var dt = new Date(localms); var utcms = dt.getTime() + (dt.getTimezoneOffset() * 60 * 1000); var event = { text: screwtopDb.guid(), startTime: utcms, duration: dur, //title: title, //location: loc, textColor: 'white', color: color, owner: username, infolink: link }; event["title-" + lang] = title; event["location-" + lang] = loc; //alert(JSON.stringify(event,null,' ')); return { text: 'schedule', events: event }; } function recurEvent(ev, nth, xDay, endMo, endYr, color) { var startDt = new Date(ev.startTime); var endDt = new Date(); endDt.setHours(0); endDt.setMinutes(0); endDt.setSeconds(0); endDt.setMonth(endMo); endDt.setDate(1); endDt.setFullYear(endYr); var recurSpec = { text: screwtopDb.guid(), nth: nth, // every 2nd recurwkday: xDay, // friday //location: ev["location"], startHr: ((startDt.getHours() - startDt.getTimezoneOffset()/60) + 24) % 24, // Local timezone hour startMin: ((startDt.getMinutes() - startDt.getTimezoneOffset()%60) + 60) % 60, // Local timezone minute duration: ev.duration, owner: ev.owner, //title: ev["title"], start: ev.startTime, end: endDt.getTime(), color: color, textColor: 'white' }; recurSpec["title-" + lang] = ev["title-" + lang]; recurSpec["location-" + lang] = ev["location-" + lang]; if (!screwtopDb.isEmpty(ev.infolink)) recurSpec.infolink = ev.infolink; if (!screwtopDb.isEmpty(ev.articleTopicId)) recurSpec.articleTopicId = ev.articleTopicId; return { text: 'recurringEvents', specifications: recurSpec }; } function initCalendar() { $('#startdate2').unbind().change(function() { var dt = new Date(Date.parse($(this).val())); $('#enddate2').datepicker('setDate',dt); $('#starttime2').timepicker('setTime', dt); }); $('#starttime2').unbind().change(function() { $('#endtime2').timepicker({'minTime': $(this).val(), 'showDuration': true }); $('#endtime2').val($(this).val()); }); var holsAdded = false; $('#calendardiv').fullCalendar({ theme: true, timeFormat: { '': 'h(:mm)t' }, eventAfterAllRender: function() { if (!holsAdded) { holsAdded = true; addHolidays(); } }, eventColor: '#4488bb', eventRender: function(event, element) { element.click(function() { var delbtnstr = "" if (event.recur == true) { delbtnstr = '' + ''; } else { delbtnstr = ''; } var morebtnstr = ""; if (!screwtopDb.isEmpty(event.infolink)) { morebtnstr = 'More info'; } else if (!screwtopDb.isEmpty(event.articleTopicId)) { morebtnstr = 'Read more'; } $('#eventdiv').html('' + event["title"] + '' + '

' + $.fullCalendar.formatDate(event.start, 'MMMM d, h:mm TT') + '

' + event.duration + ' min' + '

' + event["location"] + '

' + 'Close' + morebtnstr + delbtnstr).show('blind',500); if (!screwtopDb.isEmpty(event.owner) && event.owner != username) $('#deleventbtn,#delinstbtn,#delrecurbtn').hide(); else $('#deleventbtn,#delinstbtnm,#delrecurbtn').show(); $('#deleventbtn').unbind().click(function() { showSpinner(); screwtopDb().url(DBURL) .deleteValues(event.valueId) .invalidateCache() .end(function() { hideSpinner(); location = '/' + lang + '/calendar'; }) }); $('#delrecurbtn').unbind().click(function() { showSpinner(); screwtopDb().url(DBURL) .deleteValues(event.valueId) .invalidateCache() .end(function() { hideSpinner(); location = '/' + lang + '/calendar'; }) }); $('#delinstbtn').unbind().click(function() { showSpinner(); screwtopDb().url(DBURL) //.beginServerExecution() .topicById(event.id, {elide:true}) .addTags('exceptions',event.start.getMonth()) //.endServerExecution() .invalidateCache() .end(function() { hideSpinner(); location = '/' + lang + '/calendar'; }) }); $('#eventclosebtn').unbind().click(function() { $('#eventdiv').hide('blind', 500); }); bindLinks(); $('.morebtn2, .closebtn').corner('6px'); $('#eventdiv').corner('6px'); //if (isBlogPoster()) $('#deleventbtn').show(); }); } }); } function localLogout() { //username = ''; //$('.userinfoitem').hide(); //setAuthorActions(); epi.hidePersonalSidebar(); deleteCookie(rootBlogTopicId + '-impersonating'); deleteCookie(rootBlogTopicId + '-username'); deleteCookie(rootBlogTopicId + '-password'); //$('#addarticlebtn, #logoutbtn, #schedbtn, #deleventbtn, .localitem').hide(); //$('#loginbtn, #registerbtn').show(); deleteCookie(APPNAME + '-configpass') if (hasSessionStorage) sessionStorage[APPNAME + '-configActive'] = false; if (hasSessionStorage) sessionStorage[APPNAME + '-configpass'] = false; configActive = false; $('.configtools').remove(); window.location = '/'; } var theAnimator = null; /* function animator(targetImg,targetDiv) { if (theAnimator != null) { theAnimator.stopAnimation(); } theAnimator = this; var curLeftPx = 0; var curTopPx = 0; var curHeight; var leftInc = 0; var topInc = 0; var heightInc = 0; var divh; var divw; var ih,iw; var ratio; var frameRate; var frames; var startTime; var abort = false; var maxmag; var minmag; var delay; var rt; iw = targetImg.width(); ih = targetImg.height(); divh = parseInt(targetDiv.css('height')); divw = parseInt(targetDiv.css('width')); targetImg.css('height',(ih * (divw/iw)) + 'px'); targetImg.css('margin-left', '0px'); //alert('iwxih=' + iw + 'x' + ih + '\n' + 'divwxdivh=' + divw + 'x' + divh); this.stopAnimation = function stopAnimation() { //$('#alog').remove(); abort = true; } this.toggle = function toggle() { if (abort) { this.resumeAnimation(); } else this.stopAnimation(); } this.initAnimation = function initAnimation() { $('body').prepend('

'); leftInc = -0.1; topInc = -0.1; heightInc = 0.05; targetImg.css('height',((divw/iw) * ih) + 'px'); targetImg.css('margin-left', '0px'); curLeftPx = 0; curTopPx = 0; curHeight = (divw/iw) * ih; ratio = divw/divh; hdir = 0; vdir = 0; mdir = 0; startTime = (new Date()).getTime(); frames = 0; delay = 10; rt = 0; maxmag = ih * (divw/iw) * 2.5; minmag = ih * (divw/iw); abort = false; } this.resumeAnimation = function resumeAnimation() { abort = false; setTimeout(anim,0); } this.startAnimation = function startAnimation() { this.initAnimation(); setTimeout(anim,0); } function anim() { //var imgh = parseInt(targetImg.css("height")); //var imgw = parseInt(targetImg.css("width")); var threshold = 0; var hthresh = 0; var vthresh = 0; var mthresh = 0; // First zoom in... if (0 && curHeightPct < minmag * 100) { heightInc = 0.1; leftInc = 0.1; topInc = 0.1; curHeightPct += heightInc; curLeftPx -= heightInc*ratio; curTopPx -= heightInc*1; targetImg .css('margin-left',curLeftPx + 'px') .css('margin-top',curTopPx + 'px') .css('height',(ih * (curHeightPct/100)) + 'px'); //$('#alog').html('curHeightPct=' + Math.round(curHeightPct) + ' heightInc=' + heightInc + ', frames=' + frames + ', rt=' + rt + ', frameRate=' + Math.round(frameRate) + ', delay=' + Math.round(delay)); } else { var imgh = parseInt(targetImg.css("height")); var imgw = parseInt(targetImg.css("width")); mthresh = ((maxmag - minmag) / 2) + minmag; var distFromThresh = Math.abs(mthresh - imgh); var howClose = distFromThresh / ((maxmag - minmag) / 2); if (howClose >= 1) { if (imgh <= minmag) mdir = 0; else mdir = 1; } var minHeightInc = 0.5; var maxHeightInc = 2.0; heightInc = (((1-Math.abs(howClose)) * (maxHeightInc - minHeightInc)) + minHeightInc) * (mdir ? -1 : 1); curHeight += heightInc; //curLeftPx -= heightInc; //curTopPx -= heightInc/ratio; targetImg.css('height',curHeight + 'px'); var imgh = parseInt(targetImg.css("height")); var imgw = parseInt(targetImg.css("width")); hthresh = ((imgw - divw) / 2) * -1; howClose = Math.abs(((hthresh - curLeftPx) / hthresh)); if (howClose >= 1) { if (curLeftPx >= 0) hdir = 1; else hdir = 0; } // if (imgw + curLeftPx - divw <= 0) hdir = 1; // if (curLeftPx >= 0) hdir = 0; var minLeftInc = 0.1; var maxLeftInc = 4.0; leftInc = (((1-Math.abs(howClose)) * (maxLeftInc - minLeftInc)) + minLeftInc) * (hdir ? 1 : -1); //console.log('(((1-'+ Math.abs(howClose) + ')) * (' + maxLeftInc + ' - ' + minLeftInc + ')) + ' + minLeftInc + ') * ' + (hdir ? 1 : -1) + ' = ' + leftInc); //vthresh = ((imgh - divh) / 2) * -1; //if (imgh + curTopPx - divh <= 0) vdir = 1; //if (curTopPx >= 0) vdir = 0; //howClose = Math.abs(((vthresh - curTopPx) / vthresh)); //var minTopInc = 0.1; //var maxTopInc = 4.0; //topInc = (((1-Math.abs(howClose)) * (maxTopInc - minTopInc)) + minTopInc) * (vdir ? 1 : -1); curLeftPx += leftInc; //curTopPx += topInc; targetImg //.css('height',curHeight + 'px') .css('margin-left',curLeftPx + 'px') .css('margin-top',curTopPx + 'px'); $('#alog').html('xyz inc: ' + Math.round(leftInc*100) + ' ' + Math.round(topInc*100) + ' ' + Math.round(heightInc*100) + ', curLeftPx: ' + curLeftPx + ', hthresh: ' + Math.round(hthresh) + ', howClose: ' + Math.round(howClose*100) ); } frames++; rt = (new Date()).getTime() - startTime; frameRate = (frames*1000)/rt; if (rt > 500) { delay = delay * (frameRate/60); startTime = (new Date()).getTime(); frames = 0; } if (!abort) setTimeout(anim,delay); } return this; } */ function showLoginForm() { $('#usernametext').val(""); $('#passwordtext').val(""); $('#loginloginbtn').attr('disabled', false); $('#logindiv').show("blind", 500, function() { $('#usernametext').focus(); }); } $(document).ready(function() { $('#perf').html(perfstr); $('#endyr').html(yroptionlist); if (rootBlogOptions.indexOf('layoutpitch') >= 0) $('.nopitch').hide(); window.onpopstate = function(ev) { if (ev.state) { $('#articles').html(ev.state); bindLinks(); localize8601Dates(); fixup(); initCalendar(); updateCalendar(); } } $('.altlang').click(function() { var newlang = $(this).attr('data-lang'); var re = new RegExp('/' + lang); var newpathname = window.location.pathname + newlang; if (window.location.pathname !="/") newpathname = window.location.pathname.replace(re,'/' + newlang); window.location = newpathname; }) $('#loginbtn').click(function() { showLoginForm(); $('#loginbtn, #registerbtn').hide(); }); $('#schedbtn').click(function() { $('#logoutbtn, #schedbtn, #addarticlebtn').hide(); $('#scheddiv').show("blind", 500); }); $('#cancelschedbtn').click(function() { $('#logoutbtn, #schedbtn, #addarticlebtn').show(); $('#scheddiv').hide("blind", 500); }); $('#logincancelbtn').click(function() { $('#logindiv').hide("blind", function() { $('#loginbtn, #registerbtn').show(); }); }); $('#registerbtn').click(function() { $('#regfirstname').val(""); $('#reglastname').val(""); $('#regstreet').val(""); $('#regcity').val(""); $('#regstate').val("CA"); $('#regzip').val(""); $('#regphone').val(""); $('#regpassword').val(""); $('#regconfpassword').val(""); $('#regemail').val(""); $('#loginbtn, #registerbtn').hide(); $('#regregisterbtn').attr('disabled', false); $('#registerdiv').show("blind", 500, function() { $('#regfirstname').focus(); }); }); $('#regcancelbtn').click(function() { $('#registerdiv').hide("blind", function() { $('#registerbtn, #loginbtn').show(); }); }); function setInfoline(cb) { screwtopDb().url(DBURL) //.beginServerExecution() .topicById(rootBlogTopicId) .tag(APPNAME + '/subblogs') .values() .topics({elide:true, tagfilter: APPNAME + '/title-' + lang}) .values() .text() //.endServerExecution() .fn(function() { // Remove all but Home $('.infoitem:not(#homebtn)').remove(); }) .each(function(subblog) { if (rootBlogOptions.indexOf("layout3") < 0 && rootBlogOptions.indexOf("layout4") < 0) { $('#infoline').append('
' + subblog + '
'); } else { $('#infoline tr').append(''+subblog+''); } }) .end(function() { $('#settings').html(username); //$('#infoline tr').append('My Info'); if (privs.privconfig) $('#config').show(); $('#loggedinbtns').show(); //$('#infoline tr').append('' + username + ''); if (rootBlogOptions.indexOf("layout2") >= 0) $('.infoitem,.localitem,.userinfoitem').corner("6px"); bindSettings(); bindConfig(); bindMenuLinks(); selectSection(blogTopicTitle); cb(); }); } function showEpi() { return (blogOptions.indexOf("epi") >= 0 && !screwtopDb.isEmpty(username)); } function cookieLogin() { if (cookiesSet()) { $('#loginbtn, #registerbtn').hide(); screwtopDb().url(DBURL) .onError(function(rslt) { alert(rslt.result); deleteCookie(rootBlogTopicId + '-username'); deleteCookie(rootBlogTopicId + '-password'); document.location = 'index'; screwtopDb().url(DBURL).abort().end(); }) .login(APPNAME, getCookie(rootBlogTopicId + '-username'),getCookie(rootBlogTopicId + '-password'), 3600) .authentication(APPNAME, getCookie(rootBlogTopicId + '-username'),getCookie(rootBlogTopicId + '-password')) .push() .attributes('appAttrs') .onError() .fn(function(attrs) { privs = screwtopDb.isEmpty(attrs[0].value) ? {} : JSON.parse(attrs[0].value); }) .pop() .fn(function(data) { username = data[0].username[0]; if (username == RESPONSIBLEUSERNAME) { $('#usernametext').val(getCookie(rootBlogTopicId + '-impersonating')); $('#passwordtext').val(''); $('#loginloginbtn').click(); return; } password = getCookie(rootBlogTopicId + '-password'); $('#prebanner').show(); setInfoline(function() { $('#logoutbtn, .localitem').show(); if (isBlogPoster() && !configActive) { $('#addarticlebtn').show(); //$('#schedbtn, #deleventbtn').show(); //getCategories(); } else { $('#addarticlebtn').hide(); //$('#schedbtn, #deleventbtn').hide(); } setAuthorActions(); //dues(); if (showEpi()) epi.showPersonalSidebar(); onLogin.forEach(function(f) { f(); }); }); }) //.authentication(APPNAME, getCookie(rootBlogTopicId + '-username'),getCookie(rootBlogTopicId + '-password')) .end(); } else if (showLoginDivOnAutoLoginFail) $('#loginbtn').click(); } $('#loginloginbtn').click(function() { $('#loginloginbtn').attr('disabled', true); screwtopDb().url(DBURL) .onError(function(rslt) { if (screwtopDb.isEmpty(rslt.result)) alert('Login error.') else alert(rslt.result); $('#loginloginbtn').attr('disabled', false); screwtopDb().url(DBURL).abort().end(); }) .login(APPNAME, $('#usernametext').val(), $('#passwordtext').val(), 3600) .onError() //.authentication(APPNAME, $('#usernametext').val(), $('#passwordtext').val()) .push() .attributes('appAttrs') .fn(function(attrs) { privs = screwtopDb.isEmpty(attrs[0].value) ? {} : JSON.parse(attrs[0].value); }) .pop() .func(function(obj) { username = obj[0].username[0]; password = $('#passwordtext').val(); if (username == RESPONSIBLEUSERNAME) { var newuser = prompt("Username to impersonate:"); if (screwtopDb.isEmpty(newuser)) { localLogout(); } else { $('#usernametext').val(newuser); $('#passwordtext').val(''); setCookie(rootBlogTopicId + '-impersonating', newuser, 1); setCookie(rootBlogTopicId + '-username', RESPONSIBLEUSERNAME, 7); setCookie(rootBlogTopicId + '-password', password, 7); $('#loginloginbtn').click(); } return; } if (location.pathname == "/register" || location.pathname == "/registrationsuccess") { setCookie(rootBlogTopicId + '-username', username, 7); setCookie(rootBlogTopicId + '-password', password, 7); location = location.protocol + '//' + location.hostname; return; } function loginloginActions() { $('#logindiv').hide('blind'); $('#loginloginbtn').attr('disabled', false); $('#logoutbtn, .localitem').show(); if (isBlogPoster() && !configActive) { $('#addarticlebtn').show(); //$('#schedbtn, #deleventbtn').show(); //getCategories(); } else { $('#addarticlebtn').hide(); //$('#schedbtn, #deleventbtn').hide(); } setAuthorActions(); $('#prebanner').show(); //dues(); if (showEpi()) epi.showPersonalSidebar(); if (getCookie(rootBlogTopicId + '-impersonating') != null) { var html = $('.userinfoitem').html(); html = '' + html + ''; html = html.toUpperCase(); $('.userinfoitem').html(html); $('.userinfoitem').css('background-color','red').css('padding', '3px 10px 2px 10px').css('margin-top', '0px'); } else { setCookie(rootBlogTopicId + '-username', username, 7); setCookie(rootBlogTopicId + '-password', password, 7); } onLogin.forEach(function(f) { f(); }); } setInfoline(function() { setTimeout(loginloginActions, 100); }); }) //.logout() //.authentication(APPNAME, $('#usernametext').val(), $('#passwordtext').val()) .end(); return false; }); $('#logoutbtn').click(function() { epi.performLogoutActions(); screwtopDb().url(DBURL) .logout() .end(localLogout); }); $('#regregisterbtn').click(function() { if ($('#regpassword').val() != $('#regconfpassword').val()) { alert('Password and Confirm Passsword do not match.'); return false; } else if ($.trim($('#regfirstname').val()) == '' || $.trim($('#reglastname').val()) == '' || $.trim($('#regpassword').val()) == '' || $.trim($('#regconfpassword').val()) == '' || $.trim($('#regemail').val()) == '') { alert('Name, password, and email fields are required.'); return false; } else { var newUserObj = { username: $.trim($('#regfirstname').val()) + ' ' + $.trim($('#reglastname').val()), password: $.trim($('#regpassword').val()), email: $('#regemail').val(), firstname: $('#regfirstname').val(), lastname: $('#reglastname').val() }; var street = $('#regstreet').val() var city = $('#regcity').val() var state = $('#regstate').val() var zip = $('#regzip').val() var phone = $('#regphone').val() if (!screwtopDb.isEmpty(street)) newUserObj["street"] = street; if (!screwtopDb.isEmpty(city)) newUserObj["city"] = city; if (!screwtopDb.isEmpty(state)) newUserObj["state"] = state; if (!screwtopDb.isEmpty(zip)) newUserObj["zip"] = zip; if (!screwtopDb.isEmpty(phone)) newUserObj["phone"] = phone; screwtopDb().url(DBURL) .appName(APPNAME) .createUser2(newUserObj) //.createUser( // $('#regusername').val(), // $('#regpassword').val(), // $('#regemail').val(), // APPNAME) .end(function() { $('#loginbtn, #registerbtn').show(); $('#registerdiv').hide('blind'); alert("A confirmation email has been sent to the address you provided."); }); return false; } }); $('#addarticlebtn').click(function() { var dt = addDays(new Date(), 30); $('#newtitle').val(""); $('#priority').val(""); $('#expdate').datepicker('setDate',dt); $('#nosanitizecb').prop("checked",false); $('#newcontentarea').val(""); $('#newcategories').val("").attr('selectBoxOptions',categories); $('#newdate').val(new Date().getISO8601()); $('#newarticle').show("blind", 500, function() { $('#main').hide(); setHtmlArea(); }); $('#startdate').val(''); $('#enddate').val(''); $('#starttime').val(''); $('#endtime').val(''); $('#location').val(''); if (!editableSelectCreated) { createEditableSelect($('#newcategories')[0], 'catSelectBox'); editableSelectCreated = true; $('#catSelectBox').css('float','left'); } bindNewArticleButtons(); }); try { //history.pushState($('#articles').html()); } catch(e) {} bindLinks(); bindMenuLinks(); localize8601Dates(); fixup(); $('#newarticle, #newcomment, #logindiv, #registerdiv').hide(); cookieLogin(); $('#wrapper').fadeIn('slow'); $('#scheduleeventbtn').unbind().click(function() { if ($('#neweventdiv').is(':visible')) $('#neweventdiv').hide('blind',500); else { $('#neweventdiv').show('blind',500); $("#neweventdiv .dp").datepicker(); $("#neweventdiv .tp").timepicker(); $(".testlinkbtn").unbind().click(function() { var win=window.open($(this).prev().val(), '_blank'); win.focus(); }); //$('#evcolorpicker').farbtastic('.evcolor'); //$.farbtastic('#evcolorpicker').setColor('#4488bb'); var bgcolor = '#4488bb'; $('#evcolorpicker').farbtastic('.evcolor'); $.farbtastic('#evcolorpicker').setColor(bgcolor); $.farbtastic('#evcolorpicker').linkTo(function(clr) { bgcolor = clr; $('.evcolor').css('background-color',clr); }); $('.evcolor').click(function() { if ($('#evcolorpicker').is(':visible')) $('#evcolorpicker').hide('blind'); else $('#evcolorpicker').show('blind'); }); $('#eventokbtn').unbind().click(function() { var st = $('#starttime2').timepicker('getTime'); var sd = new Date(Date.parse($('#startdate2').val())); var et = $('#endtime2').timepicker('getTime'); var ed = new Date(Date.parse($('#enddate2').val())); var lnk = $('#eventlink').val().trim(); var loc = $('#location2').val().trim(); var evtitle = $('#eventname').val().trim(); if (screwtopDb.isEmpty(st) || screwtopDb.isEmpty(sd) || screwtopDb.isEmpty(et) || screwtopDb.isEmpty(ed) || screwtopDb.isEmpty(loc) || screwtopDb.isEmpty(evtitle)) { alert("You must fill in all fields."); return; } var startdt = Date.parse(sd.toLocaleDateString() + ' ' + st.toLocaleTimeString()); var enddt = Date.parse(ed.toLocaleDateString() + ' ' + et.toLocaleTimeString()); var dur = (enddt - startdt) / (1000 * 60); if (dur <= 0) { alert("The event end is equal to or earlier than the event start."); return; } if (!validateEventLink(lnk)) { alert("The more info link must be a valid web address."); return; } // function recurEvent(ev, nth, xDay, lastMo, lastYr) { if ($('#evrecur').is(':checked')) { var ev = schedEvent2(startdt, dur, evtitle, loc, lnk, bgcolor).events; var nth = $('#evnth').val(); var xDay = $('#evxday').val(); var endmo = $('#evendmo').val(); var endyr = $('#evendyr').val(); var enddt = new Date(); var stdt = new Date(startdt); enddt.setFullYear(endyr); enddt.setMonth(endmo); if (enddt.getTime()<= stdt.getTime()) { alert("The recurring event's end date is earlier than the event's start date.") return; } // Recurring event showSpinner(); screwtopDb().url(DBURL) .addTopics(recurEvent(ev, nth, xDay, endmo, endyr, bgcolor)) .invalidateCache() .end(function() { $('#neweventcancel').click(); events = null; hideSpinner(); location = '/' + lang + '/calendar'; }); } else { showSpinner(); screwtopDb().url(DBURL) .addTopics(schedEvent2(startdt, dur, evtitle, loc, lnk, bgcolor)) .invalidateCache() .end(function() { $('#neweventcancel').click(); events = null; hideSpinner(); location = '/' + lang + '/calendar'; }); } }); } $('#eventcancelbtn').click(function() { $('#neweventdiv').hide('blind',500); }); $('#evnth,#evxday,#evendmo,#evendyr').change(function() { $('#evrecur').prop('checked', true); }) }); initCalendar(); updateCalendar(); $(".dp").datepicker(); $(".tp").timepicker(); $('#acolorpicker').farbtastic('.acolor'); $.farbtastic('#acolorpicker').setColor(abgcolor); $.farbtastic('#acolorpicker').linkTo(function(clr) { abgcolor = clr; $('.acolor').css('background-color',clr); }); $('.acolor').click(function() { if ($('#acolorpicker').is(':visible')) $('#acolorpicker').hide('blind'); else $('#acolorpicker').show('blind'); }); $('#startdate').change(function() { var dt = new Date(Date.parse($(this).val())); $('#enddate').datepicker('setDate',dt); $('#starttime').timepicker('setTime', dt); }); $('#starttime').change(function() { $('#endtime').timepicker({'minTime': $(this).val(), 'showDuration': true }); $('#endtime').val($(this).val()); }); $('#imagediv').click(function() { if (theAnimator != null) theAnimator.toggle(); }) showhideSidebar(); selectSection(blogTopicTitle); onReady.forEach(function(f) { f(); }); if (rootBlogOptions.indexOf("layout4") >= 0 || rootBlogOptions.indexOf("layout3") >= 0 || rootBlogOptions.indexOf("layout2") >= 0) { $(".rnd, #sidebar, .infoitem, .localitem, .userinfoitem").corner("6px"); } else { $(".rnd, #sidebar").corner("6px"); } processFormDescriptors($('.blogcontent')); //if (rootBlogOptions.indexOf('nologin') >= 0) $('#topsidebar').css('margin-top','-24px'); });