/**
 *
 * LCMS and its source-code is licensed under the LGPL.
 * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
 * When copying, adapting, or redistributing this document in keeping with the guidelines above,
 * you are required to provide proper attribution to champion open systems.
 * If you reproduce or distribute the document without making any substantive modifications to its content,
 * please use the following attribution line:
 *
 * Copyright 2007 champion open systems (http://www.chaosys.ch) All rights reserved.
 *
 */



/**
* 
* Functions concerning computation and other utils for the whole Webmic.
*
*/


/** 
*
* initialize-Section.
*
*/

/**
* initialize webmic components.
*/
function initWebmic( host ) {
	addListeners();
	webappHost=host;
	viewObjectElement = document.getElementById('viewObject');
	viewObjectElement.src = host+"/pictures/webmic_blank.png";
	navigationScreenElement = document.getElementById('navigationScreenImage');
	navigationScreenElement.src = host+"/pictures/webmic_blank.png";
	labelRegistry = new Array();
	if(document.body.id == ''){
		document.body.id="tundra";
	}else{
		document.body.id=document.body.id + " tundra";
	}
	if(document.body.className == ''){
		document.body.className="tundra";
	}else{
		document.body.className=document.body.id + " tundra";
	}
	
}

/**
* initialize webmic components second step.
*/
function initStep2(){
	centerView();
	performGlobalUpdate();
}

/**
* MouseEvent - Listeners for html-components.
*/
function addListeners(){
	viewObjectElement = document.getElementById("viewObject");
	navigatorEyeElement = document.getElementById("navigatorEye");
	startButtonElement = document.getElementById("startmicrobutton");
	endButtonElement = document.getElementById("endmicrobutton");
	
	startButtonElement.onclick = function(evt){
		startX = getMicrometerX(parseFloat(calculatePercLeft(50)));
		startY = getMicrometerY(parseFloat(calculatePercTop(50)));
		startButtonElement.style.background = "green";
		endButtonElement.style.background = "none";
		document.getElementById("distancemicrometer").firstChild.nodeValue=" ";
	}
	endButtonElement.onclick = function(evt){
		endX = getMicrometerX(parseFloat(calculatePercLeft(50)));
		endY = getMicrometerY(parseFloat(calculatePercTop(50)));
		endButtonElement.style.background = "green";
		startButtonElement.style.background = "none";
		setDistance();
	}
	
	viewObjectElement.onmousemove = function(evt){
		performGlobalUpdate();
	}
	viewObjectElement.onmouseup = function(evt){
		performGlobalUpdate();
	}
	navigatorEyeElement.onmousemove = function(evt){
		navigatorEyeMoveListenerImplementation();
	}
	navigatorEyeElement.onmouseup = function(evt){
		performGlobalUpdate();
	}
	
}

/** 
*
* command-Section.
*
*/
/**
* Find the action for the chosen command.
*/
function chooseCommand(command, host){
	if(command == 'please select ..'){	
	}else if(command == 'cross hairs'){
		setCrossHairs();
	}else if(command == 'show labels'){
		if(useLabelLayer){
			hideLabelLayer();
			hideAllLabelsInNavigationscreen();
		}else{
			showLabelLayer();
			showAllLabelsInNavigationscreen();
		}
	}else if(command == 'center view'){
		centerView();
		performGlobalUpdate();
	}else if(command == 'add label'){
		if(!useLabelLayer){
			showLabelLayer();
		}
		//Actual Position in Percent.
		xperc = parseFloat(calculatePercLeft(50));
		yperc = parseFloat(calculatePercTop(50));
		addLabel( "Label"+parseInt(xperc)+"_"+parseInt(yperc), document.getElementById('labelClosedText').value, document.getElementById('labelOpenedText').value, xperc, yperc, "yellow" );
		document.getElementById('labelClosedText').value="";
		document.getElementById('labelOpenedText').value="";
	}else if(command == 'reset'){
		resetWebmic(host);
	}
}

/** 
*
* Reset-Section.
*
*/
/** 
* Restore default settings for the whole WebMicroscope.
*/
function resetWebmic(host){
	resetFields();
	if(useLabelLayer){
		hideLabelLayer();
	}
	removeAllLabels();
	viewObjectElement = document.getElementById('viewObject');
	viewObjectElement.src = host+"/pictures/webmic_blank.png";
	navigationScreenElement = document.getElementById('navigationScreenImage');
	navigationScreenElement.src = host+"/pictures/webmic_blank.png";
	centerView();
	performGlobalUpdate();
}
/** 
* Restore default settings for the inputfields.
*/
function resetFields(){
	document.getElementById('labelClosedText').value="";
	document.getElementById('labelOpenedText').value="";
	dijit.byId("zoomsliderId").setValue(0);
}

/**
* Keep webmic-components uptodate.
*/
function performGlobalUpdate() {
	try{
		//functional updates
		if(avoidWhiteAreasFlag){
			avoidWhiteAreas();
		}
		setNavigatorEye();
		setLabelLayer();
		updateInfo();
	}catch(err){}
}

