/* db_init.js
 * A collection of javascript functions that can be run in the foreground by the User Interface.
 * This module calls meisosis, akin and synthesis modules. 
 * It is not called by other modules. 
 */
function init_gears(){
    /**
     Initialise database for application's persistent storage.
     Requires with Gears plug-in.
     */
    // Called onload to initialize local server and store variables
    if (!window.google || !google.gears) 
        alert("NOTE:  You must install Gears first.");
}

function setFamSetting(param, value){
    /* Set the value of a single setting parameter in the profile database.
     */
    try {
			var mv = init_mv(); // create module variable structue and default values
			mv.dest.module 		= 'db';
			mv.dest.action 		= 'setFamSetting';
			mv.dest.ID 			= dbworker.ID
			mv.se.param 		= param;
			mv.se.value 		= value;

			trx_caller (wp, mv, null, null, mv.dest.ID);

       return true;
    } 
    catch (e) {
        alert("setFamSetting error: " + e);
    }
}

function getFamSetting(param){
/* Get an application paramete from the user settings profile database.
 * param is optional. If not specified, get all parameters.
 */
	var rsgfs ;
	var URIparamValue;
	var URIparams = new Array;
	var URIparamCount=0;


	var dbgfs 	= google.gears.factory.create('beta.database');
	var rsgfs;
	dbgfs.open(ProfileDb);

    try {

		if (param) { // if parameter is given, return the value of a single setting parameter from the profile database.
			rsgfs = dbgfs.execute(" select value, user_config from setting where parameter = (?)", [param]);
			if (rsgfs.isValidRow()) {
				rsgfs.close; 		
				dbgfs.close;
				return rsgfs.field(0);
			}
			else {
				dbgfs.close;
				return false;
			};
		}
		else { // otherwise, retrieve all params and sync the UI to these stored values. 
			try {
				rsgfs = dbgfs.execute("select parameter, value, user_config from setting");		
	        }
			catch (e)
			{// code is executed when rsgfs fails to execute. 
			 // The setting table does not yet exist because this is the first ever run.
				init_profile_db(dbgfs);			// create the tables
				init_profile_settings(dbgfs);	// populate settings table
				rsgfs = dbgfs.execute("select parameter, value, user_config from setting");		// now continue
			}
	        	while (rsgfs.isValidRow()) {
					document.getElementById( rsgfs.field(0)).value = rsgfs.field(1);
					
					// If specified a URI parameter, trumps the same parameter on the Db
					URIparamValue = gup(rsgfs.field(0)); // get URI parameter
					if (URIparamValue && rsgfs.field(2)===1) 
					{
						var validParameter = false;  // validate URI parameter values
						switch (rsgfs.field(0)) {
						 	case 'ConcMaxDepth':
								URIparamValue = Math.floor(+URIparamValue) ;
								if (0 <= URIparamValue && URIparamValue <=15) validParameter = true;			
						 	break;
						 	case 'ConcDefBreadth':
								URIparamValue = Math.floor(+URIparamValue) ;
								if (+document.getElementById('ConcMosBreadth').value <= URIparamValue &&
									+document.getElementById('ConcMaxBreadth').value >= URIparamValue ) 
									validParameter = true;
						 	break;
						 	case 'ConcDefBindPar':
								switch (URIparamValue) {
									case 'Y|X':
										document.getElementById('Select_ConcDefBindPar').options.selectedIndex = 0;
										validParameter = true; break;
									case 'X|Y':
										document.getElementById('Select_ConcDefBindPar').options.selectedIndex = 1;
										validParameter = true; break;
									case 'Y':
										document.getElementById('Select_ConcDefBindPar').options.selectedIndex = 2;
										validParameter = true; break;
									case 'X':
										document.getElementById('Select_ConcDefBindPar').options.selectedIndex = 3;
										validParameter = true; break;
								}
						 	break;
						 	case 'ConcMaxInBred':
								if (0 <= URIparamValue && URIparamValue <= 1) {
									validParameter = true;
									if (+documenConcMaxInBredById('ScopeMaxDist').value < URIparamValue) {
										document.getElementById('ScopeMaxDist').value = URIparamValue;
										document.getElementById(rsgfs.field(0)).value = URIparamValue; // do it early because param ScopeMaxDist may reference the value
									}
								}
						 	break;
						 	case 'ScopeMaxDist':
								if (URIparamValue <= 1 && URIparamValue >= document.getElementById('ConcMaxInBred').value) validParameter = true;			
						 	break;
						 	case 'ScopeMaxcTags':
								URIparamValue = Math.floor(+URIparamValue) ;
								if (0 <= URIparamValue && URIparamValue <=100) validParameter = true;			
						 	break;
						 	case 'ScopeFocusDiam':
								URIparamValue = Math.floor(+URIparamValue) ;
								if (5 <= URIparamValue && URIparamValue <=50) validParameter = true;			
						 	break;
						 	case 'ScopeMinDiam':
								if (5 <= URIparamValue && URIparamValue <= 50) {
									validParameter = true;
									if (+document.getElementById('ScopeMaxDiam').value < URIparamValue) {
										document.getElementById('ScopeMaxDiam').value = URIparamValue;
										document.getElementById(rsgfs.field(0)).value = URIparamValue; // do it early because param ScopeMaxDiam may reference the value 
									}
								}
						 	break;
						 	case 'ScopeMaxDiam':
								if (URIparamValue <= 50 && URIparamValue >= document.getElementById('ScopeMinDiam').value) validParameter = true;			
						 	break;
						 	case 'ScopeAxes':
								if (URIparamValue <= 16 && URIparamValue >= 256) validParameter = true;			
						 	break;
						 	case 'GearsWorkers':
								URIparamValue = Math.floor(+URIparamValue) ;
								if (1 <= URIparamValue && URIparamValue <=5) validParameter = true;			
						 	break;
						 	default:
								throw ('unexpected invalid URI parameter');
						 	break;
						}
						if (validParameter) {
								document.getElementById( rsgfs.field(0)).value = URIparamValue; // document variable must have same name as parameter name
								// prepare to update the Db after rsgfs cursor has finished
								URIparams[URIparamCount++] = {
								param: rsgfs.field(0),
								value: URIparamValue
							};
						}
					}			
		            rsgfs.next();
				}
		}
		URIparamCount=0; // now to update the Db with any valid URI parameters
		while (URIparamCount < URIparams.length){
			setFamSetting(URIparams[URIparamCount].param, URIparams[URIparamCount].value);
			URIparamCount++;
		}
		
		var action = 0;
		if( URIparamValue = gup('TrxSource') ) {
			if( URIparamValue = gup('TrxTarget') ) {
				action = 1;
			}
			else if( URIparamValue = gup('TrxOrganelle') ) {
				action = 2;
			}
			else {
				action = 3;
			}
		}
		else {
			if( URIparamValue = gup('TrxTarget') ) {
				if( URIparamValue = gup('TrxOrganelle') ) {
					action = 4;
				}
				else {
					action = 5;
				}
			}
			else {
				if( URIparamValue = gup('TrxOrganelle') ) {
					action = 6;
				}	
			}
		}
//		alert ("action = "+action);
    } 
    catch (e) {
        alert("getFamSetting error: " + e);
		  dbgfs.execute('end');
        dbgfs.close;
        return false;
    }
    finally {
        dbgfs.close;
    }
}

