
// ---------------
// Settings
// ---------------

// object to hold all the settings
settings = {};

// content feed
settings.server = 'amd.feedmagnet.com';
settings.groups = ['amd-game'];

// output settings
settings.output_el = '.fm-enclosure';
settings.grid_width = 200;
settings.grid_height = 200;
settings.grid_margin = 10;



// --------------------------------------------
// Function to convert an update into HTML
// --------------------------------------------

// shorten text based on a length limit
var shorten_text = function(text, len) {
    if (text.length > len) {
        return text.substr(0, len - 3) + '...';
    } else {
        return text;
    }
};

// reusable credits snippet
var credits = function(_, update) {
    var html = '<div class="fm-avatar"><img src="' + update.data.author.avatar + '"/></div>';
    if (update.data.author.profile) {
        html += '<div class="fm-author"><a target="_blank" href="' + update.data.author.profile + '">' + update.data.author.alias + '</a></div>';
    } else {
        html += '<div class="fm-author">' + update.data.author.alias + '</div>';
    }
    if (update.data.permalink) {
        html += '<div class="fm-timestamp"><a target="_blank" href="' + update.data.permalink + '">' + _(update.data.timestamp).pretty_time({'auto': true}) + '</a></div>';
    } else {
        html += '<div class="fm-timestamp">' + _(update.data.timestamp).pretty_time({'auto': true}) + '</div>';
    }
    return html;
};
    
settings.jsonToHTML = function($, _, update, output) {
    
    // determine if this is a featured update and what kind
    var featured = '';
    for (f in settings.featured) {
        if (_.intersect(settings.featured[f], update.data.groups).length) featured = f;
    }
    update.data.featured = (featured == '') ? false : true;
    
    // string that will hold the HTML
    var html = '';

    // test to see if an update is a photo
    var is_photo = function(update) {
        for (var i = 0; i < update.data.photos.length; i++) {
            if (update.data.photos[i].role == 'photo') return true;
        }
        return false;
    };
    
    // pick a random shade of grey
    var colors = ['222', '242424', '2b2b2b', '333'];
    color = colors[Math.floor(Math.random() * colors.length)];

    // photo updates
    if (is_photo(update)) {
    
        // photos are always 2x1
        update.data.grid_size = {'width': 2, 'height': 1};
    
        // build the HTML
        html += '<div class="fm-block">';
        html += '   <div class="fm-content fm-photo">';
        var photo;
        for (var i = 0; i < update.data.photos.length; i++) {
            photo = update.data.photos[i];
            
            if (photo.role == 'photo') {
                html += '<a target="_blank" href="' + update.data.permalink + '"><img src="' + photo.local_url + Math.round((update.data.grid_size.width * output.grid_width) + (update.data.grid_size.width - 1) * output.grid_margin) + '/' + Math.round((update.data.grid_size.height * output.grid_height) + (update.data.grid_size.height - 1) * output.grid_margin) + '/exact" /></a>';
                break;
            }
        }
        update.data.text = shorten_text(update.data.text, 120);
        html += '   <div class="fm-text"><a href="' + update.data.author.profile + '">' + update.data.author.alias + '</a>: ' + _(update).format_text() + '<br/><a class="fm-timestamp" href="' + update.data.permalink + '">' + _(update.data.timestamp).pretty_time() + '</a></div>';
        html += '   </div>';
        html += '   <div class="fm-content fm-channel-icon"><img src="http://display.feedmagnet.com/assets/img/channel-icons/light/' + photo.origin + '.png" /></div>';
        html += '</div>';

    // articles (blog posts)
    } else if (update.data.classification == 'article') {
    
        // articles are always double-wide
        update.data.grid_size = {'width': 2, 'height': 1};
        
        // trim down the length of the preview text, if it is too long
        if (update.data.teaser.length > 350) update.data.teaser = update.data.teaser.substr(0, 355) + '...';
        
        // build the HTML
        html += '<div class="fm-block fm-article">';
        html += '   <div class="fm-info">';
        html += '       <div class="fm-author">' + update.data.author.alias + '</div>';
        html += '       <div class="fm-timestamp">' + _(update.data.timestamp).pretty_time() + '</div>';
        html += '   </div>';
        html += '   <div class="fm-title">' + shorten_text(update.data.text, 60) + '</div>';
        html += '   <div class="fm-text">' + shorten_text(update.data.teaser, 220) + '</div>';
        html += '   <div class="fm-content fm-channel-icon"><img src="http://display.feedmagnet.com/assets/img/channel-icons/light/' + update.data.channel + '.png" /></div>';
        html += '   <div class="fm-link"><a href="' + update.data.links[0].short_url + '" target="_blank">Full Article</a></div>';
        html += '</div>';
    
    // videos
    } else if (update.data.classification == 'video' || update.data.classification == 'videoblurb') {
        
        // videos are always 2x2
        update.data.grid_size = {'width': 2, 'height': 2};
    
        // build the HTML
        html += '<div class="fm-block" style="background: #' + color + ';">';
        html += '   <div class="fm-content fm-video">';
        html += '       <div class="fm-player">' + update.data.videos[0].code + '</div>';
        html +=         credits(_, update);
        update.data.text = shorten_text(update.data.text, 120);
        html += '       <div class="fm-text">' + _(update).format_text() + '</div>';
        html += '   </div>';
        html += '   <div class="fm-content fm-channel-icon"><img src="http://display.feedmagnet.com/assets/img/channel-icons/light/' + update.data.videos[0].origin + '.png" /></div>';
        html += '</div>';
        
    // standard text updates (mostly Tweets)
    } else {
    
        // standard updates are 1x1
        update.data.grid_size = {'width': 1, 'height': 1};
        
        // build the HTML
        html += '<div class="fm-block fm-blurb' + featured + '" style="background: #' + color + ';">';
        html += '   <div class="fm-content">';
        html +=         credits(_, update);
        html += '       <div class="fm-text">';
        update.data.original_text = shorten_text(update.data.original_text, (update.data.teaser) ? 100 : 150);
        if (update.data.text) html += _(update).format_text();
        if (update.data.text && update.data.teaser) html += ' | ';
        if (update.data.teaser) html += shorten_text(update.data.teaser, 50);
        html += '       </div>';
        if (update.data.links.length) html += '<div class="fm-link"><a href="' + update.data.links[0].short_url + '" target="_blank">' + shorten_text(update.data.links[0].domain, 20) + '</a></div>';
        html += '   </div>';
        html += '   <div class="fm-content fm-channel-icon"><img src="http://display.feedmagnet.com/assets/img/channel-icons/light/' + update.data.channel + '.png" /></div>';
        html += '</div>';
    }
    
    return html;
    
};

