/*   $Id$
 *
 *   Copyright (c) 2007 Snempaa & Richie B.
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package sendSms;

import java.io.IOException;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;

/**
 *
 * @author Wouter & Richard
 */

public class BetamaxSMS extends MIDlet implements CommandListener{
    
    private TextField message, user, pass, from, betamax, cc, comment;
    public  TextField recipient;
    private Form help;
    private ChoiceGroup https, gsm, aSelect, bLookup, aStrip, sizeSms, splashScreen, charCount,exitAbove;
    private RecordStore rs;
    private Display display;
    private Form settings, about;
    public  Form sms, sendInfo;
    private String userString, passString, fromString, toString, textString, checkVersion;
    private Command exitCommand, aboutCommand, settingsCommand, cancelCommand, saveCommand, sendOwner, balanceCommand;
    private Command clearAllCommand, clearTextCommand, sendCommand, helpCommand, countCommand, contactListCommand;
    private String url = "http";
    private String afterUrl = "://myaccount.";
    private String afterDomain = "/clx/sendsms.php?username=";
    private String url2 = "&password=";
    private String url3 = "&from=";
    private String url4 = "&to=";
    private String ending = "&text=";
    private String ccString = "31";
    private String betamaxClone = "voipwise.com";
    private boolean started = false;
    private boolean havePIM = false;
    private boolean clearBool = true;
    private String secure = "no";
    public  String mobOnly = "no";
    public  String autoSelect = "no";
    private String bsmsLookup = "no";
    private String accentStrip = "yes";
    public String splash = "yes";
    private String longsms = "no";
    private String charCountSetting = "yes";
    private String exitAboveSetting = "yes";
    private String itWorksSetting = "yes";
    private int smsSize = 160;
    private static final String version = "1.6.6";
    private static final String date = "14 Dec 2007";
    private static final String authors = "Snempaa & RichieB";
    private int chars = 0;
    private int parts = 0;
    public int charItemNr = 0;
    private StringItem charsed = new StringItem(null,"chars: "+chars+" | parts: "+parts,Item.PLAIN);
    
