var mainForm;

var couponMaskAppliesToDomainNameRegistration = 1;
var couponMaskAppliesToDomainNameTransfer = 2;
var couponMaskAppliesToPackage = 4;
var couponMaskAppliesToPackageSetup = 7;
var couponMaskAppliesToAddons = 16;
var couponMaskAppliesToAddonsSetup = 32;
var couponMaskAppliesToOther = 64;

// State vars
var validateCouponCount = false;
var couponArr = new Array();
var taxRate = 0;
var taxRateDisp = 0;

function BackStepTwo()
{
    if (mainForm.hasDomainNameRegistration.value) {
        mainForm.step.value=1;
    } else {
        mainForm.step.value=0;             
        mainForm.clienttype.value=0;
        mainForm.package.options[mainForm.package.selectedIndex].value =0;                    
    }

    mainForm.submit();
}

function RecalculatePage()
{
    mainForm.step.value = 2;
    mainForm.submit();
}

function regenerateBill()
{
    var domainNameRegistrationFee = 0;
    var packageUnproratedFee = 0;
    var packageProratedFee = 0;
    var packageSetupFee = 0;
    var packageAddonsUnproratedFee = 0;
    var packageAddonsProratedFee = 0;
    var packageAddonsSetupFee = 0;
    var discount = 0;
    var taxes = 0;

    // domain name registration
    if (mainForm.hasDomainNameRegistration.value) {
        var domainData = mainForm.domainperiod.value.split('|');
        domainNameRegistrationFee = parseFloat(domainData[1]);
        if (mainForm.domainTaxable.value != "0") {
            taxes += domainNameRegistrationFee * taxRate;
        }
        $('checkoutDomainNameRegistrationFee').innerHTML = formatAsMoney(domainNameRegistrationFee, true);
        var spans = $('checkoutDomainNameRegistration').getElementsByTagName("span");
        if (domainData[0] == 0){
            spans[0].innerHTML = lang("One time payment");
        } else if (domainData[0] == 1) {
            spans[0].innerHTML = "1 " + lang('Year');
        } else {
            spans[0].innerHTML = domainData[0] + " " + lang('Years');
        }
        $('checkoutDomainNameRegistration').style.display = "block";
    }
    // package prorated fee
    if (mainForm.prorating.value && mainForm.packageProratedFee.value) {
        packageProratedFee = parseFloat(mainForm.packageProratedFee.value);
        if (mainForm.packageTaxable.value != "0") {
            taxes += packageProratedFee * taxRate;
        }
        $('checkoutPackageProratedFee').innerHTML = formatAsMoney(packageProratedFee, true);
        $('checkoutPackageProrated').style.display = "block";
    }

    // package unprorated fee
    if (mainForm.packageUnproratedFee.value != 0 || mainForm.includeFollowingPayment.value != 0) {
        packageUnproratedFee = parseFloat(mainForm.packageUnproratedFee.value);
        if (mainForm.packageTaxable.value != "0") {
            taxes += packageUnproratedFee * taxRate;
        }
        $('checkoutPackageUnproratedFee').innerHTML = formatAsMoney(packageUnproratedFee, true);
        $('checkoutPackageUnprorated').style.display = "block";
    }

    // package setup fee
    if (mainForm.packageSetupFee.value > 0) {
        packageSetupFee = parseFloat(mainForm.packageSetupFee.value);
        if (mainForm.packageTaxable.value != "0") {
            taxes += packageSetupFee * taxRate;
        }
        mainForm.setup.value = packageSetupFee;
        $('checkoutPackageSetupFee').innerHTML = formatAsMoney(packageSetupFee, true);
        $('checkoutPackageSetup').style.display = "block";
    }

    // package add-on fees
    if (mainForm.addonsRadioButtons.value == "1") {
        var addonHolders = document.getElementsByTagName('input');
    } else {
        var addonHolders = document.getElementsByTagName('select');
    }
    var addonChargesArr = new Array();
    var addonRecurringCharges = new Array(-1, 0, -1, 0, -1, -1, 0, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0);
    for (var i = 0; i < addonHolders.length; i++) {
        if (addonHolders[i].name.indexOf('addonSelect') == -1) {
            continue;
        }

        if (mainForm.addonsRadioButtons.value == "1" && !addonHolders[i].checked) {
            continue;
        }

        var selectedAddonArr = addonHolders[i].value.split('_');
        addonChargesArr.push(selectedAddonArr[1] + '_' + selectedAddonArr[2] + '_' + selectedAddonArr[3]);

        if (mainForm.prorating.value == "0" || mainForm.includeFollowingPayment.value) {
            var addonFee = addonRecurringPrices[selectedAddonArr[1]][selectedAddonArr[2]][selectedAddonArr[3]].fullPrice;
            addonRecurringCharges[selectedAddonArr[3]] += addonFee;
            packageAddonsUnproratedFee += addonFee;
            if (addonTaxable[selectedAddonArr[1]]) {
                taxes += addonFee * taxRate;
            }
        }
        if (mainForm.prorating.value) {
            packageAddonsProratedFee += addonRecurringPrices[selectedAddonArr[1]][selectedAddonArr[2]][selectedAddonArr[3]].proratedPrice;
            if (addonTaxable[selectedAddonArr[1]]) {
                taxes += addonRecurringPrices[selectedAddonArr[1]][selectedAddonArr[2]][selectedAddonArr[3]].proratedPrice * taxRate;
            }
        }
        packageAddonsSetupFee += addonSetupPrices[selectedAddonArr[1]][selectedAddonArr[2]];
        if (addonTaxable[selectedAddonArr[1]]) {
            taxes += addonSetupPrices[selectedAddonArr[1]][selectedAddonArr[2]] * taxRate;
        }
    }
    mainForm.addonChargesStr.value= addonChargesArr.join('|');
    if (packageAddonsProratedFee) {
        $('checkoutPackageAddonProratedFee').innerHTML = formatAsMoney(packageAddonsProratedFee, true);
        $('checkoutPackageAddonProrated').style.display = "block";
    } else {
        $('checkoutPackageAddonProrated').style.display = "none";
    }
    if (packageAddonsUnproratedFee) {
        for (var i = 0; i < addonRecurringCharges.length; i++) {
            if (addonRecurringCharges[i] > 0) {
                $("checkoutPackageAddonUnproratedFee_" + i).innerHTML = formatAsMoney(addonRecurringCharges[i], true);
                $("checkoutPackageAddonUnprorated_" + i).style.display = "block";
            } else if (addonRecurringCharges[i] == 0) {
                $("checkoutPackageAddonUnprorated_" + i).style.display = "none";
            }
        }
    } else {
        for (var i = 0; i < addonRecurringCharges.length; i++) {
            if (addonRecurringCharges[i] == 0) {
                $("checkoutPackageAddonUnprorated_" + i).style.display = "none";
            }
        }
    }
    if (packageAddonsSetupFee) {
        $('checkoutPackageAddonSetupFee').innerHTML = formatAsMoney(packageAddonsSetupFee, true);
        $('checkoutPackageAddonSetup').style.display = "block";
    } else {
        $('checkoutPackageAddonSetup').style.display = "none";
    }

    // coupon before taxes
    if (couponArr.length > 0) {
        if (couponArr[2] == 0) {
            discount = couponArr[4];
        } else {
            if (mainForm.transfer.value == "0" && (couponArr[3] & couponMaskAppliesToDomainNameRegistration)) {
                discount += domainNameRegistrationFee * couponArr[4];
            }
            if (mainForm.transfer.value == "1" && (couponArr[3] & couponMaskAppliesToDomainNameTransfer)) {
                discount += domainNameRegistrationFee * couponArr[4];
            }
            if (couponArr[3] & couponMaskAppliesToPackage) {
                discount += (packageUnproratedFee + packageProratedFee) * couponArr[4];
            }
            if (couponArr[3] & couponMaskAppliesToPackageSetup) {
                discount += packageSetupFee * couponArr[4];
            }
            if (couponArr[3] & couponMaskAppliesToAddons) {
                discount += (packageAddonsUnproratedFee + packageAddonsProratedFee) * couponArr[4];
            }
            if (couponArr[3] & couponMaskAppliesToAddonsSetup) {
                discount += packageAddonsSetupFee * couponArr[4];
            }
        }

        if (discount > 0) {
            mainForm.discount.value = -discount;
        }

        if (couponArr[8] == 1) {
            taxes -= discount * taxRate;

            $('checkoutDiscountPreTaxesFee').innerHTML = (discount > 0? "- " : "") + formatAsMoney(discount, true);
            $('checkoutDiscountPreTaxesName').innerHTML = couponArr[0];
            $('checkoutDiscountPreTaxes').style.display = "block";
        }
    }

    // Subtotal
    var subtotal =  domainNameRegistrationFee
                    + packageUnproratedFee
                    + packageProratedFee
                    + packageSetupFee
                    + packageAddonsUnproratedFee
                    + packageAddonsProratedFee
                    + packageAddonsSetupFee;
    if (couponArr.length > 0 && couponArr[8] == 1) {
        subtotal -= discount;
    }
    $("checkoutSubtotalAmount").innerHTML = formatAsMoney(subtotal, true);

    // taxes
    $('checkoutTaxes').style.display = "none"; // reset
    if (taxes) {
        $('checkoutTaxesRate').innerHTML = taxRateDisp;
        $('checkoutTaxesAmount').innerHTML = formatAsMoney(taxes, true);
        $('checkoutTaxes').style.display = "block";
    }

    // coupon after taxes
    if (couponArr.length > 0 && couponArr[8] == 0) {
        $('checkoutDiscountPostTaxesFee').innerHTML = (discount > 0? "- " : "") + formatAsMoney(discount, true);
        $('checkoutDiscountPostTaxesName').innerHTML = couponArr[0];
        $('checkoutDiscountPostTaxes').style.display = "block";
    }

    // Total
    var total = domainNameRegistrationFee
                + packageUnproratedFee
                + packageProratedFee
                + packageSetupFee
                + packageAddonsUnproratedFee
                + packageAddonsProratedFee
                + packageAddonsSetupFee
                - discount
                + taxes;
    mainForm.totalBill.value = total;
    $('checkoutTotalFee').innerHTML = formatAsMoney(total, true);
}

