arr_image_ext = ['.jpg', '.gif', '.png'];
arr_thumb_ext = ['.pdf', '.csv', '.xls', '.doc', 'docx', '.rtf', '.ppt', '.xml', '.txt','.zip', '.rar', 'r.gz', '.tgz', '.tar'];
arr_thumb_file = {'.pdf':'pdf.gif', '.csv':'csv.png', '.xls':'excel.png', '.doc':'word.png', 'docx':'word.png', '.rtf':'word.png', '.ppt':'ppt.png', '.xml':'xml.png', '.txt':'txt.png', '.zip':'zip.jpg', '.rar':'zip.jpg', 'r.gz':'zip.jpg', '.tgz':'zip.jpg', '.tar':'zip.jpg'};
folder_thumb = 'thumb/';

/*
 * Função que recebe como parâmetro o id do input e cria o uploder a partir dele
 */
function getMultiUploader( input )
{
	if($(input)==null) return;
	input = $(input);

	thumbwidth = (input.getAttribute('thumbwidth')!=null) ? input.getAttribute('thumbwidth') : 40 ;		
	thumbheight = (input.getAttribute('thumbheight')!=null)? input.getAttribute('thumbheight') : 40 ;					
	maxwidth = (input.getAttribute('maxwidth')!=null) ? input.getAttribute('maxwidth') : 400 ;							
	maxheight = (input.getAttribute('maxheight')!=null) ? input.getAttribute('maxheight') : 400 ;							
	displaywidth = (input.getAttribute('displaywidth')!=null) ? input.getAttribute('displaywidth') : 200 ;					
	displayheight = (input.getAttribute('displayheight')!=null) ? input.getAttribute('displayheight') : 200 ;						
	fileext = (input.getAttribute('fileext')!=null) ? input.getAttribute('fileext') : '' ;						
	image = (input.getAttribute('image')!=null) ? input.getAttribute('image') : 1 ;									
	button = (input.getAttribute('button')!=null) ? input.getAttribute('button') : '' ;										
	className = (input.getAttribute('cName')!=null) ? input.getAttribute('cName') : '' ;								
	objid1 = (input.getAttribute('objid')!=null) ? input.getAttribute('objid') : '' ;										
	displayid = (input.getAttribute('displayid')!=null) ? input.getAttribute('displayid') :'' ;								
	maxfiles = (input.getAttribute('maxfiles')!=null) ? input.getAttribute('maxfiles') : 1 ;	
	multi = (input.getAttribute('multi')!=null) ? input.getAttribute('multi') : 0 ;
	numcols = (input.getAttribute('numcols')!=null) ? input.getAttribute('numcols') : 2 ;								
	grid = (input.getAttribute('grid')!=null) ? input.getAttribute('grid') : 0 ;									
	deletable = (input.getAttribute('deletable')!=null) ? input.getAttribute('deletable') : 1 ;								
	fileclick = (input.getAttribute('fileclick')!=null) ? input.getAttribute('fileclick') : '' ;							
	objreference = (input.getAttribute('objreference')!=null) ? input.getAttribute('objreference') : '' ;	
	imgfit = (input.getAttribute('imgfit')!=null) ? input.getAttribute('imgfit') : 1 ;
	label = (input.getAttribute('label')!=null) ? input.getAttribute('label') : 1 ;
	oncomplete = (input.getAttribute('oncomplete')!=null) ? input.getAttribute('oncomplete') : '' ;
	quality = (input.getAttribute('quality')!=null) ? input.getAttribute('quality') : '50%' ;

	/*
	input = 'txt_de_upload';		//txt que receberá os endereços dos arquivos
	thumbwidth = 40;			//largura máxima do thumbnail
	thumbheight = 40;			//altura máxima do thumbnail
	maxwidth = 0;				//largura maxima da imagem
	maxheight = 0;				//altura maxima da imagem
	displaywidth = 400;			//largura maxima de exibicao da imagem (quadrado da imagem)
	displayheight = 200;		//altura maxima de exibicao da imagem (quadrado da imagem)
	fileext = '';				//extensões de arquivo
	image = 1;					// 1/0 - indica se é um upload e imagem ou generico
	button = '';				// label do botao
	className = 'teste';		// classe do div ou botão que será usado
	objid1 = '';				// id do objeto que será encobrido pelo flash. Caso não especificado será usado um botão padrao abaixo da área de upload
	displayid = '';				// id do objeto que será o local de exibição
	maxfiles = 10;				//número máximo de arquivos (default 1)
	multi = 10;					//(0- single / 1- multiple)informa se o padrão de exibição é para upload múltiplo (default 0)
	numcols = 2;				//número de colunas na grade de thumbnails
	grid = 0;					// 1/0 - indica se as imagens serão exibidas em grid (1) ou em formato arquivo (0)
	deletable = 1;				// 1/0 se os thumbs ou arquivos podem ser deletados (colocaria um xzinho ou coisa que valha) default (0)
	fileclick = 'func';			// função a ser chamada qdo se clica no thumb. são passados por parâmetro id e name da imagem
	objreference = '';			// Usado caso o objid seja vazio. O uploader será iserido antes deste objeto 
	imgfit = 1;					// 1/0 indica se as imagens serão redimensionadas com a função imgmaxrectcenter
	label = 1;					// 1/0 - indica se o label, embaixo da imagem de Single Upload será exibida
	oncomplete = 'func';		// função que será chamada quando o upload do arquivo termina - só funciona em single upload
	quality = '50%';			// qualidade da imagem 1% a 100%
	*/

	createUploader( objid1, displayid, className, button, image, grid, fileext, maxfiles, multi, displaywidth, displayheight, maxwidth, maxheight, thumbwidth, thumbheight, input.id, numcols, deletable, fileclick, oncomplete, quality, objreference, imgfit, label);
}

