﻿Ext.namespace('Ext.ux.plugins');
Ext.ux.plugins.Print = function(config){
    //Ext.apply(this, config);
};

Ext.extend(Ext.ux.plugins.Print, Ext.util.Observable, {
    dataView: function(options){
        var grid = this.component;
        var store = grid.getStore();
    },
    openExportWindow: function(){
    
        var param = this.component.selModel.selections.keys;
        var grid = this.component;
        
        
        if (param.length == 0) 
            Ext.MessageBox.alert('Item Check', "Please select 1 or more record to export ")
        else {
        
        
            //console.log(Component);
            //this.component = Component;
            //console.log(this.component.getColumnModel());
            var colmnModel = new Array();
            colmnModel[0] = {
                xtype: 'fieldset',
                title: 'Select Columns to Export',
                autoHeight: true,
                autoWidth: true,
                defaultType: 'textfield',
                items: new Array()
            };
            AddCustomerFormStoreCombo48cd33064ec8b = new Ext.data.SimpleStore({
                "fields": [{
                    "name": "name",
                    "mapping": "name"
                }, {
                    "name": "ID",
                    "mapping": "ID"
                }],
                "data": [{
                    "ID": "11",
                    "name": "Default"
                }]
            });
            
            colmnModel[1] = {
                xtype: 'fieldset',
                title: 'Select Type to Export',
                autoHeight: true,
                autoWidth: true,
                defaultType: 'radio',
                items: [                /*{
                 checked: true,
                 fieldLabel: 'Export format',
                 hideLabel: true,
                 boxLabel: 'PDF',
                 name: 'exportFormat',
                 inputValue: 'PDF'
                 
                 },  {
                 fieldLabel: '',
                 hideLabel: true,
                 labelSeparator: '',
                 boxLabel: 'XML',
                 name: 'exportFormat',
                 inputValue: 'XML'
                 },*/
                {
                    fieldLabel: '',
                    labelSeparator: '',
                    hideLabel: true,
                    boxLabel: 'CSV',
                    name: 'exportFormat',
                    inputValue: 'CSV',
                    checked: true
                }]
            };
            for (var i = 0, len = this.component.getColumnModel().config.length; i < len; i++) {
                // console.log(this.component.getColumnModel().config[i].dataIndex);
                colmnModel[0].items[i] = {
                    fieldLabel: this.component.getColumnModel().config[i].dataIndex,
                    name: this.component.getColumnModel().config[i].dataIndex,
                    xtype: "checkbox",
                    value: this.component.getColumnModel().config[i].dataIndex
                    //console.log(colmnModel);
                };
            }
            
            var AddEditableDropDowns = new Ext.FormWindow({
                "fieldList": colmnModel,
                "formUrl": "/index.php/page,Login",
                closable: true,
                
                maximizable: false,
                "title": "Export"
            });
            AddEditableDropDowns.btnCancel.hide();
            AddEditableDropDowns.btnReset.hide()
            AddEditableDropDowns.btnSave.hide()
            AddEditableDropDowns.btnSaveAndNew.hide()
            AddEditableDropDowns.formPanel.addButton({
                text: 'Export',
                handler: function(form){
                    var Options = new Array();
                    ///console.log(AddEditableDropDowns.formPanel.getForm().getValues())
                    for (var j in AddEditableDropDowns.formPanel.getForm().getValues()) {
                    
                        if (j != 'exportFormat') 
                            Options.push(j);
                    }
                    var frm = document.createElement('form');
                    frm.id = 'frmDummy';
                    frm.name = id;
                    frm.className = 'x-hidden';
                    document.body.appendChild(frm);
                    
                    var maskingAjax = new Ext.data.Connection({
                        listeners: {
                            'beforerequest': {
                                fn: function(con, opt){
                                    //Ext.get(document.body).mask('Loading...');
                                },
                                scope: this
                            },
                            'requestcomplete': {
                                fn: function(con, res, opt){
                                    obj = Ext.util.JSON.decode(res.responseText);
                                    Ext.Msg.alert('Ahem...', obj.message);
                                    AddEditableDropDowns.hide();
                                    Ext.get(document.body).unmask();
                                },
                                scope: this
                            },
                            'requestexception': {
                                fn: function(con, res, opt){
                                    AddEditableDropDowns.hide();
                                    Ext.get(document.body).unmask();
                                },
                                scope: this
                            }
                        }
                    });
                    
                    
                    maskingAjax.request({
                        disableCaching: true,
                        url: Panel.items.items[0].store.proxy.conn.url,
                        form: Ext.fly('frmDummy'),
                        params: {
                            recordID: Ext.encode(param),
                            FormId: grid.store.baseParams.FormId,
                            ExportFields: Options.length > 0 ? Ext.encode(Options) : '',
                            ExportType: 'Export',
                            ExportFormat: AddEditableDropDowns.formPanel.getForm().getValues().exportFormat
                        
                        },
                        isUpload: true
                    });
                    AddEditableDropDowns.hide();
                    
                }
            });
            AddEditableDropDowns.showBlank("asd");
            
        }
    },
    printGrid: function(options){
        var grid = this.component;
        var store = grid.getStore();
        if ((!options || options.browserEvent) && store.lastOptions && store.lastOptions.params && store.lastOptions.params.limit && store.lastOptions.params.limit != 0) {
            // Depending upon app usage, you might want to change this
            // In general, we don't want more than 100 records to be loaded at once. So, we set the limit
            // In our app, we set the limit to 0 to fetch all the records...
            var limit = Math.min(0, store.getTotalCount());
            var lastParams = store.lastOptions.params;
            var params = Ext.applyIf({
                limit: limit
            }, lastParams);
            store.load({
                params: params,
                callback: function(){
                    this.printGrid({
                        params: lastParams
                    });
                },
                scope: this
            });
            return;
        }
        var width = grid.getColumnModel().getTotalWidth();
        var params = {
            id: grid.el.id,
            width: width
        }
        window.open('/index.php/page,Waps.printer?' + Ext.urlEncode(params), "printPreview");
        if (options && options.params) {
            // following delay of 1000 millisec should be enough in most cases
            store.load.defer(1000, store, [{
                params: options.params
            }]);
        }
    },
    // EXPORT ENDS HERE
	openPublishWindow: function(){
		var param = this.component.selModel.selections.keys;
		
        var grid = this.component;
		if (param.length == 0) 
            Ext.MessageBox.alert('Item Check', "Please select 1 or more record to print ")
			else{
				 var store = new Ext.data.SimpleStore({
        fields: ['id', 'name'],
        data : [['1', 'public'], ['2', 'private']] // from states.js
    });

var getMainPanel = function(){
	if (!mainPanel) {
		var mainPanel = new Ext.FormPanel({
			items: [{
				xtype: 'datefield',
				hiddenName: 'publishdate',
				name: 'publishDate',
				fieldLabel: 'publish date',
				allowBlank: false,
				format: 'Y-m-d',
				onTriggerClick: function(){
					this.constructor.prototype.onTriggerClick.apply(this, arguments);
					mainPanel.items.get(1).reset()
				}
				
			}, {
				xtype: 'datefield',
				hiddenName: 'expirydate',
				name: 'expiryDate',
				showToday: false,
				fieldLabel: 'expiry date',
				allowBlank: true,
				format: 'Y-m-d',
				onTriggerClick: function(){
					this.constructor.prototype.onTriggerClick.apply(this, arguments);
					var startDate = mainPanel.items.get(0).getValue();
					if (startDate != '') {
						//console.log(startDate.add('j', 1))
						this.setMinValue(startDate.add('D', 1).format('m/d/Y'));
						this.menu.picker.update(startDate.add('mo', 1));
					//console.log(this)
					}
				//what.setMinValue(Ext.getCmp('publishDate').getValue() == '' ? function(){ var x = new Date(); return x.toLocaleDateString()} : Ext.getCmp('publishDate').getValue().format('m/d/Y'))
				}
			}, {
				xtype: 'combo',
				store: store,
				displayField: 'name',
				typeAhead: true,
				hiddenName: 'publishto',
				//id: 'publishto',
				allowBlank: false,
				mode: 'local',
				forceSelection: true,
				triggerAction: 'all',
				emptyText: 'Select',
				selectOnFocus: true,
				fieldLabel: 'publish to',
				listeners: {
					select: function(a, b, c){
						var x = mainPanel.items.get(3)
						x.reset()
						if (c == 1) 
							x.setDisabled(false);
						if (c == 0) 
							x.setDisabled(true);
						
					}
				}
			
			}, {
				xtype: "multiselect",
				fieldLabel: "private publish to",
				name: "Viewable",
				//id: 'Viewable',
				store: new Ext.data.JsonStore({
					autoLoad: true,
					url: '/index.php/DataService/Type,UserRules',
					baseParams: {
						'recordID': '0'
					},
					root: 'results',
					fields: ['RoleId', 'RoleName']
				}),
				valueField: 'RoleId',
				displayField: 'RoleName',
				width: 100,
				height: 100,
				allowBlank: true,
				disabled: true,
				legend: "select role/s"
			}, {
				xtype: 'hidden',
				value: Ext.encode(param),
				name: 'records'
			}, {
				xtype: 'hidden',
				value: grid.store.baseParams.FormId,
				name: 'FormId'
			}],
			title: 'publish',
			width: 'auto',
			height: 'auto',
			frame: true,
			url: '/index.php/DataService/Type,SavePublish',
			baseParams: {
				'recordID': 0
			},
			bodyStyle: {
				padding: 10
			},
			buttons: [{
				text: 'save',
				handler: function(){
					//console.log(mainPanel);
					//mainPanel.baseParams.FormFields = Ext.encode(FormFields);
					mainPanel.form.submit({
						success: function(form, action){
							mainPanel.form.clearInvalid();
							mainPanel.form.reset();
							mainPanel.hide();
							windowPanel.hide();
							Ext.MessageBox.alert('Hooray', action.result.message);
							grid.store.reload();
							
						},
						failure: function(form, action){
						
						
							Ext.MessageBox.alert('Eh...', action.failureType == 'client' ? 'Please fill all the required fields!' : (action.result.errorMessage || 'I dont know what but something went wrong.. '));
						},
						
						waitMsg: 'Submitting data',
						waitTitle: "Please wait"
					});
				}
			}]
		});
	}
	return mainPanel;
}
             var windowPanel = new Ext.Window({
        
            items: getMainPanel(),
            modal: true,
            width: 400,
            closeAction: 'hide',
            listeners: {
                hide: function(){
                    //console.log(this)
                }
            },
            closable: true
        });
        
        windowPanel.show();
				
			}
	},
    openPrintWindow: function(){
    
        var param = this.component.selModel.selections.keys;
        var grid = this.component;
        
        
        if (param.length == 0) 
            Ext.MessageBox.alert('Item Check', "Please select 1 or more record to print ")
        else {
            var colmnModel = new Array();
            colmnModel[0] = {
                xtype: 'fieldset',
                title: 'Select Columns to Print',
                autoHeight: true,
                autoWidth: true,
                defaults: {
                    width: 10
                },
                defaultType: 'textfield',
                items: new Array()
            };
            for (var i = 0, len = this.component.getColumnModel().config.length; i < len; i++) {
                // console.log(this.component.getColumnModel().config[i].dataIndex);
                colmnModel[0].items[i] = {
                    fieldLabel: this.component.getColumnModel().config[i].dataIndex,
                    name: this.component.getColumnModel().config[i].dataIndex,
                    xtype: "checkbox",
                    value: this.component.getColumnModel().config[i].dataIndex
                    //console.log(colmnModel);
                };
            }
            Panel.setVisible(true);
            var windowPanel = new Ext.Window({
                title: "Preview and Print",
                items: Panel,
                width: 400,
				autoScroll: true,
                height: 200,
                modal: true,
                closeAction: 'hide',
                listeners: {
                    hide: function(){
                        //console.log(this)
                    }
                },
                tools: [],
                closable: true,
                plugins: [new Ext.ux.plugins.Print()]
            });
            
            
            var tpl = '<tpl for="."><tpl><table class="char_select_template" width="100%" cellpadding="0" cellspacing="0" border="0">';
            
            var AddEditableDropDowns = new Ext.FormWindow({
                "fieldList": colmnModel,
                "formUrl": "/index.php/page,Login",
                closable: true,
                
                maximizable: false,
                "title": "Print"
            });
            AddEditableDropDowns.btnCancel.hide();
            AddEditableDropDowns.btnReset.hide()
            AddEditableDropDowns.btnSave.hide()
            AddEditableDropDowns.btnSaveAndNew.hide()
            AddEditableDropDowns.formPanel.addButton({
                text: 'Preview and Print',
                handler: function(form){
                    var Options = new Array();
                    for (var j in AddEditableDropDowns.formPanel.getForm().getValues()) {
                        //console.log(j);
                        Options.push(j);
                        tpl += "<tr><td width='50%' >" + j + "</td><td >{" + j + "}</td></tr>";
                    }
                    tpl += '</table><hr></tpl></tpl><div class="x-clear"><hr></div>';
                    //console.log(tpl);
                    Panel.items.items[0].store.baseParams = {
                        recordID: Ext.encode(param),
                        FormId: grid.store.baseParams.FormId,
                        ExportFields: Options.length > 0 ? Ext.encode(Options) : ''
                    
                    };
                    
                    
                    
                    if (Options.length > 0) 
                        Panel.items.items[0].tpl = new Ext.XTemplate(tpl);
                    else 
                        Panel.items.items[0].tpl = defaultTPL;
                    
                    Panel.items.items[0].store.load();
                    AddEditableDropDowns.hide();
                    windowPanel.show();
                    
                }
            });
            AddEditableDropDowns.showBlank("asd");
            
        }
    },
    printGrid: function(options){
        var grid = this.component;
        var store = grid.getStore();
        if ((!options || options.browserEvent) && store.lastOptions && store.lastOptions.params && store.lastOptions.params.limit && store.lastOptions.params.limit != 0) {
            // Depending upon app usage, you might want to change this
            // In general, we don't want more than 100 records to be loaded at once. So, we set the limit
            // In our app, we set the limit to 0 to fetch all the records...
            var limit = Math.min(0, store.getTotalCount());
            var lastParams = store.lastOptions.params;
            var params = Ext.applyIf({
                limit: limit
            }, lastParams);
            store.load({
                params: params,
                callback: function(){
                    this.printGrid({
                        params: lastParams
                    });
                },
                scope: this
            });
            return;
        }
        var width = grid.getColumnModel().getTotalWidth();
        var params = {
            id: grid.el.id,
            width: width
        }
        window.open('/index.php/page,test.printer?' + Ext.urlEncode(params), "printPreview");
        if (options && options.params) {
            // following delay of 1000 millisec should be enough in most cases
            store.load.defer(1000, store, [{
                params: options.params
            }]);
        }
    },
    
    printForm: function(){
        var form = this.component;
        var params = {
            id: form.body.id,
            type: 'form',
            title: form.title || form.ownerCt.title
        }
        window.open('/index.php/page,test.printer?' + Ext.urlEncode(params), "printPreview");
    },
    multiEdit: function(){
        var grid = this.component;
        var param = this.component.selModel.selections.keys;
        var getRemoteComponentPlugin = function(){
            return new Ext.ux.Plugin.RemoteComponent({
                url: '/index.php/ComponentService/Type,MultiEdit/FormId,' + grid.store.baseParams.FormId,
                mask: Ext.get(document.body),
                maskConfig: {
                    msg: 'remoting...'
                }
            });
        };
        var mainPanel = false;
        var getMainPanel = function(){
            if (!mainPanel) {
                mainPanel = new Ext.FormPanel({
                    title: 'Multi Edit',
                    width: 'auto',
                    height: 'auto',
                    frame: true,
                    url: '/index.php/DataService/Type,MassUpdate',
                    baseParams: {
                        'FormFields': ''
                    },
                    bodyStyle: {
                        padding: 10
                    },
                    items: [{
                        xtype: 'fieldset',
                        title: 'update fields',
                        autoHeight: true,
                        autoWidth: true,
                        defaultType: 'textfield',//
                        items: [{
                            xtype: 'hidden',
                            name: 'FormId',
                            value: grid.store.baseParams.FormId
                        }, {
                            xtype: 'hidden',
                            name: 'recordID',
                            value: Ext.encode(param)
                        }],
                        plugins: [getRemoteComponentPlugin()]
                    }],
                    buttons: [{
                        text: 'Mass update ' + param.length + ' records',
                        handler: function(){
                            var FormFields = new Array();
                            Ext.each(mainPanel.items.items[0].items.items, function(formItem, index, allItems){
                                if (formItem.xtype != 'hidden')
									{
										if(formItem.name)
										FormFields.push(formItem.name);
										else if(formItem.hiddenName)
										FormFields.push(formItem.hiddenName);
									} 
                                    
                            });
                            //console.log(mainPanel);
                            mainPanel.baseParams.FormFields = Ext.encode(FormFields);
                            mainPanel.form.submit({
                                success: function(form, action){
                                    mainPanel.form.clearInvalid();
                                    mainPanel.form.reset();
                                    mainPanel.hide();
                                    windowPanel.hide();
                                    Ext.MessageBox.alert('Hooray', action.result.message);
                                    grid.store.reload();
                                    
                                },
                                failure: function(form, action){
                                
                                
                                    Ext.MessageBox.alert('Eh...', action.failureType == 'client' ? 'Please fill all the required fields!' : (action.result.errorMessage || 'I dont know what but something went wrong.. '));
                                },
                                
                                waitMsg: 'Submitting data',
                                waitTitle: "Please wait"
                            });
                        }
                    }]
                
                });
            }
            return mainPanel;
        };
        var windowPanel = new Ext.Window({
        
            items: getMainPanel(),
            modal: true,
            width: 400,
            closeAction: 'hide',
            listeners: {
                hide: function(){
                    //console.log(this)
                }
            },
            closable: true
        });
        
        windowPanel.show();
    },
    init: function(o){
    
        function oc(a){
            var oe = {};
            for (var i = 0; i < a.length; i++) {
                oe[a[i]] = '';
            }
            return oe;
        }
        
        
        var xType = o.xtype || o.getXType();
        //console.log(o.tools);
        switch (xType) {
            case 'grid':
				
                this.component = o;
				if(!o.tools)
				o.tools = [];
				o.tools.push({
                                    id: 'print',
                                    handler: this.openPrintWindow,
									scope: this,
									hidden : true,
									qtip : 'print'
                                });
								o.tools.push({
                                        id: 'up',
                                        handler: this.openExportWindow,
										scope: this,
										hidden : true,
									qtip : 'export'
                                    });
									 o.tools.push({
                                        id: 'restore',
                                        handler: this.multiEdit,
										scope: this,
										hidden : true,
									qtip : 'multi-edit'
                                    });
									o.tools.push({
                                        id: 'save',
                                        handler: this.openPublishWindow,
										scope: this,
										hidden : true,
									qtip : 'publish'
                                    });
                o.on('beforerender', function(o){
                    Ext.Ajax.request({
                        disableCaching: true,
                        url: '/index.php/DataService/Type,getResourceAccess/recordID,0/FormId,0',
                        params: {
                            PagePath: document.URL.split("page,")[1]
                        },
                        failure: function(response, options){
                            Ext.MessageBox.alert('Warning', 'Oops...');
                        },
                        success: function(response, options){
                            
                            var responseData = Ext.util.JSON.decode(response.responseText);
							//console.log(o.tools)
							
                            if ('11' in oc(responseData)) 
                            o.tools.print.show()    
                                
                            if ('9' in oc(responseData))
							o.tools.up.show();
                                    
                             if ('18' in oc(responseData))
							 o.tools.restore.show()
							  
                            if ('12' in oc(responseData))
							 o.tools.save.show()
							 
							  
							
                            return true;
                        },
                        scope: this
                    });
                }, this)
                
                break;
                
            case 'window':
            case 'form':
                // GLOBAL REGISTRING OF THE DEFAULT TEMPLATE
                if (typeof(defaultTPL) != 'object') {
                    defaultTPL = Panel.items.items[0].tpl;
                }
                this.component = o;
                if (o.tools) {
                    o.tools.push({
                        id: 'print',
                        handler: this.printForm,
                        scope: this,
						qtip : 'print'
                    });
                }
                else {
                    var tBar = o.getTopToolbar();
                    //console.log(tBar);
                    if (tBar) {
                        var added = false;
                        for (var i = 0, len = tBar.length; i < len; i++) {
                            if (tBar[i].text == 'Print') {
                                var btn = tBar[i];
                                if (!btn.handler) {
                                    Ext.apply(btn, {
                                        handler: this.printForm,
                                        scope: o,
										qtip : 'print'
                                    });
                                    added = true;
                                }
                                break;
                            }
                        }
                        if (!added) {
                            tBar.push({
                                iconCls: 'print',
                                handler: this.printForm,
                                scope: this
                            });
                        }
                    }
                }
                break;
        }
        
    },
    
    scope: this
})

