/*
----------------------------------------------------------------------

	Filename:	fileupload.js
	Title:
	Date:
	Version:

	$$$ Copyright (c) 2006 Thomas Kjoernes / IPV - www.ipv.no $$$


	FileUploadControl

----------------------------------------------------------------------
*/


// __FileUploadConfig

var __FileUploadConfig = {

		className		: "",
		labelText		: "",
		submitText		: "Last opp",
		resetText		: "Avbryt",
		progressImage	: "/addons/fileupload/upload.gif",
		readyMessage	: null,
		finishMessage	: "Lastet opp",
		cancelMessage	: "Avbrutt",
		errorMessage	: "Feil ved opplasting",
		numFiles		: 1,
		readyTimeout	: 1500,
		debug			: false

	};


// __IFrameFileUploadTimeout()

function __IFrameFileUploadTimeout(obj) {

	if (obj) {

		clearTimeout(obj.timeoutRef);

		if (obj.status != 0) obj.formRef.reset();

		obj.onready();

	}

}


// __IFrameFileUploadOnLoad()

function __IFrameFileUploadOnLoad(iframe) {

	if (iframe) {

		var obj = iframe.ownerObject;

		var doc = (iframe.contentWindow || iframe.contentDocument);

		if (doc.document) doc = doc.document;

		responseNode = doc.body;

		if (responseNode && obj.status == 100) {

			// replace HTML entity for ampersand

			var responseText = responseNode.innerHTML.replace(/\&amp;/g, "&");
			var responseData = responseText.split(";");

			var responseStatus = responseData[0];

			if (responseStatus.indexOf("200") == 0) {

				obj.status = 200;
				obj.responseText = responseText;
				obj.responseObjects = new Array();

				// create object-array from response

				for (var i=1; i<responseData.length; i++) {

					var responseObject = new Object();
					var responseItem = responseData[i].split("&");

					for (var j=0; j<responseItem.length; j++) {

						var item = responseItem[j].split("=");

						// set property = value

						responseObject[item[0]] = decodeURIComponent(item[1]);

					}

					obj.responseObjects.push(responseObject);

				}

				if (obj.config.readyTimeout) obj.timeoutRef = setTimeout(function () { __IFrameFileUploadTimeout(obj); }, obj.config.readyTimeout);

				obj.onfinish();
				obj.onupload(obj.responseText, obj.responseObjects);

			} else {

				obj.status = 400;
				obj.onerror();

			}

		}

	}

}


// FileUploadControl()

