/*
 * WWW/fmtv/js/tvg.js
 * Copyright (c) 2010, Vizimo Ltd
 *
 * Original author: Eric Sellin
 *
 */

var saved_when = "";

var genre_colours = ['Red','Brown','Orange','Yellow','Green','Darkgreen','Teal','Blue','Navy','Black','Purple','Pink'];

function moveToHour (h)
{
  fetchListings (saved_when.substring (0, 11) +
		 (h < 10? "0": "") + h + ":00:00");
}

function fetchListings (when)
{

/*
  if ( when == saved_when )
    return;
*/

  saved_when = when;

  if ( startHour >= 0 ) {

    document.getElementById ('dragtabswrapid').style.left = (-168 * startHour + 8) + 'px';

    document.getElementById ('dragwindowwrapid').style.left = (-168 * startHour + 8) + 'px';

    document.getElementById ('draghandleid').style.left = (26 * startHour + 4) + 'px';

    document.getElementById ('draghandlemaskid').style.left = (26 * startHour + 4) + 'px';

    startHour = -1;

  }

  document.cookie = "epg_when=" + when;
  document.cookie = "epg_date=" + when.substring (0, 10);
  document.cookie = "epg_time=" + parseInt (when.substring (11, 13), 10);

  if ( window.XMLHttpRequest ) {
    request = new XMLHttpRequest ();
  } else if ( window.ActiveXObject ) {
    request = new ActiveXObject ("Msxml2.XMLHTTP");
    if ( request == null )
      request = new ActiveXObject ("Microsoft.XMLHTTP");
  }

  if ( request == null )
    return;

  ids = "";
  start = Math.floor (- parseInt (document.getElementById ('dragwindowwrapid').style.top, 10) / 42);
  if ( isNaN (start) )
    start = 0;
  for (var i=start; i<=start+10 && i<channel_ids.length; ++i) {
    if ( ids.length > 0 )
      ids += ",";
    ids += channel_ids [i];
  }

  request.onreadystatechange = processListings;
  request.open ("GET", "/ajax/programmes.htm?channels=" + ids +
                "&pkg=" + pkg + "&offset=-1&hours=5&when=" + when, true);
  request.send (null);

}

function minutesSinceMidnight (s)
{
  return parseInt (s.substring (0, 2), 10) * 60 +
         parseInt (s.substring (3), 10);
}

var channel_progs = new Array ();

var genre_map = new Array ();
var genre_highlighted = new Array ();

function trim_az (s)
{
  r = "";
  for (var i=0; i<s.length; ++i)
  {
    c = s.charAt (i);
    if ( (c >= 'A' && c <= 'Z') ||
	 (c >= 'a' && c <= 'z') ||
	 (c >= '0' && c <= '9') )
      r += c;
    else if ( c == ' ' )
      r += '_';
  }
  return r;
}

