/*
    File: js/main.js

*/
var brandName = "motorsports";
var OPML_URL  = '/motorsports/feeds.xml';

var query, DEBUG, fpk, archive_fpk, archive_feed_ele;

var behaviours = {
    'ul.portalfeed'  : function(ele) { 
        populateFeed(fpk, ele) 
    },
    'ul.archivetags' : setUpFeedTags,
    
    'ul.archivefeed' : function(ele) { 
        archive_feed_ele = ele;
        if(!checkDeepLink()){
          populateFeed(archive_fpk, ele);
        }
    }
};

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 = '.com';
    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.dodge.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']);
    if(popup){
    var link = A({'class':'link', 'href':link_url, 'title':item['title'], 'name':link_name, 'target':'_blank'}, item['title']);
    }else{
     var link = A({'class':'link', 'href':link_url, 'title':item['title'], 'name':link_name}, item['title']); 
    }
      
    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, "latest_news_headlines");
        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},
                SPAN({'class':'news_header'}, link_ele),
                BR(),
                SPAN({'class':'archive_news'}, item['description']),
                BR(),
                SPAN({'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 allowedFeeds(name){

if(name == "All Stories" ||  name == "Craftsman Truck" || name == "Sprint Cup"){
   return true;
 }
 return false;
}
function setUpFeedTags(list) {

    // Clear out all the existing contents of the list.
    while(list.firstChild) 
        list.removeChild(list.firstChild);
     
    var set_first_selected = true;
    // 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+1);
          }
        //Partial-hack: only display the top level feeds defined below
        if(allowedFeeds(title)){ 
          
          // Create the link based on the feed title.
          var link_id = title.replace(/ /g, "_").toLowerCase();
          if(set_first_selected){
            var link = A({'class':'selected', 'href':'#', 'id':link_id, 'name':link_id}, title);
            set_first_selected = false;
          }else{
            var link = A({'class':'unselected', 'href':'#', 'id':link_id, 'name':link_id}, 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);
			  
			  ///////////////////////////////////////////////////////////////////////////////////////////
			  //// this code was added to change the subhead of the page in accordance with the link ////
			  ///////////////////////////////////////////////////////////////////////////////////////////
			  newTitleVal = title+" HEADLINES";
			  if(title == "All Stories"){
				  newTitleVal = title;
			  }
			  myTargs = document.getElementsByTagName("h2");
			  theLD = 0;
			  for(ld=0;ld<myTargs.length;ld++){
				  theClass = myTargs[ld].getAttribute("class");
				  if(theClass == "grey_headline" || ld == 1){
					  myTargs[ld].firstChild.nodeValue = newTitleVal.toUpperCase();
				  }
			  }
			  //alert(myTargs[1].getAttribute("class"));
			  ///////////////////////////////////////////////////////////////////////////////////////////
			  ///////////////////////////////////////////////////////////////////////////////////////////
			  ///////////////////////////////////////////////////////////////////////////////////////////
			  
			  
              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, 20, '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('a');
                      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);
        }

    });
}

function checkDeepLink(){
  var default_section = unescape(getParameter('section'));
  if(allowedFeeds(default_section)){
    var link_id = default_section.replace(/ /g, "_").toLowerCase();
    var el = document.getElementById(link_id);
    el.onclick();
    return true;
  }
  return false;
}
function trackRSS(url, lid, lpos, newwin){
    _hbSet('lid', lid);
    _hbSet('lpos', lpos);
    _hbSend();
	if(newwin){
		window.open(url, lpos);
	}else{
    	document.location = url;
	}
}

