function remove(id){
    var field = document.getElementById(id);
    var parent = $(field).parent();
    var icon = $('.fileIcon img', parent);
    var filename = $('.fileName', parent);
    var removeButton = $('.remove', parent).attr('disabled', 'true').blur();
    
    $(field).val('');
    icon.attr('src', baseDir + 'img/file_icons/file.png');
    filename.html('No file uploaded');
}

$(document).ready(function(){
	
	if($('#admin-bar').get(0)) {
		$('body').css({
			'margin-top': '50px',
			'background-position': '0px 50px'
		});
		
		$('#admin-bar a').each(function(){
			$(this).html('<span>' + $(this).html() + '</span>');
		}).click(function(){
			$(this).blur();
		})
	}
	
	$('#logout-link').click(function(){
		$('#admin-bar').slideUp('fast').fadeOut();
	})
	
    $('.fileUpload').each(function(i){
        var uploader;
        var fileList;
        var totalSize;
        var currentProgress;
        var updateProgressInterval;
        var swfu;
        var uploaderTargetId = 'PageElementImage';
		
		var uploaderTargetId = $('input[type=hidden]', $(this).parent()).attr('id');
		
        var hasError = false;
        $('.upload', $(this)).before('<span id="spanButtonPlaceholder' + i + '"></span>');
        $('#spanButtonPlaceholder').css('position', 'absolute');
        swfu = new SWFUpload({
        
            // Backend Settings
            upload_url: baseServer + baseDir + 'uploads/send/image/' + uploaderTargetId + '.json', // Relative to the SWF file
            post_params: {
                "PHPSESSID": sessionId
            },
            
            // File Upload Settings
            file_size_limit: uploadFileSizeLimit,
            file_types: "*",
            file_types_description: "Files",
            file_upload_limit: "0",
            
            // Event Handler Settings
            file_queue_error_handler: uploadError,
            file_dialog_complete_handler: fileDialogComplete,
            upload_progress_handler: onUploadProgress,
            upload_error_handler: uploadError,
            upload_success_handler: uploadSuccess,
            upload_complete_handler: eventHandler,
            upload_start: eventHandler,
            file_dialog_start_handler: fileDialogStart,
            
            // Button Settings
            button_placeholder_id: "spanButtonPlaceholder" + i,
            button_width: 61,
            button_height: 22,
            button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
            button_cursor: SWFUpload.CURSOR.HAND,
            
            
            // Flash Settings
            flash_url: baseDir + "js/swfupload/swfupload.swf", // Relative to this file
            // Debug Settings
            debug: false
        
        });
		$('.swfupload').css({
			'position': 'absolute',
			'top': 		'12px',
			'left': 	'3px',
			'height': '30px'
		});
		$('.fileActions').css('position', 'relative');
        
        
        function uploadError(file, errorCode, message){
            // hasError is set when the error prevents the upload from continuing.
            if (errorCode == -110) {
				hasError = true;
				alert('Sorry, you cannot upload files bigger than ' + uploadFileSizeLimit + '.\nPlease contact your server admin to get this limit raised.');
			} else {
				if (errorCode == -280) {
					hasError = false;
				} else {
					hasError = true;
					alert('Sorry, there was a problem uploading your file.\n\n' + message + '\n\nError code: ' + errorCode);
				}
			}
        }
        
        function eventHandler(event, data){
        
            //console.log(event);
            //console.log(data);
        }
        
        function browse(id){
        
			alert('Sorry, you need to install Flash Player 9 or above to use this upload feature.')
            /*swfu.selectFile();
            //this.blur();
            
            uploaderTargetId = id;*/
        }
        
        
        function cancel(id){
            // TODO: Add id to the cancel operation
            swfu.cancelUpload();
            restoreUploader(id, '', baseDir + 'img/file_icons/file.png', 'No file uploaded');
            remove(id);
        }
        
        function fileDialogStart(){
        
        }
        
        function fileDialogComplete(filesSelected){
            if (filesSelected == 1 && hasError == false) {
                this.startUpload();
                this.setUploadURL(baseServer + baseDir + 'uploads/send/image/' + uploaderTargetId + '.json');
                var field = document.getElementById(uploaderTargetId);
                var parent = $(field).parent();
                
                $('.fileProgress, .fileActions .cancel', parent).show();
                $('.fileActions .upload, .fileActions .remove', parent).hide();
                
                updateProgressInterval = setInterval(updateProgress, 100);
            }
            else {
                hasError = false;
                //console.log('No files selected');
            }
        }
        
        
        function updateProgress(){
            //console.log('Progress: ' + currentProgress + ' out of ' + totalSize);
            var field = document.getElementById(uploaderTargetId);
            var parent = $(field).parent();
            
            progress = currentProgress / totalSize;
            percent = Math.ceil(progress * 1000) / 10;
            percent = percent.toFixed(1);
            
            $('.fileProgressBar', parent).css('width', percent + '%');
            $('.fileProgressText', parent).html(percent + '% - ' + Math.round(currentProgress / 1024) + 'kb of ' + Math.round(totalSize / 1024) + 'kb');
        }
        
        function onUploadProgress(file, complete, total){
            //console.log('some upload progress');
            
            currentProgress = complete;
            totalSize = total;
        }
        
        
        function onUploadComplete(event){
            //YAHOO.log(event);
        
        
        }
        
        function onUploadError(event){
            alert('Sorry! There was a bit of a problem uploading the file.')
            //YAHOO.log(event, "error");
        }
        
        function onUploadCancel(event){
            //YAHOO.log(event);
        }
        
        function restoreUploader(id, newFilename, iconFile, originalFilename){
            var field = document.getElementById(id);
            var parent = $(field).parent();
            
            var icon = $('.fileIcon img', parent);
            var filename = $('.fileName', parent);
            var removeButton = $('.remove', parent).attr('disabled', '');
            
            $('.fileProgressBar', parent).css('width', '0%');
            $('.fileProgress, .fileActions .cancel', parent).hide();
            $('.fileActions .upload, .fileActions .remove', parent).show();
            
            $(field).val(newFilename);
            icon.attr('src', iconFile);
            filename.html(originalFilename);
        }
        
        function removeComments(html){
            return html.replace(/<!(?:--[\s\S]*?--\s*)?>\s*/g, '');
        }
        
        
        function uploadSuccess(file, data){
            //console.log('Upload Success');
            //console.log(data);
            clearInterval(updateProgressInterval);
            
            // TODO: Replace with safe JSON parse, not really important given the flash movie
            // will only ever communicate with the current server.
            var response;
            try {
                data = removeComments(data);
                response = eval('(' + data + ')');
            } 
            catch (e) {
                alert(e + '\nData sent:\n' + data);
            }
            
            if (response.success) {
                restoreUploader(response.id, response.newFilename, response.icon, response.originalFilename);
            }
            else {
                alert('Sorry, there was a problem uploading your file.\n\nIt could be that the file was too big.');
                alert(data);
            }
        }
        
        function onUploadResponse(event){
            clearInterval(updateProgressInterval);
            
            // TODO: Replace with safe JSON parse, not really important given the flash movie
            // will only ever communicate with the current server.
            var response = eval('(' + event.data + ')');
            if (response.success) {
                //alert(response.originalFilename);
                restoreUploader(response.id, response.newFilename, response.icon, response.originalFilename);
            }
            else {
                alert('Sorry, there was a problem uploading your file.\n\nIt could be that the file was too big.');
                alert(event.data);
            }
            //YAHOO.log(event.data);
        }
    });
    
});
