// Copyright 2009 Google Inc. All rights reserved.

var gbus = {};

/**
 * GBus application object containing all logic for maps data rendering.
 *
 * @param {String} json Maps data in JSON format retrieved from spreadsheets.
 */
gbus.GBus = {
  map : '',
  mapMarkers : [],
  mapHTMLS : [],
  baseIcon : new GIcon(),
  label : '',
  currentPositionProperties : null,
  flag : true,
  params : {
    workSheetId : 'default',
    spreadSheetKey : 't2sjosfs-yTHzLYqDgjyVTg',
    currentBusPositionSpreadSheetKey : 't2sjosfs-yTHzLYqDgjyVTg',
    currentBusPositionWorkSheetId : '3',
    city : 'city',
    cityLatitude : 'latitude',
    cityLongitude : 'longitude',
    distanceTravelled : 'kilometers',
    bytesUsedAtPresentCity : 'bytesused',
    videos : 'videos',
    videoChannel : 'videoschannel',
    photos : 'pictures',
    reachedCityOnDAte : 'date',
    iconType : 'green',
    iconTypeOver : 'orange',
    cityPicture : 'image',
    polyLinePoint : '',
    cityReachedByBus : 'reached',
    orkutcommunity : 'orkutcommunity',
    jsonData : '',
    entry: '',
    count : 0,
    numberOfRowsForLabel : 8,
    numberOfRowsForLabelSecondRow: 16,
    sidebarDIVSecond : null,
    sidebarDIVThree : null,
    blogName: '',
    useSidebar : true,
    mapLatitude: 27.0238036,
    mapLongitude: 74.2179326
  },

  pointDetails: {
    latitude: '',
    longitude: '',
    point: '',
    bounds : new GLatLngBounds()
  },

  markerDetails : {
    markerOpts : {},
    iconCurrentPosition : new GIcon(),
    marker: '',
    polyLineColorForReached: '#0000FF',
    polyLineColorForNotReached: '#FF00FF'
  },

  load : function() {
    gbus.GBus.params.sidebarDIVSecond = document.createElement('div');
    gbus.GBus.params.sidebarDIVThree = document.createElement('div');
    if (GBrowserIsCompatible()) {
      gbus.GBus.map = new GMap2(document.getElementById('map'));
      gbus.GBus.map.addControl(new GSmallMapControl());
      gbus.GBus.map.addControl(new GMapTypeControl());
      gbus.GBus.map.setCenter(new GLatLng(gbus.GBus.params.mapLatitude,
          gbus.GBus.params.mapLongitude), 5);
      gbus.GBus.app.getJSON();
      //gbus.GBus.app.loadFeaturedVideos();
    } else {
      alert('Sorry, Google Maps API is not compatible with this browser');
    }
  },

  /*
   This the main Application object.
   */
  app : {
    /**
     * This function loads the bus route information from
     * spreadsheets(Goolgle Docs).
     */
    getJSON : function() {
      var docsKey = gbus.GBus.params.currentBusPositionSpreadSheetKey;
      var docsSheetId = gbus.GBus.params.currentBusPositionWorkSheetId;
      gbus.GBus.getJSONScriptCurrentPosition = document
          .createElement('script');
      gbus.GBus.getJSONScriptCurrentPosition
          .setAttribute('src', 'http://spreadsheets.google.com/feeds/list' +
                               '/' + docsKey +
                               '/' + docsSheetId +
                               '/public/values?' +
                               'alt=json-in-script&callback=' +
                               'gbus.GBus.app.loadCurrentPositionMapJSON');
      gbus.GBus.getJSONScriptCurrentPosition.setAttribute('id2', 'jsonScript');
      gbus.GBus.getJSONScriptCurrentPosition.setAttribute(
          'type', 'text/javascript');
      document.documentElement.firstChild.appendChild(
          gbus.GBus.getJSONScriptCurrentPosition);
      gbus.GBus.getJSONScript = document.createElement('script');
      gbus.GBus.getJSONScript.setAttribute('src',
          'http://spreadsheets.google.com/feeds/list' +
          '/' +
          gbus.GBus.params.spreadSheetKey +
          '/' +
          gbus.GBus.params.workSheetId +
          '/public/values' +
          '?alt=json-in-script&callback=gbus.GBus.app.loadMapJSON');
      gbus.GBus.getJSONScript.setAttribute('id', 'jsonScript');
      gbus.GBus.getJSONScript.setAttribute('type', 'text/javascript');
      document.documentElement.firstChild.appendChild(gbus.GBus.getJSONScript);
    },

    /**
     * Draws the polyline connecting cities on the maps.
     *
     * @param {GLatLng} previousPoint Start point.
     * @param {GlatLing} presentPoint End point.
     * @param {Boolean} reached True, if bus has reached the city.
     */
    drawPolyLine : function(previousPoint, presentPoint, reached) {
      gbus.GBus.markerDetails.polyline = '';
      gbus.GBus.markerDetails.polylineRed = '';
      if (previousPoint == '')
        gbus.GBus.params.polyLinePoint = presentPoint;
      if (reached == 'yes')
        gbus.GBus.markerDetails.polyline = new GPolyline(
            [previousPoint, presentPoint],
            gbus.GBus.markerDetails.polyLineColorForReached, 4);
      if (reached == 'no') {
        if (gbus.GBus.flag) {
          gbus.GBus.markerDetails.polyline = new GPolyline(
              [previousPoint, gbus.GBus.currentPositionProperties],
              gbus.GBus.markerDetails.polyLineColorForReached, 4);
          gbus.GBus.markerDetails.polylineRed = new GPolyline(
              [gbus.GBus.currentPositionProperties, presentPoint],
              gbus.GBus.markerDetails.polyLineColorForNotReached, 4);
          gbus.GBus.flag = false;
        } else
          gbus.GBus.markerDetails.polyline = new GPolyline(
              [previousPoint, presentPoint],
              gbus.GBus.markerDetails.polyLineColorForNotReached, 4);
      }
      if (gbus.GBus.markerDetails.polylineRed != '')
        gbus.GBus.map.addOverlay(gbus.GBus.markerDetails.polylineRed);
      gbus.GBus.map.addOverlay(gbus.GBus.markerDetails.polyline);
      gbus.GBus.params.polyLinePoint = presentPoint;
    }
  },

  /**
   * Creates a marker on the city and intializes the popup HTML.
   *
   * @param {GLatLng} point The marker geo data.
   * @param {String} title City name for the info popup.
   * @param {String} html Inner contents of the popup.
   * @param {boolean} reached True, if city has been covered in the route.
   * @param {String} image The media link for bus images.
   * @param {String} video The media link for videos.
   * @param {String} album The picassa album link.
   * @param {Number} distanceTravelled Distance travelled by the bus.
   * @param {Number} bytesUsed Bytes used by the internet bus kiosks.
   * @return {Object} The marker created.
   */
  createMarker : function(
      point, title, html, reached, image, video, album, distanceTravelled,
      bytesUsed) {
    gbus.GBus.baseIcon.shadow = 'http://www.google.com/mapfiles/shadow50.png';
    gbus.GBus.baseIcon.shadowSize = new GSize(37, 34);
    gbus.GBus.baseIcon.iconAnchor = new GPoint(9, 34);
    gbus.GBus.baseIcon.infoWindowAnchor = new GPoint(9, 2);
    gbus.GBus.baseIcon.infoShadowAnchor = new GPoint(18, 25);
    gbus.GBus.pointDetails.nIcon = new GIcon(gbus.GBus.baseIcon);
    gbus.GBus.pointDetails.nIcon.imageOut =
    'http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png';
    gbus.GBus.pointDetails.nIcon.imageOver =
    'http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png';
    gbus.GBus.pointDetails.nIcon.image = gbus.GBus.pointDetails.nIcon.imageOut;
    gbus.GBus.markerDetails.markerOpts.icon = gbus.GBus.pointDetails.nIcon;
    gbus.GBus.markerDetails.markerOpts.title = title;
    var marker = new GMarker(point, gbus.GBus.markerDetails.markerOpts);
    gbus.GBus.app.drawPolyLine(gbus.GBus.params.polyLinePoint, point, reached);
    GEvent.addListener(marker, 'click', function() {
      marker.openInfoWindowHtml(html, {
        maxWidth : 200
      });
      gbus.GBus.app.setUpChart(distanceTravelled, bytesUsed, title);
    });
    GEvent.addListener(marker, 'mouseover', function() {
      marker.setImage(marker.getIcon().imageOver);
    });
    GEvent.addListener(marker, 'mouseout', function() {
      marker.setImage(marker.getIcon().imageOut);
    });
    GEvent.addListener(marker, 'infowindowopen', function() {
      marker.setImage(marker.getIcon().imageOver);
    });
    GEvent.addListener(marker, 'infowindowclose', function() {
      marker.setImage(marker.getIcon().imageOut);
    });
    return marker;
  }

};