//Função que chama a função loadUploadImgDefault assim que o componente de upload estiver carregado 
function loadUpImgs(divid)
{
	if($(divid)!=null)
	{
		target = $($(divid).getAttribute('reference')).id;
		eval('aux = '+target+' ; ');

		if(aux.op!=null && aux.op.data!=null && aux.op.data.div_files!=null)
		{ 
			loadUploadImgDefault($(divid));
			return;
		}
	}
	setTimeout(function(){ loadUpImgs(divid); } ,100);
}
// Função que recebe como parâmetro um input que esteja sendo usado para guardar as informações de um upload.
// Esta função pega a lista de arquivos contidas no value deste input e os coloca como old-uploads de um componente upload
// o componente upload deve ter o nome de sua instância no atributo "reference" do input
function loadUploadImgDefault(input)
{
	if(input==null)
		return;

	value = input.value;

	if(value=='' || value==' ')
		return;

	taux = input.getAttribute('reference');
	eval('var target = '+taux+';');
	arrvalue = value.split(',');

	file = [];
	txt = '';
	for(var i = 0; i<arrvalue.length; i++)
	{
		stripname = arrvalue[i];
		arr_stripname = stripname.split('/');
		stripname = arr_stripname[arr_stripname.length-1];
		
		file[i] = {'id': 1000+i, 'uname': arrvalue[i], 'name': stripname , 'size': '', 'className': 'oldUpload' };
		txt += " b = {'id' : "+(1000+i)+"}; target.op.onComplete(b); ";
	}

	a = new Object;
	a['files'] = [];
	a['type'] = 'onSelected';
	a['files']= file;
	a['type'] = 'onComplete';

	input.value = '';
	target.op.onSelected(a); 
	eval(txt);
}

