var VTopOffset = 65; // отместване отгоре
if (Ext.isIE) { VTopOffset += 10 };
var VHX = 0;		// Хартия - Х
var VHY = 0;		// Хартия - У
var VHGRAM = 0;		// Хартия - Грамаж
var VHDEB = 0;		// Хартия - Дебелина
var VHCENA = 0;		// Хартия - Цена
var VUID = 0;
var VUNAME  = 'ГОСТ';
var VUFIRMA = '';
var VPORNO = 0;
var webroot = ""; 
var VRAZ = 0;
var VML = 0;
var CODE = 0;

Ext.OperGrid = Ext.extend(Ext.grid.GridPanel, {
	NewRecord: null,
	initComponent : function() {
		Ext.apply(this, {
			columns: [
				{id:'id',header: 'No', width: 40, sortable: false, dataIndex: 'oid', fixed: true},
				{header: 'Описание на операцията', width: 214, sortable: false, dataIndex: 'oime', fixed: true}
	        ],
			selModel: new Ext.grid.RowSelectionModel({ singleSelect: true }),
			autoShow : true,
			enableHdMenu: false,
			store: new Ext.data.Store({
				storeId: 'OperGridStore',
				autoDestroy: true,
				reader: new Ext.data.ArrayReader({ fields: [ {name:'oid', type: 'float'},'oime','otip','opodg','omak','ocena' ] }),
				remoteSort: false 
			}),
			tbar: new Ext.Toolbar({
					items: [
//						{ xtype: 'tbtext', text: 'Операция: ' },						
						new Ext.form.ComboBox({
							forceSelection: true, triggerAction: 'all', selectOnFocus:true, typeAhead: true, lazyRender:true,
							mode: 'local', fieldLabel: 'Операция ', emptyText: 'Изберете операция', editable: false, id: 'OPCBID',
							store: new Ext.data.JsonStore({
								storeId: 'DOPStore',
								autoDestroy: true,
								method:'GET',
								url : webroot + "/calc/modules/get_data.php?type=getdopdata",
								root: 'data', 
								fields: [ 'oid','oime','otip','opodg','omak','ocena' ],
								idIndex: 0,
								sortInfo: {field: 'oime', direction: 'ASC'}
							}), 
							listeners:{
								scope: this,
								'select': function( combo, record, index ) {
												OperGrid.NewRecord = record;
												Ext.StoreMgr.get('OperGridStore').add(OperGrid.NewRecord);
												CalcForm.CalcProc(); 
											}
							},
							valueField: 'oid',
							displayField: 'oime',
							width: 160
						}),{
						  xtype: 'button',
						  text: 'Изтрий операция',
						  tooltip: 'Изтриване на маркираната операция', 
						  tooltipType: 'title',
						  handler: this.dropoper,
						  icon: webroot + '/calc/delete.png'
						}
					]
			})	
			
		}); 
		Ext.OperGrid.superclass.initComponent.call(this);
	},
	dropoper: function() {
		if (!Ext.getCmp('opergrid-panel').getSelectionModel().hasSelection()) {
			Ext.Msg.alert('ВНИМАНИЕ', 'Първо маркирайте операцията, която желаете да изтриете !');
		} else {
			Ext.StoreMgr.get('OperGridStore').remove(Ext.getCmp('opergrid-panel').getSelectionModel().getSelected()); 
			CalcForm.CalcProc();								
		}
	}
});
Ext.reg('OperGrid', Ext.OperGrid);
var OperGrid = new Ext.OperGrid;

Ext.LoginForm = Ext.extend(Ext.form.FormPanel, {
    initComponent:function() {
        Ext.apply(this, {
			url:'calc/modules/main.php?type=login',  // URL za proverka na imeto i parolata
			frame:true,
			width: 300,
			buttonAlign: 'right',
			layout: 'absolute', 
			defaults: {
				allowBlank: false,
				selectOnFocus: true,
				msgTarget: 'side'
			},
			items:[{
				xtype: 'hidden',name: 'type', value: 'login'
			},{
				xtype:'label', x: 10, y: 15, text: 'e-mail :'
			},{
				x: 60, y: 5,
				xtype: 'textfield',  // potrebitelskoto ime
				name:  'username',
				id: 'usernameID',
				fieldLabel:'e-mail ',
				blankText: 'Потребителя е задължителен',
				width: 200
			},{
				xtype:'label', x: 10, y: 60, text: 'Парола :'
			},{
				x: 60, y: 50,
				xtype: 'textfield', // parolata
				name:  'password',
				id:  'passwordID',
				fieldLabel:'Парола ',
				inputType: 'password',
				blankText: 'Паролата е задължителена',
				width: 200
			}], 
			buttons:[{
				text:'Вход',
				formBind: true,
				handler:function(){
					if(LoginForm.getForm().isValid()){
						Ext.Ajax.request({
							url:'calc/modules/main.php?type=logina',  // URL za proverka na imeto i parolata
							method: 'POST', 
							params : { 
								username: Ext.getCmp('usernameID').getValue(),
								password: Ext.getCmp('passwordID').getValue(),
								code: CODE,
								type: 'logina'
							},
							success: function(objServerResponse){
								var obj = Ext.decode(objServerResponse.responseText);
								if (obj.success == 'true') { 
									LoginWin.hide();
									Ext.getCmp('LUSERNAME').setText('Потребител: '+obj.name);
									VUID 	= obj.id;
									VUNAME  = obj.name;
									VUFIRMA = obj.firma;
									Ext.getCmp('adresID').setValue(obj.adresd); 
									Ext.getCmp('contactID').setValue(obj.kontakt);
									Ext.getCmp('phoneID').setValue(obj.phone);
									Ext.getCmp('mailID').setValue(obj.email);
								} else {
									Ext.Msg.alert('Съобщение', 'Въвели сте грешно потребителско име или парола !');
								}
							},
							failure : function(objServerResponse){ 
								Ext.Msg.alert('Съобщение', 'Достъп до сървъра отказан !');
							}
						});
					}
				}
			}]
		});
        Ext.LoginForm.superclass.initComponent.apply(this, arguments);
    }
});
Ext.reg('LoginForm', Ext.LoginForm); 
var LoginForm = new Ext.LoginForm;