function FileUploadControl(action) {

	this.status = null;
	this.action = action ? action : "";
	this.config = {};
	this.inputCount = 0;

	for (var i in __FileUploadConfig) this.config[i] = __FileUploadConfig[i];

	if (typeof window.__UIControlCount == "undefined") window.__UIControlCount = 1;

	var count = window.__UIControlCount++;

	this.containerName = "FileUploadContainer" + count;
	this.formName = "FileUploadForm" + count;
	this.divName = "FileUploadDiv" + count;
	this.iframeName = "FileUploadIFrame" + count;
	this.submitName = "FileUploadSubmit" + count;
	this.resetName = "FileUploadReset" + count;
	this.messageName = "FileUploadMessage" + count;

	// Render()

	this.Render = function() {

		if (this.status != null) return;

		this.status = 0;

		// create HTML for empty control

		var s =
		"<div " +
			"id=\"" + this.containerName + "\" " +
			"class=\"" + this.config.className + "\">" +

			"<form " +
				"id=\"" + this.formName +"\" " +
				"name=\"" + this.formName +"\" " +
				"action=\"" + this.action + "\" " +
				"method=\"POST\" " +
				"enctype=\"multipart/form-data\" " +
				"target=\"" + this.iframeName + "\">" +
				"<label>" + this.config.labelText + "</label>";

				for (var i=0; i<this.config.numFiles; i++) {

					var inputName = "file" + (i+1);

					s +=
					"<input " +
						"id=\"" + this.formName + inputName + "\" " +
						"class=\"file\" " +
						"type=\"file\" " +
						"name=\"" + inputName + "\">";

				}

				s +=
				"<div " +
					"id=\"" + this.divName + "\"></div>" +

				"<input " +
					"id=\"" + this.submitName + "\" " +
					"class=\"button\" " +
					"type=\"submit\" " +
					"value=\"" + this.config.submitText + "\">" +

				"<input " +
					"id=\"" + this.resetName + "\" " +
					"class=\"button\" " +
					"type=\"reset\" " +
					"value=\"" + this.config.resetText + "\"" +
					"style=\"display: none\">" +

				"<span " +
					"id=\"" + this.messageName + "\" " +
					"class=\"ready\">" + (this.config.readyMessage || "") + "</span>" +

			"</form>" +

			"<iframe ";

				if (this.config.debug) {

					s += "style=\"width: 100%; height: 180px;\" frameborder=\"1\" ";

				} else {

					s += "style=\"width: 0; height: 0;\" frameborder=\"0\" ";

				}

				s +=
				"id=\"" + this.iframeName +"\" " +
				"name=\"" + this.iframeName +"\" " +
				"onload=\"__IFrameFileUploadOnLoad(this)\">" +

			"</iframe>" +

		"</div>";

		// write HTML to document

		document.write(s);

		this.containerRef = document.getElementById(this.containerName);
		this.divRef = document.getElementById(this.divName);
		this.formRef = document.getElementById(this.formName);
		this.iframeRef = document.getElementById(this.iframeName);
		this.submitRef = document.getElementById(this.submitName);
		this.resetRef = document.getElementById(this.resetName);
		this.messageRef = document.getElementById(this.messageName);

		this.formRef.ownerObject = this;
		this.iframeRef.ownerObject = this;

		// onsubmit()

		this.formRef.onsubmit = function() {

			var obj = this.ownerObject;
			var els = this.elements;
			var empty = true;

			// all empty inputs?

			for (var i=0; i<els.length; i++) {

				if (els[i].type == "file" && els[i].value != "") { empty = false; break; }

			}

			if (empty) return false;

			obj.status = 100;
			obj.onstart();

		};

		// onreset()

		this.formRef.onreset = function() {

			var obj = this.ownerObject;

			if (obj.status == 100) {

				obj.status = 0;
				obj.iframeRef.src = "about:blank";
				if (obj.config.readyTimeout) obj.timeoutRef = setTimeout(function () { __IFrameFileUploadTimeout(obj); }, obj.config.readyTimeout);
				obj.oncancel();

			}

			if (obj.status != 200) return false;

		};

	};

	// AddInput()

	this.AddInput = function(type, name, value, size, label, title, maxlength) {

		var eInput = document.createElement("INPUT");
		var eLabel = document.createElement("LABEL");

		this.inputCount++;

		var id = this.formName + "_input" + this.inputCount;

		eInput.className = type;
		eInput.id = id;
		eLabel.htmlFor = id;

		if (type) eInput.type = type;
		if (name) eInput.name = name;
		if (value) eInput.value = value;
		if (title) eInput.title = title;
		if (size) eInput.size = size;
		if (maxlength) eInput.maxlength = maxlength;

		eLabel.appendChild(eInput);

		if (label) eLabel.appendChild(document.createTextNode(label));

		this.divRef.appendChild(eLabel);

	};

	// AddSelect()

	this.AddSelect = function(name, label, title, value, src, root, mode) {

		var eSelect = document.createElement("SELECT");
		var eLabel = document.createElement("LABEL");
		var eScript = document.createElement("SCRIPT");

		var optionListName = "optionList_" + name;

		if (src) {

			eScript.type = "text/javascript";
			eScript.src = src + ((src.indexOf("?")<0) ? "?" : "&") + "name=" + optionListName + "&root=" + root + "&mode=" + mode;

			this.divRef.appendChild(eScript);

		}

		this.inputCount++;

		var id = this.formName + "select" + this.inputCount;

		eSelect.className = name;
		eSelect.id = id;
		eLabel.htmlFor = id;

		if (name) eSelect.name = name;
		if (title) eSelect.title = title;
		if (label) eLabel.appendChild(document.createTextNode(label));

		this.divRef.appendChild(eLabel);
		this.divRef.appendChild(eSelect);


		setTimeout(function() {
			var optionList = this[optionListName];
			if (optionList) {
				var options = [];
				for (var i=0; i<optionList.length; i++) {
					var eOption = document.createElement("OPTION");
					eOption.value = optionList[i].value;
					eOption.appendChild(document.createTextNode(optionList[i].name));
					eSelect.appendChild(eOption);
				}
			}
		}, 250);

	};

	// SetStatusImage()

	this.SetStatusImage = function(src) {

		this.messageRef.innerHTML = "<img src=\"" + src + "\">";

	};

	// SetStatusText()

	this.SetStatusText = function(text, className) {

		if (text != null) {

			this.messageRef.className = className;
			this.messageRef.innerHTML = text;

		}

	};


	// DisableSubmit()

	this.DisableSubmit = function() {

		this.resetRef.style.display = "";
		this.submitRef.style.display = "none";

	};

	// EnableSubmit()

	this.EnableSubmit = function() {

		this.submitRef.style.display = "";
		this.resetRef.style.display = "none";

	};


	// callback: onready()

	this.onready = function() {

		this.SetStatusText(this.config.readyMessage, "ready");
		this.EnableSubmit();

	};

	// callback: onstart()

	this.onstart = function() {

		this.SetStatusImage(this.config.progressImage);
		this.DisableSubmit();

	};

	// callback: onfinish()

	this.onfinish = function() {

		this.SetStatusText(this.config.finishMessage, "finish");
		this.EnableSubmit();

	};

	// callback: oncancel()

	this.oncancel = function() {

		this.SetStatusText(this.config.cancelMessage, "cancel");
		this.EnableSubmit();

	};

	// callback: onerror()

	this.onerror = function() {

		this.SetStatusText(this.config.errorMessage, "error");
		this.EnableSubmit();

	};

	// callback: onupload()

	this.onupload = function(responseText, responseObjects) {

	};

}

