/*  
 * SAWS Applet JavaScript Interface
 * 
 * Copyright 2008 Mobilegov - All rights reserved
 *
 * @Author   Guillaume TARTAYRE for Mobilegov - guillaume.tartayre@mobilegov.com
 * @Date     2009/03/27
 * @Version  1.5
 *
 * @Description
 * 
 * SAWS Applet JavaScript Interface is written to ease the use of SAWS Applet
 * In this file are written the JavaScript functions used to wrap SAWS Applet
 * Please refer to the SAWS 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.
 * 
 */

//********************************************************//
//***************** SawsApplet Log Codes *****************//
//********************************************************//

var SawsAppletLogs = new Array();

SawsAppletLogs["02000002"] = "Mobilegov SAWS Applet Started";
SawsAppletLogs["02000003"] = "Mobilegov SAWS Applet Stopped";
SawsAppletLogs["02000004"] = "SAWS Applet not yet initialized, cannot invoke JavaScript";
SawsAppletLogs["03000005"] = "SAWS Applet cannot invoke JavaScript";
SawsAppletLogs["0200000a"] = "Low level library has been installed in";
SawsAppletLogs["0300000b"] = "Failed to copy file from server";
SawsAppletLogs["0500000c"] = "Failed to load the low level library";
SawsAppletLogs["0500000d"] = "An error occurred during arguments parsing";
SawsAppletLogs["0200000f"] = "Hardware identification successfully generated";
SawsAppletLogs["05000011"] = "Failed to start the native interface";
SawsAppletLogs["04000012"] = "Failed to stop the native interface";
SawsAppletLogs["03000013"] = "The low level library has already been loaded";
SawsAppletLogs["04000015"] = "Unknown message command";
SawsAppletLogs["04000016"] = "There is no connected device that the policy matches";
SawsAppletLogs["04000022"] = "Command execution failed";
SawsAppletLogs["05000023"] = "Get library failed";
SawsAppletLogs["05000024"] = "Cannot instantiate reader";
SawsAppletLogs["03000025"] = "Library path error";
SawsAppletLogs["02000029"] = "Authentication attempt stored";


//********************************************************//
//************* SawsApplet Start Parameters **************//
//********************************************************//

SawsAppletAuthentication 	= 'AUTH';
SawsAppletRegistration 		= 'REG';

//********************************************************//
//************* SawsDevice JavaScript Object *************//
//********************************************************//


function SawsDevice()
{
 	this.deviceclass = "";
    this.id = "";
    this.description = "";
    this.selected = false;
}

//********************************************************//
//************** SawsApplet Static Members ***************//
//********************************************************//


var saws_device_list = new Array();

function SawsSetResult(qki, device_selection)
{
    saws_device_map = new Array();
    saws_device_list = new Array();
   
    if(device_selection.indexOf("::") == -1)
    {
        SawsResultCallback(qki, "");
        return;
    }
    
    map = device_selection.split(";;");
    for(var i=0; i < map.length; ++i){
        var sawsDeviceArr = map[i].split("::");
        var device = new SawsDevice();
        device.deviceclass = sawsDeviceArr[0];
        device.id = sawsDeviceArr[1];
        device.description = sawsDeviceArr[2];
        saws_device_list.push(device);
    }
    SawsResultCallback(qki, saws_device_list);
}


//********************************************************//
//************* SawsApplet JavaScript Object *************//
//********************************************************//


function SawsApplet()
{
    this.jar_path = "Saws.jar";
	this.base_dir = "saws-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.saws.applet.SawsApplet.class";
	
	this.parameter;
	
	//public
	this.init = SawsAppletInit;
    this.start = SawsAppletStart;
    this.reset = SawsAppletReset;
	this.restart = SawsAppletRestart;
    this.checkDevice = SawsAppletSelectDevice;
    this.getDeviceSelection  = SawsAppletGetDeviceSelection;
        
    //private
	this.xmlReq = 0;
    this.parseJarPath = SawsAppletParseJarPath;
	this.loadXmlConf = SawsAppletLoadXmlConf;
	this.parseXmlConf = SawsAppletParseXmlConf;
}

