var inputFields = ['firstname','middlename','lastname','address1','city','postal','email',
                   'dayphone','nightphone','cardnumber','expmm','expyy','username','password1',
                   'password2','pin','question1','answer1','terms','resident','email2','referrer',
                   'billaddress1','billaddress2','billcity','billstate','billcountry','billpostal',
                   'discountcode','device'];

var ol_width = 300;
var ol_offsetx = 40;
var ol_offsety = -70;
var ol_closeclick = 1;
var ol_sticky = 1;
var ol_cap = 'Terms';
var ol_fgcolor = '#ABC9DE';
var ol_bgcolor = '#0a1e60';
var ol_closecolor = '#ffffff';
var ol_close = 'Close (X)';

function init()
{
    for (var i=0; i < inputFields.length; i++)
    {
        var field = getRefToDiv(inputFields[i]);
        if (field)
        {
            addEvent(field,"change",validateField);
        }
    }

    var fields = document.getElementsByName('rateplanid');
    for (i=0; i < fields.length; i++)
    {
        addEvent(fields[i],"click",validateField);
    }

    var disccode = getRefToDiv('discountcode');
    if (disccode && (disccode.value != '') && (!fields.length))
    {
        validateField2(disccode);
    }
}

function display_rateplan_description(field)
{
    var idx = field.selectedIndex;

    for (i=1; i <= rateplancnt; i++)
    {
        var name = 'rateplan_description_' + i;
        var desc = getRefToDiv(name);

        if (i == idx)
            desc.style.display = '';
        else
            desc.style.display = 'none';
     }
}

function showterms()
{
    var fields = document.getElementsByName('rateplanid');
    for (i=0; i < fields.length; i++)
        if (fields[i].checked)
        {
            document.location = 'terms?plan=' + fields[i].value;
            return;
        }

    alert('Please select a plan in order to view its Terms of Use.');
}

function promoterms()
{
    var code = getRefToDiv('discountcode').value;

    AjaxRequest.get(
      {
        'url' : 'ax_getpromoterms',
        'code' : code,
        'onSuccess' : setPromoTerms
      }
    );
}

function copy_address(chk)
{
    if (chk.checked)
    {
        getRefToDiv('billaddress1').value        = getRefToDiv('address1').value;
        getRefToDiv('billaddress2').value        = getRefToDiv('address2').value;
        getRefToDiv('billcity').value            = getRefToDiv('city').value;
        getRefToDiv('billstate').selectedIndex   = getRefToDiv('state').selectedIndex;
        getRefToDiv('billcountry').selectedIndex = getRefToDiv('country').selectedIndex;
        getRefToDiv('billpostal').value          = getRefToDiv('postal').value;
    }
}

function selectcard(model)
{
    var card = getRefToDiv('3gcard');
    card.value = model;

    validateForm();
}

function getErrorObj(field)
{
    var obj = getRefToDiv(field.id+'Msg');

    if ((field.name == 'expmm') || (field.name == 'expyy'))
        obj = getRefToDiv('cardexpMsg');

    return obj;
}

function clearError(field,msg)
{
    try
    {
        if (!field)
            return;

        field.style.backgroundColor = '#fff';

        var fieldMsg = getErrorObj(field);

        // Special case for CardExp
        if ((field.name == 'expmm') || (field.name == 'expyy'))
        {
            var mm   = getRefToDiv('expmm').value;
            var yyyy = getRefToDiv('expyy').value;

            if ((mm == '') || (yyyy == ''))
            {
                if (fieldMsg)
                    fieldMsg.style.display = 'none';

                return;
            }
        }

        // Special case for rateplan
        if (field.id.indexOf('rateplanid') >= 0)
        {
            // Determine next step
            if (msg == '')
                getRefToDiv('nextstep').value = 'full';
            else
                getRefToDiv('nextstep').value = msg;

            if (fieldMsg)
                fieldMsg.style.display = 'none';

            // Re-validate discount code
            var code = getRefToDiv('discountcode');
            if (code)
            {
                if (code.value != '')
                    validateField2(code);
            }

            return;
        }

        if (fieldMsg)
        {
            fieldMsg.style.display = 'none'

            if (msg != '')
            {
                fieldMsg.innerHTML = msg;
                fieldMsg.style.display = '';
            }
        }
    }
    catch (e)
    {
        //alert("clearError - " + e.name + ": " + e.message);
    }
}