Ext.LoginWin = Ext.extend(Ext.Window, {
    initComponent:function() {
        Ext.apply(this, {
			id: 'LoginWin',
			itemId: 'LoginWin',
			title:'Fastprint Калкулатор',
			layout:'fit',
			width:300,
			height: 170,
			AutoHeight:true,
			closable: true,
            closeAction:'hide',
			resizable: false,
			border: false,
			modal: true,
			bodyStyle:'padding:5px',
			html:'<img style="margin-top:95px; margin-left:310px; position:absolute;" src="login.png"/>',
			items: LoginForm
		});
        Ext.LoginWin.superclass.initComponent.apply(this, arguments);
    } 
});
Ext.reg('LoginWin', Ext.LoginWin);
var LoginWin = new Ext.LoginWin;

Ext.EmailForm = Ext.extend(Ext.form.FormPanel, {
	initComponent:function() {
        Ext.apply(this, {
			frame:true,
			width: 300,
			buttonAlign: 'right',
			layout: 'absolute', 
			defaults: {
				allowBlank: false,
				selectOnFocus: true,
				msgTarget: 'side'
			},
			items:[{
				xtype: 'hidden',name: 'type', value: 'register'
			},{
				xtype:'label', x: 10, y: 15, text: 'e-mail :'
			},{
				x: 60, y: 5,
				xtype: 'textfield',  // potrebitelskoto ime
				name:  'username',
				id: 'emailID',
				fieldLabel:'e-mail ',
				blankText: 'Потребителя е задължителен',
				width: 200
			}], 
			buttons:[{
				text:'Продължи',
				formBind: true,
				handler:function(){
					if(EmailForm.getForm().isValid()){
						Ext.Ajax.request({
							url: "calc/modules/main.php?type=register",
							method: 'POST', 
							params : { 
								username: Ext.getCmp('emailID').getValue(),
								code: CODE,
								type: 'register'
							},
							success: function(objServerResponse){
								var obj = Ext.decode(objServerResponse.responseText);
								if (obj.success == 'true') { 
									EmailWin.hide();
									Ext.Msg.alert('Съобщение', obj.name);
								} else {
									Ext.Msg.alert('Грешка', obj.name);
								}
							},
							failure : function(objServerResponse){ 
								Ext.Msg.alert('Грешка', 'Достъп до сървъра отказан !');
							}
						});
					}
				}
			}]
		});
        Ext.EmailForm.superclass.initComponent.apply(this, arguments);
    }
});
Ext.reg('EmailForm', Ext.EmailForm); 
var EmailForm = new Ext.EmailForm;

Ext.EmailWin = Ext.extend(Ext.Window, {
    initComponent:function() {
        Ext.apply(this, {
			id: 'EmailWin',
			itemId: 'EmailWin',
			title:'Fastprint Регистрация',
			layout:'fit',
			width:300,
			height: 170,
			AutoHeight:true,
			closable: true,
            closeAction:'hide',
			resizable: false,
			border: false,
			modal: true,
			bodyStyle:'padding:5px',
			html:'<img style="margin-top:95px; margin-left:310px; position:absolute;" src="login.png"/>',
			items: EmailForm
		});
        Ext.EmailWin.superclass.initComponent.apply(this, arguments);
    } 
});
Ext.reg('EmailWin', Ext.EmailWin);
var EmailWin = new Ext.EmailWin;

Ext.FPForm = Ext.extend(Ext.form.FormPanel, {
	initComponent:function() {
        Ext.apply(this, {
			frame:true,
			width: 300,
			buttonAlign: 'right',
			layout: 'absolute', 
			defaults: {
				allowBlank: false,
				selectOnFocus: true,
				msgTarget: 'side'
			},
			items:[{
				xtype: 'hidden',name: 'type', value: 'fp'
			},{
				xtype:'label', x: 10, y: 15, text: 'e-mail :'
			},{
				x: 60, y: 5,
				xtype: 'textfield',  // potrebitelskoto ime
				name:  'fp',
				id: 'fpID',
				fieldLabel:'e-mail ',
				blankText: 'Потребителя е задължителен',
				width: 200
			}], 
			buttons:[{
				text:'Продължи',
				formBind: true,
				handler:function(){
					if(FPForm.getForm().isValid()){
						Ext.Ajax.request({
							url: "calc/modules/main.php?type=fp",
							method: 'POST', 
							params : { 
								username: Ext.getCmp('fpID').getValue(),
								code: CODE,
								type: 'fp'
							},
							success: function(objServerResponse){
								var obj = Ext.decode(objServerResponse.responseText);
								if (obj.success == 'true') { 
									FPWin.hide();
									Ext.Msg.alert('Съобщение', obj.name);
								} else {
									Ext.Msg.alert('Грешка', obj.name);
								}
							},
							failure : function(objServerResponse){ 
								Ext.Msg.alert('Грешка', 'Достъп до сървъра отказан !');
							}
						});
					}
				}
			}]
		});
        Ext.FPForm.superclass.initComponent.apply(this, arguments);
    }
});
Ext.reg('FPForm', Ext.FPForm); 
var FPForm = new Ext.FPForm;

