/**
 * $Id: jquery.filterHotelsController.js 2409 2009-05-18 15:01:01Z Bjoern.Moenikes $
 **/

(function($){

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

      // initialise the date picker controller with the relevant settings...
      options = $.extend(
      {
        renderDirective : '',                  // needed for autorenderer
        emptyRow : ' ',
        updateCallback : undefined, // function is beeing called after update
        selectCallback : undefined, // function is beeing called after change of selection
        JSONaction : undefined
      }
      , options
      );

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

          if (!this._fhId) {
            this._fhId = $.event.guid++;
            $.event._fhCache[this._fhId] = new FilterHotelsController(this);
            alreadyExists = false;
          }

          var controller = $.event._fhCache[this._fhId];

          controller.init(options);

          //            INIT

          $("#fhcategory").ulPopup({
            popupId : "#fhcategory",
            popupHeadline : getText('txt.flightFilter.category'),
            onChangeCallback : function() {
            //$("#modifySearch").updateOKButtonStatus();
            },
            data:[{
              className : 'travelAirportList',
              items : {} //data.data
            }]
          });

          $("#fhlocation").ulPopup({
            popupId : "#fhlocation",
            popupHeadline : getText('txt.flightFilter.location'),
            onChangeCallback : function() {
            //$("#modifySearch").updateOKButtonStatus();
            },
            data:[{
              className : 'travelAirportList',
              items : {} //data.data
            }]
          });

          
          // Workaround for slide effect in IE
          // if no defaultChecked attribute found, then no radio selected after
          // sliding (see http://dev.jquery.com/ticket/1095#comment:4)
          var str = "hinflugzeit rueckflugzeit preisProStecke".split(" ");
          for (var j = 0; j < str.length; j++)
            $("#filterFlights input:radio[name='"+str[j]+"']").click(function() {
              $("#filterFlights input:radio[name='"+str[j]+"']").removeAttr('defaultChecked').removeAttr('checked');
              $(this).attr('checked', 'checked').attr('defaultChecked', 'checked');
            });
        }
        )
    },
    // maps f:[0..100] to  [0..24]
    normalizeTo24h: function(id, value)
    {
      var lowPrice = parseInt( $(id+"1").attr( "hour"), 10 );
      var highPrice = parseInt( $(id+"2").attr( "hour"), 10 );
      var range = highPrice - lowPrice;
      //return(Math.round(24/100 * value));
      var erg = Math.round( lowPrice + range / 100 * value);
      return erg;
    },


    // maps f:[0..100] to [min..max]
    normalizeToPrice : function(value)
    {
      var lowPrice = parseInt( $("#flightPriceSlider1").attr( "price"), 10 );
      var highPrice = parseInt( $("#flightPriceSlider2").attr( "price"), 10 );
      var range = highPrice - lowPrice;
      var erg = Math.floor( lowPrice + value * (range / 100.0) );
      return erg;
    },






    // Filter the actual list of flights by using the data entered in FLIGHT.filter
    fhcExecuteHotelFilter : function()
    {
      $("#chooseHotel").chcExecuteHotelFilter();
    
    },




    fhcAdjustHotelFilter : function()
    {
      var getColumnUnique = function(xclass, first)
      {
        var obj = {};
        $("#hotelTable tbody td."+xclass).each(function(index, item){
          obj[$(item).text()] = 'X';
        });
        var arr = [];
        var i = 0;
        for(var val in obj)
          if (val != "")
            arr[i++] = val;
        arr = arr.sort();

        if (first != undefined)
          arr.unshift(first);
        return arr;
      }

      var prepRender = function(arr)
      {
        var res = [];
        for (var j = 0; j < arr.length; j++)
        {
          var item = function(a, b, c)
          {
            this.txtValue = a;
            this.styleClass = b;
            this.data = c;
          }
          res.push(new item(arr[j],"",arr[j]));
        }
        return(res);
      }


      var cat = prepRender(getColumnUnique("columnCategory",getText('txt.flightFilter.category.first')));
      var loc = prepRender(getColumnUnique("columnLocation",getText('txt.flightFilter.location.first')));

      var catData = [{
        className : 'travelAirportList',
        items : cat
      }];

      var locData = [{
        className : 'travelAirportList',
        items : loc
      }];

      var $cat = $("#fhcategory");
      var $loc = $("#fhlocation");
      $cat.ulpGenerateContent(catData, "#fhcategoryPopup div.fhcategory div");
      $("#fhcategory").pResetEvents();
      $loc.ulpGenerateContent(locData, "#fhlocationPopup div.fhlocation div");
      $("#fhlocation").pResetEvents();

      $("#fhcategory").attr("data",getText('txt.flightFilter.category.first')).change();
      $("#fhlocation").attr("data",getText('txt.flightFilter.location.first')).change();
    },

  
    _fhDestroy : 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 FilterHotelsController(ele)
  {
    this.ele = ele;

    // initial values...
    this.id				=	undefined;
    this.$context			=	undefined;

  };
  $.extend(
    FilterHotelsController.prototype,
    {
      init : function(s)
      {
        this.id = s.id;
        this.$context = $(s.id);
      }


    }
    );

  function _getController(ele)
  {
    if (ele._fhId) return $.event._fhCache[ele._fhId];
    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._fhCache || [];
    for (var i in els) {
      $(els[i].ele)._fhDestroy();
    }
  });


})(jQuery);