var req;

var salutation;
var pin;
var timeout = "NULL";
var loadingAudio;
var audioStatus = 0;
var inp1;

var mainWindow = null;

//initialize the XMLHttpRequest object
try {
	if (window.XMLHttpRequest) {
	  req = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
	  req = new ActiveXObject("Microsoft.XMLHTTP");
	}
} catch(e) {}

/**
 * Überprüft die Eingaben im Login-Formular.
 * Auf dem Server wird nachgefragt, ob die PIN überhaupt verwendet wird.
 *  
 * @return true, wenn alles OK
 */
function checkLoginForm() {
  fillInfo('');
  salutation = document.getElementById("salutation").value;
  if (document.getElementById("salutationMrSpan").style.visibility != 'hidden') {
    if (document.getElementById("Mr").checked == true) {
      salutation = getLangText(locale, 'Mr');
    }
    if (document.getElementById("Ms").checked == true) {
      salutation = getLangText(locale, 'Mrs');
    }
  }
  name = document.getElementById("name").value;
  name = name.replace(/:/g, " "); // Doppelpunkt durch Leerzeichen ersetzen
  name = trim(name);
  if (name.length == 0) {
    fillInfo(getLangText(locale, 'TypeName'));
    return false;
  }
  
  // Leerzeichen am Anfang und Ende mit RegExp entfernen  
  //pin = document.getElementById("pin").value.replace(/^\s+/, '').replace(/\s+$/, '');
  
  // Alle Nicht-Ziffern entfernen  
  pin = document.getElementById("pin").value.replace(/[^0-9]/g, '');
  document.getElementById("pin").value = pin;
  if (pin.length < 4 || pin.length > 6) {
    //fillInfo(getLangText(locale, 'TypePIN'));
    fillInfo(getLangText(locale, 'CheckPIN'));
    return false;
  }
  
  if (req != null && req.readyState != 0) {
    req.abort();
  }

  var strCallNr = '-1.-1.' + pin;
  var url = contextPath + "/comm/ajaxcommunication?action=isValidCallNr&strCallNr=" + strCallNr + "&time=" + (new Date()).getTime();
  // Überprüpfe PIN per AJAX (synchron)
  if (req != null) {
    req.open("GET", url, false);
    req.send(null);
    // Antwort auf den Login-Request
		if (req.readyState == 4) {
		  //process only if OK
		  if (req.status == 200) {
	      // PIN OK ?
		    if (req.responseText == 'yes') {
		    	originalPIN = pin
		      return true;
		    } else if (req.responseText == '1') {
		      fillInfo(getLangText(locale, 'MaxClients'));
		    } else if (req.responseText == '0') {
		      fillInfo(getLangText(locale, 'CheckPIN'));
		    }
		  }
    }
    return false;
  } else {
		//alert("Ajax steht nicht zur Verfügung");
	  mainWindow = window.open(getMainPage(), 'csn',
    			'fullscreen=yes,status=no,hotkeys=no,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes');
  }

}

/**
 * Starten der Session
 */
