var UF = [];
// public
UF.def_upload_url = SELF_URL+"upload_ajax";
UF.def_remove_url = false;
UF.def_btn_container_id = "upload_button";
UF.def_progress_id = "upload_progress";
UF.def_input_id = "upload_input";
// public 2
UF.swfupload_url = BASEURL+"js/swfupload2/swfupload.min.js"
UF.btn_image_url = BASEURL+'images/btn-browse.png';
UF.btn_image_width = 61;
UF.btn_image_height = 22;
UF.msg_success = '<font color="green">ok</font>';
UF.msg_error = '<font color="red">error</font>';
UF.msg_replace = 'Are you sure you want to replace your current file attachment?';
UF.msg_delete = 'Delete?';
UF.session = "&PHPSESSID="+PHPSESSID;
UF.max_file_size = 1000; // MB
// private
UF.swfu = [];
// stats
UF.in_progress = 0;
UF.files_queued = 0;
UF.successful_uploads = 0;
UF.upload_errors = 0;
UF.upload_cancelled = 0;
UF.queue_errors = 0;
// callbacks
UF.onSuccess = false;
UF.onError = false;
// implementation
UF.$ = function(id) { return document.getElementById(id); }
UF.insert = function( btn_container_id, upload_url, progress_id, input_id ) {
	if (typeof(SWFUpload) == "undefined") { alert('SWFUpload not defined'); return false; }
	
	if (typeof(upload_url) == "undefined") upload_url = UF.def_upload_url;
	if (upload_url.indexOf('?') == -1)
		upload_url += "?";
	upload_url += UF.session;
	
	if (typeof(btn_container_id) == "undefined") btn_container_id = UF.def_btn_container_id;
	if (typeof(progress_id) == "undefined") progress_id = UF.def_progress_id;
	if (typeof(input_id) == "undefined") input_id = UF.def_input_id;

	UF.swfu[UF.swfu.length] = new SWFUpload({
		debug: false,
		upload_url : upload_url,
		file_types : "*.*",
		file_types_description: "All Files",
		file_size_limit : UF.max_file_size+" MB",
		file_upload_limit : UF.max_file_size, 
		// button
		button_placeholder_id : btn_container_id,
		button_image_url : UF.btn_image_url,
		button_width : UF.btn_image_width,
		button_height : UF.btn_image_height,
		button_action : SWFUpload.BUTTON_ACTION.SELECT_FILE,
		/*
		button_disable : false,
		button_cursor : SWFUpload.CURSOR.HAND,
		button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT, 
		*/
		// handlers
//		file_dialog_start_handler : UF.fileDialogStart, 
//		file_dialog_complete_handler : UF.fileDialogComplete,
		//fileQueued
		file_queued_handler: UF.fileQueued,
		file_queue_error_handler : UF.fileQueueError,		
		upload_start_handler : UF.uploadStart,
		upload_progress_handler : UF.uploadProgress,
		upload_error_handler : UF.uploadError,
		upload_success_handler : UF.uploadSuccess,
		upload_complete_handler : UF.uploadComplete,
		// UF
		custom_settings : {
			btn_container_id: btn_container_id,
			upload_url: upload_url,
			input_id: input_id,
			progress_id: progress_id
		} 
	});
}
UF.getStats = function() {
	return {
		in_progress: UF.in_progress,
		files_queued: UF.files_queued,
		successful_uploads: UF.successful_uploads,
		upload_errors: UF.upload_errors,
		upload_cancelled: UF.upload_cancelled,
		queue_errors: UF.queue_errors
	}
}
UF.resetStats = function() {
	UF.in_progress = 0;
	UF.files_queued = 0;
	UF.successful_uploads = 0;
	UF.upload_errors = 0;
	UF.upload_cancelled = 0;
	UF.queue_errors = 0;	
}
UF.resetState = function() {
	for (var i = 0; i < UF.swfu.length; i++) {
		UF.swfu[i].destroy();
	}
	UF.swfu = [];
	UF.resetStats();
}
// SWFUpload handlers
UF.fileQueued = function (numFilesSelected, numFilesQueued) {
	if (this.getStats().files_queued == 0) return false;
	
	var el = UF.$(this.customSettings.input_id);	
	if (el != null && el.value != '' && !confirm(UF.msg_replace)) return false;
	UF.files_queued++;
	this.startUpload();
}
UF.fileQueueError = function(file, errorCode, message) {
	alert("Sorry! You can't upload "+file.name+". Max file size is "+UF.max_file_size+" MB");
}
UF.uploadStart = function(file) {
	var el = UF.$(this.customSettings.input_id);
	if (el != null) el.value = file.name;
	UF.in_progress++;
}
UF.uploadProgress = function (file, bytesLoaded, bytesTotal) {
	var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
	var el = UF.$(this.customSettings.progress_id);
	if (el != null) el.innerHTML = percent + '%';
}
UF.uploadSuccess = function(file, response) {
//	alert(response);
	reponse = response.replace(/\s/, "");
	
	var el = UF.$(this.customSettings.progress_id);
	if (el == null) return;
	if (response == '' || response == 'OK') {
		UF.successful_uploads++;
		el.innerHTML = UF.msg_success;
		if (UF.onSuccess) UF.onSuccess();
	} else {
		UF.upload_errors++;
		el.innerHTML = UF.msg_error;
		var el = UF.$(this.customSettings.input_id);
		if (el != null) el.value = "";
		if (UF.onError) UF.onError( response );
	}
}
UF.uploadError = function (file, errorCode, message) {
	var el = UF.$(this.customSettings.progress_id);
	if (el != null) {
		el.innerHTML = UF.msg_error;
	}
	el = UF.$(this.customSettings.input_id);
	if (el != null) {
		el.value = '';
	}
	UF.upload_errors++;
}
UF.uploadComplete = function (file) { // after success || error || 
//alert(1);
	UF.in_progress--;
}
UF.cancelUpload = function ( btn_container_id ) {
	for (var i = 0; i < UF.swfu.length; i++)
		if ( UF.swfu.customSettings.btn_container_id == btn_container_id) {
			UF.swfu[i].cancelUpload();
			UF.upload_cancelled++;
			break;
		}
}
UF.stopUpload = function( btn_container_id ) {
	if (typeof(btn_container_id) == "undefined") // stop all
		for (var i = 0; i < UF.swfu.length; i++)
			UF.stopInstanceUpload( UF.swfu[i] );
	else
		for (var i = 0; i < UF.swfu.length; i++)
			if ( UF.swfu.customSettings.btn_container_id == btn_container_id) {
				UF.stopInstanceUpload( UF.swfu[i] );
				break;
			}
}
UF.stopInstanceUpload = function ( instance ) {
	instance.stopUpload();
	var stats;
	do {
		stats = instance.getStats();
		instance.cancelUpload();
	} while (stats.files_queued !== 0);	
}
// Extended version
UF.field_index = 0;
UF.init = function() {
	var divs = document.getElementsByTagName("DIV");
	for (var i = 0; i < divs.length; i++) {
		if ( divs[i].id && (r = divs[i].id.match(/divFile(\d+)/))) {
			n = r[1];
			UF.insertEx( n );
			if ( n > UF.field_index) UF.field_index = n; 
		}
	}
}
UF.insertEx = function ( index ) {
	var s = (UF.def_upload_url.indexOf('?') != -1) ? "&" : "?";
	var url = UF.def_upload_url + s + "index="+index;
	UF.insert(UF.def_btn_container_id+index, url, UF.def_progress_id+index, UF.def_input_id+index);
}
UF.addFileField = function() {
	UF.field_index++;
	var tpl = UF.$('divFile').innerHTML;
	tpl = tpl.replace(/ID/g, UF.field_index);
	obj = document.createElement("DIV");
	obj.id = "divFile" + UF.field_index;
	obj.innerHTML = tpl;
	
	UF.$('divFileContainer').appendChild(obj);
	UF.insertEx( UF.field_index );
}
UF.delFileField = function( index ) {
	if (UF.$(UF.def_input_id + index).value != '') {
		if (!confirm('Delete?')) return false;
		if (UF.successful_uploads > 0) UF.successful_uploads--;
	}
	UF.$('divFile'+index).parentNode.removeChild(UF.$('divFile'+index)); 
	if (UF.def_remove_url && typeof(ajax) != "undefined") {
		var s = (UF.def_remove_url.indexOf('?') != -1) ? "&" : "?";
		var url = UF.def_remove_url + s + "index="+index;
		ajax( url );
	}
}
// init
if (window.addEventListener) 
	window.addEventListener("load", UF.init, false);
else if (window.attachEvent) 
	window.attachEvent("onload", UF.init);
else window.onload = UF.init;
// include sfwupload library
document.write('<scr'+'ipt type="text/javascript" src="'+UF.swfupload_url+'"></scr'+'ipt>');