﻿//  keeps track of the publish div
var _source;

function showConfirm(EntryID, source) {
    _source = $get(source);
    _EntryID = EntryID;
}

jQuery(document).ready(function() {
    // initialize some facebox plugin setting
    jQuery.facebox.settings.opacity = 0.3;
    jQuery.facebox.settings.loadingImage = jQueryBasicPath + "/images/animated_loading.gif";
    jQuery.facebox.settings.closeImage = jQueryBasicPath + "/images/closelabel.gif";

    // initialize popup facebox utility
    var faceboxes = jQuery('a[rel*=facebox]');
    faceboxes.facebox();
    jQuery('a[rel*=facebox] img').before('<span class="faceboxZoom"></span>'); 
    faceboxes.hover(function() {
        $(this).children("span").fadeIn(600);
    }, function() {
        $(this).children("span").fadeOut(200);
    });

    if (jQuery('#PublishedWrapper').length) {
        // publish entry with click-one feature
        jQuery('.publishEntry').click(function() {
            jQuery.facebox(jQuery('#PopupModal').html(), 'faceboxModal');
        });
        jQuery(document).bind('afterReveal.facebox', function() {
        jQuery('.operation .vividButton2').click(function() {
                jQuery.facebox(jQuery('#PopupProgress').html(), 'faceboxProgress');

                jQuery.ajax({
                    type: "POST",
                    url: jQueryBasicPath + "BlogServices.asmx/PublishEntry",
                    data: "{entryID:" + _EntryID + "}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                        msg = parseJson(msg);
                        jQuery(document).trigger('close.facebox');
                        if (msg === 'Succeed') {
                            _source.style.display = 'none';
                        }
                    }
                });
            });

            jQuery('.operation .vividButton1').click(function() {
                jQuery(document).trigger('close.facebox');
                return false;
            });
        });
    }

    // tagCloud widget jscript
    if (jQuery('ul.tagcloud li').length > 0) jQuery('ul.tagcloud li').ahover({ toggleEffect: 'height', moveSpeed: 75, toggleSpeed: 250 });

    // searchForm widget jscript
    jQuery('.searchInput').watermark({ defaultText: 'Search Entries', watermarkCss: 'searchWatermark' });

    if (jQuery('#rating').length > 0) {
        jQuery('#rating').rater({ postHref: jQueryBasicPath + 'BlogServices.asmx/ProcessRate', id: entryMetadata.entryID });
    }

    // build comments for current post
    jQuery('#annotations').empty().append(jQuery('#ajaxProgress').html()).addClass('ajaxProgress');
    if (jQuery('#annotations').length > 0) {
        jQuery.ajax({
            type: "POST",
            url: jQueryBasicPath + "BlogServices.asmx/BuildComment",
            data: '{entryID:' + entryMetadata.entryID + '}', //jQuery.toJSON(entryMetadata),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function() {
                jQuery('#annotations').empty().append(jQuery('#ajaxProgress').html()).addClass('ajaxProgress');
            },
            success: function(msg) {
                msg = parseJson(msg);
                if (msg === '')
                    jQuery('#annotations').removeAttr('class').empty();
                else {
                    jQuery('#annotations').removeAttr('class').html(msg).slideDown('slow');
                    //var avatar = jQuery('#annotations .avatar');
                    //if (avatar.length && !avatar.children().length) avatar.remove();
                }
            },
            error: function(xhr, status, error) {
                jQuery('#annotations').removeAttr('class').empty().html(warningRetrievingComments).addClass('warning');
            }
        });
    }

    // apply events for submit comment form
    if (jQuery('#anonDetails').length) {
        if (jQuery('#captcha').length && enableCaptcha) {
            getCapcha();
        } else {
            jQuery('#captcha').remove();
        }

        // Submit the new comment with ajax call websevice
        jQuery('#btnSubmitComment').click(function(e) {
            postComment();
            e.preventDefault();
        });
        // Deal with the shortcut submit way(Ctrl+ Enter)
        jQuery('#' + prefix + '_txtComment').bind('keydown', clt_enter);

    }
});

function changeCommentSize(d) {
    var el = jQuery('#' + prefix + '_txtComment');
    var height = el.height();
    height += d;
    if (height > 600) height = 600;
    if (height < 20) height = 20;
    el.height(height);
}