/**
 * Autoplay delay interval.
 */
gbus.GBus.app.intervalId = '';

/**
 * Number counter for markers in map.
 */
gbus.GBus.app.counter = 0;

/**
 * This method parses the map JSON and extracts contextual data for
 * populating videos, images, stats & route elements.
 *
 * @param {String} json The JSON data recieved from the spreadsheet.
 */
gbus.GBus.app.loadMapJSON = function(json) {
  if (gbus.GBus.params.useSidebar == true) {
    gbus.GBus.params.sidebarDIV = document.createElement('div');
    gbus.GBus.params.sidebarDIV.id = 'sidebarDIV';
  }
  var reached = true;
  var params = gbus.GBus.params;
  for (var i = 0; i < json.feed.entry.length; i++) {
    params.entry = json.feed.entry[i];
    params.jsonData = json;
    if (params.entry['gsx$' + params.city]) {
      gbus.GBus.pointDetails.latitude = parseFloat(
          params.entry['gsx$' + params.cityLatitude].$t);
      gbus.GBus.pointDetails.longitude = parseFloat(
          params.entry['gsx$' + params.cityLongitude].$t);
      gbus.GBus.pointDetails.point = new GLatLng(
          gbus.GBus.pointDetails.latitude, gbus.GBus.pointDetails.longitude);
      params.html = "<div id=''><div id='left-div-popup'><b>" +
                    params.entry['gsx$' + params.city].$t + '</b><br>';

      if (params.entry['gsx$' + params.cityReachedByBus].$t ==
          'yes')
        gbus.GBus.label = gbus.GBus.app.getDisplayFormatDate((
            params.entry['gsx$' + params.reachedCityOnDAte].$t)) +
                          ' ' + gbus.GBus.params.entry['gsx$' + params.city].$t;
      else {
        gbus.GBus.label = gbus.GBus.app.getDisplayFormatDate((
            params.entry['gsx$' + params.reachedCityOnDAte].$t)) +
                          ' ' + params.entry['gsx$' + params.city].$t;
        if (reached == true) { // Next stop
          var nextStop = params.entry['gsx$' + params.city].$t;
          var daysStop = params.entry['gsx$' + 'days'].$t;
          var dateOfArrival = gbus.GBus.app.getDisplayFormatDate(params.
              entry['gsx$' + params.reachedCityOnDAte].$t);
          document.getElementById('c').innerHTML = nextStop + '. Arriving on ' +
                                                   dateOfArrival + ' for ' +
                                                   daysStop + ' days.';

        }
        reached = false;
      }
      if (params.entry['gsx$' + params.distanceTravelled] &&
          reached == true) {
        params.html += 'Kilometers : ' +
                       params.entry[
                           'gsx$' +
                           params.distanceTravelled].$t +
                       '<br/>';
      }
      if (params.entry['gsx$' +
                       params.bytesUsedAtPresentCity] &&
          reached == true) {
        params.html += 'Bytes Used: ' + params.entry['gsx$'
            + params.bytesUsedAtPresentCity].$t + '<br>';
        params.html += "<font class='popUpFont'><a href='" +
                       params.entry['gsx$' + params.videoChannel].$t +
                       "' target='_blank' >Videos</a> &nbsp;" +
                       '&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;' +
                       '&nbsp;&nbsp;&nbsp;&nbsp;' +
                       "<a target='_blank' href='" +
                       params.entry['gsx$'
                           + params.photos].$t +
                       "'>Album</a><br>";
        params.html += "<a href='" +
                       params.entry['gsx$' + params.orkutcommunity].$t +
                       "' target='_blank'>Orkut Community</a><br />&nbsp;" +
                       '</font></div>';
        params.html += '<div id=\'right-div-popup\'><img width=\'70px\'' +
                       'height=\'70px\' src=\'' +
                       params.entry['gsx$' + params.cityPicture].$t +
                       '\' /></div></div';
      } else {
        params.html += 'The Internet Bus will be reaching ';
        params.html += params.entry[
            'gsx$' + params.city].$t;
        params.html += ' on <b>';
        params.html += gbus.GBus.app.getDisplayFormatDate((params.entry[
            'gsx$' + params.reachedCityOnDAte].$t));
        params.html += ' </b> for <b>' + params.entry['gsx$' + 'days'].$t +
                       ' days.</b>';


      }

      if ((params.entry['gsx$' + params.city].$t) == 'Bus is Here') {
        gbus.GBus.markerDetails.marker = gbus.GBus.createMarker(
            gbus.GBus.pointDetails.point, params.entry['gsx$' + params.city].$t,
            params.html, params.entry['gsx$'
            + params.cityReachedByBus].$t, params.entry['gsx$'
            + params.cityPicture].$t, params.entry['gsx$'
            + params.videos].$t, params.entry['gsx$'
            + params.photos].$t,
            + params.entry['gsx$' + params.distanceTravelled].$t,
            + params.entry['gsx$' + params.bytesUsedAtPresentCity].$t
            );
      } else {
        gbus.GBus.markerDetails.marker = gbus.GBus.createMarker(
            gbus.GBus.pointDetails.point,
            params.entry[
                'gsx$' + params.city].$t, params.html,
            params.entry['gsx$'
                + params.cityReachedByBus].$t,
            params.entry['gsx$'
                + params.cityPicture].$t, params.entry['gsx$'
            + params.videos].$t, params.entry['gsx$'
            + params.photos].$t,
            + params.entry['gsx$' + params.distanceTravelled].$t,
            + params.entry['gsx$' + params.bytesUsedAtPresentCity].$t
            );
      }

      gbus.GBus.map.addOverlay(gbus.GBus.markerDetails.marker);
      gbus.GBus.mapMarkers.push(gbus.GBus.markerDetails.marker);
      gbus.GBus.mapHTMLS.push(params.html);
      try {
        gbus.GBus.pointDetails.bounds.extend(gbus.GBus.pointDetails.point);
      } catch (e) {
        //IE6 sometimes throws a JS exception.
      }


      if (params.useSidebar == true) {
        params.sidebarText = '';
        params.sidebarText += gbus.GBus.label;
        params.sidebarTextFont = document.createElement('font')
        params.sidebarTextFont.appendChild(
            document.createTextNode(params.sidebarText));

        if (params.entry['gsx$' +
                         params.cityReachedByBus].$t ==
            'yes') {
          params.sidebarTextFont.setAttribute('color', '#000000');
          params.flag = false;
        }
        else
          params.sidebarTextFont.setAttribute('color', '#888888');
        params.flag = true;
      }
      if (params.count < params.numberOfRowsForLabel) {
        params.sidebarDIV.appendChild(
            params.sidebarTextFont);
        params.markerA = document.createElement('br');
        params.sidebarDIV.appendChild(params.markerA);
        document.getElementById('mapRow').appendChild(
            params.sidebarDIV);
        params.count = params.count + 1;
      }
      if ((params.count >= params.numberOfRowsForLabel) &&
          (params.count <
           params.numberOfRowsForLabelSecondRow)) {
        params.sidebarDIVSecond.appendChild(
            params.sidebarTextFont);
        params.markerA = document.createElement('br');
        params.sidebarDIVSecond.appendChild(params.markerA);
        document.getElementById('mapRowTwo').appendChild(
            params.sidebarDIVSecond);
        params.count = params.count + 1;
      }
      if (params.count >=
          params.numberOfRowsForLabelSecondRow) {
        params.sidebarDIVThree.appendChild(
            params.sidebarTextFont);
        params.markerA = document.createElement('br');
        params.sidebarDIVThree.appendChild(params.markerA);
        document.getElementById('mapRowThree').appendChild(
            params.sidebarDIVThree);
        params.count = params.count + 1;
      }
    }
  }

  try {
    gbus.GBus.map.panTo(gbus.GBus.currentPositionProperties);
  } catch (e) {}
  gbus.GBus.map.setZoom(6);
  gbus.GBus.app.loadFeaturedVideos();
};

