/*

Kinetics form ajax framework funcitons
Copyright® Kinetics Multimedia (www.kinetics.com.br)

*/


//iframe count for upload
var uploadct = 0;

function fieldvalue( fld )
{
	if( isdefined( fld ) ) return fld.value;
	return '';
}

// insert hidden field to create upload file iframe


	//div.innerHTML = '<img id="uploadimage'+ ident + '" src="' + src + '" onload="imgmaxdim(this,' + maxdisplay + ');uploadimgloaded(this);"><br><div id="btn_up"><form><input type="button" value="'+bottitle+'" onmouseover="position();"/></form></div><br><iframe src="' + url + '" scrolling="No" frameborder="No" id="fileiframe' + ident + '" class="uploadiframe"></iframe>';


function uploadfile( field, bottitle, maxsize, maxdisplay, obj )
{
	if( field.processed ) return;

	var ident = field.name + uploadct++;
	var bgcolor = field.getAttribute( 'bgcolor' ); if( bgcolor == null ) bgcolor = ''; bgcolor = escape( bgcolor );
	var link = field.getAttribute( 'link' ); if( link == null ) link = ''; link = escape( link );
	var div, src;
	field.id = 'hiddenupload' + ident;
	field.ident = ident;
	src = field.value;
	field.basevalue = src;
	if( src == '' ) src = 'kintool/' + csspath + '/noimage.gif';
	div = ce( 'div' );
	div.className = 'uploaddiv';
	field.parentNode.insertBefore( div, field );
	url = 'uploader.php?ident='+ ident + '&max=' + maxsize + '&maxdisplay=' + maxdisplay + '&bot=' + bottitle + '&bgcolor=' + bgcolor;

	var newdiv = ce('DIV');
	newdiv.innerHTML='<br><div id="btn_file'+ident+'" name="btn_file" style="position: absolute; width: 0px; height: 0px; overflow: hidden;"><form id="frm'+ident+'" enctype="multipart/form-data" action="uploader.php" method="POST" target="fileiframe' + ident + '"><input type="hidden" name="ident" value="'+ident+'"><input type="hidden" name="max" value="'+maxsize+'"><input type="hidden" name="maxdisplay" value="'+maxdisplay+'"><input type="hidden" name="bot" value="'+bottitle+'"><input type="hidden" name="bgcolor" value="'+bgcolor+'"><input type="hidden" name="setClass" value="'+field.getAttribute( 'setClass' )+'"><input type="File" id="fileup'+ident+'" name="file" size="1" accept="image/gif" id="file" oonchange="change(\''+ident+'\')" class="fileinpt" oonmouseout="restore(\''+ident+'\')"></form></div>';
	document.body.appendChild(newdiv);
	
	if(link==1)
		var txt= '<input type="button" value="'+bottitle+'" id="imgbutton' + ident + '"/>';
	else
		var txt= '<span id="imgbutton' + ident + '" class="'+field.getAttribute( 'setClass' )+'">'+bottitle+'</span>';

	div.innerHTML = '<img id="uploadimage'+ ident + '" src="' + src + '" onload="imgmaxdim(this,' + maxdisplay + ');uploadimgloaded(this)"><br><div id="btn_up'+ident+'">'+txt+'</div><br><iframe scrolling="No" frameborder="No" id="fileiframe' + ident + '" class="uploadiframe" name="fileiframe' + ident + '" src="" width="0" height="0"></iframe>';
	$('uploadimage'+ident).canvas = obj;
	
	if(link==1)
		formatbutton( $('imgbutton' + ident ) );				
	$('imgbutton' + ident ).ident = ident;
	$('imgbutton' + ident ).onmouseover=function(){	position( this );	}

	//getmouseover($('imgbutton' + ident ));
	field.processed = true;
}

function formatbutton( obj )
{
	 if(obj==null)
		return;	 
	 obj.className = 'button';
	 inputbackground( obj );
}
function getmouseover( obj )
{
	while(obj!=null)
	{
		debug(obj.id, obj.onmouseover);
		obj=obj.parentNode;
	}
}
var top=0;
var left=0;
function position( obj )
{
	ident=obj.ident;

	$('btn_file'+ident).style.position='absolute';
	$('btn_file'+ident).style.width=$('imgbutton' + ident ).scrollWidth;
	$('btn_file'+ident).style.height=$('imgbutton' + ident ).scrollHeight;
	$('btn_file'+ident).style.overflow='hidden';

	if(navigator.appName=='Microsoft Internet Explorer') 
	{
		$('fileup'+ident).style.position='absolute';
		$('fileup'+ident).style.top=0;
		$('fileup'+ident).style.left= -($('fileup'+ident).clientWidth + 20);	
	}

	left=getLeft($('btn_file'+ident));
	top=getTop($('btn_file'+ident));

	$('btn_file'+ident).style.left= getLeft($('btn_up'+ident));
	$('btn_file'+ident).style.top= getTop($('btn_up'+ident));
}
function restore(ident)
{
	$('btn_file'+ident).style.left=left;
	$('btn_file'+ident).style.top=top;
}
function change( ident )
{
	if($('fileup'+ident).value!='')
	{
		var frm = document.getElementById( 'frm'+ident );
		frm.submit();
	}
	//document.body.innerHTML = '<div class=loading>Uploading</div>';
}

//function called then some image file upload is completed
function uploadimgloaded( img )
{
	//$('img').value=img.src;
	var obj = img.canvas;
	if( isfunction( obj.onchange ) ) obj.onchange();
}

