﻿var fp_debug = false; // set to true for some debugging messages
/**
 * FlightDetails class
 */
function FlightDetails( origin, destination, departureTime, arrivalTime, flightNr, via )
{
  this.origin        = origin;
  this.destination   = destination;
  this.departureTime = departureTime;
  this.arrivalTime   = arrivalTime;
  this.flightNr      = flightNr;
  this.via           = via;
}
/**
 * FlightPlan class
 */
function FlightPlan()
{     
  if( lowfare_calendar_language == "de" )
  {
    this.lowfarecalender_link = '/de/sparkalender.html';
  }
  else if( lowfare_calendar_language == "en" )
  {
    this.lowfarecalender_link = '/en/lowfarecalendar.html';
  }
  else if( lowfare_calendar_language == "es" )
  {
    this.lowfarecalender_link = '/es/calendario-de-ahorro.html';
  }
  else if( lowfare_calendar_language == "fr" )
  {
    this.lowfarecalender_link = '/fr/calendrier-des-offres.html';
  }
  else if( lowfare_calendar_language == "it" )
  {
    this.lowfarecalender_link = '/it/calendario-delle-offerte.html';
  }
  else if( lowfare_calendar_language == "nl" )
  {
    this.lowfarecalender_link = '/nl/spaarkalender.html';
  }
  else if( lowfare_calendar_language == "pl" )
  {
    this.lowfarecalender_link = '/pl/kalendarz.html';
  }
  else if( lowfare_calendar_language == "ru" )
  {
    this.lowfarecalender_link = '/ru/lowfarecalendar-ru.html';
  }
  else
  {
    this.lowfarecalender_link = '/de/sparkalender.html';
  }
  /**
   * Render the flight plan using the XML data response from the AJAX request
   * and the HTML template provided in this page.
   */
  this.render = function( transport )
  {
    if ( transport == null || transport.responseXML == null || transport.responseXML.documentElement == null )
    {
      if ( fp_debug )
      {
        alert( 'Transport or XML response is null!' );
      }
      $( 'fp_nodata' ).show();
      return;
    }
    var xmlDoc    = transport.responseXML.documentElement;
    var template  = document.getElementById( 'fp_schedule_template' );
    var clone     = template.cloneNode( true );
    var container = document.getElementById( 'fp_container' );
    // remove previous data if available
    if ( container.firstChild != null )
    {
      container.removeChild( container.firstChild );
    }
    if ( xmlDoc.firstChild == null || ( xmlDoc.childNodes[ 0 ].firstChild == null && xmlDoc.childNodes[ 1 ].firstChild == null ) )
    {
      if ( fp_debug )
      {
        alert( 'No flight data available' );
      }
      $( 'fp_nodata' ).show();
      return; // no flight data available!
    }
    /* <general information> */
    var tmpDepartTime = this._get_text( xmlDoc.getElementsByTagName( 'from' )[ 0 ] );
    var lfcDepartTime = tmpDepartTime.substr( 3, 2 ) + '-20' + tmpDepartTime.substr( 6, 2 ); // should work up to 2099 ;)
    var lfcOrigin     = xmlDoc.getElementsByTagName( 'origin' )[ 0 ].getAttribute( 'tlc' );
    var lfcDest       = xmlDoc.getElementsByTagName( 'destination' )[ 0 ].getAttribute( 'tlc' );
    this._replace_text( document.getElementsByClassName( 'fp_from', clone )[ 0 ], this._get_text( xmlDoc.getElementsByTagName( 'from' )[ 0 ] ) );
    this._replace_text( document.getElementsByClassName( 'fp_to', clone )[ 0 ],   this._get_text( xmlDoc.getElementsByTagName( 'to' )[ 0 ] ) );
    /* </general information> */
    var flights = new Array().concat( 
      this._render_flight( clone, xmlDoc.getElementsByTagName( 'outward' )[ 0 ], { date: lfcDepartTime, depart: lfcOrigin, arrival: lfcDest } ),
      this._render_flight( clone, xmlDoc.getElementsByTagName( 'return' )[ 0 ], { date: lfcDepartTime, depart: lfcDest, arrival: lfcOrigin } ) 
    );
    document.getElementsByClassName( 'fp_schedule_flight_template', clone ).each( function( item ) { item.remove(); } ); // clear previous flight data
    var cssClass;
    this._is_ie() ? cssClass = 'block' : cssClass = 'table-row-group'; // IE doesn't know table-row-group
    flights.each( function( item ) // add new flight data
      {
        item.style.display = cssClass;
        clone.appendChild( item );
      }
    );
    /* place clone into DOM tree and display it */
    clone.style.display = 'block';
    if ( container.firstChild != null )
    {
      container.replaceChild( clone, container.firstChild );
    }
    else
    {
      container.appendChild( clone );
    }
  }
  /**
   * Render on part of the flight plan (outward or return).
   */
  this._render_flight = function( clone, xmlRoot, lfc )
  {    
    var flightNodesArray = new Array();
    if ( xmlRoot == null || xmlRoot.firstChild == null )
    {
      if ( fp_debug )
      {
        alert( 'xmlRoot is null or empty!' );
      }
      
      return flightNodesArray; // return empty array
    }
        
    var xmlFlightsRoot = xmlRoot.getElementsByTagName( 'flights' )[ 0 ];
    var xmlFlights     = xmlFlightsRoot.getElementsByTagName( 'flight' );
    var prevVia = '';
    
    for( i = 0; i < xmlFlights.length; i++ )
    {
      var flight_template = document.getElementsByClassName( 'fp_schedule_flight_template', clone )[ 0 ].cloneNode( true );
      var xmlCurFlight    = xmlFlights[ i ];
      var flightDetails = new FlightDetails(
        this._get_text( xmlRoot.getElementsByTagName( 'origin' )[ 0 ] ),
        this._get_text( xmlRoot.getElementsByTagName( 'destination' )[ 0 ] ),
        xmlCurFlight.getAttribute( 'departureTime' ),
        xmlCurFlight.getAttribute( 'arrivalTime' ),
        xmlCurFlight.getAttribute( 'flightNr' ),
        xmlCurFlight.getAttribute( 'via' )
      );
      // set low fare calendar link
      var lowfarelink = document.getElementsByClassName( 'fp_lowfarecalendar', flight_template  )[ 0 ];
      lowfarelink.href = this.lowfarecalender_link + '?DEPSTA=' + lfc.depart + '&ARRVSTA=' + lfc.arrival + '&FLIGHTDATE=' + lfc.date;
      var className;
      if ( i == xmlFlights.length - 1 )
      {
        className = 'spaceLine';
      }
      else
      {
        className = '';
      }
      try
      {
        // if this is the last flight row, add spaceLine class to first tr child
        flight_template.childNodes[ 1 ].className = className;
      }
      catch(ex)
      {
        flight_template.childNodes[ 0 ].className = className; // for I6
      }
        
      this._replace_text( document.getElementsByClassName( 'fp_origin', flight_template )[ 0 ],      flightDetails.origin );
      this._replace_text( document.getElementsByClassName( 'fp_destination', flight_template )[ 0 ], flightDetails.destination );
      
      if ( flightDetails.via != null && flightDetails.via != "" )
      {
        this._replace_text( document.getElementsByClassName( 'fp_via', flight_template )[ 0 ], "via " + flightDetails.via );
      }
      else
      {
        this._replace_text( document.getElementsByClassName( 'fp_via', flight_template )[ 0 ], "" );
      }
      this._replace_text( document.getElementsByClassName( 'fp_departuretime', flight_template )[ 0 ], flightDetails.departureTime );
      this._replace_text( document.getElementsByClassName( 'fp_arrivaltime', flight_template )[ 0 ], flightDetails.arrivalTime );
      this._replace_text( document.getElementsByClassName( 'fp_flightnr', flight_template )[ 0 ], flightDetails.flightNr );
      this._render_flight_day( flight_template, xmlCurFlight, 'fp_monday',    'monday',    fp_schedule_mon, fp_schedule_mon_gray, flightDetails );
      this._render_flight_day( flight_template, xmlCurFlight, 'fp_tuesday',   'tuesday',   fp_schedule_tue, fp_schedule_tue_gray, flightDetails );
      this._render_flight_day( flight_template, xmlCurFlight, 'fp_wednesday', 'wednesday', fp_schedule_wed, fp_schedule_wed_gray, flightDetails );
      this._render_flight_day( flight_template, xmlCurFlight, 'fp_thursday',  'thursday',  fp_schedule_thu, fp_schedule_thu_gray, flightDetails );
      this._render_flight_day( flight_template, xmlCurFlight, 'fp_friday',    'friday',    fp_schedule_fri, fp_schedule_fri_gray, flightDetails );
      this._render_flight_day( flight_template, xmlCurFlight, 'fp_saturday',  'saturday',  fp_schedule_sat, fp_schedule_sat_gray, flightDetails );
      this._render_flight_day( flight_template, xmlCurFlight, 'fp_sunday',    'sunday',    fp_schedule_sun, fp_schedule_sun_gray, flightDetails );
      if ( i > 0 && prevVia == flightDetails.via )
      {
        document.getElementsByClassName( 'fp_origindestination', flight_template )[ 0 ].style.visibility = 'hidden'; // only display origin & destination once
        lowfarelink.style.visibility = 'hidden'; // only display low far calendar link once
      }
      flightNodesArray.push( flight_template );
      
      prevVia = flightDetails.via;
    }
  
    return flightNodesArray;
  }
  /**
   * Render on row of flight details.
   */
  this._render_flight_day = function( template, xmlNode, className, xmlTag, imageEnabled, imageDisabled, flightDetails )
  {
    var xmlTag  = xmlNode.getElementsByTagName( xmlTag )[ 0 ];
    var element = document.getElementsByClassName( className, template )[ 0 ];
  
    if ( this._get_text( xmlTag ) == 'true' )
    {
      element.src = imageEnabled;
      
      var date = xmlTag.getAttribute( 'date' );
      element.parentNode.onclick = function() { 
        SearchFlights( flightDetails.origin, flightDetails.destination, date, date, '0|0', 1, 0, 0, 'R,F', 'RoundTrip' ); // see FlightSearchController.js
        return false;
      };
    }
    else
    {
      element.src = imageDisabled;            
      element.parentNode.removeAttribute( 'href' ); // disable empty links
    }
  }
  /**
   * Get text from specified node.
   */
  this._get_text = function( node )
  {
    if ( node == null )
    {
      if ( fp_debug )
      {
        alert( '_get_text: node is null' );
      }
      return;
    }
    return node.childNodes[ 0 ].nodeValue;
  }
  /**
   * Set text of specified node.
   */
  this._replace_text = function( node, text )
  {
    if ( node == null )
    {
      if ( fp_debug )
      {
        alert( '_replace_text: node is null' );
      }
      return;
    }
    if ( node.childNodes[ 0 ] != null )
    {
      node.childNodes[ 0 ].nodeValue = text;
    }  
  }
  
  /**
   * IE check.
   */
  this._is_ie = function()
  {
    return document.all;
  }
}
/**
 * Initiate a new AJAX request.
 */
