// TODO: integrate render functions...
function renderIcon(val)
{
	return (val ? '<img src="' + Ext.BLANK_IMAGE_URL + '" width="16" height="16" border="0" class="' + val + '" />' : '');
}
function renderCheckbox(val)
{
	return '<img src="' + Ext.BLANK_IMAGE_URL + '" width="16" height="16" border="0" class="x-tree-node-checkbox-' + (val == 1 ? '1' : '0') + '" />';
}
function renderDate(val)
{
	if(val && val.dateFormat) return formatDate(val);
	// converts '2007-10-20 14:30:13' to '10.20.2007 14:30', and '2007-10-20' to '10.20.2007'
	return (val && val.slice(0, 4) != '0000' ? (val.slice(8, 10) + '.' + val.slice(5, 7) + '.' + val.slice(0, 4) + (val.length >= 16 ? (' ' + val.slice(11, 16)) : '')) : '');
}
function formatDate(value){
	return value ? value.dateFormat('d.m.Y') : '';
}
function renderNl2Br(val)
{
	return (val?Ext.util.Format.nl2br(val):'');
}
function renderHtml(val)
{
	return (val?unescape(val):'');
}
function renderSelectValue(val,cell,record)
{
	var field = Ext.getCmp(record.store.bindedIdPrefix + this.editFieldId);
	var r = field.findRecord(field.valueField, val);
	if(r)
	{
		return r.data[field.displayField];
	}
	else
	{
		return val;
	}
}

function identicalPassword(val)
{
	var compareField = Ext.getCmp(this.compareFieldId);
	
	return val==compareField.getValue()?true:Ext.inCMS.labels.field_passwordsnotsame;
}

/*
base functions used in backend and frontend
*/