//function called then some file upload is completed
function uploadcomplete( ident, src, maxdisplay, w, h )
{
	var img = $('uploadimage'+ident);
	var hidden = $('hiddenupload'+ident);
	hidden.value = src;
	//CHANGES
	if ($('img')!= null) $('img').value=src;

	if( isfunction( hidden.onchange ) ) hidden.onchange();
	if ( src == '' ) src = 'kintool/' + csspath + '/noimage.gif';
	var max = Math.max( w, h );
	if( max == 0 ) max = 10000;
	var rate = max > maxdisplay ? maxdisplay/max : 1;
	w = Math.floor(w*rate);
	h = Math.floor(h*rate);
	img.src = src;
	img.style.width = w;
	img.style.height = h;
	img.onload = function() { uploadimgloaded( this );};
}

//make a AJAX POST call w = obj, f = form, nojson means dont reat result as a json response
function formsub( w, f, nojson )
{
	if( f.submiting ) return false;
	f.submiting = true;
	var json = isdefined( nojson ) ? nojson : 1;
	var fscript = json ? 'formresult' : 'resultform';
//	debug( formcontent(f) ); return false;
	ajaxrequest( nocache(f.action), fscript, w, json, 'POST', formcontent(f));
	if( isdefined( f.submitobj ) ) loading_button( f.submitobj );
	return false;
}



function formformat( obj )
{
	var tmpnew = [];
	var tmpdata = [];
	function elementvisible( el )
	{
		if( el.skip ) return 0;
		return el.clientHeight > 0;
	}
	o = obj.getElementsByTagName("FORM");
	
	//first fix classes in the form before drawing
	if( o.length )
	{
		f = o[0];
		
		
		el = f.elements;

		//reset uploaded file
		f.onreset = function()
		{
			for( i = 0 ; i < el.length ; i++ )
			{
				if( !elementvisible( el[i] ) ) continue;
				var name = el[i].name;
				formremoveerrmsg( name );
				if( el[i].type == 'hidden' && el[i].getAttribute( 'upload') == 1 )
				{
					uploadcomplete( el[i].ident, el[i].basevalue );
				}
			}
		}
		
		var focusme = null;
		for( i = 0 ; i < el.length ; i++ )
		{
			//debug(el[i].type);
			if( !elementvisible( el[i] ) ) continue;
			var label = el[i].getAttribute( 'label' );
			el[i].label = label;
			if( el[i].id == '' )
				el[i].id = el[i].label > '' ? el[i].label : el[i].name;
			el[i].helpervalue = el[i].getAttribute( 'helper' );
			if( el[i].getAttribute( 'focus' ) == 1 ) focusme = el[i];
		
			if(!ie && el[i].type == 'password' && el[i].value=='' && el[i].getAttribute('helper')!='')
			{
				el[i].setAttribute('pass', 1);
				el[i].type='text';
			}

			if( el[i].type == 'text' || el[i].type == 'password' )
			{
				if( el[i].className == '' )	el[i].className = 'inputtext';
				el[i].onfocus = function() {  inputselect( this ); };
				el[i].onblur = function() { inputfocus( this, 0 ); };
				el[i].onkeydown = function( ev ) { return inputkeytrap( this, ev ); }
				if( el[i].getAttribute('date') == 1 )
				{				
					//if(el[i].value == el[i].getAttribute('helper'))
						
					el[i].onfocus = function()
					{
						if(this.value == this.getAttribute('helper'))
							this.value = ''; 
						
						//inputfocus( this, 1 );
						inputselect( this );
						displayCalendar(this,'mm/dd/yyyy',this); 
					};
					el[i].onblur = function()
					{ 
						restoreDate(this);
						//setTimeout( function() { closeCalendar(); }, 200 );
						if(!IsMMDDYYYY(this.value))
							this.value = '';
						inputfocus( this, 0 );
					};
				}
			}
			if( el[i].type == 'password' )
			{
				if( el[i].className == '' )	el[i].className = 'inputtext';
			}
			if( 1 &&  el[i].type == 'checkbox' )
			{
				if(el[i].id=='' || !isdefined(el[i].id) || el[i].id==null || el[i]!=$(el[i].id))
					el[i].id='random'+i;

				span = document.createElement("span");
				span.id='span_'+el[i].id;
				span.auxid = el[i].id;

				el[i].oonclick=el[i].onclick;
				el[i].onclick=function()
				{
					$('span_'+this.id).onclick();
				}

				span.className = 'checkboxImg';
				span.onmouseover= function()
				{ 
					if(this.className=='checkboxImg')
						this.className='checkboxImgFocus'; 
					if(this.className=='checkboxImgChecked')
						this.className='checkboxImgCheckedFocus'; 
				
				}
				span.onmouseout= function()
				{ 
					if(this.className=='checkboxImgFocus')
						this.className='checkboxImg';
					if(this.className=='checkboxImgCheckedFocus')
						this.className='checkboxImgChecked';

				}
				span.onclick= function()
				{
					if( this.className=='checkboxImg' || this.className=='checkboxImgFocus' )
					{
						this.className='checkboxImgCheckedFocus';
						$('i_'+this.auxid).checked=true;
						$(this.auxid).checked=true;
					}
					else
					{
						this.className='checkboxImgFocus';
						$('i_'+this.auxid).checked=false;
						$(this.auxid).checked=false;
					}	
					//debug($(this.auxid).oonclick);
					if($(this.auxid).oonclick)
					{
						$(this.auxid).oonclick();
					}
					$('i_'+this.auxid).focus();

				}
				a=el[i].parentNode;
				a.insertBefore(span, el[i]);
				el[i].style.display='none';

				input = document.createElement("input");
				input.type="checkbox";
				input.id='i_'+span.auxid;
				input.auxid=span.auxid;
				input.spanid= span.id;

				input.style.position='absolute';
				input.style.left=-1000;

				input.onfocus=function()
				{
					$(this.spanid).onmouseover();
				}
				input.onblur=function()
				{
					$(this.spanid).onmouseout();
				}
				input.onchange=function()
				{
					$(this.spanid).onclick();
				}
			
				if($('div_appendCheck')==null)
				{
					div = document.createElement("DIV");
					div.id='div_appendCheck';
					div.style.position='relative';
					document.body.appendChild(div);
				}
				$('div_appendCheck').appendChild(input);

				if(el[i].checked==true)
				{
					//span.onclick();
					if( span.className=='checkboxImg' || span.className=='checkboxImgFocus' )
					{
						span.className='checkboxImgCheckedFocus';
						$('i_'+span.auxid).checked=true;
						$(span.auxid).checked=true;
					}
					else
					{
						span.className='checkboxImgFocus';
						$('i_'+span.auxid).checked=false;
						$(span.auxid).checked=false;
					}	
				}
			}
			if( el[i].type == 'textarea' )
			{
				if( el[i].className == '' )	el[i].className = 'inputtextarea';
				el[i].onfocus = function() { inputselect( this ); };
				el[i].onblur = function() { inputfocus( this, 0 ); }
				el[i].onkeydown = function( ev ) { return inputkeytrap( this, ev ); }
			}
			if( el[i].type == 'button' || el[i].type == 'submit' )
			{
				if( el[i].className == '' ) el[i].className = 'button';
				if( el[i].type == 'submit' )
				{
					el[i].frm = f;
					if( isfunction( el[i].onclick ) )
					{
						el[i].onclickold = el[i].onclick;
						el[i].onclick = function() { this.frm.submitobj = this; this.onclickold(); }

					}
					else
						el[i].onclick = function() { this.frm.submitobj = this; }
				}
				inputbackground( el[i] );
			}
			if( 1 && el[i].type == 'select-one' )
			{
				var data = new Object;
				data.records = [];
				el[i].style.display = 'none';
				for( var kk = 0 ; kk < el[i].options.length ; kk++ )
				{
					var opt = el[i].options[kk];
					data.records.push( [ el[i].options[kk].value, el[i].options[kk].text ] );
				}
				var tmpid = 'select' + Math.random();


				var helper = el[i].getAttribute( 'helper' );
				if( helper == null ) helper = '';
				var val = el[i].getAttribute( 'defaultvalue' );
				var style =  el[i].getAttribute( 'setstyle' );
				if( style == null ) style = '';
				if( val == null ) val = '';
				var name = el[i].name;
				var onchange = el[i].onchange;
				var id = el[i].id;

				var parent = el[i].parentNode;
				var span = ce('SPAN');
				parent.insertBefore( span, el[i] );
//				parent.removeChild( el[i] );
				el[i].name = 'nothing' + Math.floor(Math.random()*100000);
				el[i].skip = true;
				span.innerHTML = '<input id="' + tmpid + '" name="' + name + '" class="inputtext" type="text" predictive="1" allownew="0" usevalue="1" helper="' + helper + '" value="' + val + '" style="' + style + '">';

				$(tmpid).initdata = data;
				$(tmpid).helpervalue = helper;
				$(tmpid).onchange = onchange;
				$(tmpid).id = id;
			}
		}

		for( var i = 0 ; i < el.length ; i++ )
		{
			if( !elementvisible( el[i] ) ) continue;
			if( el[i].type == 'text' || el[i].type == 'textarea' || el[i].type == 'password' )
			{
				inputfocus( el[i], 0 );
				if( el[i].getAttribute( 'predictive') > '' )
				{
					predictive( el[i] );
				}
				inputbackground( el[i] );
			}
		}
		setTimeout( function() { formprocessuploads( el ) }, 10 );
		setTimeout( function() { formprocessselects() }, 1000 );

	}
	if( focusme != null ) { inputselect( focusme ); focusme.focus(); }

	function formprocessselects()
	{
//		alert( obj.innerHTML );
//		for( i = 0 ; i < tmpnew.length ; i++ )
//			alert( $(tmpnew[i]) );
	}

	function formprocessuploads( el )
	{
		for( i = 0 ; i < el.length ; i++ )
		{
			//if( !elementvisible( el[i].parentNode ) ) continue;
			if( el[i].type == 'hidden' && el[i].getAttribute( 'upload') == 1 )
			{
				uploadfile( el[i], el[i].getAttribute( 'button'), el[i].getAttribute( 'maxsize'), el[i].getAttribute( 'displaysize'), obj );
			}
		}
	}
}


