/**
 * $Id: jquery.chooseFlightController.js 2535 2010-03-25 09:29:01Z bjoern.moenikes $
 **/

(function($){

  $.fn.extend({
    chooseFlightController : function(options)
    {
      if (!$.event._cfcCache) $.event._cfcCache = [];

      // initialise the date picker controller with the relevant settings...
      options = $.extend(
      {
        id : '',
        $context : '',
        renderDirective : '',                  // needed for autorenderer
        selectFlightTableCallback : undefined, // function is beeing called after update
        onErrorLinkAction : undefined
      }
      , options
      );

      return this.each(
        function()
        {
          var $this = $(this);
          var alreadyExists = true;

          if (!this._cfcId) {
            this._cfcId = $.event.guid++;
            $.event._cfcCache[this._cfcId] = new ChooseFlightController(this);
            alreadyExists = false;
          }
          var controller = $.event._cfcCache[this._cfcId];
          controller.init(options);
          $this.ctrlInit();
        }
        )

    },

    // init all components for panel
    ctrlInit : function()
    {
      $this = $(this);

      // Left flight invokes update of right table
      $("#leftFlightTable").tableManager(
      {
        loadStringID : 'flight',
        stringVar1 : function(){
          return($("#modifySearch").msGetData()[phpConst.searchParam.travelAirportName]);
        },
        stringVar2 : function(){
          return($("#modifySearch").msGetData()[phpConst.searchParam.travelDestinationName]);
        },

        renderDirective : {
          'tr' : 'line <- data',   // no 'tbody tr' since we are rendering directly into the body fragment and not into the whole table
          'tr[selectionid]' : 'line.'+phpConst.flight.flightId,
          'tr[airlinecode]' : 'line.'+phpConst.flight.airlineCode,
          'tr[airlineid]' : 'line.'+phpConst.flight.airlineId,
          'tr[airlinename]' : 'line.'+phpConst.flight.airlineName,
          'tr[flightnumber]' : 'line.'+phpConst.flight.flightnumber,
          'tr[date]' : 'line.'+phpConst.flight.departureDate,
          'tr[overnight]' : 'line.'+phpConst.flight.overnight,
          'tr[flightid]' : 'line.'+phpConst.flight.flightId,
          'tr[destairportname]' : 'line.'+phpConst.flight.destAirportName,
          'tr[price]' : 'line.'+phpConst.flight.priceFloat,
          'td.columnFirst' : 'line.dateShort',
          'td.columnFirst[title]' : 'line.dateShort',
          'tr[group]' : 'line.'+phpConst.flight.airlineGroup,
          'td.columnDay' : 'line.day',
          'td.columnDeparture' : 'line.'+phpConst.flight.departureTime,
          'td.columnArrival' : function(context) {
            var arrival = context["item"][phpConst.flight.arrivalTime];
            if (context["item"][phpConst.flight.overnight] > 0)
              arrival += getText('txt.chooseFlight.overnightPlus', context["item"][phpConst.flight.overnight]);
            else if (context["item"][phpConst.flight.overnight] < 0)
              arrival += getText('txt.chooseFlight.overnightMinus', (-1) * context["item"][phpConst.flight.overnight]);
            return(arrival);
          },
          'td.columnAirline' : 'line.'+phpConst.flight.airlineName,
          'td.columnPrice' :  function(context){
            if (context["item"][phpConst.flight.price] == phpConst.flight.BYE) //real
              //                                            if (context["item"][phpConst.flight.price] < 100) //für Tests
              return "";
            else
              return getText('txt.common.euro', context["item"][phpConst.flight.price] );
          },
          'td.columnPrice[class]' : function(context){

            // for testing purpose:
            //            if (context["item"][phpConst.flight.price] < 150)
            //              context["item"][phpConst.flight.price] = phpConst.flight.BYE;

            if (context["item"][phpConst.flight.price] == phpConst.flight.BYE) 
              return "columnPrice byebyeflight byebyeflightOrange";
            else
              return "columnPrice";
          }
        },
        //         sortList : [[2,0],[0,0]],
        //        sortForce : [[5,0]], //,[3,0],],
        headers: {
          0: {
            sorter: 'minidate'
          },
          1: {                                                  // 1 means: sort column 1 (index based 0) using the dayparser plugin
            sorter: 'dayparser'
          },
          5 : {
            sorter: 'currency2'
          }
        },
        id : "#leftFlightTable",
        JSONaction : "result_flights",
        onSuccessAction : function() {
        },
        updateCallback : function(){

        },
        selectCallback : function($table){
          $("#chooseFlight").cfcByebyePriceCheck();

          if ($("#chooseFlight").cfcGetSelectFlightTableCallback() != undefined)
            $("#chooseFlight").cfcGetSelectFlightTableCallback()($table);


          //C.log("left Filter");
          // standard filter for filtering after groups-attribute
          var groupFilter = function ()
          {
//            C.log("groupFilter");
            var $leftSelection = $("#chooseFlight #leftFlightTable tbody tr:selectedRow");
//            C.log("$leftSelection");
//            C.log($leftSelection);
            //var id = "'"+$leftSelection.attr("group")+"'";
            var id = $leftSelection.attr("group");
//            C.log(id);

            var $right = $("#chooseFlight #rightFlightTable tbody tr:not(:selectByGroup("+id+"))");
            //var $right = $("#chooseFlight #rightFlightTable tbody tr:not(:selectByGroup("XXXX'))");
//            C.log("set disbaled");
//            C.log($right);
            $right.each(function(i,v){
              $(v).addClass("disabled");
            });
            $right = $("#chooseFlight #rightFlightTable tbody tr:selectByGroup('"+id+"')");
//            C.log("$remove disbaled");
//            C.log($right);
            $right.each(function(i,v){
              $(v).removeClass("disabled");
            });

            var $rightSelection = $("#chooseFlight #rightFlightTable tbody tr:selectedRow");
            if ($rightSelection.hasClass("disabled"))
              $rightSelection.addClass("invalidSelection")
            else
              $rightSelection.removeClass("invalidSelection")
          }

          // standard filter for filtering after groups-attribute
          var airlineFilter = function ()
          {
            C.log("airlineFilter");
            var $leftSelection = $("#chooseFlight #leftFlightTable tbody tr:selectedRow");
            C.log($leftSelection);
            var id = $leftSelection.attr("airlineid");
            C.log(id);
            var $right = $("#chooseFlight #rightFlightTable tbody tr:not(:selectByAirlineId('"+id+"'))");
            $right.each(function(i,v){
              $(v).addClass("disabled");
            });
            $right = $("#chooseFlight #rightFlightTable tbody tr:selectByAirlineId('"+id+"')");
            $right.each(function(i,v){
              $(v).removeClass("disabled");
            });

            var $rightSelection = $("#chooseFlight #rightFlightTable tbody tr:selectedRow");
            if ($rightSelection.hasClass("disabled"))
              $rightSelection.addClass("invalidSelection")
            else
              $rightSelection.removeClass("invalidSelection")
          }

          if ($("#chooseFlight").attr("onlysameairline") == "true")
            airlineFilter();
          else
            groupFilter();
          $("#chooseFlight").cfcByebyePriceCheck();
        },

        transformCallback : function(response)
        {
          if (response["data"][phpConst.searchParam.countryDisableCombiFlights] == 1)
            $("#chooseFlight").attr("onlysameairline","true");
          else
            $("#chooseFlight").removeAttr("onlysameairline");
          $("#leftFlightTable").attr("defaultselection",response["data"][phpConst.flight.outFlightId]);
          $("#rightFlightTable").attr("defaultselection",response["data"][phpConst.flight.retFlightId]);

          //          C.log("flight transform1");
          if (response["data"][phpConst.sort.dir]["O"] == phpConst.sort.asc)
            ;//            C.log("ascend");
          else
            ;//            C.log("descend");


          // generate data for right flight table and populate table

          var x = Array();
          x["data"] = Array();
          x["data"]["R"] = response["data"]["R"];
          x = $("#rightFlightTable").tmGetTransformCallback()(x);


          $("#rightFlightTable").populateTable(x,$("#rightFlightTable"));

          // fill left table
          response["data"] = response["data"]["O"];

          var len = response["data"].length;

          // remove year in date column and add checkbox
          for (var i = 0; i < len; i++)
          {
            var item = response["data"][i];
            var items = item[phpConst.flight.departureDate].split(".");

            var dtm = Date.fromString(item[phpConst.flight.departureDate]);
            item["day"] = dtm.getDayName(true);

            item.dateShort = getText ('txt.chooseFlight.table.date.format',
              items[0], items[1]);
          };

          return response;
        },
        sortColumn: 'columnFirst',
        'cssAsc': 'headerSortDown',
        'cssDesc' : 'headerSortUp',
        'cssHeader' :'headerUnsorted',
        'emptyRow' : '<tr><td class="columnFirst"></td><td class="columnDay"></td><td class="columnDeparture"></td><td class="columnArrival"></td> <td class="columnAirline"></td> <td class="columnPrice"></td></tr>'
      } );


      $("#rightFlightTable").tableManager(
      {
        renderDirective : {
          'tr' : 'line <- data',   // no 'tbody tr' since we are rendering directly into the body fragment and not into the whole table
          'tr[selectionid]' : 'line.'+phpConst.flight.flightId,
          'tr[airlinecode]' : 'line.'+phpConst.flight.airlineCode,
          'tr[airlineid]' : 'line.'+phpConst.flight.airlineId,
          'tr[airlinename]' : 'line.'+phpConst.flight.airlineName,
          'tr[flightnumber]' : 'line.'+phpConst.flight.flightnumber,
          'tr[date]' : 'line.'+phpConst.flight.departureDate,
          'tr[overnight]' : 'line.'+phpConst.flight.overnight,
          'tr[flightid]' : 'line.'+phpConst.flight.flightId,
          'tr[destairportname]' : 'line.'+phpConst.flight.destAirportName,
          'tr[price]' : 'line.'+phpConst.flight.priceFloat,
          'tr[group]' : 'line.'+phpConst.flight.airlineGroup,
          'td.columnFirst' : 'line.dateShort',
          'td.columnDay' : 'line.day',
          'td.columnDeparture' : 'line.'+phpConst.flight.departureTime,
          'td.columnArrival' : function(context) {
            var arrival = context["item"][phpConst.flight.arrivalTime];
            if (context["item"][phpConst.flight.overnight] > 0)
              arrival += getText('txt.chooseFlight.overnightPlus', context["item"][phpConst.flight.overnight]);
            else if (context["item"][phpConst.flight.overnight] < 0)
              arrival += getText('txt.chooseFlight.overnightMinus', (-1) * context["item"][phpConst.flight.overnight]);
            return(arrival);
          },
          'td.columnAirline' : 'line.'+phpConst.flight.airlineName,
          'td.columnPrice' :  function(context){
            //            C.log(context["item"]);
            //            C.log(context["item"][phpConst.flight.price]);
            if (context["item"][phpConst.flight.price] == phpConst.flight.BYE) //real
              //                                            if (context["item"][phpConst.flight.price] < 100) //für Tests
              return "";
            else
              return getText('txt.common.euro', context["item"][phpConst.flight.price] );
          },
          'td.columnPrice[class]' : function(context){

            // for testing purpose:
            //            if (context["item"][phpConst.flight.price] < 150)
            //              context["item"][phpConst.flight.price] = phpConst.flight.BYE;

            if (context["item"][phpConst.flight.price]  == phpConst.flight.BYE)
              return "columnPrice byebyeflight byebyeflightRed";
            else
              return "columnPrice";
          }
        },
        headers: {
          1: {                                                  // 1 means: sort column 1 (index based 0) using the dayparser plugin
            sorter: 'dayparser'
          }
        },
        id : "#rightFlightTable",
        JSONaction : "result_flights",
        updateCallback : function($tab){
        //            C.log("Update a Callback Right");
        },
    

        selectCallback : function($tab){
          $("#chooseFlight").cfcByebyePriceCheck();

          if ($("#chooseFlight").cfcGetSelectFlightTableCallback() != undefined)
            $("#chooseFlight").cfcGetSelectFlightTableCallback()($tab);

          $("#chooseFlight").cfcByebyePriceCheck();
        },
        transformCallback : function(response)
        {
          response["data"] = response["data"]["R"];
          var len = response["data"].length;

          // remove year in date column and add checkbox
          for (var i = 0; i < len; i++)
          {
            var item = response["data"][i];
            var items = item[phpConst.flight.departureDate].split(".");


            var dtm = Date.fromString(item[phpConst.flight.departureDate]); //item[phpConst.flight.departureDate]));
            item["day"] = dtm.getDayName(true);

            item.dateShort = getText ('txt.chooseFlight.table.date.format',
              items[0], items[1]);
          };
          return response;
        },
        sortColumn: 'columnFirst',
        highlightCSS: 'blue',
        'cssAsc': 'asc2',
        'cssDesc' : 'desc',
        'cssHeader' :'list',
        'emptyRow' : '<tr><td class="columnFirst"></td><td class="columnDay"></td><td class="columnDeparture"></td><td class="columnArrival"></td> <td class="columnAirline"></td> <td class="columnPrice"></td></tr>'
      } );

    },

    cfcScrollIntoView : function()
    {
      $("#leftFlightTable").tmScrollIntoView();
      $("#rightFlightTable").tmScrollIntoView();
    },


    cfcGetSortingKey : function()
    {
      var key = {};
      key["O"] = $("#leftFlightTable").tmGetSortingKey();
      key["R"] = $("#rightFlightTable").tmGetSortingKey();
      //      C.log("cfcGetSortKey");
      //      C.log(key);
      return(key);
    },

    cfcGetSortingDir : function()
    {
      var dir = {};
      dir["O"] = $("#leftFlightTable").tmGetSortingDir();
      dir["R"] = $("#rightFlightTable").tmGetSortingDir();
      return(dir);
    },

    cfcGetData : function()
    {
      var cSP = phpConst.searchParam;
      var cF = phpConst.flight;
      var data = {};
      var $hin = $("#leftFlightTable tr:selectedRow");
      var $rueck = $("#rightFlightTable tr:selectedRow");
      var msData = $("#modifySearch").msGetData();

      var key = $("#chooseFlight").cfcGetSortingKey();
      var dir = $("#chooseFlight").cfcGetSortingDir();

      data[phpConst.sort.key] = key;
      data[phpConst.sort.dir] = dir;

      var flight1 = {};
      flight1[cSP.date] = $hin.attr("date");
      flight1[cF.flightnumber] = $hin.attr("flightnumber");
      flight1[cSP.travelAirportName] = msData[cSP.travelAirportName];
      flight1[cF.departureTime] = $("td.columnDeparture", $hin).text();
      flight1[cSP.travelDestinationName] = msData[cSP.travelDestinationName];
      flight1[cF.arrivalTime] = $("td.columnArrival", $hin).text();
      flight1[cF.price] = $("td.columnPrice", $hin).text();
      flight1[cF.airlineCode] = $hin.attr("airlinecode");
      flight1[cF.airlineId] = $hin.attr("airlineid");
      flight1[cF.airlineName] = $hin.attr("airlinename");
      flight1[cF.flightId] = $hin.attr("flightid");
      flight1[cF.destAirportName]  = $hin.attr("destairportname");
      data[cSP.flightDirOutbound] = flight1;


      var flight2 = {};
      flight2[cSP.date] = $rueck.attr("date");
      flight2[cF.flightnumber] = $rueck.attr("flightnumber");
      flight2[cSP.travelAirportName] = msData[cSP.travelAirportName];
      flight2[cF.departureTime] = $("td.columnDeparture", $rueck).text();
      flight2[cSP.travelDestinationName] = msData[cSP.travelDestinationName];
      flight2[cF.arrivalTime] = $("td.columnArrival", $rueck).text();
      flight2[cF.price] = $("td.columnPrice", $rueck).text();
      flight2[cF.airlineCode] = $rueck.attr("airlinecode");
      flight2[cF.airlineId] = $rueck.attr("airlineid");
      flight2[cF.airlineName] = $rueck.attr("airlinename");
      flight2[cF.flightId] = $rueck.attr("flightid");
      flight2[cF.destAirportName]  = $rueck.attr("destairportname");
      data[cSP.flightDirReturn] = flight2;

      //data[cF.price] = parseInt(flight1[cF.price], 10) + parseInt(flight2[cF.price], 10);

      return data;
    },
    cfcReset : function()
    {

    },
    cfcSetData : function(data)
    {

    },

    cfcSetOnErrorLinkAction : function(callback)
    {
      return _w.call(this, 'setOnErrorLinkAction', callback);
    },
    cfcGetOnErrorLinkAction : function()
    {
      var c = _getController(this[0]);
      if (c) {
        return c.getOnErrorLinkAction();
      }
      return null;
    },


    cfcUpdateGUI : function()
    {
      var cSP = phpConst.searchParam;
      var cF = phpConst.flight;
      var cOut = cSP.flightDirOutbound;
      var cRet = cSP.flightDirReturn;

      var data = $("#chooseFlight").cfcGetData();

      $("#chooseFlight")._cfcUpdateGUI($("#leftChooseFlight-infoHeader"),
        $("#leftFlightTable.flightTable"),
        data[cOut][cSP.date],
        data[cOut][cF.flightnumber],
        data[cOut][cSP.travelAirportName],
        data[cOut][cF.departureTime],
        data[cOut][cF.destAirportName],
        data[cOut][cF.arrivalTime],
        data[cOut][cF.airlineName],
        data[cOut][cF.airlineCode]
        );

      $("#chooseFlight")._cfcUpdateGUI($("#rightChooseFlight-infoHeader"),
        $("#rightFlightTable.flightTable"),
        data[cRet][cSP.date],
        data[cRet][cF.flightnumber],
        data[cRet][cF.destAirportName],
        data[cRet][cF.departureTime],
        data[cRet][cSP.travelAirportName],
        data[cRet][cF.arrivalTime],
        data[cRet][cF.airlineName],
        data[cRet][cF.airlineCode]);

      var iVal = parseInt(data[cOut][cF.price], 10);
      var sum = isNaN(iVal) ?  0 : iVal;

      iVal = parseInt(data[cRet][cF.price], 10);
      sum +=  isNaN(iVal) ?  0 : iVal;

      // if either first oder second flight has no price == is byebye flight
      // set byebyeflight to true => logo is shown instead of price

      var fdata = $("#chooseFlight").cfcGetData();
      var msdata = $("#modifySearch").msGetData();


      $(".statusPanel").setGUI(fdata[cSP.flightDirOutbound][cSP.date],
        $("#chooseFlight").cfcGetTravelDuration(),
        msdata[cSP.numAdult],
        msdata[cSP.numChild],
        "");

      $(".statusPanel").spSetPrice(formatPrice(sum),
        isNaN( parseInt(data[cOut][cF.price], 10) )
        ||
        isNaN (parseInt(data[cRet][cF.price], 10) ) );
      $("div.statusPanel", $("#bookingArea")).showFlightSummary();
    },
    _cfcUpdateGUI : function($info, $table, date, flightNo, depAirport, depTime, destAirport,destTime, airline, airlineCode)
    {
      $table = $table.parent().parent();
      // head
      $(".destination", $info).text(getText('txt.common.till', depAirport, destAirport));

      // table foot
      dateStr = "ERROR in chooseFlightController.js";
      if (date != null){
        dateStr = (Date.fromString( date));
        if (dateStr)
          dateStr = dateStr.getDayName();
      }

      var $fid = $table.find(".flightInfoDetails");

      var xdata = {
        place1: getText('txt.chooseFlight.depPlace',depAirport),
        time1: getText('txt.chooseFlight.time',depTime),
        place2: getText('txt.chooseFlight.arrPlace',destAirport),
        time2: getText('txt.chooseFlight.time',destTime),
        moreInfo: "<a class=\"more\" href=\"javascript:$('.statusPanel').spbbFlightInfoButton();\">"+getText('txt.chooseFlight.flightInfos')+"</a>"
      };

      $table.find('.flightInfoDetails').autoRender(xdata);
      $table.find(".flightInfoFooter .date").attr("innerHTML",dateStr+", "+date);
      $table.find(".flightInfoFooter .flightNo").attr("innerHTML",getText('txt.chooseFlight.flight',airlineCode,flightNo,airline));
    },


    cfcFlightCombinationValid : function()
    {
      var $hin = $("#leftFlightTable tr:selectedRow");
      var $rueck = $("#rightFlightTable tr:selectedRow");
      var outDate = $hin.attr("date");
      var retDate = $rueck.attr("date");
      var out = outDate.split(".");
      var ret = retDate.split(".");
      var valid = false;
      if (out[2] < ret[2])
        valid = true;
      else if (out[1] < ret[1] && out[2] <= ret[2])
        valid = true;
      else if (out[0] < ret[0] && out[1] <= ret[1] && out[2] <= ret[2])
        valid = true;
      return valid;
    },

    cfcGetTravelDuration : function()
    {
      var cSP = phpConst.searchParam;
      var cF = phpConst.flight;
      var cOut = cSP.flightDirOutbound;
      var cRet = cSP.flightDirReturn;

      var data = $("#chooseFlight").cfcGetData();
      var diff = undefined;
      if (data[cOut][cSP.date] && data[cRet][cSP.date])
      {
        var d1 = parseDate(data[cOut][cSP.date]);
        var d2 = parseDate(data[cRet][cSP.date]);
        var day = 1000*60*60*24;
        // round should be used to eliminate problems with
        // winter/summer time switch
        diff = Math.round ((d2.getTime()-d1.getTime())/(day));

//        C.log("cfcGetTravelDuration()")
//        C.log(dat1);
//        C.log(dat2);
//        C.log(d1);
//        C.log(d2);
//        C.log(diff);

        if (diff <= 0 )
          diff = getText('txt.common.doubleDash');
      }
      return diff;
    },

    cfcGetTravelDate : function()
    {
      var cSP = phpConst.searchParam;
      var cOut = cSP.flightDirOutbound;
      var data = $("#chooseFlight").cfcGetData();
      return data[cOut][cSP.date];
    },

    cfcTravelDurationBelowMaxTravelDuration : function()
    {
      var res = false;
      var td = $("#chooseFlight").cfcGetTravelDuration();
      if (td != undefined)
      {
        if (td <= phpConst.travel.maxTravelDurationValue)
          res = true;
      }
      return res;
    },

    cfcAllFormfieldsFilled : function()
    {
      return $("#chooseFlight").cfcFlightCombinationValid();
    },

    cfcExecuteFlightFilter : function ()
    {
      // get some initial data from filter panel, abort if incorrect
      var preisProStrecke = $("input[@name='preisProStrecke']:checked").val();
      var hinflugzeit = $("input[@name='hinflugzeit']:checked").val();
      var rueckflugzeit = $("input[@name='rueckflugzeit']:checked").val();
      if ( (preisProStrecke == undefined) || (hinflugzeit == undefined) || (rueckflugzeit ==undefined) )
      {
        alert("ERROR 001");
        return;
      }

      // Check, which tables have to be filtered
      // after check, lists contains the tables to be filtered
      var lists = Array();
      if (preisProStrecke == "HinRueck")
      {
        lists[0] = "#leftFlightTable tbody";
        lists[1] = "#rightFlightTable tbody";
      }
      else if (preisProStrecke == "Hinflug")
        lists[0] = "#leftFlightTable tbody";
      else if (preisProStrecke == "Rueckflug")
        lists[0] = "#rightFlightTable tbody";


      // run the filter over the selected tables
      for (var i = 0; i < lists.length; i++)       // for each table do:
        $(lists[i]).find("tr").each(function(l,d)  // for each row do:
        {
          // get wish for start and end time and the requested price (Filter)
          var start1 = parseInt($("#outwardFlightSlider1").text(),10);
          var start2 = parseInt($("#outwardFlightSlider2").text(),10);

          var end1 = parseInt($("#returnFlightSlider1").text(),10);
          var end2 = parseInt($("#returnFlightSlider2").text(),10);

          var min = parseInt($("#flightPriceSlider1").text(),10);
          var max = parseInt($("#flightPriceSlider2").text(),10);

          // have a look at each airline, if checked, add to airlineCodes array
          var airlineCodes = Array();
          $("#flightFilterAirlineList").find("li").each(function()
          {
            if ($(this).find("input").attr("checked") == true)
            {
              var x = $(this).find("input").attr("id");
              x = x.substring(4,x.length);
              airlineCodes[x] = true;
            }
          });

          // get corresponding values for actual <tr> entry
          var row = $(this);
          var rowPrice = parseInt($(this).attr("price"),10);
          var airlineCode = $(this).attr("airlinecode");
          // get hour of arrival and departure
          var arrival = parseInt($(this).find(".columnArrival").text().split(":")[0],10);
          var departure = parseInt($(this).find(".columnDeparture").text().split(":")[0],10);

          // check wheter to hide or unhide the current column
          // hide all flights but byebyeflights by default
          if (!row.find(".columnPrice").hasClass("byebyeflight"))
            row.addClass("hidden");

          if (    (parseInt(min,10) <= parseInt(rowPrice,10)) && (parseInt(rowPrice,10) <= parseInt(max,10)) // price valid?
            && (airlineCodes[airlineCode] == true)) // airline selected?
            {
            // and now some table specific stuff, so find out which table we are and proceed
            if ($(this).parent().parent().attr("id").search(/leftFlightTable/) != -1) // are we in the left table?
            {
              if (  ((hinflugzeit=="Ankunft") && (start1 <= arrival) && (arrival <= start2))
                ||
                ((hinflugzeit=="Abflug")  && (start1 <= departure) && (departure <= start2))
                  )
                row.removeClass("hidden");
            }

            if ($(this).parent().parent().attr("id").search(/rightFlightTable/) != -1) // are we in the right table?)
            {
//          C.log("filter:");
//          C.log("     Start1: "+start1);
//          C.log("     Start2: "+start2);
//          C.log("       end1: "+end1);
//          C.log("       end2: "+end2);
//          C.log("        min: "+min);
//          C.log("        max: "+max);
//          C.log("        row: "); C.log(row);
//          C.log(  "   rowPrice: "+rowPrice);
//          C.log("  airlineCode: "+airlineCode);
//          C.log("rueckflugzeit:" + rueckflugzeit)
//          C.log("      arrival: "+arrival);
//          C.log("    departure: "+departure);
//          C.log("end1 <= arrival" + (end1 <= arrival) );
//          C.log("arrival <= end2" + (arrival <= end2) );
//          C.log("end1 <= departure" + (end1 <= departure) );
//          C.log("departure <= end2" + (departure <= end2) );

              //C.log(row);
              // check, if departure/arrival time is valid
              if (  ((rueckflugzeit=="Ankunft") && (end1 <= arrival) && (arrival <= end2))
                ||
                ((rueckflugzeit=="Abflug")  && (end1 <= departure) && (departure <= end2))
                  )
                row.removeClass("hidden");
            }
          }

        });

      // finally, trigger an update, to show changes
      $("#leftFlightTable").trigger("update");
      $("#rightFlightTable").trigger("update");

      // hide filter
//      C.log("PLEASE HAVE A LOOK AT jquery.chooseFlightController.js, : 346, replace $bookingArea by callback")
      $("#bookingArea").amToggleFlightFilter();
    },


    cfcByebyePriceCheck : function()
    {
      var left =  $("tr:selectedRow td.columnPrice", $("#leftFlightTable")).hasClass("byebyeflightOrange");
      var right = $("tr:selectedRow td.columnPrice", $("#rightFlightTable")).hasClass("byebyeflightRed");

      var $sp = $(".statusPanel",$("#bookingArea"));

      //          C.log("---- right table");
      //          C.log(left);
      //          C.log(right);

      if (left  ||  right)
      {
        $("#priceStandard").hide();
        $sp.setCommandPanelButtons(undefined,false,undefined, undefined);

        $("#pricebyebye").show();
        $(".helpCenter").hccBindCallback("#pricebyebye");
        C.log("rebinding helpcenter #pricebyebye");
      }
      else
      {
        //            C.log("show");
        $("#pricebyebye").hide();
        $("#priceStandard").show();
        if ($("#chooseFlight").attr("stopavailable") == "true")
          $sp.setCommandPanelButtons(undefined,true,undefined, undefined);
      }

    },

    cfcGetSelectFlightTableCallback : function($table)
    {
      var c = _getController(this[0]);
      if (c) {
        return c.getSelectFlightTableCallback($table);
      }
      return null;
    },
    cfcGetContext : function()
    {
      var c = _getController(this[0]);
      if (c) {
        return c.getContext();
      }
      return null;
    },


    _cfcDestroy : function()
    {
    // TODO - implement this?
    }
  });

  // private internal function to cut down on the amount of code needed where we forward
  // dp* methods on the jQuery object on to the relevant DatePicker controllers...
  var _w = function(f, a1, a2, a3)
  {
    return this.each(
      function()
      {
        var c = _getController(this);
        if (c) {
          c[f](a1, a2, a3);
        }
      }
      );
  };

  function ChooseFlightController(ele)
  {
    this.ele = ele;

    // initial values...
    this.id				=	undefined;
    this.$context			=	undefined;
    this.selectFlightTableCallback = undefined;
    this.onErrorLinkAction = undefined;
  };
  $.extend(
    ChooseFlightController.prototype,
    {
      init : function(s)
      {
        this.id = s.id;
        this.$context = $(s.id);
        this.selectFlightTableCallback = s.selectFlightTableCallback;
        this.onErrorLinkAction = s.onErrorLinkAction;
      },
      setSelectFlightTableCallback : function(a)
      {
        if (a && typeof(a) == 'function') {
          this.selectFlightTableCallback = [a];
        }
        this.selectFlightTableCallback = this.selectFlightTableCallback.concat(a);
      },
      getSelectFlightTableCallback : function(d)
      {
        return(this.selectFlightTableCallback);
      },
      getContext : function()
      {
        return(this.$context);
      },
      setOnErrorLinkAction : function(d)
      {
        if (d) {
          this.onErrorLinkAction = d;
        }
      },
      getOnErrorLinkAction : function(d)
      {
        return(this.onErrorLinkAction);
      }


    }
    );

  function _getController(ele)
  {
    if (ele._cfcId) return $.event._cfcCache[ele._cfcId];
    return false;
  };

  // make it so that no error is thrown if bgIframe plugin isn't included (allows you to use conditional
  // comments to only include bgIframe where it is needed in IE without breaking this plugin).
  if ($.fn.bgIframe == undefined) {
    $.fn.bgIframe = function() {
      return this;
    };
  };


  // clean-up
  $(window)
  .bind('unload', function() {
    var els = $.event._cfcCache || [];
    for (var i in els) {
      $(els[i].ele)._cfcDestroy();
    }
  });
})(jQuery);
