var lwapi;
                
function init() {
    //lwapi = new LWAPI("http://community.pacefoods.com");    //PROD
    lwapi = new LWAPI("http://community.pacefoods.com"); //STAGING
    
    // get up to 3 recent threads
    getRecentCategoryThreads(3,0,3);
    
    // get the first featured poll
    getFeaturedPolls(3,0,1);
    
    // get the featured pace moment
    getForumStoryboards(14000000484,0,1);
    
    // get the first pace review
    getRecentPaceReviewThread(14000000006,0,1);
}

/*###########################################################################################*/
/*########################## BEGIN RECENT THREADS FUNCTIONALITY #############################*/
/*###########################################################################################*/

function getRecentCategoryThreads(categoryID, start, numResults)
{
    lwapi.callContentService("getRecentCategoryThreads", 
        "categoryID="+categoryID+"&start="+start+"&numResults="+numResults,getThreads);
}

function getThreads(threadList) { 
    if (threadList.threads instanceof Array) {
        for (i = 0; i < threadList.threads.length; i++) {
            appendThreadHtml(threadList.threads[i]);
        }
    }
}

function appendThreadHtml(thread)
{
    var threadBody = generateSummary(thread.body,70);
    var forumThreadsArea = document.getElementById("forums");
    
    forumThreadsArea.innerHTML += '<p><a href="' + CreateLWAuthLink(thread.uRL) + '">' + thread.subject + '</a> By #user.fullname.' + thread.threadID + '<br />' +
        threadBody + ' <a href="' + CreateLWAuthLink(thread.uRL) + '" class="read-more">Read More</a>';
    
    lwapi.callUsersService("getPublicUserInfo", 
        "userID="+thread.author.userID,
        function (userInfo)
        {
            var forumThreadsArea = document.getElementById("forums");
            var html = forumThreadsArea.innerHTML;
            var regExString = '#user.fullname.' + thread.threadID;

            html = html.replace(regExString, returnNamedPropertyValue(userInfo, 'name'));
            forumThreadsArea.innerHTML = html;
        }
        );
}

/*###########################################################################################*/
/*########################## END RECENT THREADS FUNCTIONALITY #############################*/
/*###########################################################################################*/


/*###########################################################################################*/
/*########################## BEGIN RECENT REVIEW FUNCTIONALITY ##############################*/
/*###########################################################################################*/

function getRecentPaceReviewThread(categoryID, start, numResults)
{
    lwapi.callContentService("getRecentCategoryThreads", 
        "categoryID="+categoryID+"&start="+start+"&numResults="+numResults,getReviewThread);
}

function getReviewThread(threadList) { 
    renderPaceReview(threadList.threads);
}