/** 
*
* Getter and Setter - Section.
*
*/
/** 
* Returns the width of the objectiv div-tag.
*/
function getObjectivX() {
	return 500;
}

/** 
* Returns the height of the objectiv div-tag.
*/
function getObjectivY() {
	return 500;
}

/** 
* Calculate percentage of left position.
*/
function calculatePercLeft(targetPercFromTopLeft) {
	viewObjectElement = document.getElementById('viewObject');
	var left = parseFloat(viewObjectElement.style.left);
	var xmax = parseFloat(getViewObjectWidth());
	var lefttot = 0;
	if(left > 0) {
		lefttot = (getObjectivX() / 100) * targetPercFromTopLeft - left;
	}else {
		lefttot = (getObjectivX() / 100) * targetPercFromTopLeft + Math.abs(left);
	}
	var prozx = lefttot / (xmax / 100);
	return prozx;
}

/** 
* Calculate percentage of top position.
*/
function calculatePercTop(targetPercFromTopLeft) {
	viewObjectElement = document.getElementById('viewObject');
	var top = parseFloat(viewObjectElement.style.top);
	var ymax = parseFloat(getViewObjectHeight());
	var toptot = 0;
	if(top > 0) {
		toptot = (getObjectivY() / 100) * targetPercFromTopLeft - top;
	}else {
		toptot = (getObjectivY() / 100) * targetPercFromTopLeft + Math.abs(top);
	}
	var prozy = toptot / (ymax / 100);
	return prozy;
}

/** 
* Calculating percents.
*/
function calculatePercentage( total, part) {
	return part/(total/100);
}

/** 
* Set 'viewObject' width.
*/
function setViewObjectWidth( value ){
	document.getElementById('viewObject').style.width=value+"px";
}

/** 
* get 'viewObject' width.
*/
function getViewObjectWidth(){
	viewObjectElement = document.getElementById('viewObject');
	return viewObjectElement.width;
}


function getViewObjectWidthMicrometer(){
	return 500;
}
function getViewObjectHeightMicrometer(){
	return 400;
}

/** 
* Set 'viewObject' height.
*/
function setViewObjectHeight( value ){
	document.getElementById('viewObject').style.height=value+"px";
}

/** 
* get 'viewObject' height.
*/
function getViewObjectHeight(){
	viewObjectElement = document.getElementById('viewObject');
	return viewObjectElement.height;
}

/** Dataimport Sti-Webmic. **/
/** 
* convert Sti units to picture Relation.
*/

function stiUnitsToPercent(unit, picAbs){
	coordinateAsPixel = unit / 15;
	return calculatePercentage(picAbs, coordinateAsPixel);
}

var http = null;
function importXML( xmlFile ){
        if (document.implementation && document.implementation.createDocument)
        {
                xmlDoc = document.implementation.createDocument("", "", null);
                http = new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                http = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else
        {
                alert('Your browser can\'t handle this script');
                return;
        }
        http.open("GET", xmlFile, true);
       	http.onreadystatechange = ausgebenLabels; 
        http.send(null);
}

function ausgebenLabels() {
   if (http.readyState == 4) {
        labelsXml=http.responseXML;
        loadLabels();
   }
}
       
var http2 = null;
function importQuestionXML( xmlFile2 ){
        if (document.implementation && document.implementation.createDocument)
        {
                xmlDoc2 = document.implementation.createDocument("", "", null);
                http2 = new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {
                xmlDoc2 = new ActiveXObject("Microsoft.XMLDOM");
                http2 = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else
        {
                alert('Your browser can\'t handle this script');
                return;
        }
        
        http2.open("GET", xmlFile2, true);
       	http2.onreadystatechange = outputQuestions;
        http2.send(null);
}

function outputQuestions(){
   if (http2.readyState == 4) {
        questionXml=http2.responseXML;
        loadQuestions();
   }
}



function getMicrometerObjectivX(){
	xPercent = calculatePercentage(getViewObjectWidth(),getObjectivX());
	xTotalMicrometer = getViewObjectWidthMicrometer();
	result = (xTotalMicrometer / 100) * xPercent;
	return result;
}

function getMicrometerX(xperc){
	xTotalMicrometer = getViewObjectWidthMicrometer();
	result = (xTotalMicrometer / 100) * xperc;
	return result;
}

function getMicrometerY(yperc){
	yTotalMicrometer = getViewObjectHeightMicrometer();
	result = (yTotalMicrometer / 100) * yperc;
	return result;
}
function setDistance(){
	a = 0;
	b = 0;
	c = 0;
	if((startX - endX) > 0){
		a = startX - endX;
	}else{
		a = endX - startX;
	}
	if((startY - endY) > 0){
		b = startY - endY;
	}else{
		b = endY - startY;
	}
	c = Math.sqrt(a*a + b*b);
	if(infoRoundedFlag){
		c = c.toFixed(2);
	}
	document.getElementById("distancemicrometer").firstChild.nodeValue="Distance: " + c + " \u00B5m ";
}