function login(closeWindow) {

  var strCallNr = '-1.-1.' + pin;
  
  // Falls Conference-Fenster noch offen, dann beenden und Fenster schließen
  if (mainWindow) {
  	if (timeout != "NULL") {
			window.clearTimeout(timeout);
		}
    sendEndCall();
    if (closeWindow) {
    	mainWindow.close();
    }
  }
  
	if (javaClient) {
		mainWindow = window.open(getMainPage(), 'csn',
					'fullscreen=yes,status=no,hotkeys=no,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes');
	} else {
    // Sende Login-Request per AJAX, 
		// bei 'handover' wiederholen (maximale Iteration 'securityCounter')
		securityCounter = 5;
		while (strCallNr != '' && securityCounter >= 0) {
			securityCounter--;
			
			var addParams = ""
				
			if (window.location.search != "" && window.location.search.length > 1) {
				addParams = "&addParams=" + encodeURIComponent(window.location.search.substring(1))
			}
			
		  //TODO Salutation fehlt noch
		  var url = contextPath + "/comm/ajaxcommunication?action=callRequest&CallNr=" + strCallNr + "&Name=" + encodeURIComponent(name) 
		  					+ "&time=" + (new Date()).getTime() + "&oPIN=" + originalPIN + addParams;
		  if (req != null && req.readyState != 0) {
				req.abort();
		  }
		  req.open("GET", url, false);
		  req.send(null);
		  if (req.readyState == 4) {
		    //process only if OK
		    if (req.status == 200) {
		      if (req.responseText == 'failed') {
		      	strCallNr = '';
		        alert("Anmeldung fehlgeschlagen");
		      } else if (req.responseText.indexOf("Handover:") == 0) {
		      	resultArray = req.responseText.split(":");
		      	handoverPIN = resultArray[1].trim();
		      	strCallNr = '-1.-1.' + handoverPIN;
		      } else {
		      	//alert(req.responseText);
		      	strCallNr = '';
		      	handoverPIN = '';
		      	resultArray = req.responseText.split("\n");
		      	callRet = resultArray[0];
		      	clientID = resultArray[1];
		      	if (resultArray[2]) {
		      	  if (resultArray[2].indexOf('Audio:') == 0) {
		      	  	playAudio = true;
		      	  	var data = resultArray[2].split('Audio:')[1].split(',');
		      	  	beginAudio = data[0]; 
		      	  	beginCutAudio = data[1]; 
		      	  	endCutAudio = data[2];
		      	  } else if (resultArray[2].indexOf('Time:') == 0) {
		      	  	playTime = resultArray[2].split('Time:')[1];
		      	  	playTimeSet = Date.parse((new Date()).toGMTString());
		      	  }
		      	}
		      	if (resultArray[3]) {
		      	  if (resultArray[3].indexOf('Audio:') == 0) {
		      	  	playAudio = true;
		      	  	var data = resultArray[3].split('Audio:')[1].split(',');
		      	  	beginAudio = data[0]; 
		      	  	beginCutAudio = data[1]; 
		      	  	endCutAudio = data[2];
		      	  } else if (resultArray[3].indexOf('Time:') == 0) {
		      	  	playTime = resultArray[3].split('Time:')[1];
		      	  	playTimeSet = Date.parse((new Date()).toGMTString());
		      	  }
		      	}
		      	if (playAudio) {
		      		dumpString(beginAudio + ", " + beginCutAudio + ", " + endCutAudio);
		      		dumpString("Current PlayTime: " + playTime);
		      		startPlayAudio();
		      	} else {
		      		openMainWindow();
		      	}
		      }
		    }
		  }
		}
	}
}

/*
 * Normaler Start ohne Audio
 */
function openMainWindow() {
	normalExit = false;
	externEcho = false;
	
	// Hauptfenster öffnen, Kommunikation wird im neuen Fenster gestartet
	mainWindow = window.open(getMainPage(), 'csn', 
					'fullscreen=yes,status=no,hotkeys=no,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes');
	
	// Periodisch überprüfen, ob der Nutzer das Fenster geschlossen hat
	timeout = window.setTimeout("checkLogout()", 2000);
}

/*
 * Start nachdem die Audiodatei geladen wurde 
 */
function openMainWindow2() {
	flashStartAudio = true;
	closeDialog();
	openMainWindow();
}

function startPlayAudio() {
	if (!checkFlashSupport()) {
		showDialog2(getLangText(locale, 'AudioNeedFlash'), "OK", getLangText(locale, 'Advice'));
	} else {
		flashStartAudio = false;
		stopPlayAudio();
		var frame = document.createElement("iframe");
		frame.src = "/h-flash-audio-frame.html?call=" + callRet + "&id=" + clientID;
		frame.id = "audioFrame"; 
		frame.width = "20"; 
		frame.height = "20"; 
		frame.style.width = "20"; 
		frame.style.height = "20";
		frame.name = "audioFrame"; 
		frame.style.position = "absolute"; 
		frame.style.top = "0"; 
		frame.style.left = "0";
		frame.style.zIndex = "3";
		frame.style.overflow = "hidden";
		frame.style.border = "0";
		frame.allowTransparency = "true";
		document.getElementById("audio").appendChild(frame);
		
		if (loadingAudio != "NULL") {
			window.clearTimeout(loadingAudio);
		}
		loadingAudio = window.setTimeout("checkLoadingAudio()", 100);
	}
}

function checkLoadingAudio() {
	//dumpString(audioStatus);
	if (audioStatus == 1) {
		//closeDialog();
		//openMainWindow();
		window.clearTimeout(loadingAudio);
		loadingAudio = "NULL";
		//dumpString("Enable Button");
		inp1.style.display = "inline";
		audioStatus = 0;
	} else {
		window.setTimeout("checkLoadingAudio()", 100);
	}
}

function showAudioDialog() {
	showDialog(getLangText(locale, 'AudioDialog'), 'OK', 'OK', 'Audio')
}

function stopPlayAudio() {
	$("#audio").empty();
}

function setLoadingStatus(status) {
	$("#audioStatus").empty();
	var text = document.createTextNode("Ladestatus: " + Math.round(status * 100) + "%");
	document.getElementById("audioStatus").appendChild(text);
	audioStatus = status;
}

function getMainPage() {
	if (javaClient) {
		return mainPage + '?salutation=' + salutation + '&name=' + escape(name) + '&pin=' + pin;
	} else {
		return mainPage;
	}
}

function fillInfo(text) {
  var element_info = document.getElementById("info");
  element_info.innerHTML = text;
}