Ext.base = function(){
    var msgCt;

    /*function createBox(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('');
    }*/
    function createBox(t, s, i){
        return ['<div class="msgbox">',
                '<h3 class="', i, '">', t, '</h3>', '<p>', s, '</p>',
                '</div>'].join('');
    }
    return {
    	// animated msg box
        msg : function(title, format, icon){
            if(!msgCt){
                msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
            }
            msgCt.alignTo(document, 't-t');
            var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
            var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s, icon)}, true);
            m.slideIn('t').pause(1).ghost("t", {remove:true});
        },
        
        // standardised form msg repsonse
        responseMsg: function(form, response)
        {
        	if(response.failureType == 'client')
        	{
        		Ext.MessageBox.show({
		           title: $l('error_message_check'),
		           msg: $l('error_message_correct'),
		           buttons: Ext.MessageBox.OK,
		           icon: Ext.MessageBox.ERROR,
		           animEl: form.el
				});
				
				return;
        	}
        	
        	var params = response.options.params;
			var data = Ext.decode(response.response.responseText);
			var icon, buttons;

			if(data.msg)
			{
				switch(data.icon)
				{
					case 'error':
						icon = Ext.MessageBox.ERROR;
					break;
					
					case 'warning':
						icon = Ext.MessageBox.WARNING;
					break;
					
					default:
						icon = Ext.MessageBox.INFO;
				}
				
				
				Ext.MessageBox.show({
		           title: data.title || '',
		           msg: data.msg,
		           buttons: Ext.MessageBox.OK,
		           icon: icon,
		           animEl: form.el
				});
			}
        },
        
        // standardised form statusbar repsonse (needs Ext.ux.ValidationStatus plugin)
        responseStatus: function(fp, response)
        {
        	// reset temporary values?
        	if(fp.tmpVals) fp.setValues(fp.tmpVals);
        	
        	//var params = response.options.params;
			var data = Ext.decode(response.response.responseText);
			var sb = Ext.getCmp(fp.statusBarId);
            
            sb.setStatus({
                text: data.msg || '', 
                iconCls: data.iconCls || '',
                clear: true
            });
            
            fp.getEl().unmask();
        },
        
        // grid helpers
        gridColMap: function(def)
        {
        	var colMapping = [];
			for(var c = 0; c < def.length; c++ )
			{
				// if no dataIndex is set, use id
				if(!def[c].dataIndex && def[c].id)
				{
					def[c].dataIndex = def[c].id
				}
				
				colMapping[c] = {
					name: def[c].dataIndex
				};
				
				switch(def[c].type)
				{
					case 'int':
						colMapping[c]['type'] = 'int';
					break;
					/*case 'date':
						colMapping[c]['type'] = 'date';
						colMapping[c]['dateFormat'] = 'Y-m-d';
					break;
					
					case 'datetime':
						colMapping[c]['type'] = 'date';
						colMapping[c]['dateFormat'] = 'Y-m-d H:i:s';
					break;*/
				}
				 
			}
			return colMapping;
        },
        
        gridColModel: function(def, gridId)
        {
        	for(var c = 0; c < def.length; c++ )
			{
				// if no dataIndex is set, use id
				if(!def[c].dataIndex && def[c].id)
				{
					def[c].dataIndex = def[c].id
				}
				
				switch(def[c].type)
				{
					case 'date':
						def[c].renderer = Ext.util.Format.dateRenderer('d.m.Y');
						delete def[c].type;
					break;
					
					case 'datetime':
						def[c].renderer = Ext.util.Format.dateRenderer('d.m.Y H:i');
						delete def[c].type;
					break;
					
					case 'select':
						def[c].renderer = Ext.base.selectRenderer(def[c].editor.options);
						delete def[c].type;
					break;
					
					case 'checkbox':
						def[c].renderer = Ext.base.checkboxRenderer(def[c].editor.options);
						delete def[c].type;
					break;
				}
				
				if(def[c].editor)
				{
					switch(def[c].editor.inputType)
					{
						case 'text':
							def[c].editor = new Ext.form.TextField({});
						break;
						
						case 'number':
							def[c].editor = new Ext.form.NumberField({});
						break;
						
						case 'select':
							var tmpOptionsArray = [];
							for(var i in def[c].editor.options)
							{
								tmpOptionsArray[tmpOptionsArray.length] = [i,def[c].editor.options[i]];
							}
						
							def[c].editor = new Ext.form.ComboBox({
								typeAhead: true,
								triggerAction: 'all',
								displayField: 'val',
								valueField: 'key',
								mode: 'local',
								store: new Ext.data.SimpleStore({
									fields: ['key', 'val'],
									data: tmpOptionsArray
								}),
								lazyRender: true,
								listClass: 'x-combo-list-small'
				            });
			            break;
			            
			            case 'checkbox':
							def[c].editor = new Ext.form.Checkbox({});
						break;
						
						case 'datefield':
							def[c].editor = new Ext.form.DateField({
								format: 'd.m.Y'
							});
						break;
					}
				}
			}
			
			return def;
        },
        
        gridFilterMap: function(def, lists)
        {
        	var filterMapping = [];
			for(var c = 0; c < def.length; c++ )
			{
				// no filter, no entry
				if(!def[c].filter) continue;
				
				// if no dataIndex is set, use id
				if(!def[c].dataIndex && def[c].id)
				{
					def[c].dataIndex = def[c].id
				}
				
				filterMapping[filterMapping.length] = {
					dataIndex: def[c].dataIndex,
					type: def[c].filter
				};
				//console.debug(lists,def[c].dataIndex);
				// list type needs options
				if(def[c].filter == 'list')
				{
					lists = lists || [];
					filterMapping[filterMapping.length-1]['options'] = lists[def[c].dataIndex] || [];
				}
			}
			return filterMapping;
        },
        
		checkboxRenderer : function(options){
            return function(v){
               return '<img src="' + Ext.BLANK_IMAGE_URL + '" width="16" height="16" border="0" class="x-tree-node-checkbox-' + (v === true || parseInt(v)>0?'1':'0') + '" />';
            };
        },
        
        selectRenderer : function(options){
            return function(v){
                return options[v];
            };
        }
    }
}();

Ext.onReady(function(){
	Ext.inCMS.labelMapper = function(A) {
		this.map = A || {}
	}; 
	
	// lovely label implementation
	Ext.extend(Ext.inCMS.labelMapper, Ext.util.Observable, {
	   get : function(A) {
	      var B = this.map[A] || (A + " undefined!"); if(arguments.length > 1 && B.indexOf("{") >= 0) {
	         B = new Ext.Template(B).apply(Array.prototype.slice.call(arguments, 1))}
	      return B}
	   }
	);
	
	var allLabels = Ext.inCMS.labels || {};
	
	for(var i in Ext.inCMS)
	{
		if(typeof(Ext.inCMS[i]) == 'object' && Ext.inCMS[i] != null)
		{
			if(Ext.inCMS[i].labels)
			{
				for(var il in Ext.inCMS[i].labels)
				{
					allLabels[il] = Ext.inCMS[i].labels[il];
				}
			}
		}
	}
	
	var locale = new Ext.inCMS.labelMapper(allLabels); 
	$l = locale.get.createDelegate(locale);
});