var CalendarTasksGrid;
var CalendarTasksWin;
var WindowWithTasksGrid;
var id_row = false;

var d = new Date();
var month = new Date().getMonth() +1;
var year = new Date().getFullYear();

var monthTaskVisits = Ext.create('Ext.data.Store', {
  fields: ['id', 'type'],
  data: [
    {"id":1, "type":"Январь"},
    {"id":2, "type":"Февраль"},
    {"id":3, "type":"Март"},
    {"id":4, "type":"Апрель"},
    {"id":5, "type":"Май"},
    {"id":6, "type":"Июнь"},
    {"id":7, "type":"Июль"},
    {"id":8, "type":"Август"},
    {"id":9, "type":"Сентябрь"},
    {"id":10, "type":"Октябрь"},
    {"id":11, "type":"Ноябрь"},
    {"id":12, "type":"Декабрь"}
  ]
});

Ext.define('ModelTradePoint',
{
  extend: 'Ext.data.Model',
  fields: [ 'id','number' ,'name', 'address', 'city', 'latitude', 'longitude']
});
var StoreTradePoint = new Ext.data.Store(
{
  model: 'ModelTradePoint',
  proxy:
  {
    type: 'ajax',
    url: 'app/SFA_CalendarTasks.php?func=showTP',
    reader: {
      type: 'json',
      root: 'rows'
    }
  }
});
Ext.define('boss_id', {
    extend: 'Ext.data.Model',
    fields: [ 'id','FIO_B']
});
var Data_boss_id = new Ext.data.Store({
        model: 'boss_id',
           proxy: {
              type: 'ajax',
              url: 'app/SFA_CalendarTasks.php?func=boss',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
   });


// ----------------------------------Window ------------------------------------

  Ext.define('Ext.form.field.Month', {
        extend: 'Ext.form.field.Date',
        alias: 'widget.monthfield',
        requires: ['Ext.picker.Month'],
        alternateClassName: ['Ext.form.MonthField', 'Ext.form.Month'],
        selectMonth: null,
        createPicker: function () {
            var me = this,
                format = Ext.String.format;
            return Ext.create('Ext.picker.Month', {
                pickerField: me,
                ownerCt: me.ownerCt,
                renderTo: document.body,
                floating: true,
                hidden: true,
                focusOnShow: true,
                height: 200,
                minDate: me.minValue,
                maxDate: me.maxValue,
                disabledDatesRE: me.disabledDatesRE,
                disabledDatesText: me.disabledDatesText,
                disabledDays: me.disabledDays,
                disabledDaysText: me.disabledDaysText,
                format: me.format,
                showToday: me.showToday,
                startDay: me.startDay,
                minText: format(me.minText, me.formatDate(me.minValue)),
                maxText: format(me.maxText, me.formatDate(me.maxValue)),
                listeners: {
                    select: { scope: me, fn: me.onSelect },
                    monthdblclick: { scope: me, fn: me.onOKClick },
                    yeardblclick: { scope: me, fn: me.onOKClick },
                    OkClick: { scope: me, fn: me.onOKClick },
                    CancelClick: { scope: me, fn: me.onCancelClick }
                },
                keyNavConfig: {
                    esc: function () {
                        me.collapse();
                    }
                }
            });
        },
        onCancelClick: function () {
            var me = this;
            me.selectMonth = null;
            me.collapse();
        },
        onOKClick: function () {
            var me = this;
            if (me.selectMonth) {
                me.setValue(me.selectMonth);
                me.fireEvent('select', me, me.selectMonth);
            }
            me.collapse();
        },
        onSelect: function (m, d) {
            var me = this;
            me.selectMonth = new Date((d[0] + 1) + '/1/' + d[1]);
        }
    });


function show_SFA_CalendarTasks_Window()
{
  //alert('show_SFA_CalendarTasks_Window');
  if (!CalendarTasksWin || CalendarTasksWin.Window==null)
  {
    $.post('app/SFA_CalendarTasks.php', {func:'show'}, function(data)
    {    
      var resultTV = data.split('/n');
      var columnsTV = eval("(" + resultTV[0] + ")");
      var fieldsTV = eval("(" + resultTV[1] + ")");
      var dataTV = eval("(" + resultTV[2] + ")");

      Ext.define('TaskVisitsModel', {
        extend: 'Ext.data.Model',
        fields: fieldsTV
      });
      var TaskVisitsStore = new Ext.data.Store({
        model: 'TaskVisitsModel',
        data: dataTV
      });
      CalendarTasksGrid = new Ext.grid.GridPanel({
        selType: 'cellmodel',
        columnLines: true,
        id: 'TaskVisitsGridId',
        store: TaskVisitsStore,
        loadMask: true,
        border: false,
        frame: true,
        columns: columnsTV,
        autoScroll: true,
        listeners:{
          itemdblclick: function(View,record,item,index,e,eOpts){ 
            itemdblclickOnGrid(View,record,item,index,e,eOpts);
          }
        }
      });
    
    
      CalendarTasksWin = new Windows('Календарь',900,400); // create window
      CalendarTasksWin.CreateWindowMaximizableDestroy(CalendarTasksWin,CalendarTasksGrid);
       var copyVisitButtonOk = Ext.create('Ext.button.Button', { 
        text: 'Копировать',    
        handler: function()
        {
            var dateFrom = Ext.getCmp('Copy_date_from').getValue();
            var dateTo = Ext.getCmp('Copy_date_to').getValue();
            var fromDate = new Date(dateFrom);
            var fromYear = fromDate.getFullYear();
            var fromMonth = fromDate.getMonth();
            fromMonth = fromMonth + 1;
            if (fromMonth < 10) {fromMonth = "0" + fromMonth;}
            var toDate = new Date(dateTo);
            var toYear = toDate.getFullYear();
            var toMonth = toDate.getMonth();
            toMonth = toMonth + 1;
            if (toMonth < 10) {toMonth = "0" + toMonth;}
            var convertDateFrom = fromYear + "-" + fromMonth;
            var convertDateTo = toYear + "-" + toMonth;
            $.post('app/SFA_CalendarTasks.php', {func:'copyTask', convertDateFrom:convertDateFrom, convertDateTo:convertDateTo},function(data){ 
                      CalendarTasksWin.Window.remove(CalendarTasksGrid);
      $.post('app/SFA_CalendarTasks.php', {func:'show'}, function(data)
      {
        var resultTV = data.split('/n');
        var columnsTV = eval("(" + resultTV[0] + ")");
        var fieldsTV = eval("(" + resultTV[1] + ")");
        var dataTV = eval("(" + resultTV[2] + ")");

        Ext.define('TaskVisitsModel', {
          extend: 'Ext.data.Model',
          fields: fieldsTV
        });
        var TaskVisitsStore = new Ext.data.Store({
          model: 'TaskVisitsModel',
          data: dataTV
        });
        CalendarTasksGrid = new Ext.grid.GridPanel({
          selType: 'cellmodel',
          columnLines: true,
          id: 'TaskVisitsGridId',
          store: TaskVisitsStore,
          loadMask: true,
          border: false,
          frame: true,
          columns: columnsTV,
          autoScroll: true,
          listeners:{
            itemdblclick: function(View,record,item,index,e,eOpts){ 
              itemdblclickOnGrid(View,record,item,index,e,eOpts);
            }
          }
        });
        CalendarTasksWin.Window.add(CalendarTasksGrid);
         copyTasksWin.Window.destroy();
      });
            })
        }
       })
      
      var copyVisitButton = Ext.create('Ext.button.Button', { 
        text: 'Копировать',    
        iconCls: 'deluser',
        itemId: 'copy',
        id: 'copyVisit',
        handler: function()
        {
            var copyTaskPanel = Ext.create('Ext.panel.Panel', {
                bodyPadding: 5,
                width: 300,
                items: [{
                             xtype: 'monthfield',
                              fieldLabel: 'Месяц источник',
                              submitFormat: 'Y-m',
                              id: 'Copy_date_from',
                             format: 'F, Y',  
                             value: new Date()  
                        }, {
                         xtype: 'monthfield',
                          fieldLabel: 'Месяц контейнер',
                          submitFormat: 'Y-m',
                          id: 'Copy_date_to',
                         format: 'F, Y',  
                         value: new Date()  
                       
                }],
                buttons: [copyVisitButtonOk]
            });
            copyTasksWin = new Windows('Копирование задачи',300,200); // create window
            copyTasksWin.CreateWindowModal(copyTasksWin,copyTaskPanel); 
            copyTasksWin.Window.show();
        }
  });


      CalendarTasksWin.Window.addDocked({
        xtype: 'toolbar',
        dock: 'top',
        items:[
            copyVisitButton,
          //'-',
          /*{
          text: "Создать задачу",
          iconCls: 'createtask',
          handler:function(){
          createTaskVisitsWindow(0);
          }
          },'-',*/
          {
            xtype:'combo',
            id: 'monthIdComboTaskVisits',				
            store: monthTaskVisits,
            width: 100,
            queryMode: 'local',
            //queryParam: 'id',
            displayField: 'type',
            valueField: 'id',
            typeAhead: false,
            //triggerAction: 'all',
            lazyRender: true,
            editable: false,
            value:month
          },
          {
            xtype: 'numberfield',
            //name: 'numberfield',
            id: 'yearIdNumbrTaskVisits',
            width: 60,
            value:year,
            minValue: 2013,
            maxValue: 2099
          },
          {
            text: "Перейти",
            iconCls: 'left-right',
            id:'GoTaskVisits',
            handler:function(){
              var typeMonth = Ext.getCmp('monthIdComboTaskVisits').getValue();
              var typeYear = Ext.getCmp('yearIdNumbrTaskVisits').getValue();

              $.post('app/SFA_CalendarTasks.php', {func:'show', typeMonth:typeMonth, typeYear:typeYear},function(data){ 
                //alert(data);
                var resultTV2 = data.split('/n');
                var columnsTV2 = eval("(" + resultTV2[0] + ")");
                var fieldsTV2 = eval("(" + resultTV2[1] + ")");
                var dataTV2 = eval("(" + resultTV2[2] + ")");

                Ext.define('TaskVisitsModel', {
                  extend: 'Ext.data.Model',
                  fields: fieldsTV2
                });
                var TaskVisitsStore = new Ext.data.Store({
                  model: 'TaskVisitsModel',
                  data: dataTV2
                });

                Ext.getCmp('TaskVisitsGridId').destroy();

                CalendarTasksGrid = Ext.create('Ext.grid.Panel',{
                  selType: 'cellmodel',
                  columnLines: true,
                  id: 'TaskVisitsGridId',
                  store: TaskVisitsStore,
                  loadMask: true,
                  border: false,
                  frame: true,
                  columns: columnsTV2,
                  autoScroll: true,
                  listeners:{
                    itemdblclick: function(View,record,item,index,e,eOpts){
                      itemdblclickOnGrid(View,record,item,index,e,eOpts);
                    }  
                  }
                });	

                CalendarTasksWin.Window.add(CalendarTasksGrid);
              });	
            }
          },
		  {
			text: "Добавить циклический визит",
            handler:function(){
				var select = Ext.getCmp('TaskVisitsGridId').getView().getSelectionModel().getSelection()[0];
				if (select) {
					showFormVisitCycle( select.get('id'),select.get('name') );
				} else {
		        Ext.Msg.alert('Ошибка', 'Выберите пользователя');      	   
		        }
			}
		  }
		  
        ]
      });

      CalendarTasksWin.Window.show();
    });
  }
}


function itemdblclickOnGrid(View,record,item,index,e,eOpts)
{
  var posTask = Ext.getCmp('TaskVisitsGridId').getSelectionModel().getCurrentPosition();
  var cellTask = Ext.getCmp('TaskVisitsGridId').getView().getCellByPosition({row:posTask.row, column: posTask.column});
  if (posTask.column>1)
  {	
    var clickItemTask = posTask.column;		
    var dateCellTask = View.headerCt.initialConfig.items[clickItemTask].id;

	console.log('dateCellTask - '+dateCellTask);
	
    dateCellTask = dateCellTask.slice(0,-1);
	
    var idUser = record.get('id');
    var idName = record.get('name');
    var clicRec = clickItemTask-1;			
    var clickSourc = record.get(clicRec);

    /*if(clickSourc){
      //alert(dateCellTask+' '+idUser+' '+idName);
      showWindowWithTasks(dateCellTask, idUser, idName);
    }else{
      createVisitsWindow(0)
    }*/
	
	console.log('dateCellTask - '+dateCellTask);
	
    showVisit(idUser,idName,dateCellTask);
  }
}









/*
===================================================    add edit task    ==========================================
*/

function createTaskVisitsWindow(select,idvis){

  //alert(idvis);

  $.post("app/SFA_CalendarTasks.php",{func:'selectforedit',select:select}, function(data){

    var tit = 'Создание задач';
    var titleTasks = "";
    var clientTasks = "";
    var priority = ""

    if(select!=0){
      //alert(data);
      tit = 'Изминение задач';
      if(data){
        var obj = Ext.decode(data);
        titleTasks = obj.rows[0].bodyTask;
        clientTasks = obj.rows[0].clientID;
        priority = obj.rows[0].priority;
      }
    }


    Ext.define('ClientsTaskVisits', {
      extend: 'Ext.data.Model',
      fields: ['id', 'name', 'address']
    });
    var ClientStoreTaskVisits = new Ext.data.Store({
      autoLoad: true,
      autoDestroy: true,
      model: 'ClientsTaskVisits',
      proxy: {
        type: 'ajax',
        url: 'app/SFA_CalendarTasks.php?func=showClient',
        reader: {
          type: 'json',
          root: 'rows'
        }
      }
    });

    /*var panel = new Ext.panel.Panel({
    //title: 'Hello',
    //width: 200,
    //html: '<p>World!</p>'
    items:[
    {
    region:'center',
    title: 'Визит',
    height: '70%',
    width: '100%',
    autoScroll: true,
    autoHeight: true,
    layout:'anchor',
    frame:true,
    border:false,
    items:[]
    },{
    region: 'south',
    height: '30%',
    //split: true,
    //collapsible: true,
    //floatable: false,
    //closeAction: 'hide',
    //collapsed:true,
    //minHeight: 200,
    //maxHeight:600,
    autoScroll: true,
    frame:true,
    title: 'Задачи',
    margins: '0 1 1 1',
    align: 'stretch',
    layout: {
    type: 'hbox',
    align: 'stretch'
    },
    defaults: { flex : 1 },
    items:[]
    }
    ]
    });*/

    var TaskVisitsWin = new Windows(tit,550,330,false);

    //var FormConstructor = new Forms();
    //var formUser = FormConstructor.CreateComboboxFieldLabelTopLocalWidthPercent('Пользователь',UsersStoreTaskVisits,'name','id','99%');
    //var formClient = FormConstructor.CreateComboboxFieldLabelTopLocalWidthPercent('Клиент',ClientStoreTaskVisits,'name','id','100%');


    var formCalendarTask = new Ext.create('Ext.form.Panel',{
      //bodyStyle: 'background-color: #CED9E7;',
      frame:true,
      //id: 'FormTaskVisitsAdd',
      border:false,
      //width: '100%',
      //autoScroll: true,
      fieldDefaults:{
        labelAlign: 'top',
        msgTarget: 'side'
      },
      bodyPadding: 5,
      defaults:{
        anchor: '100%'
      },
      items:[
        {
          xtype: 'textarea',
          name: 'titleTasks',
          fieldLabel: 'Задача',
          height: 150,
          anchor: '100%',
          allowBlank: false,
          value:titleTasks
        },
        {
          xtype: 'container',
          anchor: '100%',
          layout: 'hbox',
          items:[
            {
              xtype: 'container',
              flex: 1,
              layout: 'anchor',
              items: [
                /*{
                xtype:'datefield',              
                fieldLabel:'Дата',
                name: 'dateTasks',
                format: 'Y-m-d',
                altFormats: 'Y-m-d',
                allowBlank: false,
                value:dateTasks,
                anchor:'99%'
                },*/
                {
                  xtype:'combo',
                  name: 'priority',
                  fieldLabel: 'Приоритет',
                  anchor:'98%',
                  selectOnTab:true,
                  store: new Ext.data.Store({
                    fields:['id','state'],
                    data:[{"id":"Высокий", "state":"Высокий"},
                      {"id":"Средний","state":"Средний"},
                      {"id":"Низкий","state":"Низкий"}
                  ]}),
                  queryMode: 'local',
                  queryParam: 'id',
                  typeAhead: true,
                  triggerAction: 'all',
                  editable: true,
                  lazyRender: true,
                  displayField: 'state',
                  valueField: 'id',
                  allowBlank: false,
                  value: priority
                }
              ]
            },{
              xtype: 'container',
              flex: 1,
              layout: 'anchor',
              items: [
                {
                  xtype:'combo',              
                  fieldLabel:'Клиент',
                  name: 'clientTasks',
                  editable:false,
                  id:"userNameTasks",
                  selectOnTab:true,
                  store: ClientStoreTaskVisits,
                  queryMode: 'local',
                  queryParam: 'id',
                  typeAhead: false,
                  //lazyRender: true,
                  displayField: 'name',
                  valueField: 'id',
                  allowBlank: false,
                  anchor:'99%',
                  value:clientTasks
                }
              ]
            }
          ]
        }
      ],
      buttons: [
        '->',
        {
          text: 'Сохранить',
          iconCls: 'save',
          handler: function(){
            var form = this.up('form').getForm();
            if (form.isValid ()){
              var username = Ext.getCmp('userNameTasks').getRawValue();
              form.submit({
                url: 'app/SFA_CalendarTasks.php',
                params: {func:'addedit', select:select, username:username, idvis:idvis},
                method  : 'POST',
                waitMsg: 'Загрузка...',
                //timeout : 5,
                success : function(form, action) {
                  //form.reset();
                  Ext.Msg.alert('Cохранено', action.result.msg);
                  form.reset();
                  if(WindowWithTasksGrid){
                    WindowWithTasksGrid.store.load();
                    WindowWithTasksGrid.getView().refresh();
                  }

                  //TaskVisitsWin.Window.destroy();

                },
                failure : function(form, action) {
                }
              });
            }

          }
        },
        {
          text:'Отмена',
          iconCls: 'cancel',
          handler:function(){
            //$('#GoTaskVisits').trigger('click');
            TaskVisitsWin.Window.destroy();
          }
        }
      ]
    });

    TaskVisitsWin.CreateWindowModal(TaskVisitsWin,formCalendarTask);

    TaskVisitsWin.Window.show();	

  });
}
//==========================================================================================================


/*
===================================================    add vis    ==========================================
*/
/*
function createVisitsWindow(select){

  $.post("app/SFA_CalendarTasks.php",{func:'selectforeditvisit',select:select}, function(data){

    var tit = 'Создание визита';
    var titleVis = "";
    var dateVis = d;
    var userVis = "";
    var TTVis = "";

    if(select!=0){
      //alert(data);
      tit = 'Изминение визита';
      if(data){
        var obj = Ext.decode(data);
        titleVis = obj.rows[0].decription_visit;
        dateVis = obj.rows[0].date_visit;
        userVis = obj.rows[0].id_user;
        TTVis = obj.rows[0].id_trade_point;
      }
    }

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

    var UsersStoreVisits = new Ext.data.Store({
      autoLoad: true,
      autoDestroy: true,
      model: 'UsersVisitsModel',
      proxy: {
        type: 'ajax',
        url: 'app/SFA_CalendarTasks.php?func=showUsers',
        reader: {
          type: 'json',
          root: 'rows'
        }
      }
    });
    var ClientStoreVisits = new Ext.data.Store({
      autoLoad: true,
      autoDestroy: true,
      model: 'ClientsVisitsModel',
      proxy: {
        type: 'ajax',
        url: 'app/SFA_CalendarTasks.php?func=showTT',
        reader: {
          type: 'json',
          root: 'rows'
        }
      }
    });



    var VisitsWin = new Windows(tit,550,330,false);


    var formCalendarVis = new Ext.create('Ext.form.Panel',{
      //bodyStyle: 'background-color: #CED9E7;',
      frame:true,
      //id: 'FormTaskVisitsAdd',
      border:false,
      //width: '100%',
      //autoScroll: true,
      fieldDefaults:{
        labelAlign: 'top',
        msgTarget: 'side'
      },
      bodyPadding: 5,
      defaults:{
        anchor: '100%'
      },
      items:[
        {
          xtype: 'textarea',
          name: 'titleTasks',
          fieldLabel: 'Название визита',
          height: 150,
          anchor: '100%',
          allowBlank: false,
          value:titleVis
        },
        {
          xtype: 'container',
          anchor: '100%',
          layout: 'hbox',
          items:[
            {
              xtype: 'container',
              flex: 1,
              layout: 'anchor',
              items: [
                {
                  xtype:'datefield',              
                  fieldLabel:'Дата',
                  name: 'dateTasks',
                  format: 'Y-m-d',
                  altFormats: 'Y-m-d',
                  allowBlank: false,
                  value:dateVis,
                  anchor:'99%'
                },
                {
                  xtype:'combo',              
                  fieldLabel:'Пользователь',
                  name: 'userTasks',
                  id: 'userNameVis',
                  editable:false,
                  selectOnTab:true,
                  store: UsersStoreVisits,
                  queryMode: 'local',
                  queryParam: 'id',
                  typeAhead: false,
                  lazyRender: true,
                  displayField: 'name',
                  valueField: 'id',
                  allowBlank: false,
                  anchor:'99%',
                  value:userVis
                }

              ]
            },{
              xtype: 'container',
              flex: 1,
              layout: 'anchor',
              items: [
                {
                  xtype:'combo',              
                  fieldLabel:'Торговая точка',
                  name: 'clientTasks',
                  editable: true,
                  selectOnTab: true,
                  store: ClientStoreVisits,
                  queryMode: 'remote',
                  queryParam: 'id',
                  typeAhead: true,
                  lazyRender: true,
                  displayField: 'name',
                  valueField: 'id',
                  allowBlank: false,
                  anchor:'99%',
                  value:TTVis
                }
              ]
            }
          ]
        }
      ],
      buttons: [
        '->',
        {
          text: 'Сохранить',
          iconCls: 'save',
          handler: function(){
            var form = this.up('form').getForm();
            if (form.isValid ()){
              var username = Ext.getCmp('userNameVis').getRawValue();
              form.submit({
                url: 'app/SFA_CalendarTasks.php',
                params: {func:'addeditvis', select:select, username:username},
                method  : 'POST',
                waitMsg: 'Загрузка...',
                //timeout : 5,
                success : function(form, action) {
                  //form.reset();
                  //Ext.Msg.alert('Cохранено', action.result.msg);
                  Ext.Msg.alert('Cохранено', action.result.msg, function(btn, text){
                    if (btn == 'ok'){
                      VisitsWin.Window.destroy();
                      $('#GoTaskVisits').trigger('click');
                      createTaskVisitsWindow(0,action.result.id);
                    }else{
                      return false;
                    }
                  });

                },
                failure : function(form, action) {
                }
              });
            }

          }
        },
        {
          text:'Отмена',
          iconCls: 'cancel',
          handler:function(){
            //$('#GoTaskVisits').trigger('click');
            VisitsWin.Window.destroy();
          }
        }
      ]
    });

    VisitsWin.CreateWindowModal(VisitsWin,formCalendarVis);

    VisitsWin.Window.show();	

  });
}

*/

//=======================================================================================================
/*
function showWindowWithTasks(dateCellTask, idUser, idName){

  Ext.define('WindowWithTasksModel', {
    extend: 'Ext.data.Model',
    fields: ['id_visit', 'taskID', 'decription_visit', 'bodyTask', 'trade_point', 'complit', 'client', 'Actionss']
  });
  var ShowTaskVisitsStore = new Ext.data.Store({
    //autoLoad: true,
    //autoDestroy: true,
    model: 'WindowWithTasksModel',
    proxy: {
      type: 'ajax',
      url: 'app/SFA_CalendarTasks.php?func=ShowEdit&dateCellTask='+dateCellTask+'&idUser='+idUser,
      reader: {
        type: 'json',
        root: 'rows'
      }
    }
  });
  ShowTaskVisitsStore.load();
 //function renderIcon(val) {
  //alert(val);
  //return '<div style="text-align:center;"><a style="margin-right:7px;" href="#" onclick="createTaskVisitsWindow(0)"><img src="images/Notes.png" alt="Редактировать">'+val+'</a><a href="#" onclick="aaa(this)"><img src="images/Erase.png" alt="Удалить"> ' + val  +'</a></div>';		  
  //}

  WindowWithTasksGrid = new Ext.create('Ext.grid.Panel',{
    selType: 'rowmodel',
    columnLines: true,
    store: ShowTaskVisitsStore,
    loadMask: true,
    border: false,
    frame: false,
    //autoScroll: true,
    stripeRows: true,
    columns:[
      {xtype: 'rownumberer',
        text : '№', 
        width: 30
      },{
        text: 'Задача', 
        dataIndex: 'bodyTask',
        sortable: true,
        hideable: false,
        flex: 1
      },{
        text: 'Торговая точка', 
        dataIndex: 'trade_point',
        width:150,
        sortable: true,
        hideable: false
      },{
        text: 'Статус', 
        dataIndex: 'complit',
        width:70,
        sortable: true,
        hideable: false
      },{
        text: 'Клиент', 
        dataIndex: 'client',
        width:70,
        sortable: true,
        hideable: false
      },
      //{
      //text : 'Действия', 
      //dataIndex : 'Actionss',
      //width:80,
      //sortable: false,
     // hideable: false,
      //renderer: renderIcon            
      }
      {
        xtype: 'actioncolumn',
        width: 80,
        text : 'Действия',
        items: [
          {
            icon   : 'images/Notes.png',
            tooltip: 'Редактировать',
            handler: function(grid, rowIndex, colIndex) {
              var rec = ShowTaskVisitsStore.getAt(rowIndex);
              //alert(rec.get('id'));
              createTaskVisitsWindow(rec.get('taskID'),rec.get('id_visit'))
            }
          },
          {
            icon   : 'images/Erase.png',
            tooltip: 'Удалить',
            handler: function(grid, rowIndex, colIndex) {
              var rec = ShowTaskVisitsStore.getAt(rowIndex);
              $.post('app/SFA_CalendarTasks.php', { func:'delete', id:rec.get('taskID') },function(data){ 
                ShowTaskVisitsStore.load();
                WindowWithTasksGrid.getView().refresh();
              })
            }
          }
        ]
      }
    ]
  });

  var WinWithTasks = new Windows('Задачи на '+dateCellTask+', пользователь - '+idName,600,400,false);
  WinWithTasks.CreateWindowModal(WinWithTasks,WindowWithTasksGrid);					


  WinWithTasks.Window.addDocked({
    xtype: 'toolbar',
    dock: 'top',
    items:[
      {
        text: "Создать задачу",
        iconCls: 'createtask',
        handler:function(){
          var rec = ShowTaskVisitsStore.getAt(0);
          createTaskVisitsWindow(0,rec.get('id_visit'));
        }
      }
    ]
  });

  WinWithTasks.Window.show();
}

*/



var msg = function(title, msg) {
  Ext.Msg.show({
    title: title,
    msg: msg,
    minWidth: 200,
    modal: true,
    icon: Ext.Msg.INFO,
    buttons: Ext.Msg.OK
  });
};

var deleteVisit = function(title, msguam, id_row) {                  // function delete client
  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'){
        //alert (select);
        $.post("app/SFA_CRUDVisit.php",{func:'delete',id:id_row},function(data)
          {
            GridVisit.store.load();
            GridVisit.getView().refresh();
            var deleteButton = Ext.getCmp('delete');
            deleteButton.setDisabled(true);
        });                                              
      }
    }
  });
};