function renderPaceReview(thread)
{        
    lwapi.callContentService("getForum", 
        "forumID="+thread.forumID,
        function (forum)
        {
            var reviewsContainer = document.getElementById("reviews");
            var html = reviewsContainer.innerHTML;
            var image;
            
            if(forum.extendedProperties instanceof Array) {
                image = returnNamedPropertyValue(forum.extendedProperties, 'forumImage');
            } else {
                image = forum.extendedProperties.value;
            }
            
            image = image.replace(/width=\"([0-9]+)\"/g, 'width=\"38\"');
            image = image.replace(/height=\"([0-9]+)\"/g, 'height=\"73\" class=\"product\"');
            
            html = html.replace(/#forum.forumImage/g, image);
            
            reviewsContainer.innerHTML = html;
            document.getElementById("reviewsWrapper").style.visibility = 'visible';
        }
        );
        
    lwapi.callUsersService("getPublicUserInfo", 
        "userID="+thread.author.userID,
        function (userInfo)
        {
            var reviewsContainer = document.getElementById("reviews");
            var html = reviewsContainer.innerHTML;
            
            html = html.replace(/#user.fullname/g, returnNamedPropertyValue(userInfo, 'name'));
            reviewsContainer.innerHTML = html;
        }
        );
    
    var reviewsContainer = document.getElementById("reviews");
    var threadBody = generateSummary(thread.body,70);
    var html = reviewsContainer.innerHTML;
    var rating = '0';   
    
    // rating is productRating xprop of the thread
    if(thread.extendedProperties instanceof Array)
    {
        rating = returnNamedPropertyValue(thread.extendedProperties,'productRating');
    }
    else if(thread.extendedProperties.name == 'productRating')
    {
        rating = thread.extendedProperties.value;
    }
    
    // rating is padded with leading zeros, remove them
    if(rating.length > 1) {
        rating = rating.substring(rating.length - 1);
    }
    
    html = html.replace(/#thread.subject/g, thread.subject);
    html = html.replace(/#thread.forumName/g, thread.forumName);
    html = html.replace(/#thread.uRL/g, CreateLWAuthLink(thread.uRL));
    html = html.replace(/#thread.body/g, threadBody);
    
    html = html.replace(/#forum.rating/g, rating);
    
    reviewsContainer.innerHTML = html;
}

/*###########################################################################################*/
/*########################### END RECENT REVIEW FUNCTIONALITY ###############################*/
/*###########################################################################################*/


/*###########################################################################################*/
/*############################## BEGIN POLL FUNCTIONALITY ###################################*/
/*###########################################################################################*/

function getFeaturedPolls(categoryID, start, numResults) {
    lwapi.callContentService("getFeaturedPolls", 
	    "categoryID="+categoryID+"&start="+start+"&numResults="+numResults,getPolls);	
}

function getPolls(poll) {
    // If they have already taken this poll show the results, if not render the poll.
    if(!doesCookieExistForPollID(poll.pollID))
    {
        appendPollHtml(poll);
    }
    else
    {
        renderPollResults(poll);
    }
}

function appendPollHtml(poll)
{
    if (poll.pollID=='undefined')
    {
	    return;
	}
	
    var objPollWrapperDiv = document.getElementById("poll");
    var objPollDiv = document.getElementById("pollradiobuttons");
    var objQuestionParagraph = document.getElementById("question");
    
    // Set the poll question.
    objQuestionParagraph.innerHTML = poll.name;
    
    
    // Write out each option for the poll.
    for (var i = 0; i < poll.options.length; i++)
    {
	    objPollDiv.innerHTML += '<div class="poll-option clearfix"><div class="poll-option-button"><input type="radio" value="' + i + '" name="communitypoll" /></div><div class="poll-option-text">' + poll.options[i].name + '</div></div>';
    }
    
    // Add the poll button with the reference to the poll id.
    objPollWrapperDiv.innerHTML += '<img src="images/community_btn_submit.gif" width="80" height="13" onclick="voteInPoll(' + poll.pollID + ');" id="lwpollsubmit" class="button" />';
}

function renderPollResults(poll)
{
    var objPollDiv = document.getElementById("pollradiobuttons");
    var objPollSubmitButton = document.getElementById("lwpollsubmit");        
    var pollResultsHTML = '<table id="pollresults">';                                
    var objQuestionParagraph = document.getElementById("question");
    
    // Set the poll question.
    objQuestionParagraph.innerHTML = poll.name;
    
    var totalvotes = 0;
    
    for (var a = 0; a < poll.options.length; a++)
    {
        totalvotes = totalvotes + parseInt(poll.options[a].value);
    }
    
    for (var i = 0; i < poll.options.length; i++)
    {
	    pollResultsHTML += '<tr><td class="spacer-row" colspan="2"></td></tr><tr class="poll-result"><td class="poll-result-percent" valign="center"><div class="percent">'+ Math.round(((parseInt(poll.options[i].value) / totalvotes) * 100)) +'%</div></td><td class="poll-result-text">' + poll.options[i].name + '</td></tr>'
    }
    
    pollResultsHTML += '</table>'
    
    objPollDiv.innerHTML = pollResultsHTML;
    if(objPollSubmitButton!=null)
    {
        objPollSubmitButton.style.display = 'none';
    }
}

function voteInPoll(pollid){    
    var voteValue = getPollVoteValue();
    
    if(voteValue == -1)
    {
        alert('Please select an answer for the poll.');
    }
    else
    {
        // vote and render the poll with the results template
	    lwapi.callContentService("voteAnonymouslyInPoll", 
		    "pollID=" + pollid + "&optionIndex=" + voteValue + "&uniqueId=" + usersessionid, renderPollResults);
		
	    // Drop cookie that states that they have already voted today.
	    set_cookie(pollid);	
	}	
}

function set_cookie(pollid)
{
    var name = 'lwpc';
    var defaultPath = '/'; //(document.URL.toLowerCase().indexOf("pacefoods.com") != -1) ? "pacefoods.com" : "/";
    
    //create the expiration date - currently 365 days
    var expire_time = new Date( new Date().getTime()+86400000*365 );    
    var expire_time_string = (expire_time.getMonth() + 1) + "/" + expire_time.getDate() + "/" + expire_time.getFullYear();
    var expire_date_new = new Date (expire_time_string);
    
    //set cookie in the browser
    document.cookie = name + '=' + pollid + ';expires=' + expire_date_new.toGMTString() + '; path=' + defaultPath;
}

function doesCookieExistForPollID(pollid)
{
    var check_name = 'lwpc';
    var allCookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; 
    
    for ( i = 0; i < allCookies.length; i++ )
    {
        // now we'll split apart each name=value pair
	    a_temp_cookie = allCookies[i].split( '=' );

	    // and trim left/right whitespace while we're at it
	    cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

	    // if the extracted name matches passed check_name
	    if ( cookie_name == check_name )
	    {
		    b_cookie_found = true;
		    // we need to handle case where cookie has no value but exists (no = sign, that is):
		    if ( a_temp_cookie.length > 1 )
		    {
			    cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
		    }
		    break;
	    }
	    a_temp_cookie = null;
	    cookie_name = '';
    }
    
    if(cookie_value == pollid)
    {
        return true;
    }
    else
    {
        return false;
    }
}

function getPollVoteValue()
{
    //TODO: Add code to get the actual vote value.
    var vote  = -1;
    var pollForm = document.forms[0];
    
    for (i = 0; i < pollForm.communitypoll.length; i++)
    {
	    if (pollForm.communitypoll[i].checked)
	    {
		    vote = pollForm.communitypoll[i].value;
		    break;
		}
	}
	
    return vote;
}

/*###########################################################################################*/
/*############################### END POLL FUNCTIONALITY ####################################*/
/*###########################################################################################*/


/*###########################################################################################*/
/*######################### BEGIN PACE MOMENTS FUNCTIONALITY ################################*/
/*###########################################################################################*/

// call getForumStoryboards to get recent storyboards and fill the storyboards element with the results
function getForumStoryboards(forumID, start, numResults)
{
    lwapi.callContentService("getForumStoryboards", 
	    "forumID="+forumID+"&start="+start+"&numResults="+numResults,getStoryBoards);	
}

function getStoryBoards(sbList)
{
    if (sbList.storyboards instanceof Array)
    {
	    renderStoryboard(sbList.storyboardList[0]);
    }
    else
    {
        renderStoryboard(sbList.storyboardList);
    }
}

function renderStoryboard(sb)
{
    var subjectLink = document.getElementById("PaceMomentsLink");
    subjectLink.href = CreateLWAuthLink(sb.uRL);
    subjectLink.innerHTML = sb.subject;
	
    var authorText = document.getElementById("PaceMomentAuthorName");
    authorText.innerHTML = '<em>&#8212; #user.fullname</em>';
    
    lwapi.callUsersService("getPublicUserInfo", 
        "userID="+sb.author.userID,
        function (userInfo)
        {
            var authorText = document.getElementById("PaceMomentAuthorName");
            var html = authorText.innerHTML;
            
            html = html.replace(/#user.fullname/g, returnNamedPropertyValue(userInfo, 'name'));
            authorText.innerHTML = html;
        }
        );
	
    var photo = document.getElementById("PaceMomentsPhoto");
    
    if(sb.photos instanceof Array)
    {
        if(sb.photos[0].name)
        {
	        photo.src = sb.photos[0].name;
	    }
    }
    else
    {
        if(sb.photos.name)
        {
	        photo.src = sb.photos.name;
	    }
    }   
	
    var captionText = document.getElementById("PaceMomentsText");
    captionText.innerHTML = generateSummary(sb.body, 70);
    
    var viewMomentLink = document.getElementById("PaceMomentsLWLink");
    viewMomentLink.href = CreateLWAuthLink(sb.uRL);
}

/*###########################################################################################*/
/*########################## END PACE MOMENTS FUNCTIONALITY #################################*/
/*###########################################################################################*/


function CreateLWAuthLink(url)
{
    if(loggedin && loggedin == 'true')
    {
        return 'javascript:checkLWAuthAndRedirect(\'' + url + '\');';
    }
    else
    {
        return url;
    }
}

function generateSummary(bodyText, summaryLength)
{
    var summary = bodyText;
    
    summary = summary.replace(/<br>/gi, " ");
    
    if(summary.length > summaryLength)
    {    
        summary = summary.substring(0, summaryLength);
        summary += '[...]';
    }
    
    return summary;
}

function returnNamedPropertyValue(nameValueObject, propertyName)
{
    if(nameValueObject[0] && nameValueObject[0].name)
    {
        for(i = 0; i < nameValueObject.length; i++)
        {
            if(nameValueObject[i].name == propertyName)
            {
                if(nameValueObject[i].value)
                {
                    return nameValueObject[i].value;
                }
            }
        }
    }
    
    return 'null';
} 

Event.observe(window,"load",init);
