var newWindow;
function openUpload(picNr) {
	//By using the same window reference, we avoid opening multiple windows
	dojo.byId("photoId").value = picNr;
	openPopup();
	window.scrollTo(0,79);
}
     
function useUploadedImage() {
	picNr = dojo.byId("photoId").value;
	// Step 1: AJAX call to server to set a flag in the session to save the image
	var deferred = dojo.xhrGet({
		url: 		environment + "/ad/useImage?id=" + picNr,
		handleAs:	"text",
		timeOut:	5000,
		handle:		function(response, ioArgs) {
			if (response instanceof Error) {
				if (response.dojoType == "cancel") {
					//The request was canceled by some other JavaScript code.
					console.debug("Request canceled.");
				} else if (response.dojoType == "timeout") {
					//The request took over 5 seconds to complete.
					console.debug("Request timed out.");
				} else{
					//Some other error happened.
					console.error(response);
				}
			} else {
				console.debug("Successful server response: " + response);
			}
		} //end of handle function
	});
	
	hidePopup();
     	
	// Step 2: Show thumbnail on this page
	var d = new Date();
	var imageId = "image" + picNr;
	dojo.byId(imageId).src = environment + "/image/uploadedSmall?id=" + picNr + "&time=" + d.getTime();
	dojo.byId(imageId).style.visibility = "visible";
	     	
	//Step 2b: Reposition image
	document[imageId].onload = function() {
		var totalHeight = dojo.style(this.parentNode, "height");
		var imgHeight = dojo.style(this, "height");
		dojo.style(this , "marginTop", ((totalHeight - imgHeight) / 2)+"px");
	}
	
	// Step 3: Display the 'delete' button
	dojo.byId("deleteHolder" + picNr).style.visibility = "visible";
	
	// Step 4: Change the 'select' button
	dojo.byId("openLink" + picNr).className = "btn-wijzigAfbeelding";
	dojo.byId("openLink" + picNr).innerHTML = "wijzig";
}
     
function deleteImage(picNr) {
	// Step 1: change image on the page
	var imageId = "image" + picNr;
	document[imageId].src = "";
	document[imageId].style.visibility = "hidden";
     	        	
	// Step 2: AJAX call to server to remove image from session
	var deferred = dojo.xhrGet({
		url: 		environment + "/ad/deleteImage?id=" + picNr,
		handleAs:	"text",
		timeOut:	5000,
		handle:		function(response, ioArgs) {
			if (response instanceof Error) {
				if(response.dojoType == "cancel"){
					//The request was canceled by some other JavaScript code.
					console.debug("Request canceled.");
				} else if(response.dojoType == "timeout"){
					//The request took over 5 seconds to complete.
					console.debug("Request timed out.");
				} else {
					//Some other error happened.
					console.error(response);
				}
			} else {
				console.debug("Successful server response: " + response);
			}
		} //end of handle function
	});
	
	// Step 3: Hide the 'delete' button
	dojo.byId("deleteHolder" + picNr).style.visibility = "hidden";
	
	// Step 4: Change the 'select' button
	dojo.byId("openLink" + picNr).className = "btn-selecteerAfbeelding";
	dojo.byId("openLink" + picNr).innerHTML = "selecteer";
}

// Progress bar initialiser
function uploadImage() {
	finished = false;
	
	// Remove any previously displayed messages
	dojo.byId("messageHolder").style.display = "none";
	
	// Get the item references
	var shell = dojo.byId("progressBarShell");
	var amount = dojo.byId("progressBarAmount");
	var bar = dojo.byId("progressBar");
	var waitIndicator = dojo.byId("waitIndicator");
	
	dojo.byId("photoPreview").src = "";
	
	// Make them all visible
	//shell.style.visibility = 'visible';
	//amount.style.visibility = 'visible';
	waitIndicator.style.visibility = 'visible';
	
	dojo.byId("usePhoto").style.visibility = "hidden";
	dojo.byId("imageHolder").style.display = "none";
	
	
	// Initialise the bar to 0%
	amount.innerHTML = "0%";
	bar.style.width = "0%";
	
	// Disable the submit button to avoid having multiple uploads, and submit the form
	dojo.byId("submitButton").disabled = true;
	dojo.byId("uploadForm").submit();
	      	
	// Show the bar after a second
	//var timer = setTimeout("updateBar()", 1000);
}

