﻿// holds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
// holds the remote server address and parameters
var serverAddress = "sys/login2.php";
var serverAddress2 = "sys/logout.php";

var L_username = "";
var L_password = "";

var username = '';

// creates an XMLHttpRequest instance
function createXmlHttpRequestObject() {
	// will store the reference to the XMLHttpRequest object
	var xmlHttp;
	// this should work for all browsers except IE6 and older
	try {
		// try to create XMLHttpRequest object
		xmlHttp = new XMLHttpRequest();
	} catch(e) {
		// assume IE6 or older
		var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
																		"MSXML2.XMLHTTP.5.0",
																		"MSXML2.XMLHTTP.4.0",
																		"MSXML2.XMLHTTP.3.0",
																		"MSXML2.XMLHTTP",
																		"Microsoft.XMLHTTP");
		// try every prog id until one works
		for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) {
			try {
				// try to create XMLHttpRequest object
				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			} catch (e) { }
		}
	}
	
	// return the created object or display an error message
	if (!xmlHttp)
		displayError("Error creating the XMLHttpRequest object.");
	else 
		return xmlHttp;
}

// call server asynchronously
function login() {
	
	//log('login()');
	
	// get username and password
	L_username = document.forms['loginform'].username.value;
	L_password = document.forms['loginform'].passwort.value;
	
	if ((L_username == '') || (L_password == '')) {
		loginNotClicked()
		return;
	}
	
	// only continue if xmlHttp isn't void
	if (xmlHttp) {
		// try to connect to the server
		try {
			// make asynchronous HTTP request to retrieve new message
			xmlHttp.open("GET", serverAddress + "?username=" + L_username + "&password=" + L_password, true);
			xmlHttp.onreadystatechange = handleCheckLogin;
			xmlHttp.send(null);
		} catch(e) {
			log('error: ' + e.toString());
		}
	}
}

// function called when the state of the HTTP request changes
function handleCheckLogin() {
	//log('handleCheckLogin()');
	
	// when readyState is 4, we are ready to read the server response
	if (xmlHttp.readyState == 4)  {
		// continue only if HTTP status is "OK"
		if (xmlHttp.status == 200)  {
			try {
				// do something with the response from the server
				checkLogin();
			}
			catch(e) {
				// display error message
				displayError(e.toString());
			}
		} else {
			// display error message
			displayError(xmlHttp.statusText);   
		}
	}
}

// handles the response received from the server
function checkLogin() {
	//log('checkLogin()');
	
	// retrieve the server's response 
	var response = xmlHttp.responseText;
	  
	response = response.split(';');
	
	//log('checkLogin - response: ' + response);  
	// login ok
	if (response[0] > 0) {
		setUserID(response[0]);
		setAdmin(response[1]);
		loggedIn();
		begintimer();
		// window.location.reload();
	} else {
		window.location='sys/login.php';
	}  
}

function loginNotClicked() {
	var html =
		'<form name="searchFormLoggedOut" action="javascript:showAddress(document.searchFormLoggedOut.address.value);">' +
			'<table><tr>'+
				'<td><img src="img/map/topbar/dot_line.png" /></td>' +
				'<td>Stra&szlig;ensuche</td>' +
				'<td>' +
					'<input type="text" class="deftext" size="35" name="address" id="address" value="'+IN_defText("in1")+'" onClick="IN_focus('+"'in1'"+')" onblur="IN_blur('+"'in1'"+')" />' +
				'</td>' +
				'<td>' +
					'<a href="javascript:showAddress(document.searchFormLoggedOut.address.value);">' +
						'<img src="img/map/topbar/search.png" title="Straße suchen" />' +
					'</a>' +
				'</td>' +
				'<td><img src="img/map/topbar/dot_line.png" /></td> ' +
				'<td><a href="javascript:loginClicked();">Anmelden</a></td>' +
				'<td><a href="javascript:loginClicked();"><img src="img/map/topbar/loginout.png" /></a></td>';
			'</tr></table>'+
		'</form>';
		
	$('innerbar').innerHTML = html;
	$('control_topmenu').innerHTML = unregisteredTopMenu();
}


function unregisteredTopMenu() {

	return globalTopMenu +
			'<div class="right">'+
			'<img src="./img/pages/topmenu/arrow.png" />'+
			'<a class="last orange" href="./sys/register.php">Neu registrieren</a>'+
			'</div>';
}

