/*  
 * UCK JavaScript API
 * 
 * Copyright 2009 Mobilegov - All rights reserved
 *
 * @Author   Guillaume TARTAYRE for Mobilegov - guillaume.tartayre@mobilegov.com
 * @Date     2009/12/16
 * @Version  1.0
 *
 * @Description
 * 
 * UCK JavaScript Interface is written to provide a web interface to the UCK.
 * Please refer to the UCK Javascript API Reference Guide for more details
 * 
 * @License
 *
 * This software is the property of Mobilegov. Please inform us whenever you
 * have to redistribute or modify this file.
 * 
 */

//********************************************************//
//********************* Uck Log Codes ********************//
//********************************************************//

var UckLogs = new Array();

UckLogs["02000002"] = "Mobilegov UCK Applet Started";
UckLogs["02000003"] = "Mobilegov UCK Applet Stopped";
UckLogs["02000004"] = "UCK Applet not yet initialized, cannot invoke JavaScript";
UckLogs["03000005"] = "UCK Applet cannot invoke JavaScript";
UckLogs["0200000a"] = "Low level library has been installed in";
UckLogs["0300000b"] = "Failed to copy file from server";
UckLogs["0500000c"] = "Failed to load the low level library";
UckLogs["0500000d"] = "An error occurred during arguments parsing";
UckLogs["03000013"] = "The low level library has already been loaded";
UckLogs["04000016"] = "There is no connected device that the policy matches";
UckLogs["04000022"] = "Command execution failed";
UckLogs["05000023"] = "Get library failed";
UckLogs["05000024"] = "Cannot instantiate reader";
UckLogs["03000025"] = "Library path error";
UckLogs["0500002e"] = "Environment non compliant ";
UckLogs["0500002f"] = "Mobilegov UCK was not able to start";
UckLogs["04010001"] = "Uck unknown exception ";
UckLogs["04010002"] = "Idbox unreachable ";
UckLogs["04010003"] = "Bad Password ";
UckLogs["04010004"] = "Password locked ";
UckLogs["04010005"] = "Bad Digital DNA ";
UckLogs["04010006"] = "Bad session ";
UckLogs["04010007"] = "Empty device selection ";
UckLogs["04010008"] = "Bad parameter ";
UckLogs["04010009"] = "No valid device connected ";
UckLogs["0401000a"] = "Idbox service error : ";
UckLogs["0401000b"] = "No registered DNA ";
UckLogs["0401000c"] = "DNA access error ";
UckLogs["0401000d"] = "Authentication error ";
UckLogs["0401000e"] = "Invalid Handle";
UckLogs["0401000f"] = "Account limit reached ";
UckLogs["04010010"] = "Deactivated user ";
UckLogs["04010011"] = "DNA expired ";
UckLogs["04010012"] = "User expired ";
UckLogs["04010013"] = "Invalid or unknown account ";
UckLogs["04010014"] = "User has been revoked ";
UckLogs["04010015"] = "One of the fields contains a too large value ";
UckLogs["04010016"] = "Unkown user ";
UckLogs["04010017"] = "This user already exists ";

/*
UckLogs["02000002"] = "Mobilegov UCK Applet d�marrage";
UckLogs["02000003"] = "Mobilegov UCK Applet arr�t";
UckLogs["02000004"] = "UCK Applet pas encore initialis�, impossible d'invoquer JavaScript";
UckLogs["03000005"] = "UCK Applet ne peut invoquer JavaScript";
UckLogs["0200000a"] = "Biblioth�que bas niveau install�e";
UckLogs["0300000b"] = "Impossible de copier un fichier depuis le serveur";
UckLogs["0500000c"] = "Impossilble de charger la biblioth�que de bas niveau";
UckLogs["0500000d"] = "Erreur durant le parsing des arguments";
UckLogs["03000013"] = "Biblioth�que bas niveau d�j� charg�e";
UckLogs["04000016"] = "Aucun p�riph�rique connect� qui correspond � la politique d'identification";
UckLogs["04000022"] = "L'�xecution de commande a �chou�";
UckLogs["05000023"] = "La r�cup�ration de la biblioth�que a �chou�";
UckLogs["05000024"] = "Impossible d'instancier le reader";
UckLogs["03000025"] = "Erreur du chemin des biblioth�ques";
UckLogs["0500002E"] = "Environnement non compatible ";
UckLogs["0500002F"] = "Mobilegov UCK n'a pas pu d�marrer";
UckLogs["04010001"] = "Exception UCK inconnue ";
UckLogs["04010002"] = "Idbox inaccessible ";
UckLogs["04010003"] = "Mot de passe invalide ";
UckLogs["04010004"] = "Mot de passe bloqu� ";
UckLogs["04010005"] = "ADN invalide ";
UckLogs["04010006"] = "Session invalide ";
UckLogs["04010007"] = "S�lection des p�riph�riques invalide ";
UckLogs["04010008"] = "Mauvais param�tre ";
UckLogs["04010009"] = "Aucun p�riph�rique valide n'est connect� ";
UckLogs["0401000a"] = "Erreur du service Idbox : ";
UckLogs["0401000b"] = "Aucun ADN enregistr� ";
UckLogs["0401000c"] = "Erreur d'acc�s � l'ADN ";
UckLogs["0401000d"] = "Erreur d'authentification ";
UckLogs["0401000e"] = "Pointeur invalide ";
UckLogs["0401000f"] = "Limite du compte atteinte ";
UckLogs["04010010"] = "Utilisateur desactiv� ";
UckLogs["04010011"] = "ADN Expir� ";
UckLogs["04010012"] = "Utilisateur expir� ";
UckLogs["04010013"] = "Compte invalide ou inconnu ";
UckLogs["04010014"] = "Utilisateur r�voqu�";
UckLogs["04010015"] = "Un des champs continent une valeur trop grande ";
UckLogs["04010016"] = "Utilisateur inconnu ";
UckLogs["04010017"] = "Cet utilisateur existe d�j� ";
*/

