cmLoginCopyReqEmail = '';
cmLoginCopyReqPwd = '';
cmLoginCopyInvalidEmail = '';
cmAccountCopyReqEmail = '';
cmAccountCopyReqPwd = '';
cmAccountCopyReqPwdConfirm = '';
cmAccountCopyInvalidEmail = '';
cmAccountCopyInvalidPwdMatch = '';
cmAccountCopyInvalidZipLength = '';

jQueryCM(document).ready(function() {
    cmSetLang(lang);
});

// loads the cmUser div
function cmSetUser() {
    if (jQueryCM('#cmUser').length != 0) {
        jQueryCM.getJSON(cmWebRoot+"/ws_user.php?&callback=?", function(data){
            cmProcessUserLoginJSON(data);
            return false;
        });
    } else {
        // there's no login div, so just check if the user is_logged_in and load the content
        jQueryCM.getJSON(cmWebRoot+"/ws_user.php?is_logged_in=1&callback=?", function(data){
            if (data['is_logged_in'] && data['is_logged_in'] == 1 && jQueryCM.isFunction(cmAltContent)) {
                cmAltContent();
            } else {
                // refresh the account DIV
                if (jQueryCM('#cmAccount').length != 0) {
                    jQueryCM.getJSON(cmWebRoot+"/ws_account.php?&callback=?", function(data){
                        cmProcessUserAccountJSON(data);
                        return false;
                    });
                } else if (jQueryCM.isFunction(cmSetContent)) {
                    cmSetContent();
                }
            }
            return false;
        });
    }
}

// this function will also check the "logged in" state of the user in the WS call
// we should probably rename the function to something more like "cmInitPage", but I ran out of time.  :(
function cmSetLang(newLang) {
    if (newLang.length != 0) {
        jQueryCM.getJSON(cmWebRoot+"/ws_user.php?lang=1&newLang="+newLang+"&callback=?", function(data){
            lang = data['lang'];
            if (jQueryCM.isFunction(cmClient_onLoad)) { cmClient_onLoad(data['is_logged_in']); }
            cmSetUser();
            return false;
        });
    }
}

function cmProcessUserLoginJSON(data) { 
    if (cmDebug) { alert('DEBUG (userLogin): '+data['debug']); }
    
    // write the html
    jQueryCM("#cmUser").html(data['html']);
    
    // update/enable the 'account' page link
    if (cmPartnerAcctPage.length != 0) {
        cmAcctPage = cmPartnerAcctPage;
        if (lang == 'es' && cmPartnerAcctPageES.length != 0) {
            cmAcctPage = cmPartnerAcctPageES;
        }
        jQueryCM("#cmUserAcctURL").attr("href", cmAcctPage);     // login.tpl
        jQueryCM(".cmPartnerAcctPage").css("display","block");
    }

    // check to see if the user changed states and the following function exists
    // if so... then cmContent was loaded, so execute it to change to the "logged in/out" content
    if(data['altContent'] && data['altContent'] == 1 && jQueryCM.isFunction(cmAltContent)) {
        cmAltContent();
    // else, just try load the content
    } else if(!data['error'] && jQueryCM.isFunction(cmSetContent)) {
        cmSetContent();
    }

    if (data['error'] && data['errorCopy']) {
        // write the error html
        jQueryCM("#cmUserSubmitError").html(data['errorCopy']['login']['cmLoginCopyInvalidEmailOrPwd']);
        jQueryCM("#cmUserSubmitError").show("slow");
    } else {
        // refresh the account DIV
        if (jQueryCM('#cmAccount').length != 0) {
            jQueryCM.getJSON(cmWebRoot+"/ws_account.php?&callback=?", function(data){
                cmProcessUserAccountJSON(data);
                return false;
            });
        }
        if (jQueryCM.isFunction(cmSetContent)) {
            cmPrevNext['flow'] = [];
        }
    }
    
    // load the validator error copy
    if (data['errorCopy']) {
        if (data['errorCopy']['login']) {
            cmLoginCopyReqEmail     = data['errorCopy']['login']['cmLoginCopyReqEmail'];
            cmLoginCopyReqPwd       = data['errorCopy']['login']['cmLoginCopyReqPwd'];
            cmLoginCopyInvalidEmail = data['errorCopy']['login']['cmLoginCopyInvalidEmail'];
        }
        if (data['errorCopy']['account']) {
            cmAccountCopyReqEmail = data['errorCopy']['account']['cmAccountCopyReqEmail'];
            cmAccountCopyReqPwd = data['errorCopy']['account']['cmAccountCopyReqPwd'];
            cmAccountCopyReqPwdConfirm = data['errorCopy']['account']['cmAccountCopyReqPwdConfirm'];
            cmAccountCopyInvalidEmail = data['errorCopy']['account']['cmAccountCopyInvalidEmail'];
            cmAccountCopyInvalidPwdMatch = data['errorCopy']['account']['cmAccountCopyInvalidPwdMatch'];
            cmAccountCopyInvalidZipLength = data['errorCopy']['account']['cmAccountCopyInvalidZipLength'];
        }
    }

    // instantiate the validator
    jQueryCM("#cmLogin").validate({
		errorContainer: "#cmUserMsgBox",
		errorLabelContainer: "#cmUserValidateError",
   		wrapper: "li",
		messages: {
            username: {
                required: cmLoginCopyReqEmail,
                email: cmLoginCopyInvalidEmail
            },
            pwd: {required: cmLoginCopyReqPwd}
		}
	});
    
    // bind the form and provide a simple callback function 
    jQueryCM('#cmLogin').ajaxForm({
        dataType:       'jsonp',
        success:        cmProcessUserLoginJSON,
        beforeSubmit:   cmPreProcessRequest,
        type:           'get',
        url:            cmWebRoot+'/ws_user.php',
        clearForm:      true,
        timeout:        3000
    });
    
    // execute any callbacks
    jQueryCM.each(data['callback'], function (k,v) {
        if (cmDebug) { alert('CALLBACK: '+v); }
        eval(v);
    });

    // execute any partner specific callbacks
    if (data['status'] && data['status'].length != 0 && jQueryCM.isFunction(cmClient_onAuth)) {
        cmClient_onAuth( data['status'] );
    }
}

function cmProcessUserAccountJSON(data) { 
    if (cmDebug) { alert('DEBUG (userAccount): '+data['debug']); }
    
    // write the html
    jQueryCM("#cmAccount").html(data['html']);

    // write the error html
    if (data['error']) {
        jQueryCM("#cmAccountError").html(data['error']);
        jQueryCM("#cmAccountError").show(1000);
    }
    
    // instantiate the validator
    jQueryCM("#cmRegistration").validate();
    
    // bind the form and provide a simple callback function 
    jQueryCM('#cmRegistration').ajaxForm({
        dataType:       'jsonp',
        success:        cmProcessUserAccountJSON,
        beforeSubmit:   cmPreProcessRequest,
        type:           'get',
        url:            cmWebRoot+'/ws_account.php',
        clearForm:      true,
        timeout:        3000
    });
    
    // execute any callbacks
    jQueryCM.each(data['callback'], function (k,v) {
        if (cmDebug) { alert('CALLBACK: '+v); }
        eval(v);
    });

    // execute any partner specific callbacks
    if (data['status'] && data['status'].length > 0 && jQueryCM.isFunction(cmClient_onAccount)) {
        cmClient_onAccount( data['status'] );
    }
}