// Função que recebe os parâmetros e instância um objeto multiUpload
// Responsável por gerenciar este processo, seus parâmetros e objetos envolvidos
// Destes objetos, podemos destacar: swfobject(botão de upload), filesobject(div em que fica a exibição dos arquivos), inputupload (input que contém os endereços dos arquivos separados por vírgula)
function createUploader(obj_id, displayid, className, button, image, grid, fileext, maxfiles, multi, displaywidth, displayheight, maxwidth, maxheight, thumbwidth, thumbheight, input, numcols, deletable, fileclick, oncomplete, quality, objreference, imgfit, label)
{
	button = (isdefined(button) && button!='') ? button : 'upload' ;
	grid = (isdefined(grid)) ? grid : 0 ;
	deletable = (isdefined(deletable)) ? deletable : 0 ;
	imgfit = (isdefined(imgfit)) ? imgfit : 1 ;
	label = (isdefined(label)) ? label : 1 ;

		//Se o obj_id existir, ele será o botão de upload, caso contrário, criamos um botão upload com o botao.value = button (default: upload)
		if(obj_id!='' && $(obj_id)!=null)
		{
			obj = $(obj_id);
			obj.style.position = 'relative';
		}
		else
		{
			if(obj_id=='')
			{
				obj_id = Math.random()+'';
				obj_id = obj_id.substr(2,5);
			}
			aux = ce('DIV');
			aux.id = 'up_aux_'+obj_id;

			if(objreference!=null && $(objreference)!=null)
				$(objreference).parentNode.insertBefore(aux, $(objreference));
			else if(input!=null && $(input)!=null)
				$(input).parentNode.insertBefore(aux, $(input));
			else
				document.body.appendChild(aux);
			
			aux.innerHTML = "<div id='target_aux_"+obj_id+"'></div><div id='container_"+obj_id+"' class='"+className+"' style='position: relative;'><input type='button' value='"+button+"' id='btn_"+obj_id+"'/><div id='obj_"+obj_id+"'>&nbsp;</div></div>";
			
			formformat($('container_'+obj_id));

			obj = $('obj_'+obj_id);
			var btnWidth = $('btn_'+obj_id).offsetWidth;
			var btnHeight = $('btn_'+obj_id).offsetHeight;
			if( isdefined($('btn_'+obj_id).wrapper) )
			{
				var wrapper = $('btn_'+obj_id).wrapper
				btnWidth = wrapper.clientWidth;
				btnHeight = wrapper.clientHeight;
			}
			$('container_'+obj_id).style.width = obj.style.width = w = btnWidth;
			$('container_'+obj_id).style.height = obj.style.height = h = btnHeight;

			if(displayid=='' || $(displayid)==null)
				displayid = "target_aux_"+obj_id;

		}

		//trata o número de uploads
		numUploads = ( maxfiles=='' || !(maxfiles>0) ) ? 0 : maxfiles;
		//multi = (maxfiles==1) ? 'false' : 'true';
		multi = (multi==1) ? 'true' : 'false';
		if(multi=='true')
			displayheight = 0;

		//Trata as extensões de imagem
		if(fileext == '*.jpg;*.gif;*.png' || image==1)
		{
			image = 1;
			filedescription = 'Image Files';
			if(fileext=='')
				fileext = '*.jpg;*.gif;*.png';
		}
		else
		{
			image = 0;
			filedescription = 'All files';
		}

		//cria a div que será reposicionada
		var up = ce('div');
		up.id = 'up'+obj.id;

		//Se display id é definido, inserimos uma div no fim, senão colocamos acima do botão de upload
		if($(displayid)==null || displayid=='')
		{
			target_files = ce('DIV');
			target_files.id = 'target_files_'+obj.id;
			obj.parentNode.insertBefore(target_files, obj);
		}
		else if($(displayid)!=null)
			$(displayid).innerHTML +='<div id="target_files_'+obj.id+'" style="border: 1px solid transparent;"></div>';

		displayid = 'target_files_'+obj.id;
		up.style.top = 0;
		up.style.left = 0;
		up.style.position = 'absolute';
		up.innerHTML += '<div id="aux_target_'+obj.id+'"><input type="button" value="'+button+'" id="target_'+obj.id+'"/></div>';
		//Adiciona input se necessário
		if(input==''|| input==null || $(input)==null)
		{
			up.innerHTML += '<input type="hidden" id="inpt_'+obj.id+'" reference="target_'+obj.id+'"/>';
			input = "inpt_"+obj.id;
		}
		else
			$(input).setAttribute('reference', 'target_'+obj.id);
		obj.appendChild(up);

		//Redimensiona o botão
		width = obj.offsetWidth;
		height = obj.offsetHeight;
		if( isdefined(obj.wrapper) )
		{
			var wrapper = obj.wrapper
			width = wrapper.clientWidth;
			height = wrapper.clientHeight;
		}


		eval(' window.target_'+obj.id+' = new multiUpload(\'target_'+obj.id+'\', \''+displayid+'\', { swf: \'kintool\/multiUpload.swf\', script: \'kintool\/upload.php\', expressInstall: \'kintool\/expressInstall.swf\', multi: '+multi+', auto: true, fileExtensions: \''+fileext+'\', fileDescription: \''+filedescription+'\', width: \''+width+'\', height: \''+height+'\', className: \''+className+'\', numUploads: \''+numUploads+'\', image: \''+image+'\', data: { maxwidth: '+maxwidth+', maxheight: '+maxheight+', displaywidth: '+displaywidth+', displayheight: '+displayheight+',  thumbwidth: '+thumbwidth+', thumbheight: '+thumbheight+', up: \'aux_target_'+obj.id+'\', target: \''+obj.id+'\', input:\''+input+'\' , numcols:\''+numcols+'\', grid:\''+grid+'\', deletable:\''+deletable+'\', fileclick: \''+fileclick+'\', oncomplete: \''+oncomplete+'\', multi: \''+multi+'\', imgfit: \''+imgfit+'\', label: \''+label+'\' , quality: \''+quality+'\'} }); ');	
		
		loadUpImgs(input);
}



