/* Copyright Wolf Frameworks India Pvt. Ltd.
version : 1.5
date    : 1 Dec 2008
*/

var evalText = "var wolf = {}";
try{if(wolf)evalText = "";}catch(e){}
eval(evalText);
//wolf.hostURL = "http://localhost/wsf/webservices/wf.handlers/";
wolf.hostURL = "https://run.wolfframeworks.com";
wolf.currentPost = {title:"",body:"",summary:"",type:""};

//***************************
//  Common Utiltiy Function that converts the querystring to a Javascript Object
//***************************
wolf.queryString = {};
evaluateQueryString(window);
function evaluateQueryString(wnd)
{
    try{
    var qs = wnd.location.href.split("?")[1].split("&")
    for (var i = 0; i< qs.length; i++)
    {
        var param = qs[i].split("=");
        
        var parameterValue = param[1];
                
        if(parameterValue.indexOf("#") >0)
        {
            parameterValue = parameterValue.substr(0, parameterValue.indexOf("#"));
        }
                
        parameterValue = unescape(parameterValue);        
        wolf.queryString[param[0].toLowerCase()] = parameterValue;
    }}catch(e){}
}    	

//***************************
//  Common Utiltiy Function that formats the date for display
//***************************
function formatDate(sDate)
{
    var arrDate = sDate.split("-");
    
    var day = arrDate[2].split("T")[0]
    
    var arrTime = arrDate[2].split("T")[1].split(":")
    
    sDate = new Date(arrDate[0], arrDate[1] -1 , day);

    var today = new Date();
    var additionalDateString = "";
    var dateDiff = parseInt((today - sDate)/(24*60*60*1000));
    var dayOfWeek = today.getDay();

    if(dateDiff == 0)
    {
        additionalDateString = " (today)";
    }
    else if(dateDiff == 1)
    {
        additionalDateString = " (yesterday)";
    }
    else if(dateDiff > 1 && dateDiff < dayOfWeek)
    {
        additionalDateString = " (this week)";
    }
    else if(dateDiff <  (dayOfWeek + 7))
    {
        additionalDateString = " (last week)";
    }
    else if(dateDiff <  today.getDate())
    {
        additionalDateString = " (this month)";
    }
    else if(dateDiff <  (today.getDate() + 31))
    {
        additionalDateString = " (last month)";
    }
    
    return sDate.toDateString().replace(" ", ", ") + additionalDateString//+ " at " + arrTime.join(":");
}

//***************************
//  Common Utiltiy Function that loops through the returned values 
//  from a business rule call and invokes the function pointer
//***************************
function postingList(wsfdocument, drawingFunction)
{
    var records = wsfdocument.record;
    try
    {
        if(records.length > 0)
        {
            for( var i = 0; i < records.length ; i++)
            {
                drawingFunction(records[i]);
            }
        }else
        {
            drawingFunction(records);
        }
    }catch(e){}
}

//***************************
//  Common utility function that creates a 
//  valid form tag that is capable of calling a business rule
//***************************
function getRequiredFormTags(key, appId, redirectURL, ruleName)
{
    if(!key)key = wolf.publicKey;
    if(!appId)appId = wolf.appId ;

    var formHTML = "<form name='wsfForm' method='post' action='" + wolf.hostURL + "/webservices/wf.handlers/formpost.ashx' onsubmit='return submitForm();'>" +
                "<input type='hidden' name='appid'          value='" + appId + "'/>" +
                "<input type='hidden' name='key'            value='" + key + "'/>" +
                "<input type='hidden' name='rulename'       value='" + ruleName +"'/>" +
                "<input type='hidden' name='redirect'       value='" + redirectURL + "'/>" +
                "<input type='hidden' name='service'        value='processbusinessrule'/>";
    return formHTML
}


