// gaOutboundTracker: jQuery Google Analytics plugin
//
// Initiating the class is required:
// $.gaOutboundTracker();
(function($) {
    $.gaOutboundTracker = function(opts) {
        opts = jQuery.extend({
            external: '/outbound/',
            download: '/download/',
            extensions: [
					'pdf', 'mp3', 'mp4', 'zip', 'ts', 'm2ts' 
			],
            exclusions: [
			        'dolby', 'addthis.com'
			],
            inclusions: [
			        'dolbygames',
			        'dolbysupport.com',
			        'livesoundforum.dolby.com',
			        'dolbysecure.com',
			        'dolbystore.epromo.com',
			        'dolby.invisionzone.com'
			]
        }, opts);

        // Returns the given URL formatted for GA tracking if it is:
        //		a) a downloadable file
        //		b) a link to an external site
        // ...otherwise returns an empty string.
        function decorateLink(u) {
            var trackingURL = '';

            if (getLinkType(u) == 'Download') {
                // no protocol - internal link - check extension
                var ext = u.split('.')[u.split('.').length - 1];
                var exts = opts.extensions;

                for (i = 0; i < exts.length; i++) {
                    if (ext == exts[i]) {
                        var path = jQuery.url.setUrl().attr("path");
                        path = path.substring(0, path.lastIndexOf('.'))
                        if (u.indexOf("/") >= 0)
                            u = u.substring(u.lastIndexOf("/") + 1, u.length);
                        trackingURL = path + opts.download + u;
                        break;
                    }
                }
            } else {
                var uhost = jQuery.url.setUrl(u).attr("host");
                var host = jQuery.url.setUrl().attr("host");

                var excluded = false;
                var excls = opts.exclusions;
                var incls = opts.inclusions;

                //We do exclusions first becuase it excludes all "Dolby" sites
                for (i = 0; i < excls.length; i++) {
                    if (uhost != null) {
                        if (uhost.indexOf(excls[i]) >= 0) {
                            excluded = true;
                            break;
                        }
                    }
                }
                //Now we'll do includes for more specific domain names
                for (i = 0; i < incls.length; i++) {
                    if (uhost != null) {
                        if (uhost.indexOf(incls[i]) >= 0) {
                            excluded = false;
                            break;
                        }
                    }
                }
                if (!excluded) {
                    // Dolby standard - remove http or https
                    if (u.substring(0, 7) == "http://")
                        u = u.substring(7, u.length);
                    else if (u.substring(0, 8) == "https://")
                        u = u.substring(8, u.length);

                    // Dolby Standard - remove extension from calling url
                    var path = jQuery.url.setUrl().attr("path");
                    path = path.substring(0, path.lastIndexOf('.'))

                    trackingURL = path + opts.external + u;
                }
            }
            return trackingURL;
        }
        // add tracking code to the current page
        function addTracking() {
            var valueByteLength = 31;
            // examine every link in the page
            $('a').each(function() {
                var u = $(this).attr('href');
                // need to feed out Javascript:// - This is an Ektron bug
                if (typeof (u) != 'undefined' && u.indexOf('Javascript://') <= 0) {
                    var newLink = decorateLink(u);

                    
                    // if it needs to be tracked manually,
                    // bind a click event to call GA with
                    // the decorated/prefixed link
                    if (newLink.length) {
                        //				        var textImage = getInnerHtml($(this).html());
                        //				        var destination = getDestination(u);
                        //				        var linkType = getLinkType(u);
                        //alert(linkType + " || " + newLink + " || " + textImage + " || " + destination);
                        $(this).click(function() {
                            //Custom vars - temporarily commented out until we can get them working in the GA reports
                            //							pageTracker._setCustomVar(1,"Link Type",decodeURIComponent(encodeURIComponent(linkType).substr(0,valueByteLength)),3);
                            //							pageTracker._setCustomVar(2,"Link Summary",decodeURIComponent(encodeURIComponent(destination).substr(0,valueByteLength)),3);
                            //pageTracker._trackPageview(newLink);

                        _gaq.push(['myTracker._trackPageview', newLink]);
                            if (this.target != "_blank") {
                                setTimeout('document.location = "' + this.href + '"', 100);
                                return false;
                            }
                        });
                    }
                }
            });
        }
        //		function getInnerHtml(ahtml){
        //		    //If the html between the anchor tags is text, return the text
        //		    //If it is an image, return the image filename.
        //		    if(ahtml.toLowerCase().indexOf("<img") >= 0){
        //    		    ahtml = ahtml.replace(/ /gi, "");
        //    		    ahtml = ahtml.replace(/\'/gi, "\"");
        //    		    if(ahtml.toLowerCase().indexOf("src=\"") >= 0){
        //    		        ahtml = ahtml.substring(ahtml.toLowerCase().indexOf("src=\"")+5,ahtml.length);
        //    		        ahtml = ahtml.substring(ahtml.lastIndexOf("/")+1,ahtml.indexOf("\""));
        //    		        return ahtml;
        //    		    } else {
        //		            return 'Error parsing image';
        //		        }
        //		    } else {
        //		        return ahtml;
        //		    }
        //		}
        //		function getDestination(destURL){
        //		    if(getLinkType(destURL) == "Download"){
        //		        var filename = destURL.substring(destURL.lastIndexOf("/")+1,destURL.length);
        //		        return filename;
        //		    } else {
        //		        var domain = jQuery.url.setUrl(destURL).attr("host");
        //		        if(domain.substring(0,domain.indexOf(".")) == "www")
        //		            domain = domain.substring(domain.indexOf(".")+1,domain.length);
        //		        return domain;
        //		    }
        //		}
        function getLinkType(url) {
            return ((url.indexOf('://') == -1) ? "Download" : "Outbound");
        }
        addTracking();
    }
})(jQuery);