//********************************************************//
//************** Uck Static Members ***************//
//********************************************************//


var uck_device_list = new Array();
var uck_is_exception    = false;
var uck_idbox_url = "";
var uck_idbox_port = "";
var uck_idbox_ssl = false;
var uck_idbox_account = "";
var calling_uck = null;
var timer = null;


var uck_applet_is_started = false;
var uck_applet_load_timeout = 120; //seconds

function UckTreatLastError(){		
	var errorCode 		= new String(UckGetAppletElement().getLastError());	
	var errorDetails	= new String(UckGetAppletElement().getLastErrorDetails());
	
	// note : calling_uck.openApi retrieves the api currently opened	
	if ((null != errorCode) &&
		( errorCode.substr(0,4) == "0401")) //codes starting with 0401 are uck exceptions
		uck_is_exception = true;
	
    UckLogCallback(errorCode, errorDetails);
}
function UckSetReady(){

	uck_applet_is_started = true;
		
	if ( null != timer ){		
		clearTimeout(timer);
		timer =null;
	}
	
	if((uck_idbox_url != "") && (null != calling_uck)){	
		alert("UckSetReady - set config");
		var uckApi = calling_uck.openApi();
		
		var settings = new ConfigSettings();
		settings.setIdboxAddress(uck_idbox_url);
		settings.setIdboxPort(uck_idbox_port);
		settings.setUseSsl(uck_idbox_ssl);
		settings.setAccountId(uck_idbox_account);
		if (false == uckApi.setConfigSettings(settings)){
			alert('Error while opening UCK');
			calling_uck.closeApi();
			return;
		}
		calling_uck.closeApi();
	}
					
    UckReadyCallback();
}

function UckSetStartupFailed(){
	if ( null != timer ){		
		clearTimeout(timer);
		timer =null;
	}
	UckTreatLastError();
}

function UckCheckIsStarted()
{
    if(uck_applet_is_started == false){
		UckLogCallback("0500002f", "Not loaded yet after " + uck_applet_load_timeout + " seconds");		
	}
}
function UckGetAppletElement(){
	var applet = document.applets["Mobilegov_IDBox_UCK"];
	if(!applet){
		alert( "UckApplet cannot be find in the page. Check that it has been effectively loaded");
		return null;
	}
	return applet;
}
function Include(fileName){
	document.write("<script type='text/javascript' src='"+fileName+"'></script>" );
}
function Reviver(key, value) {
	return value;
}

//********************************************************//
//**************** Uck JavaScript Object *****************//
//********************************************************//

