function createAttach(list,button,item){
	/**
	 * Uploader instance
	 */
	var up = new FancyUploadPincho.Attach(list, button, {
		path: 'js/Swiff.Uploader.swf',
		url: 'upload-files.do.php',
		fileSizeMax: 500 * 1024 * 1024,
		fileListMax: 2,
		
		verbose: true,
		
		onSelectFail: function(files) {
            stopAutoSubmit();		      
			files.each(function(file) {
				new Element('li', {
					'class': 'file-invalid',
					events: {
						click: function() {
							this.destroy();
						}
					}
				}).adopt(
					new Element('span', {html: file.validationErrorMessage || file.validationError})
				).inject(this.list, 'bottom');
			}, this);	
		},
		
		onFileSuccess: function(file,response) {
	        initAutoSubmit();
		    var hash=  JSON.decode(response, true).name;
        	new Element('input', {type: 'hidden', 'checked': true ,"id":"item_"+item,"name":"name_"+item,"value":hash }).inject(file.ui.element, 'top');
			file.ui.element.highlight('#e6efc2');	
            
            file.ui.cancel.set('html', 'Remove').removeEvents().addEvent('click', function() {
				if (confirm("Remove this file?")){
                    removeFile(hash)
    				file.remove();
    				return false;
    			}
			});

                        
            		
		},
		
		onFileError: function(file) {
            stopAutoSubmit();		  
			file.ui.cancel.set('html', 'Retry').removeEvents().addEvent('click', function() {
				file.requeue();
				return false;
			});
			
			new Element('span', {
				html: file.errorMessage,
				'class': 'file-error'
			}).inject(file.ui.cancel, 'after');
		},
		
		onFileRequeue: function(file) {
		    alert("rr");
		    stopAutoSubmit()  
			file.ui.element.getElement('.file-error').destroy();
			
			file.ui.cancel.set('html', 'Cancel').removeEvents().addEvent('click', function() {
				file.remove();
				return false;
			});
			
			this.start();
		}
		
	});

}


/**
 *  Carga un nuevo item de upload
 *
 **/  

function loadItem(item){

 stopAutoSubmit();

 var myRequest = new Request({
         method: 'get',
         url:'item-upload.php',
         onRequest: function() { ;},
         onSuccess: function(responseText, responseXML){
                                                               
                            new Element('div', {'html': responseText}).inject($('items_container')); 
                            createAttach("attach-list-"+item,"attach-"+item,item); 
                            var item_actual  = parseInt($('actual_item').value);
                            $('actual_item').set("value",item_actual+1);
                    },
         onFailure: function(){alert('Error');}
      }).send("item="+item);

}

/**
 *  Elimina un archivo subido previamente
 *
 **/  

function removeFile(hash){
    
    stopAutoSubmit();

    var myRequest = new Request({
         method: 'get',
         url:'remove-files.do.php',
         /*onRequest: function() { ;},
         onSuccess: function(responseText, responseXML){
                                                               
                         
                    },*/
         onFailure: function(){alert('Error');}
      }).send("hash="+hash);

    stopAutoSubmit();    
}


/**
 *  Envia el formulario
 *
 **/  
function sendForm(show_alerts){

    if (typeof(show_alerts) == "undefined"){
        show_alerts = true;
    }
    
    var items = $("actual_item").value.toInt();
    
    var nFiles = 0;
    
    //recorro para todos los items que se agregaron si exite el archivo
    //valido el contenido.
    for(var i = 0; i < items; i++){
        
        if ($("item_"+i) && $("item_"+i).value != "" ){
            
            if ($("quantity_"+i).value == ""  || $("comments_"+i).value == "" ){
                if (show_alerts) alert("File "+i+" quantity and description re required");
                return false;
            }
            
            if ($("quantity_"+i).value.toInt == 0){
                if (show_alerts) alert("Quantity must be greater than zero");
                return false;
            }
            
            nFiles++;
            
        }
    
    }
    
    if (nFiles == 0){
        if (show_alerts) alert("Files have not been uploaded");
        return false;    
    }
    
    if ($("name").value == ""){        
        if (show_alerts) alert("Must enter name");
        return false;
    }
    
    if ($("company").value == ""){        
        if (show_alerts) alert("Must enter company ");
        return false;
    }    
    
    if ($("email").value == ""){        
        if (show_alerts) alert("Must enter email");
        return false;
    }      
    
    if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test($("email").value)){
        if (show_alerts) alert("The email is not valid");
        return false;
    }  

    if ($("phone").value == ""){        
        if (show_alerts) alert("Must enter phone number");
        return false;
    }  

    
    return true;  
    
      

}

function initAutoSubmit(){
    autosubmit = true;
    time_autosubmit = 0;
    increaseAutoSubmit();	    
}

function stopAutoSubmit(){
    autosubmit = false;
    time_autosubmit = 0;	    
}

function increaseAutoSubmit(){
    if(autosubmit){
        time_autosubmit+=10;
        if (time_autosubmit >= 180){
            if (sendForm(false)){                                
                $('f_upload').fireEvent('submit');                
            }else{
                time_autosubmit = 0;
                var timer = setTimeout("increaseAutoSubmit()",10000);
            }
        }else{
            var timer = setTimeout("increaseAutoSubmit()",10000);
        }
    }                	    
}



window.addEvent('domready', function() {
	
	$('f_upload').addEvent('submit', function(e) {		
		if (typeof(e) != "undefined"){
            e.stop();
        }            		
		this.set('send', {onComplete: function(response) { 
    		$("img_confirm").setStyle('display', 'inline');
    		$("img_loading").setStyle('display', 'none');		      
            if (response == "ok"){
                alert("File has been successfully sent, you will receive a confirmation email shortly, thank you.");
                window.location.reload();
            }else{
                if (response == "no_products"){
                    alert("Files have not been uploaded");
                }else{
                    alert("Error: Try again later please");
                }
                stopAutoSubmit();
            }
            
            return false;
		}});
		//Send the form.
		if (sendForm()){
        	$("img_confirm").setStyle('display', 'none');
        	$("img_loading").setStyle('display', 'inline');		
    		this.send();
        }  
	});
});



