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

ITechs = {
	displayMessages: function(messages, is_errors, fn, scope, callback_params) {
		var msg = "";
		if (!callback_params) {
			callback_params = [];//IE fix
		}
		if (messages) {
			for(var i=0; i < messages.length; i++) {
				if (i > 0) msg += "<br>";
				msg += messages[i];
			}
		}
		if (msg != "") {
			var title = "Information";
			if (is_errors == true) {
				title = "Error";
			}

			Ext.MessageBox.alert(title, msg, function(){if (fn) fn.apply(scope, callback_params)});
		} else if (typeof fn == 'function') {
			fn.apply(scope, callback_params);
		}
	},

	requestMaskEl: 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 (opt.requestMaskEl) {
				opt.requestMaskEl.unmask();
			}
			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
    	};
    	if (this.requestMaskEl) {
    		conf.requestMaskEl = this.requestMaskEl;
    		this.requestMaskEl.mask(' Loading... ');
    	}
    	var Lconnect = new Ext.data.Connection(conf);
    	Lconnect.request(conf);
	}
};

/*
Ext.data.Connection.prototype.handleResponseReal = Ext.data.Connection.prototype.handleResponse;
Ext.data.Connection.handleResponse = function(response) {
	if (response.responseText == "LOGOUT") {
		document.location = 'logout.php';
	} else {
		this.handleResponseReal(response);
	}
};
*/

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

/** ITechs.SimpleFilter *************/
ITechs.SimpleFilter = function(oForm, dataSource) {
	this.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 = {
	_getLimit: function() {
		if (!this._need_limit) return true;
		if (this.ds.lastOptions.params && this.ds.lastOptions.params.limit > 0) {
			this.limit = this.ds.lastOptions.params.limit;
		}
		this._need_limit = false;
	},

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

	_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;
	},

	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;
		}
	}
};

ITechs.dateRender = function(value) {
	var to_format = 'Y-m-d';

	var from_format = 'U';

	if(!value || value instanceof Date){
        return value;
    }
    if (value == '0') {
    	return '';
    } else if (value == 'now') {
    	value = '0';
    }

    value = Date.parseDate(value, from_format);
    if (value) {
    	return value.dateFormat(to_format);
    } else {
    	return value;
    }
};



/*var linesReadyNotify = function(socket, id){};*/

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
	    };
    }
};

ITechs.QuickForm = function(el, config) {
	ITechs.QuickForm.superclass.constructor.call(this, el, config);

	if (!this.waitMsgTarget && this.el) {
		this.waitMsgTarget = this.el.dom.parentNode;
	}
};

Ext.extend(ITechs.QuickForm, 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 (success) {
        	action.serverResult = eval('('+action.response.responseText+')');
    	} else {
    		action.serverResult = {};
    	}
        if (action.result) {
	        if (action.type == 'submit' && action.result.errors && action.result.errors.length > 0) {
				ITechs.displayMessages(action.result.errors, !success, ITechs.QuickForm.superclass.afterAction.createDelegate(this, [action, success]));
	        	return true;
	        }
		}
        ITechs.QuickForm.superclass.afterAction.call(this, action, success);
    },

    markInvalid: function(errors) {
    	ITechs.displayMessages(errors, true);
    }
});


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.QuickForm(null, this.initialConfig);
    }
});
Ext.reg('ITform', ITechs.FormPanelWithQuickForm);