function Uck(){

	this.base_dir = "uck-js-api";

    this.logo_stopped_path = "";
    this.logo_stopped_width = 0;
    this.logo_stopped_height = 0;
	
	this.applet_width = 1;
	this.applet_height = 1;
	
	this.error = "";
	
	this.jar_name;
	this.jar_folder;
	this.jar_class = "com.mobilegov.idbox.uck.applet.UckApplet.class";
	
	this.parameter;	
	
	//public
	this.init = UckAppletInit;
    this.start = UckAppletStart;
	this.openApi = UckAppletOpenApi;
	this.closeApi = UckAppletCloseApi;
	this.isException = UckAppletIsException;
    this.reset = UckAppletReset;
	this.restart = UckAppletRestart;
    this.checkDevice = UckAppletSelectDevice;
    this.getDeviceSelection  = UckAppletGetDeviceSelection;
        
    //private
	this.xmlReq = 0;	
    this.parseJarPath = UckAppletParseJarPath;
	this.loadXmlConf = UckAppletLoadXmlConf;
	this.parseXmlConf = UckAppletParseXmlConf;
	
	Include("uck-js-api/json2.js");
}
function UckAppletOpenApi(){
	var result = null
	try{
		var applet = UckGetAppletElement();
		if(!applet){
			//this.error = "UckApplet cannot be find in the page. Check that it has been effectively loaded";
			return result;
		}
		var myJavaUckApi = applet.openApi();;
		if ( null != myJavaUckApi){			
			result = new UckApi(myJavaUckApi);					
		}
		else{			
			UckTreatLastError();
		}
			
	}
	catch(e){
		UckTreatLastError();
	}
		
	return result;
}
function UckAppletCloseApi(){
	var result = false;
	
	try{
		var applet = UckGetAppletElement();
		if(!applet)
		{
			//this.error = "UckApplet cannot be find in the page. Check that it has been effectively loaded";
			return false;
		}
		
		applet.closeApi();
		result = true;				
		this.currentOpenedAPI = null;
	}
	catch(e){
		alert("UckAppletCloseApi - failed :" + e);
	}
	
	return result;
}
function UckAppletIsException(){
    var result = uck_is_exception;
	uck_is_exception = false;
    return result;
}
function UckAppletInit(basedir){
	var result = true;
    this.base_dir = basedir;
	
	//parse XML configuration file
	if(!this.loadXmlConf(basedir+"/uck-js-api.xml"))
	    //error message is set in parseXmlConf()
		result = false;
	
	return result;
}
function UckAppletRestart(){
	if(!this.parameter)
	{
	    alert("UckApplet needs to be started with a parameter before being restarted");
		return false;
	}
	if(!this.reset())
	    return false;
	
	return this.start();
}
function UckAppletStart(){
    //exit if the elements to fill cannot be found in the page
    var appletbox = document.getElementById('UckAppletBox');
	if(!appletbox){
	    alert('Cannot find element named "UckAppletBox"');
    	return false;
	}
        	
    //parse jar path
    if(!this.parseJarPath())
    {
        alert('Cannot parse applet jar path : ' + this.jar_path);
        return false;
    }	

	//program Applet load verification	
	timer = setTimeout('UckCheckIsStarted()', uck_applet_load_timeout*1000);
    //replace applet logo by the applet itself
	if(window.opera){
	    var applet = '<applet name="Mobilegov IDBox UCK" code="' + this.jar_class + '" codebase="' + this.jar_folder + '" archive="' + this.jar_name + '"';
        applet += ' width="' + this.applet_width + '" height="'+ this.applet_height + '" mayscript="true" id="Mobilegov_IDBox_UCK">';
		applet += '</applet>';
		appletbox.innerHTML = applet;	
	}
	else{
	    //clean applet box content
        if(appletbox.hasChildNodes()) {
            while(appletbox.childNodes.length >= 1 )
                appletbox.removeChild(appletbox.firstChild);
        }
        
		//create applet
		var applet = document.createElement('applet');
		applet.setAttribute('code', this.jar_class);
		applet.setAttribute('codebase', this.jar_folder);
		applet.setAttribute('archive', this.jar_name);
		applet.setAttribute('width', this.applet_width);
		applet.setAttribute('height', this.applet_height);
		applet.setAttribute('mayscript','true');
		applet.setAttribute('name', 'Mobilegov IDBox UCK');
		applet.setAttribute('id', 'Mobilegov_IDBox_UCK');

		//insert applet in the doc
		appletbox.appendChild(applet);		
	}  
	
	calling_uck = this;
   	return true;
}
function UckAppletReset(){
	uck_applet_is_started = false;
    //exit if the elements to fill cannot be found in the page
    var appletbox = document.getElementById('UckAppletBox');
	if(!appletbox)
	{
	    alert('Cannot find element named "UckAppletBox"');
    	return false;
	}

    appletbox.style.display = 'none';

    //replace the applet by its logo if provided
	if(window.opera){
		if(this.logo_stopped_path)
			appletbox.innerHTML = '<img src="' + this.logo_stopped_path + '" width="' + this.logo_stopped_width + '" height="' + this.logo_stopped_height + '" id="UckAppletLogo" />';
		else  
			appletbox.innerHTML = '';
	}
	else{
	    //clean applet box content
        if(appletbox.hasChildNodes()) {
            while(appletbox.childNodes.length >= 1 )
                appletbox.removeChild(appletbox.firstChild);
        }

		if(this.logo_stopped_path)
		{
			//create image
	        var img = document.createElement('img');
	        img.setAttribute('src', this.logo_stopped_path);
	        img.setAttribute('width', this.logo_stopped_width);
	        img.setAttribute('height', this.logo_stopped_height);
	        img.setAttribute('id', 'UckAppletLogo');
	        img.setAttribute('alt', 'Mobilegov');
					
			//insert image in the doc
			appletbox.appendChild(img);
        }
	}
	
    appletbox.style.display = 'block' ;
	
	return true;
}
//manage device list containing selected devices, 
//using a static array to get it from a static function
function UckAppletSelectDevice(device_id){
    for(var i=0; i < saws_device_list.length; ++i){
       if(saws_device_list[i].id == device_id){
           saws_device_list[i].selected = !saws_device_list[i].selected;
           return;
       }
    }
}
function UckAppletGetDeviceSelection(){
    //do not validate selection if no device selected
    if(saws_device_list.length == 0)
        return "";
    
    //build formatted string with only hashes inside
    var result = "";
    for(var i=0; i < saws_device_list.length; ++i)
        if(saws_device_list[i].selected)
            result += ";;" + saws_device_list[i].id;
    
    //remove beginning ;;
    var res = new String(result);
    if(res.substr(0,2) == ";;")
       return res.substr(2, res.length);

    return "";
}
function UckAppletParseJarPath(){
    if(this.jar_path.match(/[\/|\\]/))
    {
        this.jar_folder = this.jar_path.match(/((.|\.)*[\/|\\])*([^\\\/]+)$/)[1];
        this.jar_folder = this.jar_folder.slice(0, this.jar_folder.length - 1);
        this.jar_name = this.jar_path.match(/[\/|\\]([^\\\/]+)$/)[1];
    }
    else
    {
        this.jar_folder = ".";
        this.jar_name = this.jar_path;
    }
    return true;
}
function UckAppletLoadXmlConf(url){
	// branch for IE/Windows ActiveX version
	if (window.ActiveXObject) {
        this.xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
        if (this.xmlReq) {
            this.xmlReq.open("GET", url, false);
            this.xmlReq.send();
        }
	}
	// branch for native XMLHttpRequest object
	else if (window.XMLHttpRequest) {
        this.xmlReq = new XMLHttpRequest();
        this.xmlReq.open("GET", url, false);
        this.xmlReq.send(null);
    }
	else {
	    alert("Browser not compatible with XML Http Request");
		return false;
	}

	return this.parseXmlConf();
}
// handle onreadystatechange event of req object
function UckAppletParseXmlConf(){
    if (this.xmlReq.readyState != 4)
		return false;	
					
	if(this.xmlReq.status != 200) {
		alert("There was a problem retrieving the XML data: " + this.xmlReq.statusText + "[" + this.xmlReq.status + "]");
		return false;
    }

	var xmlDoc = this.xmlReq.responseXML;

	//check uck root element
	uckElt = xmlDoc.getElementsByTagName("uck");
	if(uckElt.length < 1)
	{
	    alert("Cannot find XML element uck");
	    return false;
	}
	uckElt = uckElt[0];
	
	//get jar element
	elt = uckElt.getElementsByTagName("jar");
	if(elt.length < 1)
	{
	    alert("Cannot find XML element jar");
	    return false;
	}
	this.jar_path = elt[0].childNodes[0].nodeValue;
	
	
	//get logo_stopped element	
	logoStoppedElt = uckElt.getElementsByTagName("logo_stopped");
	if(logoStoppedElt.length >= 1)
	{
		logoStoppedElt = logoStoppedElt[0];
	
		//get logo_stopped path element
		elt = logoStoppedElt.getElementsByTagName("path");
		if(elt.length >= 1)
		    this.logo_stopped_path = elt[0].childNodes[0].nodeValue;	
		
		//get logo_stopped width element
		elt = logoStoppedElt.getElementsByTagName("width");
		if(elt.length >= 1)
			this.logo_stopped_width = elt[0].childNodes[0].nodeValue;		

		//get logo_stopped height element
		elt = logoStoppedElt.getElementsByTagName("height");
		if(elt.length >= 1)
			this.logo_stopped_height = elt[0].childNodes[0].nodeValue;		
	}
	
	
	//get logo_running element	
	logoRunningElt = uckElt.getElementsByTagName("logo_running");
	if(logoRunningElt.length >= 1)
	{
		logoRunningElt = logoRunningElt[0];
	
		//get logo_stopped width element
		elt = logoRunningElt.getElementsByTagName("width");
		if(elt.length >= 1)
			this.applet_width = elt[0].childNodes[0].nodeValue;		

		//get logo_stopped height element
		elt = logoRunningElt.getElementsByTagName("height");
		if(elt.length >= 1)
			this.applet_height = elt[0].childNodes[0].nodeValue;	
	}	
	
	//get idbox element	
	idboxElt = uckElt.getElementsByTagName("idbox");
	if(idboxElt.length >= 1)
	{
		idboxElt = idboxElt[0];
	
		//get idbox url element
		urlElt = idboxElt.getElementsByTagName("url");
		if(urlElt[0].childNodes.length == 0 || urlElt[0].childNodes[0].nodeValue == null)
		{
			var str = window.location+"";
			
			// HTTPS is forced
			uck_idbox_url = window.location.hostname;
			uck_idbox_port = "443";
			uck_idbox_ssl = true;
/*			
			if (str.search(/https/i) == 0 )
			{
				uck_idbox_url = window.location.hostname;
				uck_idbox_ssl = true;
				// ip v6 incompatible
				var portIndex = str.search(':') ;
				if( portIndex != -1 ){
					var portEnd = str.indexOf('/', portIndex)
					if (portEnd != -1)
						uck_idbox_port = str.substr(portIndex+1, portEnd-portIndex-1);
					else
						uck_idbox_port = str.substr(portIndex+1);
				}else
					uck_idbox_port = "443";
					
			}else
			{
				uck_idbox_url = window.location.hostname;
				uck_idbox_ssl = false;
				// ip v6 incompatible
				var portIndex = str.indexOf(':', 7) ; //skip http:// or https://
				if( portIndex != -1 ){
					var portEnd = str.indexOf("/", portIndex)
					if (portEnd != -1)
						uck_idbox_port = str.substr(portIndex+1, portEnd-portIndex-1);
					else
						uck_idbox_port = str.substr(portIndex+1);
				}else
					uck_idbox_port = "80";
			}
*/
		}
		//get idbox accountId element
		var accountElt = idboxElt.getElementsByTagName("account");
		if ((null != accountElt) && (accountElt.length >= 1))
			uck_idbox_account = accountElt[0].childNodes[0].nodeValue;	
			
		//get idbox timeout element
		var timeoutElt = idboxElt.getElementsByTagName("timeout");
		if ((null!=timeoutElt) && (timeoutElt.length >= 1))
			uck_applet_load_timeout = timeoutElt[0].childNodes[0].nodeValue;	
	}	
	
	return true;
}
//********************************************************//
//************** ********UckApi JavaScript Object *************//
//********************************************************//
function UckApi(javaJS){	
	this.getUCKVersion				= UckApiGetUCKVersion;
	this.listConnectedDevices  		= UckApiListConnectedDevices;
	this.sessionOpen				= UckApiSessionOpen;
	this.sessionUnlock				= UckApiSessionUnlock;
	this.passwordUnlock				= UckApiPasswordUnlock
	this.passwordReinit				= UckApiPasswordReinit;
	this.registerUser				= UckApiRegisterUser;
	this.setConfigSettings			= UckApiSetConfigSettings;
	this.getConfigSettings			= UckApiGetConfigSettings;
	this.existDnaUser				= UckApiExistDnaUser;
	
	this.javaJS						= javaJS;
}