    public void commandAction(Command command, Displayable displayable) {
        if (displayable == sms) {
            if (command == exitCommand) {
                toString=recipient.getString();
                textString=message.getString();
                exitMIDlet();
                return;
            }
            if (command == countCommand) {
                textString=message.getString();
                sendAlert("Count",null,"Your text is now "+String.valueOf(textString.length())+" characters, you can use "+String.valueOf(smsSize-textString.length())+" more. You are using "+String.valueOf((159+textString.length())/160)+" message(s) now!",Alert.FOREVER,null);
            }
            if (command == contactListCommand) {
                toString=recipient.getString();
                textString=message.getString();
                display.setCurrent(new ContactListForm(this));
            }
            if(command == clearAllCommand){
                clearText();
                recipient.setString("");
                toString = new String();
                textString = new String();
            }
            if (command == sendCommand) {
                String temp = recipient.getString();
                if(temp.length()>2 && temp.charAt(0) == '0'){
                    if(temp.charAt(1) == '0')
                        temp = "+"+temp.substring(2);
                    else
                        temp = "+31"+temp.substring(1);
                }
                toString=recipient.getString();
                textString=message.getString();
                
                if(betamaxClone == null || betamaxClone.length()<1) {
                    sendAlert("Error",AlertType.ERROR,"Betamax clone undefined.\nSee setings page.",Alert.FOREVER,null);
                    return;
                }
                if(userString == null || userString.length()<1) {
                    sendAlert("Error",AlertType.ERROR,"Username undefined.\nSee setings page.",Alert.FOREVER,null);
                    return;
                }
                if(passString == null || passString.length()<1) {
                    sendAlert("Error",AlertType.ERROR,"Password undefined.\nSee setings page.",Alert.FOREVER,null);
                    return;
                }
                if(ccString == null || ccString.length()<1) {
                    sendAlert("Error",AlertType.ERROR,"County code undefined.\nSee setings page.",Alert.FOREVER,null);
                    return;
                }
                if(temp.trim().length()<1) {
                    sendAlert("Error",AlertType.ERROR,"To number is empty!",Alert.FOREVER,null);
                    return;
                }
                if(message.getString().trim().length()<1) {
                    sendAlert("Error",AlertType.ERROR,"Message text is empty!",Alert.FOREVER,null);
                    return;
                }
                String sm=message.getString();
                if(accentStrip.equals("yes"))
                    sm=stripAccents(sm);
                SendViaStream s = new SendViaStream(this,url+afterUrl+betamaxClone+afterDomain+userString+url2+passString+url3+urlEncode(fromString)+url4+urlEncode(temp)+ending,sm);
                s.start();
                toString=recipient.getString();
                textString=message.getString();
            }
            if(command == settingsCommand){
                newSettingsForm();
                return;
            }
            if(command == sendOwner){
                sendInfo = new Form("Send");
                String tempData = System.getProperty("microedition.platform")+" - "+System.getProperty("microedition.profiles")+" - "+System.getProperty("microedition.configuration")+" - ";
                sendInfo.append("With this option you will text the developer(s) of this software with your brand and type of phone. I will only receive this if the software works for you! This will send one textmessage to a dutch number! If it succeeds, the menu-option will disappear. This will be texted: \n"+tempData);
                comment = new TextField("Any comment, max "+(160-tempData.length())+" chars!","",(160-tempData.length()),TextField.ANY);
                sendInfo.append(comment);
                sendInfo.addCommand(getCancelCommand());
                sendInfo.addCommand(getSendCommand());
                sendInfo.setCommandListener(this);
                display.setCurrent(sendInfo);
            }
            if(command == balanceCommand){
                if(betamaxClone == null || betamaxClone.length()<1) {
                    sendAlert("Error",AlertType.ERROR,"Betamax clone undefined.\nSee setings page.",Alert.FOREVER,null);
                    return;
                }
                if(userString == null || userString.length()<1) {
                    sendAlert("Error",AlertType.ERROR,"Username undefined.\nSee setings page.",Alert.FOREVER,null);
                    return;
                }
                if(passString == null || passString.length()<1) {
                    sendAlert("Error",AlertType.ERROR,"Password undefined.\nSee setings page.",Alert.FOREVER,null);
                    return;
                }
                CheckBalance bal = new CheckBalance(this,url+afterUrl+betamaxClone,userString,passString);
                bal.start();
            }
        } else if(displayable == sendInfo){
            if (command == cancelCommand){
                showMain();
            } else if(command == sendCommand){
                //Do sending of brand, type to my nr
                if(betamaxClone == null || betamaxClone.length()<1) {
                    sendAlert("Error",AlertType.ERROR,"Betamax clone undefined.\nSee setings page.",Alert.FOREVER,null);
                    return;
                }
                if(userString == null || userString.length()<1) {
                    sendAlert("Error",AlertType.ERROR,"Username undefined.\nSee setings page.",Alert.FOREVER,null);
                    return;
                }
                if(passString == null || passString.length()<1) {
                    sendAlert("Error",AlertType.ERROR,"Password undefined.\nSee setings page.",Alert.FOREVER,null);
                    return;
                }
                if(ccString == null || ccString.length()<1) {
                    sendAlert("Error",AlertType.ERROR,"County code undefined.\nSee setings page.",Alert.FOREVER,null);
                    return;
                }
                String tempData = System.getProperty("microedition.platform")+" - "+System.getProperty("microedition.profiles")+" - "+System.getProperty("microedition.configuration")+" - "+comment.getString();
                SendViaStream s = new SendViaStream(this,url+afterUrl+betamaxClone+afterDomain+userString+url2+passString+url3+urlEncode(fromString)+url4+urlEncode("+31619639189")+ending,tempData);
                clearBool = false;
                s.start();
            }
        } else if(displayable == help){
            display.setCurrent(settings);
        } else if(displayable == settings){
            if(command == saveCommand){
                saveSettings();
                newSmsForm();
                showMain();
                return;
            }
            if(command == helpCommand){
                String helptxt =  "Username/password: credentials for Betamax clone website.\n"+
                        "Caller ID: optional sender number, must be verified by Betamax.\n"+
                        "Betamax clone: VoIP site name without www.\n"+
                        "Enable multiple sms: Enable sending 5 text messages at once (max 800 chars)"+
                        "Use SSL/HTTPS: https (http over SSL) is needed for some sites. Data per SMS goes from 2kB to 4kB when secured.\n"+
                        "Country code: convert numbers starting with 0 to international notation using this code.\n"+
                        "Strip accents: some phone companies cannot handle the way Betamax sends accents on letters like כלספ.\n";
                if(havePIM)
                    helptxt = helptxt+
                            "Override builtin lookup: override Nokia/SonyEricsson builtin contacts lookup.\n"+
                            "Only mobile: only show mobile numbers during lookup (on supported devices).\n"+
                            "Auto select: auto select number when lookup only returns one.\n";
                helptxt = helptxt + "Show splashscreen: Enables or disables the BetaMaxSMS startup screen.";
                help = new Form("Settings help");
                help.append(helptxt);
                help.addCommand(getCancelCommand());
                help.setCommandListener(this);
                display.setCurrent(help);
            }
            if(command == cancelCommand){
                if(sms==null)
                    newSmsForm();
                showMain();
                return;
            }
        }
        if(command == clearTextCommand){
            clearText();
        }
        if (command == aboutCommand) {
            Image logo = null;
            try {
                logo = Image.createImage("/sendSms/about.gif");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            sendAlert(null,AlertType.INFO,"v"+version+"\nBuilt on "+date,Alert.FOREVER, logo);
        }
        // Always save settings after command unless return is used
        saveSettings();
    }
    
    public void getInfoFromRS(){
        try {
            userString = getRsRecord(1);
            passString = getRsRecord(2);
            fromString = getRsRecord(3);
            toString = getRsRecord(4);
            textString = getRsRecord(5);
            betamaxClone = getRsRecord(6);
            secure = getRsRecord(7);
            checkVersion = getRsRecord(8);
            ccString = getRsRecord(9);
            mobOnly = getRsRecord(10);
            autoSelect = getRsRecord(11);
            bsmsLookup = getRsRecord(12);
            accentStrip = getRsRecord(13);
            longsms = getRsRecord(14);
            if(longsms.equals("yes"))
                smsSize = 800;
            splash = getRsRecord(15);
            charCountSetting = getRsRecord(16);
            exitAboveSetting = getRsRecord(17);
            itWorksSetting = getRsRecord(18);
        } catch (Exception ex) {
            ex.printStackTrace();
            try {
                rs.closeRecordStore();
                RecordStore.deleteRecordStore("betamaxsmssettings");
                rs = RecordStore.openRecordStore("betamaxsmssettings",true);
            } catch (RecordStoreNotOpenException rex) {
                rex.printStackTrace();
            } catch (RecordStoreException r2ex) {
                r2ex.printStackTrace();
            }
            newSettingsForm();
        }
    }
    
    public Command getSendCommand(){
        if(sendCommand == null)
            sendCommand = new Command("Send", Command.SCREEN, 0);
        return sendCommand;
    }
    
    public void sleep(int i) {
        try {
            Thread.sleep(i);
        } catch (InterruptedException ex) {
        }
    }
    
    public Command getSaveCommand(){
        if(saveCommand == null){
            saveCommand = new Command("Save", Command.SCREEN, 1);
        }
        return saveCommand;
    }
    
    public Command getSendOwner(){
        if(sendOwner == null){
            sendOwner = new Command("It Works!", Command.SCREEN, 12);
        }
        return sendOwner;
    }
    
    public Command getClearAllCommand(){
        if(clearAllCommand == null)
            clearAllCommand = new Command("Reset", Command.SCREEN, 2);
        return clearAllCommand;
    }
    
    public Command getClearTextCommand(){
        if(clearTextCommand == null)
            clearTextCommand = new Command("Clear", Command.SCREEN, 3);
        return clearTextCommand;
    }
    
    public Command getContactListCommand(){
        if(contactListCommand == null)
            contactListCommand = new Command("Lookup", Command.SCREEN, 4);
        return contactListCommand;
    }
    
    public Command getCountTextCommand(){
        if(countCommand == null)
            countCommand = new Command("Count", Command.SCREEN, 5);
        return countCommand;
    }
    
    // cancelCommand needs Command.OK for SE bug, see http://developer.sonyericsson.com/entry.jspa?externalID=402&categoryID=7
    public Command getCancelCommand(){
        if(cancelCommand == null)
            cancelCommand = new Command("Cancel", Command.OK, 6);
        return cancelCommand;
    }
    
    public Command getSettingsCommand(){
        if(settingsCommand == null)
            settingsCommand = new Command("Settings", Command.SCREEN, 7);
        return settingsCommand;
    }
    
    public Command getExitCommand(){
        if(exitAboveSetting.equals("yes"))
            exitCommand = new Command("Exit", Command.SCREEN , 1);
        else
            exitCommand = new Command("Exit", Command.EXIT , 99);
        return exitCommand;
    }
    
    public Command getBalanceCommand(){
        if(balanceCommand == null)
            balanceCommand = new Command("Balance (19kB)", Command.SCREEN, 11);
        return balanceCommand;
    }
    
    public Command getHelpCommand(){
        if(helpCommand == null)
            helpCommand = new Command("Help", Command.HELP, 9);
        return helpCommand;
    }
    
    public Command getAboutCommand(){
        if(aboutCommand == null)
            aboutCommand = new Command("About", Command.HELP, 10);
        return aboutCommand;
    }
    
    public void exitMIDlet() {
        destroyApp(false);
    }
    
    public void startApp() {
        boolean settingsFirst=false;
        if(!started){
            display=Display.getDisplay(this);
            havePIM = (System.getProperty("microedition.pim.version") != null);
            try {
                rs = RecordStore.openRecordStore("betamaxsmssettings",true);
                getInfoFromRS();
            } catch (RecordStoreException ex) {
                ex.printStackTrace();
                destroyApp(false);
            }
            settingsFirst=(settings!=null);
            started = true;
            if(secure.equals("yes"))
                url = "https";
            newSmsForm();
            //Show splashscreen
            if(splash.equals("yes")) {
                ShowSplash s;
                if(settingsFirst)
                    s=new ShowSplash(this,settings);
                else
                    s=new ShowSplash(this,sms);
                display.setCurrent(s);
            }
        }
        if(checkVersion != null){
            if(!checkVersion.equals(version)){
                try {
                    rs.closeRecordStore();
                    RecordStore.deleteRecordStore("betamaxsmssettings");
                    rs = RecordStore.openRecordStore("betamaxsmssettings",true);
                } catch (RecordStoreNotOpenException ex) {
                    ex.printStackTrace();
                } catch (RecordStoreException ex) {
                    ex.printStackTrace();
                }
                saveSettings();
            }
        }
        if(!splash.equals("yes")) {
            if(settingsFirst)
                display.setCurrent(settings);
            else
                showMain();
        }
    }
    
    public void saveSettings() {
        String temp;
        if(user != null && user.size()>0)
            userString = user.getString().trim();
        if(userString == null)
            userString = new String();
        
        if(pass != null && pass.size()>0)
            passString = pass.getString().trim();
        if(passString == null)
            passString = new String();
        
        if(betamax != null && betamax.size()>0)
            betamaxClone = betamax.getString().trim();
        if(betamaxClone == null)
            betamaxClone = new String();
        
        if(cc != null && cc.size()>0)
            ccString = cc.getString().trim();
        if(ccString == null)
            ccString = new String("31");
        
        if(toString != null && toString.length()>0)
            temp = toString.toString();
        else
            temp = new String();
        toString = temp;
        
        if(textString != null && textString.length()>0)
            temp = textString.toString();
        else
            temp = new String();
        textString = temp;
        
        if(from != null)
            temp = from.getString();
        else if(fromString != null)
            temp = fromString.toString();
        else temp = new String();
        if(temp.length()>2 && temp.charAt(0) == '0'){
            if(temp.charAt(1) == '0')
                temp = "+"+temp.substring(2);
            else
                temp = "+"+ccString+temp.substring(1);
        }
        fromString = temp;
        
        if(https != null) {
            if(https.getSelectedIndex() == 1){
                secure = "yes";
                url = "https";
            } else{
                secure = "no";
                url = "http";
            }
        }
        
        if(gsm != null) {
            if(gsm.getSelectedIndex() == 1)
                mobOnly = "yes";
            else
                mobOnly = "no";
        }
        
        if(aSelect != null) {
            if(aSelect.getSelectedIndex() == 1)
                autoSelect = "yes";
            else
                autoSelect = "no";
        }
        
        if(bLookup != null) {
            if(bLookup.getSelectedIndex() == 1)
                bsmsLookup = "yes";
            else
                bsmsLookup = "no";
        }
        
        if(aStrip != null) {
            if(aStrip.getSelectedIndex() == 1)
                accentStrip = "yes";
            else
                accentStrip = "no";
        }
        if(sizeSms != null) {
            if(sizeSms.getSelectedIndex() == 1){
                longsms = "no";
                smsSize = 160;
            } else{
                longsms = "yes";
                smsSize = 800;
            }
        }
        if(splashScreen != null) {
            if(splashScreen.getSelectedIndex() == 1)
                splash = "yes";
            else
                splash = "no";
        }
        if(charCount != null) {
            if(charCount.getSelectedIndex() == 1)
                charCountSetting = "yes";
            else
                charCountSetting = "no";
        }
        if(exitAbove != null) {
            if(exitAbove.getSelectedIndex() == 1)
                exitAboveSetting = "yes";
            else
                exitAboveSetting = "no";
        }
        try {
            rs.setRecord(1,userString.getBytes(), 0, userString.getBytes().length);
            rs.setRecord(2,passString.getBytes(), 0, passString.getBytes().length);
            rs.setRecord(3,fromString.getBytes(), 0, fromString.getBytes().length);
            rs.setRecord(4,toString.getBytes(), 0, toString.getBytes().length);
            rs.setRecord(5,textString.getBytes(), 0, textString.getBytes().length);
            rs.setRecord(6,betamaxClone.getBytes(), 0, betamaxClone.getBytes().length);
            rs.setRecord(7,secure.getBytes(), 0, secure.getBytes().length);
            rs.setRecord(8,version.getBytes(), 0, version.getBytes().length);
            rs.setRecord(9,ccString.getBytes(), 0, ccString.getBytes().length);
            rs.setRecord(10,mobOnly.getBytes(), 0, mobOnly.getBytes().length);
            rs.setRecord(11,autoSelect.getBytes(), 0, autoSelect.getBytes().length);
            rs.setRecord(12,bsmsLookup.getBytes(), 0, bsmsLookup.getBytes().length);
            rs.setRecord(13,accentStrip.getBytes(), 0, accentStrip.getBytes().length);
            rs.setRecord(14,longsms.getBytes(), 0, longsms.getBytes().length);
            rs.setRecord(15,splash.getBytes(),0,splash.getBytes().length);
            rs.setRecord(16,charCountSetting.getBytes(),0,splash.getBytes().length);
            rs.setRecord(17,exitAboveSetting.getBytes(),0,exitAboveSetting.getBytes().length);
            rs.setRecord(18,itWorksSetting.getBytes(), 0,itWorksSetting.getBytes().length);
        } catch (Exception ex) {
            ex.printStackTrace();
            try {
                rs.closeRecordStore();
                RecordStore.deleteRecordStore("betamaxsmssettings");
                rs = RecordStore.openRecordStore("betamaxsmssettings",true);
                rs.addRecord(userString.getBytes(), 0, userString.getBytes().length);
                rs.addRecord(passString.getBytes(), 0, passString.getBytes().length);
                rs.addRecord(fromString.getBytes(), 0, fromString.getBytes().length);
                rs.addRecord(toString.getBytes(), 0, toString.getBytes().length);
                rs.addRecord(textString.getBytes(), 0, textString.getBytes().length);
                rs.addRecord(betamaxClone.getBytes(), 0, betamaxClone.getBytes().length);
                rs.addRecord(secure.getBytes(), 0, secure.getBytes().length);
                rs.addRecord(version.getBytes(),0,version.getBytes().length);
                rs.addRecord(ccString.getBytes(),0,ccString.getBytes().length);
                rs.addRecord(mobOnly.getBytes(),0,mobOnly.getBytes().length);
                rs.addRecord(autoSelect.getBytes(),0,autoSelect.getBytes().length);
                rs.addRecord(bsmsLookup.getBytes(),0,bsmsLookup.getBytes().length);
                rs.addRecord(accentStrip.getBytes(),0,accentStrip.getBytes().length);
                rs.addRecord(longsms.getBytes(), 0, longsms.getBytes().length);
                rs.addRecord(splash.getBytes(),0,splash.getBytes().length);
                rs.addRecord(charCountSetting.getBytes(),0,charCountSetting.getBytes().length);
                rs.addRecord(exitAboveSetting.getBytes(),0,exitAboveSetting.getBytes().length);
                rs.addRecord(itWorksSetting.getBytes(), 0,itWorksSetting.getBytes().length);
            } catch (Exception rex) {
                rex.printStackTrace();
                destroyApp(false);
            }
        }
    }
    
    public void newSettingsForm() {
        int temp;
        settings = new Form("Settings");
        if(started)
            getInfoFromRS();
        user = new TextField("Username: ",userString,25,TextField.ANY);
        pass = new TextField("Password: ",passString,25,TextField.PASSWORD);
        from = new TextField("Caller ID: ",fromString,25,TextField.PHONENUMBER);
        betamax = new TextField("Betamax clone (without www.): ",betamaxClone,40,TextField.ANY);
        cc = new TextField("Country code: ",ccString,3,TextField.NUMERIC);
        sizeSms = new ChoiceGroup("Enable multiple sms?", Choice.POPUP);
        if(longsms.equals("no")){
            sizeSms.append("Yes",null);
            temp = sizeSms.append("No",null);
        } else{
            temp = sizeSms.append("Yes", null);
            sizeSms.append("No",null);
        }
        sizeSms.setSelectedIndex(temp, true);
        https = new ChoiceGroup("Use SSL/HTTPS?",Choice.POPUP);
        if(secure.equals("yes")){
            https.append("No",null);
            temp = https.append("Yes",null);
        } else{
            temp = https.append("No",null);
            https.append("Yes",null);
        }
        https.setSelectedIndex(temp, true);
        gsm = new ChoiceGroup("Lookup only mobile numbers?",Choice.POPUP);
        if(mobOnly.equals("yes")){
            gsm.append("No",null);
            temp = gsm.append("Yes",null);
        } else{
            temp = gsm.append("No",null);
            gsm.append("Yes",null);
        }
        gsm.setSelectedIndex(temp, true);
        aSelect = new ChoiceGroup("Auto select in lookup?",Choice.POPUP);
        if(autoSelect.equals("yes")){
            aSelect.append("No",null);
            temp = aSelect.append("Yes",null);
        } else{
            temp = aSelect.append("No",null);
            aSelect.append("Yes",null);
        }
        aSelect.setSelectedIndex(temp, true);
        bLookup = new ChoiceGroup("Override builtin lookup, if any?",Choice.POPUP);
        if(bsmsLookup.equals("yes")){
            bLookup.append("No",null);
            temp = bLookup.append("Yes",null);
        } else{
            temp = bLookup.append("No",null);
            bLookup.append("Yes",null);
        }
        bLookup.setSelectedIndex(temp, true);
        aStrip = new ChoiceGroup("Strip accents from letters?",Choice.POPUP);
        if(accentStrip.equals("yes")){
            aStrip.append("No",null);
            temp = aStrip.append("Yes",null);
        } else{
            temp = aStrip.append("No",null);
            aStrip.append("Yes",null);
        }
        aStrip.setSelectedIndex(temp, true);
        splashScreen = new ChoiceGroup("Show splashscreen on startup?", Choice.POPUP);
        if(splash.equals("yes")){
            splashScreen.append("No",null);
            temp = splashScreen.append("Yes",null);
        } else{
            temp = splashScreen.append("No",null);
            splashScreen.append("Yes",null);
        }
        splashScreen.setSelectedIndex(temp, true);
        charCount = new ChoiceGroup("Show BETA charcounter?", Choice.POPUP);
        if(charCountSetting.equals("yes")){
            charCount.append("No",null);
            temp = charCount.append("Yes",null);
        } else{
            temp = charCount.append("No",null);
            charCount.append("Yes",null);
        }
        charCount.setSelectedIndex(temp,true);
        exitAbove = new ChoiceGroup("Show exit high in menu?", Choice.POPUP);
        if(exitAboveSetting.equals("yes")){
            exitAbove.append("No",null);
            temp = exitAbove.append("Yes",null);
        } else{
            temp = exitAbove.append("No",null);
            exitAbove.append("Yes",null);
        }
        exitAbove.setSelectedIndex(temp,true);
        settings.append(user);
        settings.append(pass);
        settings.append(from);
        settings.append(betamax);
        settings.append(sizeSms);
        settings.append(https);
        settings.append(cc);
        settings.append(aStrip);
        settings.append(splashScreen);
        if(System.getProperty("microedition.pim.version") != null) {
            settings.append(bLookup);
            settings.append(gsm);
            settings.append(aSelect);
        }
        settings.append(charCount);
        settings.append(exitAbove);
        settings.addCommand(getCancelCommand());
        settings.addCommand(getSaveCommand());
        settings.addCommand(getHelpCommand());
        settings.addCommand(getAboutCommand());
        settings.setCommandListener(this);
        if(started)
            display.setCurrent(settings);
    }
    
    public void updateCharStrings(){
        if(charCountSetting.equals("yes")){
            chars = message.getString().length();
            parts = (159+message.getString().length())/160;
            charsed = new StringItem(null,"chars: "+chars+" | parts: "+parts,Item.PLAIN);
            sms.insert(charItemNr, charsed);
            sms.delete(charItemNr+1);
        }
    }
    
    public void newSmsForm() {
        sms = new Form("Send An SMS");
        sms.deleteAll();
        sms.setTitle("Send an SMS");
        if(charCountSetting.equals("yes")){
            ItemStateListener listener = new ItemStateListener() {
                public void itemStateChanged(Item item) {
                    if(item == message){
                        updateCharStrings();
                    }
                }
            };
            sms.setItemStateListener(listener);
        }
        String temp1 = new String();
        String temp2 = new String();
        if(recipient != null)
            temp1 = recipient.getString();
        else if(toString != null)
            temp1 = toString.toString();
        if(message != null)
            temp2 = message.getString();
        else if(textString != null)
            temp2 = textString.toString();
        recipient = new TextField("To: ",temp1,40,bsmsLookup.equals("yes")?TextField.ANY:TextField.PHONENUMBER);
        message = new TextField("Message: ",temp2,smsSize,TextField.ANY);
        sms.append(recipient);
        if(charCountSetting.equals("yes")){
            chars = message.getString().length();
            parts = (159+message.getString().length())/160;
            charsed = new StringItem(null,"chars: "+chars+" | parts: "+parts,Item.PLAIN);
            charItemNr = sms.append(charsed);
        }
        sms.append(message);
        sms.addCommand(getExitCommand());
        sms.addCommand(getAboutCommand());
        sms.addCommand(getSettingsCommand());
        sms.addCommand(getSendCommand());
        sms.addCommand(getClearAllCommand());
        sms.addCommand(getClearTextCommand());
        if(charCountSetting.equals("no"))
            sms.addCommand(getCountTextCommand());
        sms.addCommand(getBalanceCommand());
        if(itWorksSetting.equals("yes"))
            sms.addCommand(getSendOwner());
        if(havePIM && bsmsLookup.equals("yes"))
            sms.addCommand(getContactListCommand());
        sms.setCommandListener(this);
    }
    
    public void sendAlert(String title, AlertType type, String text, int timeout, Image im) {
        Alert a = new Alert(title);
        a.setType(type);
        a.setString(text);
        if(im != null)
            a.setImage(im);
        a.setTimeout(timeout);
        display.setCurrent(a);
    }
    
    public void showMessage(String m,ContactListForm c){
        sendAlert("Error",AlertType.ERROR,m,Alert.FOREVER,null);
    }
    
    public void clearText(){
        // Clear boolean is needed for the sendOwner function, so the message won't get cleared when you send the info to me!
        if(clearBool){
            message.setString("");
            toString=recipient.getString();
            textString = new String();
        }
        else{
            itWorksSetting = "no";
            try{
                rs.setRecord(18,itWorksSetting.getBytes(), 0,itWorksSetting.getBytes().length);
            }catch(Exception e){
                newSettingsForm();
            }
            newSmsForm();
        }
        clearBool = true;
        updateCharStrings();
        showMain();
    }
    
    public void showMain(){
        display.setCurrent(sms);
    }
    
    public void contactSelected(String contact){
        try {
            recipient.setString(stripGarbage(contact));
            toString=recipient.getString();
        } catch (IllegalArgumentException e) {
            sendAlert("Set phonenumber failed",AlertType.ERROR,"IllegalArgumentException: "+e.getMessage(),Alert.FOREVER,null);
        }
        saveSettings();
    }
    
    public String getRsRecord(int i) throws RecordStoreNotOpenException, InvalidRecordIDException, RecordStoreException {
        String s = new String();
        if(rs.getRecord(i)!=null)
            s=new String(rs.getRecord(i));
        return s;
    }
    
    public String stripGarbage(String s) {
        String good =
                "+0123456789";
        String result = "";
        for ( int i = 0; i < s.length(); i++ ) {
            if ( good.indexOf(s.charAt(i)) >= 0 )
                result += s.charAt(i);
        }
        return result;
    }
    
    /**
     * MIDP has no URLEncoder.encode() function so we write out own
     * URL encoding: alphnumeric and '.', '-', '*', '_' remain the same
     * space converts to '+'
     * Everything else to %xy where xy is the hex representation.
     *
     * @param s the string to encode
     *
     * @return the encoded string
     */
    public static String urlEncode(String s) {
        
        StringBuffer result = new StringBuffer();
        int i = 0;
        char ch;
        while (i < s.length()) {
            ch = s.charAt(i);
            if (ch >= '0' && ch <= '9' ||
                    ch >= 'a' && ch <= 'z' ||
                    ch >= 'A' && ch <= 'Z' ||
                    ch == '.' || ch == '-' ||
                    ch == '*' || ch == '_') {
                result.append(ch);
            } else if (ch == ' ')
                result.append('+');
            else {
                // Convert char to UTF-8 before url encoding (requirement of Betamax sites)
                byte[] x;
                try {
                    x=String.valueOf(ch).getBytes("UTF-8");
                } catch(java.io.UnsupportedEncodingException e) {
                    x=String.valueOf(ch).getBytes();
                }
                int j=0;
                while(j < x.length) {
                    // Now get the two hex chars for the lower 8 bits of the byte
                    int b=(0x000000FF & ((int)x[j]));
                    
                    // We are looking for something of the form %3E
                    result.append('%');
                    if (b < 0x10)
                        result.append('0');
                    result.append(Integer.toHexString(b).toUpperCase());
                    j++;
                }
            }
            i++;
        }
        return result.toString();
    }
    
    public String stripAccents(String s) {
        char[] cRaw = s.toCharArray();
        StringBuffer sb = new StringBuffer();
        AccentLookup pi_AccentLookup = new AccentLookup();
        for (int i=0; i != cRaw.length; ++i) {
            String cCanon = String.valueOf(cRaw[i]);
            if (pi_AccentLookup.HasAccentEquivalence(cCanon))
                cCanon = pi_AccentLookup.GetAccentEquivalence(cCanon);
            sb.append(cCanon);
        }
        return sb.toString();
    }
    
    public void pauseApp() {
    }
    
    public void destroyApp(boolean unconditional) {
        if(sms.isShown()) {
            toString=recipient.getString();
            textString=message.getString();
        }
        saveSettings();
        try {
            rs.closeRecordStore();
        } catch (RecordStoreException ex) {
        }
        notifyDestroyed();
    }
    
}