/**
 * This method retrieves the current position of the bus from
 * data revcieved from spreadsheets and sets up maps
 * information accordingly.
 *
 * @param {String} json The JSON data recieved from spreadsheet.
 */
gbus.GBus.app.loadCurrentPositionMapJSON = function(json) {
    gbus.GBus.params.currentPositonEntry = json.feed.entry[0];
    if (gbus.GBus.params.currentPositonEntry['gsx$' + gbus.GBus.params.city]) {
      gbus.GBus.pointDetails.latitude =
      parseFloat(gbus.GBus.params.currentPositonEntry[
          'gsx$' + gbus.GBus.params.cityLatitude].$t);
      gbus.GBus.pointDetails.longitude =
      parseFloat(gbus.GBus.params.currentPositonEntry[
          'gsx$' + gbus.GBus.params.cityLongitude].$t);
      gbus.GBus.pointDetails.point = new GLatLng(
          gbus.GBus.pointDetails.latitude, gbus.GBus.pointDetails.longitude);

      gbus.GBus.params.iconBlue = new GIcon();
      gbus.GBus.params.iconBlue.image =
      'http://gk47639bus.googlecode.com/svn/trunk/gadgets/mapGadget/bus_icon.gif';
      gbus.GBus.params.iconBlue.iconSize = new GSize(40, 40);
      gbus.GBus.params.iconBlue.iconAnchor = new GPoint(6, 20);
      gbus.GBus.params.iconBlue.infoWindowAnchor = new GPoint(5, 1);

      gbus.GBus.markerDetails.markerOpts.icon = gbus.GBus.params.iconBlue;
      gbus.GBus.markerDetails.markerOpts.title =
      gbus.GBus.params.currentPositonEntry[
          'gsx$' + gbus.GBus.params.city].$t;
      gbus.GBus.markerDetails.currentPositionMarker = new GMarker(
          gbus.GBus.pointDetails.point, gbus.GBus.markerDetails.markerOpts);
      gbus.GBus.map.addOverlay(gbus.GBus.markerDetails.currentPositionMarker);
      GEvent.addListener(gbus.GBus.markerDetails.currentPositionMarker,
          'click', function() {
        gbus.GBus.markerDetails.currentPositionMarker.openInfoWindowHtml(
            gbus.GBus.params.currentPositonEntry['gsx$' +
                                                 gbus.GBus.params.city].$t);
      });
      gbus.GBus.currentPositionProperties = gbus.GBus.pointDetails.point;
      var bytesUsage = parseFloat(
          gbus.GBus.params.currentPositonEntry[
              'gsx$' + gbus.GBus.params.bytesUsedAtPresentCity].$t);
      gbus.GBus.app.setUpChart(parseFloat(
          gbus.GBus.params.currentPositonEntry[
              'gsx$' + gbus.GBus.params.distanceTravelled].$t), bytesUsage,
          'Route covered');


    }
};

