define([
		"dojo/_base/declare",
		"dojo/ready", 
		"dojo/store/Memory", 
		"dojo/store/Cache",
		"chy/store/Json", 
		"dijit/form/ComboBox",
		"dojo/request",
		"dojo/dom",
		"dojo/dom-construct",
		"dojo/_base/lang",
		"dojo/data/util/filter",
		"dojo/when",
		"dijit/registry",
		"dojo/text!chy/form/templates/PopupJson.html",
		"dojo/_base/array",
		"dojox/form/Manager",
		"dojo/date/locale",
		"chy/_base/_ValidateMixin",
	], function(declare,ready, Memory,Cache, Json, ComboBox,request,dom,domc,lang,filter,when,reg,template,array,Manager,locale,_ValidateMixin){
		
		return declare("chy.form.PopupJson",[ComboBox,_ValidateMixin],{
			templateString: template,
            store: null,
            searchAttr: "name",
            queryExpr:"${0}",
            autoComplete: false,
            required:false,
            isRequired:false,
            hasDownArrow:false,
            hasArrow:false,
            labelAttr: 'name',
            labelType: "html",
            dataUrl:'',
            useLabel:false,
            html5placeHolder:"",
            formId:null,
            hiddenId:null,
			mapping: null,
			placeHolder: 'Zoeken...',
            
            //placeHolder : placeHolder,
            
            //
            constructor: function(args){
			   declare.safeMixin(this,args);
				//console.log('Load Combobox',args);
		   		if (this.useLabel) {
					this.labelAttr = "label";	
				}
				
				this.html5placeHolder=this.placeHolder;
				//this.placeHolder=null;
								
				this.hasDownArrow=this.hasArrow;
				this.required=this.isRequired;
				this.hiddenId=this.id + "_id";
				
				if (this.dataUrl !='') {
					this.store=new Json({idProperty:"value"})
					this.store.target=this.dataUrl;
        			this.store.startLength=3;
				}	
			   
				this.inherited(arguments);
		    },
		    
		    postMixInProperties:function(){
		    	this.set("placeHolder","");
		    	
		    	this.inherited(arguments);
		    },
		    
		    buildRendering:function(){
		    	this.inherited(arguments);
		    	if (!this.hasArrow){
		    		this._buttonNode.style="display:none;";
		    	}
		    },
            
            _getDisplayQueryString: function(/*String*/ text){
            	if(text && text.replace) {
					return text.replace(/([\\\*\?])/g, "\\$1");
				}
				else { return ''; }
			},
            onChange: function(e)
            {
            	console.log("Combobox onchange",e,this.item);
				if(this.item==null)
            	{
            		var query = lang.clone(this.query);
            		// Generate query
			
					var qs = this._getDisplayQueryString(e), q;
					q = filter.patternToRegExp(qs, this.ignoreCase);
					q.toString = function(){ return qs; };
					this._lastQuery = query[this.searchAttr] = q;
					
					var options = {
						ignoreCase: this.ignoreCase,
						deep: true
					};
					
					lang.mixin(options, this.fetchProperties);
					this._fetchHandle = this.store.query(query, options);
					var _this = this;
					when(this._fetchHandle, function(result){
						_this._fetchHandle = null;
						console.log(result);
						if (result.length)
						{
							_this.set('item',result[0]);
							dom.byId(_this.id+"_id").value=result[0].value;
						} else {
							dom.byId(_this.id+"_id").value=null;	
						}
					}, function(err){
						console.error(err);
					});
		            		
            	} else {
            		if (this.mapping!=null) {
            			var _this = this;
            			array.forEach(_this.item.mappingvalues, function(mapValue, i){
	            			array.forEach(_this.mapping, function(formMap, j){
	            				if(formMap.source == mapValue.source) {
	            					console.log("Mapping Value", formMap, mapValue);
									if(mapValue.value == null){
										mapValue.value = '';
									}
									//set value with formmanager
									reg.byId(_this.formId).formNodeValue(formMap.target, mapValue.value);
	            				}
            				}); 
            			});
						this.hiddenField.value=this.item.value;
            		}
            		if (this.store!=null && this.item != null) {
	            		var tmpitem = this.item;
	            		if(tmpitem.target && dom.byId(this.formId+"_target")) {
	            			dom.byId(this.formId+"_target").value = tmpitem.target;
	            		}
	            		if(this.item.disabled) {
	            			this.set('value',this._lastQuery);
	            		}
	            		else {
	            			dom.byId(this.id+"_id").value=tmpitem.value;
	            		}
	            		
	            		if(tmpitem.submit) {
	            			//alert('do post' + getForm(KPWindowFindParent(this)).id);
	            			getForm(KPWindowFindParent(this)).onsubmit();
	            			//KPWindowDoPost('kpwindowbordertop','search');
	            			//reg.byId(getForm(KPWindowFindParent(this)).id).submit();
	            		}
	            	} else {
	            		dom.byId(this.id+"_id").value=this.item.value;
	            	}
            	}
            }
        });
});
