Ext.BLANK_IMAGE_URL = "ui/it/resources/s.gif";	// 1x1 picture, by default it is loaded from external site

ITechs = {
	msgCt: null,

	/*
	params = {name1: 'value1', name2: 'value2'}
	successfn = {scope: scope, fn: function}
	failfn = {scope: scope, fn: function}
	*/
	request: function(url, params, successfn, failfn) {

		var processResponse = function(opt, result, response) {
			if (result == true) {
				var res = Ext.decode(response.responseText);
			} else {
				var res = {
					is_error: true,
					messages: ['Request is failed.']
				}
			};
			var t = failfn;
			var cb = res.is_error != true ? successfn : failfn;
			if (!cb) {
				cb = {fn: null, scope: null};
			} else if (typeof cb == 'function') {
				cb = {fn: cb, scope: window};
			} else if (typeof cb.fn != 'function') {
				cb.fn = null;
			};
			var _ps = [res, opt];
			ITechs.displayMessages(res.messages, res.is_error, cb.fn ? cb.fn : null, cb.scope ? cb.scope : null, _ps);
    	};

		var conf = {
    		method: 'POST',
    		url: url,
    		params: params,
    		callback: processResponse
    	}
    	var Lconnect = new Ext.data.Connection(conf);
    	Lconnect.request(conf);
	},

	displayMessages: function(messages, is_errors, fn, scope, callback_params) {
		if (!callback_params) {
			callback_params = [];//IE fix
		}
		var msg = this._prepearMsg(messages);
		if (msg != "") {
			if (is_errors == true) {
				Ext.MessageBox.alert("Error", msg, function(){if (fn) fn.apply(scope, callback_params)});
				return true;
			}else{
				this.showNotice("Information", msg);
			}
		}
		if (typeof fn == 'function') {
			fn.apply(scope, callback_params);
		}
	},

	showNotice:function(title, format){
		var createBox = function (t, s){
			return ['<div class="msg">',
			'<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
			'<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>',
			'<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
			'</div>'].join('');
		};

		if(!this.msgCt){
			this.msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
		}
		this.msgCt.alignTo(document, 't-t');
		var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
		var m = Ext.DomHelper.append(this.msgCt, {html:createBox(title, s)}, true);
		m.slideIn('t').pause(4).ghost("t", {remove:true});
	 },

	_prepearMsg: function(messages) {
		var msg = "";
		if (messages) {
			if (messages instanceof Array) {
				for(var i=0; i < messages.length; i++) {
					if (i > 0) msg += "<br>";
					msg += messages[i];
				}
			} else {
				var first = true;
				for(var i in messages) {
					if (!first) msg += "<br>";
					msg += messages[i];
					first = false;
				}
			}
		}
		return msg;
	}
};

Ext.lib.Ajax.handleTransactionResponseReal = Ext.lib.Ajax.handleTransactionResponse;
Ext.lib.Ajax.handleTransactionResponse = function(o, callback, isAbort) {
	try {
		if (o.conn.responseText == "LOGOUT") {
			document.location = 'logout.php';
		} else {
			this.handleTransactionResponseReal(o, callback, isAbort);
		}
	}catch(e){
		this.handleTransactionResponseReal(o, callback, isAbort);
	}
};

/** ITechs.SimpleFilter *************/
ITechs.SimpleFilter = function(oForm, dataSource, set_limit) {
	this.limit = set_limit > 0 ? set_limit : 10;
	this._need_limit = true;

	if (typeof oForm == 'string') {
		oForm = Ext.getDom(oForm);
	}
	if (oForm && oForm.elements) {
		this.f = oForm;
		this.ds = dataSource;
		oForm.onsubmit = this.startSearch.createDelegate(this);
	}
};