// set the obj HTML content to txt and prepare the form tags to be used with AJAX
// if txt == null then use the current obj content

function resultform( txt, obj )
{
	var f, el, i, o;

	if( txt == null ) txt = obj.innerHTML;

	//using a tmpdiv to fix the form bc sometimes FF draws the form before changing the classes
	var tmpdiv = ce( 'DIV' );
	if( txt == null ) txt = obj.innerHTML;
	tmpdiv.innerHTML = txt;
	o = tmpdiv.getElementsByTagName("FORM");

	//first fix classes in the form before drawing
	if( o.length )
	{
		f = o[0];
		if( f.className == '' ) f.className = 'forminput';
		el = f.elements;
		for( i = 0 ; i < el.length ; i++ )
		{
			if( el[i].type == 'text' )
			{
				if( el[i].className == '' )	el[i].className = 'inputtext';
			}
			if( el[i].type == 'textarea' )
			{
				if( el[i].className == '' )	el[i].className = 'inputtextarea';
			}
			if( el[i].type == 'button' || el[i].type == 'submit' )
			{
				if( el[i].className == '' ) el[i].className = 'button';
			}
		}
	}

	//now process it inside the obj to add the event triggers
	obj.innerHTML = tmpdiv.innerHTML;
	o = obj.getElementsByTagName("FORM");
	obj.form = o;
	obj.formdiv = 1;

	if( o.length )
	{
		f = o[0];
		if( f.id == '' ) f.id = 'form' + Math.random();
		if( f.className == '' ) f.className = 'forminput';
		f.onsubmit = function() { return formsub(mywin(this),this); }
	}
	formformat( obj );

	var s = obj.getElementsByTagName("SCRIPT");
	for( i = 0 ; i < s.length ; i++ )
	{
		//alert( s[i].text )
		var ns = ce('SCRIPT');
		ns.type = 'text/javascript';
		ns.text = s[i].text;
		document.body.appendChild( ns );
	}
	for( i = 0 ; i < s.length ; i++ )
		s[i].parentNode.removeChild( s[i] );

	if( isfunction( obj.onchange ) ) obj.onchange();
}

