var link_idx=0;
function fileQueued(file) {
	try {			
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("<img src='images/queue.jpg'>");		
		progress.toggleCancel(true, this);
		try{
			$("#firstRun").remove();
		} catch (ex) {
			this.debug(ex);
		}
	} catch (ex) {
		this.debug(ex);
	}
}
function fileQueueError(file, errorCode, message) {
	try{
			$("#fListContainer").append("<table class='imageitem'><tr><td class='fname'><h2>"+file.name+" (<span class='txtred'>ERR:"+errorCode+"</span>)</h2></td></tr></table>");
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
	} catch (ex) {
        this.debug(ex);
    }
}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
	try {
		if (numFilesSelected > 0) {
			document.getElementById(this.customSettings.cancelButtonId).disabled = false;
		}
		try{
			if ($("#doResize").val() != 0){
				postParams.extCmd='[{"cmd":"resize","cmdParams":'+$("#doResize").val()+'}]';
			}else{
					postParams.extCmd=0;
			}
			 swfu.setPostParams(postParams);		
		}catch(ex){}	
		/* I want auto start the upload and I can do that here */
		this.startUpload();
	} catch (ex)  {
        this.debug(ex);
	}
}

function uploadStart(file) {
	try {
		/* I don't want to do any file validation or anything,  I'll just update the UI and
		return true to indicate that the upload should start.
		It's important to update the UI here because in Linux no uploadProgress events are called. The best
		we can do is say we are uploading.
		 */
		try{
			$("select[name=doResize]").attr('readonly', true);
			if ($("select[name=doResize] option:selected").val() != 0 && $("select[name=doResize] option:selected").val() != undefined ){
				postParams.extCmd='[{"cmd":"resize","cmdParams":'+$("select[name=doResize] option:selected").val()+'}]';
			}else{
					postParams.extCmd=0;
			}
			 swfu.setPostParams(postParams);		
		}catch(ex){}	
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("<img src='images/spinner.gif'>");
		progress.toggleCancel(true, this);

	}
	catch (ex) {}
	
	return true;
}

function uploadProgress(file, bytesLoaded, bytesTotal) {
	try {
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setProgress(percent);
		progress.setStatus("<img src='images/spinner.gif'>");
	} catch (ex) {
		this.debug(ex);
	}
}
function copyText(theSel) {
//theForm = theSel.form;
//theForm.copyArea.value=theSel.options[theSel.selectedIndex].value;
//r=theForm.copyArea.createTextRange();
alert("Copy to clipboard");
r=$(theSel);
r.select();
r.execCommand('copy');

} 
function uploadSuccess(file, serverData) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setComplete();
		progress.setStatus("<img src='images/ok.png'>");
		//progress.toggleCancel(false);
		//alert(serverData);
		var obj = eval(serverData);
			
		if (obj[0] ==0){
			var fstate;
			if (obj[1]['result'] == 1)
				fstate="<span class='txtblue'>Success </span>";			
			else
				fstate="<span class='txtred'>Duplicate</span>";
			link_idx++;
			var htmltxt="<table class='imageitem'><tr><td colspan=2 class='fname'><h2>"+obj[1]['filename']+" ("+fstate+")</h2></td></tr><tr><td class='thumbcontainer' valign='center'><a href='"+obj[1]['showurl']+"' target=\"_blank\"><img src="+obj[1]['tdst']+"></a></td><td class='codecontainer'><h2>Direct link </h2><input type=text value='"+obj[1]['showurl']+"' class='txtcode' readonly=\"readonly\" onmouseover=\"javascript:this.focus();this.select();\" >";
			if (special != true){
			htmltxt+="<h2>HTML Code [Full image] </h2><input type=text value='"+obj[1]['htmlfull']+"' class='txtcode' readonly=\"readonly\" onmouseover=\"javascript:this.focus();this.select();\"><h2>HTML Code [Thumb image] </h2><input type=text value='"+obj[1]['htmlthumb']+"' class='txtcode' readonly=\"readonly\" onmouseover=\"javascript:this.focus();this.select();\">";
			}
			htmltxt+="<h2>BBCode [Full image] </h2><input type=text value='"+obj[1]['bbfull']+"' class='txtcode' readonly=\"readonly\" onmouseover=\"javascript:this.focus();this.select();\" ><h2>BBCode [Thumb image] </h2><input type=text value='"+obj[1]['bbthumb']+"' class='txtcode' readonly=\"readonly\" onmouseover=\"javascript:this.focus();this.select();\"></td></tr></table>";			
			$("#fListContainer").append(htmltxt);
			var  htmlAllFull=$("#htmlAllFull").val();
			var  htmlAllTmb=$("#htmlAllThumb").val();
			var  bbAllFull=$("#bbAllFull").val();
			var  bbAllTmb=$("#bbAllThumb").val();
			$("#htmlAllFull").val(htmlAllFull+obj[1]['htmlfull']);
			$("#htmlAllThumb").val(htmlAllTmb+obj[1]['htmlthumb']);			
			$("#bbAllFull").val(bbAllFull+" "+obj[1]['bbfull']);
			$("#bbAllThumb").val(bbAllTmb+" "+obj[1]['bbthumb']);
		}else{
			$("#fListContainer").append("<table class='imageitem'><tr><td class='fname'><h2>"+obj[1]['filename']+" (<span class='txtred'>Error: "+obj[0]+"-"+obj[1]['errmsg']+"</span>)</h2></td></tr></table>");
		} 
		
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadError(file, errorCode, message) {
	try{
				if (message == null) message="Server error, please try again later!";
				$("#fListContainer").append("<table class='imageitem'><tr><td class='fname'><h2>"+file.name+" (<span class='txtred'>"+message+"</span>)</h2></td></tr></table>");
					var progress = new FileProgress(file, this.customSettings.progressTarget);
					progress.setError();		

		
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
	} catch (ex) {
        this.debug(ex);
    }
}

