Ext.namespace('Ext.ux.plugins');

Ext.override(Ext.form.Field, {

    uxDisplayOnly: function(displayOnly, cls){
        var displayOnly = (displayOnly === false) ? false : true;
        var cls = (cls) ? cls : 'x-form-display-only-field';
        
        if (displayOnly) {
            this.el.addClass(cls);
        }
        else {
            this.el.removeClass(cls);
        }
        this.el.dom.readOnly = displayOnly;
        
        var xType = this.getXType();
        
        if (xType == 'checkbox') {
            this.readOnly = displayOnly; // We need to also set the config readOnly attribute for checkboxes
        }
        
        if (xType == 'radiogroup' || xType == 'checkboxgroup') {
            var items = this.items.items;
            for (var i = 0; i < items.length; i++) {
                items[i].readOnly = displayOnly;
            };
                    }
        if (this.trigger) {
            this.trigger.setDisplayed(!displayOnly);
        }
				 if (this.isXType('combo') && this.keyNav) {
            this.keyNav[displayOnly? 'disable' : 'enable']();
        }

    }
    
});

// Create a class the can handle a string containing XML content.
Ext.data.XmlStringReader = function(meta, recordType){

    // Execute the ancestor class contructor passing the specified parameters.
    Ext.data.XmlStringReader.superclass.constructor.call(this, meta, recordType);
    
}; // End of Function - XmlStringReader()
// Extend the XmlStringReader class with the methods of the XmlReader class.
Ext.extend(Ext.data.XmlStringReader, Ext.data.XmlReader, {

    parseXmlString: function(sXml){
    
        // If the specified XML document content is a string...
        if (typeof sXml == "string") {
        
            var oXml; // Reference to the parsed XML document
            // If the current browser is Internet Explorer...
            if (window.ActiveXObject) {
            
                // Create a reference to the Microsoft XML Document Object Model.
                oXml = new ActiveXObject("Microsoft.XMLDOM");
                
                // Assign the flag to process the XML synchronously.
                oXml.async = "false";
                
                // Load the XML document with the content from the specified string.
                oXml.loadXML(sXml);
                
            }
            
            else { // Current browser is Mozilla, Firefox, Opera, etc.
                // Create a reference to the XML document parser.
                var oParser = new DOMParser();
                
                // Parse the XML string and return a reference to the XML document.
                oXml = oParser.parseFromString(sXml, "text/xml");
                
            }
            
            // Return the reference to the XML document.
            return oXml;
            
        }
        
        else { // XML document content is NOT a string...
            // Return the specified XML document since it has already been parsed.
            return sXml;
            
        }
        
    }, // End of Function - parseXmlString()
    readRecords: function(doc){
    
        // If the specified XML document is actually a string containing the XML
        // content, parse it into an XML document reference so that the reader
        // can process it into records.  If the specified XML document is not a
        // string, this statement will simply return the XML document reference.
        doc = this.parseXmlString(doc);
        
        // Execute the ancestor class method to read the records passing the XML
        // document reference.  This returns an object containing the success
        // flag for reading the data, a reference to the record set, and the
        // total number of records read.
        return Ext.data.XmlStringReader.superclass.readRecords.call(this, doc);
        
    } // End of Function - readRecords()
});

Ext.override(Ext.grid.GridView, {
    layout: function(){
        if (!this.mainBody) {
            return;
        }
        var g = this.grid;
        var c = g.getGridEl(), cm = this.cm, expandCol = g.autoExpandColumn, gv = this;
        var csize = c.getSize(true);
        var vw = csize.width;
        if (vw < 20 || csize.height < 20) {
            return;
        }
        if (g.autoHeight) {
            csize.height = this.mainHd.getHeight() + this.mainBody.getHeight();
            if (!this.forceFit) {
                csize.height += this.scrollOffset;
            }
        }
        this.el.setSize(csize.width, csize.height);
        var hdHeight = this.mainHd.getHeight();
        var vh = csize.height - (hdHeight);
        this.scroller.setSize(vw, vh);
        if (this.innerHd) {
            this.innerHd.style.width = (vw) + 'px';
        }
        if (this.forceFit) {
            if (this.lastViewWidth != vw) {
                this.fitColumns(false, false);
                this.lastViewWidth = vw;
            }
        }
        else {
            this.autoExpand();
        }
        this.onLayout(vw, vh);
    }
});



