var INTO_url = "/files/finavia2/INTO/";
var INTO_flightTemplate = "into-flight-template.html";
var INTO_messages = 
{
  'error':
  {
    'fin': "into-error-fin.html",
    'eng': "into-error-eng.html",
    'swe': "into-error-swe.html"
  },
  'noflights':
  {
    'fin': "into-noflights-fin.html",
    'eng': "into-noflights-eng.html",
    'swe': "into-noflights-swe.html"
  }
};

var INTO_init = true;
var INTO_error = false;

var INTO_flights = [];
var INTO_flightCache = {};
INTO_flightCache['arr'] = {};
INTO_flightCache['dep'] = {};
INTO_flightCache['all'] = {};


$.fn.INTO_showFlights = function (params)
{
  var _this = this;
  var flightTemplate = INTO_loadTemplate(INTO_flightTemplate);

  if (!params.airport || !params.language || !params.flightSearch && !params.flightType || !flightTemplate.length) return;
  if (!params.flightType) params.flightType = "all";

  var flightData = INTO_loadFlightData(params.airport);

  var found_arr = 0;
  var found_dep = 0;
  var no_flights = false;

  if (flightData["noflights"]) no_flights = true;
  else 
  {
    $.each(flightData, function (index, data) {
      if (data[1] == 'arr') found_arr++;
      if (data[1] == 'dep') found_dep++;
    });
  }

  if (INTO_error) $(this).empty();

  if (!flightData || params.flightType == 'arr' && found_arr < 1 || params.flightType == 'dep' && found_dep < 1)
  {
    if (found_arr > 0 || found_dep > 0) no_flights = true;

    INTO_init = true;
    INTO_error = true;
    INTO_flightCache[ params.flightType ] = {};

    if (!no_flights)
      $(this).html( INTO_loadTemplate( INTO_messages['error'][ params.language ]) );
    else
      $(this).html( INTO_loadTemplate( INTO_messages['noflights'][ params.language ]) );
  }
  else 
  {
    INTO_init = true;
    INTO_error = false;
  }

  var flightMatch = new RegExp(params.flightSearch, "i");

  INTO_flights[ params.flightType ] = {};
  $.each(flightData, function (index, data) {

    var timestamp = data[0];
    var flightType = data[1];
    var flightNumber = data[3];
    var flightNumbers = data[4];
    var airport = data[6];

    // Match flights type
    if (flightType == params.flightType || params.flightType == "all")
    {
      // Flight search
      if (!params.flightSearch || params.flightSearch && (flightMatch.exec(flightNumbers) || flightMatch.exec(airport)))
      {
        var key = params.flightType + flightNumber + airport + timestamp;
        var hash = data.join();
        var mode = false;

        // New flight
        if (!INTO_flightCache[ params.flightType ][ key ]) mode = "new";

        // Updated flight
        else if (INTO_flightCache[ params.flightType ][ key ] != hash) mode = "update";

        if (mode)
        {
          _this.INTO_createFlightHTML(key, data, params.language, mode, flightTemplate);
          INTO_flightCache[ params.flightType ][ key ] = hash;
        }
        INTO_flights[ params.flightType ][ key ] = true;
      }
    }
  });

  // Remove old flights
  $.each(INTO_flightCache, function (flightType) {
    $.each(INTO_flightCache[ flightType ], function (key) {
      if (!INTO_flights[ flightType ][ key ])
      {
        delete(INTO_flightCache[ flightType ][ key ]);
        $(document.getElementById( key )).remove();
      }
    });
  });

  // Visual effects for new/updated flights
  if (!INTO_init) $(this).INTO_updateEffects();

  // Start update loop
  if (parseInt(params.updateInterval) > 0)
  {
    var updateInterval = (parseInt(params.updateInterval) * 1000);
    delete(params.updateInterval);
    setInterval( function () { _this.INTO_showFlights(params) }, updateInterval);
  }

  INTO_init = false;
}


$.fn.INTO_createFlightHTML = function (key, data, language, mode, flightTemplate)
{
  var time = data[2];
  var codes = data[4]; 
  var terminal = data[5];
  var airport = data[6];
  var status_code = data[7];

  var status = [];
  status['eng'] = data[8];
  status['fin'] = data[9];
  status['swe'] = data[10];

  var time2 = data[11];

  var html = flightTemplate;
  html = html.replace("%ID%", key);
  html = html.replace("%TIME%", time);
  html = html.replace("%AIRPORT%", airport);
  html = html.replace("%CODES%", codes);
  html = html.replace("%STATUS_CODE%", status_code);
  html = html.replace("%STATUS_TEXT%", status[ language ]);
  html = html.replace("%TIME2%", (time2 ? time2 : ""));
  html = html.replace("%TERMINAL%", terminal);

  // New flight
  if (mode == "new")
  {
    var flight = $(html);

    if (!INTO_init)
      flight.addClass("new").hide();

    $(this).append(flight);
  }

  // Updated flight
  else if (mode == "update")
  { 
    $(document.getElementById( key ))
      .replaceWith(html)
      // .html(html)
      .addClass("update");
  }
}


$.fn.INTO_updateEffects = function ()
{
  // New flights
  var delay = 0;
  $(this).find(".new").each( function () {
    var _this = $(this);
    setTimeout( function () { _this.fadeIn(750).removeClass("new") }, delay);
    delay += 250;
  });

  // Updated flights
  $(this).find(".update").each( function () {
    $(this)
      .animate({ "opacity": 0 }, { queue: false, duration: 750 })
      .animate({ "opacity": 1 }, 750)
      .animate({ "opacity": 0 }, 750)
      .animate({ "opacity": 1 }, 750)
      .animate({ "opacity": 0 }, 750)
      .animate({ "opacity": 1 }, 750)
      .removeClass("update");
  });
}


function INTO_loadFlightData (airport)
{
  if (!airport) return false;
  var url = INTO_url + airport +".json";

  var data = "";
  $.ajax({
    "type": "GET",
    "url": url,
    "async": false,
    "cache": false,
    "dataType": "json",
    "success": function (json) { data = json }
  });

  return data;
}


function INTO_loadTemplate (template)
{
  if (!template) return false;
  var url = INTO_url + template;

  var data = "";
  $.ajax({
    "type": "GET",
    "url": url,
    "async": false,
    "cache": false,
    "success": function (html) { data = html }
  });
  if (!data.length) return false;
  return data;
}


function debug (s)
{
  console.log(s);
}

function parseQueryString (source, separator) 
{
  var fields = {};
  if (!source.length) return fields;
  var params = source.split(separator), parts;
  for (var i = 0, l = params.length; i < l; ++i) {
    if (params[i] === '') continue;
    parts = params[i].split('=', 2);
    fields[decodeURIComponent(parts[0])] = parts[1] ? decodeURIComponent(parts[1]) : false;
  }
  return fields;
}
