
// js headers

upload_once_form = '';

// when a form is uploaded, process upload
function processAllUploads()
{
    // loop through all upload input tags, skip empty ones
    if ($('li.file_upload:first form').length > 0 && $('li.file_upload:first form input[type=file]').val() != '')
    {
        formId = $('li.file_upload:first form').attr('id');
 
 		// trying to upload the same form again
 		if (upload_once_form == formId)
 		{
 			return false;
 		}
 		
 		upload_once_form = formId;
        
        // alert(formId);
        
        // alert('upload_id: ' + $('#' + formId).find('#UPLOAD_IDENTIFIER').val() + ' filename: ' + $('#' + formId).find('#file_upload').val());
        
        // show that the file has started to upload
        $.post("/_backend_new/_controller/ajax_upload_status.php",{
           upload_id: $('#' + formId).find('#UPLOAD_IDENTIFIER').val(),
           filename: $('#' + formId).find('#file_upload').val(),
           action: "add"
         }, 
            function(xml) 
            {   
               // album upload was successful, insert the id in all the forms and then add the tracks        
               if ($("status", xml).text() == 'success')
               {
                    // upload the file
                    $('#' + formId).submit(processUpload(formId));
                    return true;
               }
               else
               {    
                    alert('something went totally wrong');
                    return false;
               }
            });  
    }
    else
    {
        //alert('all uploaded, refresh' + redirectUrl);
        window.location = redirectUrl;
    }
}



// when a form is uploaded, process upload
function processUpload(formId)
{
    // alert('process upload ' + formId);
    fileUpload = new FileUpload(formId);
    fileUpload.getProgress();
    return false;
}    


// make sure the selected file is the right extension
function checkExtension(el)
{	
    var imageExtensions = ['.jpg', '.gif', '.png', '.jpeg'];
    var videoExtensions = ['.flv', '.avi', '.mov', '.mpg', '.mpeg', '.mp4', '.m4v', '.wmv', '.asf'];
    var audioExtensions = ['.mp3','.m4a'];

    var fileType        = $(el).attr('title');
	var fileName        = $(el).attr('value');

    // alert('filetype: ' + fileType + ' filename ' + fileName);
    
	switch (fileType)
	{		
        case 'image':
            for (var i = 0; i < imageExtensions.length; i++)
            {
                if (fileName.substr((fileName.length - imageExtensions[i].length), imageExtensions[i].length).toLowerCase() == imageExtensions[i])
                {                                        
                    return true;
                }
            }   
            
            // extension is not supported 
			alert('Please select a file with an extension of .jpg, .gif, .png or .jpeg');
			$('#' + elId).attr('value', '');
			
			return false;
			            
            break;
            
        case 'video':
            for (var i = 0; i < videoExtensions.length; i++)
            {   
                if(fileName.substr((fileName.length - videoExtensions[i].length), videoExtensions[i].length).toLowerCase() == videoExtensions[i])
                {                                                                   
                    return true;
                }                
            }   
            
            // extension is not supported
			alert('Please upload a file with an extension of .flv, .avi, .mov, .mpg, .mpeg, .mp4, .m4v, .wmv or .asf');
            $('#' + elId).attr('value', '');

            return false;

            break;
            
        case 'audio':
            for (var i = 0; i < audioExtensions.length; i++)
            {
                if(fileName.substr((fileName.length - audioExtensions[i].length), audioExtensions[i].length).toLowerCase() == audioExtensions[i])
                {                                        
                    return true;
                }                
            }
            
            // extension not supported
            alert('Please upload a file with an extension of .mp3 or .m4a');
            $(el).attr('value', '');   
            
            return false;
            
            break;
    }

	// alert('Please select a different file');
};







// file upload class
function FileUpload(formId)
{
    this.formId          = formId;
	
	this.identifierArray = [];
	this.uploadStatus    = [];
	this.uploadComplete  = false;

	this.createIdentifierArray();
}

        
    
    FileUpload.prototype.createIdentifierArray = function()
    {
    	fileUploadObj = this;
    	
    	$('form#' + fileUploadObj.formId + ' input[name=UPLOAD_IDENTIFIER]').each(
    	   function()
    	   {
    	       fileUploadObj.identifierArray.push(this.value);	
           }
        );
    };
    
    FileUpload.prototype.getProgress = function (event, formId)
    {
    	fileUploadObj = this;
    
        // alert('getprogress ' + fileUploadObj.formId);
        // alert($('form#' + fileUploadObj.formId + ' #upload_progress_info').html());
        
        // initialize the graphical uploader
        $('form#' + fileUploadObj.formId + ' #uploader').css('display','block');
    	$('form#' + fileUploadObj.formId + ' #upload_progress_info').html('Calculating progress');
    	
        // alert($('form#' + fileUploadObj.formId + ' #upload_progress_info').html());

    	
    	this.fileUploadInterval = setInterval(function()
    	{
    		fileUploadObj.getProgressInterval();
    	}, 5000);
    	
    	this.fileUploadTimeout = setTimeout(function()
    	{
    		fileUploadObj.getProgressTimeout();	
    	}, 200);	
    };
    
    FileUpload.prototype.getProgressTimeout = function ()
    {
    	fileUploadObj = this;
    	
    	// ? need to get the right identifier
    	/*
    	xajax_getUploadStatus(fileUploadObj.identifierArray[0], function(result)
    	{
    		fileUploadObj.getProgress_cb(result);
    	});
    	*/
    	
    	$.get('/_backend_new/_controller/ajax_upload_status.php', {id: fileUploadObj.identifierArray[0]}, 
    	   function(xml)
    	   {
    	       fileUploadObj.getProgress_cb(xml);
    	   }
    	   
        );
    	
    			
    };
    
    FileUpload.prototype.getProgress_cb = function (xml)
    {
        var response = $('response', xml).text();
            
    	eval(response);
    	    	
    	uploadPercent = Math.round(this.uploadStatus.percent) + '%';
    		
    	$("#" + this.formId + " #upload_progress_bar").animate({width:uploadPercent}, "fast");
    	$("#" + this.formId + " #upload_progress_info").empty();
    	$("#" + this.formId + " #upload_progress_info").append(this.uploadStatus.percent + '%');
    
        document.title = 'Uploading... ' + this.uploadStatus.percent + '%';
    
    	
    	if (this.uploadStatus.upload_complete === "false" && this.uploadComplete == false)
    	{
    		this.getProgressTimeout();	
    	}
    	else
    	{    	    
    		$("#" + this.formId + " #upload_progress_info").empty();
    		$("#" + this.formId + " #upload_progress_info").append('Processing... please wait');
    		
    		// new from mitchell
    		this.uploadComplete = true;
    		
    		$("#" + this.formId + " #upload_progress_info").empty();
    	    $("#" + this.formId + " #upload_progress_info").append('Done');
    	    $("#" + this.formId + " #upload_progress_bar").animate({width:'100%'}, "fast");
    	    
    	    // remove class, upload next one
        	$('li.file_upload:first').removeClass('file_upload');
    	    	
        	processAllUploads();	
    	}
    };
    
    // Do not delete
    FileUpload.prototype.getProgressInterval = function ()
    {
    	
    };
    
    FileUpload.prototype.refreshPage = function(url)
    {        
    	this.uploadComplete = true;
    	
    	//$("#" + this.formId + " #upload_progress_info").empty();
    	//$("#" + this.formId + " #upload_progress_info").append('Refreshing page');
    
    	//$("#" + this.formId + " #upload_progress_bar").animate({width:'100%'}, "fast");
    
    	// window.location = url;	
    	
    };