function loggedInTopMenu() {

	return globalTopMenu +
			'<div class="right">'+
			'<a href="sys/list_single_user.php?user_id='+ globalStatus.user_id +'" class="orange">'+
				'<img src="./img/pages/topmenu/arrow.png" />&nbsp;'+
				'Meine Unorte'+
			'</a>'+
			'<a class="last" href="sys/editprofile.php">Profil bearbeiten</a>'+
			'</div>';
}



function loginClicked() {
	var html =
		'<form name="loginform" action="javascript:login();" method="post">' +
			'<table><tr>'+
				'<td><img src="img/map/topbar/dot_line.png" /></td>' +
				'<td><a href="sys/passwordrecovery.php">Passwort vergessen?</a></td>' +
				'<td><img src="img/map/topbar/dot_line.png" /></td>' +
				'<td>Name</td>' +
				'<td><input style="width:90px;float:left;margin-top:0px;" type="text" name="username" id="username" tabindex="1" /></td>' +
				'<td>Passwort</td>' +
				'<td><input style="width:90px;float:left;margin-top:0px;" type="password" name="passwort" tabindex="2" /></td>' +
				//'<td><a href="javascript:login();"><img src="img/map/topbar/loginout.png" /></a></td>' +
				'<td><input type="image" id="submit" src="img/map/topbar/loginout.png" alt="anmelden" tabindex="3" /></td>' +
			'</tr></table>'+
		'</form>';
	
	$('innerbar').innerHTML = html;
	$('username').focus();
}

function loggedIn() {
	var html =
		'<form name="searchFormLoggedIn" action="javascript:showAddress(document.searchFormLoggedIn.address.value);">' +
			'<table><tr>'+
				'<td><img src="img/map/topbar/dot_line.png" /></td>' +
				'<td>Stra&szlig;ensuche</td>' +
				'<td>' +
					'<input type="text" class="deftext" size="35" name="address" id="address" value="'+IN_defText("in1")+'" onClick="IN_focus('+"'in1'"+')" onblur="IN_blur('+"'in1'"+')" />' +
				'</td>' +
				'<td>' +
					'<a href="javascript:showAddress(document.searchFormLoggedIn.address.value);">' +
						'<img src="img/map/topbar/search.png" title="Straße suchen" />' +
					'</a>' +
				'</td>' +
				'<td><img src="img/map/topbar/dot_line.png" /></td>';
	
	if (globalStatus.user_name != '')
		html += 
				'<td>Angemeldet als: <a href="sys/editprofile.php">' + globalStatus.user_name + '</a></td>'+
				'<td><img src="img/map/topbar/dot_line.png" /></td>';
		
	html +=
				'<td><a href="javascript:logout();">Abmelden</a></td>' +
				'<td><a href="javascript:logout();"><img src="img/map/topbar/loginout.png" /></a></td>'+
			'<tr></table>' +
		'</form>';
		
	$('innerbar').innerHTML = html;
	$('control_topmenu').innerHTML = loggedInTopMenu();
	if (globalStatus.open_window) {
		last_clicked_marker = null;
		manualOpen( unortMarkersByID['u'+globalStatus.place_id], globalStatus.place_id );
	}
}

function logout() {
	setUserID(-1);
	if (DU_form4_uploadWindow)
		DU_form4_uploadWindow.close();
		
	// reopen window, if one is open
	if (globalStatus.open_window) {
		last_clicked_marker = null;
		manualOpen( unortMarkersByID['u'+globalStatus.place_id], globalStatus.place_id );
	}
	
	// only continue if xmlHttp isn't void
	if (xmlHttp) {
		// try to connect to the server
		try {
			// make asynchronous HTTP request to retrieve new message
			xmlHttp.open("GET", serverAddress2, true);
			xmlHttp.onreadystatechange = handleLogout;
			xmlHttp.send(null);
		} catch(e) {
			log('error: ' + e.toString());
		}
	}
}

// function called when the state of the HTTP request changes
function handleLogout() {
	//log('handleCheckLogout()');
	
	// when readyState is 4, we are ready to read the server response
	if (xmlHttp.readyState == 4) {
		// continue only if HTTP status is "OK"
		if (xmlHttp.status == 200) {
			try {
				// remove userid value otherwise the creation of an unort is still possible
				loginNotClicked();
				//alert(1);
			} catch(e) {
				// display error message
				displayError(e.toString());
			}
		} else {
			// display error message
			displayError(xmlHttp.statusText);   
		}
	}
}



