ToolKit.prototype._init = function(inLoggedIn, inDriveby) {
    this.initUser(inLoggedIn, inDriveby);
    if(!this.hasOwnProperty("settings")) this.settings = {};
    this.settings.ex_page_sizes = {
        val:{
            "Letter":{
                val:"Letter",
                name:"Letter",
                widthIn:8.5
            },
            "A4":{
                val:"A4",
                name:"A4",
                widthIn:8.3
            },
            "Legal":{
                val:"Legal",
                name:"Legal",
                widthIn:8.5
            }
            }
        };
    this.settings.ex_editorAreaDimensions = {
        val:{
            width:800,
            widthIn:8
        }
        };
    if(inLoggedIn) {
        this.rmi_userSetting("*");
        this.rmi_getUserData();
        this.rmi_getReturnAddress();
    }
}


ToolKit.prototype.cb_err = function(e) {
    ui.ro(e);
}


ToolKit.prototype.cb_status = function(e) {
    ui.ro(e, true);
}


ToolKit.prototype.checkPassword = function(inNum) {
    if(inNum == 0) {
        if($("#register__password0").val().length < 6) {
            $("#register__password0__message").html("password too short");
        } else {
            $("#register__password0__message").html("ok!");
        }
    } else {
        var pw0 = $("#register__password0").val();
        var pw1 = $("#register__password1").val();
        if(pw0 == pw1) {
            $("#register__password1__message").html("ok!");
        } else {
            $("#register__password1__message").html("passwords do not match");
        }
    }
}


ToolKit.prototype.sendContactUsMsg = function() {
    var message = $.ofd(["email", "subject","message"], "contact_us__");
    if(message.subject.length == 0) {
        alert("What is the message about? Please add a subject.");
        return;
    }
    if(message.message.length == 0) {
        alert("What is your thought or question? Please type a message.");
        return;
    }
    this.rmi_sendContactUsMsg(message);
}

ToolKit.prototype.sendContactUsMsg_cb = function(e) {
    if(ui.ro(e)) {
        $.modal.close()
        ui.statusMessage("Your message has been sent", "green")
    }
}

/*
ToolKit.prototype.checkLoggedIn = function() {
	this.rmi_isLoggedIn();
}*/


ToolKit.prototype.driveBy = function() {
    return(this.bDriveByUser);
}


ToolKit.prototype.forgotPassword = function() {
    var email = $("#modalLoginRegister_iframe").contents().find("#login__email").validate("email");
    if(typeof(email) != "string") {
        alert("please enter your email address in the 'login' email field");
        return false;
    }
    this.rmi_forgotPassword(email);
}


ToolKit.prototype.forgotPassword_cb = function(e) {
    alert(e.message);
}

ToolKit.prototype.getReturnAddress_cb = function(e) {
    if(!ui.ro(e)) return;
    e.data.state = "?";
    //if(ab.stateByID.hasOwnProperty(e.data.state__id)) e.data.state = ab.stateByID[e.data.state__id].name;
    this.settings.ex_returnAddress = {
        val:e.data
        };
}

ToolKit.prototype.getUserData_cb = function(e) {
    if(!ui.ro(e)) return;

    this.userData = e.data;
}


ToolKit.prototype.initUser = function(inLoggedIn, inDriveby) {
    if(typeof(inLoggedIn) != "boolean") this.bLoggedIn = isLoggedIn;
    else this.bLoggedIn = inLoggedIn;
	
    if(typeof(inDriveby) != "boolean") this.bDriveByUser = isDrivebyUser;
    else this.bDriveByUser = inDriveby;
	
    this.sUserType = "nouser";
    if(this.loggedIn()) {
        this.sUserType = "loggedin";
        if(this.driveBy()) {
            this.sUserType = "driveby";
        }
    }
}


ToolKit.prototype.loggedIn = function() {
    return(this.bLoggedIn);
}