//***************************
//  Common utility function that creates a 
//  valid script tag that is capable of calling a business rule
//***************************
function getScriptTag(key, appId, service, ruleName, callbackName, paramString)
{
    if(!paramString)paramString = "";
    if(!key)key = wolf.publicKey;
    if(!appId)appId = wolf.appId ;
    
    var scriptTag = unescape("%3Cscript language='javascript' type='text/javascript' src='" + wolf.hostURL + "/webservices/wf.handlers/javascript.ashx?" + 
            "appid=" + appId +  
            "&key=" + key + 
            "&service=" + service + 
            "&rulename=" + ruleName + 
            //"&mode=xml" +
            "&callback=" + callbackName + paramString + "'>%3C/script>");
    return scriptTag            
}


//***************************
//  BLOG RELATED FUNCTIONS 
//  if you are not using blogs functionality then this section can be removed
//  SECTION START
//***************************

function blogCommentDisplay(wsfdocument)
{
    var records = wsfdocument.record;
    var comments = (records.length != null?records.length:1)
    document.write("<div id='blogcomments'><h3>" + comments + " Comment(s)</h3><br/>")
    postingList(wsfdocument, drawComment);
    document.write("</div>")
}

function categoryDisplay(wsfdocument)
{
    postingList(wsfdocument, drawCategory)
}

function blogDisplayLatest(wsfdocument)
{
    postingList(wsfdocument, drawLatest)
}


function blogDisplayList(wsfdocument)
{
    //alert(wsfdocument)
    document.write("<table style='width:100%'><thead>")
    document.write("<tr><td>Topic</td><td align='center' width='75px'  >Replies</td><td align='center' width='100px'>Views</td>")
    document.write("<thead><tbody>")
    postingList(wsfdocument, drawBlogListItem)
    document.write("</tbody></table>")
    
}


function blogDisplay(wsfdocument)
{
    //alert(wsfdocument)
    postingList(wsfdocument, drawBlog)
}

function drawCategory(record)
{
    var HTML = "";
    try
    {
        HTML += "<div class='categoryItem'>";
        HTML += "<h3><a " + (wolf.anchorToPostDetail== null?"":"href='" + wolf.anchorToPostDetail + "?categoryid=" + record.uid + "&categorytitle=" + record.c + "'" ) + ">" + record.c + "</a></h3><br/>";
        HTML +=  "<span class='categorySummary'>" + record.s + "</span>"
        HTML += "</div>";
    }catch(e){}
    document.write(HTML)
}

function drawLatest(record)
{
    var recentListElement = document.getElementById("recentlist")
    if(recentListElement != null)
    {
        var HTML = "";
        try
        {
            var htmlElement = document.createElement("div");
            var html        = "<a href='displayline.htm?postid=" + record.uid + "'>" + record.title + "</a>";
            html            +="<div>posted on " + formatDate(record.on) + "</div>";
            
            
            htmlElement.innerHTML = html;
            htmlElement.className = "recentlistitem";
            
        }catch(e){alert(e.message)}        
        
        recentListElement.appendChild(htmlElement)
        //document.write(HTML)
    }        
}

function drawBlogListItem(record)
{
    var HTML = "";
    try
    {
        HTML += "<tr ><td class='bloglistitem'>";
        HTML += "<div class='" + record.type + "'>";
        HTML += "<a style='font-size:1.2em'" + (wolf.anchorToPostDetail== null?"":"href='" + wolf.anchorToPostDetail + "?postid=" + record.uid + "'" ) + ">" + record.title + "</a>";
        HTML +=  "<span class='blogdate'>" + formatDate(record.publishedon) + "</span>"
        HTML += "<br/>Posted by <b>" + unescape(record.publishedby) + "</b> on " + formatDate(record.publishedon);
        HTML += "</div>";
        HTML += "</td>"
        HTML += "<td class='bloglistitem' align='center'>" + record.r + "</td>"
        HTML += "<td class='bloglistitem' align='center'>" + record.v + "</td>"
        HTML += "</tr>"

    }catch(e){}
    document.write(HTML)
    
    var categoryTitleElement = document.getElementById("categoryheader")
    
    if(categoryTitleElement != null)
    {
        categoryTitleElement.innerHTML = record.cat;
    }
    
}


