//  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
    jQuery('a[rel*=facebox]').facebox();

    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('.faceboxModal #yes').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('.faceboxModal #no').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');
            },
            error: function(xhr, status, error) {
                jQuery('#annotations').removeAttr('class').empty().html(commentListError).addClass('warning');
            }
        });
    }

    // submit the new comment with ajax call websevice
    jQuery('#btnSubmitComment').click(function() {
        var valid = verifyComment();
        if (valid) {
            // 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();
                    });
                }
				
            });
        }

        return false;
    });
});

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>' + nameError + '</li>');
    }
    if (jQuery.trim(jQuery('#' + prefix + '_txtEmail').val()).length == 0 || 
        jQuery('#' + prefix + '_txtEmail').val().search(emailRegxp) == -1) {
        $summaryError.append('<li>' + emailError + '</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>' + websiteError + '</li>');
    }
    if (jQuery.trim(jQuery('#' + prefix + '_txtComment').val()).length == 0) {
        $summaryError.append('<li>' + commentError + '</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 = parse(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; 


