# ****************************************************************************
# Surgeweb javascript - Ajax based attachment handling
# Note: sw.js is the primary surgeweb javascript code
# ----------------------------------------------------------------------------
# Implementation of "attachment queue" associated with a message. 
#   managed via Form upload dialog, Flash uploader, or desktop DND
# Implementation focus: functional code deals with a series of objects - tied
# DOM node which represents message in this case
# ****************************************************************************

function aq_init(node)
{
	var aq,ret=true;
	dbg('aq_init')
	if(!node.aq) {
		node.aq={};
		aq=node.aq;
		aq.queue=[];
	}
	node.attachments_init=true;

	var o=node.aq_container;
	if (class_contains(o,'hidden')){
		class_remove(o,'hidden');
		class_add(o.previousSibling,'hidden');
		if(sw.is_popup){
			popup_resize();
		}else{	
			do_resize_real();
		}
	}

	if(html5_available()){
		class_remove(node.html5_select,'hidden');
	} else if(swfu_available()){
		if(!node.aq.swfu){
			setTimeout(function(){swfu_upload_init(sw.active);},10);
		}else{
			ret=false;
		}
	}
	return ret;
}
function aq_total(node,o)
{
	var len=o.length;
	node.innerHTML=$('$$st_att_uploaded$$',len,plural(len));
}

# also see fdnd_msg_hover

# Add one attachment based on uploaded results
function aq_attachment_jmsg_addone(node,att)
{
	var jmsg=node.jmsg;
	attach_init(jmsg);
	jmsg.attach_ids.push(att[1]);
	jmsg.attach_info.push(att);
}
function attach_init(jmsg, force)
{
	if (force==true || !jmsg.attach_ids){
		jmsg.attach_ids=[];
		jmsg.attach_info=[];		
	}
}


# set multiple attachments based on fwd / fwd attach etc result
function aq_attachments_set(node,attach,attach_mpr,timeout)	// QQQA
{
	var aq=node.aq;
	if(html5_available()){
		// Nothing to do
	} else if((aq && !aq.swfu) && swfu_available()) {
#		// Bother the flash uploader is not yet initialised, wait for up to 30 seconds
		if(!timeout){
			timeout=300;
		}else{
			if(timeout==0) return;
		}
		setTimeout(function(){aq_attachments_set(node,attach,attach_mpr,--timeout)},100);
		return;
	}

#	// If we are adding it after popin / out then RESET the jmsg count here
#	node.jmsg.attach_ids=[];	
	aq_removeall(node);
	for(var i=0;i<attach.length;i++){
		aq_attach_one(node,attach[i]);
	}
	node.jmsg.attach_ids_mpr=attach_mpr;
	dge('btnCancel').disabled = false;
}
function aq_attach_one(node,att)
{
	var o=node.jmsg.attach_mid=att[0];

	var file={};
	file.id='myattach-'+att[0]+'-'+att[1];
	file.name=att[2];
	var progress = new AqUiWrapper(file, node.aq_files.id, (node.jmsg.action=='redirect'));

	progress.setComplete();
	attachment_add_jmsg(node,att);
	aq_total(node.attach_status,node.jmsg.attach_ids);

	progress.fileProgressWrapper.sw_id=att[1];
	progress.setStatus(att[3]);
	progress.toggleCancel(true, node.aq.swfu);
}


function aq_remove(node,id)
{
	var jmsg=node.jmsg;
	var i=my_indexOf(jmsg.attach_ids,id);
	if(i!=-1){
		jmsg.attach_ids.splice(i,1);
		jmsg.attach_info.splice(i,1);
	}
	aq_total(node.attach_status,jmsg.attach_ids);
}
function aq_removeall(node)
{
	if(node.aq && swfu_available() && swfu_ready(node.aq.swfu)) node.aq.swfu.cancelQueue();
	node.aq_files.innerHTML="";
	attach_init(node.jmsg,true);
	dbg('attachment remove all pressed')
	aq_total(node.attach_status,node.jmsg.attach_ids);
}


# ---
# callback related utility code
# ---
var g_new_attach=[],g_new_attach_mpr;
function aq_results(att,att_mpr)
{
#	dbg('results: '+att.length+' attachments');
	g_new_attach=att;
	g_new_attach_mpr=att_mpr;
}