function drawBlog(record)
{
    var HTML = "";
    try
    {
        HTML += "<div class='blogitem'>";
        HTML += "<span class='blogreply'><a href='#commentform'>Reply or Comment</a></span>";
        
        var allowEdit = ((parseInt(record.c) == 0 || record.c == null) && (window.profileDocument.record.UniqueID == record.cid));
        
        if(allowEdit == true)
        {
            HTML += "<span class='blogeditme'><a href='post.htm?postid=" + record.uid + "'>Edit this post</a></span>";
        }
        
        HTML += "<span class='blogtitle'>" + record.title + "</span>";
        HTML += "<span class='publishedby'>Posted by <b>" + record.publishedby + "</b> on " + formatDate(record.publishedon) + " </span>";
        //HTML += "<span class='blogdate'>" + formatDate(record.publishedon) + "</span>"
        HTML += "<span class='blog'>" + clearCDATA(record.body) + "</span>";
        
        
        HTML += "<span class='blogreply'><a href='#commentform'>Reply or Comment</a></span>";
        
        if(allowEdit == true)
        {
            HTML += "<span class='blogeditme'><a href='post.htm?postid=" + record.uid + "'>Edit this post</a></span>";
        }
        HTML += "</div>";
    }catch(e){}
    document.write(HTML)
    
    var thisforumElement =  document.getElementById("thisforum");
    var thisthreadElement =  document.getElementById("thisthread");
    var commentFormElement = document.getElementById("commentform");
    if(thisforumElement != null)
    {
       thisforumElement.href         = thisforumElement.href.replace("#cat#", record.catid);
       thisforumElement.innerHTML    = record.cat;
    }
    
    if(thisthreadElement != null)
    {
       thisthreadElement.href         = thisthreadElement.href.replace("#pid#", record.uid);
    }
    
    if(record.z == "1")
    {
        document.write("<style>#commentform,#formhtml{display:none}#nomorecomments{display:block}</style>")
    }
    
    
}

function deleteComment(uniqueId)
{
    addScript("service=processbusinessrule&rulename=DeleteComment&commentid=" + uniqueId + "&callback=commentDeleted");
}


function commentDeleted(wsfRecord)
{
    window.location = window.location.href;
    
}

function drawComment(record)
{
    var HTML = "";
    try
    {
        HTML += "<div class='commentblock'>";
            HTML += "<span class='commentedby " + record.type + "'><b>" + unescape(record.postedby) + "</b> <br/> " + formatDate(record.commentedon)+ " </span>";
            //HTML +=  "<span class='blogdate'>" + formatDate(record.commentedon) + "</span>"
            
            HTML += "<span class='comment'>" + clearCDATA(record.comment) + "</span>";
            if(window.profileDocument.record.UniqueID == record.cid)
            {
                HTML += "<span class='deletecomment'><a href='javascript:deleteComment(\"" + record.bcid + "\")'>Delete this comment</a></span>";
            }
            
            
        HTML += "</div>";
    }catch(e){}
    document.write(HTML)
}

function writeRecentList(key, appId, callBackName)
{
    if(!key)key = wolf.publicKey;
    if(!appId)appId = wolf.appId ;

    var callBack = callBackName;
    if(!callBack) callBack = "blogDisplayLatest";

    var script    = getScriptTag(key, appId, "processbusinessrule", "Latest Posts", callBack);
    document.write(script);
    
}


// ************************* 
//  1] Write Script that will call BlogList business rule
//**************************
function writeBlogList(key, appId, callBackName)
{
    if(!key)key = wolf.publicKey;
    if(!appId)appId = wolf.appId ;

    var callBack = callBackName;
    if(!callBack) callBack = "blogDisplayList";

    var script    = getScriptTag(key, appId, "processbusinessrule", "BlogList", callBack, "&paramcategoryid=" + wolf.queryString.categoryid);
    
    document.write(script);
}

function writeCategoryList(key, appId, callBackName, level)
{
    if(!key)key = wolf.publicKey;
    if(!appId)appId = wolf.appId ;

    var callBack = callBackName;
    if(!callBack) callBack = "categoryDisplay";
    
    if(!level) level = 0;

    var script    = getScriptTag(key, appId, "processbusinessrule", "Get Categories", callBack, "&paramtype=Forum&paramlevel=" + level);
    
    document.write(script);
}

