/**
* $Id: jquery.chooseHotelController.js 2492 2009-09-18 10:35:09Z Bjoern.Moenikes $
**/

(function($){

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

      // initialise the date picker controller with the relevant settings...
      options = $.extend(
      {
        id : '',
        $context : ''
      }
      , options
      );

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

          if (!this._chcId) {
            this._chcId = $.event.guid++;
            $.event._chcCache[this._chcId] = new ChooseHotelController(this);
            alreadyExists = false;
          }
          var controller = $.event._chcCache[this._chcId];
          controller.init(options);
          $this.chcInit();
        }
        )
    },

    chcExecuteHotelFilter : function()
    {
      //      C.log("EXECUTE HOTEL FILTER");

      var category = category2value($("#fhcategory").val());
      var searchCat = false;
      if (category != getText('txt.flightFilter.category.first'))
        searchCat = true;

      var location = $("#fhlocation").val();
      var searchLoc = false;
      if (location != getText('txt.flightFilter.location.first'))
        searchLoc = true;

      //      C.log("chcExecuteHotelFilter");
      //      C.log(category);
      //      C.log(searchCat);
      //      C.log(location);
      //      C.log(searchLoc);

      $("#hotelTable tbody tr").each(function(index, item){
        var visible = true;
        var $item = $(item, $("#hotelTable"));

        //          C.log(item)
        //          C.log($item);

        if (searchCat)
          if (category2value($("td.columnCategory", $item).text()) < category)
            visible = false;

        if (searchLoc)
        {
          //          C.log("TEST");
          //          C.log(location);
          //          C.log($("td.columnLocation", $item));

          if ($("td.columnLocation", $item).text() != location)
            visible = false;
        }
        if (visible)
          $item.show();
        else
          $item.hide();
      });
      $("#bookingArea").ambbHotelsFilternCallback();
    },

    chcInit : function(){
      $("#hotelTable").tableManager(
      {
        loadStringID : 'hotel',
        stringVar1 : function(){  
          return " ";
        },  //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.hotel.hotelId,
          'td.columnFirst div' : 'line.' + phpConst.hotel.hotelName,
          'td.columnCategory div' : 'line.' + phpConst.hotel.hotelCategoryCode,
          'td.columnCategory[float]' : function(context) {
            return (category2value(context["item"][phpConst.hotel.hotelCategoryCode]));
          },
          'td.columnLocation div' : 'line.' + phpConst.hotel.placeName,
          'td.columnAccommodation div' : 'line.' + phpConst.hotel.roomDescription,
          'td.columnMeals div' : 'line.' + phpConst.hotel.mealName,
          'td.columnPrice div'  : function(context){
            return getText('txt.common.euro', context["item"][phpConst.total.priceAdultComplete] );
          },//: 'line.' +  phpConst.total.priceAdultComplete,
          // title popup
          'td.columnFirst[title]' : 'line.' + phpConst.hotel.hotelName,
          'td.columnCategory[title]' : 'line.' + phpConst.hotel.hotelCategoryCode,
          'td.columnLocation[title]' : 'line.' + phpConst.hotel.placeName,
          'td.columnAccommodation[title]' : 'line.' + phpConst.hotel.roomDescription,
          'td.columnMeals[title]' : 'line.' + phpConst.hotel.mealName,
          'td.columnPrice[title]' : 'line.' + phpConst.total.priceAdultComplete,
          'tr[countryname]' : 'line.' + phpConst.hotel.countryName,
          'tr[hotelcode]' : 'line.' + phpConst.hotel.hotelCode,
          'tr[seasoncode]' : 'line.' + phpConst.hotel.seasonCode,
          'tr[hotelimage]' : 'line.' + phpConst.hotel.hotelImage,
          'tr[alt]' : 'line.' + phpConst.hotel.hotelName,
          'tr[hoteldescription]' : 'line.' + phpConst.hotel.hotelDescription
        },
        headers: {
          1 : {
            sorter: 'category'
          },
          5 : {
            sorter: 'currency2'
          }
        },
        id : "#hotelTable",
        JSONaction : "result_hotels",
        onErrorLinkAction : function() {
          if ($("#chooseHotel").chcGetOnErrorLinkAction() != undefined)
            $("#chooseHotel").chcGetOnErrorLinkAction()();
        },
        onSuccessAction : function() {
        },

        updateCallback : function(){
        },
        selectCallback : function(s){
          $("#chooseHotel").selectInHotelTable();

        },
        transformCallback : function(response)
        {
          $("#hotelTable").attr("defaultselection",response["data"][phpConst.hotel.hotelId]);
          response["data"] = response["data"][phpConst.hotel.result];
          return(response);
        },
        sortColumn: 'columnDate',
        'cssAsc': 'asc',
        'cssDesc' : 'desc',
        'cssHeader' :'list',
        'emptyRow' : '<tr>'
      + '<td class="columnFirst"><div class="hotelName"></div></td>'
      + '<td class="columnCategory"><div class="columnCategory"></div></td>'
      + '<td class="columnLocation"><div class="columnLocation"></div></td>'
      + '<td class="columnAccommodation"><div class="columnAccommodation"></div></td>'
      + '<td class="columnMeals"><div class="columnMeals"></div></td>'
      + '<td class="columnPrice"><div class="columnPrice"></div></td>'
      + '</tr>'
      } );

      $("#roomDescTable").tableManager(
      {
        loadStringID : '',
        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.hotel.roomMealId,
          'td.columnFirst div'  : function(context){
            return getText('txt.chooseHotel.accomodation',
              context["item"][phpConst.hotel.roomNum],
              context["item"][phpConst.hotel.roomDescription]);
          },//: 'line.' +  phpConst.total.priceAdultComplete,
          'td.columnMeals div' : 'line.' + phpConst.hotel.mealName,
          'td.columnPrice' : function(context){
            return getText('txt.common.euro', context["item"][phpConst.total.priceAdultComplete] );
          },// : 'line.' + phpConst.total.priceAdultComplete,
          // title popup
          'td.columnFirst[title]' : 'line.' + phpConst.hotel.roomDescription,
          'td.columnMeals[title]' : 'line.' + phpConst.hotel.mealName,

          'tr[roommealid]' : 'line.' + phpConst.hotel.roomMealId,
          'tr[title]' : 'line.' + phpConst.hotel.roomDescription,
          'tr[roomcode]' : 'line.' + phpConst.hotel.roomCode,
          'tr[roomnum]' : 'line.' + phpConst.hotel.roomNum,
          'tr[priceadultcomplete]' : 'line.' + phpConst.total.priceAdultComplete,
          'tr[pricechild]' : 'line.' + phpConst.total.priceChildComplete,
          'tr[pricebaby]' : 'line.' + phpConst.total.priceBabyComplete,
          'tr[mealcode]' : 'line.' + phpConst.hotel.mealCode,
          'tr[mealname]' : 'line.' + phpConst.hotel.mealName
        },
        headers: {
          2 : {
            sorter: 'currency2'
          }
        },
        id : "#roomDescTable",
        showLoadOnUpdate : false,
        JSONaction : "result_hotels",
        updateCallback : function(){
        },
        selectCallback : function(s){
          $("#chooseHotel").selectInRoomDescTable();
        },
        transformCallback : function(response)
        {          
          $("#roomDescTable").attr("defaultselection",response["data"][phpConst.hotel.roomMealId]);
          response["data"] = response["data"][phpConst.hotel.result];
          return(response);
        },
        sortColumn: 'columnFirst',
        'cssAsc': 'asc',
        'cssDesc' : 'desc',
        'cssHeader' :'list',
        'emptyRow' : '<tr>'
      + '<td class="columnFirst"><div class="roomDesc"></div></td>'
      + '<td class="columnMeals"><div class="columnMeals"></div></td>'
      + '<td class="columnPrice"></td>'
      + '</tr>'
      } );
    },
    chcSetOnErrorLinkAction : function(callback)
    {
      return _w.call(this, 'setOnErrorLinkAction', callback);
    },
    chcGetOnErrorLinkAction : function()
    {
      var c = _getController(this[0]);
      if (c) {
        return c.getOnErrorLinkAction();
      }
      return null;
    },
    chcScrollIntoView : function()
    {
      $("#hotelTable").tmScrollIntoView();
      $("#roomDescTable").tmScrollIntoView();
    },

    selectInHotelTable : function()
    {
      $("#chooseHotel").chcUpdateGUI();
    },

    selectInRoomDescTable : function()
    {
      var hotel = this.chcGetData ();
      $(".statusPanel").spSetPrice(hotel[phpConst.hotel.priceAdultComplete]);
    },



    // expects [{"hotelimage" : "bild.jpg", "alt" : "description"}]
    clearAndFillCycler : function(cycler, data, nextButton, prevButton)
    {
      $(cycler).cycle('stop').find("img").remove();
      if (data != undefined)
        for (var i = 0; i <= data.length; i++)
          if (data[i] != undefined)
            $(cycler).append('<img src="'+data[i]['hotelimage'] +'" alt="'+ data[i]["alt"] +'" />');


      if (nextButton && nextButton.length > 0)
      {
        // init jquery objects
        $(cycler).cycle({
          fx:     'fade',
          speed:  'fast',
          timeout: 0,
          next:   nextButton,
          prev:   prevButton
        });
      }
      else
      {
        $(cycler).cycle({
          fx:     'fade',
          speed:  'fast',
          timeout: 0
        });
      }
    },


    chcGetData : function()
    {
      var hotel = {};
      var cH = phpConst.hotel;
      var $selectedHotel = $("#hotelTable tr:selectedRow");

      if ($selectedHotel != null && typeof $selectedHotel != undefined)
      {
        hotel[cH.hotelName] = $("td.columnFirst", $selectedHotel).text();
        hotel[cH.hotelCategoryName] = $('td.columnCategory', $selectedHotel).text();
        hotel[cH.hotelDescription] = $selectedHotel.attr('hoteldescription');
        hotel[cH.placeName] = $('td.columnLocation', $selectedHotel).text();
        hotel[cH.hotelImage] = $selectedHotel.attr('hotelimage');
        hotel[cH.hotelCode] = $selectedHotel.attr('hotelcode');
        hotel[cH.seasonCode] = $selectedHotel.attr('seasoncode');
        hotel[cH.countryName]  = $selectedHotel.attr('countryname');
        hotel['categoryStyleClass'] = '';

        var dc = hotel[cH.hotelCategoryName];
        if (dc != null)
        {
          var stars = dc.replace('+', 'plus')
          hotel["categoryStyleClass"] = 'stars stars' + stars;
        }
      }

      var $selectedRoom = $("#roomDescTable tr:selectedRow");
      if ($selectedRoom != null && typeof $selectedRoom != undefined)
      {
        hotel[cH.roomMealId] = $selectedRoom.attr('roommealid');
        hotel[cH.priceAdult] = $('td.columnPrice', $selectedRoom).text();
        hotel[cH.priceAdultComplete] = $selectedRoom.attr('priceAdultComplete');
        hotel[cH.roomNum] = $selectedRoom.attr('roomNum');
        hotel[cH.roomCode] = $selectedRoom.attr('roomcode');
        hotel[cH.mealCode] = $selectedRoom.attr('mealcode');
        hotel[cH.mealName] = $selectedRoom.attr('mealname');
        hotel[cH.roomDescription] = $selectedRoom.attr('title');
      }

      return hotel;
    },

    chcAllFormfieldsFilled : function(data)
    {
      return true;
    },

    // request information for specific hotel and display it
    chcUpdateGUI : function(noUpdate)
    {
      var cSP = phpConst.searchParam;
      var cF = phpConst.flight;
      var cH = phpConst.hotel;
      var cS = phpConst.step;
      var personal = $("#modifySearch").msGetData();
      var flight = $("#chooseFlight").cfcGetData();
      var hotel = $("#chooseHotel").chcGetData();

      var $travelArea = $("#chooseHotel-infoHeader .travelArea");
      var $hotelname = $("#chooseHotel div.header h3");
      var $stars = $("#chooseHotel div.header .stars");
      //var $more = $("#chooseHotel div.header a");
      var $hoteldescription = $("#chooseHotel div.header h4");
      var $location = $("#chooseHotel .hotelInfoDetails h5");
      //var $more2 = $("#chooseHotel .hotelInfoDetails more");
      var $more = $("#chooseHotel .more");

      var $ch = $("#chooseHotel");
      var $mainImg = $(".mainImg img", $ch);

      var hotelCode = hotel[cH.hotelCode];

      var $travelData = $("#chooseHotel-infoHeader .flightInfo .travelData");
      var steps = $("#bookingArea").amGetStepManager().stepStatus[cS.steps];
      if (steps[cS.flight] == cS.valid)
      {
        var $travelDepTime = $("#chooseHotel-infoHeader .flightInfo .depTime");
        var $travelDstTime = $("#chooseHotel-infoHeader .flightInfo .dstTime");

        $travelData.text(getText('txt.common.till',
          personal[cSP.travelAirportName],
          personal[cSP.travelDestinationName]));
        $travelDepTime.text(getText('txt.header.travel.times',
          flight[cSP.flightDirOutbound][cF.departureTime],
          flight[cSP.flightDirOutbound][cF.arrivalTime]));
        $travelDstTime.text(getText('txt.header.travel.times',
          flight[cSP.flightDirReturn][cF.departureTime],
          flight[cSP.flightDirReturn][cF.arrivalTime]));

        $travelData.parent().parent().show();
      }
      else
      {
        $travelData.parent().parent().hide();
      }


      $hotelname.text(hotel[cH.hotelName]);
      $hoteldescription.text(hotel[cH.hotelDescription]);
      $mainImg.attr("src",hotel[cH.hotelImage]);
      $location.text(hotel[cH.placeName]);

      var detailsHref = "javascript:$('.statusPanel').spbbHotelInfoButton();";
      $more.attr('href', detailsHref);

      $stars.attr('class', hotel["categoryStyleClass"]);

      if (hotelCode != null && typeof hotelCode != undefined)
      {
        var data = {};

        data[cS.stepData] = $("#bookingArea").amGetStepManager().getStepStatus(); //[cS.steps];
        data[cH.hotelCode] = hotelCode;
        data[phpConst.processdata.datatype] = phpConst.processdata.hotel;
        if (noUpdate && noUpdate)
          ;
        else
          $("#roomDescTable").update(data,undefined,true);
      }


      var msdata = $("#modifySearch").msGetData();
      var td = $("#chooseFlight").cfcGetTravelDuration();
      if (td == undefined || $("#bookingArea").amGetStepManager().stepStatus[phpConst.step.steps][phpConst.step.flight] != phpConst.step.valid)
        td = msdata[cSP.duration];
      var tdate = $("#chooseFlight").cfcGetTravelDate();
      if (tdate == undefined || $("#bookingArea").amGetStepManager().stepStatus[phpConst.step.steps][phpConst.step.flight] != phpConst.step.valid)
        tdate = msdata[cSP.date];

      //      C.log("UPDATE GUI")
      $(".statusPanel").setGUI(tdate, td,
        msdata[cSP.numAdult], msdata[cSP.numChild]);

      var taText = getText('txt.common.till', hotel[cH.countryName],
        personal[cSP.travelDestinationName]);

//      if (getStepManager().getEngineKind() == phpConst.engineKind.hotelOnly)
        taText = taText + getText('txt.common.till2',
          $("div.travelInfo span.date").attr("startdate"),
          $("div.travelInfo span.date").attr("retdate") );

      $travelArea.text(taText);

      $("div.statusPanel", $("#bookingArea")).showFlightSummary();
      $(".statusPanel").spSetPrice(hotel[cH.priceAdultComplete]);
    },



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

    // initial values...
    this.id				=	undefined;
    this.$context			=	undefined;
    this.renderDirective = '';                  // needed for autorenderer
    this.onErrorLinkAction = undefined;
  };
  $.extend(
    ChooseHotelController.prototype,
    {
      init : function(s)
      {
        this.id = s.id;
        this.$context = $(s.id);
        this.onErrorLinkAction = s.onErrorLinkAction;
      },
      setOnErrorLinkAction : function(d)
      {
        if (d) {
          this.onErrorLinkAction = d;
        }
      },
      getOnErrorLinkAction : function(d)
      {
        return(this.onErrorLinkAction);
      }


    }
    );


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


})(jQuery);