(function($){
    /* Functional Utilities */
    $.fn.extend({
        /*
         * Opens links into a new window by calling isExternalLink
         * and checking the hrefs if they will open in an external window
         * or not. (.pdf file only for now)
         */
        isExternalLink: function() {
            var url = window.location.hostname;

            if( (this.attr('href') != undefined) && (!this.attr('href').match(/javascript/)) && ((this.attr('href').match(/\.pdf/)) || ( url != this.attr('hostname')) ) ) {
                return true;
            } else {
                return false;
            }
        },

        // Open a new window if the anchor passes isExternalLink function above
        openNewWindow: function() {
            return this.each(function() {
                $(this).click(function() {
                    // open external links in a new window if they're not modal triggers
                    if( $(this).isExternalLink() && !$(this).hasClass('modal') ) {
                        window.open(this.href);
                        return false;
                    } else if ( $(this).hasClass('external_window_helper') ) {
                        window.open(this.href,'Bizdom.com','width=600,height=350,resizable=0');
                        return false;
                    }
                });
            });
        },

        // Set Video
        setVideo: function( type ) {
            var videoSettings = {
                flowplayerPath: "/video/flowplayer/flowplayer.commercial-3.1.5.swf"
            }

            switch (type) {
                case 'main':
                    var mainVideo = flowplayer("main_video", {
                            src:            videoSettings.flowplayerPath,
                            wmode:          'transparent'
                        }, {
                        clip: {
                            autoPlay:       true,
                            autoBuffering:  true
                        }
                    });
                break;

                case 'launch':
                    var launchVideo = flowplayer("launch_video", {
                            src:            videoSettings.flowplayerPath,
                            wmode:          'transparent'
                        }, {
                        clip: {
                            autoPlay:       true,
                            autoBuffering:  true
                        }
                    });
                break;

                case 'training':
                    var trainingVideo = flowplayer("training_video", {
                            src:            videoSettings.flowplayerPath,
                            wmode:          'transparent'
                        }, {
                        clip: {
                            autoPlay:       true,
                            autoBuffering:  true
                        }
                    });
                break;
            }
        },

        // FAQ toggling
        faqToggling: function() {
            return this.each(function() {
                $(this).click(function() {
                    var answer = $(this).attr('id').substring(0, $(this).attr("id").length-1)+"A";

                    // Toggle and highlight current answer
                    if ($('#' + answer).css('display') == 'none') {
                        $('.answer').css('background', 'transparent');
                        $('#' + answer).css('background', '#ffffff');
                        $('#' + answer).animate({height: 'show'}, 700, 'linear');
                    } else {
                        $('#' + answer).animate({height: 'hide'}, 700, 'linear');
                    }

                    return false;
                });
            });
        },

        /**
         * Loading interstitial, alert boxes and more.
         *
         * Pass in new options if you want to override the defaults
         * ex: $('.foo').cModal({ confirmClass: 'fooClass', posAbsolute: true, h4: 'Hello World' })
         **/
        cModal: function(options) {
            if ( !$(this).length ) return false;

            // Defaults to be overidden
            var defaults = {
                h4:           'Thank You!',
                p:            'Please wait while we are loading your results.',
                div:          '',
                intClass:     'defaultInt',
                confirmClass: 'defaultConfirm',
                posAbsolute:  false,
                close:        false,
                closeClass:   '.closeInt',
                confirm:      false,
                confirmYes:   'Yes',
                confirmNo:    'No',
                callbackYes:  '',
                callbackNo:   '',
                speed:        650,
                opacity:      0.6
            }

            // Combine/override defaults with options passed in
            defaults = $.extend( {}, defaults, options );

            var config = {
                intContainer:   '<div style="display: none;" class="intContainer '+defaults.intClass+'">' +
                                    '<div class="intContent">' + 
                                        '<a href="#" class="closeInt">Close</a>' +
                                        '<h4>'+defaults.h4+'</h4>' + 
                                        (defaults.p != '' ? '<p>'+defaults.p+'</p>' : (defaults.div != '' ? '<div>'+defaults.div+'</div>' : '')) + 
                                '</div></div>' +
                                '<div style="display: none;" class="intMask">' +
                                '</div>',
                intConfirm:     '<div style="display: none;" class="intContainer '+defaults.confirmClass+'">' +
                                    '<div class="intContent">' + 
                                    '<a href="#" class="closeInt">Close</a>' + 
                                    '<h4>'+defaults.h4+'</h4>' + 
                                    (defaults.p != '' ? '<p>'+defaults.p+'</p>' : (defaults.div != '' ? '<div>'+defaults.div+'</div>' : '')) + 
                                    '<a href="#" class="confirmYes button mediumRed">' + defaults.confirmYes+'</a>' + 
                                    '<a href="#" class="confirmNo button mediumRed">' + defaults.confirmNo+'</a>' + 
                                '</div></div>' +
                                '<div style="display: none;" class="intMask">' +
                                '</div>',
                maskBox:        '.intMask',
                contentBox:     '.intContainer',
                showHideThis:   '.intContainer, .intMask',
                content:        '.intContent',
                confirmYes:     'confirmYes',
                confirmNo:      'confirmNo',
                confirm:        '.confirmYes, .confirmNo',
                closeOpt:       ''
            }

            // Overrides
            config.attrPosition = defaults.posAbsolute ? 'absolute' : 'fixed';
            config.intContainer = defaults.confirm ? config.intConfirm : config.intContainer;

            var method = {
                listener: function(trigger) {
                    function launchInt() {
                        // Add new interstitial to the body; hidden of course
                        $('body').prepend(config.intContainer);
						
						// If there are images, wait for them to be loaded
						if($(config.intContainer).find('img').length){
							$(config.intContainer).find('img').each(function(){
									$(this).attr('src', $(this).attr('src') + '?' + new Date().getTime())  
									}).load(function() {
								// Apply styles and attributes
								method.centerInterstitial();
								$('.intMask').css('opacity', defaults.opacity);
							
								// Show Interstitial
								$(config.showHideThis).fadeIn(defaults.speed);
								$('.interstitial_lock').attr('disabled', 'disabled').css('cursor', 'default').fadeTo('fast', 0.25);
							});
						}else{
							// Apply styles and attributes
							method.centerInterstitial();
							$('.intMask').css('opacity', defaults.opacity);
						
							// Show Interstitial
							$(config.showHideThis).fadeIn(defaults.speed);
							$('.interstitial_lock').attr('disabled', 'disabled').css('cursor', 'default').fadeTo('fast', 0.25);
						}
                        
                    }
                    return trigger.each(function() {
                        $(this).bind('click', function(e) {
                            e.preventDefault();
                            config.href = $(this).attr('href');
                            config.el   = e.target;

                            if ( $(this).is('input') ) {
                                // Workaround to make animated gifs work in IE for forms
                                $(this).closest('form').submit(function() {
                                    setTimeout(function() {launchInt();}, 1);
                                });
                            } else {
                                // Standard loading interstitial
                                launchInt();
                                $('.intContent a').openNewWindow();
                            }
                        });
                    });
                },
                confirm: function() {
                    $(config.confirm).live('click', function(e) {
                        e.preventDefault();
                        function hideBox() {
                            $(config.showHideThis).fadeOut(defaults.speed);
                            setTimeout(function() {
                               $(config.showHideThis).remove();
                            }, defaults.speed);
                        }

                        // If YES clicked
                        if ( $(this).hasClass(config.confirmYes) ) {
                            function runYesDefault() {
                                // What to do if you choose yes, continue action
                                if ( $(config.el).is('a') ) {
                                    window.location = config.href;
                                    hideBox();
                                } else if ( $(config.el).is('input') ) {
                                    $(config.el).closest('form').submit();
                                }
                            }

                            // If there is a callback function use it, else use the default action
                            $.isFunction(defaults.callbackYes) ? defaults.callbackYes() : runYesDefault();
                        }

                        // If NO clicked
                        if ( $(this).hasClass(config.confirmNo) ) {
                            function runNoDefault() {
                                hideBox();
                            }

                            // If there is a callback function use it, else use the default action
                            $.isFunction(defaults.callbackNo) ? defaults.callbackNo() : runNoDefault();
                        }
                    });
                },
                closeInt: function() {
                    // config.closeOpt is empty unless close is true (clicking mask will not close modal)
                    if ( defaults.close ) {
                        config.closeOpt = config.maskBox + ':visible,';
                    }
                    $( config.closeOpt + defaults.closeClass).live('click', function(e) {
                        e.preventDefault();
                        $(config.showHideThis).fadeOut(defaults.speed);
                        setTimeout(function() {
                           $(config.showHideThis).remove();
                        }, defaults.speed);
                    });
                },
                centerInterstitial: function() {
                    // get width and height of the visible window
                    if ( typeof( window.innerWidth ) == 'number' ) {
                        //Non-IE
                        config.windowWidth = window.innerWidth;
                        config.windowHeight = window.innerHeight;
                    } else if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
                        //IE 6+ in 'standards compliant mode'
                        config.windowWidth = document.documentElement.clientWidth;
                        config.windowHeight = document.documentElement.clientHeight;
                    }

                    // Get width and height of target el
                	config.intWidth = $(config.contentBox).width();
  					config.intHeight = $(config.contentBox).height();

                 	//centering
                    $(config.contentBox).css({
                       	'position': config.attrPosition,
                       	'top':      config.windowHeight/2-config.intHeight/2,
                       	'left':     config.windowWidth/2-config.intWidth/2
                    });
                }
            }

            // Launch the listener and optional functions
            method.listener($(this));
            method.closeInt();
            if ( defaults.confirm ) method.confirm();
        }
    });
})(jQuery);

