var WarehouseToUsersWindow;
var LogistMobile_warehouse_app_WindowAddEdit;

	Ext.define('store_grid_warehouse_model', {
    extend: 'Ext.data.Model',
    fields: ['Warehouse_ID','Name','Code','StartServeTime','EndServeTime','Address','GeoX','GeoY',{name: 'indoor', type: 'bool'}]
	});
	
	var store_grid_warehouse_users = new Ext.data.Store({
        model: 'store_grid_warehouse_model',
           proxy: {
              type: 'ajax',
              url: 'app/LogistMobile_WarehouseToUsers.php?show_grid_warehouse=true',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
	});

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


	var WarehouseStoreDef = new Ext.data.Store({
        model: 'WarehouseUsersModel',
           proxy: {
              type: 'ajax',
              url: 'app/LogistMobile_WarehouseToUsers.php?func=get_warehouse_def',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
	});
   
	var WarehouseStore = new Ext.data.Store({
        model: 'WarehouseUsersModel',
           proxy: {
              type: 'ajax',
              url: 'app/LogistMobile_WarehouseToUsers.php?func=get_warehouse',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
	});
  
	var UsersStore = new Ext.data.Store({
        model: 'WarehouseUsersModel',
           proxy: {
              type: 'ajax',
              url: 'app/LogistMobile_WarehouseToUsers.php?func=get_users',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
	});
	
	
	UsersStore.load();
	store_grid_warehouse_users.load();
	
	if(!WarehouseToUsersWindow){
         WarehouseToUsersWindow = new Ext.Window({
                        width:550,
                        height:450,
                        title: userswarehouse.warehouse,
                        closeAction : 'destroy',
                        //layout:'fit',
						layout:'border',
                        resizable: true,
                        modal:true,
                        //bodyStyle:{'background-color': '#FFFFFF'},
						listeners: {
							destroy : function(){
								WarehouseToUsersWindow = null;						
							}
						},
                        items:[
				{
                 region:'center',
                 title: userswarehouse.users_warehouse,
				 width: '100%',
                 autoScroll: true,
				 autoHeight: true,
				 layout:'anchor',
				 frame:true,
				 border:false,
                 items:[
		{
                      
					  xtype: 'form',
                      bodyStyle: {padding: '5px'},
					  id: 'form_warehouse_users',
					  //fieldwidth:'width:150px',
                      items:[
                       
                      
                      
        {
		xtype: 'combobox',
		fieldLabel: userswarehouse.users,
		store: UsersStore,
		allowBlank: false,
		labelWidth: 100,
		editable: false,
		valueField: 'id',
		displayField: 'name',
		name: 'combo_warehouse_users',
		id: 'combo_warehouse_users',
		queryMode: 'local',
		selectOnFocus:true,
		listeners: {
			select: function( field, value, eOpts ) {
				
				var myMask = new Ext.LoadMask(WarehouseToUsersWindow, {msg: all.loading});
				myMask.show();
				
				Ext.getCmp('itemselector_warehouse_users').store.removeAll();
				Ext.getCmp('itemselector_warehouse_users').store.load();
				
				//Ext.getCmp('itemselector_warehouse_users').store.bindStore(Ext.getCmp('itemselector_warehouse_users').store); 
				
				Ext.getCmp('itemselector_warehouse_users').reset();
				Ext.getCmp('itemselector_warehouse_users').setValue("");
				
				setTimeout(function(){
                    $.post("app/LogistMobile_WarehouseToUsers.php",{func:'get_warehouse_def',user:Ext.getCmp('combo_warehouse_users').getValue()}, function(data){
						if(data){
							//alert(data);
							Ext.getCmp('itemselector_warehouse_users').setValue(eval('(' + data + ')'));
						}
						myMask.hide();
					}).fail(function(){
						myMask.hide();
					});
                }, 500);
				
				
				
			}
		}
		},
		/*{
		xtype: 'combobox',
		fieldLabel: 'Склад по умолчанию',
		store: WarehouseStoreDef,
		allowBlank: false,
		labelWidth: 130,
		editable: false,
		valueField: 'id',
		displayField: 'name',
		name: 'userscombo',
		queryMode: 'local',
		selectOnFocus:true,
		/*listeners: {
			select: function( field, value, eOpts ) {
				WarehouseStore.load({
            	    params: {
            	    	notin: field.getValue()
            	    }
            	});
			}
		}
		},*/
		/*{
            xtype: 'itemselector',
            height:150,
            id:'WarehouseItems',
            buttons :['add', 'remove'],
            buttonsText : {add: 'add', remove: 'remove'},
            fromTitle: 'Склады',
            toTitle: 'Склады пользователя',
            validateOnChange:false,
            autoScroll:true,
            imagePath: '../ux/images/',
            store: WarehouseStore,
            displayField: 'name',
            valueField: 'id',
            allowBlank: false,
            msgTarget: 'side',
			name: 'warehouseitems',
        },*/
		{
			xtype: 'displayfield',
			style: 'margin-bottom:7px;',              
			value: '<b style="color:red">*</b>'+userswarehouse.text_warehouse,
		},
		{
            xtype: 'itemselector',
            name: 'itemselector_warehouse_users',
	        id: 'itemselector_warehouse_users',
			fromTitle: userswarehouse.warehouse,
            toTitle: userswarehouse.users_warehouse,
			validateOnChange: false,
            autoScroll:true,
			imagePath: '../ux/images/',
			allowBlank: true,
			store: WarehouseStore,
            displayField: 'name',
            valueField: 'id',
            msgTarget: 'side',
			value: []
        }
		
        
		],
                        buttons:[
						{
                                text: all.save,
                                handler: function() {
									var item = Ext.getCmp('itemselector_warehouse_users').getValue();
									var form = Ext.getCmp('form_warehouse_users').getForm();
									if(form.isValid()){
									//if (item == '') {
									//	Ext.MessageBox.alert(all_toir.error, '');
                                    //}else{
	                                    $.post("app/LogistMobile_WarehouseToUsers.php",{func:'save','item[]':item,'user':Ext.getCmp('combo_warehouse_users').getValue()}, function(data){
											if(data){
											var obj = Ext.decode(data);
											if(obj.success == true){
												Ext.MessageBox.alert(all_toir.message, all_toir.skill);
											}else{
												Ext.MessageBox.alert(all_toir.error, obj.message);
											}
											}
										});
	                                //} 
									}
								}
						},
						{
								text: all.cancel,
								handler:function(){
									WarehouseToUsersWindow.destroy();        
								}

						}
						]
                        
		}
				
				]},
				{
                    region: 'south',
					height: '33%',
					split: true,
                    collapsible: true,
                    floatable: false,
					closeAction: 'hide',
					minHeight: 200,
					//maxHeight:600,
					autoScroll: true,
					frame:true,
					title: 'Все склады',
					align: 'stretch',
						layout: {
						type: 'hbox',
						align: 'stretch'
						},
						defaults: { flex : 1 },
					items:[
					
		new Ext.create('Ext.grid.Panel', {
	    selType: 'rowmodel',
        store: store_grid_warehouse_users,
		columnLines: true,
		frame: false,
		border: false,
        autoScroll: true,
		id: 'grid_warehouse_users',
		features: [{
			ftype: 'summary'
        }],
		columns:[
			{
				xtype: 'checkcolumn', dataIndex: 'indoor', width: 35, hideable: false, sortable: false
			},
			{	
				xtype: 'rownumberer', width: 20
			},
			{
                //text: 'Название', 
		        text: request_toir.name, 
                dataIndex: 'Name', 
                sortable: true
			},
			{
                //text: 'Код', 
		        text: request_toir.code, 
                dataIndex: 'Code', 
                sortable: true
			},
			{
                //text: 'Адрес', 
		        text: request_toir.address, 
                dataIndex: 'Address', 
                sortable: true
			},
			{
                //text: 'Начало работ', 
		        text: request_toir.beginning_of_work, 
                dataIndex: 'StartServeTime', 
                sortable: true
			},
			{
                //text: 'Конец работ', 
		        text: request_toir.end_of_works, 
                dataIndex: 'EndServeTime', 
                sortable: true
			},
			{
		        text: 'GeoX', 
                dataIndex: 'GeoX', 
                sortable: true
			},
			{
		        text: 'GeoY', 
                dataIndex: 'GeoY', 
                sortable: true
			},
			
		],
		tbar:[
		{
            text: 'Добавить',
			iconCls: 'add',
            handler: function() {
				warehouse_users_add();
			}
        },
		{
            text: 'Удалить',
			iconCls: 'delete',
            handler: function(){
				warehouse_users_delete();
            }
        }	
		],
		listeners: {
		    	itemdblclick: function(cmp, records) {
		    		warehouse_users_add( records.get('Warehouse_ID'),records );
		    	}
		    }
		})
						
					]

                }
		
		]

                })      
     } 
    WarehouseToUsersWindow.show();
}

function warehouse_users_delete(){
							var arrayWarehouseId=[];									
							var str = '';								
							store_grid_warehouse_users.each(function(record){
								if(record.get('indoor') == true){
										arrayWarehouseId.push(record.get('Warehouse_ID'));
								}
							});
							
							if (arrayWarehouseId.length==0){
								Ext.Msg.alert(all_toir.error, 'Выберите склад(и) для удаления');
							} else {
								var myMask = new Ext.LoadMask(WarehouseToUsersWindow, {msg: all.loading});
								myMask.show();
								
								Ext.MessageBox.confirm(all_toir.attention, 'Вы действительно хотите удалить склад(ы)?',  function(btn){
								if(btn=='yes'){
								
											Ext.Ajax.request({
                                            url: 'app/LogistMobile_WarehouseToUsers.php',
                                            method: 'POST',
                                            params: { 'DeleteWarehouse':true, "arrayWarehouseId[]":arrayWarehouseId },
                                            success: function(response) {
												var obj = Ext.decode(response.responseText);
												if(obj.success == true){
													myMask.hide();
													store_grid_warehouse_users.load();
												}else{
													Ext.MessageBox.alert(all_toir.error, obj.message);
												}
                                            },
                                            failure: function(response) {
                                                Ext.MessageBox.alert(all_toir.error, response.responseText);
                                            }
                                        });
										
								}else{
									//row.set('indoor') == false;
									myMask.hide();
								}
								});
								
								//$.post("app/LogistMobile_WarehouseToUsers.php",{'DeleteWarehouse':true, 'arrayWarehouseId[]':arrayWarehouseId}, function(data){
								//myMask.hide();
								//store_grid_warehouse_users.load();
								//});
								
							}
}







function warehouse_users_add(id,records){

	var PanelMapForCenter = Ext.create('Ext.ux.GMapPanel', {
	                    zoomLevel: 11,
	                    gmapType: 'map',
	                    padding: 170, 
	                    mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
	                    setCenter: {
	                        lat:'50.5',
	                        lng:'30.5'
	                    }
	});

	if (!id){
        var title = request_toir.add_the_request;
    }else{
        var title = request_toir.edit_the_request;
    }
    var date = new Date();

    if(!LogistMobile_warehouse_app_WindowAddEdit){
		
		var place;
		var geo_x;
		var geo_у;
        
		LogistMobile_warehouse_app_WindowAddEdit = new Ext.Window({
            width:750,
            height:320,
            title: title,
            closeAction : 'destroy',
            listeners : {
                destroy : function()
				{
                    LogistMobile_warehouse_app_WindowAddEdit = null;
                },
				afterrender: function( eOpts )
				{
					var locationInput = document.getElementById('warehouselocationField-inputEl');
					locationComplete = new google.maps.places.Autocomplete(locationInput);

					google.maps.event.addListener(locationComplete, 'place_changed', function() {
						place = locationComplete.getPlace();
						geo_y = place.geometry.location.lat();
						geo_x = place.geometry.location.lng();
						if(geo_x !="" && geo_y !="")
						{
							var Cmp_Geo_X = Ext.getCmp('Geo_X');
							var Cmp_Geo_Y = Ext.getCmp('Geo_Y');
							Cmp_Geo_X.setValue(geo_x);
							Cmp_Geo_Y.setValue(geo_y);
						}
					});
				}
            },
            layout:'fit',
            resizable: true,
            constrainHeader: true,
            modal:true,
            items:[
                {
                    xtype: 'form',
                    autoScroll: true,
                    //bodyPadding: '5 5 5 5',
                    id: "warehouse_RequestFormId",
                    border: false,
                    frame: true,
                    autoHeight: true,
                    layout:'anchor',
                    items:
                    [
                    	{
                    		xtype : 'panel',
				            collapsible: false,
			                region:'center',
			                anchor:'100%',
			                //margins:'5 0 5 5',
			                split:true,
			                //width: 325,
			                //layout:'accordion',
			                layout: {
						        // layout-specific configs go here
						        type: 'accordion',
						        titleCollapse: true,
						        animate: true,
						        activeOnTop: false
						    },
			                items: 
			                [
			                	{
		                    		split:true,
			                 		//title:'Данные',
			                 		title:routes_LogistMobile.data,
								    layout: 
								    {
				                        type: 'table',
				                        columns: 2
				                        //align: 'stretch'
				                    },
				                    defaults: {
				                        //fileUpload: true,
				                        //labelAlign: 'left',
				                        labelWidth: 120,
				                        msgTarget: 'side',
				                        margin: '5 5 5 5',
				                        width: 350,
				                    },
								    items:
								    [
				                        {
				                            xtype: 'textfield',
				                            fieldLabel: request_toir.name,
				                            name: 'Name',
				                            allowBlank: false
				                        },
				                        {
				                            xtype: 'textfield',
				                            fieldLabel: request_toir.code,
				                            name : 'Code',
											allowBlank: false,
				                        },
										{
				                            xtype: 'textfield',
				                            //fieldLabel: 'Адрес',
				                            fieldLabel: request_toir.address,
				                            allowBlank: false,
											id:'warehouselocationField',
				                            name: 'OriginalAddress',
											emptyText: ' ',
				                        },
				                        {
				                            xtype: 'timefield',
				                            name: 'StartTime',
				                            //fieldLabel: 'Начало работ',
				                            fieldLabel: request_toir.beginning_of_work,
				                            format:'H:i',
				                            minValue: '00:00',
				                            maxValue: '23:45',
				                            increment: 15,
				                            anchor: '100%',
				                            allowBlank:false,
											editable: false,
											id: 'warehouseStartTime',
											value: '08:00',
											listeners:
											{
												select: function( combo, record, eOpts )
												{
													var val_StarTime = combo.getValue();
													var Cmp_EndTime = Ext.getCmp('warehouseEndTime');
													Cmp_EndTime.setValue(val_StarTime);
													Cmp_EndTime.setMinValue(val_StarTime);
												}
											}
				                        },
				                        {
				                            xtype: 'timefield',
				                            name: 'EndTime',
				                            //fieldLabel: 'Конец работ',
				                            fieldLabel: request_toir.end_of_works,
				                            format:'H:i',
				                            minValue: '00:00',
				                            maxValue: '23:45',
				                            increment: 15,
				                            anchor: '100%',
				                            allowBlank:false,
											editable: false,
											id: 'warehouseEndTime',
											value: '15:00'
				                        }, 
				                        {
				                            xtype: 'textfield',
				                            fieldLabel: 'GeoX',
				                            allowBlank: false,
				                            name: 'GeoX',
											id: 'Geo_X',
				                        },
				                        {
				                            xtype: 'textfield',
				                            fieldLabel: 'GeoY',
				                            allowBlank: false,
				                            name: 'GeoY',
				                            id: 'Geo_Y',
				                        }
								    ]
								},
								{
								     layout: 'fit',
					                 split:true,
					                 //title:'Указать на карте',
					                 title:routes_LogistMobile.point_to_map,
					                 items:	[PanelMapForCenter],
					                 listeners:{
					                 	expand:function( p, eOpts) {
					                 		PanelMapForCenter.clickOnMapRequest();
					                 	},
					                 }
								} 
			                ]
                    	}
                    ],
                    buttons:[
                    {
                        //text:'Cохранить',
                        text: all_toir.save,
                        iconCls:'save',
                        handler: function() {
                            var form = this.up('form').getForm();
                            if(form.isValid()){
									
									check_code_warehouse(form.findField("Code").getValue(),form,id);
									
							}
                        }
                    },
                    {
                        text: all_toir.cancel,
                        iconCls:'cancel',
                        handler: function(){
                            LogistMobile_warehouse_app_WindowAddEdit.destroy();
                        }
                    }
                ]
                }
            ]
        });
    }
    LogistMobile_warehouse_app_WindowAddEdit.show();
    var form = Ext.getCmp("warehouse_RequestFormId").getForm();
    if (id) {
		form.findField("OriginalAddress").setValue( records.get('Address') );
		form.findField("Code").setValue( records.get('Code') );
		form.findField("Name").setValue( records.get('Name') );
		form.findField("GeoX").setValue( records.get('GeoX') );
		form.findField("GeoY").setValue( records.get('GeoY') );
		
		form.findField("StartTime").setValue( records.get('StartServeTime') );
		form.findField("EndTime").setValue( records.get('EndServeTime') );
    }
}
/* ----------------- new order for post --------------------------------- */


function check_code_warehouse(code,form,id){
	
	if(id){
		
		warehouse_submit(form,id);
		
	}else{
	
	Ext.Ajax.request({
        url: 'app/LogistMobile_WarehouseToUsers.php',
        method: 'POST',
		scope: this,
        params: { 'checkcodewarehouse':true, "code":code },
        success: function(response) {
			var obj = Ext.decode(response.responseText);
				if(obj.success == true){
					if(obj.message==1){
						Ext.MessageBox.alert(all_toir.error, 'Склад с таким кодом уже существует');
					}else{
						warehouse_submit(form,id);
					}
				}else{
					Ext.MessageBox.alert(all_toir.error, obj.message);
				}
        },
        failure: function(response) {
                Ext.MessageBox.alert(all_toir.error, response.responseText);
        }
    });
	
	}
}

function warehouse_submit(form,id){
									form.submit({
                                    waitMsg: all_toir.loading,
                                    url: 'app/LogistMobile_WarehouseToUsers.php',
                                    wait: true,
                                    scope: this,
                                    method: 'post',
                                    params: {'addeditwarehouse':true,id:id},
                                    success: function(fp, o){
									if(o.result.success == true){
										LogistMobile_warehouse_app_WindowAddEdit.destroy();
										store_grid_warehouse_users.load();
										Ext.getCmp('itemselector_warehouse_users').store.removeAll();
										Ext.getCmp('itemselector_warehouse_users').store.load();
									}else{
										Ext.MessageBox.alert(all_toir.error, o.result.message);
									}
                                    },
                                    failure: function(fp, o){
										Ext.MessageBox.alert(all_toir.error, o.result.message);
									}
									});
}