/* 
    Tagging for Google Analytics
    http://www.ziarek.com/google-analytics/
    
    Licensed under Creative Commons Attribution-Noncommercial-Share Alike 3.0
    http://creativecommons.org/licenses/by-nc-sa/3.0/us/
    
    Commercial Licenses Available
*/

    /* Debug */ try{ console.log("[consoleCheckTrue]"); } catch(e) { console = {}; console.log = function () {} };
                if(document.location.href.indexOf("#debug") > -1) { console.log("[loggingActive]"); }

    /* Site Settings */
        var gaAccountId = "UA-411753-1";
        var domainName = "asq.org"; /* Convert this to array? */
        var ignoreOrganic = [ ];
        var customVariables = { };
            addNewCustomVariable(1, "Member Type", "visitor", false);
            addNewCustomVariable(2, "Site Section", "page", "unique");
            addNewCustomVariable(3, "Activity", "session", "sort");
        
    /* Tracking Settings */
        var captureFileEvents = true;

    /* Global Variables */
        var pageTracker = {};
        var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
        var documentRegEx = /\/([^\/]*?)\.(docx*|xlsx*|pptx*|pdf|flv|mp[34]|m4[vpa]|zip|jpe*g|gif|png|tiff*|rss|xml)/;
        var videoRegEx = /\/([^\/]*?)\.(flv|mp4|m4v|ogm|mov|wmv|rm)/;
        var audioRegEx = /\/([^\/]*?)\.(mp3|ogg|ra|m4[ap])/;
        
        
    /* ASQ-Specific */
    
        /* Set Member Type */
        if(typeof(window.mbType) ==  "string") {
            var mbrTypeMapping = { SENIOR: "Senior", REGULAR: "Full", ASSOCIATE: "Associate", PARTICIPANT: "Organization Participant", STUDENT: "Student",
                ORGANIZATION: "Organization", FELLOW: "Fellow", FORUM: "Forum / Division", SUSTAINING: "Sustaining", ORGMEMBER: "Organization Lead",
                SCHOOL: "School", DISTRICT: "District", "NON-MEMBER": "Registered User" };
            if(typeof(mbrTypeMapping[window.mbType]) != "undefined") {
                addToCustomVariable(1, mbrTypeMapping[window.mbType]);
            }
        }
        
        /* Set Page Section (Content Group) */
        jQuery("meta[name*='WT.cg_']").each( function () { 
            switch(this.name) {
                case "WT.cg_n": addToCustomVariable(2, this.content); break;
                case "WT.cg_s": addToCustomVariable(2, this.content); break;
            }
        });
        
        /* Set Member Id Type */
        if(window.mbNb) { /*addToCustomVariable(3, window.mbNb);*/ addToCustomVariable(3, "Authenticated"); }
    
	jQuery(document).ready( function () {
	        
		/* Download the Google Analytics JS File */
		jQuery.getScript(gaJsHost + "google-analytics.com/ga.js", function(){
						
			pageTracker = _gat._getTracker(gaAccountId);
			
			/* Set domain name for sub-domain tracking */
			pageTracker._setDomainName("." + domainName);
            
			/* Mark some keywords as referrals (from ignoreOrganic[]) */
			for(i=0; i<ignoreOrganic.length; i++) { pageTracker._addIgnoredOrganic(ignoreOrganic[i]); }
            
			/* Set custom variables (from customVariables[]) */
            assembleCustomVariables();
                
			/* Track this page view */
			pageTracker._trackPageview();
            
            /* If transaction data is present, track it */
            if(typeof(submitTransaction) == "function") { submitTransaction(); }
            
            /* Set up the links on the page */
            jQuery("a, area").click( function () {
            
                /* Clean the data to make all browsers match */
				var resolvedPathname = ("/" + this.pathname).replace("//", "/");
				var resolvedServerPath = ("/" + this.hostname + resolvedPathname).replace("//", "/");
				var resolvedProtocol = this.protocol.replace(":", "");
                
                /* Non-HTTP[S] Protocol */
                if(resolvedProtocol.indexOf("http") == -1) {
                    pageTracker._trackPageview("/protocol" + resolvedServerPath);
                    pageTracker._trackEvent("Protocol", resolvedProtocol.toUpperCase(), resolvedServerPath);
                }
                
                /* External Domain */
                if(this.hostname.indexOf(domainName) == -1) {
                    pageTracker._trackPageview("/external" + resolvedServerPath);
                    pageTracker._trackEvent("External", this.hostname + " Visit", resolvedServerPath);
                }
                
                /* Filename Exclusions */
                if(resolvedPathname.match(documentRegEx) != null) {
                    fileBasename = resolvedPathname.match(documentRegEx);
                    pageTracker._trackPageview(resolvedPathname);
                    pageTracker._trackEvent("File", fileBasename[2] + " Download", resolvedServerPath);
                }
                
                if(document.location.href.indexOf("#debug") > -1) { return false; }
            
            });
            
            /* Set up audio and video tracking */
                       
            jQuery("video, audio").bind( "timeupdate", function() { 
                if(this.trackVideoEngaged == undefined) {
                    if((this.currentTime / this.duration) > .1) {
                        trackMediaEvent("Engaged", this.currentSrc);
                        this.trackVideoEngaged = true;
                    }
                }
                if(this.trackVideoEngagedToEnd == undefined) {
                    if((this.currentTime / this.duration) > .9) {
                        trackMediaEvent("Dispatched", this.currentSrc);
                        this.trackVideoEngagedToEnd = true;
                    }
                }
            });
            
            jQuery("video, audio").bind( "ended", function () {
                this.trackVideoEngagedToEnd = undefined;
                this.trackVideoEngaged = undefined;
            });

            jQuery("video, audio").bind( "play", function () {
                trackMediaEvent("Play", this.currentSrc);
            });
            
            jQuery("video, audio").bind( "pause", function () {
                trackMediaEvent("Pause", this.currentSrc);
            });

        });
        
    });
    
    function trackMediaEvent(action, label) {
        label = label.replace(/https*:\/\//, "/");
        if(label.match(videoRegEx) != null) {
            reportFileType = "Video";
        } else if (label.match(audioRegEx) != null) {
            reportFileType = "Audio";
        } else {
            reportFileType = "Media";
        }
        pageTracker._trackEvent("Media", reportFileType + " " + action, label);
        console.log("[trackMediaEvent] Media " +  reportFileType + " " + action + " " + label);
    }
    
    function addNewCustomVariable(slot, name, scope, append) {
        if(slot > 5 && slot < 1) { return false; }
        if(typeof(customVariables[slot]) == "undefined") { customVariables[slot] = {}; }
        console.log("[addNewCustomVariable] slot: " + slot + ", name: " + name + ", scope: " + scope + ", append: " + append);
        customVariables[slot].name = name;
        customVariables[slot].scope = {visitor: 1, session: 2, page: 3}[scope];
        customVariables[slot].append = append;
        customVariables[slot].newVariables = [];
    }
    
    function addToCustomVariable(slot, value) {
        console.log("[addToCustomVariable] slot: " + slot + ", value: " + value);
        if(typeof(customVariables[slot]) == "undefined") { return false; }
        customVariables[slot].newVariables.push(value);
    }
    
    function assembleCustomVariables() {
        for(key in customVariables) {
            
            if(pageTracker._getVisitorCustomVar(key) != undefined) { customVariables[key].originalValue = unescape(pageTracker._getVisitorCustomVar(key).value); } else { customVariables[key].originalValue = ""; }
            customVariables[key].originalVariables = customVariables[key].originalValue.split(" | ");
            
            customVariables[key].useVariables = [].concat(customVariables[key].originalVariables, customVariables[key].newVariables);
            
            switch (customVariables[key].append) {
                case "sort":
                    customVariables[key].useVariables.sort();
                case "unique":
                    customVariables[key].useVariables = customVariables[key].useVariables.unique();
                case true:
                    customVariables[key].newValue = customVariables[key].useVariables.join(" | ").replace(/( \| )*(.*?)( \| )*$/, "$2");
                    break;
                default:
                    customVariables[key].newValue = customVariables[key].useVariables.pop();
                    break;
            }
            
            if(customVariables[key].newValue != customVariables[key].originalValue) { 
                console.log("[assembleCustomVariables] slot: " + key + ", value: " + customVariables[key].newValue);
                pageTracker._setCustomVar(key, customVariables[key].name, customVariables[key].newValue, customVariables[key].scope);
            } else {
                console.log("[assembleCustomVariables] slot: " + key + ", Ignoring as duplicate");
            }
            
        }
    }
    
    Array.prototype.unique =
        function() {
            var a = [];
            var l = this.length;
            for(var i=0; i<l; i++) {
                for(var j=i+1; j<l; j++) {
                    if (this[i] === this[j])
                    j = ++i;
                }
                a.push(this[i]);
            }
            return a;
        };