function multiUpload(id, filesdiv, options)
{
	/**
	 * Default function to create the base html that will show files
	 **/
	this.createBaseHtml = function()
	{
		style = '';
		if(this.data.displaywidth>0)
			style+='width: '+this.data.displaywidth+'px; ';
		if(this.data.displayheight>0)
			style+='height: '+this.data.displayheight+'px; ';
		if(this.multi==1)
			style+='display: none; ';
		
		div_files = ''
		while($(div_files)!=null || div_files=='')
		{
			random = Math.random()+'';
			random = random.substr(2,5);
			div_files = 'files_list_'+random+'_';
		}
		this.data.div_files = div_files;
		
		txtaux = '';
		if(this.data.imgfit==1)
			txtaux = 'onload="imgmaxrectcenter(this, '+this.data.displaywidth+', '+this.data.displayheight+');" class="img_uploader"';

		txt='';
		if(!this.multi)
			txt = '<div style="width: '+this.data.displaywidth+'px; height: '+this.data.displayheight+'px; overflow: hidden; ;"><img src="kintool/'+folder_thumb+'default.png"  '+txtaux+'/></div>';

		html = '<div id="'+div_files+'" class="files_list" style="'+style+'" multi="'+this.multi+'" imgfit="'+this.data.imgfit+'" reference="'+this.data.id+'" >'+txt+'</div>';
		document.getElementById(filesdiv).innerHTML = html;
	}
	/**
	 * Default function to add files to the default base html
	 **/
	this.onSelected = function(e)
	{
		//For 1 archive
		if(this.multi==1)
		{
			var count = (this.data.input!='' && $(this.data.input)!=null && $(this.data.input).value!='') ? getLengthSrcInput(this.data.input) : 0;
			
			//For various archives
			for (var file in e.files)
			{
				//Controla o tamanho máximo de uploads
				count++;
				if(count>this.numUploads)
						return;
				
				var info = e.files[file];
				var divfile = document.createElement("div");
				divfile.id = "file_"+info.id;

				src = info.uname;
				aux = src.substr(src.length-4,src.length);
				src = src.substr(0, src.length-4)+ aux.toLowerCase(); 

				ext = src.substr(src.length-4,src.length);
				ext = ext.toLowerCase();

				if(this.data.grid==1)
				{
					//Control the number of cols
					tr = 'float: left;';
					if((count%this.data.numcols)==0)
						tr = '';
					
					//Control verticalalign from progress barr
					style = '';
					if(this.data.thumbwidth>0 || this.data.thumbheight>0)		
						style = 'margin-top: '+Math.round((this.data.thumbheight-16)/2)+'px; margin-left: '+Math.round(this.data.thumbwidth*0.1)+'px; ';

					on = (this.data.fileclick!='') ? this.data.fileclick+'('+info.id+', \''+src+'\');' : '';
					progress = '<div class="progress" style="float: left; '+style+'"><div id="'+this.data.div_files+'_progress_'+info.id+'" filesize="'+size(info.size)+'" onclick="'+on+'">&nbsp;</div></div>';

					//If image, display the image
					thumb = '<div id="'+this.data.div_files+'_thumb_'+info.id+'" class="img squareimg" file="'+src+'" filename="'+info.name+'" style="width: '+this.data.thumbwidth+'; height: '+this.data.thumbheight+'; overflow: hidden; '+tr+'" numcols="'+this.data.numcols+'" imgfit="'+this.data.imgfit+'">'+progress+'</div>';

					divfile.innerHTML = thumb;
				}
				else
				{
					//If image, display the image
					on = (this.data.fileclick!='') ? this.data.fileclick+'('+info.id+', \''+src+'\');' : '';

					thumb = '<div id="'+this.data.div_files+'_thumb_'+info.id+'" class="img" file="'+src+'" filename="'+info.name+'" style="width: '+this.data.thumbwidth+'; height: '+this.data.thumbheight+'; overflow: hidden;">&nbsp;</div>';

					name = info.name;
					name = name.replace(/^[a-zA-Z]+\/[0-9]+_[0-9]+_/,'');

					className = (info.className!=null && info.className!='') ? info.className : '' ;
					classNameOver = (className!='') ? className+'_over' : 'multi_upload_over' ;

					out = '<div class="multi_upload '+className+'" onmouseover="this.className=\'multi_upload '+classNameOver+'\';" onmouseout="this.className=\'multi_upload '+className+'\';"><div class="thumb" style="float: left;">'+thumb+'</div><div class="uptitle" style="float: left; height: auto; overflow: hidden; margin-top: 0px;">'+name+'</div><div class="progress" style="float: left;"><div id="'+this.data.div_files+'_progress_'+info.id+'" filesize="'+size(info.size)+'"  onclick="'+on+'">&nbsp;</div></div>';
					
					divid = this.data.div_files+'_progress_'+info.id;
					if(this.data.deletable==1)
						out += '<div style="float: right;" class="close" id="close_'+divid+'" input="'+this.data.input+'" uname="'+src+'">X</div>';
					
					out += '</div>';

					divfile.innerHTML = out;

				}
				$(this.data.div_files).style.display = 'block';
				document.getElementById(this.data.div_files).appendChild(divfile); 
				
				if( (this.data.grid!=1) && ($('close_'+divid)!=null))
				{
					$('close_'+divid).onclick = function () { cancelUpload(this, this.getAttribute('uname'), this.getAttribute('input')); };
					$('close_'+divid).onmouseover = function () { this.className='close_over'; };
					$('close_'+divid).onmouseout = function () { this.className='close'; };
				}
			}
		}
		else
		{
			//erase files_list
			document.getElementById(this.data.div_files).innerHTML = '';
			
			style = '';
			if(this.data.displaywidth>0 || this.data.displayheight>0)		
				style = ' style=" margin-top: '+Math.round((this.data.displayheight-16)/2)+'px; margin-left: '+Math.round(this.data.displaywidth*0.1)+'px;" ';

			var info = e.files[0]; 

			src = info.uname;
			aux = src.substr(src.length-4,src.length);
			src = src.substr(0, src.length-4)+ aux.toLowerCase(); 

			var divfile = document.createElement("div");
			divfile.id = this.data.div_files+"_file_"+info.id;

			on = (this.data.fileclick!='') ? this.data.fileclick+'('+info.id+', \''+src+'\');' : '';
			
			divfile.innerHTML = '<div class="progress" '+style+'><div id="'+this.data.div_files+'_progress_'+info.id+'" file="'+src+'" filename="'+info.name+'" onclick="'+on+'">&nbsp;</div></div>';

			document.getElementById(this.data.div_files).appendChild(divfile); 
		}
	}

	/**
	 * Default function to remove the file from the default base html
	 **/
	this.onCancel = function(e)
	{
		var divfile = document.getElementById(this.data.div_files+"_file_"+e.id);
		document.getElementById(this.data.div_files).removeChild(divfile);
	}

	/**
	 * Default function to show the upload progress
	 **/
	this.onProgress = function(e)
	{
		var progress = Math.ceil(Number(e.bytesLoaded / e.bytesTotal * 100));
		var div = document.getElementById(this.data.div_files+"_progress_"+e.id);
		div.style.display = 'block';
		var val = String(progress)+"%";
		div.innerHTML = val;
		div.style.width = val;
	}
	this.onComplete = function(e)
	{
		var div = document.getElementById(this.data.div_files+"_progress_"+e.id);
		if(div==null) return;
		div.style.display = 'none';
		
		if(this.multi==1)
		{		
			//MULTI UPLOAD
			//exibe o tamanho do arquivo no lugar da barra de progresso -  para upload FILE
			if(div.getAttribute('filesize')!=null && this.data.grid==0)
			{
				div.style.display = 'block';
				div.parentNode.className = 'progress_end';
				div.parentNode.innerHTML = div.getAttribute('filesize');
			}

			//recebe os dados da div que conterá o thumbnail
			var newdiv = document.getElementById(this.data.div_files+"_thumb_"+e.id);
			file = src = newdiv.getAttribute('file');
			if(src!=null)
			{
				//recebe o src do arquivo upload e verifica se é imagem
				ext = src.substr(src.length-4,src.length);
				ext = ext.toLowerCase();
//					src = 'tmp/TH'+src.substring(4);
				swf = '';
				//se for arquivo de imagem, e estiver na tmp, exibimos o thumb, caso contrário, usamos o arquivo mesmo
				if(in_array(ext, arr_image_ext))
					src = (src.substring(0,3)=='tmp') ? 'tmp/TH'+src.substring(4) : src ;
				else
				{
					if(in_array(ext, arr_thumb_ext))
						src=folder_thumb+arr_thumb_file[ext];
					else 
						src = folder_thumb+'Document.png';
					
					//Arquivo swf
					swf = (ext=='.swf') ? 'kintool/'+file : '';
				}	

				//usa a função de resize na imagem
				txtaux = '';
				if(this.data.imgfit==1)
					txtaux = 'onload="imgmaxrectcenter(this, '+this.data.thumbwidth+', '+this.data.thumbheight+');" class="img_uploader"';

				divid = 'img_'+this.data.id+'_'+e.id;
				out ='<img id="'+divid+'" src="kintool/'+src+'" '+txtaux+'/>';	
		
				//se for grid, inserimos o botão de DELETE
				if(this.data.grid==1)
				{
					out = '<div style="position: relative;">'+out+'<div class="multi_upload" style="background-color: transparent; border: 0px; ">';
					if(this.data.deletable==1)
						out+= '<div style="position: absolute; top: 4px; right: 4px;" class="close" input="'+this.data.input+'" id="close_'+divid+'" file="'+file+'">X</div>';
					out+='</div></div>';
				}
				newdiv.innerHTML = out;
				
				if($('close_'+divid) != null)
				{
					$('close_'+divid).onclick = function () { cancelUpload(this.parentNode.parentNode,  this.getAttribute('file'), this.getAttribute('input')); };
					$('close_'+divid).onmouseover = function () { this.className='close_over'; };
					$('close_'+divid).onmouseout = function () { this.className='close'; };
				}

				if(swf!='')
					insertSWF(swf, divid, this.data.thumbwidth, this.data.thumbheight); 
			}  
		}
		else
		{
			//SINGLE UPLOAD
			file = src = div.getAttribute('file');
			ext = src.substr(src.length-4,src.length);
			ext = ext.toLowerCase();

			target = div.parentNode.parentNode;

			if(src!=null)
			{
				fileaux = src;
				// Se for arquivo de imagem, se existe thumb ou outro tipo de arquivo
				if(in_array(ext, arr_image_ext))
					src = (src.substring(0,3)=='tmp') ? 'tmp/TH'+src.substring(4) : src ;
				else if(in_array(ext, arr_thumb_ext))
					src = folder_thumb+arr_thumb_file[ext];
				else
					src = folder_thumb+'Document.png';

				//Arquivo swf
				swf = (ext=='.swf')? 'kintool/'+file : '';

				divid = 'img_'+this.data.id+'_'+e.id;
				name = div.getAttribute('filename');
				name = name.replace(/^[a-zA-Z]+\/[0-9]+_[0-9]+_/,'');

				//a altura muda, dependendo do uso da LABEL
				height = (this.data.label==1) ? this.data.displayheight-20 : this.data.displayheight;

				txtaux = align = '';
				//usa a função de resize na imagem
				if(this.data.imgfit==1)
					txtaux = 'onload="imgmaxrectcenter(this, '+this.data.displaywidth+', '+height+');" class="img_uploader"';

				out = '<div style="position: static;"><div style="width: '+this.data.displaywidth+'px; height: '+height+'px; overflow: hidden; " id="'+divid+'"><img src="kintool/'+src+'" '+txtaux+'/></div>';

				//insere a LABEL
				if(this.data.label==1)
					out += '<div class="label">'+name+'</div>';

				//insere o componente DELETABLE
				if(this.data.deletable==1)
					out += '<div class="multi_upload"><div style="position: absolute; top: 4px; right: 4px;" class="close" input="'+this.data.input+'" id="close_'+divid+'" file="'+fileaux+'">X</div></div>';

				out += '</div>';
				target.innerHTML = out;	

				//alocar as ações do botão close
				if($('close_'+divid) != null)
				{
					$('close_'+divid).onclick = function () { cancelUpload(this.parentNode.parentNode, this.getAttribute('file'), this.getAttribute('input')); };
					$('close_'+divid).onmouseover = function () { this.className='close_over'; };
					$('close_'+divid).onmouseout = function () { this.className='close'; };
				}
				
				//insere o swf
				if(swf!='')
					insertSWF(swf, divid, this.data.displaywidth, this.data.displayheight-20);
				
				on='';
				if(this.data.oncomplete!='') 
					on='setTimeout( function(){ '+this.data.oncomplete+'(); }, 200); ';

				if(on!='') { eval(on); }
			}
			
		}
		if(div.onclick!=null)
			$('img_'+this.data.id+'_'+e.id).onclick = div.onclick;

		addSrcInput(file, this.data.input, this.multi);
	}

	/**
	 * Default function to clear the list of files
	 **/
	this.onClearQueue = function(e)
	{
		document.getElementById(this.data.div_files).innerHTML = "";
	}

	this.prepareData = function(data)
	{
		var strData = '';
		for (var name in data)
			strData += '&' + name + '=' + data[name];
		return escape(strData.substr(1));
	}

	/**
	 * Default options
	 */
	this.op = {
		swf:               'kintool/upload.swf', // path to the swf file
		script:            'kintool/upload.php', // path to the upload script
		expressInstall:    null,
		scriptAccess:      'sameDomain',
		width:             137, // flash button width
		height:            27, // flash button height
		className:		   '', // className from object 
		wmode:             'transparent', // flash button wmode
		numUploads:		   0, //num max of uploads (0 any)
		image:			   0, //allow only images? (0 to all; 1 for images only)
		method:            'POST', // method to send vars to the upload script
		data:              {}, // data object to send with each upload. ex.: { foo: 'bar' }
		maxsize:           0, // maximum file size in bytes (0 = any size)
		fileDescription:   '', // text to show in the combo box on the bottom of the selection window
		fileExtensions:    '', // Extension to allow ex.: '*.jpg;*.gif;*.png'
		createBaseHtml:    this.createBaseHtml, // Base html
		onMouseClick:      function() {}, // function to execute when the user has clicked the uploader swf
		onSelectionCancel: function() {}, // function to execute when the user presses "Cancel" in the selection window
		onSelected:        this.onSelected, // function to execute when the user makes the selection
		onStart:           function() {}, // function to execute when the uploader starts sending a file
		onError:           function() {}, // function to execute when an Error occurs
		onProgress:        this.onProgress, // function to execute on every progress change of a single file upload
		onCancel:          this.onCancel, // function to execute when a file upload is canceled
		onComplete:        this.onComplete, // function to execute when a file upload is complete
		onAllComplete:     function() {}, // function to execute when every file from the queue was sent
		onClearQueue:      this.onClearQueue, // function to execute when the queue is cleared
		callback:          function() {} // function to execute when the swf object is embeded
	}

	this.op = mergeRecursive(this.op, options);

	var op = this.op;
	op.data.id = id;

	DOMReady(function() { op.createBaseHtml(); });

	var path = location.pathname;
	path = path.split('/');
	path.pop();
	path = path.join('/') + '/';

	var params = {};

	params.id      = id;
	params.path    = path;
	params.script  = op.script;
	params.method  = op.method;
	if (op.multi)  params.multi = true; 
	if (op.auto)   params.auto  = true;
	params.maxsize = op.maxsize;
	params.desc    = op.fileDescription;
	params.ext     = op.fileExtensions;

	if (op.data)
		params.scriptData = this.prepareData(op.data);

	swfobject.embedSWF(op.swf, id, op.width, op.height, '9.0.24', op.expressInstall, params, {'quality':'high','wmode':op.wmode,'allowScriptAccess':op.scriptAccess, 'numUploads':op.numUploads}, {'styleclass' :op.className}, op.callback);

	this.el = function()
	{
		return document.getElementById(id);
	}

	this.setData = function(data)
	{
		this.el().setData(this.prepareData(data));
	}

	this.startUpload = function()
	{
		this.el().startUpload();
	}

	this.cancelUpload = function(fileid)
	{
		this.el().cancelUpload(fileid);
	}

	this.clearUploadQueue = function()
	{
		this.el().clearUploadQueue();
	}
}