function setError(field,msg)
{
    try
    {
        if (!field)
            return;

        // Special case for duplicate email
        if (field.name == 'checkdup')
        {
            var checkdup = getRefToDiv('checkdup');

            if (confirm(msg))
            {
                checkdup.value = '0';
                validateForm();
            }

            return;
        }

        field.style.backgroundColor = '#f99';

        var fieldMsg = getErrorObj(field);
        if (fieldMsg)
        {
            fieldMsg.style.display = '';
            fieldMsg.innerHTML = msg;
        }
    }
    catch (e)
    {
        //alert("setError - " + e.name + ": " + e.message);
    }
}

function updateState()
{
    var country = '';

    if (getRefToDiv("country"))
        country = getRefToDiv("country").value;

    AjaxRequest.get(
      {
        'url' : 'ax_getstates',
        'country' : country,
        'onSuccess' : setStateSuccess
      }
    );
}

function updateCountry()
{
    var state = '';
    var country = '';

    if (getRefToDiv("state"))
    {
        state = getRefToDiv("state").value;
        if (state == '')
            return;
    }

    if (getRefToDiv("country"))
        country = getRefToDiv("country").value;

    AjaxRequest.get(
      {
        'url' : 'ax_getcountries',
        'state' : state,
        'country' : country,
        'onSuccess' : setCountrySuccess
      }
    );
}

function validateField(oEvent)
{
    oEvent = oEvent || window.event;
    var field = oEvent.target || oEvent.srcElement;

    validateField2(field);
}

function validateField2(field)
{
    var oForm = getRefToDiv('signupform');

    AjaxRequest.submit(
      oForm,
        {
            'url' : 'validateSignup',
            'key' : field.name,
            'onSuccess' : setValidateSuccess
        }
    );
}

function validateForm()
{
    var oForm = getRefToDiv('signupform');

    // Disable submit button
    var btn = getRefToDiv("submitbtn");
    if (btn)
        btn.disabled = true;

    // Display wait message
    var wait = getRefToDiv("submitwait");
    if (wait)
        wait.style.display = '';

    AjaxRequest.submit(
      oForm,
        {
            'url' : 'validateSignup',
            'onSuccess' : setValidateSuccess
        }
    );

    return false;
}

function setStateSuccess(ajaxRequest)
{
    var state = getRefToDiv("states");
    state.innerHTML = ajaxRequest.responseText;
}

function setCountrySuccess(ajaxRequest)
{
    var country = getRefToDiv("countries");
    country.innerHTML = ajaxRequest.responseText;
}

function setPromoTerms(ajaxRequest)
{
    overlib(ajaxRequest.responseText);
}

function setValidateSuccess(ajaxRequest)
{
    try
    {
        //alert(ajaxRequest.responseText);
        var json_data = json_parse(ajaxRequest.responseText);

        if (json_data.errors)
        {
            for (var key in json_data.errors)
            {
                var field = getRefToDiv(key);
                var msg = json_data.errors[key];
                setError(field, msg);
            }

            // Hide wait message
            var wait = getRefToDiv("submitwait");
            if (wait)
                wait.style.display = 'none';

            // Re-enable submit button
            var btn = getRefToDiv("submitbtn");
            if (btn)
                btn.disabled = false;
        }
        else if (json_data.key)
        {
            var key = json_data.key;
            var field = getRefToDiv(key);

            if (json_data.notice)
            {
                var msg = json_data.notice[key];
                clearError(field, msg);
            }
            else
            {
                clearError(field, '');
            }
        }
        else
        {
            // Hide wait message
            var wait = getRefToDiv("submitwait");
            if (wait)
                wait.style.display = 'none';

            var nextstep = getRefToDiv("nextstep");
            if (nextstep)
            {
                if (nextstep.value == 'card')
                    document.location = 'selectcard_html';
                else if (nextstep.value == 'full')
                    document.location = 'signup_html';
                else if (nextstep.value == 'personal')
                    document.location = 'signup_personal';
                else if (nextstep.value == 'billing')
                    document.location = 'signup_billing';
                else if (nextstep.value == 'success')
                    document.location = 'signupsuccess';
            }
            else
            {
                document.location = 'signupsuccess';
            }
        }
    }
    catch (e)
    {
        //alert("setValidateSuccess - " + e.name + ": " + e.message);
    }
}
