/*Copyright (c) 2012 Bill Burdick

This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.

Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.

2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.

3. This notice may not be removed or altered from any source distribution.*/

function replacePagedown() {
    document.body.innerHTML = new Markdown.Converter().makeHtml(document.body.innerHTML)
}

function detectPagedown() {
    var content = $('.content')

    if (content && content[0].innerHTML.match(/^ *<p>@pagedown/m)) {
	markup(content[0])
    }
}


function markup(div) {
    var wikiName
    var url

    if (document.location.pathname.match(/\/home|\/index/)) {
	url = baseUrl + "/wikiedit?name=" + projectName
    } else if (document.location.href.match(new RegExp('^' + baseUrl + '/doc/.*\.wiki'))) {
	// this is for document wiki URLs
	div.setAttribute('style', 'visibility: hidden')
	$.get(document.location.href.substring(0, document.location.href.length - document.location.search.length) + "?mimetype=text/plain", function(wikiPage) {
	    replaceContent(div, $(wikiPage).filter('div.content').find('pre')[0].innerHTML)
	})
	return
    } else if (document.location.pathname.match(/\/wiki/)) {
	url = baseUrl + "/wikiedit?name=" + (/[\\?&]name=([^&#]*)/.exec(window.location.href)[1] || 0)
    } else {
	return
    }
    div.setAttribute('style', 'visibility: hidden')
    $.get(url, function(data) {replaceContent(div, $(data).find('textarea')[0].value)})
}

function replaceContent(div, content) {
    div.innerHTML = new Markdown.Converter().makeHtml(content.match(/^[ \n]*@pagedown((.|\n)*)$/m)[1])
    div.setAttribute('style', '')
}

