/* 
Javascript functions to perform comment preview
*/
function stxPreviewComment()
{
    // get the raw comment source
    var inText = document.forms['showform_24'].elements['pxdb[data][body]'].value;
    var previewElt = document.getElementById('comment-preview');
    
    commentText = inText.replace(/^\s*|\s*$/g,"");
    commentText = keepSafeTags(commentText);
    commentText = makeLinks(commentText);
       
    previewElt.innerHTML = commentText;
    if ( commentText != "")
    {
        previewElt.style.display = 'block';
    }
    else
    {
        previewElt.style.display = 'none';
    }
}

function keepSafeTags(inputText)
{
    // easy hack, first let's turn "safe" tags into something that looks unlike html tags 
    var re= /<(B|\/b|strong|\/strong|p|\/p|i|\/i|em|\/em|br|blockquote|\/blockquote)>/gi
    safeText = inputText.replace(re, "{{$1}}");
    
    
    
    // now strip out everything we haven't whitelisted 
    var re= /<\S[^>]*>/g; 
    safeText = safeText.replace(re,""); 
    
    // and finallyturn what we whitelisted back into html tags
    // !important, note that we turn back only wahat we matched back into html tags
    // not everything between {{ }} !! 
    var re= /\{\{(B|\/b|strong|\/strong|p|\/p|i|\/i|em|\/em|br|blockquote|\/blockquote)\}\}/gi
    safeText = safeText.replace(re, "<$1>");
    
    return safeText;
    
}

function makeLinks(inputText)
{
    var re= /\b((http(s?):\/\/)|(www\.))([\w\.\-]+)([\/\w+\.]+)(\/*)\b/gi
    
    linkedText = inputText.replace(re, "<a href=\"http$3://$4$5$6$7\"target=\"_blank\">$2$4$5$6$7</a>");
    return linkedText;
    
}

function startCommentPreview()
{
    var slide_timer = window.setInterval("stxPreviewComment()", 200);
}

function stopCommentPreview()
{
   var slide_timer = window.clearInterval();   
}

// bind events to preview field
commentTextarea = document.forms['showform_24'].elements['pxdb[data][body]'];
commentTextarea.onfocus = startCommentPreview;
commentTextarea.onblur = stopCommentPreview;


/* test string:
<b></b> <strong>test </strong>
<blockquote>This is a quote</blockquote>
<div>I was in a div</div>
<blink>I want to blink</blink>
<a href="">I am a link</a>
http://www.google.com/
*/