Ext.define('ModelVisit', {
    extend: 'Ext.data.Model',
    fields: ['id', 'date', 'description', 'trade_point', 'address', 'id_user', 'date_start', 'id_client', 'close']
});

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



// ----------------------------------Window ------------------------------------

function showVisit(idName,nameUser,date)
{
  //alert('showVisit');
  
  dateVisits = date;
  id_name = idName;
  
  //createGridVisit();
  // ------------------------------------- create Grid --------------------------------------    
//function createGridVisit()
//{
  GridVisit = new Ext.grid.GridPanel({
    selType: 'rowmodel',
    columnLines: true,
    id: 'GridVisitId',
    store: StoreVisit,
    columns:[
      {
        text : 'id', 
        dataIndex : 'id',
        width:40,
        sortable: true,
        hidden: true
      },
      {
        xtype: 'rownumberer',
        text: '№',
        width: 40,
        hideable: false,
        sortable: true
      },
      {
        text : 'Дата и время', 
        dataIndex : 'date',
        width: 140,
        sortable: true,
      },
      {
        text : 'Описание', 
        dataIndex : 'description',
        width: 140,
        sortable: true,
      },
      {
        text : 'Торговая точка', 
        dataIndex : 'trade_point',
        width: 140,
        sortable: true,
      },
      {
        text : 'Адрес', 
        dataIndex : 'address',
        width: 140,
        sortable: true,
      },
      {
        text : 'Статус', 
        dataIndex : 'close',
        width: 140,
        sortable: true,
      }
    ],
    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');
		showFormVisit(id_row,id_name,dateVisits);
        //id_row = parseInt(id_row);
        //showFormVisit(id_row);
        //ShowTask(id_row);
        id_row = false;
      }
    }
  });
