//-Utility Vars
var imgUploads = new Array();
var thumbs = new Array();
var sanitized = new Array();

var upQueue = new Array();
var uploadURL = "moduleinterface.php?mact=Listings,m1_,doajaxfileupload,0&sp_=";
var uploadsp = "";
var uploadprefix = "";

var uploadDebug = false;


function clearImg(id) {
	$("#thumb"+ id).hide();
	$("#thumb"+ id).attr("src", "");
	$("#"+ id+"_file").val("");
	$("#delete"+ id).hide();
}

function changeBind() {
	var id = $(this).attr('id');
	$("#Images_"+ id +"_error").html("");
	$("#Images_"+ id +"_error").hide();
	
	if (uploadDebug) $("#imgerror").append("<br />Go changer! @ "+ id);
	var value = ajaxFileUpload(id,false);
	if (uploadDebug) $("#imgerror").append("<br />&nbsp;&nbsp;&nbsp;&nbsp;"+ id +"Return["+ value +"]");
	$("#"+ id).change(changeBind);
	
	$('#delete'+ id).click(function() {
		clearImg(id);
	});
}

function ajaxFileUpload(id, skip) {
		var fileName = $("#"+ id).val();
		if (fileName == "") {
			if (uploadDebug) $("#imgerror").append("<br />"+ id +" NullFile");
			return true;
		}
		
		if (!skip) { //If we're not skip (front of the queue)
			upQueue.push(id);
			if (upQueue.length > 1) { // and there is a queue... then queue us up and back out
				//-Show Loading Screen
				showLoading(id);
				$('#error'+ id +'').html("Queued for Upload.");
				return true;
			}
		} else { //we're front, so unshift us on to let other people know to wait for us
			upQueue.unshift(id);
		}
		
		if (uploadDebug) $("#imgerror").append("<br />&nbsp;&nbsp;&nbsp;&nbsp;"+ id +" filename: "+ fileName);
		
		
		
		//-Match against Uploaded Files
		//alert("["+ imgUploads +"] ["+ fileName +"]");
		ithumb = checkUploadsArray(fileName, imgUploads);
		
		if (ithumb >= 0) { //Found
			
			//-Fix us up with a new thumbnail
			$("#thumb"+ id).attr("src", thumbs[ithumb]);
			
			$("#loading"+ id).hide();
			$("#thumb"+ id).show();
			//-Update ajax field
			$("#"+ id+"_file").val(sanitized[ithumb]);	
			
			/*//-Wait til it comes back to show
			$("#thumb"+ id).load(function() {
				$(this).slideDown();
					$("#loading"+ id).slideUp();
					//-Clear Error
					$('#'+ id +'_error').html("");
			});*/
			
			$("#parent"+ id).html($("#"+ id).clone());
			
			
			//-Clear box value by remaking it IE(requires it to be wraped in a span)
			//$("#"+ id).parent().html($("#"+ id).parent.html());
			//document.getElementById("parent"+ id).innerHTML = $("#"+ id).clone();
			//document.getElementById("parent"+ id).innerHTML;
			
			if (uploadDebug) $("#imgerror").append("<br />&nbsp;&nbsp;&nbsp;&nbsp;"+ id +" TimeOUT ");
			setTimeout('requestCompelte("'+ id +'")',100);
			$('#error'+ id +'').html("");
			$("#delete"+ id).show();
			
			
			ClearImageError(id);
			
			return true;
		}
		//-Show Loading Screen
		showLoading(id);
		
		$.ajaxFileUpload
		(
			{
				async: true,
				url: uploadURL + uploadsp,  //'/modules/Listings/doajaxfileupload.php',
				secureuri:false,
				fileElementId: id,
				dataType: 'json',
				success: function (data, status)
				{
					//-If json returned error
					if(typeof(data.error) != 'undefined') {
						$('#error'+ id +'').html("<br />Error...");
						if(data.error != '') {
							$('#error'+ id +'').html("<br />ERROR: "+ data.error);
						} else {
							$('#error'+ id +'').html("<br />UNKNOWN ERROR.");
						}
						$("#loading"+ id).hide();
						$('#error'+ id +'').show();
						
						//Debug:
						if (uploadDebug) $("#imgerror").append("Error!");
						
						$('#thumb'+ id).attr("src", "");
						$('#'+ id +'_file').attr("value", "");
						
					//-Otherwise We're good
					} else {
						//--Push Data
						if (uploadDebug) $("#imgerror").append("<br />Pushed["+ data.fileName +"]");
						imgUploads.push(data.fileName);
						thumbs.push(data.thumb);
						sanitized.push(data.sanitized);

						$("#"+ id+"_file").val(data.sanitized);
					
						//-Update Error
						$('#error'+ id +'').html("Downloading...");
						//-Fix us up with a thumbnail
						$("#thumb"+ id).attr("src", "");
						
						
						//-Wait til it comes back to show
						$("#thumb"+ id).load(function() {
							
							$(this).show();
							$("#loading"+ id).hide();
							//-Clear Error
							$('#error'+ id +'').html("");
							$("#delete"+ id).show();
						});
						$("#thumb"+ id).attr("src", data.thumb);
						
						
					}
				},
				error: function (data, status, e)
				{
					$('#error'+ id +'').html("Unrecognized Response<br />["+ status +"]["+ e.message +"]");
					$("#loading"+ id).hide();
					
					$('#thumb'+ id).attr("src", "");
					$('#'+ id +'_file').attr("value", "");
					
				},
				complete: function() {
					//--Always Fires, even on error
					requestCompelte(id);
				}
			}
		);
		return true;
}
function checkUploadsArray(needle, haystack) {
	if (!haystack.length) return -1;
	//-Hack off before for IE
	needle = needle.match(/[^\\\/]+$/gi);
	
	if (uploadDebug) $("#imgerror").append("<br />Haystack["+ typeof haystack +"]["+ haystack +"]");
	
	try {
		haystack = haystack.toArray();
	} catch (e) {
		if (uploadDebug) $("#imgerror").append("DOh!");
	}
	
	var item = -1;
	jQuery.each(haystack, function(i, val) {
		//Debug:if (!confirm("["+ needle +"]vs["+ val +"]")) return;
		
		if (needle == val) {
			//Debug:alert("match!");
			item = i;
			return;
		}
    });

	return item;
}
function showLoading(id) {
	//-Hide uploader box
	$("#"+ id).hide();
	//-Hide Present Picture
	$("#thumb"+ id).hide();
	//Hide the x
	$("#delete"+ id).hide();
	//Clear Error
	$('#error'+ id +'').html("Uploading...");
	$('#error'+ id +'').show();
	//-Show Loading Screen
	$("#loading"+ id).css("display", "block");
}

function requestCompelte(id) {
	//-Take us off the queue
	var done = upQueue.shift();

	//Clear IE
	var oldElement = $("#"+ id);
	var newElement = $("#"+ id).clone();
	$(oldElement).attr('id', "#"+ id);
	$(oldElement).before(newElement);
	oldElement.remove();

	//clearing it FIREFOX
	$("#"+ id).val("");
	
	$("#"+ id).show();
	
	if (uploadDebug) $("#imgerror").append("<br />Done ["+ id +"]vs["+ done +"]REBIND");	
	//-Rebind Change Event
	$("#"+ id).change(changeBind);
	AddSwapOptions(id);
	
	//-Check & run Queue
	if (upQueue.length) {
		var next = upQueue.shift();
		if (uploadDebug) $("#imgerror").append("--Next["+ next +"]");
		ajaxFileUpload(next, true);
	}
}