Ext.FPWin = Ext.extend(Ext.Window, {
    initComponent:function() {
        Ext.apply(this, {
			id: 'FPWin',
			itemId: 'FPWin',
			title:'Fastprint Забравена парола',
			layout:'fit',
			width:300,
			height: 170,
			AutoHeight:true,
			closable: true,
            closeAction:'hide',
			resizable: false,
			border: false,
			modal: true,
			bodyStyle:'padding:5px',
			html:'<img style="margin-top:95px; margin-left:310px; position:absolute;" src="login.png"/>',
			items: FPForm
		});
        Ext.FPWin.superclass.initComponent.apply(this, arguments);
    } 
});
Ext.reg('FPWin', Ext.FPWin);
var FPWin = new Ext.FPWin;

Ext.FilesGrid = Ext.extend(Ext.grid.GridPanel, {
     ds : new Ext.data.JsonStore({
			url: webroot + "/calc/modules/get_data.php?type=getfiles",
            method: 'POST',
//            baseParams:{por_id: VPORNO},
            root: 'data',
            fields: [ 'id','orig_name','size','por_id' ],
       	    sortInfo: {field: 'filename', direction: 'ASC'},
        	remoteSort: true
     }),
     initComponent:function() {
		Ext.apply(this, {
           ds: this.ds ,
//		   id: 'FilesGridID',
//		   itemId: 'FilesGrid',  
           columns: [
                  { header:"id",id:"id",width:10,dataIndex:'id',hidden:true,sortable:true},
                  {header: "Прикачени Файлове", width: 170, sortable: true, dataIndex: 'orig_name'},
                  {header: "Големина", width: 60, sortable: true, dataIndex: 'size'}
           ],
           sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
 		   enableHdMenu: false,
     	   enableColLock: false,
           autoScroll: true,
           autoShow : true,
	       loadMask: true,
           trackMouseOver: true,
//           width: "100%",
           tbar:[
                {
                     id:'firmkl-files-new',
                     text:'Добави файлове',
                     tooltip:'Добавете файлове с размер не по-голям от 32 МБ. За по големи файлове използвайте FTP достъпа в "Контакти"',
                     icon: 'calc/3.png',
                     handler: this.do_upload,
                     scope:this
                },'-',{
                     id:'firmkl-files-delete',
                     text:'Изтрий',
                     tooltip:'Изтриване на избрания файл',
                     icon:'calc/delete.png' ,
                     handler: this.delete_row,
                     scope:this
                }
           ]
        });
       Ext.FilesGrid.superclass.initComponent.apply(this, arguments);
     },
     initEvents: function() {
       Ext.FilesGrid.superclass.initEvents.call(this);
     },
     onRender:function() {
       Ext.FilesGrid.superclass.onRender.apply(this, arguments);
       this.ds.load({params:{por_id: VPORNO, code: CODE}});
     },
     do_upload:function() {
		var upload_dialog = new Ext.ux.UploadDialog.Dialog({
			title: 'Прикачи файлове',
			url: webroot + "/calc/modules/upload.php",   
			base_params: { type: "upload", por_id: VPORNO, user_id: VUID, code: CODE},
			permitted_extensions: ["CDR","cdr","TIF","tif","JPG","jpg","JPEG","jpeg","PS","ps","EPS","eps","PSD","psd","PDF","pdf"],
			reset_on_hide: false,
			allow_close_on_upload: false
		});
		upload_dialog.show('upload_button');
		upload_dialog.on("uploadcomplete", function() {
            FilesGrid.ds.load({params:{por_id: VPORNO, code: CODE}});
		});
	    upload_dialog.on("hide", function() {
			this.destroy(true);
    	});
    },
     delete_row: function() {
		if (!this.getSelectionModel().hasSelection()) {
			Ext.Msg.alert('ВНИМАНИЕ', 'Първо маркирайте файла, който желаете да изтриете !');
		} else {
			var SelectedRec = this.getSelectionModel().getSelected();
            Ext.MessageBox.show({
               title:'ВНИМАНИЕ',
               msg: 'Желаете ли да изтриете файл '+SelectedRec.data.orig_name+' ?',
               buttons: Ext.MessageBox.YESNO,
               icon: Ext.MessageBox.QUESTION,
               scope:this,
               fn: function(button){
					if(button=='yes'){
						Ext.Ajax.request({
							url: "calc/modules/get_data.php",
							method: 'POST',
							params : { type: 'fdel', id: SelectedRec.data.id, por_id: SelectedRec.data.por_id, code: CODE },
							success: function(objServerResponse){
								var obj = Ext.decode(objServerResponse.responseText);
								if (obj.success = "true") { 
									FilesGrid.ds.load({params:{por_id: VPORNO, code: CODE}});
								} else {  
									Ext.Msg.alert('Съобщение', 'Достъп до сървара отказан !');
								}
							},
							failure : function(objServerResponse){ 
								Ext.Msg.alert('Съобщение', 'Достъп до сървара отказан !');
							}
						});
					}
				}
			});
		}
	}
});
Ext.reg("FilesGrid",Ext.FilesGrid);
var FilesGrid = new Ext.FilesGrid;