ITechs.dateValidator = function(val, f1,f2, d) {
	var start_date = 'birth_date_old';
	var deadline = 'now';
	var delimiter = '/';

/*	if (f1 && (typeof f1 == 'string') && f1 != '') {
		start_date = f1;
	}

	if (f2 && (typeof f2 == 'string') && f2 != '') {
		deadline = f2;
	}

	if (d && (typeof d == 'string') && d != '') {
		delimiter = d;
	}
*/
	if (this._form) {
		var form = this._form;
		if (form.items.length) {
			var startDate = form.findField(start_date);
			var deadline = form.findField(deadline);
			

			if (startDate && deadline) {
				if ((typeof startDate.value != 'undefined' && startDate.value != '') && (typeof deadline.value != 'undefined' && deadline.value != '')) {
		            var sd = startDate.value.split(delimiter);
					// old d/m/y
					// new m/d/y
		            var startTime = parseInt(sd[0], 10) * 2592000; //31104000; 
		            startTime += parseInt(sd[1], 10) * 86400;//2592000;
		            startTime += parseInt(sd[2], 10) * 31104000;

		            var dl = deadline.value.split(delimiter);
		            var deadTime = parseInt(dl[0], 10) * 2592000;
		            deadTime += parseInt(dl[1], 10) * 86400;
		            deadTime += parseInt(dl[2], 10) * 31104000;

		            if (startTime > deadTime) {
		                return false;
					} else {
						startDate.clearInvalid();
						deadline.clearInvalid();
					}
				}
			}else{

			}
		}
	}
	return true;
};
/*
ITechs.dateValidator.prototype = {
	dateFieldId1: null,
	dateFieldId2: null,

	dateField1: null,
	dateField2: null,

	init: function(dateField_1, dateField_2) {
		this.dateFieldId1 = dateField_1;
		this.dateFieldId2 = dateField_2;
		return this;
	},

	validate: function() {
		if (!this.dateField1) {
			this.dateField1 = Ext.getDom(this.dateFieldId1);
		}
		if (!this.dateField2) {
			this.dateField2 = Ext.getDom(this.dateFieldId2);
		}

	    if (this.dateField1 && this.dateField2) {
	        if (this.dateField1.value != '' && this.dateField2.value != '') {
	            if (this.dateField1.value > this.dateField2.value) {
	                return false;
	            } else {

	            }
	        }
	        return true;
	    } else {
	        return false;
	    }
	}
};
*/
/*
ITechs.dateValidator = function(el1, el2) {
    if (el1 && el2) {
        if (el1.value != '' && el2.value != '') {
            if (el1.value > el2.value) {
                return false;
            }
        }
        return true;
    } else {
        return false;
    }
};
*/
/**
 *
 * 	It does something like htmlspecialchars function in PHP.
 *
 * 	@param string - value
 * 	@return string - safely to show string
 *
 */
function htmlspecialchars(val) {
	if (val) {
		try {
/*			var res = val.replace(/&/g, "&amp;").
						replace(/</g, "&lt;").
						replace(/>/g, "&gt;").
						replace(/\"/g, "&quot;").
						replace(/\'/g, "&#039;");*/
			var res = val.replace(/</g, "&lt;").
						replace(/>/g, "&gt;");
			return res;
		} catch(e) {
			return '';
		}
	} else {
		return "";
	}
}

function htmlspecialcharsForCombobox(val) {
	if (val) {
		return	new Ext.XTemplate('<tpl for="."><div class="x-combo-list-item">{[htmlspecialchars(values.' + val + ')]}</div></tpl>');
	} else {
		return 'Error. Check function params';
	}
}

function debug(_var, info_str, _need_return) {
	var str = '';
	if (typeof _var == 'object') {
		if (_var.length) {
			str += '[';
			for(var i=0; i<_var.length; i++) {
				str += i + ' => ';
				if (typeof _var == 'object') {
					str += debug(_var[i], '', true);
				} else {
					str += _var[i];
				}
				if (i < _var.length-1) {
					str += ",\r\n"
				}
			}
			str += ']'
		} else {
			for(var i in _var) {
				str += i + ' => {';
				if (typeof _var == 'object') {
					str += debug(_var[i], '', true);
				} else {
					str += _var[i];
				}
				str += '}\r\n'
			}
		}
	} else {
		str += _var;
	}
	if (_need_return) {
		return str;
	} else {
		alert(info_str + ' => ' + str);
	}
}

/**
 *
 * Patch for PagingToolbar.
 * It will jump to last existen page if missed page has been loaded
 * ExtJS version: 2.0
 *
 */

// Store original (non-overriden) method in prototype
/*Ext.PagingToolbar.prototype.onLoad_overriden = Ext.PagingToolbar.prototype.onLoad;
Ext.override(Ext.PagingToolbar, {
    onLoad : function(ds, r, o){
		if (this.store.getTotalCount() > 0 && o && o.params && o.params.start >= this.store.getTotalCount()) {
   			var total = this.store.getTotalCount();
	   		var extra = total % this.pageSize;
			var lastStart = extra ? (total - extra) : total-this.pageSize;
	   		this.store.load({params:{start: lastStart, limit: this.pageSize}});
	   		return;
		}
		// Call original (non-overriden) method
	  	this.onLoad_overriden(ds, r, o);
	}
});*/

Ext.override(Ext.form.BasicForm, {
	setValues: function(values){
        if(values instanceof Array){ // 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(typeof values[id] != 'function' && (field = this.findField(id))){
                    if (field.xtype == 'radio') {
                           var f_list = {};
                           this.items.each(function(f){
                               if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
                                   f_list[f.inputValue] = f;
                               }
                           });
                           var setted = false;
                           if (f_list[values[id]]) {
                                f_list[values[id]].setValue('true');
                           } else {
                                field.setValue('true');
                           }
                    } else {
                         field.setValue(values[id]);
                         if(this.trackResetOnLoad){
                             field.originalValue = field.getValue();
                         }
                         }
                }
            }
        }
	}
})