function updateBar() {
	// Grab the percentage from the server
	var deferred = dojo.xhrGet({
		url: 		environment + "/ad/uploadInfo",
		handleAs:	"text",
		timeOut:	1000,
		handle:		function(response, ioArgs) {
			if (response instanceof Error) {
				if(response.dojoType == "cancel"){
					//The request was canceled by some other JavaScript code.
					console.debug("Request canceled.");
				}else if(response.dojoType == "timeout"){
					//The request took over 1 second to complete.
					console.debug("Request timed out.");
				}else{
					//Some other error happened.
					console.error(response);
				}
			} else {
				processReturnedString(response);
			}
		} //end of handle function
	});
}

function processReturnedString(response) {
	var array = response.split(";");
	if (array[1] == "DONE") {
		dojo.byId("progressBar").style.width = "100%";
		dojo.byId("progressBarAmount").innerHTML = "Done";
		finishDownload();
	} else if (array[1] == "PROCESSING") {
		dojo.byId("progressBarAmount").innerHTML = "Processing...";
		// Hide the 'select image' button
		dojo.byId("usePhoto").style.visibility = "hidden";
		dojo.byId("progressBar").style.width = "100%";
//		var timer = setTimeout("updateBar()", 1000);
	} else if (array[1] == "FAILED") {
		// Allow user to re-upload something else
		dojo.byId("submitButton").disabled = false;
		
		// Hide the progress bar 
		dojo.byId("progressBarShell").style.visibility = "hidden";
		dojo.byId("progressBarAmount").style.visibility = "hidden";
		dojo.byId("waitIndicator").style.visibility = "hidden";
		// Hide the 'select image' button
		dojo.byId("usePhoto").style.visibility = "hidden";
		
		
		// Remove any previously uploaded image
		dojo.byId("imageHolder").style.display = "none";
		dojo.byId("photoPreview").src = "";
		
		// Show the error message
		if (!finished) {
			finished = true;
			dojo.byId("messageHolder").style.display = "inline";
			dojo.byId("messageHolder").innerHTML = array[2];
		}
	} else {
		// If we're not finished already somewhere else, request uploadInfo again
		if (!finished) {
			dojo.byId("progressBarAmount").innerHTML = array[0] + "%";
			dojo.byId("progressBar").style.width = array[0] + "%";
//			var timer = setTimeout("updateBar()", 1000);
		}
	}
}

var finished = false;
function finishDownload() {
	if (!finished) {
		finished = true;
		
		// Enforce bar to reflect being finished uploading
//		dojo.byId("progressBar").style.width = "100%";
//		dojo.byId("progressBarAmount").innerHTML = "Done";
//		dojo.byId("progressBarShell").style.visibility = "hidden";
//		dojo.byId("progressBarAmount").style.visibility = "hidden";
//				
		// Display the preview
		var d = new Date();
		dojo.byId("photoPreview").src = environment + "/image/uploadPreview?id=" + dojo.byId("photoId").value + "&time=" + d.getTime(); //Added time to enforce browser reloading image
		
		// When the image is loaded, do your magic
		dojo.byId("photoPreview").onload = function() {
			// Enable upload button again, needed when they want to upload a different picture
			dojo.byId("submitButton").disabled = false;
			
			// Enable the 'select image' button
			dojo.byId("usePhoto").style.visibility = "visible";
			
			// Display the preview
			dojo.byId("imageHolder").style.display = "inline";
			
			// Hide the spinner
			dojo.byId("waitIndicator").style.visibility = "hidden";
			
			// Reposition the image
			var totalHeight = dojo.style(this.parentNode, "height");
			var imgHeight = dojo.style(this, "height");
			dojo.style(this , "marginTop", ((totalHeight - imgHeight) / 2)+"px");
		}

	}
}

function openPopup() {
	finished = false;

	// Reset the popup and show it
	var popup = dojo.byId("photoPopup");
	popup.style.visibility = "visible";
	popup.style.position = "absolute";
	popup.style.top = "79px";
	dojo.byId("imageName").value = "";
	dojo.byId("submitButton").disabled = false;
	dojo.byId("messageHolder").style.display = "none";
	
	// Clear up the progressbar
	dojo.byId("progressBarShell").style.visibility = "hidden";
	dojo.byId("progressBarAmount").style.visibility = "hidden";
	dojo.byId("waitIndicator").style.visibility = "hidden";
	dojo.byId("progressBarAmount").innerHTML = "0%";
	dojo.byId("progressBar").style.width = "0%";
	
	// Hide the image preview
	dojo.byId("imageHolder").style.display = "none";
	
	// Because the popup 'resets', hide the 'select image' button
	dojo.byId("usePhoto").style.visibility = "hidden";
}

function hidePopup() {
	var popup = dojo.byId("photoPopup");
	popup.style.visibility = "hidden";
	popup.style.position = "absolute";
	popup.style.top = "-9999px";
}
