/* A plugin to allow for easier handling of adding analytics for dynamic javascript-driven content navigation */
(function($){

    $.fn.recordAnalytics = function(options){
        var settings = {
            frameId: 'omnframe',
            action: 'pv',
            applicationName: 'ws',
            products: '',
            parent: document.body,
            referrer: document.referrer,
            sourceUrl: document.href,
            postRecordFn: ''
        };

        if(options) {
            $.extend(settings, options);
        }

        var frameParams = {
            v : 11, // This is the version parameter. Need to be updated once the version is updated.
            pr: settings.products,
            action: settings.action,
            an: settings.applicationName,
            url: settings.sourceUrl,
            ref: settings.referrer
        };

        var frameSrc = '/analytics/omniture.jsp?';
        //modify the settings.src to point to absolute url if the app name indicates that the request is from an external site.
        if(externalAppName(settings.applicationName)){
            frameSrc = 'http://www.constantcontact.com/analytics/omniture.jsp?';
        }

        var $frame = $('#' + settings.frameId).detach();
        if(!$frame.length) {
            $frame = $('<iframe/>', { id:settings.frameId, frameborder:0, height:0, width:0, marginheight:0, marginwidth:0, scrolling:'no' });
        }

        $frame.attr('src', frameSrc + $.param(clean(frameParams))).appendTo(settings.parent);
          // call the callback and apply the scope:
        if(typeof settings.postRecordFn == 'function'){
           $frame.bind('load',settings.postRecordFn);
        }
    };

    // Removes undefined params, and cleans/encodes defined params
    function clean(p) {
        $.each(p, function(k,v){
            if(v === undefined || v === null || v === ''){
                delete p[k];
            } else {
                p[k] = encodeURI(v);
            }
        });

        return p;
    }
    //Checks if the app name starts with "ext-" which indicates external site
    function externalAppName(applicationName) {
        var prefix = "ext-";
        return (applicationName && applicationName.indexOf(prefix) == 0);
    }

})(jQuery);