/**
 * Loads the video in a flash player.
 * @param {String} playerUrl The URL of the YT video.
 * @param {Number} autoplay 1, if autoplay else 0.
 */
gbus.GBus.app.loadVideo = function(playerUrl, autoplay) {
  var browser = navigator.appName;
  var b_version = navigator.appVersion;
  if (browser == 'Microsoft Internet Explorer') {
    return;
  }
  swfobject.embedSWF(playerUrl + '&rel=0&border=0&fs=1&autoplay='
      + (autoplay ? 1 : 0), 'player', '240', '160', '9.0.0', false,
      false, {
    allowfullscreen : 'true'
  });



};

/**
 * Writes the gbus stats on the main HTML.
 * @param {Number} kilometersCovered The number of kilometers covered in the
 *                 city.
 * @param {Number} bytesUsedAtCity Byte usage in the city.
 * @param {String} title The city name to be set as widget title.
 */
gbus.GBus.app.setUpChart = function(kilometersCovered, bytesUsedAtCity, title) {
  var statsText = 'Internet Bus Stats: ' + title;
  statsText += '<br/><br/> Kilometers: ' + kilometersCovered;
  statsText += '<br/><br/> Bytes     : ' + bytesUsedAtCity;
  document.getElementById('gaugeHeader').innerHTML = statsText;
};

