﻿jQuery(document).ready(function() {
    if (typeof (registerCommentVariables) != 'undefined') registerCommentVariables();

    SunBlogNuke.init();
});

// global object
SunBlogNuke = {
    settings: {
        language: '',
        webRoot: '',
        searchWatermarkDefaultText: 'Search Posts'
    },

    post: {
        id: -1,
        publishedWrapper: null,
        title: '',
        permaLink: '',
        encodeTitle: ''
    },

    comment: {
        prefix: '',
        enableCaptcha: false,
        invalidName: '',
        invalidEmail: '',
        invalidWebsite: '',
        invalidComment: '',
        invalidCaptcha: '',
        retrievedWarning: '',
        success: '',
        error: ''
    },

    clt_enter: function(e) {
        if (e.ctrlKey && e.keyCode == 13) {
            SunBlogNuke.postComment();
        }

        return true;
    },

    parseJson: function(msg) {
        // ASP.NET 3.5+
        if (msg && msg.d != undefined)
            return msg.d;
        // ASP.NET 2.0
        else
            return msg;
    },

    reset: function() {
        jQuery('#anonDetails .validation-summary-errors').hide();
        jQuery('#' + SunBlogNuke.comment.prefix + '_txtComment').val('');
    },

    parse: function(s) {
        if (s) return s.replace(/\n/, "<br/>").replace(/&/g, "&amp;").replace(/\"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
        return ""
    },

    buildCommentObject: function() {
        // Initialize the object, before adding data to it.
        //  { } is declarative shorthand for new Object().
        var annotation = {};
        annotation.EntryID = SunBlogNuke.post.id;
        annotation.Author = this.parse(jQuery('#' + SunBlogNuke.comment.prefix + '_txtAuthor').val());
        annotation.Email = encodeURI(jQuery('#' + SunBlogNuke.comment.prefix + '_txtEmail').val());
        annotation.Website = encodeURI(jQuery('#' + SunBlogNuke.comment.prefix + '_txtWebsite').val());
        annotation.Comment = jQuery('#' + SunBlogNuke.comment.prefix + '_txtComment').val();

        return annotation;
    },

    getCapcha: function() {
        jQuery.ajax({
            type: 'post',
            url: SunBlogNuke.settings.webRoot + "ws/BlogServices.asmx/BuildCaptcha",
            data: '{}',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            cache: false,
            success: function(data) {
                // parse the json object
                data = SunBlogNuke.parseJson(data);
                jQuery('#captcha').html(data).s3Capcha();
            }
        });
    },

    postComment: function() {
        var valid = SunBlogNuke.verifyComment();
        if (valid) {
            if (SunBlogNuke.comment.enableCaptcha) {
                var captchaKey = jQuery('input[name=s3capcha]:checked').val();
                jQuery.ajax({
                    type: 'post',
                    url: SunBlogNuke.settings.webRoot + "ws/BlogServices.asmx/VerifyCaptcha",
                    data: '{key:"' + captchaKey + '"}',
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8',
                    cache: false,
                    success: function(data) {
                        // parse the json object
                        data = SunBlogNuke.parseJson(data);
                        if (data === 'Success') {
                            SunBlogNuke.submitComment();
                        } else {
                            var $summaryError = jQuery('.validation-summary-errors').hide().empty();

                            $summaryError.append('<li>' + SunBlogNuke.comment.invalidCaptcha + '</li>');
                            $summaryError.fadeIn('slow');
                        }
                        // refresh capcha
                        SunBlogNuke.getCapcha();
                    }
                });
            } else {
                SunBlogNuke.submitComment();
            }
        }
    },

    submitComment: function() {
        // Create a data transfer object (DTO) with the
        //  proper structure.
        var commentObject = {
            'comment': SunBlogNuke.buildCommentObject(),
            'notify': jQuery('#chkNotification').is(':checked'),
            'rememberMe': jQuery('#chkRememberMe').is(':checked')
        };
        jQuery.ajax({
            type: 'post',
            url: SunBlogNuke.settings.webRoot + "ws/BlogServices.asmx/AddComment",
            data: jQuery.toJSON(commentObject),
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            beforeSend: function() {
                jQuery.facebox(jQuery('#ajaxProgress').html(), 'faceboxProgress');
                jQuery('#facebox .footer').hide();
            },
            success: function(msg) {
                jQuery(document).trigger('close.facebox');
                // parse the json object
                msg = SunBlogNuke.parseJson(msg);
                jQuery(msg).appendTo("#annotations").fadeTo(1000, 1);
                SunBlogNuke.reset();
            },
            error: function(xhr, status, error) {
                jQuery('#facebox .content').removeClass().addClass('content failure').empty().html(SunBlogNuke.comment.error).fadeIn(3000, function() {
                    jQuery('#facebox .footer').show();
                });
            }
        });
    },

    verifyComment: function() {
        var $summaryError = jQuery('.validation-summary-errors').hide().empty();
        if (jQuery.trim(jQuery('#' + SunBlogNuke.comment.prefix + '_txtAuthor').val()).length == 0) {
            $summaryError.append('<li>' + SunBlogNuke.comment.invalidName + '</li>');
        }
        if (jQuery.trim(jQuery('#' + SunBlogNuke.comment.prefix + '_txtEmail').val()).length == 0 ||
        jQuery('#' + SunBlogNuke.comment.prefix + '_txtEmail').val().search(emailRegxp) == -1) {
            $summaryError.append('<li>' + SunBlogNuke.comment.invalidEmail + '</li>');
        }
        if (jQuery.trim(jQuery('#' + SunBlogNuke.comment.prefix + '_txtWebsite').val()) != 'http://' &&
        jQuery.trim(jQuery('#' + SunBlogNuke.comment.prefix + '_txtWebsite').val()).length > 0 &&
        jQuery('#' + SunBlogNuke.comment.prefix + '_txtWebsite').val().search(urlRegxp) == -1) {
            $summaryError.append('<li>' + SunBlogNuke.comment.invalidWebsite + '</li>');
        }
        if (jQuery.trim(jQuery('#' + SunBlogNuke.comment.prefix + '_txtComment').val()).length == 0) {
            $summaryError.append('<li>' + SunBlogNuke.comment.invalidComment + '</li>');
        }

        if (jQuery.trim($summaryError.html()).length > 0) {
            $summaryError.fadeIn('slow');
            return false;
        }

        return true;
    },

    registerFaceboxEvents: function() {
        jQuery(document).bind('afterReveal.facebox', function() {
            jQuery('.faceboxModal #yes').click(function() {
                jQuery.facebox(jQuery('#PopupProgress').html(), 'faceboxProgress');

                jQuery.ajax({
                    type: 'post',
                    url: SunBlogNuke.settings.webRoot + "ws/BlogServices.asmx/PublishEntry",
                    data: "{entryID:" + jQuery('#targetPostId').val() + "}",
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8',
                    success: function(data) {
                        data = SunBlogNuke.parseJson(data);
                        jQuery(document).trigger('close.facebox');
                        if (data === 'Succeed' && SunBlogNuke.post.publishedWrapper != null)
                            SunBlogNuke.post.publishedWrapper.hide();
                    }
                });
            });

            jQuery('.faceboxModal #no').click(function() {
                jQuery(document).trigger('close.facebox');
                return false;
            });
        });
    },

    registerPublishEvent: function() {
        //if (jQuery('.publishEntry').length) {
        // publish entry with click-one feature
        jQuery('.publishEntry').click(function(e) {
            jQuery.facebox(jQuery('#PopupModal').html(), 'faceboxModal');

            // keeps track of the published wrapper
            var wrapper = jQuery(this).parent();
            SunBlogNuke.post.publishedWrapper = wrapper;
            jQuery('#targetPostId').val(wrapper.attr('id').split('_')[1]);

            e.preventDefault();
        });

        this.registerFaceboxEvents();
        //        } else {
        //            $('#publishConfirmWrapper').remove();
        //        }
    },

    changeCommentSize: function(d) {
        var el = jQuery('#' + SunBlogNuke.comment.prefix + '_txtComment');
        var height = el.height();
        height += d;
        if (height > 600) height = 600;
        if (height < 20) height = 20;
        el.height(height);
    },

    initPosts: function() {
        this.registerPublishEvent();
        jQuery("div[id^='rating_']").each(function() {
            var postid = jQuery(this).attr('id').split('_')[1];
            jQuery(this).rater({ postHref: SunBlogNuke.settings.webRoot + 'ws/BlogServices.asmx/ProcessRate', id: postid });
        });
    },

    initComments: function() {
        if (jQuery('#annotations').length) {
            // build comments for current post
            jQuery.ajax({
                type: 'post',
                url: SunBlogNuke.settings.webRoot + "ws/BlogServices.asmx/BuildComment",
                data: '{entryID:' + SunBlogNuke.post.id + '}', //jQuery.toJSON(entryMetadata),
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                beforeSend: function() {
                    jQuery('#annotations').empty().append(jQuery('#ajaxProgress').html()).addClass('ajaxProgress');
                },
                success: function(msg) {
                    msg = SunBlogNuke.parseJson(msg);
                    if (msg === '')
                        jQuery('#annotations').removeAttr('class').empty();
                    else
                        jQuery('#annotations').removeAttr('class').html(msg).slideDown('slow');
                },
                error: function(xhr, status, error) {
                    jQuery('#annotations').removeAttr('class').empty().html(SunBlogNuke.comment.retrievedWarning).addClass('warning');
                }
            });
        }
    },

    initCommentForm: function() {
        // apply events for submit comment form
        if (jQuery('#anonDetails').length) {
            if (jQuery('#captcha').length && SunBlogNuke.comment.enableCaptcha) {
                SunBlogNuke.getCapcha();
            } else {
                jQuery('#captcha').remove();
            }

            // Submit the new comment with ajax call websevice
            jQuery('#btnSubmitComment').click(function(e) {
                SunBlogNuke.postComment();
                e.preventDefault();
            });
            // Deal with the shortcut submit way(Ctrl+ Enter)
            jQuery('#' + SunBlogNuke.comment.prefix + '_txtComment').bind('keydown', SunBlogNuke.clt_enter);
        }
    },

    initFacebox: function() {
        // initialize some facebox plugin setting
        jQuery.facebox.settings.opacity = 0.3;
        jQuery.facebox.settings.loadingImage = SunBlogNuke.settings.webRoot + "images/animated_loading.gif";
        jQuery.facebox.settings.closeImage = SunBlogNuke.settings.webRoot + "images/closelabel.gif";

        // initialize popup facebox utility
        var faceboxes = jQuery('a[rel*=facebox]').facebox().hover(function() {
            $(this).children("span").fadeIn(600);
        }, function() {
            $(this).children("span").fadeOut(200);
        });
        // initialize popup zoom with facebox effect
        jQuery('a[rel*=facebox] img').before('<span class="faceboxZoom"></span>');
    },

    initWidgets: function() {
        // initialize timeago format
        //jQuery('abbr.timeago').timeago();

        // tagCloud widget
        if (jQuery('ul.tagcloud li').length)
            jQuery('ul.tagcloud li').ahover({ toggleEffect: 'height', moveSpeed: 75, toggleSpeed: 250 });

        // search widget
        jQuery('.searchInput').watermark({ defaultText: SunBlogNuke.settings.searchWatermarkDefaultText, watermarkCss: 'searchWatermark' });

        SunBlogNuke.initFacebox();
    },

    init: function() {
        this.initPosts();
        this.initComments();
        this.initCommentForm();
        this.initWidgets();
    }
};

var emailRegxp = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
var urlRegxp = /^(?:https?|s?ftp|telnet|ssh|scp):\/\/(?:(?:[\w]+:)?\w+@)?(?:(?:(?:[\w-]+\.)*\w[\w-]{0,66}\.(?:[a-z]{2,6})(?:\.[a-z]{2})?)|(?:(?:25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})))(?:\:\d{1,5})?(?:\/(~[\w-_.])?)?(?:(?:\/[\w-_.]*)*)?\??(?:(?:[\w-_.]+\=[\w-_.]+&?)*)?$/i; 
