
// lot of table manipulation code is based on stuff here: http://www.mredkj.com/tutorials/htmljs.html#tables

function artwork__setup() 
{
	if(targettype != 0 && ownstarget)
	{
		// thank you: http://www.isocra.com/2007/07/dragging-and-dropping-table-rows-in-javascript/ 
		tableDnD = new TableDnD();
		tableDnD.init($('artwork_table'));	
		tableDnD.lastSortOrder = artwork__sortOrderHash($('artwork_table'));
	
		tableDnD.onDrop = function(table, row) 
		{
			var sortorder = artwork__sortOrderHash(table);

			var a = tableDnD.lastSortOrder.toQueryString();
			var b = sortorder.toQueryString();

			if(a != b) 
			{
				tableDnD.lastSortOrder = sortorder.clone();

				sortorder.set('targetid', targetid);
				sortorder.set('targettype', targettype);

				new Ajax.Request("/widgets/artwork_upload/artwork_upload.php", {
							'parameters': sortorder,
							'onFailure': function(xmlhttp) {
								alert("Can't save changes.\n\n" + xmlhttp.responseText);
							}
						});

			}
		}
	}

	var settings = {
		flash_url : "/s/swfupload/swfupload.swf",
		upload_url: "/widgets/artwork_upload/artwork_upload.php",	// Relative to the SWF file
		post_params: {"targettype" : targettype, "targetid" : targetid},
		file_size_limit : "100 MB",
		file_types : "*.*",
		file_types_description : "All Files",
		file_upload_limit : 100,
		file_queue_limit : 0,
		custom_settings : {
			progressTarget : "artworkUploadProgress",
			cancelButtonId : "btnCancel"
		},
		debug: false,

		button_image_url: "/s/swfupload/tmp_upload.png",
		button_width: "91",
		button_height: "28",
		button_placeholder_id: "artworkUploadButton",

		file_queued_handler : artwork__fileQueued,
		file_queue_error_handler : artwork__fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,
		upload_start_handler : artwork__uploadStart,
		upload_progress_handler : artwork__uploadProgress,
		upload_error_handler : artwork__uploadError,
		upload_success_handler : artwork__uploadSuccess,
		upload_complete_handler : artwork__uploadComplete,
		queue_complete_handler : artwork__queueComplete	// Queue plugin event
	};

	swfu = new SWFUpload(settings);
			
}


function artwork__sortOrderHash(table)
{
	var rows = table.tBodies[0].rows;

	var sortorder = new Hash;
	
	for(var i=0; i<rows.length; i++)
	{
		var cells = rows[i].cells;
		for(var j=0; j<cells.length; ++j)
		{
			if(cells[j].id.indexOf("artwork_edit_") == 0) // rows[i].down('td.edit') doesn't work in IE
				sortorder.set("sortorder[" + i + "]", artwork__editCellIDToArtworkID(cells[j].id));
		}
	}
	
	return sortorder;
}

function artwork__editCellIDToArtworkID(id)
{
	return id.substring(13);  // artwork_edit_AID
}
	     
	     

function artwork__login(after_login)
{
	var url = '/widgets/artwork_upload/artwork_upload.php?task=checklogin';

	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) 
		{
			if(transport.responseText == "<not_logged_in/>")
			{			
				showPopupLogin('Please log in to upload.');
				Event.observe(document,'myfonts:loggedin',after_login);
			}
			else if(transport.responseText == "<logged_in/>")
			{			
				after_login();
			}			
			
		},
		onFailure : function(transport)
		{
			alert("check login fail. http code " + transport.status);
		}
	});
	
	return true;
}


