define([
    "dojo/_base/declare",
    "./_RequestMixin",
    "./_MessagesMixin",
    "dojo/dom",
	"dojo/dom-attr",
    "dojo/query",
    "dojo/_base/window",
    "dijit/Tooltip",
    "dojox/html/_base",
    "dojo/has", 
    "dojo/sniff"
], function(declare, req, mess, dom, attr, query, win, Tooltip,html,has,sniff){
	return declare("chy._base._FormMixin", [req,mess], {
		// public
		
		defaultTarget: "content",

		//privates
				
		/*
		* override by implemtation
		*/
		displayLoad: function(){
			
		},
		
		post:function(frm,trgt){},
		
		//members
		getForm: function(trgt){
			var nl;
			if (trgt==null || trgt.length ==0) {
				trgt=this.defaultTarget;
			}
			nl=query("#" + trgt + " form");
			if(nl.length>0)
			{
				return nl[0];
			}

			nl=query("form");
			if(nl.length>0)
			{
				return nl[0];
			}
			
		},
		
		getTrgtObj: function(trgt){
			var obj=dom.byId(trgt);
			if (obj==null){
				return win.doc;
			}
			return obj;
		},

		clntSub: function ( ddDiagTarget, trgt, expire, validate )
		{ // Submit initiated from the client with support of targets ( submit another form then the one having the button defined )
		  // The client submit button must have an associated hidden field ddDiagTarget so the receiver knows which button is pressed. 
		  // For backwards compatibility a check in subButton is also made.
		  	
	  	  	validate = typeof validate !== 'undefined' && validate == 'false' ? false : true;

		  	
		  	var obj, subField;
		  	var frm=this.getForm(trgt);
		  	
		  	if (frm==null || frm.nodeName!='FORM'){
		  		return false;
		  	}
		  	
		  	for( var i = 0; i <frm.elements.length; i++ ) {
				if( (frm.elements[ i ].type == "radio" || frm.elements[ i ].type == "checkbox" ) && frm.elements[ i ].name.indexOf( 'foldercheck' ) > 0 )
				{
					if( frm.elements[ i ].checked )
					{ // Set the hidden field on position [ i + 1 ] which is related to the radio box 
						frm.elements[ i + 1 ].value = frm.elements[ i ].value
					}
				}
				// Same deal for text fields
				if( frm.elements[ i ].type == "text" &&  frm.elements[ i ].name.indexOf( 'foldertext_' ) >= 0 )
				{
					if( frm.elements[ i ].value == '' )
					{ // Set the hidden field on position [ i + 1 ] which is related to the radio box 
						frm.elements[ i + 1 ].value = '';
					} else {
						frm.elements[ i + 1 ].value = frm.elements[ i ].name.substring(frm.elements[ i ].name.lastIndexOf('_')+1);	
					}
				}
			}
		  	
			if((validate  && this.checkForm( frm, trgt )) || !validate )
			{
				obj = this.getTrgtObj( trgt );
				subField = ( frm.elements[ 'DD_DIAG_TARGET' ] ) ? 'DD_DIAG_TARGET' : ( frm.elements[ 'subButton' ] ) ? 'subButton' : undef;
				if( frm.elements[ subField ] )
				{
					if( frm.elements[ subField ].type )
					{
						if( frm.elements[ subField ].type == 'hidden' )
						{
							if( frm.elements[ 'DD_SAVE' ] && frm.DD_SAVE.value == 1 )
							{ // Prevent posting of out of date data
								alert( translate[lang]['clntSub_msg1']);
							}
							else
							{
								
								if( frm.elements[ 'DD_SAVE' ] && (!expire || expire =='true') )
								{ // Expire the page if we want to
									frm.DD_SAVE.value = 1;
								}
								
								if(ddDiagTarget==''){
									ddDiagTarget = frm.elements[ subField ].value;
								}
								
								frm.elements[ subField ].value = ddDiagTarget;
								this.post(frm,trgt);
							}
						}
					}
				}
				else
				{
					alert(translate[lang]['clntSub_msg2'] );
				}
			}
			else {
				subField = ( frm.elements[ 'DD_DIAG_TARGET' ] ) ? 'DD_DIAG_TARGET' : ( frm.elements[ 'subButton' ] ) ? 'subButton' : undef;
				frm.elements[ subField ].value = ddDiagTarget;
				this.closeMessage();
			}
		},
		checkForm:function( frm, trgt, nowarning )
		{ // overwrite of the dd.js onsubmit event 
		// set the selected values of the radio groups in the hidden field related to the 
		// radio to make sure that the selected value are passed when the form is posted.
		
		for( var i = 0; i < frm.elements.length; i++ )
		{
			if( (frm.elements[ i ].type == "radio" || frm.elements[ i ].type == "checkbox" ) && frm.elements[ i ].name.indexOf( 'foldercheck' ) > 0 )
			{
				if( frm.elements[ i ].checked )
				{ // Set the hidden field on position [ i + 1 ] which is related to the radio box 
					frm.elements[ i + 1 ].value = frm.elements[ i ].value
				}
			}
			// Same deal for text fields
			;
			if( frm.elements[ i ].type == "text" &&  frm.elements[ i ].name.indexOf( 'foldertext_' ) >= 0 )
			{
				if( frm.elements[ i ].value == '' )
				{ // Set the hidden field on position [ i + 1 ] which is related to the radio box 
					frm.elements[ i + 1 ].value = '';
				} else {
					frm.elements[ i + 1 ].value = frm.elements[ i ].name.substring(frm.elements[ i ].name.lastIndexOf('_')+1);	
				}
					
				/*if( getProperty( indexOfEntries[ window.document.my.elements[ i ].indxID ].property, 'obligate' ) == 'true' )
				{ // Add the mandatory fields to the list of mandatory fields which is stored in the dd hidden
				  // field obligate which is checked in dd.js
					window.document.my.obligate.value = ( window.document.my.obligate.value ) ?
						window.document.my.obligate.value + ',' + window.document.my.elements[ i ].name :
						window.document.my.elements[ i ].name
					window.document.my.elements[ i ].label = indexOfEntries[ window.document.my.elements[ i ].indxID ].desc
				}*/
			}
		}
		var chkMand = this.checkMandatory(frm);
		var chkVali = validateForm(frm, false, true, false, true, 17, false, '');
		
		if(nowarning == null || nowarning == undefined) { nowarning = false; }
		
		if (chkMand && chkVali && nowarning == true){
			return true;
		}
		else if (chkMand && chkVali){
			return validateForm(frm, false, true, false, true, 0, true, trgt);
			
		}
		return false ;
		// Wrapper
		/*			var chkVali = true;
			var chkMand = true;

			//chkMand = checkMandatory( trgt );
			if (chkMand) chkVali = validateForm(frm, false, false, false, true, 8, false, '');	
			if (chkMand && chkVali) return true;
			return false ;*/
		},
		checkMandatory: function( frm )
		{   
			
			// Check the comma separated list of fields in the hidden field obligate for values
			var fldName, fldObj, stat = true, errMsg = "", flag = 0;
			//var frm = this.getForm( trgt );
			if (frm == null || frm == "" || frm == "undefined"){
				console.error("geen form");
				return false;
			}
			var mVal = frm.obligate.value;
			if( mVal != "" )
			{
				mandFields = mVal.split(",");
				for( var i=0; i < mandFields.length; i++ )
				{      
					fldObj = frm.elements[ mandFields[ i ] ];
					if (this.isNodeList(fldObj)) {
						fldObj = fldObj[0];
					}
					
					if( fldObj && fldObj.value == "" )
					{
						fldName = ( fldObj.label ) ? ( fldObj.label != ''  ? fldObj.label : fldObj.name ) : fldObj.name;
						errMsg = errMsg + translate[lang]['checkMandatory_msgPre'] + ' ' + fldName + ' ' + translate[lang]['checkMandatory_msgPost'];
						stat = false;
						if( flag == 0 )
						{
							fldObj.focus();
							flag = 1;
						}
					} 
				}
			}
			/*if( !stat )
			{
				//alert( errMsg );
			}*/
			return stat;
		},
		
		search:function(id, t){
			var fld=dom.byId(id);
			var tmpDiv=dom.byId("tempDiv");
			//var a=e;
			if (fld.value.length >= 4) {
				//alert('key up more than 4');
				Tooltip.hide(fld);
				var tooltipUrl;		
				if(t.indexOf("cddid") > -1) {
					tooltipUrl= t + "&SEARCHKEY="+fld.value;
				}
				else {
					tooltipUrl ='jsp/lookup.jsp?searchKey='+fld.value+'&targetfld=' + fld.id + '&searchTable=' + t;
				}
				this.getContent(tooltipUrl,id,function(response){
					/*html.set(tmpDiv,response.text,{
						executeScripts:true,
						parseContent: true,
						scriptHasHooks: false,
						renderStyles:false	
					});*/
					if (response.text.trim().length > 0) {
						Tooltip.show(response.text,id);
					} else {
						Tooltip.hide(id);	
					}
				});
				
			} else {
				//alert('a4');
				Tooltip.hide(fld);	
			}
			
		},
		isNodeList: function(nodes) {
		  var result = Object.prototype.toString.call(nodes);
		
	  	if (has("ie") <= 8) {
		  if (
		    typeof nodes === 'object'
		    /*&&
		    /^\[object (HTMLCollection|NodeList|Object)\]$/.test(result)*/
		    &&
		    Object.prototype.hasOwnProperty.call(nodes,'length')
		    &&
		    (nodes.length == 0 || (typeof nodes[0] === "object" && nodes[0].nodeType > 0))
		  ) {
		    return true;
		  }
	  		
	  	} else {
		  if (
		    typeof nodes === 'object'
		    &&
		    /^\[object (HTMLCollection|NodeList|RadioNodeList|Object)\]$/.test(result)
		    &&
		    /*nodes.hasOwnProperty('length')
		    &&*/
		    (nodes.length == 0 || (typeof nodes[0] === "object" && nodes[0].nodeType > 0))
		  ) {
		    return true;
		  }
		 }
		  return false;
		},
		
		/* Zet het aantal tekens dat nog kan worden ingevoerd in input 'field' in input 'cntfield',
		   en trim de tekst in 'field' tot de maximale lengte.
		   
		   Komt uit dd_treeinput.js, want is ook buiten vragenlijsten nodig
		   (verder nog niet gedojoficeerd)
		*/
		textCounter: function(field,cntfield,maxlimit) {
			var val;
			if(typeof(field.getValue) == 'undefined') {
				val = field.value;
			}
			else {
				val = field.getValue();		
			}
			
			if (typeof(maxlimit) === 'undefined') {
				maxlimit = attr.get(field, 'maxlength');
			}
			
			if (val.length > maxlimit) { // if too long...trim it!
				if(typeof(field.setValue) == 'undefined') {
					field.value = field.value.substring(0, maxlimit);
				}
				else {
					field.setValue(val.substring(0, maxlimit));
				}
			}
			else {
				cntfield.value = maxlimit - val.length;
			}		
		}
		
	});
});
