Ext.ns('Ext.ux.plugins');
Ext.ns('Ext.ux.form');
Ext.ns('Ext.ux.panel');

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

// Ext.Ajax.on('beforerequest', this.showSpinner, this);

Ext.Ajax.on('requestcomplete', function(conn, response, options) {

    if (options == undefined || !options.isUpload) {
        switch (response.status) {
            case 200:
                // do nothing;
                break;
            default:
                Ext.Msg.alert('Unexpected Server Response (' + response.status + ')', 'The server returned an unexpected response:\n' + response.statusText);
        }
    } else {
        var temp = Ext.decode(response.responseText);
        if (!temp.success) {
            Ext.Msg.alert('Unexpected Server Response (' + response.status + ')', 'The server returned an unexpected response:\n' + response.statusText);
        }
    }
}, this);

Ext.Ajax.on('requestexception', function(con, response, opt) {
	// debugger;
		Ext.Msg.alert('Server Error (' + response.status + ')', '<p>The server has responded to your request with an unexprected an error: <span class="red">' + response.statusText + '</span></p><p>The error has been logged for investigation. You may be able to repeat the request, however if not, we suggest you contact a system administrator for assistance.</p><p>The error detail is shown below:</p> <div style="border:1px solid silver;padding:5px;background-color:#FFF;height:200px;width:500px;overflow:scroll">' + response.responseText + '</div>')
	}, this);

if (Ext && Ext.ux && Ext.ux.grid && Ext.ux.grid.GridFilters) {
	Ext.override(Ext.ux.grid.GridFilters, {
		buildQuery : function(filters) {
			return {
				filters :Ext.encode(filters)
			};
		}
	});
};

Ext.form.Action.Submit.prototype.run = Ext.form.Action.Submit.prototype.run.createInterceptor( function() {
	this.form.items.each( function(item) {
		if (item.el.getValue() == item.emptyText) {
			item.el.dom.value = '';
		}
	});
});

Ext.form.Action.Submit.prototype.run = Ext.form.Action.Submit.prototype.run.createSequence( function() {
	this.form.items.each( function(item) {
		if (item.el.getValue() == '' && item.emptyText) {
			item.el.dom.value = item.emptyText;
		}
	});
});

// Ext.override(Ext.form.CheckboxGroup, {
// getName: function(){
//
// return this.items.first().getName();
// },
// getNames: function(){
// var n = [];
// this.items.each(function(item){
//
// if (item.getValue()) {
// n.push(item.getName());
// }
// });
//
// return n;
// },
// getValues: function(){
// var v = [];
// this.items.each(function(item){
//
// if (item.getValue()) {
// v.push(item.getRawValue());
// }
// });
//
// return v;
// },
// setValue: function(v){
// a = eval('[' + v + ']');
// this.items.each(function(item){
// for (var i = 0; i < a.length; i++) {
//
// if (a[i] == item.inputValue) {
// item.setValue(true);
// }
// }
// });
// },
// setValues: function(v){
// alert('setValues:' + v);
// var r = new RegExp('(' + v.join('|') + ')');
// this.items.each(function(item){
// item.setValue(r.test(item.getRawValue()));
// });
// }
// });

// Ext.override(Ext.form.RadioGroup, {
// getName: function(){
//
// return this.items.first().getName();
// },
// getValue: function(){
// var v;
// this.items.each(function(item){
// v = item.getRawValue();
//
// return !item.getValue();
// });
//
// return v;
// },
// setValue: function(v){
// this.items.each(function(item){
// item.setValue(item.getRawValue() == v);
// });
// }
// });
/* Create a NULL plugin to deal with */
Ext.ux.plugins.Null = function() {
};
Ext.ux.plugins.Null.prototype = {
	init : function() {
	}
};

// Ext.override(Ext.form.CheckboxGroup, {
// afterRender: function(){
// Ext.form.CheckboxGroup.superclass.afterRender.apply(this, arguments);
// var form = this.findParentByType('form').getForm();
// form.add.apply(form, this.items.items);
// }
// });

/*
 * NOTE: No override needed for ReadioBox as it extends checkbox.
 */
Ext.override(Ext.ux.grid.GridFilters, {
	buildQuery : function(filters) {
		return {
			filters :Ext.encode(filters)
		}
	}
});

