$(document).ready(function(){
	
	var button = $('#button1'), interval;
	
	new AjaxUpload(button,{
		//action: 'upload-test.php', // I disabled uploads in this example for security reasons
		action: 'api.php', 
		name: 'mediafile',

		onSubmit : function(file, ext){
		
			// One file at time
			this.disable();
			
			// TODO enable ext filtering and max size based on the config
			
			/*if (! (ext && /^(jpg|png|jpeg|gif)$/i.test(ext))){
                    // extension is not allowed
                    alert('Error: invalid file extension');
                    // cancel upload
                    return false;
            }*/
			
			checked = $('input:checkbox:checked');
			
			if(checked.length == 0 ){
				alert("You must select at least one tag!");
				this.enable();
				return false;
			}
			/*else if(checked.length > 5){
				alert("You may only select 5 elements");
				this.enable();
				return false
			}*/

			tags = getTags();
				
			this.setData({"clsid" :tags});
			
			// Uploding -> Uploading. -> Uploading...
			interval = window.setInterval(function(){
				var text = button.text();
				if (text.length < 13){
					button.text(text + '.');					
				} else {
					button.text('Uploading');				
				}
			}, 200);
		},
		
		onComplete: function(file, response){
			button.text('Upload');
						
			window.clearInterval(interval);
						
			// add file to the list
			//$('#uploaded').html("<strong>" + file + "</strong>");	
			
			if(!isInt(response)){
				alert("error in response! Response: " + response);
			}else{
			
				// TODO save these off in on submit
				page = "processing.php?pid=" + response + "&cids=" + getTags();
									
				// Load a new page
				window.location.replace(page);	
			}			
		}
	});	

	
});
	
// Extraordinarily lame that JS doesn't have this...
function isInt(value){
		if((parseFloat(value) == parseInt(value)) && !isNaN(parseInt(value))){
			return true;
		} else {
			return false;
		} 
}

function getTags(){
	tags = "";
					
	// We need to dynamically load all of the classids
	$('#advancedBlock input:checkbox:checked').each(function(index,obj){
		tags += obj.value + ","
	
	});
	
	return tags.substring(0,tags.length-1);
}
	