function processListings ()
{

  if ( request.readyState != 4 ||
       request.status != 200 )
    return;

  resp = eval (request.responseText);

  for (var i=0; i<resp.length; ++i) {

    html = '';

    previous_stop = 0;

    if ( channel_progs [resp [i][0]] == null )
      channel_progs [resp [i][0]] = new Array ();

    for (var j=0; j<resp [i][1].length; ++j) {
      var p = new Object ();
      p.title = resp [i][1][j][0];
      p.start = resp [i][1][j][1];
      p.stop = resp [i][1][j][2];
      p.cpid = resp [i][1][j][3];
      p.marked = resp [i][1][j][4];
      p.watchnow = resp [i][1][j][5];
      p.genre = resp [i][1][j][7];
      channel_progs [resp [i][0]][channel_progs [resp [i][0]].length] = p;
    }

    channel_progs [resp [i][0]].sort (function (a, b) {
      if ( a.start < b.start )
        return -1;
      else if ( a.start > b.start )
        return 1;
      return 0;
    });

    var next_day = false;

    for (var j=0; j<channel_progs [resp [i][0]].length; ++j) {

      p = channel_progs [resp [i][0]][j];

      if ( p.start == null || p.stop == null )
        continue;

      start = Math.floor (minutesSinceMidnight (p.start.substring (11, 16)) / 5) * 5;
      stop = Math.floor (minutesSinceMidnight (p.stop.substring (11,16)) / 5) * 5;

      // Programme runs across midnight
      if ( stop < start ) {
	if ( p.start.substring (0, 10) < saved_when.substring (0, 10) ) {
	  start = 0;
        } else {
          stop += 24 * 60;
	  next_day = true;
        }
      } else if ( next_day ) {
	start += 1440;
	stop += 1440;
      }

/*
      // Programme might start after midnight while we're looking at
      // the end of the day
      if ( start < 0 && stop < 0 ) {
        start += 24 * 60;
        stop += 24 * 60;
      }

      // Programme might start before midnight while we're looking at
      // the start of the day
      if ( start > 180 && stop > 180 ) {
        start -= 24 * 60;
        stop -= 24 * 60;
      }

      if ( stop >= 180 ) {
        if ( start >= 180 )
          continue;
        stop = 180;
      }

      if ( start <= 0 ) {
        if ( stop <= 0 )
          continue;
        start = 0;
      }
*/

      if ( start > 1560 )
        continue;

      if ( stop > 1560 )
        stop = 1560;

      if ( start < previous_stop || stop <= previous_stop )
        continue;

      if ( stop - start < 5 )
        continue;

      width = (stop - start) / 5 * 14 - 6;

      if ( start > previous_stop ) {
	var now = parseInt (saved_when.substring (11, 13), 10) * 60;
        if ( now > previous_stop && start > now ) {
 	  html += '<div class="showpadding" style="width:' + ((now - previous_stop) / 5 * 14 - 6) + 'px"></div>';
          html += '<div class="noshow" style="width:' + ((start - now) / 5 * 14 - 6) + 'px"></div>';
	} else {
	  html += '<div class="showpadding" style="width:' + ((start - previous_stop) / 5 * 14 - 6) + 'px"></div>';
	}
      }

      previous_stop = stop;

      html += '<div class="show" style="width:' + width + 'px;">';

      if ( genre_map [p.genre] == null )
        genre_map [p.genre] = new Array ();
      genre_map [p.genre][genre_map [p.genre].length] =
        p.cpid;

      html += '<div class="link-wrap"><a href="/' + p.cpid + '_tv_' + trim_az (p.title) + '" id="epg-show-link" class="addToolTip" title="' + p.cpid + '">';

      if ( stop > start + 5 )
        html += p.title.replace (/\s/g, ' ');
      else
        html += '<img src="img/icons/ico-13-info.gif" style="margin-left:0" width="6" height="15" class="info" />';

      html += '</a><img id="imgcp' + p.cpid + '" height="3px" width="' + (width+5) + 'px" class="highlight" border="0" src="img/epg/colourGradientsDefault.png" /></div>';

      if ( p.marked == 'Y' )
        html += '<img src="img/icons/ico-13-mark.gif" alt="Marked show" class="icon" />';

      if ( p.watchnow == 'Y' )
        html += '<img src="img/icons/ico-13-watchnow.gif" alt="TV on Demand" class="icon" />';

      html += '</div>';

    }

    document.getElementById ('divch_' + resp [i][0]).innerHTML = html;

  }

  for (var i=0; i<genre_ids.length; ++i) {
    if ( genre_highlighted [genre_ids [i]] == null )
      continue;
    var g = genre_ids [i];
    if ( genre_map [g] == null )
      continue;
    for (var j=0; j<genre_map [g].length; ++j) {
      document.getElementById ('imgcp' + genre_map [g][j]).src = 'img/epg/colourGradients' + genre_colours [i] + '.jpg';
    }
  }

  addwarning ();

}

function highlight_genre (index, g)
{

  if ( document.getElementById ('genre_cb_' + g).checked ) {
    genre_highlighted [g] = true;
    if ( genre_map [g] != null ) {
      for (var i=0; i<genre_map [g].length; ++i) {
        document.getElementById ('imgcp' + genre_map [g][i]).src = 'img/epg/colourGradients' + genre_colours [index] + '.jpg';
      }
    }
  } else {
    genre_highlighted [g] = null;
    if ( genre_map [g] != null ) {
      for (var i=0; i<genre_map [g].length; ++i) {
        document.getElementById ('imgcp' + genre_map [g][i]).src = 'img/epg/colourGradientsDefault.png';
      }
    }
  }

  // Store list of highlighted genres in a cookie
  var s = '';
  for (g in genre_highlighted) {
    if ( genre_highlighted [g] == null )
      continue;
    if ( s != '' )
      s += ',';
    s += g;
  }
  document.cookie = "gh=" + s + "; expires=Tue, 1 Jan 2030 00:00:00 UTC";

}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function update_genre_cbs () {
  var c = readCookie ('gh');
  if ( c != null ) {
    var ca = c.split(',');
    for (var i=0; i<ca.length; ++i) {
      genre_highlighted [ca [i]] = true;
      var z = document.getElementById ('genre_cb_' + ca [i]);
      if ( z != null )
        z.checked = true;
    }
  }
}