Ext.CalcForm = Ext.extend(Ext.form.FormPanel, {
    initComponent:function() {
        Ext.apply(this, {
			id: 'aForm',
			layout:'absolute',
			labelAlign: 'top',
			frame:true,
//			title: 'Калкулатор',
			width: 795, 
			height: 340,
			items: [
				{ 	xtype:'label', x: 10, y: 5, text: 'Изделие :'
			},
				new Ext.form.ComboBox({ 
					x: 10, y: 20,
					forceSelection: true, triggerAction: 'all', selectOnFocus:true, typeAhead: true, lazyRender:true,
					mode: 'local', emptyText: 'Изберете изделие', editable: false, id: 'IZDCBID',
					allowBlank: true,
					blankText: 'Това поле е задължително!',
					store: new Ext.data.JsonStore({
						storeId: 'IStore',
						autoDestroy: true,
						method:'GET',
						url : webroot + "/calc/modules/get_data.php?type=getidata",
						root: 'data', 
						fields: [ 'iid', 'iime', 'ix', 'iy'],
						idIndex: 0,
						sortInfo: {field: 'iime', direction: 'ASC'},
						remoteSort: false 
					}), 
					listeners:{
						scope: this,
						'select': function( combo, record, index ) {
										CalcForm.getForm().setValues({IZDIME: record.data.iime, IX: record.data.ix, IY: record.data.iy});
									}
					},
					valueField: 'iime',
					displayField: 'iime',
					width: 300
				})
			,{ 
				x: 10, y: 20,
				xtype:'textfield',
				id: 'IZDIMEID',
				name: 'IZDIME',
				allowBlank: false,
				emptyText: 'Въведете име или изберете от списъка',
				blankText: 'Това поле е задължително!',
				width: 283
			},{
				xtype:'label', text: 'X /см/ :', x: 330, y: 5
			},{
				x: 330, y: 20,
				xtype:'numberfield',
				id: 'IXID',
				name: 'IX',
				style: 'text-align:right',
				allowBlank: false,
				blankText: 'Това поле е задължително!',
				width: 60
			},{	
				xtype:'label', text: 'Y /см/ :', x: 400, y: 5 
			},{
				x: 400, y: 20,
				xtype:'numberfield',
				id: 'IYID',
				name: 'IY',
				style: 'text-align:right',
				allowBlank: false,
				blankText: 'Това поле е задължително!',
				width: 60
			},{
				xtype:'label', html: 'Тираж :', x: 470, y: 5
			},{
				x: 470, y: 20,
				xtype:'numberfield',
				id: 'tirajid',
				name: 'Tiraj',
				style: 'text-align:right',
				allowBlank: false,
				minValue: 1,
				blankText: 'Това поле е задължително!',
				width: 60
			},{
				xtype:'label', html: 'Хартия :', x: 10, y: 50
			},
				new Ext.form.ComboBox({
					x: 10, y: 65,
					forceSelection: true, triggerAction: 'all', selectOnFocus:true, typeAhead: true, lazyRender:true,
					mode: 'local', fieldLabel: '* Хартия ', emptyText: 'Изберете тип хартия', editable: false, id: 'HID',
					allowBlank: false,
					blankText: 'Това поле е задължително!',
					store: new Ext.data.JsonStore({
						storeId: 'HStore',
						autoDestroy: true,
						method:'GET',
						url : webroot + "/calc/modules/get_data.php?type=gethdata",
						root: 'data', 
						fields: [ 'hid', 'hime', 'hx', 'hy', 'hdeb', 'hgram', 'hcena' ],
						idIndex: 0,
						sortInfo: {field: 'hime', direction: 'ASC'},
						remoteSort: false 
					}), 
					listeners:{
						scope: this,
						'select': function( combo, record, index ) {
										CalcForm.getForm().setValues({gram: record.data.hgram, deb: record.data.hdeb});
										VHX = record.data.hx; VHY = record.data.hy;
										VHGRAM = record.data.hgram; VHDEB = record.data.hdeb; VHCENA = roundNumber(record.data.hcena,4);
									}
					},
					valueField: 'hime',
					displayField: 'hime',
					width: 300
				})
			,{
				xtype:'label', html: 'Цветност :', x: 330, y: 50
			},{
				x: 330, y: 65,
				xtype:'numberfield',
				hideLabel: true,
				id: 'CW1ID',
				name: 'CW1',
				style: 'text-align:center',
				allowBlank: false,
				blankText: 'Това поле е задължително!',
				width: 35,
				listeners:{
					scope: this,
					'change': this.SetWurt
				}				
			},{
				xtype:'label', text: '+', x: 366, y: 70
			},{
				x: 375, y: 65,
				xtype:'numberfield',
				hideLabel: true,
				id: 'CW2ID',
				name: 'CW2',
				style: 'text-align:center',
				allowBlank: false,
				blankText: 'Това поле е задължително!',
				width: 35,
				listeners:{
					scope: this,
					'change': this.SetWurt
				}				
			},{
				xtype:'label', html: 'Въртене :', x: 430, y: 50
			},
				new Ext.form.ComboBox({
					x: 430, y: 65,
					forceSelection: true, triggerAction: 'all', selectOnFocus:true, typeAhead: true, lazyRender:true,
					mode: 'local', fieldLabel: 'Въртене ', emptyText: 'Изберете', editable: false, id: 'WURTID', allowBlank: false,
					store: new Ext.data.Store({
						data: [ {"wurtId": "1","displayText":"ДА"},{"wurtId": "2","displayText":"НЕ"}],	
						storeId: 'wurtStore',
						reader: new Ext.data.JsonReader({ fields: [ 'wurtId', 'displayText'] })
					}),
					valueField: 'wurtId',
					displayField: 'displayText',
					width: 100
				})
			,{
				xtype:'label', text: 'Допълнителни операции :', x: 10, y: 95
			},{
				x: 10, y: 110,
				xtype:'OperGrid',
				id: 'opergrid-panel',
				height: 170, 
				width: 300,
				frame: true
			},{
				xtype:'label', id: 'LEDCENAID', text: 'Ед. цена :', x: 330, y: 120
			},{
				x: 390, y: 110,
				xtype:'numberfield',
				allowDecimals: true,
				decimalPrecision: 6,
				id: 'NEDCENAID',
				name: 'NEDCENA',
				style: 'text-align:right',
				width: 70,
				readOnly: true
			},{
				xtype:'label', id: 'LSTOJNID', text: 'Стойност :', x: 330, y: 155
			},{
				x: 390, y: 145,
				xtype:'numberfield',
				allowDecimals: true,
				decimalPrecision: 2,
				id: 'NSTOJNID',
				name: 'NSTOJN',
				style: 'text-align:right',
				width: 70,
				readOnly: true
			},{
				xtype:'label', id: 'LDDSID', text: 'ДДС 20% :', x: 330, y: 190
			},{
				x: 390, y:180,
				xtype:'numberfield',
				allowDecimals: true,
				decimalPrecision: 2,
				id: 'NDDSID',
				name: 'NDDS',
				style: 'text-align:right',
				width: 70,
				readOnly: true
			},{
				xtype:'label', id: 'LSUMAOID', text: 'Сума :', x: 330, y: 225
			},{
				x: 390, y: 215,
				xtype:'numberfield',
				allowDecimals: true,
				decimalPrecision: 2,
				id: 'NSUMAOID',
				name: 'NSUMAO',
				style: 'text-align:right',
				width: 70,
				readOnly: true
			},{
				x: 460, y: 110,
				xtype:'numberfield',
				allowDecimals: true,
				decimalPrecision: 6,
				id: 'EDCENAID',
				name: 'EDCENA',
				style: 'text-align:right',
				width: 70,
				readOnly: true
			},{
				x: 460, y: 145,
				xtype:'numberfield',
				allowDecimals: true,
				decimalPrecision: 2,
				id: 'STOJNID',
				name: 'STOJN',
				style: 'text-align:right',
				width: 70,
				readOnly: true
			},{
				x: 460, y:180,
				xtype:'numberfield',
				allowDecimals: true,
				decimalPrecision: 2,
				id: 'DDSID',
				name: 'DDS',
				style: 'text-align:right',
				width: 70,
				readOnly: true
			},{
				x: 460, y: 215,
				xtype:'numberfield',
				allowDecimals: true,
				decimalPrecision: 2,
				id: 'SUMAOID',
				name: 'SUMAO',
				style: 'text-align:right',
				width: 70,
				readOnly: true
				
				
            },{
				x: 330, y: 250,
				id: 'CalcBtn',
				xtype:'button',
                text: 'Калкулирай цена',
				icon: webroot + 'calc/1.gif',
				height: 30, 
				width: 130,
				handler: function() { 
					CalcForm.CalcProc();
				} 
			},{
				xtype:'label', id: 'LRAZTEXT', text: '', x: 10, y: 283
			},{
				xtype:'label', id: 'LUSERNAME', text: 'Потребител: ГОСТ', x: 543, y: 4, cls:'x-form-user-label'
			},{
				x: 543, y: 20,
				xtype:'panel',
				height: 300, 
				width: 240,
				closable: true,
//				title: 'Помощна информация',
				itemId: 'help-panel', 
				html: '<p>&nbsp</p><p align="center"><b>Помощна Информация</b></p><p>=> Ако сте рекламна агенция моля регистрирайте се и използвайте входа за регистрирани потребители.</p><p>=> Ако не сте рекламна агенция можете да калкулирате цена и да пуснете поръчка без регистрация.</p><p>=> Използвайте опцията въртене, когато имате двустранен печат /например 4+4цв/ и в машинен лист се събират четен брой изделия, това ще доведе до по ниска цена. Ако цветността Ви е 1+0цв, 2+0цв, 3+0цв или 4+0цв опцията въртене няма значение.</p>'				
			}],
			tbar: [ 
				'->', 
				{	
					text:'Регистрация за рекламни агенции',
					icon: webroot + '/calc/ext303/resources/images/default/grid/hmenu-unlock.png',
					handler: function() { 
						CalcForm.Register();
					} 
				},{
					text:'Забравена парола',
					icon: 'calc/pass.gif',
					handler: function() { 
						CalcForm.FP();
					} 
				},{
				 
					xtype: 'button', 
					text: 'Вход за рекламни агенции', 
					icon: webroot + '/calc/group_key.png',
					handler: function() { 
						CalcForm.Login();
					} 
				}    
			]
		}); // eo apply
        Ext.CalcForm.superclass.initComponent.apply(this, arguments);
	}, 
	SetWurt: function() {
		if ((Ext.getCmp('CW1ID').getValue()==0)||(Ext.getCmp('CW2ID').getValue()==0)) {
			Ext.getCmp('WURTID').setValue("НЕ"); 
			Ext.getCmp('WURTID').disable(); 
		} else { 
			Ext.getCmp('WURTID').setValue(""); 
			Ext.getCmp('WURTID').enable(); 
		};
	}, 
	FP: function() {
		FPForm.getForm().reset();
        FPWin.show();		
	}, 
	Register: function() {
		EmailForm.getForm().reset();
        EmailWin.show();		
	}, 
	Login: function() {
		LoginForm.getForm().reset();
        LoginWin.show();		
	}, 
	GetDop: function() {
		var resData = '';
		Ext.StoreMgr.get('OperGridStore').queryBy( function(record, id) {
			resData = resData + record.data.oime + '; ';  
		});
		return (resData);  
	},
	CalcProc: function() {
		if (CalcForm.getForm().isValid()) {
	
		var JSONDOP = ''; 
		Ext.StoreMgr.get('OperGridStore').queryBy( function(record, id) {
			if (JSONDOP.length!=0) {JSONDOP=JSONDOP+' OR '};
			JSONDOP = JSONDOP + "oid= "+record.data.oid;
		});
		Ext.Ajax.request({
			url : webroot + "/calc/modules/get_data.php?type=calc",
			method: 'POST',
			params : { 
				TIRAJ: Ext.getCmp('tirajid').getValue(),
				CW1: Ext.getCmp('CW1ID').getValue(),
				CW2: Ext.getCmp('CW2ID').getValue(),
				WURT: Ext.getCmp('WURTID').getValue(),
				VDOPA: JSONDOP, 
				HIME: Ext.getCmp('HID').getValue(),
				HX: VHX,
				HY: VHY,
				HGRAM: VHGRAM,
				HDEB: VHDEB,
				HCENA: VHCENA,
				IZDIME: Ext.getCmp('IZDIMEID').getValue(),
				IX: Ext.getCmp('IXID').getValue(),
				IY: Ext.getCmp('IYID').getValue(),
				code: CODE
			},
			success: function(objServerResponse){
				var obj = Ext.decode(objServerResponse.responseText);
				if (obj.success == "true") { 
					Ext.getCmp('NSTOJNID').setValue(obj.data.NSTOJN);
					Ext.getCmp('NDDSID').setValue(obj.data.NDDS);
					Ext.getCmp('NSUMAOID').setValue(obj.data.NSUMA);
					Ext.getCmp('NEDCENAID').setValue(obj.data.NCENA); 
					Ext.getCmp('STOJNID').setValue(obj.data.STOJN);
					Ext.getCmp('DDSID').setValue(obj.data.DDS);
					Ext.getCmp('SUMAOID').setValue(obj.data.SUMA);
					Ext.getCmp('EDCENAID').setValue(obj.data.CENA); 

					VRAZ = obj.data.RAZ;
					VML  = obj.data.MLO;
					Ext.getCmp('LRAZTEXT').setText('Разкрой по '+obj.data.RAZ+' броя изделия '+Ext.getCmp('IXID').getValue()+'x'+Ext.getCmp('IYID').getValue()+' см в машинен лист с печатаемо поле 33х45 см');
					Ext.getCmp('LEDCENAID').show();
					Ext.getCmp('LSTOJNID').show();
					Ext.getCmp('LDDSID').show();
					Ext.getCmp('LSUMAOID').show();
					if (VUID == 0) {	
						Ext.getCmp('EDCENAID').hide();
						Ext.getCmp('STOJNID').hide();
						Ext.getCmp('DDSID').hide();
						Ext.getCmp('SUMAOID').hide();
						Ext.getCmp('NEDCENAID').show();
						Ext.getCmp('NSTOJNID').show();
						Ext.getCmp('NDDSID').show();
						Ext.getCmp('NSUMAOID').show();
					} else {
						Ext.getCmp('NEDCENAID').hide();
						Ext.getCmp('NSTOJNID').hide();
						Ext.getCmp('NDDSID').hide();
						Ext.getCmp('NSUMAOID').hide();
						Ext.getCmp('EDCENAID').show();
						Ext.getCmp('STOJNID').show();
						Ext.getCmp('DDSID').show();
						Ext.getCmp('SUMAOID').show();
					};
					PorForm.show();
					FilesGrid.hide(); 
				} else {
					Ext.Msg.alert('ГРЕШКА!', obj.data); 
				}
			},
			failure : function(objServerResponse){ 
				Ext.Msg.alert('Съобщение', 'Достъп до сървъра отказан !');
			}
		});
		} else {
			Ext.Msg.alert('Грешка', 'Не сте попълнили коректно всички необходими атрибути!');
		}
	}
});
Ext.reg('CalcForm', Ext.CalcForm); 
var CalcForm = new Ext.CalcForm;