function clt_enter(e) {
    if (e.ctrlKey && e.keyCode == 13) {
        postComment();
    }

    return true;
}

function postComment() {
    var valid = verifyComment();
    if (valid) {
        if (enableCaptcha) {
            var captchaKey = jQuery('input[name=s3capcha]:checked').val();
            jQuery.ajax({
                type: 'POST',
                url: jQueryBasicPath + "BlogServices.asmx/VerifyCaptcha",
                data: '{key:"' + captchaKey + '"}',
                cache: false,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) {
                    // parse the json object
                    data = parseJson(data);
                    getCapcha();
                    if (data === 'Success') {
                        submitComment();
                    } else {
                        var $summaryError = jQuery('.validation-summary-errors').hide().empty();

                        $summaryError.append('<li>' + invalidCaptcha + '</li>');
                        $summaryError.fadeIn('slow');
                    }
                }
            });
        } else {
            submitComment();
        }
    }
}

function submitComment() {
    // Create a data transfer object (DTO) with the
    //  proper structure.
    var DTO = {
        'comment': initComment(),
        'notify': jQuery('#chkNotification').is(':checked'),
        'rememberMe': jQuery('#chkRememberMe').is(':checked')
    };
    jQuery.ajax({
        type: "POST",
        url: jQueryBasicPath + "BlogServices.asmx/AddComment",
        data: jQuery.toJSON(DTO),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        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 = parseJson(msg);
            reset();
            jQuery(msg).appendTo("#annotations").fadeTo(1000, 1);
        },
        error: function(xhr, status, error) {
            jQuery('#facebox .content').removeClass().addClass('content failure').empty().html(addCommentWithError).fadeIn(3000, function() {
                jQuery('#facebox .footer').show();
            });
        }
    });
}

var getCapcha = function() {
    jQuery.ajax({
        type: "POST",
        url: jQueryBasicPath + "BlogServices.asmx/BuildCaptcha",
        data: '{}',
        cache: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            // parse the json object
            data = parseJson(data);
            jQuery('#captcha').html(data).s3Capcha();
        }
    });
};

function parseJson(msg) {
    // ASP.NET 3.5+
    if (msg && msg.d != undefined)
        return msg.d;
    // ASP.NET 2.0
    else
        return msg;
}

function verifyComment() {
    var $summaryError = jQuery('.validation-summary-errors').hide().empty();
    if (jQuery.trim(jQuery('#' + prefix + '_txtAuthor').val()).length == 0) {
        $summaryError.append('<li>' + invalidName + '</li>');
    }
    if (jQuery.trim(jQuery('#' + prefix + '_txtEmail').val()).length == 0 ||
        jQuery('#' + prefix + '_txtEmail').val().search(emailRegxp) == -1) {
        $summaryError.append('<li>' + invalidEmail + '</li>');
    }
    if (jQuery.trim(jQuery('#' + prefix + '_txtWebsite').val()) != 'http://' &&
        jQuery.trim(jQuery('#' + prefix + '_txtWebsite').val()).length > 0 &&
        jQuery('#' + prefix + '_txtWebsite').val().search(urlRegxp) == -1) {
        $summaryError.append('<li>' + invalidWebsite + '</li>');
    }
    if (jQuery.trim(jQuery('#' + prefix + '_txtComment').val()).length == 0) {
        $summaryError.append('<li>' + invalidComment + '</li>');
    }

    if (jQuery.trim($summaryError.html()).length > 0) {
        $summaryError.fadeIn('slow');
        return false;
    }

    return true;
}

function initComment() {
    // Initialize the object, before adding data to it.
    //  { } is declarative shorthand for new Object().
    var annotation = {};
    annotation.EntryID = entryMetadata.entryID;
    annotation.Author = parse(jQuery('#' + prefix + '_txtAuthor').val());
    annotation.Email = encodeURI(jQuery('#' + prefix + '_txtEmail').val());
    annotation.Website = encodeURI(jQuery('#' + prefix + '_txtWebsite').val());
    annotation.Comment = jQuery('#' + prefix + '_txtComment').val();

    return annotation;
}

function parse(s) {
    if (s) return s.replace(/\n/, "<br/>").replace(/&/g, "&amp;").replace(/\"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    return ""
};

function reset() {
    jQuery('#anonDetails .validation-summary-errors').hide();
    jQuery('#' + prefix + '_txtComment').val("");
};

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; 