/*
 * checkout.js
 */

CAYMANCHEM.checkout = {
    label: {
        domestic:"US only",
        international:"Worldwide",
        collect:"Collect"
    },
    shippingMethods: {
        "FXP1":{
            label:"Priority One (US only)",
            collect:false,
            domestic:true
        },
        "FXP1C":{
            label:"Priority One Collect (US only)",
            collect:true,
            domestic:true
        },
        "FXSOS":{
            label:"Standard Overnight (US only)",
            collect:false,
            domestic:true
        },
        "FXSOSC":{
            label:"Standard Overnight Collect (US only)",
            collect:true,
            domestic:true
        },
        "FXPI":{
            label:"Priority One International (Worldwide)",
            collect:false,
            domestic:false
        },
        "FXPIC":{
            label:"Priority One International Collect (Worldwide)",
            collect:true,
            domestic:false
        }
    },
    creditCardTypes: {
        "AmEx":{
            label:"American Express"
        },
        "Discover":{
            label:"Discover"
        },
        "MasterCard":{
            label:"Master Card"
        },
        "Visa":{
            label:"Visa"
        }
    },
    populateCreditCardTypes: function(){
        var select = $('#creditCardType');

        //  Strip all options
        select.empty();

        //  Populate with utility options
        select.append($("<option>").attr('disabled','disabled').attr('value','').text("Pick a credit card type"));
        select.append($("<option>").attr('disabled','disabled').attr('value','').text('\u2014'));

        //  Populate select with available options
        $.each(CAYMANCHEM.checkout.creditCardTypes,function(id,creditCardType){
            select.append($("<option>").attr('id',id).attr('value',creditCardType.label).text(creditCardType.label).attr('selected', creditCardType === id ? 'selected': '' ));
        })
    },
    adjustShippingMethods: function(selectedShippingMethod,countryRegionId){
        var select = $('#shippingMethod');
        var domestic = countryRegionId === 'US';

        //  Strip all options
        select.empty();

        //  Populate with utility options
        select.append($("<option>").attr('value','').text("Pick a shipping method").attr('data-collect',false));
        select.append($("<option>").attr('value','').attr('disabled','disabled').text('\u2014').attr('data-collect',false));

        //  Populate select with options appropriate to country
        $.each(CAYMANCHEM.checkout.shippingMethods,function(id,shippingMethod){
            if( domestic === shippingMethod.domestic )
                select.append($("<option>").attr('id',id).attr('value',id).text(shippingMethod.label).attr('selected', selectedShippingMethod === id ? 'selected': '' ).attr('data-collect',shippingMethod.collect));
        })

        CAYMANCHEM.checkout.adjustFedexAccountNumber();
    },
    adjustFedexAccountNumber: function(){
        var collect = $('#shippingMethod option:selected').attr('data-collect') === 'true';

        if( collect ) {
            $('#fedexAccountNumber').removeAttr('disabled');
            $('#fedexAccountNumber,label[for="fedexAccountNumber"]').show().css('display','block');
        } else {
            $('#fedexAccountNumber').attr('disabled','disabled');
            $('#fedexAccountNumber,label[for="fedexAccountNumber"]').hide();
        }

        //  Adjust height
        CAYMANCHEM.wizard.height($('#wizard'),$('#wizard').data("scrollable").getItems().eq(0));

        //  Revalidate
        $('.error').hide();
        $('#unifiedShippingForm').data("validator").checkValidity();
    },
    adjustPurchaseOrder: function(){
        var checked = $('input[name="uop_creditCardRecId"]:checked').val() == '-1';

        if( checked ) {
            $('#uop_purchaseOrder').removeAttr('disabled');
            $('#uop_purchaseOrder,label[for="uop_purchaseOrder"]').show().css('display','block');
            $('#uop_optionalPurchaseOrder,label[for="uop_optionalPurchaseOrder"]').hide();
            $('#uop_poAddress').show();
        } else {
            $('#uop_purchaseOrder').attr('disabled','disabled');
            $('#uop_purchaseOrder,label[for="uop_purchaseOrder"]').hide();
            $('#uop_optionalPurchaseOrder,label[for="uop_optionalPurchaseOrder"]').show().css('display','block');
            $('#uop_poAddress').hide();
        }
    },

    /** Validate shipping information */
    checkShipping: function(){
        var selectedShippingCountry;
        if ($('input[name=uop_shippingAddrRecId]:checked').val() == 0)
        {
            selectedShippingCountry = $('#uop_shippingAddrCountryRegionId').val();
        }
        else
        {
            selectedShippingCountry = $('input[name=uop_shippingAddrRecId]:checked').attr('rel');
        }
        $('#shippingAddressOrig').text('' + selectedShippingCountry);
//        alert("selected shipping country: " + selectedShippingCountry);
        $('#addressVerificationWidget').overlay({
            expose: {
                color: 'rgb(13,60,99)',
                loadspeed: 100,
                opacity: 0.25
            },
            closeOnClick: false,
            load: true
        });
    },

    /** Place order */
    placeOrder: function(options){
        $.ajax({
            url: options.url,
            context: options.context,
            data: options.data,
            dataType: 'json',
            success: options.success,
            error: function(xmlHttpRequest,textStatus,errorThrown){
                location.href = options.error;
            },
            complete: function(xmlHttpRequest,textStatus){
            }
        })
    },

    /** credit card residue */
    residue: function(creditCardNumber) {
        var creditCardNumberLength = creditCardNumber.length;
        var creditCardResidue = (creditCardNumberLength > 4) ? creditCardNumber.substring(creditCardNumberLength-4) : creditCardNumber;
        return creditCardResidue;
    },

    /** Review: copy data from forms and session into review pane of scrollable */
    review: function(options){
        var shippingAddrRecId = $('input[name=uop_shippingAddrRecId]:radio:checked').val();
        
        var creditCardResidue = CAYMANCHEM.checkout.residue($('#creditCardNumber').val());

        //  --- Shipping ---

        if( shippingAddrRecId != 0 )
        {
            // Address on file
            $('#shippingAddressFormatted').html($('#shippingAddressData' + shippingAddrRecId).html());
            $('#shippingAddressFormatted').fadeIn();
            $('#shippingAddressRaw').fadeOut();
        }
        else
        {
            // New address
            $('#shippingAddressRaw').fadeIn();
            $('#shippingAddressFormatted').fadeOut();
            $('#shippingAddressInstitutionReview').text($('#uop_shippingAddrInstitution').val());
            $('#shippingAddressAttnReview').text($('#uop_shippingAddrAttention').val());
            $('#shippingAddressLine1Review').text($('#uop_shippingAddr1').val());
            $('#shippingAddressLine2Review').text($('#uop_shippingAddr2').val());
            $('#shippingAddressCityReview').text($('#uop_shippingAddrCity').val());
            if( $('#uop_shippingAddrCountryRegionId').val() === "US" ||
                $('#uop_shippingAddrCountryRegionId').val() === "CA" )
            {
                $('#shippingAddressStateReview').fadeIn();
                $('#shippingAddressStateReview').text($('#uop_shippingAddrState').val());
            }
            else
            {
                $('#shippingAddressStateReview').fadeOut();
            }
            $('#shippingAddressZipCodeReview').text($('#uop_shippingAddrZipCode').val());
            $('#shippingAddressCountryReview').text($('#uop_shippingAddrCountryRegionId').val());
        }

        $('#shippingMethodReview').text(CAYMANCHEM.checkout.shippingMethods[$('#shippingMethod').val()].label);

        if( $('#fedexAccountNumber').val() != '' )
        {
            $('#fedexAccountNumberReview').text("FedEx Account: " + $('#fedexAccountNumber').val());
            $('#fedexAccountNumberReview').fadeIn();
        }
        else
        {
            $('#fedexAccountNumberReview').fadeOut();
        }

        //  --- Billing ---

        var billingAddrRecId = $('input[name=uop_billingAddrRecId]:radio:checked').val();
        if( billingAddrRecId != 0 )
        {
            // Address on file
            $('#billingAddressFormatted').html($('#billingAddressData' + billingAddrRecId).html());
            $('#billingAddressFormatted').fadeIn();
            $('#billingAddressRaw').fadeOut();
        }
        else
        {
            // New address
            $('#billingAddressRaw').fadeIn();
            $('#billingAddressFormatted').fadeOut();
            $('#billingAddressInstitutionReview').text($('#uop_billingAddrInstitution').val());
            $('#billingAddressAttnReview').text($('#uop_billingAddrAttention').val());
            $('#billingAddressLine1Review').text($('#uop_billingAddr1').val());
            $('#billingAddressLine2Review').text($('#uop_billingAddr2').val());
            $('#billingAddressCityReview').text($('#uop_billingAddrCity').val());
            if( $('#uop_billingAddrCountryRegionId').val() === "US" ||
                $('#uop_billingAddrCountryRegionId').val() === "CA" )
            {
                $('#billingAddressStateReview').fadeIn();
                $('#billingAddressStateReview').text($('#uop_billingAddrState').val());
            }
            $('#billingAddressZipCodeReview').text($('#uop_billingAddrZipCode').val());
            $('#billingAddressCountryReview').text($('#uop_billingAddrCountryRegionId').val());
        }

        //  --- Payment ---
        var creditCardId = $('input[name=uop_creditCardRecId]:radio:checked').val();
        var optionalPurchaseOrder = $('#uop_optionalPurchaseOrder').val();
        if( creditCardId == -1 )
        {
            var purchaseOrder = $('#uop_purchaseOrder').val();
            $('#purchaseOrderReview').fadeIn();
            $('#purchaseOrderReview').text("Purchase Order " + purchaseOrder);
            $('#newCreditCardReviewContainer').fadeOut();

            // Treat like address on file
            $('#billingAddressFormatted').html($('#uop_custAccountAddress').val());
            $('#billingAddressFormatted').fadeIn();
            $('#billingAddressRaw').fadeOut();
        }
        else if( creditCardId == 0 )
        {
            $('#newCreditCardReviewContainer').fadeIn();
            $('#creditCardIdReview').fadeOut();
            var creditCardType = $('#creditCardType').val();
            $('#creditCardTypeReview').text(creditCardType);
            $('#creditCardNumberReview').text('Credit card ending in *' + creditCardResidue);
            $('#creditCardNameReview').text($('#creditCardName').val());
            $('#creditCardExpirationReview').text("Expiring on " + $('#creditCardExpirationDateMonth').val() + "/" + $('#creditCardExpirationDateYear').val());
            if (optionalPurchaseOrder)
            {
                $('#purchaseOrderReview').fadeIn();
                $('#purchaseOrderReview').text("Reference Purchase Order " + optionalPurchaseOrder);
            }
        }
        else
        {
            $('#creditCardIdReview').fadeIn();
            $('#newCreditCardReviewContainer').fadeOut();
            $('#creditCardIdReview').text("Credit card ending with " + $('#creditCardResidue' + creditCardId).text() + " expiring on " + $('#creditCardExpiration' + creditCardId).text());
            if (optionalPurchaseOrder)
            {
                $('#purchaseOrderReview').fadeIn();
                $('#purchaseOrderReview').text("Reference Purchase Order " + optionalPurchaseOrder);
            }
        }
    },

    /** Update checkout process in session */
    update: function(options){
        $.ajax({
            url: options.url,
            context: options.context,
            data: options.data,
            dataType: 'json',
            success: options.success,
            error: function(xmlHttpRequest,textStatus,errorThrown){
                alert(textStatus);
            },
            complete: function(xmlHttpRequest,textStatus){
            }
        })
    },

    dummy: true
}
