//  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();
    
    // 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' });
    
    // 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 + ',userID:' + entryMetadata.userID + '}', //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 $summaryError = jQuery('#anonDetails .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');
        } else {
            var comment = {
                entryID: entryMetadata.entryID,
                userID: entryMetadata.userID,
                name: parse(jQuery('#' + prefix + '_txtAuthor').val()),
                email: encodeURI(jQuery('#' + prefix + '_txtEmail').val()),
                website: encodeURI(jQuery('#' + prefix + '_txtWebsite').val()),
                comment: parse(jQuery('#' + prefix + '_txtComment').val())
            };
            jQuery.ajax({
                type: "POST",
                url: jQueryBasicPath + "BlogServices.asmx/AddComment",
                data: jQuery.toJSON(comment),
                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);
//                    var annotationMsg = jQuery(msg).fadeTo(0, 0, function() {
//                        annotationMsg.appendTo("#annotations").fadeTo(1000, 1);
//                        //jQuery('#annotationsEmpty').hide();
//                    });
                },
                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 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; 
