/*----------------------------------------------------------------------------\
|                                 XML Extras                                  |
|-----------------------------------------------------------------------------|
|                         Created by Erik Arvidsson                           |
|                  (http://webfx.eae.net/contact.html#erik)                   |
|                      For WebFX (http://webfx.eae.net/)                      |
|-----------------------------------------------------------------------------|
| XML and XML HTTP request abstraction.                                       |
|-----------------------------------------------------------------------------|
|             Copyright (c) 2001, 2002, 2003, 2006 Erik Arvidsson             |
|-----------------------------------------------------------------------------|
| Licensed under the Apache License, Version 2.0 (the "License"); you may not |
| use this file except in compliance with the License.  You may obtain a copy |
| of the License at http://www.apache.org/licenses/LICENSE-2.0                |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| Unless  required  by  applicable law or  agreed  to  in  writing,  software |
| distributed under the License is distributed on an  "AS IS" BASIS,  WITHOUT |
| WARRANTIES OR  CONDITIONS OF ANY KIND,  either express or implied.  See the |
| License  for the  specific language  governing permissions  and limitations |
| under the License.                                                          |
|-----------------------------------------------------------------------------|
| 2001-09-27 | Original Version Posted.                                       |
| 2006-05-29 | Changed license to Apache Software License 2.0.                |
|-----------------------------------------------------------------------------|
| Created 2001-09-27 | All changes are in the log above. | Updated 2006-05-29 |
\----------------------------------------------------------------------------*/

//<script>
//////////////////
// Helper Stuff //
//////////////////

// used to find the Automation server name
function getDomDocumentPrefix() {
	if (getDomDocumentPrefix.prefix)
		return getDomDocumentPrefix.prefix;

	var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
	var o;
	for (var i = 0; i < prefixes.length; i++) {
		try {
			// try to create the objects
			o = new ActiveXObject(prefixes[i] + ".DomDocument");
			return getDomDocumentPrefix.prefix = prefixes[i];
		}
		catch (ex) {};
	}

	throw new Error("Could not find an installed XML parser");
}

function getXmlHttpPrefix() {
	if (getXmlHttpPrefix.prefix)
		return getXmlHttpPrefix.prefix;

	var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
	var o;
	for (var i = 0; i < prefixes.length; i++) {
		try {
			// try to create the objects
			o = new ActiveXObject(prefixes[i] + ".XmlHttp");
			return getXmlHttpPrefix.prefix = prefixes[i];
		}
		catch (ex) {};
	}

	throw new Error("Could not find an installed XML parser");
}

//////////////////////////
// Start the Real stuff //
//////////////////////////

// XmlHttp factory
function XmlHttp() {}

XmlHttp.create = function () {
	try {
		if (window.XMLHttpRequest) {
			var req = new XMLHttpRequest();

			// some versions of Moz do not support the readyState property
			// and the onreadystate event so we patch it!
			if (req.readyState == null) {
				req.readyState = 1;
				req.addEventListener("load", function () {
					req.readyState = 4;
					if (typeof req.onreadystatechange == "function")
						req.onreadystatechange();
				}, false);
			}

			return req;
		}
		if (window.ActiveXObject) {
			return new ActiveXObject(getXmlHttpPrefix() + ".XmlHttp");
		}
	}
	catch (ex) {}
	// fell through
	throw new Error("Your browser does not support XmlHttp objects");
};

XmlHttp.getXmlHttp = function () {
	var xmlhttp = false;
	try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) { xmlhttp = false;
		}
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		try { xmlhttp = new XMLHttpRequest();
		} catch (e) { alert('Seu browser não suporta a tecnologia AJAX.'); 
		}
	}
	return xmlhttp;
};

// XmlDocument factory
function XmlDocument() {}

XmlDocument.create = function () {
	try {
		// DOM2
		if (document.implementation && document.implementation.createDocument) {
			var doc = document.implementation.createDocument("", "", null);

			// some versions of Moz do not support the readyState property
			// and the onreadystate event so we patch it!
			if (doc.readyState == null) {
				doc.readyState = 1;
				doc.addEventListener("load", function () {
					doc.readyState = 4;
					if (typeof doc.onreadystatechange == "function")
						doc.onreadystatechange();
				}, false);
			}

			return doc;
		}
		if (window.ActiveXObject)
			return new ActiveXObject(getDomDocumentPrefix() + ".DomDocument");
	}
	catch (ex) {}
	throw new Error("Your browser does not support XmlDocument objects");
};

