/*
    File: js/main.js

*/
var brandName = "Chrysler";
var OPML_URL  = 'feeds.xml';

var query, DEBUG, fpk, archive_fpk, archive_feed_ele;

var behaviours = {
    'ul.portalfeed'  : function(ele) { 
        populateFeed(fpk, ele) 
    },
    'ul.archivefeed' : function(ele) { 
        archive_feed_ele = ele;
        populateFeed(archive_fpk, ele);
    },
    'ul.archivetags' : setUpFeedTags
};

var currentPage = "autoshow";
var curSubPage  = "";
var curVehicle  = "brand";
var brand       = brandName.toLowerCase();
            
function buildFeedItemLink(feed, item, lpos_type) {
    
    // Snag the link URL from the feed item.
    var link_url = item['link'];
    
    // Lop off the absolute domain at the front of the URL, add the reader=portal param.
    var as = 'autoshow/';
    var as_pos = link_url.indexOf(as);
    if (as_pos != -1) {
        link_url  = link_url.substring(as_pos + as.length);
        link_url += '&reader=portal';
    }
    
    // Hook up the metrics on-click handler.
    var metrics_pos = feed.metrics_prefix + (++feed.counter);
    
    var popup;
    // If this is a link to a non-brand site, throw into a pop-up
    if (link_url.indexOf('www.'+brand+'.com') == -1){
        popup = true;
    }else{
      popup = false;
    }
    // Build the actual hyper link, with metrics info.
    //var link_name = '&lpos='+escape(metrics_pos)+'&lid='+escape(link_url);
	var link_name = '&lpos='+lpos_type+'&lid='+item['title'];
    //var link = A({'class':'link', 'href':'javascript:trackRSS("'+link_url+'","'+item['title']+ '", "'+lpos_type+'", "'+popup+'" )', 'title':item['title'], 'name':link_name }, item['title']);
    var link = A({'class':'link', 'href':link_url, 'title':item['title'], 'name':link_name, 'target':'_blank'}, item['title']);
      
    if (lpos_type == "archive"){
	    link.onclick = function () {
			_hbSet('lid', item['title']);
			_hbSet('lpos', lpos_type);
			_hbSend();
			//trackRSS(item['title'], lpos_type);
	        //logDebug("Feed click metric ID: "+metrics_pos+" URL: "+link);
	        //_hbLink(link_url, metrics_pos);
	    }
    }

    return link; 
}

function init() {
    // See also: http://dean.edwards.name/weblog/2005/09/busted/
    if (arguments.callee.done) return;
    arguments.callee.done = true;

    // Grab the query params and figure out the debug mode.
    query = parseQueryString(location.search.substring(1));
    DEBUG = (query.debug == '1') ? true : DEBUG;
    if (DEBUG) createLoggingPane(true);

    log("Starting up...");

    // Should we be using preview or production feeds?
    if (query.prod != '1' && location.href.indexOf('preview') != -1) {
        log("Using preview feeds.");
        OPML_URL = 'feeds-preview.xml';
    } else {
        log('Using production snapshot feeds.');
    }
    
    // Construct the portal page feed toolkit instance
    fpk = new FeedPortalKit();
    fpk.MAX_ITEMS        = 15;
    fpk.TIME_DELAY_START = 0;
    fpk.DO_FADE          = (query.dofade == '1');
    fpk.LAST_VIEWED_DATE = new Date();
    
    // Set up the DOM rendering template for the portal page feed items
    fpk.renderFeedItem = function(feed, item, id) {
      var lpos_type;
      (/PR/.test(feed['title'])) ? lpos_type='press_release' : lpos_type='blog_headline';
        var link_ele = buildFeedItemLink(feed, item, lpos_type);
        
        return LI({'class':'item', 'id':id},
                P({'class':'news'}, link_ele),
                ( 
                    (/PR/.test(feed['title'])) ? 
                        '' : 
                        P({'class':'news_header'}, 
                            'From '+item['source']+' on '+
                                Date.strftime('%a, %d %b %Y', item['date'])
                          ) 
                )
            );
    }
    
    // Construct the archive page feed toolkit instance
    archive_fpk = new FeedPortalKit();
    archive_fpk.MAX_ITEMS        = 50;
    archive_fpk.TIME_DELAY_START = 0;
    archive_fpk.DO_FADE          = (query.dofade == '1');
    archive_fpk.LAST_VIEWED_DATE = new Date();
    
    // Set up the DOM rendering template for the archive page feed items
    archive_fpk.renderFeedItem = function(feed, item, id) {
        var link_ele = buildFeedItemLink(feed, item, "archive");
        
        return LI({'class':'item', 'id':id},
                P({'class':'news_header'}, link_ele),
                P({'class':'archive_news'}, item['description']),
                P({'class':'archive_from'}, 'From '+item['source']+' on '+
                        Date.strftime('%a, %d %b %Y', item['date'])
                    )
            );
    }
    
    // Load up the feeds list and signal done loading when ready.
    fpk.loadOPML(OPML_URL, function() {
        fpk.loaded = true; finishInit();
    });
    /*
    // Load up the feeds list and signal done loading when ready.
    archive_fpk.loadOPML(OPML_URL, function() {
        archive_fpk.loaded = true; finishInit();
    });
    */
}