function uploadComplete(file) {
	if (this.getStats().files_queued === 0) {
		document.getElementById(this.customSettings.cancelButtonId).disabled = true;
		$("select[name=doResize]").removeAttr('readonly');

	}
}

// This event comes from the Queue Plugin
function queueComplete(numFilesUploaded) {
	var status = document.getElementById("divStatus");
	status.innerHTML = numFilesUploaded + " file" + (numFilesUploaded === 1 ? "" : "s") + " uploaded.";
}

function FileProgress(file, targetID) {
	this.fileProgressID = file.id;
	this.opacity = 100;
	this.height = 0;
	this.fileProgressWrapper = document.getElementById(this.fileProgressID);
	if (!this.fileProgressWrapper) {
		this.fileProgressWrapper = document.createElement("div");
		this.fileProgressWrapper.className = "progressWrapper";
		this.fileProgressWrapper.id = this.fileProgressID;

		this.fileProgressElement = document.createElement("div");
		this.fileProgressElement.className = "progressContainer";

		var progressCancel = document.createElement("a");
		progressCancel.className = "progressCancel";
		progressCancel.href = "#";
		progressCancel.style.visibility = "hidden";
		progressCancel.appendChild(document.createTextNode(" "));

		var progressText = document.createElement("div");
		progressText.className = "progressName";
		progressText.appendChild(document.createTextNode(file.name));

		var progressBar = document.createElement("div");
	
		var progressStatus = document.createElement("div");
		progressStatus.className = "progressBarStatus";
		progressStatus.innerHTML = "&nbsp;";

		this.fileProgressElement.appendChild(progressCancel);
		this.fileProgressElement.appendChild(progressText);
		this.fileProgressElement.appendChild(progressStatus);
		this.fileProgressElement.appendChild(progressBar);

		this.fileProgressWrapper.appendChild(this.fileProgressElement);

		document.getElementById(targetID).appendChild(this.fileProgressWrapper);
	} else {
		this.fileProgressElement = this.fileProgressWrapper.firstChild;
		this.reset();
	}

	this.height = this.fileProgressWrapper.offsetHeight;
}

FileProgress.prototype.reset = function () {
	this.fileProgressElement.className = "progressContainer";
	this.fileProgressElement.childNodes[2].innerHTML = "&nbsp;";
	this.fileProgressElement.childNodes[2].className = "progressBarStatus";
	$("#eProgressBar").width("0%");
	$("#eProgressBar").className="progressBarInProgress";
	$("#eProgressBar").text("");
	$(this.fileProgressWrapper).fadeIn('slow');
};