function checkLogout() {
	if (!checkWindow() && !normalExit) {
		// Fenster geschlossen und nicht normal beendet
		stopPlayAudio();
		// Call beenden, da Fenster geschlossen und der Moderator die Session nicht beendet hat
		sendEndCall();
		timeout = "NULL";
		mainWindow = null;
	} else if (checkWindow() && handoverPIN != '') {
		// Fenster offen und Handover gesetzt
		
		// Abmelden
		sendEndCall();
		
		//Mit HandoverPIN anmelden
		pin = handoverPIN;
		login(false);
	} else {
		// Externes Echo falls eingeschalten
		if (externEcho) {
			var url = contextPath + "/comm/ajaxcommunication?action=checkModus&Call=" + callRet + "&ID=" + clientID + 
								"&time=" + (new Date()).getTime();
		  if (req != null && req.readyState != 0) {
				req.abort();
		  }
		  // Synchroner Aufruf
		  req.open("GET", url, false);
		  req.send(null);
	    if (req.readyState == 4) {
		    if (req.status == 200) {
		    	if (req.responseText.indexOf('ChatStatus:') == 0) {
		    		chatStatus = req.responseText.split(':')[1];
		    	}
		    	if (req.responseText.indexOf('EndCall') == 0) {
		      	externEcho = false;
		      	normalExit = true;
		    	}
		      if (req.responseText != "Nothing" && req.responseText.indexOf('ChatStatus:') != 0 && 
		      		req.responseText.indexOf('Pointer:') != 0 && req.responseText.indexOf('NewAnno') != 0 &&
		      		req.responseText.indexOf('ChatMessage:') != 0 && req.responseText.indexOf('AVLoaded') != 0 &&
		      		req.responseText.indexOf('EndCall')) {
		      	externEcho = false;
		    		// Hauptfenster öffnen, Kommunikation wird im neuen Fenster gestartet
				  	//mainWindow = window.open(mainPage + "?echo=" + req.responseText + "&ChatStatus=" + chatStatus, 'csn', 
				  	//				'fullscreen=yes,status=no,hotkeys=no,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes');
				  	mainWindow.location.href = mainPage + "?echo=" + req.responseText + "&ChatStatus=" + chatStatus;
		      }
		    }
		  }
		}
		if (!normalExit) {
			timeout = window.setTimeout("checkLogout()", 2000);
		} else {
			stopPlayAudio();
		}
	}
}

function sendEndCall() {
	//dumpString("<div>EndCall: " + clientID + "</div>")
	var url = contextPath + "/comm/ajaxcommunication?action=endCall&Call=" + callRet + "&ID=" + clientID + 
						"&time=" + (new Date()).getTime();
  if (req != null && req.readyState != 0) {
		req.abort();
  }
  req.open("GET", url, false);
  req.send(null);
}

function checkWindow() {
	if (!mainWindow) {
		return false;
	} 
	if (mainWindow.closed) {
		return false;
	}
	return true;
}

function trim(s) {
  while (s.substring(0, 1) == ' ') {
    s = s.substring(1,s.length);
  }
  while (s.substring(s.length - 1, s.length) == ' ') {
    s = s.substring(0, s.length - 1);
  }
  return s;
}

