var GridQuestion;
var WindowQuestion;       // variable creating window declaration

var deleteQuestion = function(title, msguam, id_row) {                  // function delete question
  Ext.Msg.show({
    title: title,
    msg: msguam,
    minWidth: 200,
    modal: true,
    icon: Ext.Msg.QUESTION,
    buttons:Ext.Msg.YESNO,
    fn:function(btn){
      if(btn=='no'){
        var deleteButton = Ext.getCmp('delete');
        deleteButton.setDisabled(true);     
      }
      if(btn=='yes'){
        $.post("app/SFA_CRUDQuestion.php",{func:'delete',id:id_row},function(data)
          {
            GridQuestion.store.load();
            GridQuestion.getView().refresh();
            var deleteButton = Ext.getCmp('delete');
            deleteButton.setDisabled(true);

        });                                              
      }
    }
  });
};

Ext.define('ModelQuestion', {
  extend:'Ext.data.Model',
  fields:['id', 'name', 'name_client', 'date_start', 'date_end', 'name_type_question']
});

var StoreQuestion = new Ext.data.Store({
  model: 'ModelQuestion',
  proxy: {
    type: 'ajax',
    url: 'app/SFA_CRUDQuestion.php?func=show',
    reader: {
      type: 'json',
      root: 'rows'
    }
  }
});


Ext.define('ModelTypeQuestion', {
    extend: 'Ext.data.Model',
    fields: [ 'id','name' ]
});