// retira as mensagens de erro de umformulario
function formremoveerrmsg( name )
{
		var err = $(name+'_err')
		if( err != null )
		{
			err.parentNode.removeChild( err );
			err.innerHTML = '';
			err.style.display = 'none';
		}
}

function setinput( inpt, val )
{
	if( inpt == null ) return;
	if(inpt.tagName=='DIV' || inpt.tagName=='SPAN')
	{
		inpt.innerHTML=val;
		return;
	}
	if( inpt.type == 'checkbox')
	{
		//inpt.checked = val == 'true' || val == 1;
		if(val==1&&inpt.checked==false)
		{
			inpt.onclick();
		}
	}
	else if( inpt.type == 'select-one' ) selectset( inpt, val );
	else if( inpt.getAttribute( 'predictive' ) > '' )
	{
		if( inpt.usevalue )
		{
			inpt.valueid = val;
			inpt.value = '';
		}
		else inpt.value = val;
		if( isfunction( inpt.onchange ) ) inpt.onchange();
//		debug( 'pred', inpt.name, inpt.getAttribute( 'predictive' ), inpt.value );
	}
	else inpt.value = val;
	inpt.valueinit = val;

	inputfocus( inpt, 0 );
}


// retorna o conteudo post de um formulario
function formcontent( f )
{
	var obj, el, i, vals, name, val, args, err;

	obj = f;
	el = obj.elements;
	vals = new Array();
	for( i = 0 ; i < el.length ; i++ )
	{
		var name = el[i].name;
		formremoveerrmsg( name );
		if( el[i].type == 'select-one' ) { val = el[i].options[el[i].selectedIndex].value }
		else if( el[i].type == 'radio' ) val = el[i].value;
		else if( el[i].type == 'checkbox' ) val = el[i].checked;
		else
		{
			val = el[i].value;
			var def = el[i].getAttribute( 'helper' );
			if( val == def ) val = el[i].valueid = '';
			if( el[i].getAttribute( 'usevalue' ) == 1 )	val = el[i].valueid;
		}
		if( el[i].type != 'radio' || el[i].checked )
		{
			val += '';
			sval = val.replace( /\&/g, '%26' );
			vals.push( name + '=' + sval );
		}
	}
	vals[vals.length] = 'formid=' + f.id;
//	debug( vals.join('&') );
	return vals.join('&');
}