function UckApiGetUCKVersion() {
	var result = null;
			
	try{
		result  =  new String(this.javaJS.getUCKVersion());				
		if ( null == result)		
			UckTreatLastError();
	}
	catch(e){
		alert("UckApiGetVersion failed : " + e);
		uck_is_exception = true;
	}	
	return result;
}
function UckApiListConnectedDevices() {
	
	uck_is_exception = false;
	var result = null;
			
	try{
		var jsonRsp =  this.javaJS.listConnectedDevices();				
		if ( null != jsonRsp){
			var devStruct = JSON.parse(jsonRsp, Reviver);
			var devices = new Array();
			for(var i=0; i < devStruct.length ; i++){			
				var dev = new Device(devStruct[i].deviceClass,
													devStruct[i].instanceId,
													devStruct[i].description,
													devStruct[i].unicity);
				devices.push(dev);
			}					
			result = devices;		
		}
		else
			UckTreatLastError();
	}
	catch(e){
		alert("UckApiListConnectedDevices failed : " + e);
		uck_is_exception = true;
	}
	
	return result;
}
function UckApiSessionOpen(login, password, confirmcode){
	uck_is_exception = false;
	var result = null;
	try{
		var javaSession = null;
		if ( null == confirmcode)			
			javaSession = this.javaJS.sessionOpen(login, password);
		else
			javaSession = this.javaJS.sessionOpen(login, password, confirmcode);		
		
		if ( null != javaSession)
			result =  new Session(javaSession);
		else			
			UckTreatLastError();		
	}
	catch(e){
		alert("UckApiSessionOpen failed : " + e.toString());
		uck_is_exception = true;
	}
	
	return result;
}
function UckApiSessionUnlock(login, password, mailTemplate){
	uck_is_exception = false;
	var result = false;
	
	try{
		if ( null == mailTemplate){
			result = this.javaJS.sessionUnlock(login, password);
		}
		else{		
			result = this.javaJS.sessionUnlock(login, password, mailTemplate);
		}
		
		if (false == result)
			UckTreatLastError();		
	}
	catch(e){
		alert("UckApiSessionUnlock failed : " + e);
		uck_is_exception = true;
	}
	
	return result;
}
function UckApiPasswordUnlock(login, mailTemplate){
	uck_is_exception = false;
	var result = false;
	
	try{
		result = this.javaJS.passwordUnlock(login, mailTemplate);	
		if (false == result)
			UckTreatLastError();			
	}
	catch(e){
		alert("UckApiPasswordUnlock failed : " + e);
		uck_is_exception = true;
	}
	
	return result;
}
function UckApiPasswordReinit(login, password, confirmcode){
	uck_is_exception = false;
	var result = false;

	try{
		result = this.javaJS.passwordReinit(login, password, confirmcode);
		if (false == result)
			UckTreatLastError();
	}
	catch(e){
		alert("UckApiPasswordReinit failed : " + e);		
		uck_is_exception = true;
	}
	
	return result;
}
function UckApiRegisterUser(login, userSettings, dna){
	uck_is_exception = false;
	var result = null;

	try{
		var userSettingsJSON = JSON.stringify(userSettings, null, '\t');
		var jsonRsp = null;
		if (null == dna){
			 jsonRsp 		=  this.javaJS.registerUser(login, userSettingsJSON);
		}
		else{
			var dnaJSON 	= JSON.stringify(dna, null, '\t');
			jsonRsp 		=  this.javaJS.registerUser(login, userSettingsJSON, dnaJSON);
		}
		
		if (null != jsonRsp){
			var userPassportStruct = JSON.parse(jsonRsp, Reviver);
			result = new UserPassport(userPassportStruct.uuid,userPassportStruct.strongKey);
		}
		else
			UckTreatLastError();
	}
	catch(e){
		alert("UckApiRegisterUser failed : " + e);
		uck_is_exception = true;
	}
		
	return result;
}
function UckApiSetConfigSettings(configSettings){
	uck_is_exception = false;
	var result = false;
	try{
		var myJSONText = JSON.stringify(configSettings, null, '\t');			
		result = this.javaJS.setConfigSettings(myJSONText);			
		if (false == result)
			UckTreatLastError();
	}
	catch(e){
		alert("UckApiSetConfigSettings - Error while opening UCK : exception " + e);	
		uck_is_exception = true;
	}

	return result;			
}
function UckApiGetConfigSettings(){
	uck_is_exception = false;
	var result = null;
	try{			
		var jsonRsp = this.javaJS.getConfigSettings();
		if ( null != jsonRsp){			
			var configSettingsStruct 	= JSON.parse(jsonRsp, Reviver);
			result = ConfigSettingsFactory(	configSettingsStruct.idboxAddress, 
											configSettingsStruct.idboxAddress, 
											configSettingsStruct.useSsl, 
											configSettingsStruct.accountId);
		}
		else
			UckTreatLastError();
	}
	catch(e){
		alert("UckApiGetConfigSettings failed " + e);	
		uck_is_exception = true;
	}

	return result;			
}