ToolKit.prototype.login = function() {
    //if(lman.dirtyLetterBackout()) return(false);
    if(this.driveBy()) {
        if(!confirm("You are currently a temporary user.  When you log in, any addresses and letters you have just created will be moved to your account.\nProceed?")) {
            ui.statusMessage("To clear your data please click the little 'x' in the top left corner.", "error");
            return (false);
        }
    } else if(this.loggedIn() && lman.dirtyLetter() && (this.userData.email != $("#modalLoginRegister_iframe").contents().find("#login__email").val())) {
        if(!confirm("You are currently logged in as " + this.userData.email + ".  If you change users, you will loose unsaved changes to your letters.\nProceed?")) {
            ui.statusMessage("To clear your data please click the little 'x' in the top left corner.", "error");
            return (false);
        }
    }
    ui.statusMessage("logging you in");
    this.loginUser = {
        email: $("#modalLoginRegister_iframe").contents().find("#login__email").val(),
        password: $("#modalLoginRegister_iframe").contents().find("#login__password").val(),
    }
    this.rmi_login(this.loginUser);
}


ToolKit.prototype.login_cb = function(e) {
    if(!ui.ro(e)) {
        switch (e.data) {
            case "unconfirmed" :
                $("#loginPanel").snippet("login_panel_confirm");
                $("#confirm__email").val(this.loginUser.email);
                break;
            default : //"baduserpass"
                $("#loginMessage").snippet("status_message_default", {
                    "message":e.message,
                    "cssClass":"error"
                });
        }
        return (false);
    }
    $("#modalLoginRegister_iframe").contents().find("#pageForm").submit(),
    $.modal.close();
    this.userData = e.data;
    this.settings = e.data.userSettings;
    this._init(true, (e.data.driveby_user == "true"));
    lman.searchDrafts(false);
    ui.displayMain("drafts");

    ui.setLoginElements();
}

/**
 * ajax - Creates a driveby user for the given session
 * inCallback (used in loginDriveBy_cb) either string to trigger behavior or function to be called after driveby user is created
 */
ToolKit.prototype.loginDriveBy  = function(inCallback) {
    if(this.loggedIn()) {
        alert("the page is trying to create a drive by when you're already logged in!");
        return (false);
    }
    if(typeof(this.creatingDriveby) != "undefined") {
        if(this.creatingDriveby) {
            ui.log("already doing driveby");
            return false;
        }
    }
    this.creatingDriveby = true;
    try {
        ui.statusMessage("setting you up");
    } catch (e) {
        $.log(e, "exception", true);
        return false;
    }
    this.loginDriveByCallback = inCallback;
    tk.rmi_loginDriveBy();
}


ToolKit.prototype.loginDriveBy_cb = function(e) {
    this.creatingDriveby = false;
    if(!ui.ro(e)) return false;
    this.userData = e.data;
    this.settings = e.data.userSettings;
    this._init(true, true);
    ui.setLoginElements();

    if(typeof this.loginDriveByCallback == "function") {
        this.loginDriveByCallback();
    } else {
        switch (this.loginDriveByCallback) {
            case "newLetter"    :
                lman.newLetter();
                break;
            case "saveContact"  :
                ab.saveContact();
                break;            
        }
    }
}


ToolKit.prototype.logout = function() {
    if(this.loggedIn()  && ! this.driveBy()) {
        this.rmi_logout();
    }
}


ToolKit.prototype.logout_cb = function() {
    this.initUser(false, false);
    ui.displayMain("home");
    lman.closeAllEditLetterPanels();
    ui.setLoginElements();
    ui.statusMessage("you are logged out", "green");
    showConfStatus = "";
    this.rmi_loadJSTemplates(dependency_init);
}


ToolKit.prototype.modalAccount = function(inShowPanel) {
    if(tk.driveBy() || !tk.loggedIn()) {
        ui.modalLogin();
    }
    var tpE = {
        modalTitle:"Account & Settings",
        modalTopRight: ui.btnRedSml({
            id:"",
            text:"save",
            title:"save changes",
            onclick:"tk.saveAccountInfo()"
        })
        + " " + ui.btnGrySml({
            id:"",
            text:"cancel",
            title:"close window, do not save changes",
            onclick:"$.modal.close()"
        }),
        state:ab.stateList,
        page_sizeList:tk.setting("ex_page_sizes"),
        email:tk.userData.email
    }

    ui.modal("modal__account__root", tpE, "viewRecipients");
    if(typeof(inShowPanel) == "string") {
        this.modalAccountDisplayPanel(inShowPanel);
    }
    tk.setAccountModalData();
    $("#user___password").listen({keyCode:{
        13:function() {
            if($("#user___password").val().length > 5) tk.saveAccountInfo();
        }
        }});
        
    this.rmi_getAccountInfo(function(e) {tk.modalAccountBillingPanel(e);});
}