ITechs.SimpleFilter.prototype = {
	startSearch: function() {
		if (this.f) {
			this._getLimit();
			this.ds.baseParams = this._grabParams();
			this.ds.load({params: {limit: this.limit, start:0}});
		}
		return false;
	},

	resetFilter: function() {
		this.ds.baseParams = {};
		this.f.reset();
		this._getLimit();
		this.ds.load({params: {limit: this.limit, start:0}});
	},

	assignFilterField: function(fname, val) {
		if (fname) {
			this.ds.baseParams[fname] = val;
		}
	},

	_grabParams: function() {
		var params = {};
		if (this.f) {
			for(var i=0; i<this.f.elements.length; i++) {
				var c_el = this.f.elements[i];
				switch(c_el.type) {
				case 'select-one':
				case 'hidden':
				case 'text':
					params[c_el.name] = c_el.value;
					break;

				case 'radio':
				case 'checkbox':
					if (c_el.checked) {
						params[c_el.name] = c_el.value;
					} /*else {
						this.assignFilterField(c_el.name, '');
					}*/
					break;
				}
			}
		}
		return params;
	},

	_getLimit: function() {
		if (!this._need_limit) return true;
		if (this.ds.lastOptions && this.ds.lastOptions.params && this.ds.lastOptions.params.limit > 0) {
			this.limit = this.ds.lastOptions.params.limit;
		}
		this._need_limit = false;
	}
};
/** ITechs.SimpleFilter *************/

ITechs.ErrorsReader = function() {};

ITechs.ErrorsReader.prototype = {
	read : function(response){
        var json = response.responseText;
        var o = eval("("+json+")");
        if(!o) {
            throw {message: "ErrorsReader.read: Json object not found"};
        }
        var r = [];
        if (o.messages) {
        	for(var i=0; i<o.messages.length; i++) {
        		r.push({data: o.messages[i]});
        	}
        } else {
        	r = null;
        }
        return {
	        success : o.is_error ? false : true,
	        records : r
	    };
    }
};
Ext.override(Ext.form.BasicForm, {
	afterAction : function(action, success){
        this.activeAction = null;
        var o = action.options;

        if(this.waitMsgTarget === true){
            this.el.unmask();
        }else if(this.waitMsgTarget){
            this.waitMsgTarget.unmask();
        }else{
            Ext.fly(document.body).unmask();
        }

        if(success){
            if(o.reset){
                this.reset();
            }
            Ext.callback(o.success, o.scope, [this, action]);
            this.fireEvent('actioncomplete', this, action);
        }else{
            Ext.callback(o.failure, o.scope, [this, action]);
            this.fireEvent('actionfailed', this, action);
        }
    }
});

Ext.override(Ext.menu.Menu, {
    autoWidth : function(){
        var el = this.el, ul = this.ul;
        if(!el){
            return;
        }
        var w = this.width;
        if(w){
            el.setWidth(w);
        }else if(Ext.isIE && !Ext.isIE8){
            el.setWidth(this.minWidth);
            var t = el.dom.offsetWidth; // force recalc
            el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
        }
    }
});

ITechs.QuickFormP = function(el, config) {
	ITechs.QuickFormP.superclass.constructor.call(this, el, config);
	if (!this.waitMsgTarget && this.el) {
		this.waitMsgTarget = this.el.dom.parentNode;
	}
};

Ext.extend(ITechs.QuickFormP, Ext.form.BasicForm, {
	errorReader: new ITechs.ErrorsReader(),

	submit : function(options){
		var dop = {
    		waitMsg: 'Sending request'
    	};
    	if (options && !options.waitMsg) {
	        Ext.applyIf(options, dop);
	    } else {
	    	options = dop;
	    }
        this.doAction('submit', options);
        return this;
    },

	afterAction : function(action, success){
        if (action.response && action.response.responseText != '') {
	        action.serverResult = eval('('+action.response.responseText+')');
	    } else {
		    action.serverResult = {};
	    }
        if(!this.stopMessages && success){
        	if (action.type == 'submit' && action.result && action.result.errors && action.result.errors.length > 0) {
				ITechs.displayMessages(action.result.errors, false, ITechs.QuickFormP.superclass.afterAction.createDelegate(this, [action, success]));
            	return true;
            }
        }
        ITechs.QuickFormP.superclass.afterAction.call(this, action, success);
    },

    markInvalid: function(errors) {
    	if (!this.stopMessages) {
	    	ITechs.displayMessages(errors, true);
		} else {
			ITechs.QuickFormP.superclass.markInvalid.call(this, errors);
		}
    }
});


ITechs.QuickForm = function(el, config) {
	ITechs.QuickForm.superclass.constructor.call(this, el, config);
	if (!config || !config.fieldInvalidClass) {
		this.fieldInvalidClass = 'x-form-invalid';
	}
	if (!this.waitMsgTarget && this.withoutMask != true && this.el) {
		this.waitMsgTarget = this.el.dom.parentNode;
	}
	this._fieldsList = {};
	for(var i=0; i<this.el.dom.elements.length; i++) {
		var el = this.el.dom.elements[i];
		var key = el.getAttribute("_dIndex");
		if (!key) continue;
		this._fieldsList[key] = Ext.get(el);
	}
	if (this.unsetErrorsReader) {
		this.errorReader = null;
	}
};