# ---
# Attachment form based dialog code
# ---
function do_attach_simple()
{
#	if we get here the Flash based attachments are unavailable
	attach_dialog();
#	alert('$$st_err_noflash2$$');
}
function do_attach_filestore()
{
	alert('unimplemented')
}

# ---
# Filesystem drag and drop based interfacing
# ---
var fdnd={};
fdnd.queue=[];
fdnd.uploading=false;
fdnd.count=0;
function aq_fdnd_init(node)
{
}
function aq_fdnd_add(file)
{
	dbg('File dropped '+file.name+' size='+file.size);
	var fdnd_item={}
	fdnd_item.file=file;
	var node=sw.active;
	file.id='DNDUpload_'+(fdnd.count++);
	file.node=node;
	var progress = new AqUiWrapper(file, node.aq_files.id, (node.jmsg.action=='redirect'));
	fdnd.queue.push(fdnd_item);
	dge('btnCancel').disabled = false;	
	progress.toggleCancel(true, node.aq.swfu);
	// cf aq_attach_one	
}
function aq_fdnd_upload()
{
	if(fdnd.uploading) return;
	fdnd.uploading=true;
	var item=fdnd.queue.shift();
	var file=item.file;
	var progress = new AqUiWrapper(file, file.node.aq_files.id, (file.node.jmsg.action=='redirect'));
	dbg('UPLOAD ATTEMPTED: '+file.name);
	var win=sw.is_popup?sw_win:window;	
	win.ajax_upload(file,U,
		function(success){
			dbg('progress 1')
			if(!success){
				progress.setError();
			}else{
#				QQQ DND	ATTACH
				var att=win.g_new_attach[0];
				progress.setComplete();
				attachment_add_jmsg(file.node,att);
				progress.fileProgressWrapper.sw_id=att[1];
				aq_total(file.node.attach_status,file.node.jmsg.attach_ids);
				progress.setStatus(att[3]);
			}
			fdnd.uploading=false;
			if(fdnd.queue.length>0) setTimeout(aq_fdnd_upload,0);
			dbg('progress 2')
		},
		function(bytesLoaded,bytesTotal){
			dbg('progress A')
			var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
			progress.setProgress(percent);
			dbg('progress B')
		}
		,true);
}
function swfu_upload_progress_cb(file, bytesLoaded, bytesTotal) 
{
	swfu=this;
	var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
	dbg("RAW progress: "+percent+"%");
	var progress = new AqUiWrapper(file, swfu.customSettings.progressTarget);
	progress.setProgress(percent);
}


function html5_available()
{
#	//seems a bit of a dodgy test for html5 uploader availability but best I could find
	if (isIE && isVersion<=10) return false;
	try {
		var dummy = new FileReader();
	}catch(e){
		return false;
	}
	if (pref.attach_flash=='html5') return true;
#	// Upgrade old "flash default" to html5 if we can :-)
	if (pref.attach_flash=='' || pref.attach_flash=='flash') return true;
	return false;
}
# ---
# SWF surgeweb interface to Flash file uploader module
# ---
function swfu_available()
{
	if(pref.attach_flash=='form') return false;
#	// flash value now switched to "flash_old", so old "flash" value will actually default to html5
	if(pref.attach_flash=='flash') return false;
	if(sw.swf_version<10) return false;
	return true;	
}
function swfu_ready(swfu)
{
	if(!swfu) return false;
	var movie = swfu.getMovieElement();
	if(!movie) return false;
	if (typeof(movie.StartUpload) !== "function") return false;
	return true;
}
function swfu_upload_init(node) 
{
	if (!swfu_available()) return;
	
	var plain_btn = sw.active.button_place_holder.nextSibling.nextSibling;
	var settings = {
		flash_url : "||www_base||shared/modules/swfupload.swf",
		upload_url: '||cgi||?cmd=attach_upload,show&sid='+sid+'&if=ajax&page=~result.js',	// Relative to the SWF file

		button_width: plain_btn.offsetWidth,
		button_height: plain_btn.offsetHeight,
		button_placeholder_id: 'spanButtonPlaceHolder'+sw.active.instance,

		post_params: {'attach_mid' : sw.active.jmsg.attach_mid},
		file_size_limit : "100 MB",
		file_types : "*.*",
		file_types_description : "All Files",
		file_upload_limit : 100,
		file_queue_limit : 0,
		prevent_swf_caching: isIE,		
		custom_settings : {
			progressTarget : node.aq_files.id,
			cancelButtonId : "btnCancel"
		},
		debug: false,

		file_queued_handler : swfu_queued_cb,
		file_queue_error_handler : swfu_queue_error_cb,
		file_dialog_complete_handler : swfu_dlg_complete_cb,
		upload_start_handler : swfu_upload_start_cb,
		upload_progress_handler : swfu_upload_progress_cb,
		upload_error_handler : swfu_upload_error_cb,
		upload_success_handler : swfu_upload_success_cb
	};
	
#	// Safari & FF do not these cookies through Flash, so do ourselves
#	//  but the following does not work under IE!! go figure.... at least it does enough to do what I want  :-)
	var s=get_cookie("SW-AUTHTOKEN");
	if (s) settings.post_params['SW-AUTHTOKEN']=s;

	node.aq.swfu = new SWFUpload(settings);
	node.aq.swfu.sw_panel=node;
}

