/**
 * InstantService Object
 *
 * This object handles instant service interaction on the 
 * Quicken Loans website. It provides methods to attach 
 * chat invites to the document, as well as handling 
 * manual chat triggers, and helper methods to address 
 * pop up window generation and resizing.
 *
 * @namespace QL.vendors
 * @class InstantService
 * @constructor
 */

if (typeof(QL.vendors) === 'undefined') {
    QL.namespace('vendors');
}

QL.vendors.InstantService = function()
{

    /**
     * Chat window attributes
     *
     * @param   {Object}
     */
    var windowAttributes = {
        center: true,
        height: 455,
        name: 'INSTANT_SERVICE_CHAT',
        scrollbars: 0,
        width: 530
    };

    /**
     * Adds a listener to the document to handle any link with a
     * 'chat' class.
     *
     * @method addChatLinkListener
     * @static
     */
    var addChatLinkListener = function()
    {
        $E.addListener(document, 'click', function(e) {
            // Get element
            var el = $E.getTarget(e);

            if (el.nodeName.toLowerCase() === 'a' && $D.hasClass(el, 'chat')) {
                // Stop event
                $E.preventDefault(e);

                // Pop window
                QL.utilities.Window.open(el.getAttribute('href', 1), windowAttributes);
            }
        });
    };

	var selectSpecificDepartment = function()
	{
		if ( !$D.get( 'chat' ) || !$D.get( 'department_id' ) || !$D.get( 'state' ) || !$D.get( 'loanPurpose' ) ) return false;
		
		$E.on( $D.get( 'chat' ), 'submit', function( ev ) {		
    		switch ( $D.get( 'loanPurpose' ).value ) {
    		    case 'Refinance':
        		    if( qlRefinanceStateBasedDepartmentIds[ $D.get( 'state' ).value ] ) {
        			    $D.get( 'department_id' ).value = qlRefinanceStateBasedDepartmentIds[ $D.get( 'state' ).value ];
        			}
        			
        			if( !qlRefinanceStateBasedDepartmentIds[ $D.get('state').value ] ) {
        			    $D.get( 'department_id' ).value = '20067';
        			}
    		    break;
		    
                case 'Purchase':
                    if( qlPurchaseStateBasedDepartmentIds[ $D.get( 'state' ).value ] ) {
                        $D.get( 'department_id' ).value = qlPurchaseStateBasedDepartmentIds[ $D.get( 'state' ).value ];
                    }
                                        
                    if( !qlPurchaseStateBasedDepartmentIds[ $D.get('state').value ] ) {
                        $D.get( 'department_id' ).value = '20067';
                    }
                break;
                
                case 'Purchase w/Signed Purchase Agreement':
                    if( qlPurchaseStateBasedDepartmentIds[ $D.get( 'state' ).value ] ) {
                        $D.get( 'department_id' ).value = qlPurchaseStateBasedDepartmentIds[ $D.get( 'state' ).value ];
                    }
                    
                    if( !qlPurchaseStateBasedDepartmentIds[ $D.get('state').value ] ) {
                        $D.get( 'department_id' ).value = '20067';
                    }
                break;

    		    default:
    		        /* this should never happen since loan purpose is required, but just in case a loan purpose
    		        is not selected, set 20067 (general sales department) as the department ID */
                    $D.get( 'department_id' ).value = '20067';
    		    break;
    		};
		} );
	};

    /**
     * Resizes the browser window based on the existence of errors in
     * the form. This is to accomodate the growing/shrinking of the form
     * element.
     *
     * @method resizeWindowOnErrors
     * @static
     */
    var resizeWindowOnErrors = function()
    {
        if (!$D.get('chat')) return false;

        // Get error elements if they exist
        var errors = $D.getElementsByClassName('error', 'dd');

        if (errors.length === 0) return false;

        // Set new window height
        if (errors.length > 1) {
            windowAttributes.height += 120;
        } else {
            windowAttributes.height += 80;
        }

        // Resize window
        window.resizeTo(windowAttributes.width, windowAttributes.height);
    };

	/**
	 * SWAT 137711 - due to default behavior browser variances ie6 and ie7.
	 * Pass the referring URL to the chat survey popup window by grabbing the location of the parent window
	 * and writing it to the hidden field on the chat survey. Upon submission of the chat survey popup this
	 * value gets submitted to the instant service console.
	 * @method passReferer
	 */
	
	var passReferer = function()
	{
		if(!$D.get('referer')) return false;
		
		// get the hidden field element
		var refererField = $D.get('referer');
	
		// default value
		var parentWindowLocation = 'direct page hit';

		// if a parent window exists get the location of it
		if (window.opener) {
			parentWindowLocation = window.opener.location;			
		}

		//write the value to the hidden field
		refererField.value = parentWindowLocation;
		
	}

    $E.onDOMReady(function() {
        QL.utilities.Form.focusOnFirstElement( 'chat' );
        addChatLinkListener();
        resizeWindowOnErrors();
		passReferer();
    });
}();