function UckApiExistDnaUser(login){
	uck_is_exception = false;
	var result = false;
	try{		
		var exist = this.javaJS.existDnaUser(login);
		if (null == exist)		
			UckTreatLastError();
		else{			
			if ( "true" == exist)
				result = true;			
		}			
	}
	catch(e){
		alert("UckApiExistDnaUser failed : " + e);		
		uck_is_exception = true;
	}
		
	return result;
}


//********************************************************//
//************** Dna JavaScript Object *************//
//********************************************************//
function Dna(){		
	this.getDescription	= DnaGetDescription;
	this.setDescription	= DnaSetDescription;
	this.getType		= DnaGetType;
	this.setType		= DnaSetType;	
	this.getDevices		= DnaGetDevices;
	this.setDevices		= DnaSetDevices;	
	this.getUid			= DnaGetUid;
	this.setUid			= DnaSetUid;
	
	this.description	= "";
	this.type			= 0;
	this.devices		= null;
	this.uid			= "";	
}
function DnaFactory(description, type, devices, uid){	
	var dna = new Dna();
	dna.setDescription(description);
	dna.setType(type);
	dna.setDevices(devices);
	dna.setUid(uid);
	return dna;
}
function DnaGetDescription(){
	return this.description;
}
function DnaSetDescription(description){
	this.description = description;
}
function DnaGetType(){
	return this.type;
}
function DnaSetType(type){
	this.type = type;
}
function DnaGetDevices(){
	return this.devices;
}
function DnaSetDevices(devices){
	if ( null == this.devices )
		this.devices = new Array();
		
	this.devices = devices;
}
function DnaGetUid(){
	return this.uid;
}
function DnaSetUid(uid){
	this.uid = uid;
}