// processa o retorno XML de um form ajax. Coloca as mensagens de erro ou 
// executa as intrucoes de sucesso
function formresult( txt, obj )
{
//  debug( txt );
//	if( $('submit') != null ) $('submit').innerHTML = '';

	var form=0;
	if(obj!=null)
	{
		o = obj.getElementsByTagName("FORM");
		var obj1=o[0];
		if(obj1!=null) 
		{
			form=1;
			obj1.jsonreturn=json(txt);
		}
	}
	loading_button_out();
	var data = json( txt );
	var status = data.status + '';
	if( status == '' )
	{
//		globalerror( 'bad content on ajax form: objid = ' + obj.id + '\nreturned value=' + txt );
		debug( 'error', '<textarea rows=10 cols=40>' + txt + '</textarea>' );
	}
	status *= 1;

	if( status )
	{
		var okmess, okscript, okurl, oktitle;

		if(form==1 && isdefined(data.okparams) && obj1.getAttribute('okparams')!=null)
		{
			var func = eval( obj1.getAttribute('okparams') );
			data=func( data );
//			eval(obj1.getAttribute('okparams')+'('+data.okparams+');');
		}

		if(form==1 && (!isdefined(data.okmess) || data.okmess=='') && obj1.getAttribute('okmess')!=null){ data.okmess =obj1.getAttribute('okmess'); }
		if(form==1 && (!isdefined(data.okscript) || data.okscript=='') && obj1.getAttribute('okscript')!=null){ data.okscript =obj1.getAttribute('okscript'); }
		if(form==1 && (!isdefined(data.okurl) || data.okurl=='') && obj1.getAttribute('okurl')!=null){ data.okurl =obj1.getAttribute('okurl');}
		if(form==1 && (!isdefined(data.okajax) || data.okajax=='') && obj1.getAttribute('okajax')!=null){ data.okajax =obj1.getAttribute('okajax');}

		okmess = data.okmess;		
		if( okmess != '' ) obj.innerHTML = '';
		if( isfunction(obj.onchange) && obj.onchange != null ) obj.onchange();
		if( okmess != '' ) obj.innerHTML += okmess;
		okscript = data.okscript;		
		if( isdefined(okscript) && okscript != '' )
		{
			var ns = ce('SCRIPT');
			ns.type = 'text/javascript';
			ns.text = okscript;
			document.body.appendChild( ns );
		}
		okurl = data.okurl;
		
		if( isdefined(okurl) && okurl != '' ) document.location = okurl;
			okajax = data.okajax;
	
		if( isdefined(okajax) && okajax > '' )
		{
			obj.innerHTML = '<div class="loading"></div>';
			ajaxrequest( nocache(okajax), 'resultform', obj, 0 );
		}

		if( isfunction( obj.onsuccess ) ) obj.onsuccess();
	}
	else
	{
		var i;
		var errlist = data.errors;
		var formid = data.formid;
		var field, form, parent;
		var form = null;

//		if( 1|| formid == '' || formid == null )
			form = obj.getElementsByTagName("FORM")[0];
//		else
//			form = $(formid);
		if( form == null )
			debug( 'no valid form in div object' );

		form.submiting = false;

		var errfloat = form.getAttribute('errfloat') != null ? form.getAttribute('errfloat') : '';

		for( i = 0 ; i < errlist.length ; i++ )
		{
			var errid = errlist[i].errid + '_err';
			errobj = $(errid);
			if( errobj ) errobj.parentNode.removeChild( errobj );
			errobj = ce( 'div' );
			errobj.id = errlist[i].errid + '_err';
			errobj.className = 'error';
			errobj.style.display = 'block';
			errobj.innerHTML = errlist[i].errmess;
			if( form != null )
			{
				field = form[errlist[i].errid];
				if( field != null )
				{
					tfield = field;
					parent = field.parentNode;
					if( isdefined( field.span ) ) // if input encapsulated in a SPAN the error must go outside it
					{
						tfield = parent;
						parent = parent.parentNode;
					}

					for( j = 0 ; j < parent.childNodes.length; j++ )
					{
						if( parent.childNodes[j] == tfield ) break;
					}


					if( errfloat != '' )
					{
						document.body.appendChild( errobj );
						errobj.className = 'errbox';
						if( errobj.clientWidth > 200 ) errobj.style.width = 200;
						if( errfloat == 'left' )
						{
							errobj.style.background = 'transparent';
							errobj.style.backgroundImage = 'url( kintool/css/errleft.png)';
							errobj.style.backgroundPosition = 'center right';
							errobj.style.paddingRight = 10;
							errobj.style.top = getTop( field ) + Math.floor(( field.clientHeight - errobj.clientHeight )/2);
							errobj.style.left = getLeft( field ) - errobj.clientWidth - 2;
						}
						else if( errfloat == 'right' )
						{
							errobj.style.background = 'transparent';
							errobj.style.backgroundImage = 'url( kintool/css/errright.png)';
							errobj.style.backgroundPosition = 'center left';
							errobj.style.paddingLeft = 10;
							errobj.style.top = getTop( field ) + Math.floor(( field.clientHeight - errobj.clientHeight )/2);
							errobj.style.left = getLeft( field ) + field.clientWidth + 2;
						}
						else if( errfloat == 'top' )
						{
							errobj.style.background = 'transparent';
							errobj.style.backgroundImage = 'url( kintool/css/errtop.png)';
							errobj.style.backgroundPosition = 'bottom left';
							errobj.style.paddingBottom = 10;
							errobj.style.top = getTop( field ) - errobj.clientHeight;
							errobj.style.left = getLeft( field );
						}
						else if( errfloat == 'bottom' )
						{
							errobj.style.background = 'transparent';
							errobj.style.backgroundImage = 'url( kintool/css/errbottom.png)';
							errobj.style.backgroundPosition = 'top left';
							errobj.style.paddingTop = 10;
							errobj.style.top = getTop( field ) + field.clientHeight;
							errobj.style.left = getLeft( field );
						}
					}
					else
					{
						if( j == parent.childNodes.length-1 )
							parent.appendChild( errobj );
						else
							parent.insertBefore( errobj, parent.childNodes[j+1] );
					}
					if( i == 0 )
					{
						if(field.type == 'text' )
						{
							field.focus();
							inputselect( field );
						}
					}
				}
				else debug( 'invalid errid', errlist[i].errid, errlist[i].errmess );
			}
		}
		var errscript = data.errscript;
		if( errscript != '' )
		{
			var ns = ce('SCRIPT');
			ns.type = 'text/javascript';
			ns.text = errscript;
			document.body.appendChild( ns );
		}

	}
	if( isfunction( obj.onchange ) ) obj.onchange();

}

// find the div containing the current form
function mywin( node )
{
	while( (node.tagName != 'DIV' && !isdefined( node.formdiv )) && node != document.body )
	{
		node = node.parentNode;
	}
	return node;
}

function nohelper( o )
{
	removeclass( o, 'inputhelper' );
	return;
	cn = o.className + '';
	cn = cn.replace( / inputhelper/, '' );
	o.className = cn;
}

function focusclass( o, st )
{
	if( st )
	{
		removeclass( o, 'inputfocused' );
		addclass( o, 'inputfocused' );
	}
	else
	{
		removeclass( o, 'inputfocused' );
	}
	inputbackground( o );
}

function loading_button_out()
{
	var lb = $( 'loading_button_div' );
	if( lb != null )
		lb.parentNode.removeChild( lb );
}

function loading_button( o )
{
	loading_button_out();
	var lb = ce( 'DIV' );
	lb.className = 'loading_button';
	lb.id = 'loading_button_div';
	document.body.appendChild( lb );
	var w = lb.clientWidth;
	var h = lb.clientHeight;
	var ow = o.clientWidth;
	var oh = o.clientHeight;
	if( ow/2 < w+10 ) 
	{
		loading_button_out();
		return;
	}
	lb.style.top = getTop(o) + Math.floor((oh-h)/2);
	lb.style.left = getLeft(o) + 2;
	watch_animate( lb );
}

var inputbackgroundstack = [];
function inputbackgroundpush( o )
{
	inputbackgroundstack.push( o );
	setTimeout( inputbackgroundpop, 1 );
}

function inputbackgroundpop()
{
	var o = inputbackgroundstack.shift();
	inputbackground( o );
}