function formatAsMoney(mnt, format)
{
    mnt -= 0;
    var currencyPrecision = mainForm.currencyprecision.value;
    
    // prevent rounding issue
    factor = Math.pow(10, currencyPrecision);
    mnt += 1 / (factor * 1000);
    mnt = Math.round(mnt * factor) / factor;
    // end rounding fix
    
    var tmnt = mnt;
    for (var i=0; i < currencyPrecision; i++){
        if(intPow(mnt, 10, i) == Math.floor(intPow(mnt, 10, i))){
            if(i == 0){
                tmnt += '.';
            }
            for (var j=0; j < currencyPrecision - i; j++){
                tmnt += '0';
            }
            break;
        }
    }
    
    if(format){
        if(mainForm.currencyalignment.value == 'left'){
            return mainForm.currencysymbol.value + tmnt;
        }else{
            return tmnt + mainForm.currencysymbol.value;
        }
    }else{
        return tmnt;
    }
}

// use only integers exponents
function intPow(number, base, exponent)
{
    var result = number;
    if(exponent > 0){
        for(var i=0; i<exponent; i++){
            result *= base;
        }
    }else if(exponent < 0){
        for(var i=0; i>exponent; i--){
            result /= base;
        }
    }
    return result;
}

function validateCoupon(form)
{   
    validateCouponCount = true;
    if (!form.coupon_code.value) {
        return;
    }

    var couponCode = encodeURIComponent(form.coupon_code.value);
    var clientType = encodeURIComponent(form.clienttype.value);
    // 'package' must be quoted or I get an error
    var plan = encodeURIComponent(form.elements['package'].value);
    if (typeof form.paymentterm == 'undefined') {
        var billingCycle = 0;
    } else {
        var billingCycle  = encodeURIComponent(form.paymentterm.value);
    }

    new Ajax.Request('index.php?fuse=clients&view=ValidateCoupon',
                     {parameters    : 'code='+couponCode+'&clienttype='+clientType+'&plan='+plan+'&billingcycle='+billingCycle,
                      onLoading     : function(){resetStatus(lang('Validating'))},
                      onComplete    : applyDiscount});
}

