/**
 * 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: 590
    };

    /**
     * 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();
    });
}();


function resizeWindow() {
    var config = {
        height: $('#chat').height() + 120,
        width: 590
    }
    
    window.resizeTo(config.width, config.height);
}

// Should we disable the submit button
function disableSubmit() {
    if ( $('#purchase_info_wrapper').find('dd.error').length > 0 || 
         $('#typeOfHome').parent().next().attr('class') == 'error') {
        $('#submitChatLogin').attr('disabled', 'disabled');
    } else {
        $('#submitChatLogin').attr('disabled', '');
    }
}

function errorMessaging() {
    var typeOfHome   = $('#typeOfHome'),
        creditRating = $('#creditRating'),
        purchaseDate = $('#purchaseDate');

    // Type of home error displayed
    typeOfHome.bind('change', function() {
        if ( $(this).val() == 'Mobile or Manufactured' && $(this).parent().parent().find('.error').length == 0 ) {
            $(this).parent().parent().append('<dd class="error">We are not able to finance mobile manufactured \n\
                homes at this time. However, we can help you finance modular homes. If you are unsure \n\
                which type you are purchasing, call (800) 251-9080 to learn more about the loan options available!</dd>');

        } else if ( $(this).val() != 'Mobile or Manufactured' ) {
            $(this).parent().parent().find('dd.error').remove();
        }

        disableSubmit();
        resizeWindow();
    });
    
    // Credit error displayed
    creditRating.bind('change', function() {
        var lowRatings = ['Poor', 'Below average'];

        if ( $.inArray($(this).val(), lowRatings) > -1 && $(this).parent().parent().find('.error').length == 0 ) {
            $(this).parent().parent().append('<dd class="error">Thank you for your interest in Quicken Loans. \n\
                Please call (800) 251-9080 to speak with a mortgage banker to continue the process. \n\
                Check out our partner at <a href="http://www.quizzle.com/?qls=QZL_prechats.badcredits">www.quizzle.com</a> \n\
                to receive a free \n\ credit report as well as take a look at other great tools they offer.</dd>');

        } else if ( $.inArray($(this).val(), lowRatings) == -1 ) {
            $(this).parent().parent().find('dd.error').remove();
        }

        disableSubmit();
        resizeWindow();
    });
    
    // Purchase date error displayed
    purchaseDate.bind('change', function() {
        var distantDates = ['Hope to buy within 2 to 3 months', 'Not sure of timing: House hunting'];

        if ( $.inArray($(this).val(), distantDates) > -1 && $(this).parent().parent().find('.error').length == 0 ) {
            $(this).parent().parent().append('<dd class="error"><p>At this point in the home buying process we recommend that you visit our partner Quizzle at <a href="http://www.quizzle.com/?qls=QZL_prechats.purchtiming">www.quizzle.com</a> as they outline "7 Easy Steps for Home Ownership" and take you from making an offer to closing the deal!</p><p>If you’re just researching rates, check out our <a href="/mortgage-rates/current-mortgage-rates">mortgage rates page</a>.</p></dd>');

        } else if ( $.inArray($(this).val(), distantDates) == -1 ) {
            $(this).parent().parent().find('dd.error').remove();
        }

        disableSubmit();
        resizeWindow();
    });
}

// Display purchase attributes and launch error messaging
function purchaseListener() {
    var loanPurpose       = $('#loanPurpose'),
        purchaseInfoBlock = $('#purchase_info_wrapper');

    // Hide info block by default unless page loads with purchase selected
    if ( loanPurpose.val() == 'Purchase' ) {
        purchaseInfoBlock.css('display', 'block');
        setTimeout(function() {
            errorMessaging();
            resizeWindow();
        }, 100);
    } else {
        purchaseInfoBlock.css('display', 'none');
    }

    // Toggle purchase info block
    loanPurpose.bind('change', function() {
        if ( $(this).val() == 'Purchase' ) {
            purchaseInfoBlock.css('display', 'block');
        } else {
            purchaseInfoBlock.css('display', 'none');
            $('#purchase_info_wrapper dl dd select').each(function() {
                $(this).val('');
                $(this).parent().parent().find('dd.error').remove();
            });
        }
        disableSubmit();
        resizeWindow();
    });
    
    errorMessaging();
}

$(document).ready(function() {
    purchaseListener();
});