Ext.ux.WizardPanel = Ext.extend(Ext.Panel, {
	currentPage :0,
	initComponent : function(config) {
		Ext.apply(this, {
			layout :'card',
			layoutConfig : {
				deferredRender :false
			},
			frame :true,
			activeItem :0,
			bbar : [ new Ext.Toolbar.Fill(), '-' ]
		});
		Ext.ux.WizardPanel.superclass.initComponent.call(this);
	},
	onRender : function(ct, position) {
		Ext.ux.WizardPanel.superclass.onRender.call(this, ct, position);
		tb = this.getBottomToolbar();
		this.restartButton = tb.addButton( {
			disabled :true,
			text :'<< Restart',
			scope :this,
			handler :this.goRestart
		});
		tb.addSeparator();
		this.backButton = tb.addButton( {
			disabled :true,
			text :'<< Back',
			scope :this,
			handler :this.goPreviousPage
		});
		tb.addSeparator();
		this.nextButton = tb.addButton( {
			scope :this,
			disabled :false,
			text :'Next >>',
			handler : function() {
				this.goNextPage()
			}
		});
		tb.addSeparator();
		this.repeatButton = tb.addButton( {
			disabled :true,
			text :'Repeat >>',
			scope :this,
			handler :this.goRepeatPage
		});
		tb.addSeparator();
		this.finishButton = tb.addButton( {
			disabled :true,
			text :'Finish',
			scope :this,
			handler :this.finish
		});
		this.on('afterlayout', function() {

			if (this.layout.activeItem.fxAllowMultiple == 'true') {
				this.repeatButton.setDisabled(false);
			} else {
				this.repeatButton.setDisabled(true);
			}
		}, this);
	},
	onAfterLayout : function(ct, layout) {
		alert('asd');
		Ext.ux.WizardPanel.superclass.onAfterLayout.call(this, ct, layout);
	},
	changePage : function(x) {
		this.currentPage += x;
		this.getLayout().setActiveItem(this.currentPage);

		if (this.layout.activeItem.fxAllowMultiple == 'true') {
			this.repeatButton.setDisabled(false);
		} else {
			this.repeatButton.setDisabled(true);
		}
		this.backButton.setDisabled(this.currentPage == 0);
		this.nextButton.setDisabled(this.currentPage == this.items.getCount() - 2);
		this.finishButton.setDisabled(this.currentPage != this.items.getCount() - 2);
	},
	goRepeatPage : function(x) {
		try {
			OnNextButton(this.layout.activeItem);
		} catch (e) {
		}
		for ( var i = 0; i < this.findByType('form').length; i++) {
			this.findByType('form')[i].getForm().reset();
		}
	},
	goNextPage : function(x) {
		try {
			OnNextButton(this.layout.activeItem);
		} catch (e) {
		}
		this.changePage(1);
	},
	goPreviousPage : function(x) {
		this.changePage(-1);
	},
	goRestart : function(x) {
		for ( var i = 0; i < this.findByType('form').length; i++) {
			this.findByType('form')[i].getForm().reset();
		}
		this.currentPage = 0;
		this.changePage(0);
		this.restartButton.setDisabled(true);
	},
	finish : function(x) {
		try {
			OnFinishButton(this.layout.activeItem);
		} catch (e) {
		}
		this.changePage(1);
		this.backButton.setDisabled(true);
		this.nextButton.setDisabled(true);
		this.restartButton.setDisabled(false);
	}
});
Ext.reg("uxwizardpanel", Ext.ux.WizardPanel);

Ext.ux.form.XCheckbox = Ext.extend(Ext.form.Checkbox, {

	submitOffValue :'false',
	submitOnValue :'true',

	onRender : function(ct) {
		debugger;
		this.inputValue = this.submitOnValue;

		Ext.ux.form.XCheckbox.superclass.onRender.apply(this, arguments);

		this.hiddenField = this.wrap.insertFirst( {
			tag :'input',
			type :'hidden'
		});
		this.updateHidden();
	},

	setValue : function(v) {
		var checked = this.checked;
		this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
		if (this.rendered) {
			this.el.dom.checked = this.checked;
			this.el.dom.defaultChecked = this.checked;
		}
		if (checked != this.checked) {
			this.fireEvent('check', this, this.checked);
			if (this.handler) {
				this.handler.call(this.scope || this, this, this.checked);
			}
		}
		return this;
	},
	updateHidden : function() {

		if (this.rendered) {
			if (this.hiddenField) {
				this.hiddenField.dom.value = this.checked ? this.submitOnValue : this.submitOffValue;
				this.hiddenField.dom.name = this.checked ? '' : this.el.dom.name;
			}
		}
	}
});

// Ext.reg('xcheckbox', Ext.ux.form.XCheckbox);
Ext.reg('xcheckbox', Ext.form.Checkbox);

