/**
 * $Id: jquery.chooseCarController.js,v 1.82 2009/05/25 13:09:19 igor Exp $
 **/

(function($){

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

      // initialise the date picker controller with the relevant settings...
      options = $.extend(
      {
        id : '',
        $context : '',
        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._cccId) {
            this._cccId = $.event.guid++;
            $.event._cccCache[this._cccId] = new ChooseCarController(this);
            alreadyExists = false;
          }

          var controller = $.event._cccCache[this._cccId];
          controller.init(options);
          $(this).cccInit();
        }
        )
    },
    cccInit : function() {
      $("#carTable").tableManager(
      {
        loadStringID : 'rentalCar',
        stringVar1 : function(){
          return($("#chooseFlight").cfcGetData()[phpConst.flight.outFlightDirection][phpConst.flight.destAirportName]);
        },
        stringVar2 : function(){
          return(" ");
        },

        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.car.mobility,
          'tr[numseats]' : 'line.'+phpConst.car.numSeats,
          'tr[numdoors]' : 'line.'+phpConst.car.numDoors,
          'tr[categorygear]' : 'line.'+phpConst.car.categoryGear,
          'tr[carid]' : 'line.'+phpConst.car.id,
          'tr[categoryac]' : 'line.'+phpConst.car.categoryAC,
          'tr[stationcode]' : 'line.'+phpConst.car.stationCode,
          'tr[stationname]' : 'line.'+phpConst.car.stationName,
          'tr[stationaddressstreet]' : 'line.'+phpConst.car.stationAddressStreet,
          'tr[stationplace]' : 'line.'+phpConst.car.stationPlace,
          'tr[stationaddresscountry]' : 'line.'+phpConst.car.stationAddressCountry,
          'tr[stationtelefon]' : 'line.'+phpConst.car.stationTelefon,
          'tr[stationfax]' : 'line.'+phpConst.car.stationFax,
          'tr[stationopendays]' : 'line.'+phpConst.car.stationOpenDays,
          'tr[stationopenfrom]' : 'line.'+phpConst.car.stationOpenFrom,
          'tr[stationopento]' : 'line.'+phpConst.car.stationOpenTo,
          'tr[stationdaterent]' : 'line.'+phpConst.car.stationDateRent,
          'tr[stationtimerent]' : 'line.'+phpConst.car.stationTimeRent,
          'tr[stationdateback]' : 'line.'+phpConst.car.stationDateBack,
          'tr[stationtimeback]' : 'line.'+phpConst.car.stationTimeBack,
          'tr[image]' : 'line.'+phpConst.car.image,
          'tr[price]' : 'line.'+phpConst.total.priceAdultComplete,
          'td.columnFirst div' : 'line.'+phpConst.car.type,
          // title popup
          'td.columnFirst[title]' : 'line.' + phpConst.car.type,
          'td.columnCategory' : 'line.'+phpConst.car.categoryName,
          'td.columnCompany' : 'line.'+phpConst.car.stationName,
          'td.columnEquipment' : 'line.'+phpConst.car.equipment,
          'td.columnPrice' : function(context){
            var price = context["item"][phpConst.total.priceAdultComplete];
            price = price.replace(/\s/, '&nbsp;');
            return getText('txt.common.euro', price );
          }
        },
        highlightCheck : false,
        headers: {
          4 : {
            sorter: 'currency2'
          }
        },
        id : "#carTable",
        JSONaction : "result_cars",
        updateCallback : function(){
        },
        onSuccessAction : function() {
        },
        selectCallback : function(s){
          $("#chooseCar").cccUpdateGUI();

          //C.log("SELECT");
          var res = $("#chooseCar").attr("defaultmobility");
          //C.log(res);
          if (res && res.length != 0 && res == phpConst.car.mobility_notrans)
          {
            $("#chooseCar").removeAttr("defaultmobility");
            //            C.log("NO TRANS");
            $('#rbNothing').click();
          }
          else if (res && res.length != 0 && res == phpConst.car.mobility_trans)
          {
            $("#chooseCar").removeAttr("defaultmobility");
            //            C.log("TRANS");
            $("#rbTransfer").click();
          }
          else if (res && res.length != 0)
          {
            $("#chooseCar").removeAttr("defaultmobility");
            //            C.log("MOBILITY");
            //            C.log(res);
            var $target = $("tr[carid='"+res+"']");
            //            C.log($target);
            $("#carTable").tmSetSelection($("#carTable"),$target)
            $('#rbRentalCar').click();
            
            $("#chooseCar").cccUpdateGUI();
          }
          else
          {
            $('#rbRentalCar').click();
            $("#chooseCar").cccUpdateGUI();
          }
        },
        transformCallback : function(response)
        {
          $("#rbRentalCar").attr("statuscode", response["data"][phpConst.car.statusCode]);
          $("#rbTransfer").attr("price", response["data"][phpConst.car.mobility_trans][phpConst.total.priceAdultComplete]);
          $("#rbNothing").attr("price", response["data"][phpConst.car.mobility_notrans][phpConst.total.priceAdultComplete]);
          $("#chooseCar").attr("defaultmobility", response["data"][phpConst.car.mobility]); // set default mobility

          if (   response["data"][phpConst.car.mobility] == phpConst.car.mobility_trans
            || response["data"][phpConst.car.mobility] == phpConst.car.mobility_notrans)
            {
            $("#carTable").removeAttr("defaultselection");
            switch(response["data"][phpConst.car.mobility])
            {
              case phpConst.car.mobility_trans:
                $("#rbTransfer").click();
                break;
              case phpConst.car.mobility_notrans:
                $("#rbNothing").click();
                break;
              default:
                $("#rbRentalCar").click();
            }
          }
          else
            $("#carTable").attr("defaultselection", response["data"][phpConst.car.mobility]); // set is as defaultselection

          response["data"] = response["data"][phpConst.car.mobility_rentcar];



          return (response);
        },

        sortColumn: 'columnPrice',
        'cssAsc': 'asc',
        'cssDesc' : 'desc',
        'cssHeader' :'list',
        'emptyRow' : '<tr>'
      + '<td class="columnFirst"><div class="carName"></div></td>'
      + '<td class="columnCategory"></td>'
      + '<td class="columnCompany"></td>'
      + '<td class="columnEquipment"></td>'
      + '<td class="columnPrice"></td>'
      + '</tr>'
      } );


      // pricetyp property needed to update total price description
      $("#rbNothing").bind("click", function(){
        $("#carTable").tmSetHighlightCheck(false);
        $("#chooseCar").removeAttr("pricetype");
        $("div.statusPanel", $("#bookingArea")).spSetPrice($("#rbNothing").attr("price"));
        $("#bookingArea").amGetStepManager().updatePriceDescription();
      });

      $("#rbTransfer").bind("click", function(){
        $("#carTable").tmSetHighlightCheck(false);
        $("#chooseCar").attr("pricetype", 'Transfer');
        $("div.statusPanel",$("#bookingArea")).spSetPrice($("#rbTransfer").attr("price"));
        $("#bookingArea").amGetStepManager().updatePriceDescription();
      });

      $("#rbRentalCar").bind("click", function()
      {
        $("#carTable").tmSetHighlightCheck(true);
        $("#chooseCar").attr("pricetype", 'RentalCar');
      });

      $("#chooseCar").cccReset();
      $("#rbTransfer").click();

      $("#chooseCar div.carDetails a.more").attr('href', 'javascript:$("#information2").icToggleByURL("/index.php?id=38&type=9",function (){},$("#information2 .content"),"MIETWAGEN.agb");');

      // 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)
      $("#chooseCar input:radio").click(function() {
        $("#chooseCar input:radio").removeAttr('defaultChecked').removeAttr('checked');
        $(this).attr('checked', 'checked').attr('defaultChecked', 'checked');
      });
    },


    cccCheckTransferOptions : function()
    {
      var carAvailable = false;
      var transferPanelAvailable = false;
      var transferAvailable = false;

      // count number of cars
      var count  = 0;
      $("#carTable tbody tr").each(function(){
        count++;
      });
      if (count > 0)
        carAvailable = true;

      var stepStat = $("#bookingArea").amGetStepManager().getStepStatus()[phpConst.step.steps][phpConst.step.hotel];
      if (stepStat == phpConst.step.valid)
        transferPanelAvailable = true;

      // if no cars available, display info text and hide car details
      if (!carAvailable)
      {
        var key = 'txt.chooseCar.noRentalCar.noCarAvailable';
        var statusCode = parseInt($("#rbRentalCar").attr("statuscode"), 10);
        if (statusCode == phpConst.car.tooManyPersons)
          key = 'txt.chooseCar.noRentalCar.tooManyPersons';
        if (statusCode == phpConst.car.noCarAvailable)
          key = 'txt.chooseCar.noRentalCar.noCarAvailable';

        $("#chooseCar fieldset.transfer").removeClass("transfer").addClass("transferLargeGap");
        $("#chooseCar h3.carName").text(getText(key));
        $("#chooseCar div.informationPanel div.content").addClass("hidden");
      }
      else // show car details
      {
        $("#chooseCar div.informationPanel div.content").removeClass("hidden");
        $("#chooseCar .content2 fieldset").removeClass("transferLargeGap").addClass("transfer");
      }

      // adjust transfer options
      // check, if hotel has been choosen, if so, show optional options
      if (transferPanelAvailable)
      {
        $("#chooseCar .content2 fieldset").removeClass("hidden");

        if (!$("#rbTransfer").attr("price")) // check if there is NO price
        {
          $("#rbTransfer").attr('disabled', 'disabled');
          $("#rbTransfer").rbDisable();
          $("#rbTransfer").parent().find("label").text(getText('txt.chooseCar.noTransfer'));
        }
        else // there is a price
        {
          $("#rbTransfer").removeAttr('disabled');
          $("#rbTransfer").rbEnable();
          $("#rbTransfer").parent().find("label").text(getText('txt.chooseCar.transfer'));
          transferAvailable = true;
        }
      }
      else
      {
        $("#chooseCar .content2 fieldset").addClass("hidden");
        $("#rbRentalCar").click();   // ensure that it is selected
      }

      // ensure, that at least one option is selected
      // and that each selected option is valid
      if (     ( !$("#rbRentalCar").attr("checked") && !$("#rbTransfer").attr("checked") && !$("#rbNothing").attr("checked"))
        || ( !carAvailable && $("#rbRentalCar").attr("checked"))
        || ( !transferPanelAvailable && !$("#rbNothing").attr("checked"))
        ){
        if (transferPanelAvailable && transferAvailable )
          $("#rbTransfer").click();
        else if (carAvailable)
          $("#rbRentalCar").click();
        else
          $("#rbNothing").click();
      }

    },


    cccScrollIntoView : function()
    {
      $("#carTable").tmScrollIntoView();
    },


    cccUpdateGUI : function() {
      var cSP = phpConst.searchParam;
      var cF = phpConst.flight;
      var cOut = cSP.flightDirOutbound;
      var cRet = cSP.flightDirReturn;
      var cC = phpConst.car;
      var $ccc = $("#chooseCar");

      var fd = $("#chooseFlight").cfcGetData();
      var cd = $ccc.cccGetData();

      var travelArea = fd[cOut][cF.destAirportName];
      var travelData = fd[cOut][cSP.travelAirportName]+" - " + fd[cOut][cSP.travelDestinationName];
      var depTime = getText('txt.header.travel.times',
        fd[cOut][cF.departureTime], fd[cOut][cF.arrivalTime]);
      var dstTime = getText('txt.header.travel.times',
        fd[cRet][cF.departureTime], fd[cRet][cF.arrivalTime]);

      var cH = phpConst.hotel;
      if ($("#bookingArea").amGetStepManager().getStepStatus()[phpConst.step.steps][phpConst.step.hotel] == phpConst.step.valid)
      {
        var hd = $("#chooseHotel").chcGetData();
        var hotelName =  hd[cH.hotelName];
        var hotelCategory = getText('txt.chooseCar.category',hd[cH.hotelCategoryName]);
        var hotelCity = hd[cH.placeName];
        var hotelDescription = getText ('txt.chooseCar.hotel.description',
          hd[cH.roomDescription].split(',')[0], hd[cH.mealName]);
        $("#hotelInfoBox").show();
      }
      else
      {
        $("#hotelInfoBox").hide(); // no valid hotel data
      }
      var carName = cd[cC.type];
      if (carName)
      {
        var carNavi = '';
        var carManualGear = (cd[cC.categoryGear] == cC.categoryGearMan);
        var carAutomaticGear = (cd[cC.categoryGear] == cC.categoryGearAut);
        var carAC =  cd[cC.categoryAC];
        var rentDate = getText ('txt.common.datetime', cd[cC.stationDateRent],
          cd[cC.stationTimeRent]);        
        var rentLocation =  getText ('txt.chooseCar.airport', travelArea);
        var returnDate = getText ('txt.common.datetime', cd[cC.stationDateBack],
          cd[cC.stationTimeBack]);        
        var returnLocation =  getText ('txt.chooseCar.airport', travelArea);

        $("h3.carName", $ccc).text(getText ('txt.chooseCar.header.carName', carName));
        $(".carInformation", $ccc).text(cd[cC.equipment]);
        $(".carSeats", $ccc).text("x" +cd[cC.numSeats]);
        $(".carDoors", $ccc).text("x" +cd[cC.numDoors]);
        $(".carLeasing .clDate", $ccc).text(rentDate);
        $(".carLeasing .clLocation", $ccc).text(rentLocation);
        $(".carReturn .clDate", $ccc).text(returnDate);
        $(".carReturn .clLocation", $ccc).text(returnLocation);
        $(".carImage img",$ccc).attr("src",cd[cC.image]);

        var $carNavi = $ccc.find(".carNavi");
        var $carManualGear = $ccc.find(".carManualGear");
        var $carAutomaticGear = $ccc.find(".carAutomaticGear");
        var $carAC = $ccc.find(".carAC");

        if(carNavi)
          $carNavi.show();
        else
          $carNavi.hide();

        if(carManualGear)
          $carManualGear.show();
        else
          $carManualGear.hide();

        if(carAutomaticGear)
          $carAutomaticGear.show();
        else
          $carAutomaticGear.hide();

        if(carAC)
          $carAC.show();
        else
          $carAC.hide();
      }

      var $info = $("#chooseCar-infoHeader");
      $(".travelArea", $info).text(travelArea);
      $(".travelData", $info).text(travelData);
      $(".depTime", $info).text(depTime);
      $(".dstTime", $info).text(dstTime);
      $(".hotelTitle", $info).text(hotelName);
      $(".hotelCategory", $info).text(hotelCategory);
      $(".hotelCity", $info).text(hotelCity)
      $(".hotelDescr", $info).text(hotelDescription);

      $ccc.cccCheckTransferOptions();

      var price = 0;
      // check, which kind of transfer is requested and present price
      if ($("#rbNothing").attr("checked"))
        price = $("#rbNothing").attr("price");
      else if ($("#rbTransfer").attr("checked"))
        price = $("#rbTransfer").attr("price");
      else if ($("#rbRentalCar").attr("checked") && cd[phpConst.total.priceAdultComplete])
        price = cd[phpConst.total.priceAdultComplete];

      $("#bookingArea").amGetStepManager().updatePriceDescription();

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

      $(".statusPanel").setGUI(tdate,
        td,
        data[cSP.numAdult],
        data[cSP.numChild],
        price);
    },

    cccGetData : function() {
      var $sr = $("#carTable tr:selectedRow");
      var data = {};

      if ($sr != null && typeof($sr) != undefined)
      {
        data[phpConst.car.id] = $sr.attr("carid");
        data[phpConst.car.numSeats] = $sr.attr("numseats");
        data[phpConst.car.numDoors] = $sr.attr("numdoors");
        data[phpConst.car.categoryGear] = $sr.attr("categorygear");
        data[phpConst.car.categoryAC] = $sr.attr("categoryac");
        data[phpConst.car.type] = $sr.find(".columnFirst").text();
        data[phpConst.car.categoryName] = $sr.find(".columnCategory").text();
        data[phpConst.car.stationName] = $sr.find(".columnCompany").text();
        data[phpConst.car.equipment] = $sr.find(".columnEquipment").text();
        data[phpConst.total.priceAdultComplete] = $sr.attr("price");
        data[phpConst.car.stationCode] = $sr.attr("stationcode");
        data[phpConst.car.stationName] = $sr.attr("stationname");
        data[phpConst.car.stationAddressStreet] = $sr.attr("stationaddressstreet");
        data[phpConst.car.stationPlace] = $sr.attr("stationplace");
        data[phpConst.car.stationAddressCountry] = $sr.attr("stationaddresscountry");
        data[phpConst.car.stationTelefon] = $sr.attr("stationtelefon");
        data[phpConst.car.stationFax] = $sr.attr("stationfax");
        data[phpConst.car.stationOpenDays] = $sr.attr("stationopendays");
        data[phpConst.car.stationOpenFrom] = $sr.attr("stationopenfrom");
        data[phpConst.car.stationOpenTo] = $sr.attr("stationopento");
        data[phpConst.car.stationDateRent] = $sr.attr("stationdaterent");
        data[phpConst.car.stationTimeRent] = $sr.attr("stationtimerent");
        data[phpConst.car.stationDateBack] = $sr.attr("stationdateback");
        data[phpConst.car.stationTimeBack] = $sr.attr("stationtimeback");
        data[phpConst.car.image] = $sr.attr("image");

        // check, which kind of transfer is requested
        if ($("#rbNothing").attr("checked") == true)
          data[phpConst.car.mobility] = phpConst.car.mobility_notrans;
        if ($("#rbTransfer").attr("checked") == true)
          data[phpConst.car.mobility] = phpConst.car.mobility_trans;
        if ($("#rbRentalCar").attr("checked") == true)
          data[phpConst.car.mobility] = $sr.attr("carid");
      }
      return data;
    },
    cccSetData : function(data) {
    },
    cccReset : function()
    {
    },
    cccAllFormfieldsFilled : function()
    {
      var val = true;
      if ($("#rbRentalCar").attr("checked")==""
        && $("#rbTransfer").attr("checked")==""
        && $("#rbNothing").attr("checked")=="")
        val = false;
      return(val);
    },
    cccSetRenderDirective : function(directive)
    {
      return _w.call(this, 'setUpdateCallback', directive);
    },
    cccSetEmptyRow : function(emptyRow)
    {
      return _w.call(this, 'setEmptyRow', emptyRow);
    },
    cccSetUpdateCallback : function(callback)
    {
      return _w.call(this, 'setUpdateCallback', callback);
    },
    cccSetSelectCallback : function(callback)
    {
      return _w.call(this, 'setSelectCallback', callback);
    },
    cccSetJSONAction : function(action)
    {
      return _w.call(this, 'setJSONAction', action);
    },
    cccGetRenderDirective : function()
    {
      var c = _getController(this[0]);
      if (c) {
        return c.getRenderDirective();
      }
      return null;
    },
    _cccDestroy : 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 ChooseCarController(ele)
  {
    this.ele = ele;

    // initial values...
    this.id				=	undefined;
    this.$context			=	undefined;
    this.renderDirective = '';                  // needed for autorenderer
    this.emptyRow = ' ';
    this.updateCallback = undefined; // function is beeing called after update
    this.selectCallback = undefined; // function is beeing called after change of selection
    this.JSONaction = undefined;
  };
  $.extend(
    ChooseCarController.prototype,
    {
      init : function(s)
      {
        this.id = s.id;
        this.$context = $(s.id);
        this.renderDirective = s.renderDirective;
        this.emptyRow = s.emptyRow;
        this.updateCallback = s.updateCallback;
        this.selectCallback = s.selectCallback;
        this.JSONaction = s.JSONaction;
      },
      setRenderDirective : function(d)
      {
        if (d) {
          this.renderDirective = d;
        }
      },
      setEmptyRow : function(d)
      {
        if (d) {
          this.emptyRow = d;
        }
      },
      setUpdateCallback : function(a)
      {
        if (a && typeof(a) == 'function') {
          a = [a];
        }
        this.updateCallback = this.updateCallback.concat(a);
      },
      setSelectCallback : function(a)
      {
        if (a && typeof(a) == 'function') {
          a = [a];
        }
        this.selectCallback = this.selectCallback.concat(a);
      },
      getRenderDirective : function(d)
      {
        return(this.renderDirective);
      },
      getEmptyRow : function(d)
      {
        return(this.emptyRow);
      },
      getUpdateCallback : function(a)
      {

        return(this.updateCallback);
      },
      getSelectCallback : function(a)
      {
        return(this.selectCallback);
      }
    }
    );


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


})(jQuery);
