var db = undefined;
function settings_db_open() {
    if (db == undefined)
        db = LocalStorage.openDatabaseSync("harbour-tetrafish", "1.0", "StorageDatabase", 100000);
    return db;
}
/// GAME SETTINGS
function getValue(setting,def) {
    var db = settings_db_open();
    var res=def;
    try {
       db.transaction(function(tx) {
          var rs = tx.executeSql('SELECT value FROM settings WHERE setting=?;', [setting]);
             if (rs.rows.length > 0) {
                res = rs.rows.item(0).value;
             } else {
                res = def;
             }
       })
    } catch (err) {
       res = def
    };
    return res
}

function setValue(setting, value) {
    var db = settings_db_open();
    var res = "";
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS settings(setting TEXT UNIQUE, value TEXT)');
        var rs = tx.executeSql('INSERT OR REPLACE INTO settings VALUES (?,?);', [setting,value]);
             if (rs.rowsAffected > 0) {
                res = "OK";

             } else {
                res = "Error";
             }
       }
    );
    return res;
}
/// LOAD/SAVE GAME
function getSave(setting,def) {
    var db = settings_db_open();
    var res=def;
    try {
       db.transaction(function(tx) {
          var rs = tx.executeSql('SELECT value FROM savegame WHERE setting=?;', [setting]);
             if (rs.rows.length > 0) {
                res = rs.rows.item(0).value;
             } else {
                res = def;
             }
       })
    } catch (err) {
       res = def
    };
    return res
}

function setSave(setting, value) {
    var db = settings_db_open();
    var res = "";
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS settings(savegame TEXT UNIQUE, value TEXT)');
        var rs = tx.executeSql('INSERT OR REPLACE INTO savegame VALUES (?,?);', [setting,value]);
             if (rs.rowsAffected > 0) {
                res = "OK";

             } else {
                res = "Error";
             }
       }
    );
    return res;
}