var playing = 0;
/**
 * Event handler for starting the auto-play of route.
 */
gbus.GBus.app.mapAutoPlay = function() {
  if (playing != 1) {
    gbus.GBus.app.intervalId = self.setInterval('gbus.GBus.app.nextMarker()',
        4000);
    playing = 1;
  }
};

/**
 * Moves to the next marker for auto-play.
 */
gbus.GBus.app.nextMarker = function() {
  if (gbus.GBus.app.counter >= gbus.GBus.mapMarkers.length) {
    gbus.GBus.app.counter = 0;
    gbus.GBus.app.intervalId = window.clearInterval(gbus.GBus.app.intervalId);
    playing = 0;
  }
  gbus.GBus.mapMarkers[gbus.GBus.app.counter].openInfoWindowHtml(
      gbus.GBus.mapHTMLS[gbus.GBus.app.counter], {
    maxWidth : 200
  });
  gbus.GBus.app.counter++;
};

/**
 * Event handler for pausing the auto-play of route.
 */
gbus.GBus.app.pauseAutoplay = function() {
  if (playing == 1) {
    gbus.GBus.app.intervalId = window.clearInterval(gbus.GBus.app.intervalId);
    playing = 2;
  }

};

/**
 * Event handler for stopping the auto-play of route.
 */