//********************************************************//
//************** UserSettings JavaScript Object *************//
//********************************************************//
function UserSettings(){
	this.getEmail 			= UserSettingsGetEmail;
	this.setEmail 			= UserSettingsSetEmail;
	this.setPassword 		= UserSettingsSetPassword;
	
	this.email				= "";
	this.password			= "";
}
function UserSettingsFactory(email, password){	
	var userSettings = new UserSettings();
	userSettings.setEmail(email);
	userSettings.setPassword(password);
	return userSettings;
}
function UserSettingsGetEmail(email){
	return this.email;
}
function UserSettingsSetEmail(email){
	this.email = email;
}
function UserSettingsSetPassword(password){
	this.password = password;
}

//********************************************************//
//************** ConfigSettings JavaScript Object *************//
//********************************************************//
function ConfigSettings(){
	this.getAccountId		= ConfigSettingsGetAccountId
	this.setAccountId		= ConfigSettingsSetAccountId;
	this.getIdboxAddress	= ConfigSettingsGetIdboxAddress;
	this.setIdboxAddress	= ConfigSettingsSetIdboxAddress;
	this.getIdboxPort		= ConfigSettingsGetIdboxAddress;
	this.setIdboxPort		= ConfigSettingsSetIdboxPort;
	this.getUseSsl			= ConfigSettingsGetUseSsl;
	this.setUseSsl			= ConfigSettingsSetUseSsl;
	this.getCacertFile		= ConfigSettingsGetCacertFile;
	this.setCacertFile		= ConfigSettingsSetCacertFile;
	this.getProxyAddress	= ConfigSettingsGetProxyAddress;
	this.setProxyAddress	= ConfigSettingsSetProxyAddress;
	this.getProxyPort		= ConfigSettingsGetProxyPort;
	this.setProxyPort		= ConfigSettingsSetProxyPort;	
	

	this.accountId			= "";
	this.idboxAddress		= "";
	this.idboxPort			= "";
	this.useSsl				= false;
	this.cacertFile			= "";
	this.proxyAddress		= "";
	this.proxyPort			= "";
	
}
function ConfigSettingsFactory(idboxAddress, idboxPort, useSsl, accountId){	
	var configSettings = new ConfigSettings();
	configSettings.setIdboxAddress(idboxAddress);
	configSettings.setIdboxPort(idboxPort);
	configSettings.setUseSsl(useSsl);
	configSettings.setAccountId(accountId);
	return configSettings;
}
function ConfigSettingsGetAccountId(){
	return this.accountId 	= accountId;
}
function ConfigSettingsSetAccountId(accountId){
	this.accountId 	= accountId;
	return true;
}
function ConfigSettingsGetIdboxAddress(){
	return this.idboxAddress;
}
function ConfigSettingsSetIdboxAddress(address){
	this.idboxAddress	=	address;
	return true;
}
function ConfigSettingsGetIdboxPort(){
	return this.idboxPort;
}
function ConfigSettingsSetIdboxPort(port){
	this.idboxPort		=	port;
	return true;
}
function ConfigSettingsGetUseSsl(){
	return this.useSsl;
}
function ConfigSettingsSetUseSsl(sslOn){
	this.useSsl 		= 	sslOn;
	return true;
}
function ConfigSettingsGetCacertFile(){
	return this.cacertFile;
}
function ConfigSettingsSetCacertFile(cacertFile){
	this.cacertFile = cacertFile;
}
function ConfigSettingsGetProxyAddress(){
	return this.proxyAddress;
}
function ConfigSettingsSetProxyAddress(proxyAddress){
	this.proxyAddress = proxyAddress;
}
function ConfigSettingsGetProxyPort(){
	return this.proxyPort;
}
function ConfigSettingsSetProxyPort(proxyPort){
	this.proxyPort = proxyPort;
}