// -------------------
// Load FeedMagnet
// -------------------

var ready = function(fx) {
    if (typeof $FM !== 'undefined' && typeof $FM.ready === 'function') { $FM.ready(fx); }
    else { window.setTimeout(function() { ready.call(null, fx); }, 50); }
};
var fmjs = document.createElement('script');
fmjs.src = ('https:' === document.location.protocol ? 'https://' : 'http://') + settings.server + '/embed.js';
fmjs.setAttribute('async', 'true'); document.documentElement.firstChild.appendChild(fmjs);
ready(function($, _) {
    
    // create the feed object to pull in new updates
    var feed = $FM.Feed(settings.groups);
    
    // create the output element object to display the updates pulled in
    var output = $FM.Element(settings.output_el).display(feed);
    output.grid_width = settings.grid_width;
    output.grid_height = settings.grid_height;
    output.grid_margin = settings.grid_margin;
    
    // set up the grid (runs on page load and on resize)
    output.setup = function() {

        // get the width
        this.width = $(this.selector).width();

        // reset the height value
        this.height = 0;
        
        // figure out how many columns we should have
        this.columns = Math.round((this.width + 10) / 220);
        
        // create a grid object to determine where everything should go
        this.grid = new Grid(this.columns);
        
        // add the load more button
        this.e.append('<a class="fm-load-more" href="#">Load More</a>');
        $('.fm-load-more').click(function(ev) {
            ev.preventDefault();
            feed.more();
        });
                        
    };

    // initialize the page
    output.setup();
        
    // convert json for each update into HTML
    feed.connect('new_update', function(self, data) {
        data.update.html = settings.jsonToHTML($, _, data.update, output);
    });
        
    // move the loading more graphic to the next opening
    output.position_loadmore = function() {
        pos = this.grid.nextOpening();
        var self = this;
        $('.fm-load-more').fadeOut(function() {
            $(this).css({
                'top': pos.row * (self.grid_height + self.grid_margin),
                'left': pos.col * (self.grid_width + self.grid_margin)
            }).fadeIn();
        });
    };
    
    // add a new update to the grid and position it on the page
    output.place_update = function(update, resize) {
        var pos = this.grid.addItem(update.data.grid_size);
        
        // as we get new updates, keep expanding the height of the output object
        // to ensure it is big enough to encompass the updates in it
        update._el.css({
            'top': pos.row * (this.grid_height + this.grid_margin),
            'left': pos.col * (this.grid_width + this.grid_margin),
            'width': this.grid_width * update.data.grid_size.width + (update.data.grid_size.width - 1) * this.grid_margin,
            'height': this.grid_height * update.data.grid_size.height + (update.data.grid_size.height - 1) * this.grid_margin
        });
        var updateBottom = (pos.row * (this.grid_height + this.grid_margin)) + (update.data.grid_size.height * this.grid_height) + (update.data.grid_size.height - 1) * this.grid_margin;
        if (updateBottom > this.height) {
            if (updateBottom > this.height) this.height = updateBottom;
            $(this.selector).css({'height': updateBottom + this.grid_height + this.grid_margin });
        }
        
        // return the bottom of the newly positioned update
        return pos.row * (this.grid_height + this.grid_margin);
        
    };
        
    // process new updates as they are placed in the DOM
    output.connect('updates_placed', {
        'strong': true,
        'callback': function(self, data) {
            
            // place each new update in the grid
            for (i = 0; i < data.new_updates.length; i++) {
                self.place_update(data.new_updates[i]);
            }
            
            // reposition the load more graphic
            self.position_loadmore();
            
            // show new updates
            self.show_next();
                        
        }
    });
    
    // fade in all the updates that are hidden
    output.show_next = function() {
        $(this.selector).find('.fm-update:hidden:first').fadeIn();
        if ($(this.selector).find('.fm-update:hidden').length) {
            var self = this;
            setTimeout(function() {
                self.show_next();
            }, 100);
        }
    };
    
    // finally, go get the latest updates from the feed and display them
    feed.poll({'limit': 20, 'wait': 14});

});