Ext.ux.PrintSetup = function(){
    this.init();
}

Ext.ux.PrintSetup = Ext.extend(Ext.ux.PrintSetup, {
    setupGrid: function(){
        var width = this.params.width;
        if (!isNaN(width)) {
            width = parseInt(width) + "px";
        }
        else {
            width = undefined;
        }
        var params = {
            height: null,
            width: width
        };
        
        this.applyStyles("div[class*='x-grid3-hd-inner']", {
            "padding-right": null
        });
        this.applyStyles("div[class*='x-grid3-header-inner']", {
            "width": null
        });
        
        this.applyStyles("div[class='x-grid3-scroller']", params);
        this.applyStyles("div[class='x-panel-body']", params);
        this.applyStyles("div[class='x-grid3']", params);
        
        this.setTitle();
    },
    
    applyStyles: function(selector, styles){
        var elements = Ext.DomQuery.select(selector);
        if (elements) {
            var dh = Ext.DomHelper;
            for (var i = 0, len = elements.length; i < len; i++) {
                dh.applyStyles(elements[i], styles);
            }
        }
    },
    
    setTitle: function(className){
        if (!className) {
            className = "x-panel-header-text";
        }
        var elements = Ext.DomQuery.select("span[class='" + className + "']");
        if (elements && elements.length > 0) {
            document.title = elements[0].innerHTML;
        }
    },
    
    setupForm: function(){
        document.title = this.params.title;
    },
    
    init: function(){
        var parentWin = window.opener;
        if (parentWin) {
            var params = Ext.urlDecode(location.href.substring(location.href.indexOf("?") + 1));
            this.params = params;
            if (params.id) {
                window.document.body.innerHTML = parentWin.document.getElementById(params.id).innerHTML;
                Ext.applyIf(params, {
                    type: 'grid'
                });
                switch (params.type) {
                    case "grid":
                        this.setupGrid();
                        break;
                    case "form":
                        this.setupForm();
                }
                //window.print();
                //window.close();
            }
        }
    }
});

