<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<!--

* * * * * * * * * * * * * * * * * * * * *

Got a cause and a website? Make a gadget.
http://www.google.com/electionstools2008

* * * * * * * * * * * * * * * * * * * * *

-->
<ModulePrefs title="Elections 2008 from Google" width="300" height="362" scrolling="false"
thumbnail="http://igoogmegagadget.googlepages.com/thumb.png"
screenshot="http://igoogmegagadget.googlepages.com/thumb2.jpg"
category="politics"
author="Google"
author_email="electionsgadget@gmail.com"
author_affiliation="Google, Inc."
description="Keep up-to-date with latest news, maps, videos and blog posts from the campaign trail -- all from your iGoogle page."
author_location="Mountain View, CA">
<Require feature="setprefs"/>
<Require feature="flash" />
<Require feature="analytics"/>
</ModulePrefs>
<UserPref name='e2008prefs' default_value='' datatype="hidden"/>
<UserPref name='sawNewCandidates' default_value='0' datatype="hidden"/>
<UserPref name='lastTab' default_value='' datatype="hidden"/>
<UserPref name='gadgetInitAdd' default_value='0' datatype="hidden"/>
<Content type="html">
<![CDATA[
<style>

* { font-family: arial; color:#666667; }

a { color: #0000cc }

.contentMaster {
  float: left;
  display: inline;
  width: 300px;
  min-height: 100%;
  margin: 0;
  padding: 0;
}

.redFont {
  color: #790026;
}

.minImage {
  width: 70%;
}

.bottom_banner {
  font-size: 10pt;
  text-align: center;
  background-color: #f4f4f4;
  position: relative;
  bottom: 0px;
}

.contentBox {
  display: none;
  text-align: left;
  margin: 0;
  position:relative;
  top: 0px;
  left: 0px;
}

.tabs {
  width:58px;
  height:17px;
  float:left;
  font-size:8pt;
  text-align:center;
  valign:bottom;
}

</style>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAN4OnZlJ_Emy8iKtYDx0QchTRERdeAiwZ9EeJWta3L_JZVS0bOBQ-usJDSzwE1rJddXhc3pT-pKhR6Q"
type="text/javascript"></script>
<script type="text/javascript">

// ***************************************
  var kBasePath = "./modules/elections/mega_gadget_content/";
//  var kBasePath = "http://igoogmegagadget.googlepages.com/";
// ***************************************

var kImg = {top: 'top4.jpg', top_promo:'top5-promo2.jpg', tab_open: 'tab_open2.jpg', tab_closed: 'tab_closed2.jpg',
    arrow_left: 'arrow_left.jpg', arrow_right: 'arrow_right2.jpg', drop_shadow_video: 'drop_shadow_video.jpg',
    background_tabs: 'background-tabs.jpg', plus: 'plus.jpg', moins: 'moins.jpg', blogs_border: 'blogs_border.jpg'};
var kTabs = ['Videos', 'News', 'Maps', 'Blogs', 'Candidates']
var kNeutralFeed = 'citizentube';
var gVideosFeeds = [];
var gVideos = [];
var gSelectedTab = null;
var gFirstVideoPlayerLoad = true;

var kMonths = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var kSlateFeed = "http://mapthecandidates.com/googlexml/";
var kBlogsFeed = 'hl=en&ctz=480&c2coff=1&as_epq=&as_oq=&as_eq=&as_drrb=q&as_qdr=a&as_mind=1&as_minm=1&as_miny=2000&as_maxd=15&as_maxm=11&as_maxy=2007&lr=&safe=active&q=%22Chuck+Baldwin%22+OR+%22Bob+Barr%22+OR+%22John+McCain%22+OR+%22Cynthia+McKinney%22+OR+%22Ralph+Nader%22+OR+%22Barack+Obama%22&ie=utf-8&num=10&output=rss'

var kCand = {
  'Chuck Baldwin': {yt: 'officialbaldwin2008', p: 'i', blog: 'hl=en&c2coff=1&lr=&safe=active&q=%22Chuck+Baldwin%22&ie=utf-8&num=10&output=rss'},
  'Bob Barr': {yt: 'BobBarr2008', p: 'i', blog: 'hl=en&c2coff=1&lr=&safe=active&q=%22Bob+Barr%22&ie=utf-8&num=10&output=rss'},
  'John McCain': {yt: 'JohnMcCaindotcom', p: 'r', blog: 'hl=en&c2coff=1&lr=&safe=active&q=%22John+McCain%22&ie=utf-8&num=10&output=rss'},
  'Cynthia McKinney': {yt: 'RunCynthiaRun', p: 'i', blog: 'hl=en&c2coff=1&lr=&safe=active&q=%22Cynthia+McKinney%22&ie=utf-8&num=10&output=rss'},
  'Ralph Nader':  {yt: 'votenader08', p: 'i', blog: 'hl=en&c2coff=1&lr=&safe=active&q=%22Ralph+Nader%22&ie=utf-8&num=10&output=rss'},
  'Barack Obama': {yt: 'BarackObamadotcom', p: 'd', blog: 'hl=en&c2coff=1&lr=&safe=active&q=%22Barack+Obama%22&ie=utf-8&num=10&output=rss'}};

var kCandNumber = 0;
var news_bottom_banner;
var blogs_banner;

var gBlogsFeeds = [];
var gBlogsData = {};
var gBlogsState = [];
var gPrefs = [];
var kBaseBlogURL = 'http://blogsearch.google.com/blogsearch_feeds?';
var gVideoPlaying = 0;
var gFirstVideoLoad = true;
var prefs;
var playVideoTimeout;
var gCurrVideoIdx = 0;
var gCurrAutoPlayIdx = 0;
var gMapObj;
var gMapBaseIcon;
var gBlogRefreshingTimeout;
var gAnalytics = "UA-18009-2";
var gTrackedLastTab;
var gTrackedLastTabLoadtime;

var isIE = navigator.userAgent.indexOf('MSIE') != -1;

function onLoad()
{
  for(var i in kCand)
    kCandNumber++;

  for(var i in kImg)
    kImg[i] = kBasePath + kImg[i];

  prefs = new _IG_Prefs();

  initCandidates();

  gPrefs = prefs.getString('e2008prefs');

  if(gPrefs == "")
    gPrefs = [];
  else
    gPrefs = gPrefs.split(',');

  var defaultTab = prefs.getInt('lastTab') || 4;
  var sawNewCandidates = prefs.getInt("sawNewCandidates") != 0;
  if (!sawNewCandidates) {
    prefs.set("sawNewCandidates", 1);
  }

  if(gPrefs.length == 0 || !sawNewCandidates)
  {
    // check all the candidate boxes and show them to the user so
    // she can uncheck if she likes
    defaultTab = 4;
    _gel('checkAll').checked = true;
    checkAll();
  } else {
    for(var i = 0; i < gPrefs.length; i++)
    {
      if(!_gel('checkbox_' + gPrefs[i])) {
        continue;
      }

      _gel('checkbox_' + gPrefs[i]).checked = true;
    }

    scanCheckBoxes();
  }

  _gel('video_selector_right_img').src = kImg['arrow_right'];
  _gel('video_selector_right_img').onclick = function() { selector(1) };
  _gel('video_selector_right_img').style.cursor = "pointer";
  _gel('video_selector_right_img').style.top = (isIE ? '-19' : '-3') + 'px';

  _gel('video_selector_left_img').src = kImg['arrow_left'];
  _gel('video_selector_left_img').onclick = function() { selector(0) };
  _gel('video_selector_left_img').style.cursor = "pointer";
  _gel('video_selector_left_img').style.top = (isIE ? '-19' : '-3') + 'px';

  //_gel('tabs').style.background = 'url('+ kImg['background_tabs'] +')';


  initTabs(kTabs[defaultTab]);

  var dateNow = new Date();
  dateNow = dateNow.getTime();

  var topHeader;

  if(prefs.getInt("gadgetInitAdd") != 0 && prefs.getInt("gadgetInitAdd") + 86400 * 1000 < dateNow)
  {
    topHeader = kImg.top;
  }
  else
  {
    if(prefs.getInt("gadgetInitAdd") == 0)
      prefs.set("gadgetInitAdd", dateNow);

    topHeader = kImg.top_promo;
  }

  _gel('topImg').src = topHeader;

    onResize();
    window.onresize = onResize;
}

function GetWindowSize()
{
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement &&
      ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }

  return {'width' : myWidth, 'height' : myHeight};
}

function $(id) {
 return document.getElementById(id);
}

function onResize() {
 var dim = GetWindowSize();
 var w = dim.width;
 $('content').style.width = w-2 + 'px';
 $('contentMaster').style.width = w-2 + 'px';
 if (!isIE)
  $('contentheader').style.width = w-2 + 'px';
 $('content_Blogs').style.width = w + 'px';
 $('blogs_border').style.width = w - 3 + 'px';
 $('blogs_data').style.width = w - 7 + 'px';
 $('tabs').style.left = w / 2 - 298 /2 + 'px';
 $('tabcontainer').style.width = w-2 + 'px';
 if (isIE) {
  if (w % 2 == 0)
   $('topright').style.right = '-2px';
  else
   $('topright').style.right = '-3px';
 } else {
  $('topright').style.right = '0px';
 }
}

function initTabs(selected) {
  var out = "";

  for(var i in kTabs)
  {
    var tab_type = 'tab_closed';
    var tab_caption = '<font id="tab_text_'+ kTabs[i] +'" style="color:#000000">'+ kTabs[i] +'</font>';
    if (kTabs[i] == selected)
    {
      tab_caption = '<font id="tab_text_'+ kTabs[i] +'" style="color:#790026">'+ _hesc(kTabs[i]) +'</font>';
      tab_type = 'tab_open';
      gSelectedTab = selected;
      eval('doActionTab_' + selected + '();');
      _gel('content_' + selected).style.display = 'block';
    }
    out += '<div onclick="refreshTabs(\''+ kTabs[i] +'\');" id="tabs_'+ i +'" class="tabs" style="cursor:pointer;background: url('+kImg[tab_type]+')">';
    out += "<div style='margin-top:3px;font-size:10px;'>" + tab_caption + "</div>";
    out += '</div>';
  }

  _gel('tabs').innerHTML = out;
}

function refreshTabs(selected)
{
  if (gSelectedTab == selected) { return; }

  if (selected != 'Videos')
    _gel('video_player').innerHTML = '';

  if (selected == 'Candidates') {
    _gel('bottom_banner').innerHTML = '';
    _gel('bottom_banner').style.display = 'none';
  } else {
    _gel('bottom_banner').style.display = 'block';
  }

  for(var i in kTabs)
  {
    var tab_type = 'tab_closed';
    _gel('tab_text_' + kTabs[i]).style.color = '#000000';
    if (kTabs[i] == selected) {
      tab_type = 'tab_open';
      _gel('tab_text_' + kTabs[i]).style.color = '#790026';
    }
    _gel('tabs_' + i).style.background = 'url('+ kImg[tab_type] +')';
  }

  if (gSelectedTab != null)
    _gel('content_' + gSelectedTab).style.display = 'none';

  eval('doActionTab_' + selected + '();');
  _gel('content_' + selected).style.display = 'block';
  gSelectedTab = selected;
}

function doActionTab_Blogs()
{
  changeToTab(3);
  urTrack('tab_blogs');
  prefs.set('lastTab', 3);

  _gel('bottom_banner').style.display = "block";

  _gel('bottom_banner').innerHTML = '<a target="_blank" href="http://www.google.com/ig/directory?hl=en&root=/ig&dpos=top">More political gadgets on iGoogle</a>';

  if(gVideosFeeds.length == 0 || gVideosFeeds.length == kCandNumber)
    _gel('blogs_info').innerHTML = '<center><div style="margin-top:2px;">Featured: Blog entries about all candidates</div></center>';
  else
    _gel('blogs_info').innerHTML = '<center><div style="margin-top:2px;">Featured: Blog entries about your selected candidates</div></center>';

  _gel('bottom_banner').style.top = "2px";

  if(gVideosFeeds.length == 0)
  {
    return;
  }

  loadBlogs();
}

function videoTabSetAllCandidates()
{
  _gel('checkAll').checked = true;

  checkAllCandidates();
  scanCheckBoxes();

  doActionTab_Videos();
}

function doActionTab_Videos()
{
  changeToTab(0);
  urTrack('tab_videos');
  prefs.set('lastTab', 0);

  _gel('bottom_banner').style.display = "none";

  if(gVideosFeeds.length == 0 || gVideosFeeds.length == kCandNumber)
  {
    _gel('bottom_banner_video').innerHTML = '<a onclick="urTrack(\'link_more_candidate_videos_on_yt\')" target="_blank" href="http://www.youtube.com/youchoose">More candidate videos on YouTube</a>';
    _gel('video_info').innerHTML = '<br/><center>Now playing: Videos from all candidates</center>';
  }
  else
  {
    _gel('bottom_banner_video').innerHTML = '<a onclick="urTrack(\'link_more_candidate_videos_on_yt\')" target="_blank" href="http://www.youtube.com/youchoose">More candidate videos on YouTube</a>';
    _gel('video_info').innerHTML = '<br/><center>Now playing: Videos from your selected candidates</center>';
  }

  if(gVideosFeeds.length == 0)
  {
    videoTabSetAllCandidates();
    return;
  }

  if (gFirstVideoLoad == false)
    playVideo(gVideoPlaying, false);

  refreshFeeds();
}

function delayedFetch(feed)
{
  _IG_FetchXmlContent(feed, function(data)
  {
    if (data == null || typeof(data) != "object" || data.firstChild == null)
      return;

    var allItems = data.getElementsByTagName('video');
    for(var j = 0; j < allItems.length; j++) {
      var videoData = getXMLNodes(allItems[j], ['id', 'title', 'upload_time', 'thumbnail_url', 'embed_id', 'author']);
      gVideos.push(videoData);
    }
    gVideos.sort(function(a, b) { return b['upload_time'] - a['upload_time']; });

    updateSelector();
  });
}

function refreshFeeds()
{
  gVideos = [];

  scanCheckBoxes();

//  if(gVideosFeeds.length == kCandNumber)
//    delayedFetch('http://www.youtube.com/api2_rest?method=youtube.videos.list_by_playlist&dev_id=wPps8hRwUdA&page=1&per_page=100&id=95BEAA9C046FEEBB');
//  else
  {
    for(var i = 0; i < gVideosFeeds.length; i++)
    {
      var url = "http://www.youtube.com/api2_rest?method=youtube.videos.list_by_user&dev_id=wPps8hRwUdA&page=1&per_page=100&user="+gVideosFeeds[i];
      delayedFetch(url);
    }
  }
}

function newsTabSetAllCandidates()
{
  _gel('checkAll').checked = true;

  checkAllCandidates();
  scanCheckBoxes();

  doActionTab_News();
}

function doActionTab_News()
{
  changeToTab(1);
  urTrack('tab_news');
  prefs.set('lastTab', 1);

  _gel('bottom_banner').style.display = "block";
  _gel('bottom_banner').innerHTML = '<a onclick="urTrack(\'link_more_election_stories\')" target="_blank" href="http://news.google.com/?ned=us&topic=el">More election stories on Google News</a>';
  if(gVideosFeeds.length == 0)
  {
    newsTabSetAllCandidates();
    return;
  }

  loadNews();
}

function loadNews()
{
  var newsFeedUrl = 'http://news.google.com/news?topic=el&num=10&hl=en&ned=us&ie=UTF-8&output=rss&q=';

  var newsFeedCandidates = [];

  for(var i in kCand)
  {
    if(_gel('checkbox_' + kCand[i]['yt']).checked == true || gVideosFeeds.length == 0)
    {
      var candidateLastName = i.split(" ");
      candidateLastName = candidateLastName[1];
      newsFeedCandidates.push(candidateLastName);
    }
  }

  newsFeedUrl += newsFeedCandidates.join("+OR+");

  _IG_FetchXmlContent(newsFeedUrl, function(data) {
    if (data == null || typeof(data) != "object" || data.firstChild == null)
      return;

    var specificCandidatesChosen = true;
    if(gVideosFeeds.length == 0 || gVideosFeeds.length == kCandNumber)
      specificCandidatesChosen = false;

    var allItems = data.getElementsByTagName('item');
    var content = '<div style="overflow:auto;overflow-x:hidden;height:259px;border:1px solid #a8a8a8">';

    var news_items = {};

    for(var j = 0; j < allItems.length; j++)
    {
      content += '<div>';
      var newsData = getXMLNodes(allItems[j], ['description', 'title', 'link']);
      image = newsData['description'].match(/src=([^ ]+)/);

      content += "<table border=0 cellspacing=0 cellpadding=0 style='widt'>";
      content += "<tr><td width='70' align=center style='width:70px;'>";

      if(image)
      {
        var src = "";

        try {
          src = newsData['link'].match(/url=http:\/\/([^/]+)/)[1].replace(/www\./,"");
        } catch(E) { }

        content += '<div style="font-size:8pt;width:70px;margin-top:5px;overflow:hidden">';
        content += '<img style="height:45px;" src="'+ image[1] +'"><br>';
        var max_length = 10;

        var newsLink = newsData['link'].replace(/.+&url\=http:\/\/([^\/]+).+$/, "http://$1");

        if (src.length > max_length)
          content += '<a onclick="urTrack(\'news_link_thumbnail\')" style="color:#008000" target="_blank" href="'+ newsLink+ '">'+ _hesc(src.substr(0,max_length)) +'...</a>';
        else
          content += '<a onclick="urTrack(\'news_link_thumbnail\')" style="color:#008000" target="_blank" href="'+ newsLink+ '">'+ _hesc(src) +'</a>';
      }
      else
        content += "<div style='width:70px'>&nbsp;</div>";

      content += "</td><td valign=top>";

      var description = newsData['description'].replace(/<br>/g, " ");
      description = description.replace(/<[^>]+>/g, "");
      description = description.replace(/[ ]+/g, " ");
      content += '<div style="padding:6px;padding-top:4px;padding-bottom:4px;margin-right:10px;;font-size:8pt;text-align:left">';

      var title = newsData['title'].replace(/ -.*/, "");
      var body = description;

      body = body.replace(title, "")

      content += '<a onclick="urTrack(\'news_link_article\')" target="_blank" href="'+ newsData['link'] +'">'+ title +'</a> ';
      content += "<span style='color:#000'>"+ body.substr(0,120) + '...' + "</span>";

      content += "</td></tr></table>";

      content += '</div>';
    }

    content += '</div>';

    if(specificCandidatesChosen)
      content += "<center><div style='margin-top:2px;font-size:10px;color:#666667;margin-bottom:0px;'>Featured: News about your selected candidates</div></center>";
    else
      content += "<center><div style='margin-top:2px;font-size:10px;color:#666667;margin-bottom:0px;'>Featured: News about all candidates</div></center>";

    _gel('content_News').innerHTML = content;

    _gel('bottom_banner').style.top = "-3px";
  }, 0);
}

function doActionTab_Candidates()
{
  changeToTab(4);
  urTrack('tab_candidates');

  prefs.set('lastTab', 4);
}

function doActionTab_Maps()
{
  changeToTab(2);
  urTrack('tab_maps');
  prefs.set('lastTab', 2);
    var out = '<div style="padding: 2px; font-size: 12px; font-weight:bold;color:#790026">Today\'s Campaign Stops</div>';
  out += "<div id='mapDiv' style='height:214px;width:100%;'></div>";
  out += "<center><div style='margin-top:3px;font-size:10px;font-weight:bold;color:#790026'>Zip code or address: ";
  out += "<input type=text style='width:80px;font-size:11px' id='mapZoomInput' onkeydown='return mapInputValidate(event)'> ";
  out += "<input type=submit onclick='mapZoomToZip()' value='Go'></div>";

  if(gVideosFeeds.length == 0 || gVideosFeeds.length == kCandNumber)
  {
    out += "<div style='margin-top:5px;font-size:9px;color:#666667'>Mapped: Stops by all candidates, courtesy of ";
    out += "<a href='http://www.slate.com' target='_blank'>Slate.com</a></div>";
  }
  else
  {
    out += "<div style='margin-top:5px;font-size:9px;color:#666667'>Mapped: Stops by selected candidates, courtesy of ";
    out += "<a href='http://www.slate.com' target='_blank'>Slate.com</a></div>";
  }
    out += '</center>';
  _gel('content_Maps').innerHTML = out;

  setTimeout(initMapDiv, 300);
}

function mapInputValidate(e)
{
  if(e.keyCode == 13)
    mapZoomToZip();

  return true;
}

function mapZoomToZip()
{
  var value = _gel('mapZoomInput').value;

  if(value == "")
  {
    gMapObj.setCenter(new GLatLng(40, -95), 3);
    return;
  }

  try{
  var geocoder = new GClientGeocoder();
  } catch(E) { return; }

  if(!geocoder)
    return;

  geocoder.getLatLng(value, function(point)
  {
    if(point && gMapObj && _gel('content_Maps').style.display == "block")
      gMapObj.setCenter(point, 5);
  });
}

gMapBaseIcon = new GIcon();
gMapBaseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png"
gMapBaseIcon.shadowSize = new GSize(37, 34);
gMapBaseIcon.iconSize = new GSize(22, 34);
gMapBaseIcon.iconAnchor = new GPoint(11, 34);
gMapBaseIcon.infoWindowAnchor = new GPoint(11, 34);

function initMapDiv()
{
  gMapObj = new GMap2(document.getElementById("mapDiv"));
  gMapObj.setCenter(new GLatLng(40, -95), 3);
  gMapObj.addControl(new GSmallMapControl());


  _IG_FetchXmlContent(kSlateFeed, function(data)
  {
    if (data == null || typeof(data) != "object" || data.firstChild == null)
      return;

    if(!(gMapObj && _gel('content_Maps').style.display == "block"))
      return;

    var allItems = data.getElementsByTagName('marker');
    var dataAttributes = ['candidate','lat','lon','address','datetime','venue'];
    var today = new Date();

    for(var j = 0; j < allItems.length; j++)
    {
      var thisMarker = {};

      for(var currAttrIdx = 0; currAttrIdx < dataAttributes.length; currAttrIdx++)
        thisMarker[dataAttributes[currAttrIdx]] = allItems[j].getAttribute(dataAttributes[currAttrIdx]);

      var showCand = false;

      for(var currCand in kCand)
      {
        if(currCand == thisMarker.candidate)
        {
          if(_gel('checkbox_' + kCand[currCand]['yt']).checked == true || gVideosFeeds.length == 0)
            showCand = true;

          break;
        }
      }

      if(!showCand)
        continue;

      thisMarker.lat = parseFloat(thisMarker.lat);
      thisMarker.lon = parseFloat(thisMarker.lon);

      var markerDate = /^([0-9]{4})-([0-9]{2})-([0-9]{2})/.exec(thisMarker.datetime);

      if(markerDate.length != 4)
        continue;

      markerDate[1] = parseInt(markerDate[1].replace(/^0/, ""));
      markerDate[2] = parseInt(markerDate[2].replace(/^0/, ""));

      if(!(markerDate[1] == today.getFullYear() && markerDate[2] == (1 + today.getMonth())
        && parseInt(markerDate[3]) == today.getDate()))
        continue;

      var markerHtml = "<div style='font-size:11px;color:black;width:180px'>";
      markerHtml += "<div style=''>"+thisMarker.candidate+"</div>";
      markerHtml += "<div style='font-size:13px;font-weight:bold'>"+thisMarker.venue+"</div>";
      markerHtml += "<div style='font-style:italic'>"+thisMarker.address+"</div>";
      markerHtml += "<div>"+ kMonths[markerDate[2] - 1]  +". "+ markerDate[3] +', '+ markerDate[1]  +"</div>";
      markerHtml += "</div>";

      var iconPath = kBasePath + "markers/" + thisMarker.candidate.replace(" ", "-");
      iconPath = iconPath.toLowerCase() +"-marker.png";

      var marker = createMarker(new GLatLng(thisMarker.lat, thisMarker.lon), iconPath, markerHtml);
      gMapObj.addOverlay(marker);
    }
  }, 3600);
}

var icons = {};

function createMarker(point, iconPath, html)
{
  if(!gMapBaseIcon)
    return;

    if (typeof icons[iconPath] == 'undefined')
    {
      icons[iconPath] = new GIcon(gMapBaseIcon);
      icons[iconPath].image = iconPath;
    }
    letteredIcon = icons[iconPath];

  var marker = new GMarker(point, {icon: letteredIcon});

  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(html);
  });

  return marker;
}

function initCandidates()
{
  var content = '';
  for (var i in kCand)
  {
    content += '<input type="checkbox" id="checkbox_'+ kCand[i].yt +'" onclick="scanCheckBoxes();"> <span style="color:#666667">' + i + '</span><br>';
  }
  _gel('candidates').innerHTML = content.substr(0, content.length-4);

  return;
}

function scanCheckBoxes()
{
  var t_gVideosFeeds = [];
  var t_gBlogsFeeds = [];
  gPrefs = [];
  var allChecked = true;

  for (var i in kCand) {
    if (_gel('checkbox_' + kCand[i].yt).checked == true)
    {
      t_gVideosFeeds.push(kCand[i].yt);
      t_gBlogsFeeds.push(kCand[i].blog)
      gPrefs.push(kCand[i].yt);
    } else {
      allChecked = false;
    }
  }

  _gel('checkAll').checked = allChecked;

  prefs.set("e2008prefs", gPrefs.join(','));

  gVideosFeeds = t_gVideosFeeds;
  gBlogsFeeds = t_gBlogsFeeds;
}

function checkAll()
{
  checkAllCandidates();
  scanCheckBoxes();
  if (_gel('checkAll').checked == true) {
    news_bottom_banner = '<a target="_blank" href="http://news.google.com">More election stories on Google News</a>';
    blogs_banner = '<a target="_blank" onclick="urTrack(\'link_more_election_blogs_and_gadgets\')" href="http://www.google.com/ig/">More elections blogs and gadgets on iGoogle</a>';
    gBlogsFeeds = [kBlogsFeed];
  } else {
    news_bottom_banner = '<a target="_blank" href="http://news.google.com/?ned=us&topic=el">Stories about more candidates on Google News</a>';
    blogs_banner = '<a target="_blank" href="http://blogsearch.google.com/">Blog entries on more candidates</a>';
  }
  return;
}

function tpp(l, max) {
  if (l > max)
  {
    return '...';
  } else {
    return '';
  }
}

function expandBlog(id)
{
  if (gBlogs[id]['expanded'] == false)
  {
    description = gBlogs[id]['description'] + '...';
    _gel('expander_' + id).src = kImg['moins'];
    gBlogs[id]['expanded'] = true;
  } else {
    description = gBlogs[id]['description'].substr(0,50) + tpp(gBlogs[id]['description'].length, 50);
    _gel('expander_' + id).src = kImg['plus'];
    gBlogs[id]['expanded'] = false;
  }
  var content = '<a target="_blank" href="'+ gBlogs[id]['link'] +'">'+ _hesc(gBlogs[id]['title']) +'</a> - ';
  content += "<span style='color:#000'>" + description + "</span>";

  var creator = getCreatorFromURL(gBlogs[id]['link']);

  content += ' from <a target="_blank" href="'+ gBlogs[id]['link'] +'">' + creator +'</a>';

  _gel('blog_' + id).innerHTML = content;
}

function getCreatorFromURL(url)
{
  var creator = url.replace(/^http:\/\/([^\/]+).*$/, "$1");

  if(creator.length)
  {
    creator = creator.split('.');
    creator = creator.slice(creator.length - 2).join('.');
  }
  else
    creator = "";

  return creator;
}

function refreshBlogs()
{
  if(gBlogRefreshingTimeout)
    clearInterval(gBlogRefreshingTimeout);

  gBlogRefreshingTimeout = setTimeout(timedRefreshBlogs, 200);
}

function timedRefreshBlogs()
{
  gBlogs.sort(function(a, b) { return b['ts'] - a['ts']; });
  var content = '';
  for (var i=0; i < gBlogs.length; i++)
  {
    content += '<div style="margin-top:5px;width:100%">'
    content += '<div style="float:left;text-align:top">';
    content += '<img onClick="expandBlog(' + i + ');" id="expander_' + i + '"src="' + kImg['plus'] + '">';
    content += '</div>';
    content += '<div id="blog_'+ i +'" style="margin-left:20px;font-size:9pt;text-align:left">';
    content += '<a onclick="urTrack(\'blogs_link_article\')" target="_blank" href="'+ gBlogs[i]['link'] +'">'+ gBlogs[i]['title']+'</a> - ';
    content += "<span style='color:#000'>"+ gBlogs[i]['description'].substr(0,50) + tpp(gBlogs[i]['description'].length, 50) + '</span>';

    var creator = getCreatorFromURL(gBlogs[i]['link']);

    content += ' from <a target="_blank" href="'+ gBlogs[i]['link'] +'">' + creator +'</a></div>';
    content += '</div>';
  }

  _gel('blogs_data').innerHTML = content;
  return;
}
function getTS(date) {
  date = date.replace(/T|Z/g, " ");
  date = date.replace(/-/g,"/");
  d = new Date(date);
  return d.getTime() / 1000;
}

function loadBlogs()
{
  gBlogs = [];
  _gel('blogs_data').innerHTML = '';
  for (var feed = 0; feed < gBlogsFeeds.length; feed++) {
    var tFeed = kBaseBlogURL + gBlogsFeeds[feed];
    _IG_FetchXmlContent(tFeed, function(data) {
      if (data == null || typeof(data) != "object" || data.firstChild == null)
        return;

      var allItems = data.getElementsByTagName('item');
      var content = '';
      var items = {};
      var m = allItems.length; //Math.min(5,allItems.length);
      for(var j = 0; j < m; j++) {
        var data = getXMLNodes(allItems[j], ['title', 'link', 'description', 'dc:creator', 'creator', 'dc:date', 'date']);
        var date = data['dc:date'] || data['date'];
        var creator = data['dc:creator'] || data['creator'];
        var title = data['title'].replace(/<[^>]+>/g, " ");
        title = title.replace(/[ ]+/g, " ");
        var description = data['description'].replace(/<[^>]+>/g, " ");
        description.replace(/[ ]+/g, " ");
        var t_Data = {'description': description.substr(0,200), 'ts': getTS(date), 'title': title,
            'link': data['link'], 'creator': creator, 'expanded': false };
        gBlogs.push(t_Data);
      }
      refreshBlogs();
    });
  }
}

function checkAllCandidates()
{
  var v = _gel('checkAll').checked;
  for (var i in kCand) {
    _gel('checkbox_' + kCand[i].yt).checked = v;
  }
  scanCheckBoxes();
}

function concatChildValues(node, def)
{
  var value = "";
  var child = node.firstChild;
  var childValue;
  while(child) {
    childValue = child.nodeValue;
    if(childValue) {
        value += childValue;
    }
    child = child.nextSibling;
  }
  if(value == "" && def != undefined) {
    value = def;
  }
  return value;
}

function getXMLNodes(node, xmlItems)
{
  xmlData = {};

  for(var xmlItemIdx = 0; xmlItemIdx < xmlItems.length; xmlItemIdx++)
  {
    var tmp = (node.getElementsByTagName(xmlItems[xmlItemIdx]))[0];
    if(tmp && tmp.firstChild && tmp.firstChild.nodeValue)
      xmlData[xmlItems[xmlItemIdx]] = concatChildValues(tmp);
    else
      xmlData[xmlItems[xmlItemIdx]] = "";
  }

  return xmlData;
}


function selector(way)
{
  if(!way && gCurrVideoIdx == 0)
    return;

  if(way && gCurrVideoIdx + 4 >= gVideos.length)
    return;

  gCurrVideoIdx = ((way)? 1 : -1) + gCurrVideoIdx;

  if (way == 0)
    gVideos.unshift(gVideos.pop());
  else
    gVideos.push(gVideos.shift());

  updateVideosThumbs();
}

function getNbVids() {
  var dim = GetWindowSize();
  var max_vids = Math.floor(dim.width / 80);
  if (gVideos.length < max_vids)
    max_vids = gVideos.length;
  return max_vids;
}

function updateVideosThumbs()
{
    var max_vids = getNbVids();
    var allSelectors = '';
    var w = GetWindowSize().width;

  for (var i = 0; i < max_vids; i++)
  {
    thumb = gVideos[i]['thumbnail_url'];
    var txtalign = '';
    if (i == 0) txtalign = 'left';
    else if (i == max_vids - 1) txtalign = 'right';

    var out = '<span id="video_selector_'+i+'" style="text-align:'+txtalign+';width:58px;height:60px;margin-right: 4px; margin-left:4px;">';
    out += '<img onclick="playVideo(\''+ gVideos[i]['id'] +'\', true);" width=58 height=43 style="cursor:pointer;border:';

    if(gVideos[i].id == gVideoPlaying)
      out += "2px solid #790026;margin:0px;";
    else
      out += '1px solid #666667;margin:1px;';

    out += '" ';
    out += " onmouseover='showVideoThumbHint("+i+")' onmouseout='hideVideoThumbHint()' ";
    out += ' src="'+ thumb +'">';

    if(i == 0)
      out += "<span style='font-size:10px; position: absolute;top: 48px;left:20px;'>newer</span>";
    else if(i == max_vids - 1)
      out += "<span style='font-size:10px; position: absolute;top: 48px;right:"+(20)+"px;'>older</span>";

    out += '</span>';
    allSelectors += out;
//    _gel('video_selector_' + i).innerHTML = out;
  }

    _gel('video_selector_container').innerHTML = allSelectors;
}

function showVideoThumbHint(idx)
{
  _gel('video_thumb_hint').style.top = "257px";

  var left = 64 * idx;

  if(idx == 0)
    left = 18;
  else if(idx == 3)
    left = 140;

  _gel('video_thumb_hint').style.left = left + "px";
  _gel('video_thumb_hint').innerHTML = gVideos[idx]['title'];
  _gel('video_thumb_hint').style.display = "block";
}

function hideVideoThumbHint()
{
  _gel('video_thumb_hint').style.display = "none";
}

function updateSelector() {

  updateVideosThumbs();

  if (gVideos.length == 0)
  {
    for (var i = 0; i < 4; i++)
      _gel('video_selector_' + i).innerHTML = '';
  } else
  {
    playVideo(gVideos[0]['id'], false);
    gFirstVideoLoad = false;
  }
}

function playVideo(id, autoplay)
{
  if(playVideoTimeout)
    clearTimeout(playVideoTimeout);

  playVideoTimeout = setTimeout(function()
  {
    timedOutPlayVideo(id, autoplay);
  }, 300);
}

function timedOutPlayVideo(id, autoplay)
{
  gVideoPlaying = id;
    var dim = GetWindowSize();
  var videoW = dim.width;
  var videoH = 202;

  var url = 'http://www.youtube.com/v/'+ id + ((autoplay)? '&autoplay=1':'');
  //    url += '&enablejsapi=1&playerapiid=videoplayer';

  _IG_EmbedFlash(url, 'video_player', {width:videoW,height:videoH, 'AllowScriptAccess' : 'always', 'id' : 'videoplayer'});

  var nbVids = getNbVids();

  for(var i = 0; i < Math.min(gVideos.length, nbVids); i++)
  {
    if(gVideos[i].id == gVideoPlaying)
      _gel('video_selector_'+i).firstChild.style.border = "2px solid #790026";
    else
      _gel('video_selector_'+i).firstChild.style.border = "1px solid #666667";
  }
}

function urTrack(evt)
{
  _IG_Analytics(gAnalytics, "/mega-gadget/"+evt);
}

function changeToTab(newTabIdx)
{
  if(gTrackedLastTab == newTabIdx)
    return;

  if(gTrackedLastTab == 4)
    urTrack("number_of_candidates_"+gVideosFeeds.length);

  var newTime = new Date();
  newTime = newTime.getTime();

  if(!gTrackedLastTab)
  {
    gTrackedLastTab = newTabIdx;
    gTrackedLastTabLoadtime = newTime;
    return;
  }

  urTrack('time_per_tab_'+gTrackedLastTab+'_'+(newTime - gTrackedLastTabLoadtime));

  gTrackedLastTab = newTabIdx;
  gTrackedLastTabLoadtime = newTime;
}

_IG_RegisterOnloadHandler(onLoad);
</script>

<center>
<div id='content' style='border: #cbc9ca 1px solid;width:100%;height:360px'>
<div id="contentheader" style="width:100%; background: url('/ig/modules/elections/mega_gadget_content/topline2.jpg') repeat-x; height: 43px;
position:absolute; top:1px; left:1px;">
<img src='' id=topImg style='height:43px; position: absolute; top: 0px; left: 0px;'>
<img id="topright" src='/ig/modules/elections/mega_gadget_content/topright4.jpg' style='position: absolute; top: 0px; right: 0px;'>
</div>

  <div style="height:43px;">&nbsp</div>
  <div id="tabcontainer" style="background:#eae8e9; height: 17px; position:relative;top:-1px;"><span id='tabs' style='height:17px;left:33px;background:#eae8e9; position: absolute;'></span></div>
  <div id='contentMaster' class="contentMaster">
    <div class="contentBox" id="content_Videos" style="height:300px">
      <div id="video_player_master" style="width:100%;height:202px">
        <div id="video_player" style="position:relative;top:8px;left:13px;"></div>
      </div>
      <div id="video_selector" style="position:relative;top:13px;height:40px; width: 100%;">
      <center>
        <img src="" id='video_selector_left_img' style="position: relative;">
                    <span id="video_selector_container"></span>
        <img src="" id='video_selector_right_img' style="position: relative;">
      </center>
      </div>
      <div id="video_info" style="position:absolute;top:256px;left:0px;text-align:center;font-size:8pt;text-align:center;width:100%;color:#666667;"></div>
      <div id="bottom_banner_video" class="bottom_banner" style="position:absolute;bottom:0px;z-index:90;width:100%;height:16px"></div>
      <div id='video_thumb_hint' style='z-index:100;position:absolute;display:none;background-color:white;border:1px solid #666667;width:130px;padding:1px;font-size:10px;'></div>
    </div>
    <div class="contentBox" id="content_News" style="margin-top:5px;height:280px;width:100%;overflow:hidden;text-valign:top;">
    </div>
    <div class="contentBox" id="content_Maps" style="margin-top:5px;height:280px;width:100%;overflow:hidden;text-valign:top;">
    </div>
    <div class="contentBox" style="font-size:10pt;text-align:left;text-valign:top" id="content_Candidates">
      <div style="text-align:center; width: 100%;margin-top:15px;margin-bottom:5px">Pick the candidates you want to follow:</div>
            <center>
      <div style="width:260px;background-color:#f4f4f4; text-align: left;">
        <div id="candidates" style="background-color:#f4f4f4;float:left;width:260px;height:170px">
        </div>
        <center><span style='color:#000'><input type="checkbox" id="checkAll" onclick="checkAll();"/>Select All</span> (restore original settings)</center>
      </div>
            </center>
      <div style="position:relative;margin-top:5px;margin-bottom:5px">
      <center><font style="font-size:8pt">*Your candidates' results will be viewed on all tabs</font></center>
      </div>
    </div>
    <div class="contentBox" id="content_Blogs" style="width:100%;height:280px">
      <div id="blogs_border" style="position:relative;top:8px;left:0px;width:288px;height:255px;border:1px solid #a8a8a8">
        <div id="blogs_data" style="width:284px;height:255px;padding-left:4px;overflow:auto;overflow-x:hidden;text-valign:top;"></div>
      </div>
      <div id="blogs_info" style="position:absolute;top:266px;text-align:center;font-size:8pt;text-align:center;height:20px;width:100%"></div>
    </div>
  </div>
</div>
</center>

]]>
</Content>
</Module>
