// regex.js
// Plugin for Echo Stream application that applies a CSS class to items that match a regular expression

(function($) {
    var filters;

    var plugin = Echo.createPlugin({
	    "name": "Regex",
	    "applications": ["Stream"],
	    "init": function(plugin, application) {
		    plugin.extendRenderer("Item", "content", plugin.contentRenderer, "Regex");
            filters = application.config.get(plugin.config("filters"));
	    }
    });

    plugin.contentRenderer = function(element, dom) {
        var data = this.data;
        
        var x;
        for (x in filters) {
            if (filters.hasOwnProperty(x)) {
                var property = getObjectProperty(data, filters[x].target);
                if (filters[x].pattern.test(property)) {
                    if (typeof filters[x].className !== 'undefined') {
                        element.addClass(filters[x].className);
                    }
                    if (typeof filters[x].replace !== 'undefined') {
                        getObjectProperty(data, filters[x].target, filters[x].replace);
                    }
                }
            }
        }

	    this.parentRenderer("content", arguments);
    };

    // Gets a nested property of an object using dot notation
    // Example: getObjectProperty(window, "location.href");
    // If "value" is provided, the property will be changed
    function getObjectProperty(obj, prop, value) {
        if (typeof obj !== 'object') {
            return null;
        }

        var index = prop.indexOf('.');
        if (index === -1) {
            if (typeof value !== 'undefined') {
                obj[prop] = value;
            }
            return obj[prop];
        }
        else {
            var thisProp = prop.substring(0, index);
            var nextProp = prop.substring(index + 1);
            return getObjectProperty(obj[thisProp], nextProp, value);
        }
    }

}(jQuery));