// Create namespaces
QL.namespace('application');

// quickenloans application function
QL.application = function()
{
    return {

        init: function()
        {
            $E.onDOMReady(function() {

                // open external links in new window
                $('a').openNewWindow();

                // setup flowplayer videos
                if ($('#playlist').length) {
                    if($('#main_video').length) {
                        $('#main_video').setVideo('main');
                    }
                    if($('#training_video').length){
                        $('#training_video').setVideo('training');
                    }
                    if($('#launch_video').length){
                        $('#launch_video').setVideo('launch');
                    }
                }

                // setup faq toggling
                if ($('#content ol').length) {
                    $('#content ol a').faqToggling();
                }

                // setup social media modals
                $('.facebookModalTrigger').cModal({
                    h4: '',
                    p: '',
                    div: $('#facebookModalContent').html(),
                    close: true,
                    intClass: 'defaultInt socialInt'
                });
                $('.twitterModalTrigger').cModal({
                    h4: '',
                    p: '',
                    div: $('#twitterModalContent').html(),
                    close: true,
                    intClass: 'defaultInt socialInt'
                });
                
                // setup image modal
                $('.imageModalTrigger').each(function(){
					$(this).cModal({
                    	h4: '',
                    	p: '',
                    	div: '<a href="#"><span class="closeInt"></span></a><img class="closeInt" src="' + $(this).attr('href') + '">',
                    	close: false,
                    	intClass: 'defaultInt imageInt'
                	});
				});
            });
        }
    };
}();

// Run app
QL.application.init();