gbus.GBus.app.stopAutoplay = function() {
  gbus.GBus.app.intervalId = window.clearInterval(gbus.GBus.app.intervalId);
  gbus.GBus.app.counter = 0;
  playing = 0;
};

/**
 * This methods sets up the video element in the main HTML page.
 *
 */
gbus.GBus.app.loadFeaturedVideos = function() {
  var docsKey = gbus.GBus.params.currentBusPositionSpreadSheetKey;
  var docsSheetId = 4;
  gbus.GBus.app.featVideosScript = document.createElement('script');
  gbus.GBus.app.featVideosScript.setAttribute('src',
      'http://spreadsheets.google.com/feeds/list' +
                               '/' + docsKey +
                               '/' + docsSheetId +
                               '/public/values?' +
                               'alt=json-in-script&callback=' +
                               'gbus.GBus.app.renderVideos');
  gbus.GBus.app.featVideosScript.setAttribute('id', 'featVideoJsonScript');
  gbus.GBus.app.featVideosScript.setAttribute('type', 'text/javascript');
  document.documentElement.firstChild.appendChild(
      gbus.GBus.app.featVideosScript);
};

/**
 * Parses the spreadsheet to setup video on screen. Used as a JSON callback
 * @param {JsonObject} data JSON returned from feed.
 */