function fp_update( rdCulture )
{
  if ( $( 'fp_form_origin' ).selectedIndex == 0 )
  {
    $( 'fp_form_origin' ).focus();
    return;
  }
  if ( $( 'fp_form_destination' ).selectedIndex == 0 )
  {
    $( 'fp_form_destination' ).focus();
    return;
  }
  if ( $( 'fp_form_calendarweek' ).selectedIndex == 0 )
  {
    $( 'fp_form_calendarweek' ).focus();
    return;
  }
  new Ajax.Request( '/ajax/FlightPlan.ashx',
    {
      parameters: { origin: $( 'fp_form_origin').value, destination: $( 'fp_form_destination' ).value, calendarweek: $( 'fp_form_calendarweek' ).value, culture: rdCulture },
      onLoading: function() { $( 'fp_nodata' ).hide(); $( 'fp_error' ).hide(); $( 'fp_loading' ).show(); },
      onSuccess: function( transport ) { new FlightPlan().render( transport ); },
      onException: function( request, exception ) { if ( fp_debug ) { alert( exception ) }; $( 'fp_error' ).show(); },
      onFailure: function() { $( 'fp_error' ).show(); },
      onComplete: function() { $( 'fp_loading' ).hide(); }
    }
  );
}
/**
 * Event when prev button is clicked.
 */