Ext.util.Format.FormatterFactory = function(c, d, t, s, ap){
    return function(n){
        if (n != '') {
            var m = (c = Math.abs(c) + 1 ? c : 2, d = d || ",", t = t || ".", /(\d+)(?:(\.\d+)|)/.exec(n + "")), x = m[1].length > 3 ? m[1].length % 3 : 0;
            var ret = '';
            if (ap == 1) 
                ret += s + ' '
            
            ret += ((x ? m[1].substr(0, x) + t : "") + m[1].substr(x).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + (+m[2] || 0).toFixed(c).substr(2) : ""));
            if (ap == 0) 
                ret += ' ' + s
            return ret;
        }
        //return s+' '+((x ? m[1].substr(0, x) + t : "") + m[1].substr(x).replace(/(\d{3})(?=\d)/g,          "$1" + t) + (c ? d + (+m[2] || 0).toFixed(c).substr(2) : ""));
    }
}


Ext.form.VTypes['phone'] = function(Z, v){
    //var E = /^(\d{3}[-]?){1,2}(\d{4})$/;
	var E = /^[0-9\-\+\s]+$/;
    return E.test(Z);
}
Ext.form.VTypes.phoneText = "Not a valid phone number. Number can contain only digits, hyphen (-), space( )";
Ext.form.VTypes.phoneMask = /[\d-+]/;

Ext.override(Ext.form.Field, {
	
    showContainer: function(){
        //this.enable();
        this.show();
        this.getEl().up('.x-form-item').setDisplayed(true); // show entire container and children (including label if applicable)
    },
    setColor: function(){
        this.getEl().up('.x-form-item').setStyle('color', '#c1000f'); // show entire container and children (including label if applicable)
    },
    hideContainer: function(){
        if (this.xtype != 'select') {
            //this.disable(); // for validation
            this.hide();
            this.getEl().up('.x-form-item').setDisplayed(false); // hide container and children (including label if applicable)
        }
        
    },
    
    setContainerVisible: function(visible){
        if (visible) {
            this.showContainer();
        }
        else {
            this.hideContainer();
        }
        return this;
    }
});