function showDialog(dialogText, btn1, btn2, title) {
	layer = document.createElement("div");
	layer.style.position = "absolute";
	layer.style.left = "0px";
	layer.style.top = "0px";
	layer.style.width = "100%";
	layer.style.height = "100%";
	layer.style.zIndex = 100;
	layer.style.filter = "alpha(opacity=65)";
	layer.style.MozOpacity = 0.65;
	layer.style.backgroundColor = "#000";
	layer.id = "layer";
	//layer.onclick = closeDialog;
	document.getElementsByTagName("body")[0].appendChild(layer);
	/*
		<div style="position: absolute; z-index: 101; left: 400px; top: 500px">
			<ul class="navlist">
				<li>
					<a href="#" class="currentTab" style="background-color:FD8003">Bestätigung</a>
				</li>
			</ul>
			<table style="height: 100px; width: 300px;" class="boxContent2" cellspacing="10px">
				<tr>
					<td class="tabText">
						Möchten Sie die Gruppe test wirklich löschen?
					</td>
				</tr>
				<tr height="100%">
					<td style="text-align: right; vertical-align: bottom">
						<input type="button" value="Ja" onclick="alert('Ja')" class="btn"/>
						<input type="button" value="Nein" onclick="alert('Nein')" class="btn"/>
					</td>
				</tr>
			</table>
		</div>				
				*/
	div = document.createElement("div");
	div.style.position = "absolute";
	div.style.left = (Math.round(pageWidth() / 2) - 175) + "px";
	div.style.top = (Math.round(pageHeight() / 2) - 60) + "px";
	div.style.zIndex = 101;
	var ul = document.createElement("ul");
	ul.className = "navlist";
	var li = document.createElement("li");
	var a = document.createElement("a");
	a.href = "#";
	a.className = "currentTab";
	if (!title) {
		title = "Best\xe4tigung";
	}
	var tabText = document.createTextNode(title);
	a.appendChild(tabText);
	li.appendChild(a);
	ul.appendChild(li);
	var table = document.createElement("table");
	table.style.height = "100px";
	table.style.width = "350px";
	table.className = "boxContent2";
	table.cellSpacing = "10px";
	var tb = document.createElement("tbody");
	var tr1 = document.createElement("tr");
	var td1 = document.createElement("td");
	td1.className = "tabText";
	var divText = document.createElement("div");
	var divTextStatus = document.createElement("div");
	divTextStatus.id = "audioStatus";
	var text = document.createTextNode(dialogText);
	divText.appendChild(text);
	td1.appendChild(divText);
	td1.appendChild(divTextStatus);
	tr1.appendChild(td1);
	var tr2 = document.createElement("tr");
	tr2.height = "100%";
	var td2 = document.createElement("td");
	td2.style.textAlign = "right";
	td2.style.verticalAlign = "bottom";
	inp1 = document.createElement("input");
	inp1.type = "button";
	inp1.value = btn1;
	inp1.style.display = "none";
	inp1.id = "audioStartButton";
	inp1.onclick = openMainWindow2;
	//inp1.className = "btn";
	/*var inp2 = document.createElement("input");
	inp2.type = "button";
	inp2.value = btn2;
	inp2.onclick = closeDialog;*/
	//inp2.className = "btn";
	td2.appendChild(inp1);
	//td2.appendChild(inp2);
	tr2.appendChild(td2);
	tb.appendChild(tr1);
	tb.appendChild(tr2);
	table.appendChild(tb);
	div.appendChild(ul);
	div.appendChild(table);
	document.getElementsByTagName("body")[0].appendChild(div);
	return false;
}

function showDialog2(dialogText, btn1, title) {
	layer = document.createElement("div");
	layer.style.position = "absolute";
	layer.style.left = "0px";
	layer.style.top = "0px";
	layer.style.width = "100%";
	layer.style.height = "100%";
	layer.style.zIndex = 100;
	layer.style.filter = "alpha(opacity=65)";
	layer.style.MozOpacity = 0.65;
	layer.style.backgroundColor = "#000";
	layer.id = "layer";
	layer.onclick = openMainWindow2;
	document.getElementsByTagName("body")[0].appendChild(layer);
	div = document.createElement("div");
	div.style.position = "absolute";
	div.style.left = (Math.round(pageWidth() / 2) - 175) + "px";
	div.style.top = (Math.round(pageHeight() / 2) - 60) + "px";
	div.style.zIndex = 101;
	var ul = document.createElement("ul");
	ul.className = "navlist";
	var li = document.createElement("li");
	var a = document.createElement("a");
	a.href = "#";
	a.className = "currentTab";
	if (!title) {
		title = "Best\xe4tigung";
	}
	var tabText = document.createTextNode(title);
	a.appendChild(tabText);
	li.appendChild(a);
	ul.appendChild(li);
	var table = document.createElement("table");
	table.style.height = "100px";
	table.style.width = "350px";
	table.className = "boxContent2";
	table.cellSpacing = "10px";
	var tb = document.createElement("tbody");
	var tr1 = document.createElement("tr");
	var td1 = document.createElement("td");
	td1.className = "tabText";
	var divText = document.createElement("div");
	var divTextStatus = document.createElement("div");
	divTextStatus.id = "audioStatus";
	var text = document.createTextNode(dialogText);
	divText.appendChild(text);
	td1.appendChild(divText);
	td1.appendChild(divTextStatus);
	tr1.appendChild(td1);
	var tr2 = document.createElement("tr");
	tr2.height = "100%";
	var td2 = document.createElement("td");
	td2.style.textAlign = "right";
	td2.style.verticalAlign = "bottom";
	inp1 = document.createElement("input");
	inp1.type = "button";
	inp1.value = btn1;
	inp1.id = "audioStartButton";
	inp1.onclick = openMainWindow2;
	td2.appendChild(inp1);
	tr2.appendChild(td2);
	tb.appendChild(tr1);
	tb.appendChild(tr2);
	table.appendChild(tb);
	div.appendChild(ul);
	div.appendChild(table);
	document.getElementsByTagName("body")[0].appendChild(div);
	return false;
}

function closeDialog() {
	if (inp1) {
		inp1.style.display = "none";
	}
	document.getElementsByTagName("body")[0].removeChild(div);
	document.getElementsByTagName("body")[0].removeChild(layer);
}