var StoreTypeQuestion = new Ext.data.Store({
        model: 'ModelTypeQuestion',
           proxy: {
              type: 'ajax',
              url: 'app/SFA_CRUDQuestion.php?func=showTypeQuestion',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
});


Ext.define('ModelClient', {
    extend: 'Ext.data.Model',
    fields: ['id', 'name', 'phone', 'city', 'address']
});

var StoreClient = new Ext.data.Store({
  model: 'ModelClient',
  proxy: {
    type: 'ajax',
    url: 'app/SFA_CRUDQuestion.php?func=showClient',
    reader: {
      type: 'json',
      root: 'rows'
    }
  }
});


function show_SFALite_Question_Window()
{
//------------------------------create window---------------------------------------
  if (!WindowQuestion || WindowQuestion.Window==null)
  {
    WindowQuestion = new Windows('Редактор вопросов',800,500);      //create constructor
    StoreQuestion.load();
    createGridQuestionAndForm();
    WindowQuestion.CreateWindowMaximizableDestroy(WindowQuestion,GridQuestionAndForm);    //filling window
  }
  
  WindowQuestion.Window.show();
}


// ------------------------------------- create Grid --------------------------------------    
function createGridQuestionAndForm()
{
  GridQuestion = Ext.create('Ext.grid.Panel', {
  selType: 'rowmodel',
  store: StoreQuestion,
  columnLines: true,
  frame: false,
  border: false,
  columns:[
    {xtype: 'rownumberer', width: 30},
    {dataIndex: 'id', text: 'id', hidden: true},
    {text: "Вопрос", flex: 1, sortable: false, hideable: false, dataIndex: 'name'},
    {text: "Тип", width: 100, sortable: false, hideable: false, dataIndex: 'name_type_question'},
    {text: "Клиент", width: 200, sortable: false, hideable: false, dataIndex: 'name_client'},
    {text: "Дата старта", width: 100, sortable: false, hideable: false, dataIndex: 'date_start'},
    {text: "Дата окончания", width: 100, sortable: false, hideable: false, dataIndex: 'date_end'},
  ],
  listeners:
  {
    itemclick: function (View,record,item,index,e,eOpts)
    {
      id_row = record.get('id');
      id_row =parseInt(id_row);
      var deleteButton = Ext.getCmp('delete');
      deleteButton.setDisabled(false);
    }
  }
});
  
  var FormConstructor = new Forms();
  var fieldName = FormConstructor.CreateTextAreaFieldWidthPercent('Вопрос','top','95%',1);
  StoreTypeQuestion.load();
  var field_id_type_question = FormConstructor.CreateComboboxFieldProxyWidthPercent('Тип','top',StoreTypeQuestion,'name','id','95%');
  StoreClient.load();
  var field_id_client = FormConstructor.CreateComboboxFieldProxyWidthPercent('Клиент','top',StoreClient,'name','id','95%');
  var fieldDateStart = FormConstructor.CreateDateField('Дата старта','left','120','','Y-m-d');
  var fieldDateEnd = FormConstructor.CreateDateField('Дата окончания','left','120','','Y-m-d');
  /*StoreTradePoint.load();
  var field_id_trade_point = FormConstructor.CreateComboboxFieldLabelTopProxyWidthPercent('Торговая точка',StoreTradePoint,'name','id','95%');*/
  /*StoreCategoryQuestion.load();
  var field_id_category_question = FormConstructor.CreateComboboxFieldLabelTopProxyWidthPercent('Категория',StoreCategoryQuestion,'name','id','95%');*/
  
  var GridQuestionForm = Ext.create('Ext.form.Panel', {
  frame:true,
  id: 'GridQuestionForm',
  bodyStyle:'padding: 10px 20px 10px 15px',
  autoScroll: true,
  layout: 'anchor',
  fieldDefaults: {
    labelAlign: 'left',
    labelWidth: 100,
    msgTarget: 'side'
  },
  items: [
    fieldName,
    field_id_type_question,
    field_id_client,
    fieldDateStart,
    fieldDateEnd
    //field_id_trade_point,
    //field_id_category_question
  ],
  buttons: [
    '->',
    {
      text: 'Добавить',
      id: 'addButton',
      //disabled: true,
      handler: function(){
        var name = fieldName.getValue();
        var id_type_question = field_id_type_question.getValue();
        var id_client = field_id_client.getValue();
        var DateStart = fieldDateStart.getRawValue();
        var DateEnd = fieldDateEnd.getRawValue();
        

        if (name=='' || id_type_question=='')
        {
          msg('Ошибка!', 'Проверьте данные!');
          if (name==''){fieldName.markInvalid('Проверьте данные!');}
          if (id_type_question==''){field_id_type_question.markInvalid('Проверьте данные!');}
        }
        else 
        {
          $.post("app/SFA_CRUDQuestion.php",{func:'add',name:name, id_type_question:id_type_question, id_client:id_client, date_start:DateStart, date_end:DateEnd}, function(data){
            //alert(data);
            GridQuestion.store.load();
            GridQuestion.getView().refresh();
            
            fieldName.setValue('');
            field_id_type_question.setValue('');
            field_id_client.setValue('');
            
            var deleteButton = Ext.getCmp('delete');
            deleteButton.setDisabled(true);
          });
        }
      }
    },
    {
      text: 'Удалить',
      disabled: true,
      id: 'delete',
      handler: function(){
        deleteQuestion('Удаление', 'Вы точно хотите удалить данный вопрос!?',id_row);
      }
    }
  ],
  /*listeners:
  {
    itemclick: function ()
    {
      alert(1);
      var addButton = Ext.getCmp('addButton');
      addButton.setDisabled(false);
    }
  }*/
});
  
  GridQuestionAndForm = Ext.create('Ext.panel.Panel', {
    layout: {type: 'border'},
    items:
      [
        {
          region: 'north',
          height: '40%',
          autoScroll: true,
          items:[ GridQuestion ]
        },
        {
          region: 'south',
          autoScroll: true,
          height: '60%',
          layout: 'fit',
          items:[ GridQuestionForm ]
        },
      ],
    /*listeners:
    {
      itemclick: function(View,record,item,index,e,eOpts )
      {
        id_row = record.get('id');
        id_row =parseInt(id_row);
        var deleteButton = Ext.getCmp('delete');
        deleteButton.setDisabled(false);
      },
      itemdblclick: function(View,record,item,index,e,eOpts )
      {
        id_row = record.get('id');
        id_row=parseInt(id_row);
        showFormTradePoint(id_row);
        id_row=0;
      }
    }*/
  });
}