//}
  
  StoreVisit.load({params:{date: dateVisits, id_name: id_name}});
  var WindowVisit = new Windows('Визиты для '+nameUser+' на '+date,675,380);       // create window
  WindowVisit.CreateWindowModal(WindowVisit,GridVisit);
  
  WindowVisit.Window.on('destroy',function()
    {
      CalendarTasksWin.Window.remove(CalendarTasksGrid);
			  var typeMonth = Ext.getCmp('monthIdComboTaskVisits').getValue();
              var typeYear = Ext.getCmp('yearIdNumbrTaskVisits').getValue();
      $.post('app/SFA_CalendarTasks.php', {func:'show', typeMonth:typeMonth, typeYear:typeYear}, function(data)
      {
        var resultTV = data.split('/n');
        var columnsTV = eval("(" + resultTV[0] + ")");
        var fieldsTV = eval("(" + resultTV[1] + ")");
        var dataTV = eval("(" + resultTV[2] + ")");

        Ext.define('TaskVisitsModel', {
          extend: 'Ext.data.Model',
          fields: fieldsTV
        });
        var TaskVisitsStore = new Ext.data.Store({
          model: 'TaskVisitsModel',
          data: dataTV
        });
        CalendarTasksGrid = new Ext.grid.GridPanel({
          selType: 'cellmodel',
          columnLines: true,
          id: 'TaskVisitsGridId',
          store: TaskVisitsStore,
          loadMask: true,
          border: false,
          frame: true,
          columns: columnsTV,
          autoScroll: true,
          listeners:{
            itemdblclick: function(View,record,item,index,e,eOpts){ 
              itemdblclickOnGrid(View,record,item,index,e,eOpts);
            }
          }
        });
        CalendarTasksWin.Window.add(CalendarTasksGrid);
      });
    });
  
  
  // ------------------------------ create button ------------------------------------------  
  var addVisit = Ext.create('Ext.button.Button', { 
    text: 'Добавить',
    iconCls: 'adduser',
    handler: function(){ showFormVisit(null,id_name,dateVisits); }
  });
  var correctVisit = Ext.create('Ext.button.Button', { 
    text: 'Редактировать',
    iconCls: 'createtask',
    handler: function()
    {
      
	  if (!id_row){msg('Выбрано 0 записей.', 'Выберите запись!');}
      else
      {
        showFormVisit(id_row,id_name,dateVisits);
        id_row = false;
      }
    }
  });
  var deleteVisitButton = Ext.create('Ext.button.Button', { 
    text: 'Удалить',    
    iconCls: 'deluser',
    disabled: true,
    itemId: 'delete',
    id: 'delete',
    handler: function()
    {
      if (!id_row){msg('Выбрано 0 записей', 'Выберите запись!');}
      else{
        //deleteRow('Удаление', 'Вы точно хотите удалить данный визит !?',id_row,'Visit');
		Ext.MessageBox.confirm('Удаление', 'Вы действительно хотите удалить данный визит?',  function(btn){
		if(btn=='yes'){
			 $.post('app/SFA_CRUDVisit.php', { func:'delete', id:id_row },function(data){ 
                StoreVisit.load({params:{date: dateVisits, id_name: id_name}});
				StoreVisit.load();
              })
		}});
      }
    }
  });
  WindowVisit.Window.addDocked(
    {
      xtype: 'toolbar',
      dock: 'top',
      items:[addVisit,correctVisit,deleteVisitButton]
  });
  //---------------------------------------------------------------------------------------- 

  WindowVisit.Window.show();
}



