Ext.namespace('fcbm.component.ImageAnnotationManager');

/*
 * fcbm.component.ImageAnnotationManager
 *   Extends Ext.util.Observable
 *   
 *   config object must have the following properties :
 *   - document: fcbm.model.Document
 *   - documentType: int (fcbm.model.ImageAnnotationConfig.ATLAS|fcbm.model.ImageAnnotationConfig.TRAINING)
 *   - solutionMode: boolean
 *   
 */
fcbm.component.ImageAnnotationManager = function (config) {
	
	// Properties
	//////////////////////////////////////////////////////////////////////////////////
	this.initialConfig = Ext.apply(config);
	this.annotations = this.initialConfig.document.imageWall.graphicalFormuleData;
	this.cellIdSelected = 'PNN';
	this.leucoCount = new Ext.util.MixedCollection();
	this.leucoCountDataStore = null;
	this.leucoCountColumnView = new Ext.grid.ColumnModel([
		{
			header: "",
			sortable: false,
			width: 160,
			dataIndex: 'name',
			id: 'item',
			menuDisabled: true,
			renderer: function(data, cell, record, rowIndex, columnIndex, storeDocuments){
				if (parseInt(record.get('special')) == 1)
					return "<b>" + data + "</b>";
				else
					return data;
			}
		},
		{header: "Nb", sortable: false, width: 30, dataIndex: 'nb', menuDisabled:true, align: 'right'},
		{header: "%", sortable: false, width: 30, dataIndex: 'percent', menuDisabled:true, align: 'right'},
		{header: "10<sup>9</sup>/l", sortable: false, width: 50, dataIndex: 'milliardieme', menuDisabled:true, align: 'right'}
	]);
	this.leucoCountSolutionColumnView = new Ext.grid.ColumnModel([
		{
			header: "%",
			sortable: false,
			width: 160,
			dataIndex: 'name',
			id: 'item',
			menuDisabled: true,
			renderer: function(data, cell, record, rowIndex, columnIndex, storeDocuments){
				if (parseInt(record.get('special')) == 1)
					return "<b>Total</b>";
				else
					return data;
			}
		},
		{header: "Référence", sortable: false, width: 65, dataIndex: 'percentRef', menuDisabled:true, align: 'right'},
		{header: "Vous", sortable: false, width: 45, dataIndex: 'percent', menuDisabled:true, align: 'right'}
	]);
	this.leucoCountNb = 0;
	
	/*
	 * TEMP
	 */
	this.initialConfig.documentType = fcbm.model.ImageAnnotationConfig.TRAINING;
	this.initialConfig.solutionMode = false;
	/*
	 * 
	 */

	this.registeredImg = new Ext.util.MixedCollection();

	
	// Methods
	//////////////////////////////////////////////////////////////////////////////////
	
	// public
	// Creee une occurrence d'une ImageAnnotation en correspondance avec une image
	// Envoi les annotations correspondantes à l'ImageAnnotation 
	this.createImgAnnotation = function (imgId, ctId, imgContainerType) {
		
		var ctElAnnotations = this.annotations.get(imgId);
		var ctEl = document.getElementById (ctId);
		ctEl.imgAnnotation = new fcbm.component.ImageAnnotation ({
			id: imgId,
			ctId: ctId,
			imgContainerType: imgContainerType,
			documentType: this.initialConfig.documentType, 
			solutionMode: this.initialConfig.solutionMode,
			imgAnnotationMgr: this
		});
		
		this.registeredImg.add (imgId+ctId, {imgId:imgId, ctId:ctId, imgContainerType: imgContainerType});
		this.sendAnnotations (ctId, ctElAnnotations);
		
	};
	
	// Défini la cellule qui sera identifée via le mur d'image
	// Envoi l'info aux panneaux latéraux de sélection des cellules
	this.setCellIdSelected = function (id) {
		this.cellIdSelected = id;
		
		var data = this.initialConfig.document.formuleLeuco.getDataObjects();
		this.updatePanelCellIdSelected(id, 'Grid', data);
		this.updatePanelCellIdSelected(id, 'Zoom', data);
		
	};
	
	// Change l'item sélectionné sur les panneaux latéraux de sélection des cellules
	this.updatePanelCellIdSelected = function (id, mode, data) {
		var el = Ext.get('panelFormLeuco' + mode);
		if (el != null) {
			for (var i = 0; i < data.length; i++) {
				el = Ext.getCmp('radio'+mode+'_'+data[i].id);
				el.suspendEvents();
				if (el.inputValue == id)
					el.setValue(true);
				else
					el.setValue(false);
				el.resumeEvents();
			}
			this.leucoCount.eachKey (function (key, item) {
				Ext.getCmp('text'+mode+'_'+ key).setValue(item);
			});
		}
	}

	// Renvoi l'id du type de cellule à sélectionner
	this.getCellIdSelected = function () {
		return this.cellIdSelected;
	};
	
	// Renvoi l'abbréviation d'une cellule sélectionné
	this.getCellAbbrevById = function (id) {
		return this.initialConfig.document.formuleLeuco.getAbbrevById(id);
	};
	
	// private
	// Envoi les annotations à l'ImageAnnotation contenu dans le container ctId
	this.sendAnnotations = function (ctId, annotations) {
		var ctEl = document.getElementById (ctId);
		ctEl.imgAnnotation.setAnnotations (annotations);
	};
	
	// public
	// ImageAnnotation send a command to tell that user has modified his annotations
	// stores the new annotations and dispatch the information (this.dispatchAnnotation)
	this.updateAnnotations = function (imgId, annotations) {
		this.annotations.replace(imgId, annotations);
		
		this.updatePanelCount();
		
		this.dispatchAnnotation (imgId, annotations);
	};
	
	// updatePanelCount
	// Met à jour le compte des cellules identifiées par l'utilisateur sur le mur d'image 
	// Appelle updateIndividualPanel qui effectue l'action sur les panneaux concernés
	this.updatePanelCount = function () {
		var data = this.initialConfig.document.formuleLeuco.getDataObjects();
		
		this.countLeuco();
		this.updateIndividualPanel ('Grid', data);
		this.updateIndividualPanel ('Zoom', data);
		
	};
	
	// updateIndividualPanel
	// Met à jour le compte des cellules identifiées par l'utilisateur sur le mur d'image 
	this.updateIndividualPanel = function (mode, data) {
		var el = Ext.get('panelFormLeuco' + mode);
		if (el != null) {
			for (var i = 0; i < data.length; i++) {
				Ext.getCmp('text'+mode+'_'+data[i].id).setValue("0");
			}
			this.leucoCount.eachKey (function (key, item) {
				Ext.getCmp('text'+mode+'_'+ key).setValue(item);
			});
		}
	}
	
	// countLeuco
	// Met à jour la variable leucoCount de 'ImageAnnotationManager
	this.countLeuco = function () {
		this.leucoCount.clear();

		this.annotations.eachKey ( function (key, item) {
			for (var i=0; i<item.length; i++) {
				if (item[i].userAnswerId != "") {
					var cur = this.leucoCount.get(item[i].userAnswerId);
					if (cur != null)
						this.leucoCount.replace(item[i].userAnswerId, cur+1);
					else
						this.leucoCount.add(item[i].userAnswerId, 1);
				}
			}
		}, this);
		// maj store
		this.getFormuleLeucoCountDataStore();
	};
	
	// public
	// User has replied to a training, set the solution mode and
	// dispatch the information to the wall images
	this.setSolutionMode = function (isSolutionMode) {
		this.initialConfig.solutionMode = true;
		this.registeredImg.eachKey (function (key, item) {
			var el = document.getElementById(item.ctId);
			if (el != null)
				el.imgAnnotation.setSolutionMode (true); 
		});
	};
	
	// private
	// Envoi les annotations aux images concernées
	this.dispatchAnnotation = function (imgId, annotations) {
		this.registeredImg.eachKey (function (key, item) {
			if (key.indexOf(imgId) != -1) {
				var el = document.getElementById(item.ctId);
				if (el != null)
					this.imgAnnotationMgr.sendAnnotations (item.ctId, this.annotations); 
			}
		}, {imgAnnotationMgr: this, annotations: annotations});
	};
	
	// getFormuleLeucoCountDataStore
	this.getFormuleLeucoCountDataStore = function () {
		var data = [];
		this.leucoCountNb = 0;
		var totalRef = 0;
		var fl = this.initialConfig.document.formuleLeuco.getDataObjects();
		var gb = this.initialConfig.document.numeration.getGBValue ();
		this.leucoCount.eachKey (function (key, item) {
			var nb = this.leucoCount.get(key);
			if (nb != null && key != 'ERB')
				this.leucoCountNb += nb;
		}, this);
		for (var i = 0; i < fl.length; i++) {
			if (fl[i].id != 'ERB')
				totalRef += parseInt(fl[i].value);
		}
		for (var i=0; i<fl.length; i++) {
			var cur = fl[i];
			cur.nb = (this.leucoCount.get(cur.id) == null ? 0 : this.leucoCount.get(cur.id));
			cur.percent = (this.leucoCountNb == 0 ? 0 : Math.round(cur.nb / this.leucoCountNb * 100));
			cur.percentRef = (totalRef == 0 ? 0 : Math.round(cur.value / totalRef * 100));
			if (cur.id != 'ERB')
				cur.milliardieme = (this.leucoCountNb == 0 ? 0 : Math.round(cur.nb * gb / this.leucoCountNb * 10) / 10);
			else
				cur.milliardieme = "";
			data.push ([
				(cur.idx == fl.length ? cur.idx + 1 : cur.idx),
				cur.id,
				cur.abbrev,
				cur.shortName,
				cur.name,
				cur.value,
				cur.special,
				cur.nb,
				cur.percent,
				cur.milliardieme,
				cur.percentRef
			]);
		}
		// total
		data.push ([
			fl.length,
			"id",
			"abbrev",
			"shortName",
			"Nombre de leucocytes",
			-1,
			1,
			this.leucoCountNb,
			100,
			gb,
			100
		]);
		
		if (this.leucoCountDataStore == null) {
			this.leucoCountDataStore = new Ext.data.Store({
				proxy: new Ext.data.MemoryProxy(data),
				reader: new Ext.data.ArrayReader(
					{}, 
					[
						{name: 'idx'},
						{name: 'id'},
						{name: 'abbrev'},
						{name: 'shortName'},
						{name: 'name'},
						{name: 'value'},
						{name: 'special'},
						{name: 'nb'},
						{name: 'percent'},
						{name: 'milliardieme'},
						{name: 'percentRef'}
					]
				),
				sortInfo:{field: 'idx', direction: "ASC"}
			});
			this.leucoCountDataStore.load();
		} else {
			this.leucoCountDataStore.proxy = new Ext.data.MemoryProxy(data);
			this.leucoCountDataStore.reload();
		}
	};
	
	// init store
	this.getFormuleLeucoCountDataStore();
	
};
Ext.extend(fcbm.component.ImageAnnotationManager, Ext.util.Observable);
// End fcbm.component.ImageAnnotationManager