Ext.PorForm = Ext.extend(Ext.form.FormPanel, {
    initComponent:function() {
        Ext.apply(this, {
			id: 'PorForm',
			layout:'absolute',
			labelAlign: 'top',
			frame:true,
			title: 'Поръчка',
			width: 795, 
			height: 240,
			items: [
			{
				xtype:'label', text: 'Доставка :', x: 10, y: 5
			},
				new Ext.form.ComboBox({
					x: 10, y: 20,
					forceSelection: true, triggerAction: 'all', selectOnFocus:true, typeAhead: true, lazyRender:true,
					mode: 'local', fieldLabel: '* Доставка ', emptyText: 'Изберете', editable: false, id: 'DOSTID',
					blankText: 'Това поле е задължително!',
					allowBlank: false,
					store: new Ext.data.Store({ 
						data: [ {"dId": "1","displayText":"По куриер"},{"dId": "2","displayText":"В печатницата"}],
						storeId: 'DStore',
						reader: new Ext.data.JsonReader({ fields: [ 'dId', 'displayText' ] })
					}),
					valueField: 'displayText',
					displayField: 'displayText',
					width: 135
				})
			,{
				xtype:'label', text: 'Адрес за доставка :', x: 150, y: 5
			},{
				x: 150, y: 20,
				xtype:'textfield',
				allowBlank: false,
				blankText: 'Това поле е задължително!',
				name: 'adres',
				id: 'adresID',
				width: 260
			},{
				xtype:'label', text: 'Плащане :', x: 10, y: 50
			},
				new Ext.form.ComboBox({
					x: 10, y: 65,
					forceSelection: true, triggerAction: 'all', selectOnFocus:true, typeAhead: true, lazyRender:true,
					mode: 'local', emptyText: 'Изберете', editable: false, id: 'PLID',
					blankText: 'Това поле е задължително!',
					allowBlank: false,
					store: new Ext.data.Store({ 
						data: [ {"plId": "1","displayText":"В брой"},{"plId": "2","displayText":"С наложен платеж"},{"plId": "3","displayText":"По банков път"}],
						storeId: 'PLStore',
						reader: new Ext.data.JsonReader({ fields: [ 'plId', 'displayText' ] })
					}),
					valueField: 'displayText',
					displayField: 'displayText',
					width: 135
				})
			,{
				xtype:'label', text: 'Лице за контакт :', x: 150, y: 50
			},{
				x: 150, y: 65,
				xtype:'textfield',
				allowBlank: false,
				blankText: 'Това поле е задължително!',
				name: 'contact',
				id: 'contactID',
				width: 260
			},{
				xtype:'label', text: 'Телефон :', x: 415, y: 5
			},{
				x: 415, y: 20,
				xtype:'textfield',
				allowBlank: false,
				blankText: 'Това поле е задължително!',
				name: 'phone',
				id: 'phoneID',
				width: 115					
			},{
				xtype:'label', text: 'e-mail :', x: 415, y: 50
			},{
				x: 415, y: 65,
				xtype:'textfield',
				allowBlank: false,
				blankText: 'Това поле е задължително!',
				invalidText: 'Невалидна стойност! пример: name@domain.com',
				name: 'mail',
				id: 'mailID',
				width: 115,
				regex: /^([\w\-\'\-]+)(\.[\w-\'\-]+)*@([\w\-]+\.){1,5}([A-Za-z]){2,4}$/, 
				fieldLabel:'e-mail '
			},{
				xtype:'label', text: 'Пояснителен текст :', x: 10, y: 95
			},{
				x: 10, y: 110,
				xtype:'textarea', 
				id:'text',
				height:50,
				width: 520
			},{
				id: 'LCT', xtype:'label', text: 'Код за достъп :', x: 10, y: 185
			},{
				x: 95, y: 175,
				xtype:'textfield',
				allowBlank: false,
				blankText: 'Това поле е задължително!',
				name: 'CODE',
				id: 'CODEID',
				width: 70
			},{
				xtype:'label', name: 'HCODE', id: 'HCODEID', x: 170, y: 185
			},{
				x: 330, y: 167,
				id: 'PorBtn',
				xtype:'button',
				text:'Изпрати поръчка',
				icon: webroot + '/calc/Gear.png',
				height:30,
				width: 120,
                handler: function(){
				if (Ext.getCmp('HCODEID').text != Ext.getCmp('CODEID').getValue()) {
						Ext.Msg.alert('Съобщение','Грешно въведен код за достъп!');
					} else {
					if (CalcForm.getForm().isValid() && PorForm.getForm().isValid() ) {
						var VEDCENA = 0; var VSTOJN = 0; var VDDS = 0; var VSUMA = 0;
						if (VUID == 0) {	
							VEDCENA = Ext.getCmp('NEDCENAID').getValue();
							VSTOJN  = Ext.getCmp('NSTOJNID').getValue();
							VDDS    = Ext.getCmp('NDDSID').getValue();
							VSUMA   = Ext.getCmp('NSUMAOID').getValue();
						} else {
							VEDCENA = Ext.getCmp('EDCENAID').getValue();
							VSTOJN  = Ext.getCmp('STOJNID').getValue();
							VDDS    = Ext.getCmp('DDSID').getValue();
							VSUMA   = Ext.getCmp('SUMAOID').getValue();
						};
						Ext.Ajax.request({
							url : webroot + "/calc/modules/send_data.php?type=send_data",
							method: 'POST', 
							params : { 
								user_id: VUID,
								user_name: VUNAME,
								user_firma: VUFIRMA,
								// изделие
								izdime: Ext.getCmp('IZDIMEID').getValue(),
								izdX: Ext.getCmp('IXID').getValue(),
								izdY: Ext.getCmp('IYID').getValue(),
								izdTiraj: Ext.getCmp('tirajid').getValue(),
								izdCW1: Ext.getCmp('CW1ID').getValue(),
								izdCW2: Ext.getCmp('CW2ID').getValue(),
								WURT: Ext.getCmp('WURTID').getValue(),
								// хартия
								hime: Ext.getCmp('HID').getValue(),
								razkroj: VRAZ,
								ml: VML,
							// допълнителни операции
								DOP: CalcForm.GetDop(),
								// опаковки и цени
								brop: 0,
								op: 0,
								tegloop: 0,
								edcena: VEDCENA,
								stojn: VSTOJN,
								dds: VDDS,
								suma: VSUMA,
								adres: Ext.getCmp('adresID').getValue(),  								
								contact: Ext.getCmp('contactID').getValue(),  		
								phone: Ext.getCmp('phoneID').getValue(),  		
								email: Ext.getCmp('mailID').getValue(),  		
								dost: Ext.getCmp('DOSTID').getValue(),  		
								pl: Ext.getCmp('PLID').getValue(),  		
								// пояснителен текст
								TEXT: Ext.getCmp('text').getValue(),
								code: CODE
							},
							success: function(objServerResponse){
								var obj = Ext.decode(objServerResponse.responseText);
								if (obj.success == 'true') { 
									VPORNO = obj.data.id;
									Ext.getCmp('LPORNOID').setText('Поръчка № '+VPORNO);
									Ext.getCmp('FilesGridID').show();
									Ext.getCmp('CalcBtn').hide();
									Ext.getCmp('LCT').hide();
									Ext.getCmp('CODEID').hide();
									Ext.getCmp('HCODEID').hide();
									Ext.getCmp('PorBtn').hide();
									Ext.Msg.alert('Съобщение', 'Вашата поръчка № '+VPORNO+' е изпратена успешно! Моля не забравяйте да добавите файловете си!');
									FilesGrid.ds.load({params:{por_id: VPORNO}});
								} else {
									Ext.Msg.alert('Съобщение', 'Достъп до сървъра отказан !');
								}
							},
							failure : function(objServerResponse){ 
								Ext.Msg.alert('Съобщение', 'Достъп до сървъра отказан !');
							}
						});
					} else { Ext.Msg.alert('Грешка', 'Не сте попълнили коректно всички необходими атрибути!'); }
					
					}
				}
			},{
				xtype:'label', id: 'LPORNOID', text: '', x: 543, y: 5, cls:'x-form-user-label'
			},{
				x: 543, y: 20,
   				xtype:'FilesGrid',
				id: 'FilesGridID', 
//				hidden: true,
				height:120, 
				width: 240		
			},{
				x: 680, y: 167,
				xtype:'button',
                text: 'Изход',
				height: 30, 
				width: 100,
				icon: webroot + '/calc/delete.png',
                handler: function(){ Ext.getCmp('CalcWin').hide(); }
			}]
		}); // eo apply
        Ext.PorForm.superclass.initComponent.apply(this, arguments);
    }
});
Ext.reg('PorForm', Ext.PorForm); 
var PorForm = new Ext.PorForm;

Ext.onReady(function(){
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';

	var myMask = new Ext.LoadMask(Ext.getBody(), {msg: "Моля изчакайте..."});
	Ext.Ajax.on('beforerequest', myMask.show, myMask);
	Ext.Ajax.on('requestcomplete', myMask.hide, myMask);
	Ext.Ajax.on('requestexception', myMask.hide, myMask);	
	
	Ext.Ajax.request({ 
		url: 'calc/modules/start.php',
		method : 'POST'
	});

    var CalcWin;
    var UsersBtn = Ext.get('Calc-link');
    UsersBtn.on('click', function(){
		myMask.show();
        if(!CalcWin){   
            CalcWin = new Ext.Window({
				id: 'CalcWin',
				itemId: 'CalcWin',
                applyTo:'calc-win',
                layout:'form',
				title: '<div align="center">FastPrint онлайн калкулатор</div>', 
                closeAction:'hide',
                plain: true,
				closable: true,
				resizable: false,
				border:false,
				modal: true,
				items: [ CalcForm, PorForm ],
				width: 807,
				height: 620,
				y: VTopOffset
            });
			Ext.StoreMgr.get('IStore').load();	
			Ext.StoreMgr.get('HStore').load();	
			Ext.StoreMgr.get('DOPStore').load();
        }
		Ext.Ajax.request({ 
			url: 'calc/modules/main.php?type=getcode',
			method : 'POST',
			params : { type: "getcode" },
			success: function(objServerResponse){
				var obj = Ext.decode(objServerResponse.responseText);
				if (obj.success == 'true') { 
					CODE = obj.code;
					Ext.getCmp('HCODEID').setText(CODE); 
				} else {
					Ext.Msg.alert('Съобщение', 'Достъп до сървъра отказан !');
				}
			},
			failure : function(objServerResponse){ 
				Ext.Msg.alert('Съобщение', 'Достъп до сървъра отказан !');
			}
		});
		Ext.getCmp('LEDCENAID').hide();
		Ext.getCmp('EDCENAID').hide();
		Ext.getCmp('LSTOJNID').hide();
		Ext.getCmp('STOJNID').hide();
		Ext.getCmp('LDDSID').hide();
		Ext.getCmp('DDSID').hide();
		Ext.getCmp('LSUMAOID').hide();
		Ext.getCmp('SUMAOID').hide();

		Ext.getCmp('NEDCENAID').hide();
		Ext.getCmp('NSTOJNID').hide();
		Ext.getCmp('NDDSID').hide();
		Ext.getCmp('NSUMAOID').hide();


		Ext.getCmp('FilesGridID').hide();
		Ext.getCmp('CalcBtn').show();
		Ext.getCmp('LCT').show();
		Ext.getCmp('CODEID').show();
		Ext.getCmp('HCODEID').show();
		Ext.getCmp('PorBtn').show();
		Ext.getCmp('LPORNOID').setText('');
		VPORNO = 0; 
		PorForm.hide();
        CalcWin.show(this);
		myMask.hide();
    });
});

function roundNumber(number,decimals) {
	var newString;// The new rounded number
	decimals = Number(decimals);
	if (decimals < 1) {
		newString = (Math.round(number)).toString();
	} else {
		var numString = number.toString();
		if (numString.lastIndexOf(".") == -1) {// If there is no decimal point
			numString += ".";// give it one at the end
		}
		var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number
		var d1 = Number(numString.substring(cutoff,cutoff+1));// The value of the last decimal place that we'll end up with
		var d2 = Number(numString.substring(cutoff+1,cutoff+2));// The next decimal, after the last one we want
		if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated
			if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point
				while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
					if (d1 != ".") {
						cutoff -= 1;
						d1 = Number(numString.substring(cutoff,cutoff+1));
					} else {
						cutoff -= 1;
					}
				}
			}
			d1 += 1;
		} 
		if (d1 == 10) {
			numString = numString.substring(0, numString.lastIndexOf("."));
			var roundedNum = Number(numString) + 1;
			newString = roundedNum.toString() + '.';
		} else {
			newString = numString.substring(0,cutoff) + d1.toString();
		}
	}
	if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
		newString += ".";
	}
	var decs = (newString.substring(newString.lastIndexOf(".")+1)).length;
	for(var i=0;i<decimals-decs;i++) newString += "0";
	return Number(newString); 
};