// Create the loadXML method and xml getter for Mozilla
if (window.DOMParser &&
	window.XMLSerializer &&
	window.Node && Node.prototype && Node.prototype.__defineGetter__) {

	// XMLDocument did not extend the Document interface in some versions
	// of Mozilla. Extend both!
	//XMLDocument.prototype.loadXML =
	Document.prototype.loadXML = function (s) {

		// parse the string to a new doc
		var doc2 = (new DOMParser()).parseFromString(s, "text/xml");

		// remove all initial children
		while (this.hasChildNodes())
			this.removeChild(this.lastChild);

		// insert and import nodes
		for (var i = 0; i < doc2.childNodes.length; i++) {
			this.appendChild(this.importNode(doc2.childNodes[i], true));
		}
	};


	/*
	 * xml getter
	 *
	 * This serializes the DOM tree to an XML String
	 *
	 * Usage: var sXml = oNode.xml
	 *
	 */
	// XMLDocument did not extend the Document interface in some versions
	// of Mozilla. Extend both!
	/*
	XMLDocument.prototype.__defineGetter__("xml", function () {
		return (new XMLSerializer()).serializeToString(this);
	});
	*/
	Document.prototype.__defineGetter__("xml", function () {
		return (new XMLSerializer()).serializeToString(this);
	});
}

/*****************************
** authentication functions **
******************************/
function loggedin() {
	var campoMostrado = document.getElementById("loginForm");
	if (campoMostrado == null) {
		campoMostrado = document.getElementById("user_info_area").innerHTML;
		var indice = campoMostrado.indexOf('javascript:logout()');
		if (indice == '-1') {
//			alert("Erro no serviço.");
			return false;
		} else {
//colocar para verificar com o cookie
			return true;
		}
	} else {
		return false;
	}
}
function logar() {
	var username = document.getElementById("j_username").value;
	var password = document.getElementById("j_password").value;
if (username == null || password == null || username == '' || password == '') {
	alert("Entre com seu nome de usuário e senha.");
} else {
	password = encodeURIComponent(password);
	var subMenu = document.getElementById("sm3");
	loadingImageAt("loginForm");
	var xmlhttp = new XmlHttp.create();
	xmlhttp.open("POST", "/jmobi-auth/j_security_check", true);
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
	    		verifyAuthentication();
			} else if (xmlhttp.status == 403) {
    			alert("Nome do usuário ou senha inválido, por favor tente novamente.");
    			showLoginForm();
	    	} else {
	    		alert("Desculpe-nos, problema no serviço. Tente\nnovamente mais tarde.");
    			showLoginForm();
	    	}
	    }
	}
	xmlhttp.send("j_username="+username+"&j_password="+password);
}
}
function logout() {
	var xmlHttp = new XmlHttp.create();
	xmlHttp.open("GET", "/jmobi-auth/logout", true);
	xmlHttp.send(null);
	if (document.getElementById("sm3") != null) {
		hideMe("sm3");
		openContent('sobre', 'm1');
	}
	showLoginForm();
}
function viewUserInformation() {
	var xmlHttp = new XmlHttp.create();
	xmlHttp.open("GET", "/jmobi-auth/about?type=xml", true);
	xmlHttp.onreadystatechange=function() {
    	if (xmlHttp.readyState==4) {
    		var htmlText = xmlHttp.responseText;
    		var information = htmlText.indexOf('j_security_check');
			if (information == '-1') {
				showUserStatus(htmlText);
			}
		}
	}
	xmlHttp.send(null);
}
function verifyAuthentication() {
	var xmlHttp = new XmlHttp.create();
	xmlHttp.open("GET", "/jmobi-auth/about?type=xml", true);
	xmlHttp.onreadystatechange=function() {
    	if (xmlHttp.readyState==4) {
    		var htmlText = xmlHttp.responseText;
    		var information = htmlText.indexOf('j_security_check');
			if (information == '-1') {
				showUserStatus(htmlText);
			} else {
				alert("Login inválido. Tente novamente!");
				showLoginForm();
			}
		}
	}
	xmlHttp.send(null);
}
function showUserStatus(ajaxResponse) {
	var xml_doc = XmlDocument.create();
	xml_doc.loadXML( ajaxResponse );
	var userItem = xml_doc.getElementsByTagName("jmobi-user");
	var username = userItem.item(0).getElementsByTagName('username').item(0).firstChild.nodeValue;
	var fullName = userItem.item(0).getElementsByTagName('full-name').item(0).firstChild.nodeValue;
	var userStatusText = "<p id='user_info' >Bem-vindo:<br/><strong>" + fullName + "</strong><br/><a href='javascript:logout()'>sair</a>"
	userStatusText= userStatusText + "<span style='display: none;' id='jmobi-username'>"+username+"</span></p>"
   	document.getElementById("user_info_area").innerHTML = userStatusText;
}
function showLoginForm() {
	var xmlhttp = new XmlHttp.create();
	xmlhttp.open("GET", "/website/loginForm.xml", true);
	xmlhttp.onreadystatechange=function() {
    	if (xmlhttp.readyState==4) {
			var contentBegin = xmlhttp.responseText.indexOf('<texto>') + 9;
			var contentEnd = xmlhttp.responseText.indexOf('</texto>',contentBegin);
			var content = xmlhttp.responseText.substring(contentBegin,contentEnd);
			document.getElementById("user_info_area").innerHTML = content;
   		}
   	}
   	xmlhttp.send(null);
}
