/**
 * The Referral function handles the showing/hiding of
 * Loan Purpose blocks and the error highlighting of
 * invalid fields.
 *
 * @namespace QL.application
 * @class Referral
 * @constructor
 */
QL.application.Referral = function()
{

    /**
     * Loan purpose values.
     *
     * @property loanPurposes
     * @type Object[]
     */
    var loanPurposes = {
        purchaseBlock: [
            'Signed purchase agreement',
            'Hope to buy within 2-3 months',
            'Making an offer within 30 days',
            'Researching options',
        ],
        refinanceBlock: [
            'refinance',
            'debtconsolidation',
            'homeequitycredit'
        ]
    };

    /**
     * Default loan purpose block to display.
     *
     * @property defaultBlock
     * @type String[]
     */
    var defaultBlock = 'refinanceBlock';


    /**
     * Adds a onchange listener to the loan purpose select box.
     *
     * @method addLoanPurposeListener
     * @static
     */
    var addLoanPurposeListener = function()
    {
        $E.addListener('referral_LoanPurpose', 'change', displayValueBlockBasedOnLoanPurpose);
    }

    /**
     * Displays the appropriate block based on the selected
     * loan purpose value.
     *
     * @method displayValueBlockBasedOnLoanPurpose
     * @static
     * @param {Mixed} Event or null
     */
    var displayValueBlockBasedOnLoanPurpose = function(el)
    {
        var block, el;

        // Get loan purpose element
        if (typeof el === 'undefined') {
            el = $D.get('referral_LoanPurpose');
        } else {
            el = $E.getTarget(el);
        }
        
        if ( el.value == 'refinance' ) {
            $D.setStyle( $D.get( 'fhaBorrowerContainer' ) , 'display', 'block');
        } else {
            $D.setStyle( $D.get( 'fhaBorrowerContainer' ) , 'display', 'none');
        }
        
        // Get loan purpose block to display
        block = getLoanPurposeBlock(el);

        if (!block) {
            block = defaultBlock;
        }

        // Display the specified value block
        displayValueBlock(block);
    }

    /**
     * Gets the loan purpose block to display based
     * on the loan purpose value.
     *
     * @method getLoanPurposeBlock
     * @static
     * @param {Object}    Loan purpose element
     */
    var getLoanPurposeBlock = function(el)
    {
        if (!el) return false;

        // Look up the loan purpose block based on the loan purpose value
        for (block in loanPurposes) {
            for (var i = 0; i < loanPurposes[block].length; i++) {
                if (el.value === loanPurposes[block][i]) {
                    return block;
                }
            }
        }

        return false;
    }

    /**
     * Displays the selected value block.
     *
     * @method displayValueBlock
     * @static
     * @param {String}  block
     */
    var displayValueBlock = function(block)
    {
        if (!$D.get(block)) return false;

        // Hide all value blocks
        hideValueBlocks();

        // Display selected value block
        $D.setStyle(block, 'display', 'block');
                        
        // Set selected value block
        setSelected(block);
    };

    /**
     * Hide all value blocks.
     *
     * @method hideValueBlocks
     * @static
     */
    var hideValueBlocks = function ()
    {
        var fieldsets = $D.getElementsByClassName('block', 'fieldset');

        $D.setStyle(fieldsets, 'display', 'none');
    };

    /**
     * Sets the selected property.
     *
     * @method setSelected
     * @static
     * @param {String} selected
     */
    var setSelected = function(selected)
    {
        selectedOption = selected;
    };

    /**
     * Add the 'error' class to any fields that have
     * an error on them.
     *
     * @method highlightSubmissionErrors
     * @static
     */
    var highlightSubmissionErrors = function()
    {
        // Get DD elements with the 'error' class
        var errors = $D.getElementsByClassName('error', 'dd');

        if ( errors <= 0 ) return false;
        
        scrollTo( $D.getX( $D.get( 'referralWrapper' ) ), $D.getY( $D.get( 'referralWrapper' ) ) );

        // Add 'error' class to DL ancestors
        $D.batch(errors, function(el) {
            var ancestor = $D.getAncestorByTagName(el, 'dl');

            if (!ancestor) return false;

            $D.addClass(ancestor, 'error');
        });
    };
    
    
    /*
    * Display arm future adjusting rates in table form via modal window
    * that is displayed when clicking the future adjustments link.
    * Adds class javascript_on for css control when JS off vs JS on.
    */
    var armOverlayWindow = function()
    {
        if(!$S.query('a.activate_modal_window')) return false;
        
        /* 
        *  Add class javascript_on to add styling control when JS is on vs off.
        *  Set style visibility hidden to prevent flicker effect of container box
        *  on page load
        */
        var getContainer = $D.getElementsByClassName('container_modal_window');
        $D.addClass(getContainer, 'javascript_on');
        $D.setStyle(getContainer, 'visibility', 'hidden');

        // Loop through all links with class activate_modal_window
        $D.batch($S.query('a.activate_modal_window'), function(el){
            // Get link id, div id, and set overlay function
            var link_id = el.getAttribute('id'),
                div_id = link_id.replace('trigger-', ''),
                closeButtons = $D.getElementsByClassName('close_window'),
                myOverlay = new QL.widget.Overlay(div_id, { xy:[570,579],
                                                            visible:false,
                                                            width:'500px',
                                                            effect:{effect:QL.widget.ContainerEffect.FADE,duration:0.3} } );
            myOverlay.render();
            // Show overlay window
            $E.on(link_id, 'click', function(ev){
                $E.preventDefault(ev);
                myOverlay.show();
            }, myOverlay, true);
            // Hide overlay window
            $E.on(closeButtons, 'click', myOverlay.hide, myOverlay, true);
        });
        
        // Add class alternate to table rows for striping effect
        if(!$S.query('div.container_modal_window div.future_adjustments_wrapper table')) return false;
        
        var tableRows = $S.query('div.container_modal_window div.future_adjustments_wrapper table tbody tr');
        var odd = false;
        $D.batch(tableRows, function(el){
            if(odd == true)
            {
                $D.addClass(el, 'alternate');
                odd = false;
            }else {
                odd = true;
            }
        });
    }    

    return {

        /**
         * Displays the default value block and
         * creates the calculator chooser.
         */
        init: function()
        {
            $E.onDOMReady(function() {
                addLoanPurposeListener();

                // Displays the appropriate value block based on loan purpose value
                displayValueBlockBasedOnLoanPurpose();

                // Check for form errors
                highlightSubmissionErrors();
                
                // Display arm future adjustments modal window
                armOverlayWindow();
            });
        }()
    };

}();