//********************************************************//
//******************** Device JavaScript Object *************//
//********************************************************//
function Device(deviceClass,instanceId,description,unicity){	
	this.getDeviceClass	= DeviceGetDeviceClass;
	this.getInstanceId	= DeviceGetInstanceId;
	this.getDescription	= DeviceGetDescription;
	this.getUnicity		= DeviceGetUnicity;
	
	this.deviceClass 	= deviceClass;
	this.instanceId 	= instanceId;
	this.description	= description;
	this.unicity		= unicity;	
}
function DeviceGetDeviceClass(){
	return this.deviceClass;
}
function DeviceGetInstanceId(){
	return this.instanceId;
}
function DeviceGetDescription(){
	return this.description;
}
function DeviceGetUnicity(){
	return this.unicity;
}

//********************************************************//
//*************** UserPassport JavaScript Object *************//
//********************************************************//
function UserPassport(uuid,strongKey){	
	this.getUuid		= UserPassportGetUuid;
	this.getStrongKey	= UserPassportGetStrongKey;

	this.uuid 			= uuid;
	this.strongKey 		= strongKey;

}
function UserPassportGetUuid(){
	return this.uuid;
}
function UserPassportGetStrongKey(){
	return this.strongKey;
}

//********************************************************//
//********************** Otp JavaScript Object *************//
//********************************************************//
function Otp(password){	
	this.getPassword		= OtpGetPassword;

	this.password 			= password;
}
function OtpGetPassword(){
	return this.password;
}