// See also: http://dean.edwards.name/weblog/2005/09/busted/
if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", init, null);
} else {
     addLoadEvent(init);
}

function finishInit() {
    if (!fpk.loaded) return;
    // if (!archive_fpk.loaded) return;

    // HACK: Just reuse the feeds list loaded by the non-archive FPK
    archive_fpk.feeds = fpk.feeds;

    // Register and fire off the behaviors to populate all feed sections.
    Behaviour.register(behaviours);
    Behaviour.apply();
}

function populateFeed(fpk, ele) {
    var ele_title = ele.getAttribute('title');
    ele.setAttribute('title', '');
    
    var parts     = ele_title.split('|');
    var title     = parts[0];
    var limit     = 15;
    if (parts.length > 1) {
        limit = parts[1];
        logDebug("Found limit at "+limit);
    }
    var metrics_prefix = (parts.length > 2) ? parts[2] : 'AEF';
    
    populateFeedByTitle(fpk, ele, title, limit, metrics_prefix, function() {
       // _LP(document.links,1);   
    });
}

function populateFeedByTitle(fpk, ele, title, limit, metrics_prefix, onload_func) {
    if (!limit) limit = 15;

    var feeds = fpk.getFeedsByTitle(title);

    log("Populating feed: '"+title+"'...");
    if (feeds.length) {
        forEach(feeds, function(feed) {
            // HACK: Need a per-feed counter for metrics position tracking.
            feed.counter        = 0;
            feed.metrics_prefix = metrics_prefix;
            
            fpk.loadFeed(feed, ele, true, limit, onload_func);
        });
    }
}

function setUpFeedTags(list) {

    // Clear out all the existing contents of the list.
    while(list.firstChild) 
        list.removeChild(list.firstChild);
        
    // Create feed nav links for each feed in the OPML
    forEach(archive_fpk.feeds, function(feed) {

        // HACK: Lop off the brand name
        var title = feed['title'];
        if (title.indexOf(brandName) != 1) {
            title = title.substring(brandName.length);
        }
        
        // Create the link based on the feed title.
        var link = A({'class':'archive_caps', 'href':'#'}, title);
        
        // Set up the link onclick to swap the visible feed items.
        link.onclick = function() {
            _hbSet('lid', title);
            _hbSet('lpos', 'popular tags');
            _hbSend();
            logDebug("Clicked on "+feed.title);
            
            var curr_feedlink = this.parentNode;

            // Switch the just-clicked feed title indicator to 'loading'
            var spans = curr_feedlink.getElementsByTagName('span');
            if (spans) spans[0].className = 'loading';

            populateFeedByTitle(archive_fpk, archive_feed_ele, feed.title, 100, 'AEF', function() {
                logDebug("Sidenav loaded feed");

                // Set all existing indicators to unselected, except for this one.
                var feedlinks = getElementsByTagAndClassName('li', 'feedlink');
                forEach(feedlinks, function (feedlink) {
                    var spans = feedlink.getElementsByTagName('span');
                    if (spans) {
                        spans[0].className = (feedlink == curr_feedlink) ? 
                            'selected' : 'unselected';
                        logDebug(spans[0].className);
                    }
                });

            });
        };

        var feed_link = LI({'class':'feedlink'},
            SPAN({'class':'unselected'}, ' '),
            link
        );
        
        // Add the link to the list.
        list.appendChild(feed_link);

    });
}