function applyDiscount(responseObj)
{
    unsetStatus(false);

    var responseArr = responseObj.responseText.split('|');

    couponArr = responseArr;
    
    if (couponArr == '0') {
        $('invalid_code').style.visibility = 'visible';
        return;
    }

    if (couponArr[2] != '0') {
        var discount = couponArr[4]*100+'%';
        var langDiscount = couponArr[4]*100; // can't pass % to lang()
    } else {
        var discount = formatAsMoney(couponArr[4], true);
        var langDiscount = discount;
    }

    $('invalid_code').style.visibility = 'hidden';
    $('coupon_name').innerHTML = couponArr[0] + ': '+discount+' '+lang('off');

    if (couponArr[2] != 0 &&  couponArr[3] != (  couponMaskAppliesToDomainNameRegistration
                                                | couponMaskAppliesToDomainNameTransfer
                                                | couponMaskAppliesToPackage
                                                | couponMaskAppliesToPackageSetup
                                                | couponMaskAppliesToAddons
                                                | couponMaskAppliesToAddonsSetup
                                                | couponMaskAppliesToOther))
    {
        var appliesTo = new Array();
        if (couponArr[3] & couponMaskAppliesToDomainNameRegistration) {
            appliesTo.push(lang("Domain Name Registration Fees"));
        }
        if (couponArr[3] & couponMaskAppliesToDomainNameTransfer) {
            appliesTo.push(lang("Domain Name Transfer Fees"));
        }
        if (couponArr[3] & couponMaskAppliesToPackage) {
            appliesTo.push(lang("Package Fees"));
        }
        if (couponArr[3] & couponMaskAppliesToPackageSetup) {
            appliesTo.push(lang("Package Setup Fees"));
        }
        if (couponArr[3] & couponMaskAppliesToAddons) {
            appliesTo.push(lang("Package Add-on Fees"));
        }
        if (couponArr[3] & couponMaskAppliesToAddonsSetup) {
            appliesTo.push(lang("Package Add-on Setup Fees"));
        }

        $('coupon_name').innerHTML += ' ' + lang('on %', appliesTo.join(", "));
    }

    if (couponArr[5] != '0') {
        $('coupon_name').innerHTML += ' '+lang('on every periodic payment');
        if (couponArr[7] != '0') {
            $('coupon_name').innerHTML += ' '+lang('during % month(s), as follows:', couponArr[7])+'<br />';
            $('coupon_name').innerHTML += lang('* % discount(s) of %', Math.ceil(couponArr[7]/couponArr[9]), langDiscount) + (couponArr[2] != 0? '%' : "");
            $('coupon_name').innerHTML += ', '+lang('1 discount every % month(s)', couponArr[9]);
        }
    }

    regenerateBill();
}