function artwork__addRow(artwork_row)
{
	var newrow = $('artwork_table').tBodies[0].insertRow(1);
	
	// newrow.innerHTML = artwork_row, newrow.replace(artwork_row), and newrow.update(artwork_row) don't work in IE	
	
	var ar = artwork_row;
	var i = 0;
	while(ar.length)
	{ 	
  		// trim the first <td>
  		ar = ar.substring(ar.indexOf("<td") + 3);
  		elementClose = ar.indexOf(">") + 1;
  		
  		attrib_c = ar.indexOf("class='");
  		
  		if(attrib_c > elementClose)
  			attrib_c = -1;
  		
  		if(attrib_c != -1)
  		{
  			arc = ar.substring(attrib_c + 7);
  			
  			attrib_c = arc.substring(0, arc.indexOf("'"));
  		}

  		attrib_id = ar.indexOf("id='");

  		if(attrib_id > elementClose)
  			attrib_id = -1;  		

  		if(attrib_id != -1)
  		{
  			arc = ar.substring(attrib_id + 4);
  			
  			attrib_id = arc.substring(0, arc.indexOf("'"));
  		}  		
  		
  		ar = ar.substring(elementClose);
  		
  		// find the closing 
  		var s1 = ar.indexOf("</td>");
  		
  		if(s1 == -1)
  			break;
  			
  		
  		var c = ar.substring(0, s1);
  	
  		var newcell = newrow.insertCell(i);
  		
  		if(attrib_c != -1)
  			newcell.setAttribute('class', attrib_c);
 
  		if(attrib_id != -1)
			newcell.setAttribute('id', attrib_id);
  		 			
  		newcell.innerHTML = c;
		
  		// move on to the next td
  		ar = ar.substring(s1 + 5); 
  		
  		++i;  		
  	}
  	
	artwork__refresh();
}


function artwork__refresh()
{
  	Behaviour.apply();
  	
  	if(targettype != 0 && ownstarget)
  		tableDnD.init($('artwork_table'));
}


function artwork__closeEdit(el)
{
	el.up('td').down('div').removeClassName("hidden");
	el.up('form').addClassName("hidden");	
}


function artwork__openEdit(el)
{
	el.up('div').addClassName("hidden");
	el.up('td').down('form').removeClassName("hidden");
}


var artworkRules = {

	"#artwork #upload_button" : function(el) {
 		el.onclick = function() {
        	
         		artwork__login(function() { swfu.refreshCookies(); swfu.selectFiles(); });
        		return false;
		}
        
  	},
  	
 	"#artwork .cmd_delete" : function(el) {
 		el.onclick = function() {
        	
        		var aid = artwork__editCellIDToArtworkID(el.parentNode.id);  // artwork_edit_AID

        		if(confirm("Are you sure you wish to delete this entry?"))
        		{				
				new Ajax.Request("/widgets/artwork_upload/artwork_upload.php", {
					'parameters': {'task' : 'delete', 'newinfo[ArtworkID]' : aid },
					'onSuccess' : function(transport) {
						var delRow = el.up("tr"); 
						var tbl = el.up("table");
						tbl.deleteRow(delRow.sectionRowIndex);
					},
					'onFailure': function(transport) {
						alert("Can't delete.\n\n" + transport.responseText);
					}	
				});
        		}
        		
        		return false;
		}
        
  	},

 	"#artwork .cmd_unlink" : function(el) {
 		el.onclick = function() {
        	
        		var aid = artwork__editCellIDToArtworkID(el.parentNode.id);  // artwork_edit_AID

        		if(confirm("Are you sure you wish to unlink this entry?"))
        		{				
				new Ajax.Request("/widgets/artwork_upload/artwork_upload.php", {
					'parameters': {'task' : 'unlink', 'newinfo[ArtworkID]' : aid, 'targetid': targetid, 'targettype': targettype },
					'onSuccess' : function(transport) {
						var delRow = el.up("tr"); 
						var tbl = el.up("table");
						tbl.deleteRow(delRow.sectionRowIndex);
					},
					'onFailure': function(transport) {
						alert("Can't delete.\n\n" + transport.responseText);
					}	
				});
        		}
        		
        		return false;
		}
        
  	},
  	
  	"#artwork form input[type=reset]" : function(el) {
  		el.onclick = function() {

			artwork__closeEdit(el);
 			return true;
  		}
  	},
  	
  	"#artwork form input[type=submit]" : function(el) {
  		el.onclick = function() {

			artwork__closeEdit(el);

			var f = el.up();
						
			var params = new Hash(f.serialize(true));
			params.set('targetid', targetid);
			params.set('targettype', targettype);
			
			new Ajax.Request("/widgets/artwork_upload/artwork_upload.php", {
				'parameters': params,
				'onSuccess': function(xmlhttp) {

					f.up('tr').replace(xmlhttp.responseText);
					artwork__refresh();
				},
				'onFailure': function(xmlhttp) {
					alert("Can't save changes.\n\n" + xmlhttp.responseText);
					f.reset();
				}
			});
					

			
 			return false;
  		}
  	},  	
  	
  	"#artwork .cmd_edit" : function(el) {
  		el.onclick = function() {
  		
  			document.lastEditButton = el; // hack! 
  			
			artwork__openEdit(document.lastEditButton);
			//artwork__login(function() { artwork__openEdit(document.lastEditButton); });
			
 			return false;
  		}
  	}

};                   