function mergeRecursive(obj1, obj2)
{
	for (var p in obj2)
	{
		try
		{
			if (obj2[p].constructor == Object)
				obj1[p] = mergeRecursive(obj1[p], obj2[p]);
			else
				obj1[p] = obj2[p];
		}
		catch(e)
		{
			obj1[p] = obj2[p];
		}
	}
	return obj1;
}

function DOMReady(f)
{
	//if (/(?!.*?compatible|.*?webkit)^mozilla|opera/i.test(navigator.userAgent))
	//	document.addEventListener("DOMContentLoaded", f, false);
	//else
		window.setTimeout(f,0);
}

function size(val)
{
	if(val==0) return '';
	var kb = Number(Number(val)/1024).toFixed(1);
	return kb >= 1000 ? Number(kb/1024).toFixed(1) + " MB" : kb + " KB";
}

function in_array(needle,haystack) 
{
	return new RegExp('(^|\,)'+needle+'(\,|$)','gi').test(haystack);
}

function cancelUpload( inpt, name, input )
{
	if(input=='' || $(input)==null)
		return;

	//reajusta o float das outras divs
	divid_orig = inpt.parentNode.id;
	sufix_orig = divid_orig.substring(0,24);
	num_orig = divid_orig.substring(24) * 1;

	obj =  inpt.parentNode.parentNode.parentNode;
	var elist = obj.getElementsByTagName("DIV");
	var j = 0;
	for( var i = 0 ; i < elist.length ; i++ )
	{
		elid = elist[i].id;
		sufix_elid = elid.substring(0,24);
		num_elid = elid.substring(24) * 1;
		
		if(sufix_elid==sufix_orig && elid!=divid_orig)
		{
			j++;
			if((j%elist[i].getAttribute('numcols'))!=0)
			{
				elist[i].style.cssFloat = 'left';
				elist[i].style.styleFloat = 'left';
			}
			else
			{
				elist[i].style.cssFloat = 'none';
				elist[i].style.styleFloat = 'none';
			}
		}
	}
	delSrcInput( name, input );

	//exibe o arquivo padrão
	obj=inpt.parentNode.parentNode;
	//inpt.parentNode.parentNode.parentNode.style.display='block';
	if(obj.getAttribute('multi')=='false')
	{
		eval('displaywidth = window.'+obj.getAttribute('reference')+'.op.data.displaywidth; displayheight = window.'+obj.getAttribute('reference')+'.op.data.displayheight;');

		txtaux = '';
		if(obj.getAttribute('imgfit')==1)
			txtaux = 'onload="imgmaxrectcenter(this, '+displaywidth+', '+displayheight+');" class="img_uploader"';

		obj.innerHTML = '<div style="width: '+displaywidth+'px; height: '+displayheight+'px; overflow: hidden;"><img src="kintool/'+folder_thumb+'default.png" '+txtaux+'/></div>'; 
		obj.style.display = 'block';

		$(input).value = "";
	}
	else
	{
		if(getLengthSrcInput(input)==0) 
			inpt.parentNode.parentNode.parentNode.style.display = 'none';

		if(inpt!=null && inpt.parentNode!=null && inpt.parentNode.parentNode!=null)
			inpt.parentNode.parentNode.removeChild(inpt.parentNode); 
	}
}
function insertSWF( src, divid, width, height )
{
	swfobject.embedSWF(src, divid, width, height, '9.0.24', null, {}, {'allowScriptAccess':'never', 'quality':'low', 'wmode':'transparent'}, {}, null);
}

function addSrcInput( src, input , multi)
{
	if(input==null || $(input)==null)
		return;

	value = $(input).value;
	if(multi==1 && value>'')
		value += ','+src;
	else
		value = src;

	$(input).value = value;
}
function delSrcInput( src, input )
{	
	if(input==null || $(input)==null)
		return;

	value = $(input).value;
	arrvalue = value.split(',');

	if(value=='' || value==' ')
		return;

	len = getLengthSrcInput(input);

	for(var i=0; i<len; i++)
	{
		if(arrvalue[i]==src)
			arrvalue.splice(i,1);
	}

	value = arrvalue.join();
	$(input).value = value;
}
function getLengthSrcInput(input)
{
	if(input==null || $(input)==null)
		return;

	value = $(input).value;
	arrvalue = value.split(',');

	var len = (arrvalue!=' ' && arrvalue!='') ? arrvalue.length : 0;

	return len;
}