function inputbackground( o )
{
	if( !formDecorate ) return;
	if( o.type != 'text' && o.type != 'textarea' && o.type != 'submit' && o.type != 'button' && o.type != 'reset' && o.type != 'password' ) return;
	o.style.border = 0;
	var w = o.clientWidth;
	var h = o.clientHeight;
	if( h > 0 && h < 20 )
	{
		inputbackgroundpush( o );
		return;
	}
	o.style.background = 'transparent';
	var burl = '';
	var furl = '';
	if( !o.className.match( /button/ ) && !isdefined( o.span ) )
	{
		//encapsula o input num span para poder usar o background;
		var parent = o.parentNode;
		var span;
//		alert( o.name + ', ' + o.type + ', ' +  w + ', ' +  h );
		if( o.type != 'textarea' )
		{
			span = ce( 'SPAN' );
			span.style.fontSize = '100px';
			span.style.lineHeight = 'normal';
			span.style.margin = 0;
			span.style.padding = 0;
			span.style.border = 0;
			span.style.width = w;
			span.style.height = h;
			span.style.overflow = 'hidden';
		}
		else
		{
			var wmargin = 15;
			var hmargin = 20;

			wmargin = 15;
			hmarmgin = 15;
			if( !ie )
			{
				o.style.width = w - wmargin;
				o.style.height = h - hmargin;
				w -= hmargin;
				h -= hmargin;
			}
			else
			{
				o.style.width = w-wmargin;
				o.style.height = h-hmargin;
			}
			span = ce( 'DIV' );
			span.style.fontSize = '100px';
			span.style.lineHeight = 'normal';
			span.style.margin = 0;
			span.style.padding = 0;
			span.style.border = 0;
			span.style.width = w;
			span.style.height = h;
			span.style.padding = 10;
			span.style.overflow = 'hidden';
		}
		parent.insertBefore( span, o );
		parent.removeChild( o );
		span.appendChild( o );
		o.span = span;
	}
	if( !isdefined( o.span ) ) o.span = o;
	var span = o.span;
	if( o.type == 'textarea')
	{
		w = span.clientWidth;
		h = span.clientHeight;
	}
	if( o.className.match( /button/ ) )
	{
		burl = 'kintool/img.php?i=' + csspath + '/' + formButtonImg + '&t=' + formButtonImgType + '&w=' + w + '&h=' + h  + '&mh=' + formButtonMh + '&mw=' + formButtonMw;
	}
	else
	{
		var img = o.className.match( /inputfocused/ ) ? formFieldFocusedImg : formFieldImg;
		img = csspath + '/' + img;
		var iconright = '';
		if( o.className.match( /inputsel/ ) ) iconright = '&ir=' + csspath + '/predictive&irm=8';
		if( o.className.match( /inputlocksel/ ) ) iconright = '&ir=' + csspath + '/pulldown&irm=8';
		var iconleft = '';
		burl = 'kintool/img.php?i=' + img + '&t=' + formFieldImgType + '&w=' + w + '&h=' + h  + '&mh=' + formFieldMh + '&mw=' + formFieldMw + iconleft + iconright;
		furl = 'kintool/img.php?i=' + csspath + '/' + formFieldFocusedImg + '&t=' + formFieldImgType + '&w=' + w + '&h=' + h  + '&mh=' + formFieldMh + '&mw=' + formFieldMw + iconleft + iconright;
// 		debug( burl );
		preloadimg( furl );
	}
	o.style.background = 'transparent';
	//o.style.background = 'blue';
	span.style.backgroundImage = 'url(' + burl + ')';
//	span.style.background = 'red';
	span.style.backgroundRepeat = 'no-repeat';
}

//puts the helper msg inside the text box if the 'helper' attribute is set and value is empty
function inputfocus( inpt, focused )
{
	if(navigator.appName != "Microsoft Internet Explorer" && inpt.type == 'password' && inpt.value=='' && inpt.getAttribute('pass')==1)
	{
		inpt.type='text';
		inpt.value= inpt.getAttribute('helper');
	}

	var def = inpt.getAttribute( 'helper');
	//if( def == null || def == '' ) return;

	if( focused )
	{
		if( inpt.value == def )
		{
			nohelper( inpt );
			inpt.value = '';
		}
		focusclass( inpt, 1 );
	}
	else
	{
		nohelper( inpt );
		if( inpt.type != 'password' && def != null && inpt.value == '' || inpt.value == def )
		{
			addclass( inpt, 'inputhelper' );
//			inpt.className = inpt.className + ' inputhelper';
			inpt.value = def;
		}
		else
			removeclass( inpt, 'inputhelper' );

		focusclass( inpt, 0 );
	}
}

var inptseltim = null;
function inputselect( inpt )
{
//	debug('inputselect');
	if(navigator.appName != "Microsoft Internet Explorer" && inpt.type == 'text' && inpt.value==inpt.getAttribute('helper') && inpt.getAttribute('pass')==1)
	{
		inpt.value='';
		inpt.type='password';
	}

	clearTimeout( inptseltim );
	//closeCalendar();
	inptseltim = setTimeout( function() { inpt.select(); }, 100 );
	inpt.select();
	focusclass( inpt, 1 );
	inpt.onmouseup = function() { this.onmouseup = null; return false; };
}


function getsel()
{
	if (window.getSelection)
		return window.getSelection();
	else if (document.getSelection)
		return document.getSelection();
	else if (document.selection)
		return document.selection.createRange().text;
}

// no matter what key has been stroke, if value == helper then clean the value
function inputkeytrap( inpt, ev )
{
	if( inpt.value == inpt.helpervalue ) inpt.value = '';
	nohelper( inpt );
	return true;
}

function setpredictive( inpt, script, data )
{
	inpt.setAttribute( 'predictive', script );
	if( inpt.value != inpt.valueinit )
	{
		inpt.value = '';
	}
	inputfocus( inpt, 0 );
	if( isdefined( data ) ) inpt.initdata = data;
	predictive( inpt );
}


