﻿trendingTopics = function() {

};

trendingTopics.prototype.config = {
    container: '',
    topic: '',
    refresh_url: ''
};

trendingTopics.prototype.getTweets = function() {
    if (this.config.refresh_url == '') {
        this.config.refresh_url = '?q=' + this.config.topic + '&lang=en&count=5';
    }

    var scope = this;
    var ajaxObject = {
        url: '/infosec/trending_topics_json.aspx?json=true&url=' + encodeURIComponent(this.config.refresh_url),
        success: function() {
            scope.getTweetsSuccess.call(scope, arguments[0]);
        }
    };
    cp.ajax.post(ajaxObject);

    setTimeout(function() {
        scope.getTweets.call(scope);
    }, 5000);
};

trendingTopics.prototype.getTweetsSuccess = function(responseObj) {
    var json = eval("[" + responseObj.responseText + "]");
    var resultsLength = (json[0].results.length > 5 ? 5 : json[0].results.length);

    for (var i = 0; i < resultsLength; i++) {
        try {
            var div = [];
            div.push('<div class="tweet"');

            if ((i + 1) == 1) {
                div.push(' style="margin-bottom: 0px; border-bottom: 0px;"');
            }
            div.push('>');
            div.push('<div class="profile-img"><img src="');
            div.push(json[0].results[i].profile_image_url);
            div.push('" /></div>');
            div.push('<div class="info">', json[0].results[i].text, '</div>');
            div.push('<div class="clear"></div>');
            div.push('</div>');
            this.addNewTweet(div.join(''));
        }
        catch (pError) {
        }
    }

    this.config.refresh_url = json[0].refresh_url + '&lang=en';
    var scope = this;
};

trendingTopics.prototype.removeLastChild = function() {
    var scope = this;
    var lastChild = Dom.getLastChild(this.config.container);
    Dom.get(scope.config.container).removeChild(lastChild);
};

trendingTopics.prototype.addNewTweet = function(newTweet) {
    var html = Dom.get(this.config.container);
    html.innerHTML = (newTweet + html.innerHTML);

    var children = Dom.getChildren(this.config.container);
    if (children.length >= 6) {
        for (var i = 5; i < children.length; i++) {
            Dom.get(this.config.container).removeChild(children[i]);
        }
    }
};

trendingTopics.prototype.init = function(container, topic) {
    this.config.container = container;
    this.config.topic = topic;
    this.getTweets();
};