function fp_prev_week()
{
  var dropdown = $( 'fp_form_calendarweek' );
  
  if ( dropdown.selectedIndex > 1 )
  {
    dropdown.selectedIndex--;
    fp_update();
  }
}
/**
 * Event when next button is clicked.
 */
function fp_next_week()
{
  var dropdown = $( 'fp_form_calendarweek' );
  
  if ( dropdown.selectedIndex < dropdown.length - 1 )
  {
    dropdown.selectedIndex++;
    fp_update();
  }
}
function fp_position_element( el )
{
  var container = $( 'fp_container' );
  Element.extend( container );
  Element.extend( el );
  var cDimensions = container.getDimensions();
  var cPosition = Position.page( container );
  var eDimensions = el.getDimensions();
  el.style.left = cPosition[ 0 ] + ( ( cDimensions.width - eDimensions.width ) / 2 ) + 'px';
  el.style.top  = cPosition[ 1 ] + ( ( cDimensions.height - eDimensions.height ) / 2 ) + 'px';
}
/**
 * Update of flight plan via teaser link
 */
function fp_teaser_update( rdCulture, origin, destination, calendarWeek )
{
  stations_preselect( $( 'fp_form_origin' ), origin );
  stations_update( { type: 'destination', affiliate: $( 'fp_form_origin' ).value, node: $( 'fp_form_destination' ), rdCulture: rdCulture,
    callback: function() {
      stations_preselect( $( 'fp_form_destination' ), destination );
      var cw = $( 'fp_form_calendarweek' );
      cw.disabled = false;
      if ( cw.length > 1 )
      {
        cw[ 1 ].selected = true; // select first calendarweek as default
      }
      if ( calendarWeek != null && calendarWeek != '' )
      {
        for ( var i = 0; i < cw.length; i++ )
        {
          if ( cw[ i ].value == calendarWeek )
          {
            cw[ i ].selected = true;
          }
        }
      }
      fp_update( rdCulture );
    }
  } );
}