ToolKit.prototype.modalAccountBillingPanel = function(e) {
    if($("#account_panel__letters_undebited_count").length == 0) {
        setTimeout(function(){tk.modalAccountBillingPanel(e);}, 250);
        return;
    }
    if(!ui.ro(e)) return;
    var tpE = {list:[]};
    $("#account_panel__letters_undebited_count").html(e.data.letters_undebited_count);

    $("#account_panel__balance").html("$" + e.data.balance.toFixed(2));
    $("#account_panel__outbox_balance").html("$" + e.data.outbox_balance.toFixed(2));
    if(e.data.combined_balance < 0) {
        tpE.list.push({"val":Math.abs(e.data.combined_balance).toFixed(2), "display_name":"$" + Math.abs(e.data.combined_balance).toFixed(2)} );
    }
    var priceList = [        
        "5.00",
        "10.00",
        "20.00",
        "40.00",
        "100.00"
    ];
    for(var i = 0; i < priceList.length; i++) {
        tpE.list.push({"val":priceList[i], "display_name":"$" + priceList[i]});
    }
    var optionHTML = $.snippet("option_item_list", tpE);
    //alert(optionHTML);
    $("#account_panel__transaction_amount").html(optionHTML);
    
}

ToolKit.prototype.modalAccountDisplayPanel = function(inPanelName) {
    if($("#account_panelTabWrapper:visible").length == 0) {
        setTimeout("tk.modalAccountDisplayPanel('" + inPanelName + "');", 250);
        return;
    }
    $("#account_panelTabWrapper").attr("className", "account_panelTabWrapper_" + inPanelName);
    $("#account_panelContentWrapper").attr("className", "account_panelContentWrapper_" + inPanelName);
}


ToolKit.prototype.popupHelpByID = function(inID) {
    this.rmi_getHelpItem(inID, function(e) {
        tk.popupHelpByID_cb(e);
    });
}

ToolKit.prototype.popupHelpByID_cb = function(e) {
    if(!ui.ro(e)) return(false);
    $.modal($.snippet("modal_help_item", e.data));
}

ToolKit.prototype.registerConfirmUser = function() {
    var regInfo = $.ofd(["email", "conf_code"], "confirmation_modal__");
    this.rmi_registerConfirmUser(regInfo, function(e) {
        lman.supressDraftMsg = true; tk.login_cb(e);
    });
}
	
	
ToolKit.prototype.registerUser = function() {
    var regInfo = $.ofd(["password0", "password1", "email"], "register__");
    if(regInfo.email.length < 5) {
        alert("your user name is too short");
        return false;
    }
    if(regInfo.password0.length < 6) {
        alert("your password must be at least 6 characters long");
        return false;
    }
    if(regInfo.password0 != regInfo.password1) {
        alert("passwords do not match");
        return false;
    }
    var returnAddress = $.ofd(["name", "street", "city", "zip", "state__id"], "register__address__");
    $.log("around line 368 toolkit.class.js need to add address verfication code");
    ui.statusMessage("registering you as " + regInfo.email);
    regInfo.returnAddress  = returnAddress;
    this.rmi_registerUser(regInfo);
}


ToolKit.prototype.registerUser_cb = function(e) {
    //$.log(e, "registerUser_cb", true);
    ui.ro(e, true);
    if(e.ok) {
        $("#modalTitle").html("Confirm Registration");
        ui.modalSetContent($.snippet("modal_confirm_field", e.data));
        setTimeout("$('#confirmation_modal__conf_code').focus()", 200);
        for(var i in letterControl) if(letterControl.hasOwnProperty(i)) {
            lman.autoSaveDraft(i);
        }
    }
}

ToolKit.prototype.resendConfirm = function() {
    var email = $("#confirm__email").val();
    this.rmi_resendConfirm(email);
}


ToolKit.prototype.resendConfirm_cb = function(e) {
    if(!ui.ro(e, true)) {
}
}


