
/*****************************************************************************************************************
* BEGIN Quicken Loans Custom Code - Business Implementation (our engineers wrote this).
* To make sense of all this, Refer to the most recent attachments in Task#193829.
*
* package    QuickenLoans
* subpackage Omniture
* copyright  2005 - 2011 Quicken Loans Inc. All rights reserved. Trade
*             Secret, Confidential and Proprietary.  Any dissemination outside
*             of Quicken Loans is strictly prohibited.
*
* author     Christina Hanna <ChristinaHanna@QuickenLoans.com>
* author     Brian Wilson <BrianWilson@QuickenLoans.com>
*****************************************************************************************************************/

/*** This is written in the context of literal. The location matching and alerting is a pre-production warning system ***/




// setOmniture relies on the meta tags set on each page.
(function($) {
    $.getByteCount = function( value )
    {
        var manualTagByteLimit = 100;
        var escapedValue = escape( value );

        if ( escapedValue.indexOf( '%' ) != -1) {
            var byteCount = escapedValue.split( '%' ).length - 1;
            if ( byteCount == 0 ) {
                byteCount++;
            }
            var temp = escapedValue.length - ( byteCount * 3 )
            byteCount = byteCount + temp;
        } else {
            byteCount = escapedValue.length;
        }

        if ( ! location.host.match( 'www' ) ) {
            if ( byteCount >= manualTagByteLimit ) {
                alert( 'Your Spoon is Too Big!\n\n You\'re attempting to send Omniture a value over ' + manualTagByteLimit + ' bytes.\n\n The offending value is "' + value + '" and it weighs in at ' + byteCount + ' bytes.' );
            }
        }
    }

    $.setOmniture = function(config) {
        //$.getByteCount('foobarasdfasdfasdfasfasdfasg,kjagjhasd;haslkjglaksjdflakhjfjahdsflkasdfhasdfkasfkdja;slkdfjalskdjfalskdjfalksdjfjal;sdkjffaslkjff');
        /**********************************************************************
         * BEGIN Omniture code that got moved here for order of operations.
         * This sets core attributes to be used by our code.
         *
         * @author Calvin Bushor <CalvinBushor@QuickenLoans.com>
         *********************************************************************/
        /* Placing URL into an array to get count of how deep a visitor is */
        var urlPage = new String(window.location);
        urlPageArray = new Array();
        urlPageArray = urlPage.split("/");

        if (urlPageArray){
        if (urlPageArray.length<5){
        /* Checking the length of the URL Array to determine if the visitor is on the homepage */
        s.defaultPage="home" //Used to force a "home" section and a page name for the homepage
        }
        /* The visitor is not on the homepage */
        else{
        s.defaultPage=""
        }
        }
        else{}

        /* Setting the Omniture getPageName() plugin */
        if(!s.pageName){s.pageName=s.getPageName();}

        /* Removing hyphens from s.pageName */
        if(s.pageName){s.pageName=s.pageName.replace(/-/g," ");}

        /* Setting the custom page view event if s.pageName is set */
        if(s.pageName){
           s.events=s.apl(s.events,"event10",",",2) //Sets custom event on all page views so that page views can be a success metric in SiteCatalyst reprots
        }

        // For error pages
        if ( $('.error_404, .error_500').length ) {
            s.pageName = "";
            s.pageType = "errorPage";
        }

        /* This needed to be moved here, outside of the Omniture code,
         *  because s.prop17 needed to be set before checking it */
        s.prop17=s.getPreviousValue(s.pageName,'gpv_p17','');
        /**********************************************************************
         * END Omniture code that got moved here for order of operations.
         * This sets core attributes to be used by our code.
         *********************************************************************/

        var options = {
            document: $(document),
            metas: $('meta'),
            check: /(\w+)\[([^}]*)]/,
            keyword: {
                data: 'data',
                tag: 'omniture'
            },
            productString: []
        };
        var config = $.extend(options, config);
        var pageData = {};

        // These are available globally to this object and used in the various functions
        // pageData.reportSuiteId         - represents the current reportSuiteId or you can use s_account
        // pageData.leadTypeCode          - represents the lead type code from the meta tag
        // pageData.rootUrlPath           - represents the path to the page my-mortgage for example
        // pageData.searchResultCount     - represents the number of search results returned on the page
        // pageData.searchQuery           - represents the query that the user searched
        // pageData.userState             - represents the state from the user's session
        // pageData.userZip               - represents the zip from the user's session
        // pageData.googleOptimizerTestId - represents the google optimizer test id present on the page
        // pageData.multiStepProgress     - indicator to tell us if the user is at the start, middle or complete of the multi step flow
        // pageData.multiStepName         - represents one step of a multi step flow
        // pageData.multiStepFormName     - represents the name of the multi step flow
        // pageData.creditRating          - represents the value of the user's self assessed credit rating

        var method = {
            checkBitSize: function() {
                for ( var i=0; i<=100; i++ ) {
                    // check bit size of s.props
                    if ( s['prop'+i] ) {
                        $.getByteCount(s['prop'+i]);
                    }
                    // check bit size of s.eVars
                    if ( s['eVar'+i] ) {
                        $.getByteCount(s['eVar'+i]);
                    }
                }

                // check bit size of pageName
                $.getByteCount(s.pageName);
            },
            writeOmnitureObjectToDomForQuest: function(obj) {
                // Write a block of KEYS and VALS to the document for Quest to scrape
                if ( !window.location.href.match(/www\./) ) {
                    $('body').append('<div id="omniture_quest_object" style="display: none;" class="displayNone"><ul></ul></div>');

                    for (var key in obj) {
                        if ( !$.isFunction(obj[key]) ) {
                            $('#omniture_quest_object ul').append('<li>'+key+'='+obj[key]+'</li>');
                        }
                    }
                }
            },
            start: function() {
                config.metas.each(function(i) {
                    if ( $(this).attr('name') && $(this).attr('name').match(config.check) ) {
                        config.tagType = $(this).attr('name').match(config.check)
                        if ( config.tagType[1] == config.keyword.data) {
                            pageData[config.tagType[2]] = $(this).attr('content');
                        }
                    }
                });
                // these will be run every time a page is loaded.
                method.tag.sniffRootURLPath();
                method.tag.customLinkTagging();
                method.tag.assignObjectID();
                method.setTags();

                // Set product string
                if ( config.productString.length > 0 ) {
                    s.products = 'D="' + config.productString.join(',');

                    // Handle some weird formatting for the end of the string (search for eVar32"= for places).
                    for (var i=0;i<config.productString.length;i++) {
                        if ( !s.products.match(/eVar32"/) ) {
                            s.products = s.products + '"';
                        }
                    }
                }

                // Run Omniture with updated s object
                var renderOmniture = s.t();
                if (renderOmniture) {
                    document.write(renderOmniture);
                }

                method.writeOmnitureObjectToDomForQuest(s);
                method.checkBitSize();
            },
            // looks for the corresponding omniture[methodName] meta tag
            setTags: function() {
                config.metas.each(function(i) {
                    if ( $(this).attr('name') && $(this).attr('name').match(config.check) ) {
                        config.tagType = $(this).attr('name').match(config.check);
                        if ( config.tagType[1] == config.keyword.tag) {
                            method['tag'][config.tagType[2]]($(this).attr('content'));
                        }
                    }
                });
            },
            // Define all of the custom logic, these are omniture[methodName]
            tag: {
                assignObjectID: function() {
                    $('a').each(function(i) {
                        i=i+1;
                        $(this).bind('click', function() {
                            if ( $(this).attr('data-omniture-objectid')) {
                                s_objectID = $(this).attr('data-omniture-objectID')+'_'+i;
                            } else {
                                s_objectID = $(this).attr('href')+'_'+i;
                            }
                        })

                    })
                },
                // sniffRootURLPath - triggered if we match the root path, add more cases as needed.
                sniffRootURLPath: function(){
                    var href = window.location.href;
                    var c = href.split("/");
                    var rootUrlPath = c[3];
                    switch( rootUrlPath ){
                        case 'mortgage-calculator':
                            s.prop8 = s.pageName;
                            break;
                        case 'my-mortgage':
                            s.prop7 = s.pageName;
                            break;
                        default:
                            break;
                    }
                    // make this value available
                    pageData.rootUrlPath = rootUrlPath;
                },
                // measureSearchResult - triggered when a user searches on our site. note: 0 must be zero
                measureSearchResult: function(){
                    if( pageData.searchResultCount == 'zero' ) {
                        s.events = s.apl(s.events,'event18',',',2);
                        s.prop6 = pageData.searchResultCount;
                    } else {
                        s.prop6 = pageData.searchResultCount;
                    }
                },
                // measureReferralForm - triggered when a referral form is present on the page, s.prop17 represents page history
                measureReferralForm: function() {
                    if(s.prop17){
                        s.eVar13 = "D=c17"; //Copying to Commerce Variable
                        config.productString.push(';'+pageData.leadTypeCode+';;;;eVar32"=c17');
                    } else {
                        config.productString.push(';'+pageData.leadTypeCode );
                    }
                    s.events = s.apl(s.events,'event6',',',2);
                    s.eVar31 = pageData.leadTypeCode;

                    if(pageData.creditRating){
                        s.prop36 = pageData.creditRating;
                        s.eVar39 = pageData.creditRating;
                    }
                },
                // measureDemographics - triggered when we have a user's state and/or zip in their session
                measureDemographics: function(){
                    if(pageData.userState != undefined || pageData.userState != '') {
                        s.state = pageData.userState;
                    }
                    if (pageData.userZip != undefined || pageData.userZip != '') {
                        s.zip = pageData.userZip;
                    }
                },
                // measureConversion - triggered when we reach a thank you page
                measureConversion: function(){
                    s.events = s.apl(s.events,'event7',',',2);
                    s.purchaseID = pageData.leadTypeCode;
                    if(pageData.creditRating){
                        s.prop36 = pageData.creditRating;
                        s.eVar39 = pageData.creditRating;
                    }

                    // Loan purpose
                    s.prop37 = pageData.loanPurpose;
                    s.eVar40 = s.prop37;

                    config.productString.push(';'+pageData.leadTypeCode+';;;;eVar32"='+s.prop17);
                },
                // measureGoogleOptimizer - triggered when we have an active google optimizer test
                measureGoogleOptimizer: function(){
                    s.prop19 = pageData.googleOptimizerTestId;
                },
                // measureMultiStepFlow - triggered when are inside of any multi step form workflow that we have been asked to track
                measureMultiStepFlow: function(){
                    switch(pageData.multiStepProgress){
                        // fire off different metrics depending on where you are in the multi step flow
                        case 'start':
                            s.events = s.apl(s.events,'event25',',',2);
                            config.productString.push(';'+pageData.multiStepFormName+';;;;eVar32"='+s.prop17);
                            s.prop31 = pageData.multiStepName;
                            break;
                        case 'middle':
                            s.prop31 = pageData.multiStepName;
                            break;
                        case 'complete':
                            s.events = s.apl(s.events,'event24',',',2);
                            config.productString.push(';'+pageData.multiStepFormName+';;;;eVar32"='+s.prop17);
                            s.prop31 = pageData.multiStepName;
                            break;
                        default:
                            break;
                    }
                },
                // customLinkTagging - measures link clicks and optionally impressions for all the links that have a data-omniture attribute
                customLinkTagging: function() {
                    $('[data-omniture]').live('click',function(){
                        var linkName = $(this).data('omniture').linkName;
                        var s=s_gi(s_account);
                        s.linkTrackVars='eVar16,prop20,events';
                        s.linkTrackEvents='event16';
                        s.eVar16 = linkName;
                        s.prop20 = linkName;
                        s.events = s.apl(s.events,'event16',',',2);
                        s.tl(this,'o','custom link click');
                    });

                    if (!s.products){
                        s.products = '';
                    }

                    // measure impressions
                    config.concatLinknames = '';
                    $('[data-omniture]').each(function(i) {
                        config.linkName = $(this).data('omniture').linkName;
                        config.linkImpression = $(this).data('omniture').linkImpression;

                        // Needs comma after first page linkname
                        if ( i == 0 ) {
                            config.concatLinknames +=';;;;;eVar16='+config.linkName;
                        } else {
                            config.concatLinknames +=',;;;;;eVar16='+config.linkName;
                        }
                    });

                    // If impressions are enabled
                    if (config.linkImpression == true) {
                        s.events = s.apl(s.events,'event20',',',2);
                        config.productString.push(config.concatLinknames);
                    }

                },
                overridePageName: function(name) {
                    s.pageName = name;
                }

            }
        }
        method.start();
    }

})(jQuery);
// run QLs code
$.setOmniture();
/*****************************************************************************************************************
 END Quicken Loans Custom Code (our engineers wrote this code).
*****************************************************************************************************************/

