EA.namespace('Twitter');

EA.Twitter = {
	useSSL: false,
    pageNumber: 2,
    pageSize: 10,
    postCharCount: 140,
    nextFeaturedPageNum: 1,
    followUser: '',
    poller: '',
    indicatorId: '#indicator',

    init: function() {
        EA.Twitter.startPoller();
        EA.Twitter.setLatestPostId();
        $j("#latestPost_1").show();
    },
    
    getSecureBaseUrl: function() {
    	if(EA.Twitter.useSSL == true)
    	{
	    	var urlStr = location.href;
	    	urlStr = urlStr.replace(/http/, 'https');
	    	var cutIndex = urlStr.indexOf("twitter");
	    	return urlStr.substr(0,cutIndex);
    	}
    	else
    	{
    		return "";
    	}
    },
    
    setLatestPostId: function() {
        var postId = $j("#liveFeed .content .twitterPost:first").attr("id");

        if (postId) {
            TwitterProperties.latestPostId = EA.Twitter.parseId(postId);
        }
    },

    parseId: function(id) {
        var postIdPattern = /(?:featuredPost_|post_)(\d*)/im,
            match = postIdPattern.exec(id);
        
        return match ? match[1] : '';
    },

    startPoller: function() {
        EA.Twitter.poller = setTimeout(function() {
            EA.Twitter.getNewPosts();
        }, 5000);
    },

    stopPoller: function() {
        clearTimeout(EA.Twitter.poller);
    },

    showIndicator: function() {
        $j(EA.Twitter.indicatorId).show();
    },

    hideIndicator: function() {
        $j(EA.Twitter.indicatorId).hide();
    },

    votePost: function(vote, id, callback) {
        $j.ajax({
            type: "POST",
            dataType: "html",
            url: "twitter!votePost",
            data: "id=" + id + "&vote=" + vote,
            success: function(data, textStatus){
                callback(vote, id);
            }
        });
    },

    getFeaturedPost: function(direction) {
        var nextPage = EA.Twitter.nextFeaturedPageNum;

        if (nextPage > 0) {
            if (direction == "next" && nextPage < TwitterProperties.numberOfFeaturedPosts) {
                nextPage++;
            } else if (direction == "next" && nextPage == nextPage) {
                nextPage = 1;
            } else if (direction == "prev" && nextPage > 1) {
                nextPage--;
            } else {
                nextPage = 1;
            }

            var url = "twitter!getFeaturedReply?page=" + nextPage;
            var postElement = $j("#featuredPostBox").load(url);
        }
    },

    getMore: function(element, api, queryString) {
        $j.ajax({
            type: "POST",
            dataType: "html",
            url: "twitter!" + api,
            data: "page=" + EA.Twitter.pageNumber + queryString,
            success: function (data, textStatus) {
                if (data == null || data == "" || data == " ") {
                    $j("#" + element + " .endOfResults").show();
                    $j("#" + element + " .moreResults").hide();
                }

                $j("#" + element + " .tweet-responses").append(data);

                EA.Twitter.pageNumber++;
            }
        });
    },
    
    getAuthorsLatestPost: function(page) {
        $j(latestPost).find(".latestAuthorPost").each(function(i) {
            if (i + 1 == page) {
                $j(this).show();
            } else {
                $j(this).hide();
            }
        });
    },

    followTwitterUser: function(uName, pWord, followUsername) {
        $j.ajax({
            type: "POST",
            dataType: "html",
            url: EA.Twitter.getSecureBaseUrl() + "twitter/twitter!followTwitterUser",
            data: "username=" + uName + "&password=" + pWord + "&followUsername=" + followUsername,
            success: function (data, textStatus) {
                if (data == "SUCCESS") {
                    $j('#followUserBox').dialog('close');
                } else if (data == "TWITTER_ERROR") {
                    $j("#followUserBox .statusUpdate").html("Invalid username or password.");
                } else if (data == "SSFAILURE") {
                    $j("#followUserBox .statusUpdate").html("Error communicating with server.");
                }
            }
        });
    },

    postReply: function(text, uName, pWord, callback) {
        $j.ajax({
            type: "POST",
            dataType: "html",
            url: EA.Twitter.getSecureBaseUrl() + "twitter/twitter!postTweet",
            data: "tweetText=" + escape(text) + "&username=" + uName + "&password=" + pWord,
            success: callback
        });
    },
    
   postHomePageReply: function(text, uName, pWord, callback) {
        $j.ajax({
            type: "POST",
            dataType: "html",
            url: EA.Twitter.getSecureBaseUrl() + "twitter/twitter!postTweet",
            data: "tweetText=" + escape(text) + "&username=" + uName + "&password=" + pWord,
            success: callback
        });
    },

    postQuestion: function(questionText, username, password) {
        $j.ajax({
            type: "POST",
            dataType: "html",
            url: EA.Twitter.getSecureBaseUrl() + "twitter/twitter!adminAddQuestion",
            data: "questionText=" + escape(questionText) + "&username=" + username + "&password=" + password,
            success: function (data, textStatus) {
                if(data=="SUCCESS") {
                    $j('#adminAddQuestion').dialog('close');
                } else if(data=="TWITTER_ERROR") {
                    $("#adminAddQuestion .statusUpdate").html("Invalid username or password.");
                } else if(data=="SSFAILURE") {
                    $("#adminAddQuestion .statusUpdate").html("Error communicating with server.");
                }
             }
        });
    },

    editQuestion: function(questionText, username, password) {
        $j.ajax({
            type: "POST",
            dataType: "html",
            url: EA.Twitter.getSecureBaseUrl() + "twitter/twitter!adminEditQuestion",
            data: "questionText=" + escape(questionText) + "&username=" + username + "&password=" + password,
            success: function (data, textStatus)
                     {
                        if(data=="SUCCESS") {
                            $j('#adminEditQuestion').dialog('close');
                        } else if(data=="TWITTER_ERROR") {
                            $("#adminEditQuestion .statusUpdate").html("Invalid username or password.");
                        } else if(data=="SSFAILURE") {
                            $("#adminEditQuestion .statusUpdate").html("Error communicating with server.");
                        }
                     }
        });
    },

    getNewPosts: function() {
        if ($j('#tabLiveFeed').attr("class") == "selected") {
            $j.ajax({
                type: "POST",
                dataType: "html",
                url: "twitter!getPosts",
                data: "sinceId=" + TwitterProperties.latestPostId,
                success: function (data, textStatus) {
                    if (data.length > 0) {
                        var elementData = data.replace(/\n/g, '');
                        elementData = elementData.replace(/\r/g, '');
                        elementData = elementData.replace(/\t/g, '');

                        $j(elementData).each(function(i) {
                            $j(this).prependTo("#liveFeed .content");
                            $j(this).hide();
                            $j(this).slideDown("slow");
                        });

                        EA.Twitter.setLatestPostId();
                    }

                    EA.Twitter.startPoller();
                }
            });
        }
    },

    getLiveFeed: function(callback) {
        EA.Twitter.pageNumber = 2;
        EA.Twitter.startPoller();
        EA.Twitter.showIndicator();
        $j.ajax({
            type: "POST",
            dataType: "html",
            url: "twitter!getLatestPosts",
            data: "page=1",
            success: function (data, textStatus) {
                callback(data);
                EA.Twitter.hideIndicator();
            }
        });
    },

    getTopReplies: function(callback) {
        EA.Twitter.pageNumber = 2;
        EA.Twitter.stopPoller();
        EA.Twitter.showIndicator();

        $j('#topReplies .moreResults').show();
        $j('#topReplies .endOfResults').hide();

        $j.ajax({
            type: "POST",
            dataType: "html",
            url: "twitter!getPostsLeaderboard",
            data: "page=1",
            success: function (data, textStatus) {
                callback(data);
                EA.Twitter.hideIndicator();
            }
        });
    },

    getTopUsers: function(callback) {
        EA.Twitter.pageNumber = 2;
        EA.Twitter.stopPoller();
        EA.Twitter.showIndicator();

        $j('#topUsers .moreResults').show();
        $j('#topUsers .endOfResults').hide();

        $j.ajax({
            type: "POST",
            dataType: "html",
            url: "twitter!getUsersLeaderboard",
            data: "page=1",
            success: function (data, textStatus) {
                callback(data);
                EA.Twitter.hideIndicator();
            }
        });
    }
};

$j(document).ready(EA.Twitter.init);