function getTax()
{
    var country = "";
    var state = "";
    if (typeof countryVAR != 'undefined' && mainForm.elements[countryVAR] !=null){
        country = mainForm.elements[countryVAR].value;         
    }
    if (typeof stateVAR != 'undefined' && mainForm.elements[stateVAR] !=null){
        state = mainForm.elements[stateVAR].value;
    }

    if (country) {
        new Ajax.Request(   'index.php?fuse=clients&action=GetTax&country='+country+'&state='+state,
                            {   onSuccess   : setTax}
        );
    } else {
        regenerateBill();
    }
}

function setTax(responseObj)
{
    mainForm.taxrate.value = responseObj.responseText;
    taxRateDisp = responseObj.responseText;
    taxRate = parseFloat(responseObj.responseText) / 100;
    regenerateBill();
}

function ConfirmLogin_Callback(responseObj)
{
    //>0 = User is valid
    //0 = User is invalid
    var userid = responseObj.responseText;
    if (userid>0){
        $('membervalid').innerHTML = '';
        country = document.forms['accountinfo'].elements['memberuserid'].value=userid;
        document.forms['accountinfo'].submit();                 
    }else{
        $('membervalid').innerHTML = '<font color=red>'+lang('Invalid login information, please contact support for assistance')+'</font>';
    }
}

function ConfirmLogin()
{
    new Ajax.Request(   'index.php?fuse=clients&action=ConfirmLogin',
                        {parameters     : 'memberEmail=' + document.forms['accountinfo'].elements['member_email'].value + '&passwd=' + document.forms['accountinfo'].elements['member_password'].value,
                         onComplete     : ConfirmLogin_Callback});
}

function SubmitStepTwo()
{
    if (document.getElementById('coupon_code')) {
        if(document.forms['accountinfo'].elements['coupon_code'].value && !validateCouponCount){
            if(confirm("You inserted a coupon code, but it has not validated. Do you want valide the coupon now?")){
                validateCoupon(document.forms['accountinfo']);
            }
        }
    }
    if(document.forms['accountinfo'].elements['member'].checked){
        // check if domaim credentials have to be entered
        if (document.getElementById("domainCredentials")) {
            if ($("new_domain_username").value == "" || $("new_domain_password").value == "") {
                alert(lang("Please fill the domain username and password"));
                return false;
            }
        }

        //check to see if their member information is accurate
        ConfirmLogin();
    }else{
        check(document.forms['accountinfo'],document.forms['accountinfo'].elements.length);                 
    }
    return false;
}

function SwitchRecurringVisibility(paymentGateway) 
{
    field = $('recurringField');
    if (paymentGateway.value.indexOf('paypal') != -1) {
        // don't allow paypal subscriptions when trial period > 90
        subscriptionsDisabled = $('disablesubscriptions');
        if ( subscriptionsDisabled.value == '1') return;
        
        field.style.display = '';
    } else {
        field.style.display = 'none';
    }
}