// ------------------------------- Create Form for Add and Correct Data Visit ------------------------

function showFormVisit(id_row,id_name,dateVisits)
{
  //alert('showFormVisit');
   //alert(id_row);
    //alert(id_name);
	console.log("dateVisits - "+dateVisits);
   
  var idSelectingRow = id_row;

  $.post('app/SFA_CRUDVisit.php', {func:'edit',id:idSelectingRow}, function(data){
    
	if(id_row){
		var arrayDataVisit  = data.split('/t');
		var id = parseInt(arrayDataVisit[0]);
		var dateTime = arrayDataVisit[1];
    if (dateTime)
    {
      var arrayDateTime = dateTime.split(' ');
      var date = arrayDateTime[0];
      var time = arrayDateTime[1].substr(0,5);
    }
    else 
    {
      var date = dateVisits;
      var time = '00:00';
    }
    
    var description = arrayDataVisit[2];
    var id_trade_point = parseInt(arrayDataVisit[3]);
    var id_user = parseInt(arrayDataVisit[4]);
	}else{
		//var date = Ext.Date.format(new Date(),'Y-m-d');
		var date = dateVisits;
		var time = Ext.Date.format(new Date(),'H:i');
		var description = "";
		var id_trade_point = "";
		var id = "";
	}
	
	console.log("date - "+date);
	
    /*var FormConstructor = new Forms();
    var fieldDate = FormConstructor.CreateDateField('Дата','top','100',date,'Y-m-d');
    var fieldTime = FormConstructor.CreateTimeField('Время','top','80',time,'H:i');
    var fieldDescription = FormConstructor.CreateTextFieldWidthPercent('Описание','top','190%',description);
    var fieldId_trade_point = FormConstructor.CreateComboboxFieldProxyWidthPercent('Торговая точка','top',StoreTradePoint,'name','id','95%',id_trade_point);
    Data_boss_id.load();
    var fieldId_user = FormConstructor.CreateComboboxFieldProxyWidthPercent('Пользователь','top',Data_boss_id,'FIO_B','id','95%',id_user);
    */
	StoreTradePoint.load();
   
    var formVisit = Ext.create('Ext.form.Panel', 
    {
        frame:true,
        bodyStyle: 'padding: 7px',
        width: '100%',
        autoScroll: true,
        fieldDefaults: 
        {
          labelAlign: 'top',
          //msgTarget: 'side'
        },                
        items:[
        {
            xtype: 'fieldcontainer',
            layout: 'hbox',
            defaults: {
                        //hideLabel: 'true'
            },
            items: [
				{
                  xtype:'datefield',              
                  fieldLabel:'Дата',
				  //width: 100,
                  name: 'dateTasks',
				  id: 'dateTasks',
                  format: 'Y-m-d',
				  //labelAlign: 'left',
				  //labelWidth: 40,
                  altFormats: 'Y-m-d',
				  readOnly: true,
				  editable: false,
                  allowBlank: false,
				  value: date,
				  width:'15%'
                },
				{
                  xtype:'timefield',				
                  format: 'H:i',
                  name: 'timeTasks',
				  id: 'timeTasks',
				  altFormats: 'H:i',              
                  fieldLabel: 'Время',
				  allowBlank: false,
				  //labelAlign: 'left',
				  //labelWidth: 40,
				  //width: 70,
				  value: time,
				  margin: '0 0 0 5',
                  editable: false,
				  width: '15%'
				},
				{
                  xtype:'combobox',              
                  fieldLabel:'Торговая точка',
                  name: 'clientTasks',
				  id: 'clientTasks',
                  editable: true,
				  //hideTrigger: true,
				  //triggerAction: 'query',
				  //lazyRender: true,
				  //pageSize: 50,
                  selectOnTab: true,
                  store: StoreTradePoint,
                  queryMode: 'remote',
				  minChars: 1,
                  queryParam: 'id',
                  typeAhead: true,
                  displayField: 'name',
				  margin: '0 0 0 5',
                  valueField: 'id',
                  allowBlank: false,
				  value: id_trade_point,
				  //labelAlign: 'left',
				  //labelWidth: 90,
                  width:'69%'
                }
            ]
        },
		{
                  xtype:'textarea',				
                  name: 'infoTasks',
				  id: 'infoTasks',				  
                  fieldLabel: 'Описание',
				  //allowBlank: false,
				  value: description,
                  width:'99%'
		}
		]
    });
    var windowFormVisit = new Windows('Данные визита',600,220);
    windowFormVisit.CreateWindowModal(windowFormVisit,formVisit);

    var saveDataVisit = Ext.create('Ext.button.Button', { 
      text: 'Сохранить',    
      iconCls: 'save',
      handler: function()
      {
        
       
		//var date = fieldDate.getRawValue()+' '+fieldTime.getRawValue();
		//var description = fieldDescription.getValue();
		//var id_trade_point = fieldId_trade_point.getValue();
		//var id_user = fieldId_user.getValue();
		var date = Ext.getCmp('dateTasks').getRawValue()+' '+Ext.getCmp('timeTasks').getRawValue();
		var description = Ext.getCmp('infoTasks').getValue();
        var id_trade_point = Ext.getCmp('clientTasks').getValue();
		var id_user = id_name;
        
		
        
		if (id_trade_point=='')
        //if (description=='' || id_trade_point=='')
        {
          msg('Ошибка!', 'Проверьте данные!');
          //if (description==''){fieldDescription.markInvalid('Проверьте данные!');}
          //if (id_trade_point==''){fieldId_trade_point.markInvalid('Проверьте данные!');}
          //if (id_user==''){fieldId_user.markInvalid('Проверьте данные!');}
        }
        else 
        {
          $.post("app/SFA_CRUDVisit.php",{func:'update',id:id, date:date, description:description, id_trade_point:id_trade_point, id_user:id_user}, function(data){
            //alert(data);
            windowFormVisit.Window.destroy();
            GridVisit.store.load({params:{date: dateVisits, id_name: id_name}});
            GridVisit.getView().refresh();
            var deleteButton = Ext.getCmp('delete');
            deleteButton.setDisabled(true);
          });
        }
		
		
      }
    });
	
    var cancelInputDataVisit = Ext.create('Ext.button.Button', {
      text: 'Отмена',    
      handler: function(){
        windowFormVisit.Window.destroy();
        GridVisit.store.load({params:{date: dateVisits, id_name: id_name}});
        GridVisit.getView().refresh();
        var deleteButton = Ext.getCmp('delete');
        deleteButton.setDisabled(true);
      }
    });
	
    windowFormVisit.Window.addDocked({
        xtype: 'toolbar',
        dock: 'bottom',
        items:['->',saveDataVisit,'-',cancelInputDataVisit]
    });

    windowFormVisit.Window.show();
	
  });
}



























