﻿if (typeof(Edentity) == 'undefined') {
    window.Edentity = {};
}

if (typeof(Edentity.LatestTwitterPosts) == 'undefined') {

    Edentity.LatestTwitterPosts = {};
    
    (function(LatestTwitterPosts, $) {

        LatestTwitterPosts.Constants = {
            jTemplateID: "LatestTwitterPostsTemplate",
            resultsTargetID: "LatestTwitterPostsResults"
        }

        LatestTwitterPosts.Display = function(json, containerID, count) {
            var constants = LatestTwitterPosts.Constants,
                $resultsTarget = $("#" + containerID);

            //Display only the necesary count
            var counted = [];
            if (count < json.length) {
                for (var c = 0; c < count; c++) {
                    counted[counted.length] = json[c];
                }
            }
            else {
                counted = json;
            }

            $resultsTarget.setTemplateElement(constants.jTemplateID);
            $resultsTarget.processTemplate(counted);

            $(".Separator", $resultsTarget).not(":last").show();
        }

        LatestTwitterPosts.Retrieve = function(webServiceUrl, reqParamJsonStr, containerID, count) {
            $.ajax({
                type: "POST",
                url: webServiceUrl,
                contentType: "application/json",
                data: reqParamJsonStr,
                dataType: "json",
                success: retrievalSuccess,
                error: retrievalError
            });

            function retrievalSuccess(results) {
                if (results && results.d) {
                    LatestTwitterPosts.Display(results.d, containerID, count);
                }
            }

            function retrievalError(XMLHttpRequest, textStatus, errorThrown) {
                //do something
            }
        }

    })(Edentity.LatestTwitterPosts, jQuery);
}

function ParseLinks(tweet) {
    var parsedTweet = tweet;
    parsedTweet = parsedTweet.replace(/([A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+)/g, "<a href='$1'>$1</a>");
    parsedTweet = parsedTweet.replace(/(^|\s)@([A-Za-z0-9-_]+)/g, "$1@<a target='_blank' href='http://twitter.com/$2'>$2</a>");
    parsedTweet = parsedTweet.replace(/(^|\s)\#([A-Za-z0-9-_]+)/g, "$1<a target='_blank' href='http://search.twitter.com/search?q=%23$2'>#$2</a>");
    return parsedTweet;
}