// By adding setValues() this will be called on form load and can set the
// displayValue()

Ext.override(Ext.form.ComboBox, {
	setValue : function(v, values) {
		var text = v;
		var displayValue = null
		if (this.initialDisplayValue) {
			displayValue = this.initialDisplayValue;
			delete this.initialDisplayValue;
		} else if (this.initialDisplayField && values) {
			displayValue = values[this.initialDisplayField];
		} else if (this.valueField) {
			var r = this.findRecord(this.valueField, v);
			if (r) {
				displayValue = r.data[this.displayField];
			}
		}
		if (displayValue) {
			text = displayValue;
		} else if (Ext.isDefined(this.valueNotFoundText)) {
			text = this.valueNotFoundText;
		}

		this.lastSelectionText = text;
		if (this.hiddenField) {
			this.hiddenField.value = v;
		}
		Ext.form.ComboBox.superclass.setValue.call(this, text);
		this.value = v;
		return this;
	}
});

Ext.override(Ext.form.BasicForm, {
	setValues : function(values) {
		if (Ext.isArray(values)) {
			// array of objects
		for ( var i = 0, len = values.length; i < len; i++) {
			var v = values[i];
			var f = this.findField(v.id);
			if (f) {
				f.setValue(v.value);
				if (this.trackResetOnLoad) {
					f.originalValue = f.getValue();
				}
			}
		}
	} else {
		// object hash
		var field, id;
		for (id in values) {
			if (!Ext.isFunction(values[id]) && (field = this.findField(id))) {
				field.setValue(values[id], values);
				if (this.trackResetOnLoad) {
					field.originalValue = field.getValue();
				}
			}
		}
	}
	return this;
}
});

Ext.override(Ext.form.Field, {
	getFormPanel : function() {
		return this.findParentBy( function(x) {
			return x.isXType('form');
		})
	}
});

notify = function(message, title) {
	new Ext.ux.Notification( {
		title :title ? title : 'Notification',
		html :message
	}).show(document);
}

Ext.override(Ext.form.Action.Submit, {
    /**
    * @cfg {boolean} clientValidation Determines whether a Form's fields are
    *      validated in a final call to
    *      {@link Ext.form.BasicForm#isValid isValid} prior to submission. Pass
    *      <tt>false</tt> in the Form's submit options to prevent this. If not
    *      defined, pre-submission field validation is performed.
    */
    type: 'submit',

    // private
    /**
    * This is nearly a copy of the original submit action run method
    */
    run: function() {
        var o = this.options;
        var method = this.getMethod();
        var isPost = method == 'POST';
        var isGet = method == 'GET';


        //		var params = this.options.params || {};
        var params = {};
        if (isPost)
            Ext.applyIf(params, this.form.baseParams);

        // now add the form parameters
        this.form.items.each(function(field) {
            if (!field.disabled && field.getXType() != 'fileuploadfield') {
                // check if the form item provides a specialized getSubmitValue() and use
                // that if available
                if (typeof field.getSubmitValue == "function")
                    params[field.getName()] = field.getSubmitValue();
                else
                    params[field.getName()] = field.getValue();
            }
        });

        // convert params to get style if we are not post
        if (!isPost)
            params = Ext.urlEncode(params);

        if (o.clientValidation === false || this.form.isValid()) {

            if (this.form.fileUpload) {

                notify('This may take some time depending on file size.', 'Uploading your files');

                Ext.Ajax.request(Ext.apply(this.createCallback(o), {
                    form: this.form.el.dom,
                    url: this.getUrl(isGet),
                    method: method,
                    headers: o.headers,
                    params: !isGet ? this.getParams() : null,
                    isUpload: this.form.fileUpload
                }));

            }
            else {
                Ext.Ajax.request(Ext.apply(this.createCallback(o), {
                    headers: o.headers,
                    url: this.getUrl(!isPost),
                    method: method,
                    params: Ext.apply(params, this.options.params)
                }));

            }

        } else if (o.clientValidation !== false) {
            // client validation failed
            this.failureType = Ext.form.Action.CLIENT_INVALID;
            this.form.afterAction(this, false);
        }
    }
});

Ext.override(Ext.form.DateField, {
	getSubmitValue : function() {
		var v = this.getValue();
		if (v !== '') {
			var date = new Date(v);
			return date.format("Y-m-d");
		}
	}
});

Ext.override(Ext.grid.GridView, {
    //use this code to override and retain original
    // private
    afterRender: Ext.grid.GridView.prototype.afterRender.createSequence(function () {
        this.fireEvent("viewready", this);//new event
    })
});

