if (window.DISQUS === undefined) {
    var DISQUS = {};
}

// mixpanel requires mpq to be available to the async script
var mpq = [];

DISQUS.funnelcake = (function(){
    var self = {};

    self.current_path = window.location.pathname || "";
    self.triggers = [];
    self.authenticated = false;
    self.fired = {};
    self.AB = {};
    self.additional_properties = {};

    var _escape_regex = function(str) {
        // by design, this doesn't esacpe the * character.
        return (str+'').replace(/([\\\.\+\?\[\^\]\$\(\)\{\}\=\!\|\:])/g, "\\$1");
    };

    self.fire_event = function(condition, callback) {
        callback = (typeof callback == "undefined")?function(){}:callback;
        if (!self.fired[condition.id]) {
            var properties = {};
            // always track path
            properties.path = self.current_path;
            // track AB
            // get AB setting if available
            if (window.AB_TESTS !== undefined) {
                self.AB = window.AB_TESTS;
            }
            $.each(self.AB, function(key, value) {
                properties["AB_"+key] = value;
            });
            self.fired[condition.id] = true;
            mpq.push(["track", condition.name, $.extend({}, properties, self.additional_properties), callback]);
        }
    };

    var requirements = {
        'Logged In': function(condition) {
            return (self.authenticated===true);
        },
        'Logged Out': function(condition) {
            return (self.authenticated===false);
        },
        'Filter Half': function(condition) {
            return (Math.random() > 0.9);
        }
    };

    var types = {
        'URL': function(condition) {
            self.fire_event(condition);
        },
        'Event': function(condition) {
            events[condition.trigger](condition);
        },
        'URL+Event': function(condition) {
            events[condition.trigger](condition);
        },
        'Wildcard URL': function(condition) {
            var urlregex = _escape_regex(condition.url).split("*").join(".*?");
            if (self.current_path.match(new RegExp(urlregex))) {
                self.fire_event(condition);
            }
        }
    };

    var events = {
        'On Click': function(condition) {
            $(condition.selector).live('click', function(e) {
                if (this.nodeName.toLowerCase() === 'a') {
                    var href = $(this).attr('href');
                    e.preventDefault();
                    self.fire_event(condition, function() {
                        document.location = href;
                    });
                } else {
                    self.fire_event(condition);
                }
            });
        },
        'On Hover': function(condition) {
            $(condition.selector).hover(function(e) {
                self.fire_event(condition);
            }, function(e) {
            });
        }
    };

    var passes_requirements = function(condition) {
        var passed = true;
        $.each(condition.requires, function(index, requirement) {
            if (!passed) {
                return false;
            }
            passed = requirements[requirement](condition);
            return true;
        });
        return passed;
    };

    var parse_triggers = function() {
        $.each(self.triggers, function(index, condition) {
            if (passes_requirements(condition)) {
                self.fired[condition.id] = false;
                types[condition.type](condition);
            }
        });
    };

    self.init = function(token, options) {

        function onLoad() {
            window.$.ajax = tunnel.contentWindow.jQuery.ajax;
            // Flush queued ajax calls
            $.each(ajax_queue, function(_, options) { $.ajax(options); });
            ajax_queue = null;
        }

        if (context.disqusDomain == "secure.disqus.com") {
            // set up ajax to work across tunnel
            window.$._ajax = window.$.ajax;
            var ajax_queue = [];

            // Queue ajax calls until our cross-domain jQuery tunnel is open
            $.ajax = function(options) {
                ajax_queue.push(options);
            };

            var tunnel = $('<iframe>')
                .attr('src', context.disqusUrl + '/tunnel/')
                .load(onLoad)
                .appendTo('head')[0];
        }

        var defaults = {
            debug: false,
            authenticated: false,
            additional_properties: {},
            fetch: true
        };
        var settings = $.extend({}, defaults, options);
        self.authenticated = settings.authenticated;
        self.additional_properties = settings.additional_properties;
        mpq.push(["init", token]);
        (function(){
            var mp = document.createElement("script");
            mp.type = "text/javascript";
            mp.async = true;
            mp.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + "//api.mixpanel.com/site_media/js/api/mixpanel.js";
            var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(mp, s);
        })();
        if (settings.debug) {
            // see http://blog.mixpanel.com/a-way-to-ease-your-integration-with-mixpanel
            // and http://blog.mixpanel.com/debugging-javascript-api-requests
            mpq.push(["set_config", {'test': 1, 'debug': true}]);
        }

        // set super properties
        // always track auth status for users
        mpq.push(["register", {'authenticated': self.authenticated}]);

        // Fetch triggers via API
        if (settings.fetch) {
            DISQUS.sexyapi["internal/funnelcake"].list({
                data: {
                    path: self.current_path
                },
                success: function(data) {
                    self.triggers = data.triggers;
                    parse_triggers();
                }
            });
        }
    };

    return self;
})();


