

//var swfu = null;
//var file_progress_list_id = "";
//var swf_upload_hash = "";

function MySwfUpload(button_id, list_id, host_dir, upload_hash)
{
	var me = this;

	var file_progress_list_id = "";
	var swf_upload_hash = "";

	file_progress_list_id = list_id;

	swf_upload_hash = upload_hash;

	
	this.file_chosen = new Event();
	this.data_uploaded = new Event();


	var swfu = new SWFUpload({
		upload_url : "http://"+host_dir+"/save_file.php?up_id="+upload_hash
		, flash_url : "http://"+host_dir+"/js/swfup/swfupload.swf"

		// Button settings		
		, button_image_url: "http://"+host_dir+"/img/btn_browsefiles_all_2.gif" // Relative to the Flash file
		, button_placeholder_id : button_id
		, button_width: "287"
		, button_height: "30"
		, button_cursor : SWFUpload.CURSOR.HAND

		// The event handler functions
		, swfupload_loaded_handler : SwfLoaded
		, file_queued_handler : fileQueued
		, file_queue_error_handler : fileQueueError
		, upload_progress_handler : uploadProgress
		, upload_error_handler : uploadError
		, upload_complete_handler : uploadComplete

		, file_size_limit : "2000 MB"
		//, file_size_limit : "1100 MB"
	});


	this.Disable = function(){  }


	this.UploadStart = function()
	{
		//alert("UploadStart");
		swfu.startUpload();
		swfu.setButtonDisabled(true);
	}

	function SwfLoaded()
	{
		// pie veiksmīgas ielādes paslēpjam parasto html failu izvēli
		//E('file_list').style.display = "none";
		E('file_list').style.visibility = "hidden";

		// parādam flash ielādes pogas rāmi, kas satur pašu pogu
		//E('frame_flash_upload').style.display = "block";
		E('frame_flash_upload').style.visibility = "visible";

		//alert(8);
	}



	var tmp_target_inner_html = ''; // pagaidu vieta kopējā innerhtml glabāšanai, kas reāli tiks pievienota tikai tad, kad nebūs notikušas izmaiņas kādu laiku
	var tmp_target_last_change = 0; // seko pēdējai mainīšanas reizei, lai zinātu, kad updeitoties

	function fileQueued(file)
	{
		//alert("fileQueued");
		me.file_chosen.Fire();

		//alert(["fileQueued", file.id, file.index, file.name, file.size, file.type, file.creationdate, file.modificationdate, file.filestatus]);
		/*
		{
			id : string,			// SWFUpload file id, used for starting or cancelling and upload
			index : number,			// The index of this file for use in getFile(i)
			name : string,			// The file name. The path is not included.
			size : number,			// The file size in bytes
			type : string,			// The file type as reported by the client operating system
			creationdate : Date,		// The date the file was created
			modificationdate : Date,	// The date the file was last modified
			filestatus : number,		// The file's current status. Use SWFUpload.FILE_STATUS to interpret the value.
			
		}
		*/

		try
		{
			
			// faila identifikators
			/*var uid = new Date().getTime();
			uid += "" + Math.random();
			uid = "" + Math.random();
			uid = uid.replace(/\./g, "");*/
			var uid = file.index;

			var target = document.getElementById(file_progress_list_id);
			/*var file_row = ""
				+ "<table border='0' cellpadding='0' id='i_"+uid+"'><tr style='height: 22px;'><td>"
				+ "<div style='width: 280px; white-space: nowrap; overflow: hidden;'>" + file.name + "</div>"
				+ "</td><td>&nbsp;&nbsp;&nbsp;</td><td width='160'><table cellpadding='0' valign='middle' border='0' ><tr>"
				+ "<td id='progress_cell_"+uid+"' style='background: url(http://www.failiem.lv/img/bg_progrbar.gif) repeat-x; width: 200px;'>"
				+ "<img id='p_"+uid+"' src='http://www.failiem.lv/img/bg_progrbaron.gif' style='height: 11px; width: 0%;'>"
				+ "</td></tr></table></td><td>&nbsp;&nbsp;&nbsp;</td><td>"
				+ "<img id='c_"+uid+"' src='http://www.failiem.lv/img/ic_stop.gif' title='Atcelt' OnClick='SwfCancelFile(\""+file.id+"\", "+uid+")' "
				+ "style='width: 20px; height: 21px; cursor: pointer;'></td></tr></table>";*/

			var file_row = ""
				+ "<div class='resultbox' id='frame_"+file.index+"'><p class='inprogr'>" + file.name + "</p>"
				+ "<a href='javascript://Cancel' title='Atcelt' id='cancel_"+file.index+"' Onclick='flash_manager.SwfCancelFile(\""+file.id+"\", "+file.index+")'>"
				+ "<img src='img/ic_stop.gif' alt='' class='act' /></a>"
				+ "<div><img src='img/progr.gif' style='width: 0%;' height='7' alt=''  id='progress_"+file.index+"'/>"
				+ "<span><!-- progr.bar mask --></span></div><br clear='all' /></div>";

			//target.innerHTML += file_row;
			//target.innerHTML = file_row + target.innerHTML;

			//tmp_target_inner_html = file_row + tmp_target_inner_html;
			tmp_target_inner_html = tmp_target_inner_html + file_row;
			tmp_target_last_change = (new Date()).getTime();
			UpdateFileList();

		} 
		catch (e) 
		{
			alert(["fileQueued", e.message]);
		}
	}


	var update_file_list_running = false;
	function UpdateFileList()
	{
		// ja galvenā funkcija nav taimautā, tad to izsaucam
		if (update_file_list_running == false)
		{
			UpdateFileListMain();
		}
	}
	function UpdateFileListMain()
	{
		// ar taimauta palīdzību updeito reālo failu sarakstu, ja tas nav mainījies pēdējās sekundēs
		update_file_list_running = true;

		// cik sen bijušas pēdējās izmaiņas
		var delta_ms = (new Date()).getTime() - tmp_target_last_change;
		if (delta_ms > 250)
		{
			var target = document.getElementById(file_progress_list_id);
			//target.innerHTML = tmp_target_inner_html + target.innerHTML;
			target.innerHTML = target.innerHTML + tmp_target_inner_html;
			tmp_target_inner_html = '';
			update_file_list_running = false;
		}
		else
		{
			setTimeout(function(){ UpdateFileListMain(); }, 300);
		}
	}




	this.SwfCancelFile = function(file_id, file_index)
	{
		//alert('SwfCancelFile');
		swfu.cancelUpload(file_id);
		//document.getElementById("i_"+file_index).style.display = "none";
		document.getElementById("frame_"+file_index).style.display = "none";
	}





	function uploadProgress(file, bytesLoaded, bytesTotal)
	{
		//alert('uploadProgress');
		try
		{
			// līdzko fails sākts lādēts, vairs neļaujam to atcelt
			document.getElementById("cancel_"+file.index).style.visibility = "hidden";

			var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
			document.getElementById("progress_"+file.index).style.width = percent+"%";
		}
		catch (e)
		{
			alert(["uploadProgress", e.message]);
		}
	}

	function uploadComplete(file)
	{
		/*// atzīmējam, ka fails ir pabeigts
		document.getElementById("progress_cell_"+file.index).innerHTML = "<span style='color: #6b9c02;'><b>Veiksmīgi saglabāts!</b></span>";
		document.getElementById("progress_cell_"+file.index).style.background = "";
		document.getElementById("c_"+file.index).src = "http://www.failiem.lv/img/ok.jpg";
		document.getElementById("c_"+file.index).title = "";
		document.getElementById("c_"+file.index).style.display = "block";
		document.getElementById("c_"+file.index).onclick = function(){};
		document.getElementById("c_"+file.index).style.cursor = "auto";*/

		//alert("uploadComplete");
		
		var foo_text2 = ""
		+ "<p>" + file.name + "</p>"
		+ "<img src='img/ic_tick.gif' alt='' title='Veiksmīgi saglabāts' class='act'/>"
		+ "<p class='resultmsg'>Veiksmīgi saglabāts</p><br clear='all' />";
		E('frame_'+file.index).innerHTML = foo_text2;


		if (this.getStats().files_queued === 0)
		{
			//alert("viss");
			//document.getElementById(this.customSettings.cancelButtonId).disabled = true;

			// izsaucam notikumu, ka visi faili veiksmīgi ielādēti
			me.data_uploaded.Fire();


			/*
			// ja esam te, tad visi faili veiksmīgi uplodēti
			//var link = "http://www.failiem.lv/list.php?i="+swf_upload_hash;
			//E('file_list_link').innerHTML = "&nbsp;<a style='color: #CC6600;' href='"+link+"'>"+link+"</a>";
			var link = "http://www.failiem.lv/list.php?i="+swf_upload_hash;
			E('file_list_link').innerHTML = "&nbsp;<a style='color: #CC6600;' href='"+link+"'>"+link+"</a>";

			E('email_list').style.display = "block";
			E('email_text_field_frame').style.display = "block";

			ShowEmailFields(0);
			ShowEmailBody(0);*/
		}
		else
		{
			// turpinam uplodēt nākamo failu
			this.startUpload();
		}
	}




	function fileQueueError(file, errorCode, message)
	{
		//alert('fileQueueError');
		try
		{
			if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED)
			{
				alert("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
				return;
			}

			//var progress = new FileProgress(file, this.customSettings.progressTarget);
			//progress.setError();
			//progress.toggleCancel(false);

			switch (errorCode)
			{
				case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
					//progress.setStatus("File is too big.");
					alert("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
					//progress.setStatus("Cannot upload Zero Byte files.");
					alert("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
					//progress.setStatus("Invalid File Type.");
					alert("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				default:
					if (file !== null)
					{
						//progress.setStatus("Unhandled Error");
					}
					alert("Error Code (QE): " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
			}
		}
		catch (e)
		{
			alert(["fileQueueError", e.message]);
		}
	}



	function uploadError(file, errorCode, message)
	{
		//alert('uploadError');
		try
		{
			// error description
			// http://swfupload.org/forum/generaldiscussion/204

			//var progress = new FileProgress(file, this.customSettings.progressTarget);
			//progress.setError();
			//progress.toggleCancel(false);

			switch (errorCode)
			{
				case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
					//progress.setStatus("Upload Error: " + message);
					alert("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message 
						+ ". Download latest Flash player from: http://www.adobe.com/go/getflash");
					break;
				case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
					//progress.setStatus("Upload Failed.");
					alert("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.IO_ERROR:
					//progress.setStatus("Server (IO) Error");
					alert("Problēmas ar internetu. Zvani 1188! Error Code: IO Error, File name: " + file.name + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
					//progress.setStatus("Security Error");
					alert("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
					//progress.setStatus("Upload limit exceeded.");
					alert("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
					//progress.setStatus("Failed Validation.  Upload skipped.");
					alert("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
					// If there aren't any files left (they were all cancelled) disable the cancel button
					if (this.getStats().files_queued === 0) {
						//document.getElementById(this.customSettings.cancelButtonId).disabled = true;
					}
					//progress.setStatus("Cancelled");
					//progress.setCancelled();
					break;
				case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
					//progress.setStatus("Stopped");
					break;
				default:
					//progress.setStatus("Unhandled Error: " + errorCode);
					alert("Error Code (UE): " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
			}

			// faila atcelšanas gadījumā neturpinam uploudu
			if (errorCode != SWFUpload.UPLOAD_ERROR.FILE_CANCELLED)
			{
				// turpinam uplodot nākamo failu
				this.startUpload();
			}
		}
		catch (e)
		{
			alert(["uploadError", e.message]);
		}


	}

}


