var EXIF = OZ.Class().extend(App.Module);
App.Modules.push(EXIF);

EXIF.prototype.init = function(app) {
	this.app = app;
	
	this._data = {};
	this._active = false;
	this._image = OZ.DOM.elm("img");
	this._table = OZ.DOM.elm("table");
	this._tbody = OZ.DOM.elm("tbody");
	
	this._table.appendChild(this._tbody);
}

EXIF.prototype.activate = function() {
	this._active = true;
	var c = this.app.getContent();
	OZ.DOM.addClass(c, "exif");
	
	c.appendChild(this._image);
	c.appendChild(this._table);
}

EXIF.prototype.deactivate = function() {
	this._active = false;
	var c = this.app.getContent();
	OZ.DOM.removeClass(c, "exif");
}

EXIF.prototype.update = function() {
	var file = this.app.currentFile();
	if (file in this._data) {
		this._build(this._data[file]);
	} else {
		this._request(file);
	}

	this.app.preload(this.bind(this._loadedImage));
}

EXIF.prototype._build = function(data) {
	OZ.DOM.clear(this._tbody);
	var url = this.app.currentBig();

	for (var id in EXIF.tags) {
		if (!(id in data)) { continue; }
		var name = EXIF.tags[id];
		var value = data[id];
		this._addPair(name, value);
	}
}

EXIF.prototype._addPair = function(name, value) {
	var tr = OZ.DOM.elm("tr");
	var td1 = OZ.DOM.elm("td", {className: "name"});
	var td2 = OZ.DOM.elm("td", {className: "value"});
	
	td1.innerHTML = name;
	td2.innerHTML = value;
	
	OZ.DOM.append([tr, td1, td2], [this._tbody, tr]);
	
}

EXIF.prototype._loadedImage = function(src) {
	var c = this.app.getContent();
	var size = this.app.resizeTo(c.offsetWidth/2 - 2, c.offsetHeight - 2);
	this._image.style.width = size[0]+"px";
	this._image.style.height = size[1]+"px";
	this._image.src = src;
}

EXIF.prototype._request = function(file) {
	OZ.Request(document.location.pathname + "?exif&file=" + file, this.bind(this._response), {xml:true});
}

EXIF.prototype._response = function(xml) {
	var image = xml.getElementsByTagName("exif")[0];

	var data = {};
	for (var j=0;j<image.attributes.length;j++) {
		var attr = image.attributes[j];
		var name = attr.nodeName;
		var value = attr.nodeValue;
		data[name] = value;
	}

	/* postprocess */
	if (data.Flash) { data.Flash = (data.Flash.match(/fired/i) ? "Ano" : "Ne"); }
	if (data.FNumber) { data.FNumber = "f/" + data.FNumber; }
	if (data.ExposureTime) { data.ExposureTime += " s"; }
	if (data.Make && data.Model) {
		data.Model = this._firstUp(data.Make) + " " + data.Model;
		delete data.Make;
	}
	if (data.FocalLength && data.FocalPlaneDiagonal) {
		var d = Math.sqrt(36*36+24*24);
		var crop = d / parseFloat(data.FocalPlaneDiagonal);
		var f = crop * parseFloat(data.FocalLength);
		f = Math.round(10*f)/10;
		data.FocalLength += " ("+f+" mm equiv.)";
	}
	
	this._data[data.file] = data;
	if (this._active) { this._build(data); }
}

EXIF.prototype._firstUp = function(str) {
	return str.replace(/\w+/g, function(x) {
		return x.charAt(0).toUpperCase() + x.substring(1).toLowerCase();
	});
}
