var squareblog = {};

squareblog.onDocumentReady = function() {
	var logoutLink = MochiKit.DOM.getElement('link-logout');
	if (logoutLink) {
		squareblog.makeLinkPost(logoutLink, "Really log out?");
	}

    var i;

    var deleteCommentLinks = MochiKit.DOM.getElementsByTagAndClassName('a', 'link-delete-comment');

    for (i = 0; i< deleteCommentLinks.length; i++) {
        squareblog.makeLinkPost(deleteCommentLinks[i], "Really delete this comment?");
    }

    var acceptCommentLinks = MochiKit.DOM.getElementsByTagAndClassName('a', 'link-moderate-comment');

    for (i = 0; i< acceptCommentLinks.length; i++) {
        squareblog.makeLinkPost(acceptCommentLinks[i], "Really accept this comment?");
    }

    var footNoteLink = MochiKit.DOM.getElement('link-to-footnote');
    var footNote = MochiKit.DOM.getElement('footnote');

    MochiKit.Signal.connect(footNoteLink, 'onclick', function() {
        MochiKit.Style.setStyle(footNote, {'font-weight': 'bold'});
        MochiKit.Style.setStyle(footNote, {'font-size': '100%'});
        MochiKit.Visual.Highlight(footNote);
    });
}

MochiKit.Signal.connect(window, 'onload', squareblog, 'onDocumentReady');

/**
 * Changes a link so that it uses POST.
 */
squareblog.makeLinkPost = function(link, confirmation) {
	var f = MochiKit.Base.partial(squareblog.fullPagePost, link.href)
	if (confirmation) {
		f = squareblog.wrapWithConfirm(f, confirmation);
	}
	
	f = squareblog.wrapWithStopEvent(f);
	
	MochiKit.Signal.connect(link, 'onclick', f);
}

/**
 * Wraps a function in request for confirmation.
 */
squareblog.wrapWithConfirm = function(fun, confirmation) {
	return function() {
		if (confirm(confirmation)) {
			fun(arguments);
		}
	}
}

/**
 * Wraps a function in a event-blocker.
 */
squareblog.wrapWithStopEvent = function(fun) {
	return function(event) {
		event.stop();
		fun();
		return false;
	}
}

/**
 * Performs a full-page POST (non-AJAX) to given url
 */
squareblog.fullPagePost = function(url) {
	// create a form
	var f = MochiKit.DOM.FORM(
		{'action' : url, 'method': 'POST'}
	);
	// add it to the body
	MochiKit.DOM.appendChildNodes(
		MochiKit.DOM.currentDocument().body,
		f
	);
	// submit
	f.submit();
}