/*
 * 
 */

var timeOutRollOut = null
var lroId = ""; // last rollover id
var lroTs = 0; // last rollover timestamp
var lrouTs = 0; // last rollout timestamp
var timerROut = 50; // timer rollOut
var aRo = [];

function rollOver(el) {
	clearTimeout(timeOutRollOut);
	
	if (lroId != el.id) {
		if (lroId != "") {
			if (document.getElementById(lroId)) {
				var divs = document.getElementById(lroId).parentNode.getElementsByTagName('div');
				for (var i = 0; i < divs.length; i++) {
					if (divs[i].getAttribute('id') == lroId) 
						divs[i].className = 'ovRep';
				}
			}
		}
		aRo.push(lroId = el.id);
		lroTs = new Date().getTime();
		if (el) {
			var divs = el.parentNode.getElementsByTagName('div');
			for (var i = 0; i < divs.length; i++) {
				if (divs[i].getAttribute('id') == el.id) 
					divs[i].className = 'ovRepHover';
			}
		}
	}	
};

function rollOut(el) {
	clearTimeout(timeOutRollOut);	
	lrouTs = new Date().getTime();
	timeOutRollOut = setTimeout("verif_rollOut()", timerROut + 5);
};

function verif_rollOut() {
	if (lroTs < lrouTs) {
		for (var i=0; i<aRo.length; i++) {
			var el = document.getElementById(aRo[i]);
			if (el) {
				var divs = el.parentNode.getElementsByTagName('div');
				for (var j = 0; j < divs.length; j++) {
					if (divs[j].getAttribute('id') == el.id && divs[j].className == 'ovRepHover') 
						divs[j].className = 'ovRep';
				}
			}
		}
		aRo = [];
		lroId = "";
		lroTs = lrouTs = 0;
	}
}

function assignCell (el) {
	var imgAnnot = el.parentNode.parentNode.imgAnnotation;
	imgAnnot.setCellId (el.id);
}