function predictive( inpt )
{
	var url = inpt.getAttribute('predictive');
	inpt.allownew = inpt.getAttribute('allownew') == 1;
	inpt.useid = inpt.getAttribute('useid') == 1;
	inpt.setAttribute("autocomplete","off");
	inpt.oldval = -1;
	inpt.usevalue = inpt.getAttribute('usevalue') == 1;
	inpt.pagesize = inpt.getAttribute('pagesize') > 0 ? inpt.getAttribute('pagesize')*1 : 10;
	var time = null;

	if( inpt.usevalue )
	{
		inpt.valueid = inpt.value;
		inpt.value = '';
	}

	inpt.predict_div = null;

	function predictselect( o, idx )
	{
		o.savepredict = false;
		o.value = o.found[idx][1];
		o.valueid = o.found[idx][0];
		o.optselected = true;
		nohelper( o );

		if( inpt.predict_div != null )
			document.body.removeChild( inpt.predict_div );
		inpt.predict_div = null;
		if( isfunction( o.onchange ) ) o.onchange();
		o.blur();
	}

	function key( o, ev )
	{
		var keycode;
		if( ie ) ev = event;
		if( ev != null ) 
			keycode = ev.keyCode;

		// clears value if == helpervalue
		if( o.value == o.helpervalue )
		{
			o.oldval = o.value = '';
			nohelper( o );
		}
		// arrow down
		if( keycode == 40 )
		{
			if( o.selidx < o.found.length-1 )
			{
				o.selidx++;
				if( o.selidx >= o.idx + o.pagesize ) o.idx += o.pagesize;
				showresults( o, o.idx );
			}
			return false;
		}

		// arrow up
		if( keycode == 38 )
		{
			if( o.selidx > 0 )
			{
				o.selidx--;
				if( o.selidx < o.idx ) o.idx -= o.pagesize;
				showresults( o, o.idx );
			}
			return false;
		}

		// enter
		if( keycode == 13 )
		{
			if( o.found.length )
			{
				predictselect( o, o.selidx )
			}
			o.onblur();
			return false;
		}
		if( keycode != 9 ) o.savepredict = false;

		focusclass( o, 1 );
		return true;
	}

	function predover( div, idx )
	{
		var o = getme( div );
		if( o.lastover == idx ) return;
		// cleans all ip_item_sel
		var divs = div.parentNode.getElementsByTagName( 'DIV' );
		for( var i = 0 ; i < divs.length ; i++ )
			if( divs[i].className == 'ip_item_sel' ) divs[i].className = 'ip_item';
		o.selidx = o.lastover = idx;
		div.className = 'ip_item_sel';
	}

	function predout( div, idx )
	{
	}

	function predclick( div, idx )
	{
		predictselect( getme( div ), idx )
	}

	function predgo( div, idx )
	{
		var o = getme( div );
		o.showresults( o, idx );

		return false;
	}

	inpt.predover = predover;
	inpt.predout = predout;
	inpt.predclick = predclick;
	inpt.predgo = predgo;
	inpt.showresults = showresults;
	function rePosition( inpt, o )
	{
		//debug(o.offsetParent);
		if( o==null || inpt.predict_div==null) { return; }
		
		try
		{
			x=o.offsetParent;
		}
		catch(e)
		{
			if(o!=null)
			{
				stoppredict(o, 0);
				return;
			}
		}

		if(o!= null && getTop(o)+ o.clientHeight ==0 && getLeft( o )==0 )
		{
			stoppredict(o, 0);
			return;
		}
		
		var top=getTop( o )+o.clientHeight+'px';
		var left=getLeft( o )+'px';
		if(top!=inpt.predict_div.style.top ||  left!=inpt.predict_div.style.left)
		{
			//stoppredict(o, 0);
			inpt.blur();
			return;
		}

		inpt.predict_div.style.top = getTop( o ) + o.clientHeight;
		inpt.predict_div.style.left = getLeft( o );

		clearTimeout( time );
		time = setTimeout( function() { rePosition( inpt , o ); }, 300 );
	}

	function showresults( o, idx )
	{		
		o.idx = idx;

		if( o.selidx < idx ) o.selidx = idx;
		if( o.selidx >= idx + o.pagesize ) o.selidx = idx + o.pagesize -1;
		if( o.found.length == 0 )
		{
			if( inpt.predict_div != null )
			{
				document.body.removeChild( inpt.predict_div );
				inpt.predict_div = null;
			}
			return;
		}
		if( o.found.length == 1 && o.value == o.found[0][1] && inpt.predict_div == null) return;
		if( inpt.predict_div == null )
		{
			inpt.predict_div = ce( 'DIV' );
			inpt.predict_div.className = 'inputtext inputpredict';
			document.body.appendChild( inpt.predict_div );
			inpt.predict_div.component = o;
			inpt.predict_div.style.zIndex = 100000;
		}
		inpt.predict_div.style.width = o.clientWidth;
		inpt.predict_div.style.top = getTop( o ) + o.clientHeight;
		inpt.predict_div.style.left = getLeft( o );

		clearTimeout( time );
		time = setTimeout( function() { rePosition( inpt , o ); }, 300 );

		var lim = idx + o.pagesize;
		if( lim > o.found.length ) lim = o.found.length;
		var opts = '';
		for( var i = idx ; i < lim ; i++ )
		{
			var cn = i == o.selidx ? 'ip_item_sel' : 'ip_item';
			opts += '<div class="' + cn + '" onmouseover="getme(this).predover(this, ' + i + ')" onmouseout="getme(this).predout(this, ' + i + ')" onmousedown="getme(this).predclick(this, ' + i + ')">&nbsp;' + o.found[i][2] + '</div>';
		}
		var nav = '';

		if( idx > 0 )
			nav += '<div class="ip_prev"><a id="predict_more" href="#" onmousedown="return getme(this).predgo(this, ' + (idx-o.pagesize) + ')">prev</a></div>';

		if( lim < o.found.length )
			nav += '<div class="ip_next"><a id="predict_more" href="#" onmousedown="return getme(this).predgo(this, ' + (idx+o.pagesize) + ')">next</a></div>';

		if(o.getAttribute('navigate') == 1)
			nav='';

		if( nav > '' ) opts += '<div class="ip_nav"></div>' + nav;
		else opts += '<div class="ip_bottom"></div>';
		inpt.predict_div.innerHTML = opts;
	}


	function predict( o, ev )
	{
		if(o.getAttribute('navigate') == 1 && o.value=='')
		{
			stoppredict(o, 1);
			return;
		}
		
		var val = o.value + '';
		var sval = val;
		if( val == o.oldval ) return;
		var def = o.helpervalue + '';
		if( val == def ) val = '';
		val = val.replace( /[\)\(\^\$]/g, '' );
		val = val.replace( /\//g, '\\/' );
		var found = [];
		var pattern = '/(^|[^a-z])(' + val  + ')/i';
		var match = val > '' ? 'str.match( ' + pattern + ')' : '1';
		o.selidx = 0;
		for( var i = 0 ; i < o.records.length ; i++ )
		{
			var id = o.records[i][0];
			var str = o.records[i][1];
			if( str == '' ) continue;
			if( eval( match ) )
			{
				var strorig = str;
				if( val > '' )
				{
					eval( 'str = str.replace( /^(' + val + ')/i, "<b>$1</b>" )' );
					eval( 'str = str.replace( /([^a-z<])(' + val + ')/i, "$1<b>$2</b>" )' );
				}
				found.push( [ id, strorig, str ] );
			}
		}
		if( !o.allownew &&  found.length == 0 )
		{
			o.value = o.oldval;
			return;
		}
		o.found = found;
		o.oldval = sval;
		showresults( o, 0 );
	}

	function startpredict( o )
	{
		removeclass( o, 'inputhelper' );
		o.savevalue = o.value;
		o.savevalueid = o.valueid;
		o.savepredict = true;
		o.optselected = false;
		o.value = '';
	}

	function stoppredict( o , focus)
	{
		if( inpt.predict_div != null )
		{
			document.body.removeChild( inpt.predict_div );
		}
		inpt.predict_div = null;
		if( !o.optselected && o.allownew == false )
			o.value = '';
		if( focus!=1)
		if( o.savepredict && o.found.length > 0 )
		{
			o.value = o.savevalue;
			o.valueid = o.savevalueid;
		}
		o.savepredict = false;
		o.found = [];
		o.selidx = 0;
		o.oldval = -1;
		if(focus!=1) inputfocus( o, 0 );
	}

	function sortlabel( a, b )
	{
		var aa = a[1].toUpperCase();
		var bb = b[1].toUpperCase();
		if( aa == bb ) return 0;
		return aa > bb ? 1 : -1;
	}

	function sortvalue( a, b )
	{
		var aa = a[0];
		var bb = b[0];
		if( aa == bb ) return 0;
		return aa > bb ? 1 : -1;
	}



	function result( txt )
	{
		data = json( txt );

		// override allownew if defined
		if( isdefined( data.allownew ) )
		{
			inpt.setAttribute( 'allownew', data.allownew );
			inpt.allownew = data.allownew == 1;
		}

		// override usevalue if defined
		if( isdefined( data.usevalue ) )
		{
			inpt.setAttribute( 'usevalue', data.usevalue );
			inpt.usevalue = data.usevalue == 1;
			if( inpt.usevalue )
			{
				inpt.valueid = inpt.value;
				inpt.value = '';
			}
		}

		// override pagesize if defined
		if( isdefined( data.pagesize ) )
		{
			inpt.setAttribute( 'pagesize', data.pagesize );
			inpt.pagesize = data.pagesize * 1;
		}


		if( data.records == null ) return;

		removeclass( inpt, 'inputsel' );
		removeclass( inpt, 'inputlocksel' );
		if( data.records.length > 0 ) addclass( inpt, inpt.allownew ? 'inputsel' : 'inputlocksel' );
		inputbackground( inpt );

		var sort = inpt.getAttribute('sort');
		var sortfunc = sortlabel;
		if( sort > '' )
		{
			if( sort == '0' || sort.toUpperCase() == 'OFF')
				sortfunc = null;
			else if( sort.toUpperCase() == 'VALUE' )
				sortfunc = sortvalue;
		}
		if( sortfunc != null ) data.records.sort( sortfunc );
		inpt.records = data.records;
		if( inpt.usevalue && inpt.valueid != '' )
		{
			inpt.value = inpt.helpervalue;
			for( var i = 0 ; i < data.records.length ; i++ )
			{
				if( data.records[i][0] == inpt.valueid )
				{
					inpt.value = data.records[i][1];
					nohelper( inpt );
					break;
				}
			}
		}
		inpt.onfocus = function() { inputselect( inpt ); startpredict( inpt ); predict( inpt ); }
		inpt.onkeyup = function( ev ) { predict( inpt, ev ); }
		inpt.onkeydown = function( ev ) { return key( inpt, ev ); }
		inpt.onblur = function() { stoppredict( inpt ); }
	}

	if( isdefined( inpt.initdata ) )
		result( jsonout( inpt.initdata ) );
	else if( url == 1  )// nesse caso o parametro jį é o json de retorno
		result( base64.decode(inpt.getAttribute('data')) );
	else ajaxrequest( nocache(url), result, null, 1);
}
function bubbleoutcheck( ev )
{
	if( ie ) ev = event;
	var target = ie ? ev.srcElement : ev.target;
	var inbubble = upDom( target, 'bubbleobj' ) != null;
	//alert( isbubble );
	if( !inbubble )
	{
		nobubble();
		document.body.onmousedown = null;
	}
	return true;
}
function upDom( obj, ident )
{
	while( isdefined( obj ) && obj != null )
	{
		try
		{
			var v = eval( 'obj.' + ident );
			if( isdefined( v ) )
			{
				return v;
			}
		}
		catch( err ) {}
		obj = obj.parentNode;
	}
	return null;
}