gbus.GBus.app.renderVideos = function(data) {
  gbus.GBus.app.videofeed = data.feed;
  gbus.GBus.app.videoentries = gbus.GBus.app.videofeed.entry || [];
  gbus.GBus.app.html = [];
  gbus.GBus.app.htmlTwo = [];
  gbus.GBus.app.htmlThree = [];
  var ytUrl = null;
  var thumbnail = null;
  var swfUrl = null;
  var title = null;
  var videoEntry = null;
  var browser = navigator.appName;

  for (var i = 0; i < gbus.GBus.app.videoentries.length; i++) {
    videoEntry = gbus.GBus.app.videoentries[i];
    ytUrl = videoEntry['gsx$' + 'yturl'].$t;
    thumbnail = videoEntry['gsx$' + 'thumbnail'].$t;
    swfUrl = videoEntry['gsx$' + 'swfurl'].$t;
    title = videoEntry['gsx$' + 'title'].$t;
    if (i == 0) {
      gbus.GBus.app.html.push('<p onclick="gbus.GBus.app.loadVideo(\'',
          swfUrl,
          '\', true)">', '<img src="', thumbnail,
          '" width="114" height="76"/>', '</p>');
      document.getElementById('relOne').innerHTML = gbus.GBus.app.html.join('');
      document.getElementById('relOneInfo').innerHTML = '<br/><a href=\'' +
          ytUrl + '\' target=_blank>' + title +
          '</a';
    }
    else if (i == 1) {
      gbus.GBus.app.htmlTwo.push('<p onclick="gbus.GBus.app.loadVideo(\'',
          swfUrl,
          '\', true)">', '<img src="', thumbnail,
          '" width="114" height="76"/>', '</p>');
      document.getElementById('relTwo').innerHTML =
      gbus.GBus.app.htmlTwo.join('');
      document.getElementById('relTwoInfo').innerHTML = '<br/><a href=\'' +
          ytUrl + '\' target=_blank>' + title +
          '</a';
    }
    else if (i == 2) {
      gbus.GBus.app.htmlThree.push(
          '<p onclick="gbus.GBus.app.loadVideo(\'',
              swfUrl,
          '\', true)">', '<img src="', thumbnail,
          '" width="114" height="76"/>', '</p>');
      document.getElementById('relThree').innerHTML =
      gbus.GBus.app.htmlThree.join('');
      document.getElementById('relThreeInfo').innerHTML = '<br/><a href=\'' +
          ytUrl + '\' target=_blank>' + title +
          '</a';

    }
   }
};

/**
 * A simple util to convert a MM/DD/YYY date to DD MON format.
 * @param {String} date A date in MM/DD/YYYY format.
 * @return {String} Formatted date in DD MON format.
 */
gbus.GBus.app.getDisplayFormatDate = function(date) {
  try {
    var splitArray = date.split('/');
    var month = null;
    if (splitArray[1].length == 1)
      splitArray[1] = '0' + splitArray[1];
    switch (splitArray[0]) {
      case '1':
      case '01':
        month = 'Jan';
        break;
      case '2':
      case '02':
        month = 'Feb';
        break;
      case '3':
      case '03':
        month = 'Mar';
        break;
      case '4':
      case '04':
        month = 'Apr';
        break;
      case '5':
      case '05':
        month = 'May';
        break
      case '6':
      case '06':
        month = 'Jun';
        break;
      case '7':
      case '07':
        month = 'Jul';
        break
      case '8':
      case '08':
        month = 'Aug';
        break;
      case '9':
      case '09':
        month = 'Sep';
        break;
      case '10':
        month = 'Oct';
        break
      case '11':
        month = 'Nov';
        break;
      case '12':
        month = 'Dec';
        break;
      default : month = 'Feb';
    }
    return splitArray[1] + ' ' + month;
  } catch (e) {
  }
  return date;
};
