ns('Carib.Order');

/**
 * @version $Id: app_controller.js 865 2010-03-19 17:01:03Z  $
 */
Carib.Order.AppController = function() {
  this.send_win = null;
  this.common_info_controller = null;
  this.order_controller = null; 
  this.tourists_controller = null;
  this.send_button = null;
  this.wizard_mode = true;
}

Carib.Order.AppController.prototype = {
  start: function() {
    this.getCommonInfoController().doStart();
    this.getOrderController().doStart(); 
    this.getTouristsController().doStart();
    this.initEvents();
    this.calcTravelDuration();
    
    this.getOrderController().doAddOrder();
  },
  
  doSend: function() {
    if(!this.validate())
      return;
      
    this.getSendWin().show();
    this.getSendWin().loadPreview(this.serialize());
  },
  
  initEvents: function() {
    this.initButtonsEvents();
    this.initWizardEvents();
    this.initOrderEvents();
  },

  initButtonsEvents: function() {
    this.getSendButton().click(this.onSendOrder.createDelegate(this));
    $('#order_tables .wizard_control button').hover(
      function() { $(this).addClass('ui-state-hover'); },
      function() { $(this).removeClass('ui-state-hover'); }
    );
  },
  
  initWizardEvents: function() {
    this.getOrderController().getWizardWin().on('ok', this.onOrderOk, this);
    this.getOrderController().getWizardWin().on('cancel', this.onCancel, this);
    
    this.getTouristsController().getTouristWin().on('ok', this.onTouristOk, this);
    this.getTouristsController().getTouristWin().on('cancel', this.onCancel, this);
    
    this.getCommonInfoController().getWin().on('ok', this.onCommonInfoOk, this);
    this.getCommonInfoController().getWin().on('cancel', this.onCancel, this);
    
    this.getCommonInfoController().getAdditionalInfoWin().on('ok', this.onAdditionalInfoOk, this);
    this.getCommonInfoController().getAdditionalInfoWin().on('cancel', this.onCancel, this);
  },  
  
  initOrderEvents: function() {
    this.getOrderController().getOrder().on('datachanged', this.onChangeOrder, this);
  },
  
  validate: function() {
    var validator = new Carib.Order.Validation.Validator();
    validator.add(new Carib.Order.Validation.Rules.Callback({
      callback: this.validateOrder,
      scope: this
    }));
    validator.add(new Carib.Order.Validation.Rules.Callback({
      callback: this.validateTourists,
      scope: this
    }));
    
    var errors = validator.validate(this);
    this.getCommonInfoController().validate(errors);
    if(!errors.isValid()) {
      var messages = '- ' + errors.getAllMessages().join("\r\n- ");
      alert('Не все данные введены правильно: \r\n' + messages);
      return false;      
    }
    return true;
  },
  
  validateOrder: function(controller, errors) {
    if(controller.getOrderController().getOrder().getCount() == 0)
      errors.add('order', 'должна быть указано хотябы одна страна или курорт');
  },
  
  validateTourists: function(controller, errors) {
    if(controller.getTouristsController().getTourists().getCount() == 0)
      errors.add('order', 'должен быть указан хотябы один турист');
  },
  
  serialize: function() {
    var result = {};
    this.serializeCommonInfo(result);
    this.serializeOrder(result);
    this.serializeTourists(result);
    return result;
  },
  
  serializeCommonInfo: function(result) {
    var serializator = new Carib.Order.Data.Serializators.Record({
      result: result,
      name: 'common_info'
    });
    serializator.serialize(this.getCommonInfoController().getRecord());
  },
  
  serializeOrder: function(result) {
    var serializator = new Carib.Order.Data.Serializators.Recordset({
      result: result,
      name: 'order'
    });
    serializator.serialize(this.getOrderController().getOrder(), Carib.Order.Data.Serializators.Order);
  },
  
  serializeTourists: function(result) {
    var serializator = new Carib.Order.Data.Serializators.Recordset({
      result: result,
      name: 'tourist'
    });
    serializator.serialize(this.getTouristsController().getTourists(), Carib.Order.Data.Serializators.Record);
  },
  
  getCommonInfoController: function() {
    if(!this.common_info_controller) {
      this.common_info_controller = new Carib.Order.CommonInfoController();
    }
    return this.common_info_controller;
  },
  
  getOrderController: function() {
    if(!this.order_controller) {
      this.order_controller = new Carib.Order.OrderController({
        default_order_record: this._createDefaultOrderRecord()
      });
    }
    return this.order_controller;
  },
  
  getTouristsController: function() {
    if(!this.tourists_controller) {
      this.tourists_controller = new Carib.Order.TouristsController();
    }
    return this.tourists_controller;
  },
  
  _createDefaultOrderRecord: function() {
    var residence = new Carib.Order.Data.Residence({
      transfer: 'Нет'
    });
    var country = Carib.Order.App.getCountries().getAt(0);
    if(country) {
      residence.set('country_id', country.getId());
      residence.set('country_name', country.get('name'));
    }
    var number_category = Carib.Order.App.getNumberCategories().getAt(0);
    if(number_category) {
      residence.set('number_category_id', number_category.getId());
      residence.set('number_category_name', number_category.get('name'));
    }
    var placing_category = Carib.Order.App.getPlacingCategories().getAt(0);
    if(placing_category) {
      residence.set('placing_category_id', placing_category.getId());
      residence.set('placing_category_name', placing_category.get('name'));
    }
    var food_type = Carib.Order.App.getFoodTypes().getAt(0);
    if(food_type) {
      residence.set('food_type_id', food_type.getId());
      residence.set('food_type_name', food_type.get('name'));
    }
    return new Carib.Order.Data.Order({
      residence: residence,
      airfare: 'нет',
      guide: '-',
      language: 'русскоговорящий'
    });
  },
  
  getSendButton: function() {
    return $('#send_order_button');
  },
  
  getSendWin: function() {
    if(!this.send_win) {
      this.send_win = new Carib.Order.Widgets.SendWin({
        selector: '#send_win',
        listeners: {
          cancel: this.onCancel,
          scope: this
        }
      });
    }
    return this.send_win;
  },
  
  calcTravelDuration: function() {
    var nights = 1;
    this.getOrderController().getOrder().each(function(num, record) {
      nights += parseInt(record.data.residence.data.nights);
    });
    this.getCommonInfoController().getRecord().set('travel_duration', nights);
    this.getCommonInfoController().getRecord().commit();
  },
  
  onSendOrder: function() {
    this.doSend();
  },
  
  onCommonInfoOk: function() {
    if(this.wizard_mode)
      this.getCommonInfoController().doShowAdditionalInfoWin();
  },
  
  onOrderOk: function() {
    if(this.wizard_mode) {
      Carib.Order.Widgets.confirm(
        'Добавление страны, города',
        'Желаете добавить ещё одну страну, город, курорт или тур?',
        this.onAddOrder,
        this.onAddTourist,
        this
      );
    }
  },
  
  onAddOrder: function() {
    if(this.wizard_mode) 
      this.getOrderController().doAddOrder();
  },
  
  onAddTourist: function() {
    if(this.wizard_mode) 
      this.getTouristsController().doAddTourist();
  },
  
  onTouristOk: function() {
    if(this.wizard_mode) {
      Carib.Order.Widgets.confirm(
        'Добавление туриста',
        'Желаете добавить ещё одного туриста?',
        this.onAddTourist,
        this.onEditAdditionalInfo,
        this
      );
    }
  },
  
  onEditAdditionalInfo: function() {
    if(this.wizard_mode) 
      this.getCommonInfoController().doShowCommonInfoWin();
  },
  
  onCancel: function() {
    this.wizard_mode = false;
  },
  
  onAdditionalInfoOk: function() {
    if(this.wizard_mode) 
      this.doSend();    
  },
  
  onChangeOrder: function() {
    this.calcTravelDuration();
  }  
}