Ext.extend(ITechs.QuickForm, Ext.form.BasicForm, {
	errorReader: new ITechs.ErrorsReader(),

	afterAction : function(action, success){
        if (action.type == 'submit') {
	        if (action.response.responseText != '') {
		        action.serverResult = eval('('+action.response.responseText+')');
		    } else {
			    action.serverResult = {};
		    }
		    if(success && (action.result.errors || action.result.messages)){
        		var list = action.result.errors ? action.result.errors : action.result.messages;
        		ITechs.displayMessages(list, false, ITechs.QuickForm.superclass.afterAction.createDelegate(this, [action, success]));
        		this.clearInvalid();
        		return true;
	        }
	    }
        ITechs.QuickForm.superclass.afterAction.call(this, action, success);
    },

    beforeAction : function(action){
        if(this.waitMsgTarget === true){
            /*'<br />', 'x-mask-loading'*/
            this.el.mask();
        }else if(this.waitMsgTarget){
            this.waitMsgTarget = Ext.get(this.waitMsgTarget);
            this.waitMsgTarget.mask();
        }else{
            Ext.fly(document.body).mask();
        }
    },

    markInvalid: function(errors) {
        var c = 0;
        for (var fname in this._fieldsList) {
        	var f = this._fieldsList[fname];
        	if (errors[fname]) {
        		f.dom.qtip = errors[fname];
        		f.addClass(this.fieldInvalidClass);
        	} else {
        		f.removeClass(this.fieldInvalidClass);
        		f.dom.qtip = '';
        	}
        	c++;
        }
        if (c == 0 || errors instanceof Array) {
        	if (!this._errorsTarget) {
        		this._errorsTarget = Ext.DomHelper.insertBefore(this.el, {tag: 'div', style:'text-align: center; padding-bottom: 6px; color: red;'});
        	}
        	this._errorsTarget.innerHTML = ITechs._prepearMsg(errors);
        }
        return this;
    },

    clearInvalid : function(){
        var c = 0;
        for (var fname in this._fieldsList) {
    		var f = this._fieldsList[fname];
    		f.removeClass(this.fieldInvalidClass);
        	f.dom.qtip = '';
        	c++;
        }
        if (this._errorsTarget) {
        	this._errorsTarget.innerHTML = '';
        }
    }
});


ITechs.FormPanelWithQuickForm = function(config) {
	ITechs.FormPanelWithQuickForm.superclass.constructor.call(this, config);
};

Ext.extend(ITechs.FormPanelWithQuickForm, Ext.form.FormPanel, {
	createForm: function(){
        delete this.initialConfig.listeners;
        return new ITechs.QuickFormP(null, this.initialConfig);
    }
});

function htmlspecialchars(val) {
	if (val) {
		try {
			var res = val.replace(/&/g, "&amp;").
						replace(/</g, "&lt;").
						replace(/>/g, "&gt;").
						replace(/\"/g, "&quot;").
						replace(/\'/g, "&#039;");
			return res;
		} catch(e) {
			return '';
		}
	} else {
		return "";
	}
}

var enable_btn = function(btn, mode) {
	if (!mode) {
		btn.addClass('disabled_btn');
	} else {
		btn.removeClass('disabled_btn');
	}
	var b_dom = btn.dom ? btn.dom : btn;
	if (b_dom.ico && b_dom.ico.dd_mod != 'off') {
		b_dom.ico.src = !mode ? b_dom.ico.disabled_src : b_dom.ico.enabled_src;
	} else if (!b_dom.ico) {
		var fc = b_dom.firstChild;
		if (fc && fc.tagName == 'IMG') {
			var disabled_src = fc.getAttribute('dis_src');
			if (disabled_src) {
				b_dom.ico = fc;
				b_dom.ico.disabled_src = disabled_src;
				b_dom.ico.enabled_src = fc.src;
				b_dom.ico.src = !mode ?  b_dom.ico.disabled_src :  b_dom.ico.enabled_src;
				return;
			}

		}
		b_dom.ico = {dd_mod: 'off'};
	}
};

Ext.DatePicker.prototype.startDay = 1;