function init_profile_db(dbip){
    //	Create the profile Db if it does not already exist	
    
    try {
         dbip.execute('create table if not exists ' +
        ' culture (' +
        ' id integer primary key autoincrement, ' +
        ' name text unique not null, ' +
        ' latest_focus_ID text, ' +
        ' last_used date not null)');

        dbip.execute('create table if not exists ' +
        ' setting (' +
        ' id integer primary key , ' +
        ' user_config integer not null check (user_config=0 or user_config=1), ' +
        ' parameter text unique not null, ' +
        ' value text)');  

		dbip.execute('create table if not exists ' +
			' debug (' +
	        ' line integer primary key autoincrement, ' +
	        ' batch integer, ' +
	        ' module text, ' +
	        ' action text, ' +
	        ' status text, ' +
           	' msg text) ' );
    } 
    catch (e) {
		  alert("init_profile_db error: " + e);
    }
};

function init_profile_settings(dbips){
    //	Create the profile Db if it does not already exist	
    
    try {
           var set = []; // initialise application / system parameters on first ever use
            set[0] = { p: 'ConcAkinityVers',	u: 0,	v: '0.1'	};
            set[1] = { p: 'ConcMosBreadth',		u: 0,	v: '8'		};
            set[2] = { p: 'ConcMaxBreadth',		u: 0,	v: '12'		};
            set[3] = { p: 'ConcMaxDepth',		u: 1,	v: '15'		};
            set[4] = { p: 'ConcDefBreadth',		u: 1,	v: '10'		};
            set[5] = { p: 'ConcDefBindPar',		u: 1,	v: 'Y|X'	};
            set[6] = { p: 'ConcMaxInBred',		u: 1,	v: '0.60'	};
            set[7] = { p: 'ScopeMaxDist',		u: 1,	v: '1'		};
            set[8] = { p: 'ScopeMaxcTags',		u: 1,	v: '30'		};
            set[9] = {p: 'ScopeFocusDiam',		u: 0,	v: '20'		};
            set[10] = {p: 'ScopeMinDiam',		u: 1,	v: '15'		};
            set[11] = {p: 'ScopeMaxDiam',		u: 1,	v: '30'		};
            set[12] = {p: 'ScopeAxes',			u: 1,	v: '64'		};
            set[13] = {p: 'ScopeSearchExpiry',	u: 1,	v: '100'	};
            set[14] = {p: 'ScopeRelScale',		u: 1,	v: '0'		};
			set[15] = {p: 'GearsWorkers',		u: 1,	v: '3'		};
 			set[16] = {p: 'IntFlickrAPIURL',	u: 0,	v: 'http://api.flickr.com/services/rest/?method='		};
 			set[17] = {p: 'IntFlickrAPIKey',	u: 0,	v: 'adc29581556f04c89956e3b56fdc0815'		};
            set[18] = {p: 'IntFlickrOn',		u: 1,	v: '1'		};
            set[19] = {p: 'IntFlickrSynGens',	u: 1,	v: '2'		};
       
	        dbips.execute('begin');
	        for (i = 0; i < set.length; i++) {
	            dbips.execute("insert into setting (id, parameter, user_config, value) values (?,?,?,?)", [i + 1, set[i].p, set[i].u, set[i].v]);
	        }
	        dbips.execute('commit');
    } 
    catch (e) {
       alert("init_profile_settings error: " + e);
    }
};