Behaviour.register(artworkRules);
  	
  	


/* **********************
   Event Handlers
   These are my custom event handlers to make my
   web application behave the way I went when SWFUpload
   completes different tasks.  These aren't part of the SWFUpload
   package.  They are part of my application.  Without these none
   of the actions SWFUpload makes will show up in my application.
   ********************** */
function artwork__fileQueued(file) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("Pending...");
		progress.toggleCancel(true, this);

	} catch (ex) {
		this.debug(ex);
	}

}

function artwork__fileQueueError(file, errorCode, message) {
	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.");
			this.debug("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.");
			this.debug("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.");
			this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		default:
			if (file !== null) {
				progress.setStatus("Unhandled Error");
			}
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
	try {
		if (numFilesSelected > 0) {
			document.getElementById(this.customSettings.cancelButtonId).disabled = false;
		}
		
		/* I want auto start the upload and I can do that here */
		this.startUpload();
	} catch (ex)  {
        this.debug(ex);
	}
}

function artwork__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.
		 */
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("Uploading...");
		progress.toggleCancel(true, this);
	}
	catch (ex) {}
	
	return true;
}

function artwork__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("Uploading...");
	} catch (ex) {
		this.debug(ex);
	}
}

function artwork__uploadSuccess(file, serverData) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setComplete();
		progress.setStatus("Complete.");
		progress.toggleCancel(false);
		artwork__addRow(serverData);
	} catch (ex) {
		this.debug(ex);
	}
}

function artwork__uploadError(file, errorCode, message) {
	try {
		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);
			this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			progress.setStatus("Upload Failed.");
			this.debug("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");
			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			progress.setStatus("Security Error");
			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			progress.setStatus("Upload limit exceeded.");
			this.debug("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.");
			this.debug("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);
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}

		switch (message) {
			case "506":
			alert("You're not logged in. Please login and try again.");
			break;

			case "507":
			alert("Please upload images in either PDF and PNG format. MyFonts will automatically choose the optimum image for use on the website.");
			break;

			case "508":
			alert("Permission denied.");
			break;
			
			case "509":
			alert("The uploaded file exceeds the 2MB limit.");
			break;					
			
			case "510":
			alert("No file was uploaded.");
			break;		
			
			case "511":
			alert("The uploaded file was only partially uploaded.");
			break;					
			
			case "512":
			alert("File upload failed.");
			break;												

			default:
			alert(message);
			break;
		}


	} catch (ex) {
        this.debug(ex);
    }
}

function artwork__uploadComplete(file) {
	if (this.getStats().files_queued === 0) {
		document.getElementById(this.customSettings.cancelButtonId).disabled = true;
	}
}

function artwork__queueComplete(numFilesUploaded) {
	var i = 1;  // doesn't work with empty function
//	var status = document.getElementById("divStatus");
//	status.innerHTML = numFilesUploaded + " file" + (numFilesUploaded === 1 ? "" : "s") + " uploaded.";
}