FileProgress.prototype.setProgress = function (percentage) {
	this.fileProgressElement.className = "progressContainer green";
	$("#eProgressBar").width(percentage + "%");
	$("#eProgressBar").className="progressBarInProgress";
	$("#eProgressBar").text(percentage + "%");
	$(this.fileProgressWrapper).fadeIn('slow');
};
FileProgress.prototype.setComplete = function () {
	this.fileProgressElement.className = "progressContainer blue";
	$("#eProgressBar").width("0%");
	$("#eProgressBar").className="progressBarComplete";
	$("#eProgressBar").text("");
	$(this.fileProgressWrapper).fadeOut(2000);

};
FileProgress.prototype.setError = function () {
	this.fileProgressElement.className = "progressContainer red";
	$("#eProgressBar").width("0%");
	$("#eProgressBar").text("");
	$(this.fileProgressWrapper).fadeOut(2000);
};
FileProgress.prototype.setCancelled = function () {
	this.fileProgressElement.className = "progressContainer";
	$("#eProgressBar").width("0%");
	$(this.fileProgressWrapper).fadeOut(2000);
};
FileProgress.prototype.setStatus = function (status) {
	this.fileProgressElement.childNodes[2].innerHTML = status;
};

// Show/Hide the cancel button
FileProgress.prototype.toggleCancel = function (show, swfUploadInstance) {
	this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
	if (swfUploadInstance) {
		var fileID = this.fileProgressID;
		this.fileProgressElement.childNodes[0].onclick = function () {
			swfUploadInstance.cancelUpload(fileID);
			return false;
		};
	}
};

var SWFUpload;
if (typeof(SWFUpload) === "function") {
	SWFUpload.queue = {};
	
	SWFUpload.prototype.initSettings = (function (oldInitSettings) {
		return function () {
			if (typeof(oldInitSettings) === "function") {
				oldInitSettings.call(this);
			}
			
			this.queueSettings = {};
			
			this.queueSettings.queue_cancelled_flag = false;
			this.queueSettings.queue_upload_count = 0;
			
			this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
			this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler;
			this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler;
			this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler;
			
			this.settings.queue_complete_handler = this.settings.queue_complete_handler || null;
		};
	})(SWFUpload.prototype.initSettings);

	SWFUpload.prototype.startUpload = function (fileID) {
		this.queueSettings.queue_cancelled_flag = false;
		this.callFlash("StartUpload", [fileID]);
	};

	SWFUpload.prototype.cancelQueue = function () {
		this.queueSettings.queue_cancelled_flag = true;
		this.stopUpload();
		
		var stats = this.getStats();
		while (stats.files_queued > 0) {
			this.cancelUpload();
			stats = this.getStats();
		}
	};
	
	SWFUpload.queue.uploadStartHandler = function (file) {
		var returnValue;
		if (typeof(this.queueSettings.user_upload_start_handler) === "function") {
			returnValue = this.queueSettings.user_upload_start_handler.call(this, file);
		}
		
		// To prevent upload a real "FALSE" value must be returned, otherwise default to a real "TRUE" value.
		returnValue = (returnValue === false) ? false : true;
		
		this.queueSettings.queue_cancelled_flag = !returnValue;

		return returnValue;
	};
	
	SWFUpload.queue.uploadCompleteHandler = function (file) {
		var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler;
		var continueUpload;
		
		if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) {
			this.queueSettings.queue_upload_count++;
		}

		if (typeof(user_upload_complete_handler) === "function") {
			continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true;
		} else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) {
			// If the file was stopped and re-queued don't restart the upload
			continueUpload = false;
		} else {
			continueUpload = true;
		}
		
		if (continueUpload) {
			var stats = this.getStats();
			if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) {
				this.startUpload();
			} else if (this.queueSettings.queue_cancelled_flag === false) {
				this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]);
				this.queueSettings.queue_upload_count = 0;
			} else {
				this.queueSettings.queue_cancelled_flag = false;
				this.queueSettings.queue_upload_count = 0;
			}
		}
	};
}