function setFamSetting(param, value){
    /* Set the value of a single setting parameter in the profile database.
     */
    try {
			var mv = init_mv(); // create module variable structue and default values
			mv.dest.module 		= 'db';
			mv.dest.action 		= 'setFamSetting';
			mv.dest.ID 			= dbworker.ID
			mv.se.param 		= param;
			mv.se.value 		= value;

			trx_caller (wp, mv, null, null, mv.dest.ID);

       return true;
    } 
    catch (e) {
        alert("setFamSetting error: " + e);
    }
}

function mount_culture(culture){
     try {
			var mv = init_mv(); 
			mv.dest.module 		= 'db';
			mv.dest.action 		= 'mount_culture';
			mv.dest.ID 			= dbworker.ID
			mv.cu.name 			= culture;

			trx_caller (wp, mv, null, null, mv.dest.ID);
    } 
    catch (e) {
        alert("mount_culture error: " + e);
    }
 }

function create_objects(culture){
     try {
			var mv = init_mv(); 
			mv.dest.module 		= 'db';
			mv.dest.action 		= 'create_objects';
			mv.dest.ID 			= dbworker.ID
			mv.cu.name 			= culture;
			trx_caller (wp, mv, null, null, mv.dest.ID);
    } 
    catch (e) {
        alert("create_objects error: " + e);
    }
 }

function list_cultures(){

    var i = 0;
    function clearOptions(){ // reset the drop down list
        var i = 0;
        var x = document.getElementById("Select_CultureName");
        while (i < x.length) {
            x.remove(x.i++) }
    }
    
function addOption(culture, binding_id){ // add a new option to the drop down list
        var opt = document.createElement("option");
        document.getElementById("Select_CultureName").options.add(opt);
        opt.text = culture;
        opt.value = binding_id;
    }
    
    try {
		var dblc 	= google.gears.factory.create('beta.database');
        clearOptions();
       	dblc.open('UserSettings');
        dblc.execute('begin');
        
       //	List profile cultures in order of recent use
        var rslc = dblc.execute(' select name, latest_focus_ID ' +
        ' from culture ' +
        ' order by last_used desc');
        while (rslc.isValidRow()) {
            addOption(rslc.field(0), rslc.field(1));
            i++;
            rslc.next();
        }
        dblc.execute('end');
        dblc.close;
        
        if (i === 0)  //	If no cultures were present (because first time use) then let the caller create one
			return false;
		else return true;
		
    } 
    catch (e) {
        alert("list_cultures error: " + e);
    }
    finally {
        dblc.close;
    }
}