function SawsAppletInit(basedir)
{
    this.base_dir = basedir;
	
	//parse XML configuration file
	if(!this.loadXmlConf(basedir+"/saws-js-api.xml"))
	{
	    //error message is set in parseXmlConf()
		return false;
	}
	
	return true;
}

function SawsAppletRestart()
{
	if(!this.parameter)
	{
	    this.error = "SawsApplet needs to be started with a parameter before being restarted";
		return false;
	}
	if(!this.reset())
	    return false;
	
	return this.start(this.parameter);
}

function SawsAppletStart(saws_param)
{
    //save parameter for restart function
    this.parameter = saws_param;
	
    //exit if the elements to fill cannot be found in the page
    var appletbox = document.getElementById('SawsAppletBox');
	if(!appletbox)
	{
	    this.error = 'Cannot find element named "SawsAppletBox"';
    	return false;
	}
        	
    //parse jar path
    if(!this.parseJarPath())
    {
        this.error = 'Cannot parse applet jar path : ' + this.jar_path;
        return false;
    }	

	//this.jar_folder = '/webdna/saws-js-api/applet';
	
    //replace applet logo by the applet itself
	if(window.opera){
	    var applet = '<applet name="SawsApplet" code="' + this.jar_class + '" codebase="' + this.jar_folder + '" archive="' + this.jar_name + '"';
        applet += ' width="' + this.applet_width + '" height="'+ this.applet_height + '" mayscript="true" id="sawsappletelement">';
		applet += '<param name="SAWS_PARAM" value="' + saws_param + '"/>';
		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', 'SawsApplet');
		applet.setAttribute('id', 'sawsappletelement');

		//add applet params
		var param1 = document.createElement('param');
		param1.setAttribute('name', 'SAWS_PARAM');
		param1.setAttribute('value', saws_param);
		applet.appendChild(param1);

		//insert applet in the doc
		appletbox.appendChild(applet);		
	}  
   	return true;
}

function SawsAppletReset()
{
    //exit if the elements to fill cannot be found in the page
    var appletbox = document.getElementById('SawsAppletBox');
	if(!appletbox)
	{
	    this.error = 'Cannot find element named "SawsAppletBox"';
    	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="SawsAppletLogo" />';
		else  
			appletbox.innderHTML = '';
	}
	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', 'SawsAppletLogo');
	        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 SawsAppletSelectDevice(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 SawsAppletGetDeviceSelection()
{
    //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 SawsAppletParseJarPath()
{
    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 SawsAppletLoadXmlConf(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 {
	    this.error = "Browser not compatible with XML Http Request";
		return false;
	}

	return this.parseXmlConf();
}

// handle onreadystatechange event of req object
function SawsAppletParseXmlConf() 
{
    if (this.xmlReq.readyState != 4)
		return false;	
					
	if(this.xmlReq.status != 200) {
		this.error = "There was a problem retrieving the XML data: " + this.xmlReq.statusText + "[" + this.xmlReq.status + "]";
		return false;
    }

	var xmlDoc = this.xmlReq.responseXML;

	//check sawsapplet root element
	sawsappletElt = xmlDoc.getElementsByTagName("sawsapplet");
	if(sawsappletElt.length < 1)
	{
	    this.error = "Cannot find XML element sawsapplet";
	    return false;
	}
	sawsappletElt = sawsappletElt[0];
	
	//get jar element
	elt = sawsappletElt.getElementsByTagName("jar");
	if(elt.length < 1)
	{
	    this.error = "Cannot find XML element jar";
	    return false;
	}
	this.jar_path = elt[0].childNodes[0].nodeValue;
	
	
	//get logo_stopped element	
	logoStoppedElt = sawsappletElt.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 = sawsappletElt.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;	
	}	
	
	return true;
}



