PageRenderTime 53ms CodeModel.GetById 2ms app.highlight 44ms RepoModel.GetById 1ms app.codeStats 0ms

/BlogEngine/BlogEngine.NET/Scripts/blog.js

#
JavaScript | 613 lines | 507 code | 71 blank | 35 comment | 123 complexity | f417147fe16bddab272866e71c014a95 MD5 | raw file
  1// global object
  2BlogEngine = {
  3    $: function (id) {
  4        return document.getElementById(id);
  5    }
  6	,
  7    webRoot: '',
  8    applicationWebRoot: '',
  9    blogInstanceId: '',
 10    // internationalization (injected into the <head> by BlogBasePage)
 11    i18n: {
 12        hasRated: '',
 13        savingTheComment: '',
 14        comments: '',
 15        commentWasSaved: '',
 16        commentWaitingModeration: '',
 17        cancel: '',
 18        filter: '',
 19        apmlDescription: '',
 20        beTheFirstToRate: '',
 21        currentlyRated: '',
 22        ratingHasBeenRegistered: '',
 23        rateThisXStars: ''
 24    }
 25	,
 26    setFlag: function (iso) {
 27        if (iso.length > 0)
 28            BlogEngine.comments.flagImage.src = BlogEngine.webRoot + "pics/flags/" + iso + ".png";
 29        else
 30            BlogEngine.comments.flagImage.src = BlogEngine.webRoot + "pics/pixel.gif";
 31    }
 32	,
 33
 34    // Shows the preview of the comment
 35    showCommentPreview: function () {
 36        var oPreview = this.$('preview');
 37        var oCompose = this.$('compose');
 38
 39        if (oPreview) oPreview.className = 'selected';
 40        if (oCompose) oCompose.className = '';
 41        this.$('commentCompose').style.display = 'none';
 42        this.$('commentPreview').style.display = 'block';
 43        this.$('commentPreview').innerHTML = '<img src="' + BlogEngine.webRoot + 'pics/ajax-loader.gif" alt="Loading" />';
 44        var argument = this.$('commentPreview').innerHTML;
 45        this.addComment(true);
 46    }
 47	,
 48    composeComment: function () {
 49        var oPreview = this.$('preview');
 50        var oCompose = this.$('compose');
 51
 52        if (oPreview) oPreview.className = '';
 53        if (oCompose) oCompose.className = 'selected';
 54        this.$('commentPreview').style.display = 'none';
 55        this.$('commentCompose').style.display = 'block';
 56    }
 57	,
 58    endShowPreview: function (arg, context) {
 59        BlogEngine.$('commentPreview').innerHTML = arg;
 60    }
 61	,
 62    toggleCommentSavingIndicators: function (bSaving) {
 63        BlogEngine.$("btnSaveAjax").disabled = bSaving;
 64        BlogEngine.$("ajaxLoader").style.display = bSaving ? "inline" : "none";
 65        BlogEngine.$("status").className = "";
 66        BlogEngine.$("status").innerHTML = "";
 67        if (!bSaving) {
 68            BlogEngine.$('commentPreview').innerHTML = "";
 69            BlogEngine.composeComment();
 70        }
 71    }
 72    ,
 73    onCommentError: function (error, context) {
 74        BlogEngine.toggleCommentSavingIndicators(false);
 75        error = error || "Unknown error occurred.";
 76        var iDelimiterPos = error.indexOf("|");
 77        if (iDelimiterPos > 0) {
 78            error = error.substr(0, iDelimiterPos);
 79            // Remove numbers from end of error message.
 80            while (error.length > 0 && error.substr(error.length - 1, 1).match(/\d/)) {
 81                error = error.substr(0, error.length - 1);
 82            }
 83        }
 84
 85        if (document.getElementById('recaptcha_response_field')) {
 86            Recaptcha.reload();
 87        }
 88        if (document.getElementById("spnSimpleCaptchaIncorrect")) document.getElementById("spnSimpleCaptchaIncorrect").style.display = "none";
 89
 90        alert("Sorry, the following error occurred while processing your comment:\n\n" + error);
 91    }
 92	,
 93    addComment: function (preview) {
 94        var isPreview = preview == true;
 95        if (!isPreview) {
 96            BlogEngine.toggleCommentSavingIndicators(true);
 97            this.$("status").innerHTML = BlogEngine.i18n.savingTheComment;
 98        }
 99
100        var author = BlogEngine.comments.nameBox.value;
101        var email = BlogEngine.comments.emailBox.value;
102        var content = BlogEngine.comments.contentBox.value;
103        var captcha = BlogEngine.comments.captchaField.value;
104
105        var website = BlogEngine.comments.websiteBox ? BlogEngine.comments.websiteBox.value : "";
106        var country = BlogEngine.comments.countryDropDown ? BlogEngine.comments.countryDropDown.value : "";
107        var notify = BlogEngine.$("cbNotify") ? BlogEngine.$("cbNotify").checked : false;
108        var replyToId = BlogEngine.comments.replyToId ? BlogEngine.comments.replyToId.value : "";
109                
110        var recaptchaResponseField = document.getElementById('recaptcha_response_field');
111        var recaptchaResponse = recaptchaResponseField ? recaptchaResponseField.value : "";
112
113        var recaptchaChallengeField = document.getElementById('recaptcha_challenge_field');
114        var recaptchaChallenge = recaptchaChallengeField ? recaptchaChallengeField.value : "";
115
116        var simpleCaptchaChallengeField = document.getElementById('simpleCaptchaValue');
117        var simpleCaptchaChallenge = simpleCaptchaChallengeField ? simpleCaptchaChallengeField.value : "";
118
119        var avatarInput = BlogEngine.$("avatarImgSrc");
120        var avatar = (avatarInput && avatarInput.value) ? avatarInput.value : "";
121
122        var callback = isPreview ? BlogEngine.endShowPreview : BlogEngine.appendComment;
123        var argument = author + "-|-" + email + "-|-" + website + "-|-" + country + "-|-" + content + "-|-" + notify + "-|-" + isPreview + "-|-" + captcha + "-|-" + replyToId + "-|-" + avatar + "-|-" + recaptchaResponse + "-|-" + recaptchaChallenge + "-|-" + simpleCaptchaChallenge;
124
125        WebForm_DoCallback(BlogEngine.comments.controlId, argument, callback, 'comment', BlogEngine.onCommentError, false);
126
127        if (!isPreview && typeof (OnComment) != "undefined")
128            OnComment(author, email, website, country, content);
129    }
130    ,
131    cancelReply: function () {
132        this.replyToComment('');
133    }
134	,
135    replyToComment: function (id) {
136
137        // set hidden value
138        BlogEngine.comments.replyToId.value = id;
139
140        // move comment form into position
141        var commentForm = BlogEngine.$('comment-form');
142        if (!id || id == '' || id == null || id == '00000000-0000-0000-0000-000000000000') {
143            // move to after comment list
144            var base = BlogEngine.$("commentlist");
145            base.appendChild(commentForm);
146            // hide cancel button
147            BlogEngine.$('cancelReply').style.display = 'none';
148        } else {
149            // show cancel
150            BlogEngine.$('cancelReply').style.display = '';
151
152            // move to nested position
153            var parentComment = BlogEngine.$('id_' + id);
154            var replies = BlogEngine.$('replies_' + id);
155
156            // add if necessary
157            if (replies == null) {
158                replies = document.createElement('div');
159                replies.className = 'comment-replies';
160                replies.id = 'replies_' + id;
161                parentComment.appendChild(replies);
162            }
163            replies.style.display = '';
164            replies.appendChild(commentForm);
165        }
166
167        BlogEngine.comments.nameBox.focus();
168    }
169	,
170    appendComment: function (args, context) {
171        if (context == "comment") {
172
173            if (document.getElementById('recaptcha_response_field')) {
174                Recaptcha.reload();
175            }
176            if (document.getElementById("spnSimpleCaptchaIncorrect")) document.getElementById("spnSimpleCaptchaIncorrect").style.display = "none";
177
178            if (args == "RecaptchaIncorrect" || args == "SimpleCaptchaIncorrect") {
179                if (document.getElementById("spnCaptchaIncorrect")) document.getElementById("spnCaptchaIncorrect").style.display = "";
180                if (document.getElementById("spnSimpleCaptchaIncorrect")) document.getElementById("spnSimpleCaptchaIncorrect").style.display = "";
181                BlogEngine.toggleCommentSavingIndicators(false);
182            }
183            else {
184
185
186                if (document.getElementById("spnCaptchaIncorrect")) document.getElementById("spnCaptchaIncorrect").style.display = "none";
187                if (document.getElementById("spnSimpleCaptchaIncorrect")) document.getElementById("spnSimpleCaptchaIncorrect").style.display = "none";
188
189                var commentList = BlogEngine.$("commentlist");
190                if (commentList.innerHTML.length < 10)
191                    commentList.innerHTML = "<h1 id='comment'>" + BlogEngine.i18n.comments + "</h1>"
192
193                // add comment html to the right place
194                var id = BlogEngine.comments.replyToId ? BlogEngine.comments.replyToId.value : '';
195
196                if (id != '') {
197                    var replies = BlogEngine.$('replies_' + id);
198                    replies.innerHTML += args;
199                } else {
200                    commentList.innerHTML += args;
201                    commentList.style.display = 'block';
202                }
203
204                // reset form values
205                BlogEngine.comments.contentBox.value = "";
206                BlogEngine.comments.contentBox = BlogEngine.$(BlogEngine.comments.contentBox.id);
207                BlogEngine.toggleCommentSavingIndicators(false);
208                BlogEngine.$("status").className = "success";
209
210                if (!BlogEngine.comments.moderation)
211                    BlogEngine.$("status").innerHTML = BlogEngine.i18n.commentWasSaved;
212                else
213                    BlogEngine.$("status").innerHTML = BlogEngine.i18n.commentWaitingModeration;
214
215                // move form back to bottom
216                var commentForm = BlogEngine.$('comment-form');
217                commentList.appendChild(commentForm);
218                // reset reply to
219                if (BlogEngine.comments.replyToId) BlogEngine.comments.replyToId.value = '';
220                if (BlogEngine.$('cancelReply')) BlogEngine.$('cancelReply').style.display = 'none';
221
222            }
223        }
224
225        BlogEngine.$("btnSaveAjax").disabled = false;
226    }
227	,
228    validateAndSubmitCommentForm: function () {
229        var bBuiltInValidationPasses = Page_ClientValidate('AddComment');
230        var bNameIsValid = BlogEngine.comments.nameBox.value.length > 0;
231        document.getElementById('spnNameRequired').style.display = bNameIsValid ? 'none' : '';
232        var bAuthorNameIsValid = true;
233        if (BlogEngine.comments.checkName) {
234            var author = BlogEngine.comments.postAuthor;
235            var visitor = BlogEngine.comments.nameBox.value;
236            bAuthorNameIsValid = !this.equal(author, visitor);
237        }
238        document.getElementById('spnChooseOtherName').style.display = bAuthorNameIsValid ? 'none' : '';
239        if (bBuiltInValidationPasses && bNameIsValid && bAuthorNameIsValid) {
240            BlogEngine.addComment();
241            return true;
242        }
243        return false;
244    }
245
246	 ,
247
248    addBbCode: function (v) {
249        try {
250            var contentBox = BlogEngine.comments.contentBox;
251            if (contentBox.selectionStart) // firefox
252            {
253                var pretxt = contentBox.value.substring(0, contentBox.selectionStart);
254                var therest = contentBox.value.substr(contentBox.selectionEnd);
255                var sel = contentBox.value.substring(contentBox.selectionStart, contentBox.selectionEnd);
256                contentBox.value = pretxt + "[" + v + "]" + sel + "[/" + v + "]" + therest;
257                contentBox.focus();
258            }
259            else if (document.selection && document.selection.createRange) // IE
260            {
261                var str = document.selection.createRange().text;
262                contentBox.focus();
263                var sel = document.selection.createRange();
264                sel.text = "[" + v + "]" + str + "[/" + v + "]";
265            }
266        }
267        catch (ex) { }
268
269        return;
270    }
271	,
272    // Searches the blog based on the entered text and
273    // searches comments as well if chosen.
274    search: function (root) {
275        var input = this.$("searchfield");
276        var check = this.$("searchcomments");
277
278        var search = "search.aspx?q=" + encodeURIComponent(input.value);
279        if (check != null && check.checked)
280            search += "&comment=true";
281
282        top.location.href = root + search;
283
284        return false;
285    }
286	,
287    // Clears the search fields on focus.
288    searchClear: function (defaultText) {
289        var input = this.$("searchfield");
290        if (input.value == defaultText)
291            input.value = "";
292        else if (input.value == "")
293            input.value = defaultText;
294    }
295	,
296    rate: function (id, rating) {
297        this.createCallback("rating.axd?id=" + id + "&rating=" + rating, BlogEngine.ratingCallback);
298    }
299	,
300    ratingCallback: function (response) {
301        var rating = response.substring(0, 1);
302        var status = response.substring(1);
303
304        if (status == "OK") {
305            if (typeof OnRating != "undefined")
306                OnRating(rating);
307
308            alert(BlogEngine.i18n.ratingHasBeenRegistered);
309        }
310        else if (status == "HASRATED") {
311            alert(BlogEngine.i18n.hasRated);
312        }
313        else {
314            alert("An error occured while registering your rating. Please try again");
315        }
316    }
317	,
318    /// <summary>
319    /// Creates a client callback back to the requesting page
320    /// and calls the callback method with the response as parameter.
321    /// </summary>
322    createCallback: function (url, callback) {
323        var http = BlogEngine.getHttpObject();
324        http.open("GET", url, true);
325
326        http.onreadystatechange = function () {
327            if (http.readyState == 4) {
328                if (http.responseText.length > 0 && callback != null)
329                    callback(http.responseText);
330            }
331        };
332
333        http.send(null);
334    }
335	,
336    /// <summary>
337    /// Creates a XmlHttpRequest object.
338    /// </summary>
339    getHttpObject: function () {
340        if (typeof XMLHttpRequest != 'undefined')
341            return new XMLHttpRequest();
342
343        try {
344            return new ActiveXObject("Msxml2.XMLHTTP");
345        }
346        catch (e) {
347            try {
348                return new ActiveXObject("Microsoft.XMLHTTP");
349            }
350            catch (e) { }
351        }
352
353        return false;
354    }
355	,
356    // Updates the calendar from client-callback
357    updateCalendar: function (args, context) {
358        var cal = BlogEngine.$('calendarContainer');
359        cal.innerHTML = args;
360        BlogEngine.Calendar.months[context] = args;
361    }
362	,
363    toggleMonth: function (year) {
364        var monthList = BlogEngine.$("monthList");
365        var years = monthList.getElementsByTagName("ul");
366        for (i = 0; i < years.length; i++) {
367            if (years[i].id == year) {
368                var state = years[i].className == "open" ? "" : "open";
369                years[i].className = state;
370                break;
371            }
372        }
373    }
374	,
375    // Adds a trim method to all strings.
376    equal: function (first, second) {
377        var f = first.toLowerCase().replace(new RegExp(' ', 'gi'), '');
378        var s = second.toLowerCase().replace(new RegExp(' ', 'gi'), '');
379        return f == s;
380    }
381	,
382    /*-----------------------------------------------------------------------------
383    XFN HIGHLIGHTER
384    -----------------------------------------------------------------------------*/
385    xfnRelationships: ['friend', 'acquaintance', 'contact', 'met'
386										, 'co-worker', 'colleague', 'co-resident'
387										, 'neighbor', 'child', 'parent', 'sibling'
388										, 'spouse', 'kin', 'muse', 'crush', 'date'
389										, 'sweetheart', 'me']
390	,
391    // Applies the XFN tags of a link to the title tag
392    hightLightXfn: function () {
393        var content = BlogEngine.$('content');
394        if (content == null)
395            return;
396
397        var links = content.getElementsByTagName('a');
398        for (i = 0; i < links.length; i++) {
399            var link = links[i];
400            var rel = link.getAttribute('rel');
401            if (rel && rel != "nofollow") {
402                for (j = 0; j < BlogEngine.xfnRelationships.length; j++) {
403                    if (rel.indexOf(BlogEngine.xfnRelationships[j]) > -1) {
404                        link.title = 'XFN relationship: ' + rel;
405                        break;
406                    }
407                }
408            }
409        }
410    }
411	,
412
413    showRating: function (container, id, raters, rating) {
414        var div = document.createElement('div');
415        div.className = 'rating';
416
417        var p = document.createElement('p');
418        div.appendChild(p);
419        if (raters == 0) {
420            p.innerHTML = BlogEngine.i18n.beTheFirstToRate;
421        }
422        else {
423            p.innerHTML = BlogEngine.i18n.currentlyRated.replace('{0}', new Number(rating).toFixed(1)).replace('{1}', raters);
424        }
425
426        var ul = document.createElement('ul');
427        ul.className = 'star-rating small-star';
428        div.appendChild(ul);
429
430        var li = document.createElement('li');
431        li.className = 'current-rating';
432        li.style.width = Math.round(rating * 20) + '%';
433        li.innerHTML = 'Currently ' + rating + '/5 Stars.';
434        ul.appendChild(li);
435
436        for (var i = 1; i <= 5; i++) {
437            var l = document.createElement('li');
438            var a = document.createElement('a');
439            a.innerHTML = i;
440            a.href = 'rate/' + i;
441            a.className = this.englishNumber(i);
442            a.title = BlogEngine.i18n.rateThisXStars.replace('{0}', i.toString()).replace('{1}', i == 1 ? '' : 's');
443            a.onclick = function () {
444                BlogEngine.rate(id, this.innerHTML);
445                return false;
446            };
447
448            l.appendChild(a);
449            ul.appendChild(l);
450        }
451
452        container.innerHTML = '';
453        container.appendChild(div);
454        container.style.visibility = 'visible';
455    }
456	,
457
458    applyRatings: function () {
459        var divs = document.getElementsByTagName('div');
460        for (var i = 0; i < divs.length; i++) {
461            if (divs[i].className == 'ratingcontainer') {
462                var args = divs[i].innerHTML.split('|');
463                BlogEngine.showRating(divs[i], args[0], args[1], args[2]);
464            }
465        }
466    },
467
468    englishNumber: function (number) {
469        if (number == 1)
470            return 'one-star';
471
472        if (number == 2)
473            return 'two-stars';
474
475        if (number == 3)
476            return 'three-stars';
477
478        if (number == 4)
479            return 'four-stars';
480
481        return 'five-stars';
482    }
483	,
484    // Adds event to window.onload without overwriting currently assigned onload functions.
485    // Function found at Simon Willison's weblog - http://simon.incutio.com/
486    addLoadEvent: function (func) {
487        var oldonload = window.onload;
488        if (typeof window.onload != 'function') {
489            window.onload = func;
490        }
491        else {
492            window.onload = function () {
493                oldonload();
494                func();
495            }
496        }
497    }
498	,
499    filterByAPML: function () {
500        var width = document.documentElement.clientWidth + document.documentElement.scrollLeft;
501        var height = document.documentElement.clientHeight + document.documentElement.scrollTop;
502        document.body.style.position = 'static';
503
504        var layer = document.createElement('div');
505        layer.style.zIndex = 2;
506        layer.id = 'layer';
507        layer.style.position = 'absolute';
508        layer.style.top = '0px';
509        layer.style.left = '0px';
510        layer.style.height = document.documentElement.scrollHeight + 'px';
511        layer.style.width = width + 'px';
512        layer.style.backgroundColor = 'black';
513        layer.style.opacity = '.6';
514        layer.style.filter += ("progid:DXImageTransform.Microsoft.Alpha(opacity=60)");
515        document.body.appendChild(layer);
516
517        var div = document.createElement('div');
518        div.style.zIndex = 3;
519        div.id = 'apmlfilter';
520        div.style.position = (navigator.userAgent.indexOf('MSIE 6') > -1) ? 'absolute' : 'fixed';
521        div.style.top = '200px';
522        div.style.left = (width / 2) - (400 / 2) + 'px';
523        div.style.height = '50px';
524        div.style.width = '400px';
525        div.style.backgroundColor = 'white';
526        div.style.border = '2px solid silver';
527        div.style.padding = '20px';
528        document.body.appendChild(div);
529
530        var p = document.createElement('p');
531        p.innerHTML = BlogEngine.i18n.apmlDescription;
532        p.style.margin = '0px';
533        div.appendChild(p);
534
535        var form = document.createElement('form');
536        form.method = 'get';
537        form.style.display = 'inline';
538        form.action = BlogEngine.webRoot;
539        div.appendChild(form);
540
541        var textbox = document.createElement('input');
542        textbox.type = 'text';
543        textbox.value = BlogEngine.getCookieValue('url') || 'http://';
544        textbox.style.width = '320px';
545        textbox.id = 'txtapml';
546        textbox.name = 'apml';
547        textbox.style.background = 'url(' + BlogEngine.webRoot + 'pics/apml.png) no-repeat 2px center';
548        textbox.style.paddingLeft = '16px';
549        form.appendChild(textbox);
550        textbox.focus();
551
552        var button = document.createElement('input');
553        button.type = 'submit';
554        button.value = BlogEngine.i18n.filter;
555        button.onclick = function () { location.href = BlogEngine.webRoot + '?apml=' + encodeURIComponent(BlogEngine.$('txtapml').value) };
556        form.appendChild(button);
557
558        var br = document.createElement('br');
559        div.appendChild(br);
560
561        var a = document.createElement('a');
562        a.innerHTML = BlogEngine.i18n.cancel;
563        a.href = 'javascript:void(0)';
564        a.onclick = function () { document.body.removeChild(BlogEngine.$('layer')); document.body.removeChild(BlogEngine.$('apmlfilter')); document.body.style.position = ''; };
565        div.appendChild(a);
566    }
567	,
568    getCookieValue: function (name) {
569        var cookie = new String(document.cookie);
570
571        if (cookie != null && cookie.indexOf('comment=') > -1) {
572            var start = cookie.indexOf(name + '=') + name.length + 1;
573            var end = cookie.indexOf('&', start);
574            if (end > start && start > -1)
575                return cookie.substring(start, end);
576        }
577
578        return null;
579    }
580    ,
581    test: function () {
582        alert('test');
583    }
584	,
585    comments: {
586        flagImage: null,
587        contentBox: null,
588        moderation: null,
589        checkName: null,
590        postAuthor: null,
591        nameBox: null,
592        emailBox: null,
593        websiteBox: null,
594        countryDropDown: null,
595        captchaField: null,
596        controlId: null,
597        replyToId: null
598    }
599};
600
601BlogEngine.addLoadEvent(BlogEngine.hightLightXfn);
602
603// add this to global if it doesn't exist yet
604if (typeof ($) == 'undefined')
605    window.$ = BlogEngine.$;
606
607if (typeof (registerCommentBox) != 'undefined')
608    BlogEngine.addLoadEvent(registerCommentBox);
609if (typeof (setupBlogEngineCalendar) != 'undefined')
610    BlogEngine.addLoadEvent(setupBlogEngineCalendar);
611
612// apply ratings after registerVariables.
613BlogEngine.addLoadEvent(BlogEngine.applyRatings);