function showFormVisitCycle(id_row,id_name)
{
     
  
   
    var formVisitCycle = Ext.create('Ext.form.Panel', 
    {
        frame:true,
        bodyStyle: 'padding: 7px',
        width: '100%',
        autoScroll: true,
        fieldDefaults: 
        {
          labelAlign: 'top',
          //msgTarget: 'side'
        },                
        items:[
        {
            xtype: 'fieldcontainer',
            layout: 'hbox',
            defaults: {
                        //hideLabel: 'true'
            },
            items: [
				{
                  xtype:'datefield',              
                  fieldLabel:'Дата начала',
				  //width: 100,
                  name: 'dateTasksFrom',
				  //id: 'dateTasks',
                  format: 'Y-m-d',
				  //labelAlign: 'left',
				  //labelWidth: 40,
                  altFormats: 'Y-m-d',
				  //readOnly: true,
				  editable: false,
                  allowBlank: false,
				  //value: date,
				  width:'15%'
                },
				{
                  xtype:'datefield',              
                  fieldLabel:'Дата окончания',
				  //width: 100,
                  name: 'dateTasksTo',
				  //id: 'dateTasks',
                  format: 'Y-m-d',
				  //labelAlign: 'left',
				  //labelWidth: 40,
                  altFormats: 'Y-m-d',
				  //readOnly: true,
				  editable: false,
                  allowBlank: false,
				  margin: '0 0 0 5',
				  //value: date,
				  width:'15%'
                },
				{
                  xtype:'timefield',				
                  format: 'H:i',
                  name: 'timeTasks',
				  //id: 'timeTasks',
				  altFormats: 'H:i',              
                  fieldLabel: 'Время',
				  allowBlank: false,
				  //labelAlign: 'left',
				  //labelWidth: 40,
				  //width: 70,
				  //value: time,
				  margin: '0 0 0 5',
                  editable: false,
				  width: '15%'
				},
				{
					xtype:'combobox',              
                    fieldLabel:'Кратность',
                    name: 'periodDaysTasks',
					selectOnTab: true,
					width: '15%',
					store: new Ext.data.Store({fields:['id','type'],data:[
					{"id":"1", "type":"1 день"},
					{"id":"7", "type":"7 дней"},
					{"id":"14", "type":"14 дней"},
					{"id":"21", "type":"21 день"},
					{"id":"28", "type":"28 дней"}
					]}),
					queryMode: 'local',
					typeAhead: true,
					displayField: 'type',
					margin: '0 0 0 5',
					valueField: 'id',
					editable: false,
					value: 7,
					allowBlank: false
				},
				{
                  xtype:'combobox',              
                  fieldLabel:'Торговая точка',
                  name: 'clientTasks[]',
				  //id: 'clientTasks',
                  editable: true,
				  //hideTrigger: true,
				  //triggerAction: 'query',
				  //lazyRender: true,
				  //pageSize: 50,
                  selectOnTab: true,
                  store: StoreTradePoint,
                  queryMode: 'remote',
				  minChars: 1,
                  queryParam: 'id',
                  typeAhead: true,
                  displayField: 'name',
				  margin: '0 0 0 5',
                  valueField: 'id',
                  allowBlank: false,
				  //value: id_trade_point,
				  //labelAlign: 'left',
				  //labelWidth: 90,
				  multiSelect: true,
                  width:'39%'
                }
            ]
        },
		{
                  xtype:'textarea',				
                  name: 'infoTasks',
				  //id: 'infoTasks',				  
                  fieldLabel: 'Описание',
				  //allowBlank: false,
				  //value: description,
                  width:'99%'
		}
		]
    });
    var windowFormVisitCycle = new Windows('Создание циклического визита для пользователя '+id_name,700,220);
    windowFormVisitCycle.CreateWindowModal(windowFormVisitCycle,formVisitCycle);

    var saveDataVisitCycle = Ext.create('Ext.button.Button', { 
      text: 'Сохранить',    
      iconCls: 'save',
      handler: function()
      {
        var form = formVisitCycle.getForm();
		if(form.isValid()){
								form.submit({
								waitMsg:'Идет отправка...',
	                            url: 'app/SFA_CRUDVisit.php',							
								wait: true,
								scope: this,
								method: 'post',							
								params: {func:'addVisitCycle',id_user:id_row},
	                            success: function(fp, o){
	                            	
	                            	windowFormVisitCycle.Window.destroy();
									
									
									
	
      var typeMonth = Ext.getCmp('monthIdComboTaskVisits').getValue();
      var typeYear = Ext.getCmp('yearIdNumbrTaskVisits').getValue();
      $.post('app/SFA_CalendarTasks.php', {func:'show', typeMonth:typeMonth, typeYear:typeYear}, function(data)
      {
        var resultTV = data.split('/n');
        var columnsTV = eval("(" + resultTV[0] + ")");
        var fieldsTV = eval("(" + resultTV[1] + ")");
        var dataTV = eval("(" + resultTV[2] + ")");

        Ext.define('TaskVisitsModel', {
          extend: 'Ext.data.Model',
          fields: fieldsTV
        });
        var TaskVisitsStore = new Ext.data.Store({
          model: 'TaskVisitsModel',
          data: dataTV
        });
        CalendarTasksGrid = new Ext.grid.GridPanel({
          selType: 'cellmodel',
          columnLines: true,
          id: 'TaskVisitsGridId',
          store: TaskVisitsStore,
          loadMask: true,
          border: false,
          frame: true,
          columns: columnsTV,
          autoScroll: true,
          listeners:{
            itemdblclick: function(View,record,item,index,e,eOpts){ 
              itemdblclickOnGrid(View,record,item,index,e,eOpts);
            }
          }
        });
        CalendarTasksWin.Window.add(CalendarTasksGrid);
      });

									
									
									
	                            }
								})
		}else{
			Ext.Msg.alert('Ошибка', 'Обязательные поля не заполнены');
		}
 /*      
		
		var date = Ext.getCmp('dateTasks').getRawValue()+' '+Ext.getCmp('timeTasks').getRawValue();
		var description = Ext.getCmp('infoTasks').getValue();
        var id_trade_point = Ext.getCmp('clientTasks').getValue();
		var id_user = id_name;
        
		
        

        if (description=='' || id_trade_point=='')
        {
          msg('Ошибка!', 'Проверьте данные!');
          if (description==''){fieldDescription.markInvalid('Проверьте данные!');}
          if (id_trade_point==''){fieldId_trade_point.markInvalid('Проверьте данные!');}
          //if (id_user==''){fieldId_user.markInvalid('Проверьте данные!');}
        }
        else 
        {
          $.post("app/SFA_CRUDVisit.php",{func:'update',id:id, date:date, description:description, id_trade_point:id_trade_point, id_user:id_user}, function(data){
            //alert(data);
            windowFormVisit.Window.destroy();
            GridVisit.store.load({params:{date: dateVisits, id_name: id_name}});
            GridVisit.getView().refresh();
            var deleteButton = Ext.getCmp('delete');
            deleteButton.setDisabled(true);
          });
        }
*/		
		
      }
    });
	
    var cancelInputDataVisitCycle = Ext.create('Ext.button.Button', {
      text: 'Отмена',    
      handler: function(){
        windowFormVisitCycle.Window.destroy();
        //GridVisit.store.load({params:{date: dateVisits, id_name: id_name}});
        //GridVisit.getView().refresh();
        //var deleteButton = Ext.getCmp('delete');
        //deleteButton.setDisabled(true);
      }
    });
	
    windowFormVisitCycle.Window.addDocked({
        xtype: 'toolbar',
        dock: 'bottom',
        items:['->',saveDataVisitCycle,'-',cancelInputDataVisitCycle]
    });

    windowFormVisitCycle.Window.show();
	
  
}