Ext.onReady(function(){
    var formWindow = function(config){
        var myConfig = {};
        
        // make these externally facing so you can
        // change stuff if you want.
        this.btnSave = new Ext.Button({
            text: 'submit',
            handler: this.submitForm,
            scope: this, 
			iconCls : config.submitButtonCss,
			cls : 'leftBtn'
        });
        this.btnSaveAndNew = new Ext.Button({
            text: 'Add and New',
            handler: this.submitFormAndNew,
            scope: this
        });
        
        
        this.btnReset = new Ext.Button({
            text: 'reset',
            handler: this.resetForm,
            scope: this, 
			iconCls : config.resetButtonCss,
			cls : 'leftBtn'
        });
        
        this.btnCancel = new Ext.Button({
            text: 'cancel',
            handler: this.closeWindow,
            scope: this
        });
        this.formPanel = new Ext.FormPanel({
            //labelWidth: config.labelWidth != '' ? config.labelWidth : 200, // label settings here cascade unless overridden
            labelWidth: parseInt(config.labelWidth) || 100, // label settings here cascade unless overridden
            url: config.formUrl || 'save-form.php',
            bodyStyle: 'padding:5px 5px 0',
            width: config.width != '' ? config.width : 350,
            frame: false,
			border: false,
			renderTo: config.renderTo,
            autoScroll: true,
            monitorValid: true,
            //autoHeight:true,
            defaults: {
                labelSeparator: ''
                //width: 200
            },
            //defaultType      : 'textfield',
            trackResetOnLoad: true,
            //items: [].concat(config.fieldList)
            items: config.fieldList,
			tbar: config.ShowToolbar == true ? ['only required fields (RED) are shown by default. click here to', {
                "text": "view all optional fields",
                "pressed": false,
                "enableToggle": true,
                "toggleHandler": function(asd, istoggled){
                    if (!istoggled) 
                        asd.setText("view all optional fields");
                    else 
                        asd.setText("hide all  optional fields");
                    this.onShowRequired(istoggled);
                },
                
                scope: this
            }] : ''
        });
        
        //Defaults
        Ext.apply(myConfig, config, {
            //width: 400,
            //height: 450,
			border: false,
			 header: false,
			autoHeight: true,
			submitButtonCss: '',
			resetButtonCss: '',
            //autoScroll	: true,
            items: [this.formPanel],
            bodyStyle: 'padding:5px;',
            buttonAlign: 'right',
            buttons: [this.btnSave, this.btnReset],
            listeners: {
                render: {
                    fn: function(){
                        this.onShowRequired(false);
						if(this.ShowToolbar == true){
						this.formPanel.getTopToolbar().getEl().dom.style.background = 'white'
						this.formPanel.getTopToolbar().getEl().dom.style.border = 'none'
}
//Ext.getCmp('northPanel').getTopToolbar().getEl().dom.style.background = 'black';

                    }
                }
            }
			
        });
        
        
        //call the parent class constructor with the scope of 'this'
        formWindow.superclass.constructor.call(this, myConfig);
    }
    
    
    Ext.FormWindow = Ext.extend(formWindow, Ext.Panel, {
        showBlank: function(toRefresh){
            formWindow.superclass.render.call(this);
            this.toRefresh = toRefresh;
        },
        submitForm: function(){
            this.formPanel.form.submit({
                success: this.onSubmitFormSuccess,
                failure: this.onSubmitFormFailure,
                scope: this,
                waitMsg: 'Submitting data',
                waitTitle: "Please wait"
            });
        },
        onSubmitFormSuccess: function(form, action){
            //alert(action.failureType);
            //Ext.MessageBox.alert('hurray', action.failureType == 'client' ? 'Please fill all the required fields!' : (action.result.errorMessage || 'I dont know what but something went wrong.. '));
            //alert(dataView);
            this.resetForm();
            form.clearInvalid();
            this.closeWindow();
            eval(this.toRefresh);
            Ext.MessageBox.alert('Hooray', 'action performed successfully');
            
        },
        onSubmitFormFailure: 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.. '));
        },
        onEsc: function(){
            this.closeWindow();
        },
        resetForm: function(){
            if (this.formDataObj) {
                this.loadData(this.formDataObj);
                this.formPanel.form.clearInvalid();
            }
            else {
                // set all values to null manually, being that we loaded
                // a record and .reset() will not work
                Ext.each(this.formPanel.form.items.items, function(formItem, index, allItems){
                    formItem.reset();
                    //formItem.setValue(null);
                });
                this.formPanel.form.clearInvalid();
            }
        },
        onShowRequired: function(btn){
            // set all values to null manually, being that we loaded
            // a record and .reset() will not work
            
            Ext.each(this.formPanel.form.items.items, function(formItem, index, allItems){
            
                if (formItem.allowBlank && btn && formItem.inputType != 'hidden') // ADDED   && formItem.inputType != 'hidden' 26th sept 
                    formItem.setContainerVisible(true);
                else 
                    if (formItem.allowBlank && !btn && formItem.inputType != 'hidden' && this.ShowToolbar) { // ADDED   && formItem.inputType != 'hidden' 26th sept
                        this.hasNonRequiredFields = true;
                        formItem.setContainerVisible(false)
                    }
                if (formItem.allowBlank == false && formItem.inputType != 'hidden') 
                    formItem.setColor();
				
                /*
                 *
                 if(formItem.allowBlank == false)
                 formItem.getEl().up('.x-form-item').applyStyles('color:#c1000f');
                 */
                //formItem.hideLabel = true;
                //
            }, this);
            if (!this.hasNonRequiredFields && this.ShowToolbar) 
                this.formPanel.tbar.hide();
			
            //this.formPanel.form.clearInvalid();
        
        },
        loadData: function(record){
        
            if (typeof record == 'object') {
                // Ext record object
                if (typeof record.override == 'function') {
                    this.formPanel.form.loadRecord(record);
                }
                // Assume it's a Json obj
                else {
                    this.formPanel.form.setValues(record);
                }
            }
        },
        closeWindow: function(){
            //cleanup and reset
            if (this.formDataObj) {
                delete this.formDataObj;
                this.resetForm();
            }
			
			//console.log(this.formPanel.getTopToolbar().items.get(1).getText())
//			if(this.formPanel.getTopToolbar().items.get(1).getText() == "hide optional Fields")
//			this.formPanel.getTopToolbar().items.get(1).toggle();
			//console.log(this.formPanel.getTopToolbar())
            this.hide();
        }
    });
});