ToolKit.prototype.saveAccountInfo = function() {

    if($("#user___password").val().length == 0) {
        alert("please enter your password below the save button to confirm changes");
        return false;
    }
    var returnAddress = $.ofd(["id", "name", "street", "city", "zip", "state__id"], "return_address__");
    var userAccount = $.ofd(["newPassword","newPasswordConfirm","newEmail", "newEmailConfirm" ], "user_setting__");
    var userInfo = {};
    var userSettings = {};
    var jQ;
    for(var i in tk.settings) if(tk.settings.hasOwnProperty(i)) {
        jQ = $("#user_setting__" + i);
        if(jQ.length == 1) {
            userSettings[i] = jQ.is(":checkbox")? jQ.is(":checked").toString() : jQ.val();
        }
    }

    if(userAccount.newPassword.length > 0) {
        if(userAccount.newPassword != userAccount.newPasswordConfirm) {
            ui.statusMessage("password confirmation does not match!", "error");
            return(false)
        }
        userInfo.password = userAccount.newPassword;
    }

    if(userAccount.newEmail.length > 0 ) {
        if(userAccount.newEmail != userAccount.newEmailConfirm) {
            ui.statusMessage("email confirmation does not match!", "error");
            return(false)
        }
        userInfo.email = userAccount.newEmail;
    }

    this.rmi_saveAccountInfo($("#user___password").val(), {
        settings:userSettings,
        address:returnAddress
    }, userInfo);
    ui.statusMessage("saving info");
}

ToolKit.prototype.saveAccountInfo_cb = function(e) {
    if(!e.ok) {
        alert(e.message); return;
    }
    this.rmi_userSetting("*");
    this.rmi_getReturnAddress();
    $.modal.close();
    ui.statusMessage(e.message, "green");
}

ToolKit.prototype.setAccountModalData = function() {
    var item = "";
    var jQ = {};

    for(i in tk.settings) if(tk.settings.hasOwnProperty(i)) {
        item = tk.settings[i];
        if(item.group_name == "letter_settings") {
            jQ = $("#user_setting__" + i);
            if(jQ.is(":checkbox")) {
                if(item.val == "true") jQ.attr("checked", "checked");
            } else {
                jQ.val(item.val);
            }
        }
    }

    if(tk.settings.hasOwnProperty("ex_returnAddress")) {
        $.log(tk.settings.ex_returnAddress.val, "return address", true);
        for(i in tk.settings.ex_returnAddress.val) if(tk.settings.ex_returnAddress.val.hasOwnProperty(i)) {
            item = tk.settings.ex_returnAddress.val[i];            
            $("#return_address__" + i).val(item);
        }
    }
    

}


ToolKit.prototype.setting = function(inSettingName, inSettingValue) {
    if(typeof(inSettingValue) != "undefined") {
        if(this.hasOwnProperty("settings")) this.settings[inSettingName].val = inSettingValue;
        else {
            $.log("Trying to set:" + inSettingName + "=" + inSettingValue + " - this setting does not exist locally", "tk.setting()" ); return(false)
        }
        ui.statusMessage("saving setting");
        this.rmi_userSetting(inSettingName, inSettingValue);
        return(inSettingValue);
    } else {
        if(!this.hasOwnProperty("settings")) {
            ui.statusMessage("we're grabbing some information from the server.<br>please try again in a moment", "error");
            this.rmi_userSetting("*");
            return(false);
        }
        if(!this.settings.hasOwnProperty(inSettingName)) {
            $.log("no tk.settings." + inSettingName, "tk.setting()");
            return(false);
        }
        return(this.settings[inSettingName].val);
    }
}





ToolKit.prototype.userSetting_cb = function(e) {
    if(!ui.ro(e)) return;
    if(typeof this.settings != "object") this.settings = {};
        
    for(var i in e.data) if(e.data.hasOwnProperty(i)) { //looping because there may be only one setting returned
        this.settings[i] = e.data[i];
    }
}


ToolKit.prototype.userType = function () {
    return(this.sUserType);
}


ToolKit.prototype.winCloseCheck = function()
{
    if(lman.dirtyLetter()) {
        return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
    }
}