//********************************************************//
//********************** Session JavaScript Object *************//
//********************************************************//
function Session(session){	
	this.getType				= SessionGetType;
	this.getDna					= SessionGetDna;
	this.sessionClose			= SessionClose;
	this.getUserPassport 		= SessionGetUserPassport;
	this.getOtp					= SessionGetOtp;
	this.setUserSettings		= SessionSetUserSettings;
	this.getUserSettings		= SessionGetUserSettings;	
	this.revokeUser				= SessionRevokeUser;
	this.registerDna			= SessionRegisterDna;
	this.listDna				= SessionListDnas;
	this.revokeDna				= SessionRevokeDna;
	
	this.javaSession 			= session;
}
function SessionGetType(){
	uck_is_exception = false;
	var result = null;		
	try{			
		result = this.javaSession.getType();
		if (null == result )
			UckTreatLastError();		
	}
	catch(e){
		alert("SessionGetType failed : " + e);
		uck_is_exception = true;
	}
	return result;
}
function SessionGetDna(){
	uck_is_exception = false;
	var result = null;		
	try{			
		var jsonRsp = this.javaSession.getDna();
		if ( null != jsonRsp){			
			var dnaStruct 	= JSON.parse(jsonRsp, Reviver);
			
			//-- retrieve deviceList
			var devices = new Array();
			for(var j=0; j < dnaStruct.devices.length ; j++){			
				var dev = new Device(	dnaStruct.devices[j].deviceClass,
										dnaStruct.devices[j].instanceId,
										dnaStruct.devices[j].description,
										dnaStruct.devices[j].unicity);
				devices.push(dev);
			}
			
			//-- create dna
			result = DnaFactory(	dnaStruct.description,
									dnaStruct.type,
									devices,
									dnaStruct.uid);			
		}
		else
			UckTreatLastError();
	}
	catch(e){
		alert("SessionGetDna failed : " + e);
		uck_is_exception = true;
	}
	return result;
}
function SessionClose(){
	uck_is_exception = false;
	var result = false;
	try{
		result = this.javaSession.sessionClose();
		if ( false == result)
			UckTreatLastError();
	}
	catch(e){
		alert("SessionClose failed : " + e);
		uck_is_exception = true;
	}
	return result;
}
function SessionGetUserPassport() {
	uck_is_exception = false;
	var result = null;		
	try{			
		var jsonRsp = this.javaSession.getUserPassport();
		if ( null != jsonRsp){			
			var userPassportStruct 	= JSON.parse(jsonRsp, Reviver);
			result = new UserPassport(userPassportStruct.uuid,userPassportStruct.strongKey);
		}
		else
			UckTreatLastError();
	}
	catch(e){
		alert("SessionGetUserPassport failed : " + e);
		uck_is_exception = true;
	}
	
	return result;
}
function SessionGetOtp(){
	uck_is_exception = false;
	var result = null;
	
	try{		
		var jsonRsp =  this.javaSession.getOtp();
		if ( null != jsonRsp){
			var otpStruct 	= JSON.parse(jsonRsp, Reviver);
			result 			= new Otp(otpStruct.password);
		}
		else
			UckTreatLastError();
	}
	catch(e){
		alert("SessionGetOtp failed : " + e);
		uck_is_exception = true;
	}
	
	return result;
}
function SessionSetUserSettings(userSettings){
	uck_is_exception = false;
	var result = false;		
	try{
		var dnaJSON = JSON.stringify(userSettings, null, '\t');
		result = this.javaSession.setUserSettings(dnaJSON);
		if ( false == result)
			UckTreatLastError();
	}
	catch(e){
		alert("SessionSetUserSettings failed : " + e);
		uck_is_exception = true;
	}	
	return result;
}
function SessionGetUserSettings(){
	uck_is_exception = false;
	var result = null;
	
	try{		
		var jsonRsp =  this.javaSession.getUserSettings();
		if ( null != jsonRsp){
			var userSettingsStruct 	= JSON.parse(jsonRsp, Reviver);
			result 	= UserSettingsFactory(	userSettingsStruct.email, 
											userSettingsStruct.password);
		}
		else
			UckTreatLastError();
	}
	catch(e){
		alert("SessionGetUserSettings failed : " + e);
		uck_is_exception = true;
	}	
	return result;
}
function SessionRevokeUser(){
	uck_is_exception = false;
	var result = false;
	try{
		result = this.javaSession.revokeUser();
		if (false == result)
			UckTreatLastError();
	}
	catch(e){
		alert("SessionRevokeUser failed : " + e);
		uck_is_exception = true;
	}	
	return result;
}
function SessionRegisterDna(dna){
	uck_is_exception = false;
	var result = false;
		
	try{
		var dnaJSON = JSON.stringify(dna, null, '\t');
		result = this.javaSession.registerDna(dnaJSON);
		if (false == result)
			UckTreatLastError();
	}
	catch(e){
		alert("SessionRegisterDna failed : " + e);
		uck_is_exception = true;
	}	
	return result;
}
function SessionListDnas() {
	uck_is_exception = false;
	var result = null;
	try{		
	
		var jsontext =  this.javaSession.listDna();
		if ( null != jsontext){
			var jsonStruct = JSON.parse(jsontext, Reviver);		
			
			var dnaList = new Array();
			for(var i=0; i < jsonStruct.length ; i++){		
				
				//-- retrieve deviceList
				var devices = new Array();
				for(var j=0; j < jsonStruct[i].devices.length ; j++){			
					var dev = new Device(	jsonStruct[i].devices[j].deviceClass,
											jsonStruct[i].devices[j].instanceId,
											jsonStruct[i].devices[j].description,
											jsonStruct[i].devices[j].unicity);
					devices.push(dev);
				}
				
				//-- create dna
				var dna = DnaFactory(	jsonStruct[i].description,
										jsonStruct[i].type,
										devices,
										jsonStruct[i].uid);
				//--- push into the list
				dnaList.push(dna);
			}
			result = dnaList;
		}
		else
			UckTreatLastError();
	}
	catch(e){
		alert("SessionListDnas failed : " + e);
		uck_is_exception = true;
	}
	
	return result;
}
function SessionRevokeDna(dna){
	uck_is_exception = false;
	var result = false;
		
	try{
		var dnaJSON = JSON.stringify(dna, null, '\t');
		result = this.javaSession.revokeDna(dnaJSON);
		if (false == result)
			UckTreatLastError();
	}
	catch(e){
		alert("SessionRegisterDna failed : " + e);
		uck_is_exception = true;
	}	
	return result;
}

