(function($) {
    DAYLIFE_Globals = {
        qualified_path: "http://soccernews.bigsoccer.com/",
        static_qualified_path: "http://www.daylife.com/",
        js_path: "http://diacache.daylife.com/_static/release-52678/v2/js",
        img_path: "http://diacache.daylife.com/_static/release-52678/v2/img",
        site_name: "Soccer News",
        topicfinderapi_url: "http://soccernews.bigsoccer.com/topicfinderapi",
        use_hyphens: ""
    };

    DAYLIFE.publisher_domain = DAYLIFE_Globals.qualified_path.slice(0,-1);
    DAYLIFE.static_domain = DAYLIFE_Globals.static_qualified_path.slice(0,-1);
    DAYLIFE.js_path = DAYLIFE_Globals.js_path;
    DAYLIFE.img_path = DAYLIFE_Globals.img_path;
    DAYLIFE.site_name = DAYLIFE_Globals.site_name;
    DAYLIFE.topicfinderapi_url = DAYLIFE_Globals.topicfinderapi_url;

    if (!DAYLIFE.widget_queue) {
        DAYLIFE.widget_queue = [];
    }
    if (!DAYLIFE.highlight_topic_selectors) {
        DAYLIFE.highlight_topic_selectors = {};
    }
    if (!DAYLIFE.pending_topic_calls) {
        DAYLIFE.pending_topic_calls = {};
    }
    if (!DAYLIFE.displayed_topics) {
        DAYLIFE.displayed_topics = [];
    }
    if (!DAYLIFE.highlighted_topics) {
        DAYLIFE.highlighted_topics = [];
    }
    if (!DAYLIFE.content_chunks_count) {
        DAYLIFE.content_chunks_count = [];
    }

    if (!DAYLIFE.topicfinderapi_topics_to_link || typeof DAYLIFE.topicfinderapi_topics_to_link != 'number') {
        var num_to_link = parseInt(DAYLIFE.topicfinderapi_topics_to_link, 10);
        if (num_to_link > 0) {
            DAYLIFE.topicfinderapi_topics_to_link = num_to_link;
        } else {
            DAYLIFE.topicfinderapi_topics_to_link = 999;
        }
    }
    
    DAYLIFE.EmbedModule = function(options) {
        this.topicfinderapi_data;
        this.content_selector;
        this.options = $.extend({}, options);
        this.query = this.options.query;
        this.params = this.options.params;
        this.first_load = true;
        this.loaded = false;
    };

    DAYLIFE.EmbedModule.prototype = {

        runner: function(selector) {
            var topic_filter = this.get_topic_filter();
            var cached = (selector && selector in DAYLIFE.highlight_topic_selectors)
                         && topic_filter in DAYLIFE.highlight_topic_selectors[selector];
            var pending = (selector && selector in DAYLIFE.pending_topic_calls)
                         && topic_filter in DAYLIFE.pending_topic_calls[selector];
            DAYLIFE.log(['Running', this.query['embed_placeholder'], selector, {'cached': cached}, {'pending': pending}, {'topic_filter': topic_filter}, {'query':this.query}, {'params':this.params}]);

            if (selector && !cached && !pending) {
                this.chunk_and_fetch_data(selector, topic_filter);
            } else if (cached) {
                var topics = DAYLIFE.highlight_topic_selectors[selector][topic_filter];
                this.handle_found_topics(topics);
                this.call_next_queued_module();
            } else if (pending) {
                // Add back on to queue to run later
                // DAYLIFE.log(['Pending call']);
                return true;
            } else if (this.options.embed) {
                var embed_placeholder_found = this.establish_embed_placeholder(selector);
                if (embed_placeholder_found) {
                    this.load_embed();
                }
            }
        },
        
        is_topic_content_widget: function() {
            var widgets = [
                'topics-only'
            ];
            
            return $.inArray(this.query['display_size'], widgets) == -1;
        },
        
        // ===============================
        // = Read Content and Fetch Data =
        // ===============================
        
        chunk_and_fetch_data: function(selector, topic_filter) {
            this.content_selector = selector;

            // Load up the document's HTML to feed into the TopicFinderApi/ContentAPI
            var orig_text = this.grab_orig_text();

            if (orig_text.length) {
                if (!DAYLIFE.content_chunks_count[selector]) {
                    DAYLIFE.content_chunks_count[selector] = {};
                }
                DAYLIFE.content_chunks_count[selector][topic_filter] = orig_text.length;
                for (var t=0, t_len=orig_text.length; t < t_len; t++) {
                    var text = orig_text[t];

                    this.grab_raw_data(text);
                }
            }
        },

        grab_orig_text: function() {
            var orig_text = [];
            var selector = this.content_selector;
            
            var $selector = this.find_content_selector(selector);
            
            // DAYLIFE.log(['Selector', $selector.length, $selector.text().length, $selector, selector]);
            if ($selector.length && $selector.text().length) {
                var textNodes = $selector.textNodes(99);
                var text = new Array();
                var match = $selector.html();
                for (var t=0,t_len=textNodes.length; t<t_len; t++) {
                    var currentNode = textNodes[t];
                    if (!$(currentNode).parents('.DL-embed-module,.topicfinderapi_overlay_link').length) {
                        text.push(currentNode.nodeValue);
                    }
                }
                // DAYLIFE.log(['Text', text]);
                if (text && text.length) {
                    text = text.join(' ').replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '');

                    var chunk_size = 3950;
                    if (DAYLIFE.Browser.IE) {
                        chunk_size = 1800;
                    }

                    while (text) {
                        orig_text.push(text.substr(0, chunk_size));
                        text = text.substr(chunk_size);
                    }
                    DAYLIFE.log(['Original Text', {'text':orig_text}, orig_text.length]);
                }
            }

            return orig_text;
        },
        
        find_content_selector: function(selector) {
            var $selector;
            
            if (selector == 'detect') selector = this.find_content_container();

            if (typeof selector == 'object') {
                $selector = selector;
            } else {
                if (selector.indexOf('#') == -1 && selector.indexOf('.') == -1) {
                    if ($('#' + selector).text().length) {
                        selector = '#' + selector;
                    } else if ($('.' + selector).text().length) {
                        selector = '.' + selector;
                    }
                }

                $selector = $(selector);
            }
            
            return $selector;
        },

        grab_raw_data: function(content) {
            var self = this;
            var topicfinderapi_url = DAYLIFE.topicfinderapi_url + "/content_getTopics";
            var topic_filter = this.get_topic_filter();
            var selector = this.content_selector;

            if (DAYLIFE.mock_topicfinderapi) {
                DAYLIFE.log(['TopicFinderAPI MOCK Data', DAYLIFE.mock_topicfinderapi, 
                             {'topics': DAYLIFE.mock_topicfinderapi.response.payload.topic}]);
                self.topicfinderapi_data = DAYLIFE.mock_topicfinderapi.response.payload.topic|| null;
                if (   typeof self.topicfinderapi_data == 'object'
                    && self.topicfinderapi_data.length
                    && self.options.highlight != false)
                {
                    self.highlight_topics_on_page();
                } else if (self.options.embed) {
                    self.load_embed();
                }
            } else {
                // Send the request to grab the TopicFinderApi data from the TopicFinderApi API
                var params = {
                    text: content
                };
                var global_callback = 'DAYLIFE_'+self.query['embed_placeholder'];
                
                if (topic_filter) {
                    params['topic_filter'] = topic_filter;
                }
                if (this.options.embed) {
                    params.show_topic_image = true;
                }
                
                window[global_callback] = function(o) {
                    if (!DAYLIFE.highlight_topic_selectors[selector]) {
                        DAYLIFE.highlight_topic_selectors[selector] = {};
                    }
                    var topics = self.merge_found_topics(selector, topic_filter, o);
                    
                    DAYLIFE.highlight_topic_selectors[selector][topic_filter] = topics;
                    DAYLIFE.content_chunks_count[selector][topic_filter]--;
                    
                    if (DAYLIFE.content_chunks_count[selector][topic_filter] == 0) {
                        delete DAYLIFE.pending_topic_calls[selector][topic_filter];
                        self.handle_found_topics(topics);
                        self.call_next_queued_module();
                    }
                };
                
                
                if (!DAYLIFE.pending_topic_calls[selector]) {
                    DAYLIFE.pending_topic_calls[selector] = {};
                }
                DAYLIFE.pending_topic_calls[selector][topic_filter] = true;

                $.ajax({
                    // url: 'http://www.diablo.com' + '?callback=' + global_callback,
                    url: topicfinderapi_url + '?callback=' + global_callback,
                    data: params,
                    error: function(o) {
                        DAYLIFE.log(['TopicFinderAPI Data Error', o]);
                    },
                    dataType: 'jsonp',
                    type: 'GET'
                });
            }
        },
        
        merge_found_topics: function(selector, topic_filter, topics) {
            var existing_topics = DAYLIFE.highlight_topic_selectors[selector][topic_filter];
            if (existing_topics) {
                for (var t=0, t_len=topics.length; t < t_len; t++) {
                    var topic = topics[t];
                    var found = false;
                    
                    // DAYLIFE.log(['Topic Merge', topic, existing_topics]);
                    for (var e=0, e_len=existing_topics.length; e < e_len; e++) {
                        var existing_topic = existing_topics[e];
                        if (topic.topic_id == existing_topic.topic_id) {
                            // DAYLIFE.log(['Merging', existing_topic.location, topic.location, existing_topics.length, e]);
                            existing_topic.location = $.merge(existing_topic.location, topic.location);
                            found = true;
                            break;
                        }
                    }
                    
                    if (!found) {
                        existing_topics.push(topic);
                    }
                }
            } else {
                existing_topics = topics;
            }
            
            existing_topics.sort(function(a, b) {
                return a.location.length < b.location.length;
            });
            
            return existing_topics;
        },

        handle_found_topics: function(topics) {
            DAYLIFE.log(['TopicFinderAPI Data', topics.length + ' topics', {'topics': topics}]);
            this.topicfinderapi_data = topics;
            
            if (typeof this.topicfinderapi_data == 'object'
                && this.topicfinderapi_data.length
                && this.options.highlight) {
                // DAYLIFE.log(['Rewriting', this.options]);
                this.highlight_topics_on_page();
            }
            
            if (this.options.embed) {
                this.establish_embed_placeholder();
                this.load_embed(topics);
            }
            
        },
        
        call_next_queued_module: function() {
            // DAYLIFE.log(['Completing load']);
            if (DAYLIFE.widget_queue.length && DAYLIFE.widget_queue[0].loaded) {
                // DAYLIFE.log(['Shifting initial load out of queue']);
                DAYLIFE.widget_queue.shift();
            }
            var pending_queue = [];
            
            while (DAYLIFE.widget_queue.length) {
                var queued_widget = DAYLIFE.widget_queue.shift();
                var pending_widget = queued_widget.widget.runner.call(queued_widget.widget, queued_widget.selector);
                
                if (pending_widget) {
                    pending_queue.push(queued_widget);
                }
            }
            
            while (pending_queue.length) {
                DAYLIFE.widget_queue.push(pending_queue.shift());
            }
        },


        // ================================
        // = SmartContext Topic Highlight =
        // ================================

        highlight_topics_on_page: function() {
            // Perform TopicFinderApi rewriting and topic highlighting
            this.highlight_with_topicfinderapi();

            // Attach click handlers
            this.attach_clicks();
        },

        highlight_with_topicfinderapi: function() {
            var self = this;
            var topics = this.topicfinderapi_data;
            var div = this.content_selector;
            var allnodes = div + " *, " + div;
            var textNodes = $(allnodes).textNodes(99);

            var selected_topics = this.filter_displayed_topics(topics, DAYLIFE.topicfinderapi_topics_to_link, false);
            
            // DAYLIFE.log(['Highlighting', topics, div, allnodes, textNodes]);
            for (var t=0, t_len=selected_topics.length; t < t_len; t++) {
                var topic = selected_topics[t];
                var topic_found = false;
                var prev_i = 0;
                var found = false;
                for (var a = 0; a < topic.location.length; a++) {
                    if (found) {
                        found = false;
                        break;
                    }
                    var topic_alias = topic.location[a].original_text;
                    var before, after, original;
                    // DAYLIFE.log(['Topic Alias', topic_alias, topic.location[a].end, textNodes.length + ' textNodes']);
                    found = self.find_and_replace(topic, topic_alias, $(div)[0]);
                    if (found) {
                        DAYLIFE.highlighted_topics.push(topic['topic_id']);
                    } else if (!found) {
                        DAYLIFE.log(['Topic not found (for highlighting)', topic, topic_alias]);
                    }
                }
            }
        },

        find_and_replace: function(topic, searchText, searchNode) {
            var found = false,
                self = this,
                apostrophe_option = '';

            if (!searchText) {
                return found;
            }
            
            // DAYLIFE.log(['Apostrophes', parseInt(this.query.highlight_topics_with_apostrophes, 10)]);
            if (parseInt(this.query.highlight_topics_with_apostrophes, 10)) {
                apostrophe_option = '(\'s\\b)?';
            }
            
            var regex = new RegExp('('+searchText+apostrophe_option+'(\\b)?(?=[.,?!:;<\\]\\)\\s]|$))(\\s?)', 'i'),
                childNodes = (searchNode || document.body).childNodes,
                cnLength = childNodes.length - 1,
                cnIndex = -1,
                excludes = 'html,head,style,title,link,meta,script,object,iframe';
            while (cnIndex++ < cnLength) {
                var currentNode = childNodes[cnIndex];
                if (currentNode.nodeType === 1 &&
                    (excludes + ',').indexOf(currentNode.nodeName.toLowerCase() + ',') === -1) {
                    found = this.find_and_replace(topic, searchText, currentNode);
                    if (found) {
                        return found;
                    }
                }
                if (currentNode.nodeType !== 3 || !regex.test(currentNode.data) ) {
                    continue;
                }
                if ($(currentNode).parents('.DL-embed-module').length) {
                    continue;
                }
                var original_text = currentNode.data.match(regex);
                DAYLIFE.log(['Original Text', {'text':original_text.slice()}]);
                var replacement = this.wrap_topicfinderapi_topic(topic, original_text[1], original_text[original_text.length-1]);
                var parent = currentNode.parentNode;
                var frag = (function(self){
                    var html = currentNode.data.replace(regex, replacement);
                    var wrap = document.createElement('div');
                    var frag = document.createDocumentFragment();
                    
                    wrap.innerHTML = html;
                    
                    while (wrap.firstChild) {
                        frag.appendChild(wrap.firstChild);
                    }
                    
                    return frag;
                })(self);
                parent.insertBefore(frag, currentNode);
                parent.removeChild(currentNode);
                found = true;
                break;
            }

            return found;
        },

        attach_clicks: function() {
            var topics = this.topicfinderapi_data;

            for (var t=0, t_len=topics.length; t < t_len; t++) {
                var topic = topics[t];
                
                if (topic.topic_url && !topic.daylife_url) topic.daylife_url = topic.topic_url;
                
                var $topic = $('.DL-topic-highlighted[href$='+topic.daylife_url.match(/topic\/(.*)/)[0]+']');
                // DAYLIFE.log(['Topic Attachmentment', topic, $topic, topic.daylife_url.match(/topic\/(.*)/)[0]]);

                if ($topic.length && !$topic.data('linked')) {
                    $topic.data('linked', true);
                    var $topic_popup = $topic.next('.topicfinderapi_overlay_link').eq(0);
                    daylife_tb_init($topic_popup);

                    imgLoader = new Image();// preload image
                    imgLoader.src = DAYLIFE.js_path + '/../img/loadinfo_bigger.gif';
                    
                    $('img.DL_TopicFinderApi_img', $topic_popup).hover(function() {
                        $(this).attr('src', DAYLIFE.js_path + '/../img/topicfinderapi_on.png');
                    },function() {
                        $(this).attr('src', DAYLIFE.js_path + '/../img/topicfinderapi_off.png');
                    });
                }
            }
        },
        
        wrap_topicfinderapi_topic: function(topic, topicfinderapi_text, after_text) {
            var topic_url = topic['topic_url'] || this.strip_host_from_daylife_url(topic.daylife_url);
            if (DAYLIFE_Globals.use_hyphens) {
                topic_url = topic_url.replace(/-+/g,'hyphenplaceholder').replace(/_+/g,'-').replace(/hyphenplaceholder+/g,'_');
            }

            var before = '<a class="DL-topic-highlighted" href="'+DAYLIFE.publisher_domain+topic_url+'">';
            var after = '</a>';
            DAYLIFE.log(['Wrapping', topicfinderapi_text, topic.name, topic]);
            if (this.options.show_highlight_topics_icon == 'smart_links') {
                after += '<a href="'+DAYLIFE.publisher_domain + '/topicfinderapi_overlay?id=' + topic_url.replace('/topic/','')+'&daylife_TB_iframe=true&height=500&width=730" title="Click to see related content for '+topic.name+'" class="thickbox topicfinderapi_overlay_link"><img src="'+DAYLIFE.js_path + '/../img/topicfinderapi_off.png" width="13" border="0" style="margin: 0 4px 0 6px;padding: 0;display: inline;float:none;" class="DL_TopicFinderApi_img" /><span style="display:none" class="thickbox_title"><img src="http://cache.daylife.com/imageserve/00gH7qSfSR0Ln/75x.jpg" /> '+DAYLIFE.site_name+' Topics</span></a>';
            }
            after_text = '<span>'+after_text+'</span>';
            DAYLIFE.topicfinderapi_topics_to_link--;
            return before + topicfinderapi_text + after + after_text;
        },

        // ========================================
        // = Readability - Find Content Container =
        // ========================================

        find_content_container: function() {
            // Adapted from Readability v0.4: http://lab.arc90.com/experiments/readability/

        	var $allParagraphs = $('p');
        	var topDivCount = 0;
        	var topDiv = null;
        	var topDivParas;

        	var articleContent = document.createElement("DIV");
        	var articleTitle = document.createElement("H1");
        	var articleFooter = document.createElement("DIV");

        	// Study all the paragraphs and find the chunk that has the best score.
        	// A score is determined by things like: Number of <p>'s, commas, special classes, etc.
        	for (var j=0; j	< $allParagraphs.length; j++) {
        		$parentNode = $allParagraphs.eq(j).parent();

        		// Initialize readability data
        		if( typeof $parentNode.data('contentScore') == 'undefined')
        		{
        			$parentNode.data("contentScore", 0);

        			// Look for a special classname
        			if ($parentNode[0].className.match(/(comment|meta|footer|footnote)/)) {
        				$parentNode.data("contentScore", $parentNode.data("contentScore")-50);
    				} else if ($parentNode[0].className
                .match(/((^|\\s)(post|hentry|entry[-]?(content|text|body)?|article[-]?(content|text|body)?)(\\s|$))/)) {
        				$parentNode.data("contentScore", $parentNode.data("contentScore")+25);
    				}

        			// Look for a special ID
        			if ($parentNode[0].id.match(/(comment|meta|footer|footnote)/)) {
        				$parentNode.data("contentScore", $parentNode.data("contentScore")-50);
    				} else if ($parentNode[0].id
    				    .match(/^(post|hentry|entry[-]?(content|text|body)?|article[-]?(content|text|body)?)$/)) {
        				$parentNode.data("contentScore", $parentNode.data("contentScore")+25);
    				}
        		}

        		// Add a point for the paragraph found
        		if ($allParagraphs.eq(j).text().length > 10) {
                    $parentNode.data("contentScore", $parentNode.data("contentScore")+1);
                }

        		// Add points for any commas within this paragraph
        		var commas = $allParagraphs.eq(j).text().split(',').length;
        		$parentNode.data("contentScore", $parentNode.data("contentScore")+commas);
        	}

        	// Assignment from index for performance. See http://www.peachpit.com/articles/article.aspx?p=31567&seqNum=5
        	for (var nodeIndex = 0; (node = document.getElementsByTagName('*')[nodeIndex]); nodeIndex++) {
        		if (typeof $(node).data("contentScore") != 'undefined' && (topDiv == null || $(node).data('contentScore') > $(topDiv).data('contentScore'))) {
        			topDiv = node;
    			}
			}

            return $(topDiv);
        },

        // ==============================
        // = SmartContext Embed Widgets =
        // ==============================

        establish_embed_placeholder: function(selector) {
            // DAYLIFE.log(['Embed Placeholder', this.query['embed_placeholder']]);
            var embed_placeholder = selector || this.query['embed_placeholder'];
            this.$embed_placeholder = $('#'+embed_placeholder);
            if (!(this.$embed_placeholder).length) {
                DAYLIFE.log(['No embed placeholder found. Did you update the placeholder, too?', embed_placeholder, $('#'+embed_placeholder)]);
                return false;
            }
            return true;
        },

        make_embed_topics_node: function() {
            var title = this.query.module_title || 'Related Topics';
            var size = this.query.display_size || 'medium';

            this.$embed_title = $.make('div', { className: 'DL-embed-title' }, title);
            this.$embed_topics = $.make('div', { className: 'DL-embed-topics' });
            this.$embed_content = $.make('div', { className: 'DL-embed-content' });
            this.$embed_wrapper = $.make('div', { className: 'DL-embed-wrapper' }, [
                this.$embed_title,
                this.$embed_topics,
                this.$embed_content
            ]);
            this.$topic_loader = $.make('div', { className: 'DL-loader' } , [
                $.make('img', { src: DAYLIFE_Globals.img_path + '/../img/b_w_loader.gif'})
            ]);
            this.$embed = $.make('div', { className: 'DL-embed-module DL-initial-load DL-embed-size-'+size }, [
                this.$embed_wrapper.hide(),
                this.$topic_loader
            ]);
            this.$embed_placeholder.replaceWith(this.$embed);
        },

        make_embed_gallery_node: function() {
            var title = this.query.module_title || 'Related Topics';
            var size = this.query.display_size || 'medium';

            this.$embed_content = $.make('div', { className: 'DL-embed-content' });
            this.$embed_wrapper = $.make('div', { className: 'DL-embed-wrapper' }, [
                this.$embed_content
            ]);
            this.$topic_loader = $.make('div', { className: 'DL-loader' } , [
                $.make('img', { src: DAYLIFE_Globals.img_path + '/../img/b_w_loader.gif'})
            ]);
            this.$embed = $.make('div', { className: 'DL-embed-module DL-initial-load DL-embed-size-'+size }, [
                this.$embed_wrapper.hide(),
                this.$topic_loader
            ]);
            this.$embed_placeholder.replaceWith(this.$embed);
        },

        load_embed: function(topics) {
            if (topics && topics.length) {
                this.make_embed_topics_node();
                this.show_loader();
                var num_topics = this.query.num_topics || 3;
                var $topics = this.display_topics(topics, num_topics);

                if (!$topics) {
                    DAYLIFE.log(['No topics, removing embed', this]);
                    this.$embed.remove();
                    return;
                }

                $('.DL-topic', $topics).eq(0).addClass('DL-first');
            	$('.DL-topic:last', $topics).addClass('DL-last');
            	
            	this.$embed_topics.html($topics);

                var is_topic_content_widget = this.is_topic_content_widget();
                if (is_topic_content_widget) {
            	    this.$embed_topics.bind('click', $.rescope(this.click_topic, this));

                    var $first_topic = $('.DL-topic a', $topics).eq(0);
                    this.load_module($first_topic.data('topic'), $first_topic);
                } else {
                    this.hide_loader();
                }
            } else if (this.options.embed) {
                this.make_embed_gallery_node();
                this.show_loader();
                this.load_module();
            } else {
                this.no_topics_founds();
            }
        },

        no_topics_founds: function() {
        },

        click_topic: function(elem, e) {
            var self = this;

            $.targetIs(e, { tagSelector: '.DL-topic-link, .DL-topic-image-link' }, function($t){
                e.preventDefault();
                var topic = $t.data('topic');
                topic.$topic = $t;
                self.load_module(topic, $t);
            });
        },

        display_topics: function(topics, num_topics) {
            var self = this;
            // var selected_topics = this.filter_popular_topics(topics, num_topics);
            var selected_topics = this.filter_displayed_topics(topics, num_topics, true);
            // DAYLIFE.log(['selected_topics', selected_topics]);


            if (!selected_topics.length) {
                // No topics left! Remove module
                return;
            }

            // var selected_topics = topics;
            var $topics = $.make('ul', { className: 'DL-topics' });

            num_topics = Math.min(num_topics, selected_topics.length);

            for (var t=0; t < num_topics; t++) {
                var topic = selected_topics[t];
                var topic_url = topic['topic_url'] || this.strip_host_from_daylife_url(topic.daylife_url);
                if (topic.hero_image) {
                    var img_src = topic.hero_image.hero_image_url;
                } else if (topic.image) {
                    var img_src = topic.image.thumb_url;
                } else {
                    var img_src = "http://diacache.daylife.com/_static/release-52678/v2//img/missing_topic_photo_default.png";
                }
                var $topic = $.make('li', { className: 'DL-topic' }, [
                    $.make('a', { className: 'DL-topic-link', href: DAYLIFE.publisher_domain + topic_url }, [
                    	$.make('img', { src: img_src, className: 'DL-topic-image' }),
                    	$.make('div', { className: 'DL-topic-name-wrapper' }, [
                    	    $.make('span', { className: 'DL-topic-name' }, topic.name)
                    	])
                    ]).data('topic', topic)
                ]);

                $topics.append($topic);
            }
            return $topics;
        },

        strip_host_from_daylife_url: function(url) {
            return url.replace(/^http(s?):\/\/(.*?)\//, '/');
        },

        get_topic_filter: function() {
            var topic_filter = '';

            if (DAYLIFE.topic_filter) {
                topic_filter = DAYLIFE.topic_filter.toLowerCase();
            } else if (this.query.topic_filter) {
                topic_filter = this.query.topic_filter;
            }

            return topic_filter;
        },

        filter_popular_topics: function(topics, max_topics) {
            var selected_topics = [];
            for (var t=0, t_len=topics.length; t < t_len; t++) {
                var topic_mentions = topics[t].location.length;
                if (selected_topics.length < max_topics) {
                    selected_topics.push(topics[t]);
                } else {
                    for (var s=0, s_len=selected_topics.length; s < s_len; s++) {
                        if (topic_mentions > selected_topics[s].location.length
                            && $.inArray(topics[t], selected_topics) == -1) {
                            selected_topics.splice(s, 1, topics[t]);
                        }
                    }
                }
            }
            return selected_topics;
        },

        filter_displayed_topics: function(topics, max_topics, for_display) {
            var selected_topics = [];
            
            if (!max_topics) {
                max_topics = 99;
            }
            
            for (var t=0, t_len=topics.length; t < t_len; t++) {
                var topic = topics[t];
                
                // Filter out PLACEs
                if (topic.type == 'PLACE') {
                    continue;
                }
                
                // Filter out already-highlighted topics (staying below max_topics)
                if ((for_display && $.inArray(topic.topic_id, DAYLIFE.displayed_topics) != -1)
                    || (!for_display && $.inArray(topics[t]['topic_id'], DAYLIFE.highlighted_topics) != -1)) {
                    continue;
                } else if (selected_topics.length < max_topics) {
                    selected_topics.push(topic);
                    if (for_display) {
                        DAYLIFE.displayed_topics.push(topic.name);
                    }
                } else {
                    break;
                }
            }
            return selected_topics;
        },

        load_module: function(topic, $topic) {
            var self = this;
            var url = this.options.module_url; // .replace('samuel.diablo.com', 'www.diablo.com'); // CROSS-DOMAIN TEST
            if (topic) {
                // DAYLIFE.log(['Topic', topic, $topic]);
                $topic.parent().siblings().removeClass('DL-active');
                $topic.parent().addClass('DL-active');
                url = this.create_module_url(url, topic.topic_id);
            }

            this.show_loader();

            $.getScript(url, function() {
                self.$embed_content.html(DAYLIFE.content);
                $.activate_related_topics();
                $('.DL-media-wrapper:last', this.$embed).addClass('DL-last-module');
                self.hide_loader();
                self.$embed.show();
                $('.DL-topic-name-wrapper .DL-topic-name', this.$embed).each(function() {
                    // $(this).textOverflow();
                });
            });
        },

        create_module_url: function(url, topic_id) {
            url = url + '&amp;id=' + topic_id;
            return url;
        },

        show_loader: function() {
            if (!this.first_load) {
                $('.DL-embed-content', this.$embed).animate({'opacity': .05}, 600);
            }
            this.$topic_loader.show();
        },

        hide_loader: function() {
            if (!this.first_load) {
                $('.DL-embed-content', this.$embed).stop().animate({'opacity': 1}, 100);
            } else {
                this.first_load = false;
                this.$embed.removeClass('DL-initial-load');
            }
            this.$embed_wrapper.show();
            this.$topic_loader.hide();
        }

    };


    $(document).ready(function() {

        // DAYLIFE.log(['qs', DAYLIFE.content_selector, {'text':$(DAYLIFE.content_selector).text()}]);
        var selector;
        var query = {};
        var params = {};
        var is_embed = query['embed_placeholder']
                       || DAYLIFE.gallery_embed
                       || DAYLIFE.content_selector
                          ? true
                          : false;
        var is_highlight_topics = parseInt(query['highlight_topics'],10)
                                  || !is_embed
                                     ? true
                                     : false;

        if (DAYLIFE.topicfinderapi_div) DAYLIFE.content_selector = DAYLIFE.topicfinderapi_div;

        if (query.embed_selector) {
            selector = query.embed_selector;
        } else {
            selector = DAYLIFE.gallery_embed ? null : DAYLIFE.content_selector;
        }

        var show_highlight_topics_icon = DAYLIFE.topicfinderapi_icon
                                      || (parseInt(query['show_highlight_topics_icon'],10)
                                          ? 'smart_links'
                                          : null);

        var options = {
            'embed': is_embed,
            'highlight': is_highlight_topics,
            'show_highlight_topics_icon': show_highlight_topics_icon,
            'query': query,
            'params': params,
            'module_url': "http://soccernews.bigsoccer.com/module"
        };

        DAYLIFE.log(['SmartContext Init', 'embed_placeholder' in query && query['embed_placeholder'], selector, {'query': query}, {'optiions': options}]);

        var _EmbedModule = new DAYLIFE.EmbedModule(options);
        if (DAYLIFE.widget_queue.length) {
            // DAYLIFE.log(['Adding Widget to Queue']);
            DAYLIFE.widget_queue.push({'widget':_EmbedModule, 'selector': selector, 'loaded': false});
        } else {
            // DAYLIFE.log(['Executing Widget (no queue)']);
            DAYLIFE.widget_queue.push({'widget':_EmbedModule, 'selector': selector, 'loaded': true});
            _EmbedModule.runner(selector);
        }

    });
})($DL);