function clearCDATA(value)
{
    value = value.replace("<![CDATA[","").replace("]]>", "");
    return value;
}

// ************************* 
//  1] Put the information from the wsfDocument into the wolf.currentPost object
//  2] Call the actual callback if any has been set.
//**************************
function lineCallBack(wsfdocument)
{

    wolf.currentPost.title      = wsfdocument.record.title;
    wolf.currentPost.body       = clearCDATA(wsfdocument.record.body);
    wolf.currentPost.scope      = wsfdocument.record.scope;
    wolf.currentPost.summary    = wsfdocument.record.summary;
    wolf.currentPost.type       = wsfdocument.record.type;
    
    if(wolf.lineCallBack)
    {
        eval(wolf.lineCallBack + "(wsfdocument)");
    }
    
    var postElement = document.getElementById("paramtitle");
    
    if(postElement != null)
    {
        postElement.value = wolf.currentPost.title;
        document.getElementById("paramsummary").value   = wolf.currentPost.summary;
        document.getElementById("parambody").value      = wolf.currentPost.body;
        
    }
    
}

// ************************* 
//  1] Fetch Blog Line
//  2] Direct LineCallBack to invoke blogDisplay
//**************************
function writeBlogLine(key, appId, callBackName, blogUID)
{
    if(!key)key = wolf.publicKey;
    if(!appId)appId = wolf.appId ;
    
    if(!callBackName)callBackName = "blogDisplay";
    
    fetchPostLine(key, appId, callBackName, blogUID);
}

// ************************* 
// Writes all the comments against a blog;
//**************************
function writeBlogComments(key, appId, callBackName, blogUID)
{
    if(!key)key = wolf.publicKey;
    if(!appId)appId = wolf.appId ;

    if(!blogUID)blogUID = wolf.queryString.postid;
    if(blogUID == null) return;

    if(!callBackName) callBackName = "blogCommentDisplay";

    var script    = getScriptTag(key, appId, "processbusinessrule", "BlogCommentsList", callBackName, "&paramblogid=" + blogUID);
    document.write(script);
}

//*****************************
//  BLOGS SECTION END
//*****************************

// *******************
//  SECTION COMMON TO ALL TYPES OF POSTS
// draw a form that is capable of collecting postings for
// 1] Blogs
// 2] News
// 3] Discussion forums
// draws the Form and all its elements required for the blog to be posted
// *******************


// ************************* 
//  1] Write Script that will call rule
//  2] Direct the Script to LineCallBack
//**************************
function fetchPostLine(key, appId, callBackName, uid)
{
    if(!key)key = wolf.publicKey;
    if(!appId)appId = wolf.appId ;

    if(callBackName) wolf.lineCallBack  = callBackName;
    if(!uid)uid = wolf.queryString.postid;

    if(uid == null) return;
    var script    = getScriptTag(key, appId, "processbusinessrule", "BlogLine", "lineCallBack", "&paramuid=" + uid);

    document.write(script);
}

function addScript(queryString)
{
    var scriptSource  =   wolf.hostURL + "/webservices/wf.handlers/javascript.ashx?appid=" + wolf.appId + "&key=" + wolf.publicKey +  "&" + queryString
    
    if(wolf.queryString != null)
    {
        var reservedwords = ",appid,publickey,formredirecturl,uid,successmsg,"
        
        for(var k in wolf.queryString)
        {
            if(reservedwords.indexOf("," + k + ",") == -1)
            {
                var parameterValue = wolf.queryString[k.toString()];
                
                if(parameterValue.indexOf("#") >0)
                {
                    parameterValue = parameterValue.substr(0, parameterValue.indexOf("#"));
                }
                
                parameterValue = unescape(parameterValue);
                scriptSource += "&param" + k.toString() + "=" + parameterValue;
                
            }
            
        }
    }

    var scriptTag   = document.createElement("script");
    scriptTag.type  = "text/javascript";
    
    scriptTag.src   = scriptSource;
    
    
    document.getElementsByTagName("HEAD")[0].appendChild(scriptTag);
}

