﻿jQuery(document).ready(function() {
    if (typeof (registerCommentVariables) != 'undefined') registerCommentVariables();

    SunBlogNuke.init();
});

// global object
SunBlogNuke = {
    settings: {
        language: '',
        webRoot: '',
        modulePath: '',
        blogid: -1,
        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;
    },

    cancelDigg: function(elem, id, diggType) {
        jQuery(elem).find('.diggtip').html('Cancel...');
        currentDiggType = diggType;
        currentDiggEntryId = id;
        jQuery.ajax({
            type: 'post',
            url: SunBlogNuke.settings.modulePath + "ws/BlogServices.asmx/CancelDigg",
            data: '{postid:' + id + ',diggType:' + diggType + '}',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function(response) {
                response = SunBlogNuke.parseJson(response);
                var diggElem = jQuery('#digg_' + currentDiggEntryId);
                if (response == -1) {
                    location.href = SunBlogNuke.settings.webRoot + "/default.aspx?ctl=login&returnurl=" + location.href;
                } else if (response == 0) {
                    alert('Voting failure, please contact with administrator.');
                } else {
                    if (currentDiggType == 1) {
                        diggElem.find('.diggit span').html(parseInt(diggElem.find('.diggit span').html()) - 1);
                    } else if (currentDiggType == 2) {
                        diggElem.find('.buryit span').html(parseInt(diggElem.find('.buryit span').html()) - 1);
                    }
                    alert('Cancel voting successfully.');
                    jQuery(elem).find('.diggedType').html('0');
                }
            }
        });
    },

    attachDigg: function(elem, id, diggType) {
        var diggedType = jQuery(elem).find('.diggedType').html();
        if (diggedType == 0) {
            jQuery(elem).find('.diggtip').html('Voting...');
            currentDiggType = diggType;
            currentDiggEntryId = id;
            jQuery.ajax({
                type: 'post',
                url: SunBlogNuke.settings.modulePath + "ws/BlogServices.asmx/Digg",
                data: '{postid:' + id + ',diggType:' + diggType + '}',
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function(response) {
                    response = SunBlogNuke.parseJson(response);
                    var diggElem = jQuery('#digg_' + currentDiggEntryId);
                    if (response == -1) {
                        location.href = SunBlogNuke.settings.webRoot + "/default.aspx?ctl=login&returnurl=" + location.href;
                    } else if (response == -2) {
                        diggElem.find('.diggtip').html('Voted');
                    } else if (response == 0) {
                        alert('Vote failure, please contact with administrator.');
                    } else {
                        if (currentDiggType == 1) {
                            diggElem.find('.diggit span').html(parseInt(diggElem.find('.diggit span').html()) + 1);
                        } else if (currentDiggType == 2) {
                            diggElem.find('.buryit span').html(parseInt(diggElem.find('.buryit span').html()) + 1);
                        }
                        if (diggElem.find('.result').length) {
                            diggElem.find('.result').html(parseInt(diggElem.find('.diggit span').html()) - parseInt(diggElem.find('.buryit span').html()));
                        }
                        alert('Thanks for your vote.');
                        diggElem.find('.diggedType').html(currentDiggType);
                    }
                }
            });
        } else if (diggedType == 1) {
            jQuery(elem).find('.diggtip').html('Voted');
        } else if (diggedType == 2) {
            jQuery(elem).find('.diggtip').html('Buried');
        }
    },

    getCapcha: function() {
        jQuery.ajax({
            type: 'post',
            url: SunBlogNuke.settings.modulePath + "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() {
        function verifyReCaptcha() {
            challengeField = jQuery("#recaptcha_challenge_field").val();
            responseField = jQuery("#recaptcha_response_field").val();

            jQuery.ajax({
                type: 'post',
                url: SunBlogNuke.settings.modulePath + "Handlers/VerifyReCAPTCHA.aspx",
                data: "blogkey=" + SunBlogNuke.settings.blogid + "&recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
                cache: false,
                success: function(data) {
                    if (data == 'True') {
                        SunBlogNuke.submitComment();
                    } else {
                        if (typeof Recaptcha.old_finish_reload === 'undefined') {
                            Recaptcha.old_finish_reload = Recaptcha.finish_reload;
                            Recaptcha.finish_reload = function(a, b, c, d) {
                                Recaptcha.old_finish_reload(a, b, c, d);
                                jQuery('recaptcha_widget_div').removeClass('recaptcha_nothad_incorrect_sol');
                                jQuery('recaptcha_widget_div').addClass('recaptcha_had_incorrect_sol');
                            };
                        }

                        var $summaryError = jQuery('.validation-summary-errors').hide().empty();
                        $summaryError.append('<li>' + SunBlogNuke.comment.invalidCaptcha + '</li>');
                        $summaryError.fadeIn('slow');
                    }

                    Recaptcha.reload();
                }
            });
        }

        function verifyCaptCha() {
            var captchaKey = jQuery('input[name=s3capcha]:checked').val();
            jQuery.ajax({
                type: 'post',
                url: SunBlogNuke.settings.modulePath + "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();
                }
            });
        }

        var valid = SunBlogNuke.verifyComment();
        if (valid) {
            if (SunBlogNuke.comment.enableReCaptcha) verifyReCaptcha();
            else if (SunBlogNuke.comment.enableCaptcha) verifyCaptCha();
            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.modulePath + "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');
                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.modulePath + "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.modulePath + 'ws/BlogServices.asmx/ProcessRate', id: postid });
        });

        jQuery("div[id^='digg_']").each(function() {
            var diggElem = jQuery(this);
            var postid = diggElem.attr('id').split('_')[1];
            // 1 - Up, 2 - Down
            diggElem.find('.diggit').click(function() {
                SunBlogNuke.attachDigg(diggElem, postid, 1);
            });
            diggElem.find('.buryit').click(function() {
                SunBlogNuke.attachDigg(diggElem, postid, 2);
            });
        });
    },

    initCommentForm: function() {
        // apply events for submit comment form
        if (jQuery('#anonDetails').length) {
            if (jQuery('#captcha').length && SunBlogNuke.comment.enableCaptcha) {
                SunBlogNuke.getCapcha();
            }

            // 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.modulePath + "images/animated_loading.gif";
        jQuery.facebox.settings.closeImage = SunBlogNuke.settings.modulePath + "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>');
    },

    initWatermark: function() {
        var textVal = SunBlogNuke.settings.searchWatermarkDefaultText;
        jQuery('.searchInput').data('text', textVal).val(textVal).addClass('searchWatermark').focus(function() {
            var $input = jQuery(this);
            if ($input.val() === $input.data('text'))
                $input.val('').removeClass('searchWatermark');
        }).blur(function() {
            var $input = jQuery(this);
            if ($.trim($input.val()) === '')
                $input.val($input.data('text')).addClass('searchWatermark');
        });
    },

    initWidgets: function() {
        // initialize timeago format
        jQuery('abbr.timeago').timeago();
        // search widget
        SunBlogNuke.initWatermark();
        // initialize facebox effect
        SunBlogNuke.initFacebox();
    },

    init: function() {
        this.initPosts();
        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):\/\/|www.){1}(?:(?:[\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; 