# swfu callbacks
function swfu_queued_cb(file,id) 
{
	if(!id) id=this.customSettings.progressTarget;
	var progress = new AqUiWrapper(file, id);
	progress.toggleCancel(true, this);
	dbg('******** attachment queued fname='+file.name);
}
function swfu_queue_error_cb(file, errorCode, message) 
{
	if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
		var err=(message===0?'$$st_att_limit$$' : $('$$st_att_selectn$$', message, plural(message)) );
		alert("$$st_att_toomany$$\n" + err);
		return;
	}
	var progress = new AqUiWrapper(file, this.customSettings.progressTarget);
	progress.setError();
#	progress.toggleCancel(false);
	switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: progress.setStatus("$$st_att_toobig$$"); break;
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: progress.setStatus("$$st_att_zerosize$$"); break;
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE: progress.setStatus("$$st_att_invalid$$"); break;
		default: if (file !== null) { progress.setStatus("$$st_att_unhandled$$");}
	}
}
function swfu_dlg_complete_cb(numFilesSelected, numFilesQueued) 
{	
	swfu=this;
	if (numFilesSelected > 0) {
		dge(swfu.customSettings.cancelButtonId).disabled = false;
	}
	
	swfu.startUpload();
}
function swfu_upload_start_cb(file) 
{
	swfu=this;
	var progress = new AqUiWrapper(file, swfu.customSettings.progressTarget);
	progress.toggleCancel(true, swfu);
}
function swfu_upload_progress_cb(file, bytesLoaded, bytesTotal) 
{
	swfu=this;
	var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
	dbg("RAW progress: "+percent+"%");
	var progress = new AqUiWrapper(file, swfu.customSettings.progressTarget);
	progress.setProgress(percent);
}
function swfu_upload_success_cb(file, serverData, id) 
{
	swfu=this;
	try {
		if(!id) id=swfu.customSettings.progressTarget;
		var progress = new AqUiWrapper(file, id);
		progress.setComplete();

		// Now our own result handling
		eval(serverData);
		var att=g_new_attach[0];
		sw.active.jmsg.attach_mid=att[0];
		progress.fileProgressWrapper.sw_id=att[1]; //g_attach_id;
		attachment_add_jmsg(sw.active,att);
		aq_total(sw.active.attach_status,sw.active.jmsg.attach_ids);
		progress.setStatus(att[3]);
		var jmsg=sw.active.jmsg;
		dbg('attachment uploaded [M'+jmsg.instance+'] ['+att.join(' ')+']  total='+jmsg.attach_ids.length);
	}catch(e){
		var reason='$$st_att_warn$$ ';
		if(e.name && e.message) reason+= '<br>'+e.name+':'+e.message;
		set_status(reason,'warning');
	}
}
function swfu_upload_error_cb(file, errorCode, message) 
{
	dbg('event uploadError');
	var progress = new AqUiWrapper(file, this.customSettings.progressTarget);
	progress.setError();
#	progress.toggleCancel(false);
	set_status('$$st_att_error$$ '+errorCode,'warning');
	if (errorCode==-220){
		x_alert('<div style="margin-left:70px;">$$st_att_fail1$$<br><br> $$st_att_fail2$$</div>');
	}
}


