/**
 * $Id: jquery.progressBarController.js 2194 2009-04-16 15:52:56Z Bjoern.Moenikes $
 **/

(function($){

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

      // 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._pbcId) {
            this._pbcId = $.event.guid++;
            $.event._pbcCache[this._pbcId] = new ProgressBarController(this);
            alreadyExists = false;
          }

          var controller = $.event._pbcCache[this._pbcId];
          controller.init(options);
        }
        )
    },
    pbcSetMode : function(mode)
    {
      var checkLinkAvailableAndFollow = function(event, bookLine, step)
      {
        var target;
        var $item;
        if ( $("div.tx-byebye-pi1").length > 0)  // event routine for non ssl part:
        {
          var erg = false;
          if ( (event && event.target) )
          {
            $item = $(event.target);
            if (!$item.hasClass("checked"))
              return;
            target = $item.attr("id").replace(/li/,"");
            var $sm = $("#bookingArea").amGetStepManager();
            $sm.restoreToStep(bookLine, step);
            $("#bookingArea #progressBar ul li:gt("+ (step-1) +")").removeClass("active").removeClass("checked");

          }
        }
        else if ( $("div.tx-byebye-pi3").length > 0) // event routine for ssl part:
        {
          $item = $(event.target);
          if (!$item.hasClass("checked"))
            return;
          target = $item.attr("id").replace(/li/,"");

          var selectionURL = getSelectionURL();

          if (selectionURL)
            window.location.href = selectionURL + "?tx_byebye_pi1[jump]="+target;
          //C.log(selectionURL + "?tx_byebye_pi1[jump]="+target);
          else
            alert("error");
        }
        else
          C.log("outside");
      }

      switch(mode)
      {
        case phpConst.engineKind.individualTravel:
          $("#bookingArea #progressBar")
          .removeClass("nostep step4_1 step4_2 step4_3 step4_4 step3_3 step3_2 step3_1 step2_2 step2_1")
          .addClass("step4_1").attr("mode",4);

          $("#bookingArea #progressBar ul li")
          .replaceWith(""); //  empty();

          $("#bookingArea #progressBar ul")
          .append($("<li>").attr("id","li"+phpConst.step.flight)
            .attr("divclass","step4_1")
            .text(getText('txt.progressbar.chooseFlight'))
            .addClass("pb4steps active").
            bind("click",function(event){
              checkLinkAvailableAndFollow(event,phpConst.engineKind.individualTravel, phpConst.step.flight)
            }))
          .append($("<li>")
            .attr("id","li"+phpConst.step.hotel)
            .attr("divclass","step4_2")
            .text(getText('txt.progressbar.chooseHotel'))
            .addClass("pb4steps").bind("click",  function(event){
              checkLinkAvailableAndFollow(event,phpConst.engineKind.individualTravel, phpConst.step.hotel)
            }))
          .append($("<li>")
            .attr("id","li"+phpConst.step.rentalCar)
            .attr("divclass","step4_3")
            .text(getText('txt.progressbar.chooseExtras'))
            .addClass("pb4steps").bind("click",function(event){
              checkLinkAvailableAndFollow(event,phpConst.engineKind.individualTravel, phpConst.step.rentalCar)
            }))
          .append($("<li>")
            .attr("id","li"+phpConst.step.commit)
            .attr("divclass","step4_4")
            .text(getText('txt.progressbar.commitBooking'))
            .addClass("pb4steps")
            .bind("click",function(event){
              checkLinkAvailableAndFollow(event,phpConst.engineKind.individualTravel, 4)
            }));
          break;


        case phpConst.engineKind.flightOnly:
          $("#bookingArea #progressBar")
          .removeClass("nostep step4_1 step4_2 step4_3 step4_4 step3_3 step3_2 step3_1 step2_2 step2_1")
          .addClass("step2_1").attr("mode",2);

          $("#bookingArea #progressBar ul li")
          .replaceWith(""); //  empty();
          
          $("#bookingArea #progressBar ul")
          .append($("<li>")
            .attr("id","li"+phpConst.step.flight)
            .attr("divclass","step2_1")
            .text(getText('txt.progressbar.chooseFlight'))
            .addClass("pb2steps active")
            .bind("click",function(event){
              checkLinkAvailableAndFollow(event,phpConst.engineKind.flightOnly, phpConst.step.flight)
            }))
          .append($("<li>")
            .attr("id","li"+phpConst.step.commit)
            .attr("divclass","step2_2")
            .text(getText('txt.progressbar.commitBooking'))
            .addClass("pb2steps")
            .bind("click",function(event){
              checkLinkAvailableAndFollow(event,phpConst.engineKind.flightOnly, 4)
            }));
          break;


        case phpConst.engineKind.hotelOnly:
          $("#bookingArea #progressBar")
          .removeClass("nostep step4_1 step4_2 step4_3 step4_4 step3_3 step3_2 step3_1 step2_2 step2_1")
          .addClass("step2_1").attr("mode",2);

          $("#bookingArea #progressBar ul li")
          .replaceWith(""); //  empty();

          $("#bookingArea #progressBar ul")
          .append($("<li>")
            .attr("id","li"+phpConst.step.hotel)
            .attr("divclass","step2_1")
            .text(getText('txt.progressbar.chooseHotel'))
            .addClass("pb2steps active")
            .bind("click",function(event){
              checkLinkAvailableAndFollow(event, phpConst.engineKind.hotelOnly, phpConst.step.hotel)
            }))
          .append($("<li>")
            .attr("id","li"+phpConst.step.commit)
            .attr("divclass","step2_2")
            .text(getText('txt.progressbar.commitBooking'))
            .addClass("pb2steps")
            .bind("click",function(event){
              checkLinkAvailableAndFollow(event, phpConst.engineKind.hotelOnly, 4)
            }));
          break;
          
        case phpConst.engineKind.flyDrive:
          $("#bookingArea #progressBar")
          .removeClass("nostep step4_1 step4_2 step4_3 step4_4 step3_3 step3_2 step3_1 step2_2 step2_1")
          .addClass("step3_1").attr("mode",3);
          $("#bookingArea #progressBar ul li")
          .replaceWith();
          $("#bookingArea #progressBar ul")
          .append($("<li>")
            .attr("id","li"+phpConst.step.flight)
            .attr("divclass","step3_1")
            .text(getText('txt.progressbar.chooseFlight'))
            .addClass("pb3steps active")
            .bind("click",function(event){
              checkLinkAvailableAndFollow(event, phpConst.engineKind.flyDrive, phpConst.step.flight)
            }))
          .append($("<li>")
            .attr("id","li"+phpConst.step.rentalCar)
            .attr("divclass","step3_2")
            .text(getText('txt.progressbar.chooseExtras'))
            .addClass("pb3steps")
            .bind("click",function(event){
              checkLinkAvailableAndFollow(event, phpConst.engineKind.flyDrive, phpConst.step.rentalCar)
            }))
          .append($("<li>")
            .attr("id","li"+phpConst.step.commit)
            .attr("divclass","step3_3")
            .text(getText('txt.progressbar.commitBooking'))
            .addClass("pb3steps")
            .bind("click",function(event){
              checkLinkAvailableAndFollow(event, phpConst.engineKind.flyDrive, 4)
            }));
          break;
        case phpConst.engineKind.notDefined:
        default:
          C.log("progressBarController.js::: pbcSetMode defaulting: "+mode);
          $("#bookingArea #progressBar")
          .removeClass("step4_1 step4_2 step4_3 step4_4 step3_3 step3_2 step3_1 step2_2 step2_1")
          .addClass("nostep");
          $("#bookingArea #progressBar ul li")
          .replaceWith("");
          break;
      }
    },

    pbcGetMode : function()
    {
      return ($("#bookingArea #progressBar").attr("mode"));
    },

    pbcSetStep : function(step)
    {
      var $pb = $("#bookingArea .progressBar");
      $("li.active",$pb).removeClass('active');
      var $x = $("li[id='li"+step+"']",$pb);
      $x.addClass('active');
      if (step == phpConst.step.flight)
      {
        $("li[id='li"+phpConst.step.hotel+"']",$pb).removeClass("checked").removeClass("skipped");
        $("li[id='li"+phpConst.step.rentalCar+"']",$pb).removeClass("checked").removeClass("skipped");
      }
      else if (step == phpConst.step.hotel)
      {
        $("li[id='li"+phpConst.step.rentalCar+"']",$pb).removeClass("checked").removeClass("skipped");
      }

      $("#bookingArea .progressBar").removeClass("nostep step4_1 step4_2 step4_3 step4_4 step3_3 step3_2 step3_1 step2_2 step2_1").addClass($x.attr("divclass"));
    },

    // map AppMain.stepStatus.engStepStat datastructure to progressbar to set checked/skipped class attribute
    pbcUpdateStepStatus : function(stepStatus)
    {
      $("#bookingArea #progressBar li[id='li"+phpConst.step.flight+"']").removeClass("checked").removeClass("skipped");

      if (!stepStatus || !stepStatus[phpConst.step.steps])
        return;

      if (stepStatus.engStepStat[phpConst.step.flight] == phpConst.step.valid)
        $("#bookingArea #progressBar li[id='li"+phpConst.step.flight+"']").addClass("checked");
      else if (stepStatus.engStepStat[phpConst.step.flight] == phpConst.step.skip)
        $("#bookingArea #progressBar li[id='li"+phpConst.step.flight+"']").addClass("skipped");

      if (stepStatus.engStepStat[phpConst.step.hotel] == phpConst.step.valid)
        $("#bookingArea #progressBar li[id='li"+phpConst.step.hotel+"']").addClass("checked");
      else if (stepStatus.engStepStat[phpConst.step.hotel] == phpConst.step.skip)
        $("#bookingArea #progressBar li[id='li"+phpConst.step.hotel+"']").addClass("skipped");

      if (stepStatus.engStepStat[phpConst.step.rentalCar] == phpConst.step.valid)
        $("#bookingArea #progressBar li[id='li"+phpConst.step.rentalCar+"']").addClass("checked");
      else if (stepStatus.engStepStat[phpConst.step.rentalCar] == phpConst.step.skip)
        $("#bookingArea #progressBar li[id='li"+phpConst.step.rentalCar+"']").addClass("skipped");
    },

    pbcSetRenderDirective : function(directive)
    {
      return _w.call(this, 'setUpdateCallback', directive);
    },
    pbcSetEmptyRow : function(emptyRow)
    {
      return _w.call(this, 'setEmptyRow', emptyRow);
    },
    pbcSetUpdateCallback : function(callback)
    {
      return _w.call(this, 'setUpdateCallback', callback);
    },
    pbcSetSelectCallback : function(callback)
    {
      return _w.call(this, 'setSelectCallback', callback);
    },
    pbcSetJSONAction : function(action)
    {
      return _w.call(this, 'setJSONAction', action);
    },
    pbcGetRenderDirective : function()
    {
      var c = _getController(this[0]);
      if (c) {
        return c.getRenderDirective();
      }
      return null;
    },
    _pbcDestroy : 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 ProgressBarController(ele)
  {
    this.ele = ele;

    // initial values...
    this.inline				=	null;
    this.context			=	'#name';
    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(
    ProgressBarController.prototype,
    {
      init : function(s)
      {
        this.context = this.ele;
        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._pbcId) return $.event._pbcCache[ele._pbcId];
    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._pbcCache || [];
    for (var i in els) {
      $(els[i].ele)._pbcDestroy();
    }
  });

})(jQuery);