(function($) {
    DAYLIFE_Globals = {
        qualified_path: "http://www.mediavillage.com/",
        static_qualified_path: "http://www.daylife.com/",
        js_path: "http://diacache.daylife.com/_static/release-49068/v2/js",
        img_path: "http://diacache.daylife.com/_static/release-49068/v2/img",
        site_name: "Jack Myers",
        topicfinderapi_url: "http://www.mediavillage.com/topicfinderapi"
    };

    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.topicfinderapi_topics_to_link || typeof DAYLIFE.topicfinderapi_topics_to_link != 'number') {
        var num_to_link = parseInt(DAYLIFE.topicfinderapi_topics_to_link);
        if (num_to_link > 0) {
            DAYLIFE.topicfinderapi_topics_to_link = num_to_link;
        } else {
            DAYLIFE.topicfinderapi_topics_to_link = 999;
        }
    }

    DAYLIFE.TopicFinderApi = function() {

        var _TopicFinderApi_Data = null;
        var _TopicFinderApi_Topic = null;
        return {
            grab_data: function(div, options) {
                if(!_TopicFinderApi_Data){
                    _TopicFinderApi_Data = new DAYLIFE.TopicFinderApi.Data();
                    _TopicFinderApi_Data.runner(div, options);
                }
                return _TopicFinderApi_Data;
            },
            remove_data: function() {
                if (_TopicFinderApi_Data) {
                    _TopicFinderApi_Data = null;
                }
            }
        };
    }();

    DAYLIFE.TopicFinderApi.Data = function() {
        this.topicfinderapi_data;
        this.content_selector;
        this.query = {};
        this.param = {};
        this.options = {};
        this.first_load = true;
    };

    DAYLIFE.TopicFinderApi.Data.prototype = {

        runner: function(div, options) {
            if (options) this.options = options;
            this.content_selector = div;

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

            if (this.orig_text) {
                this.grab_raw_data(this.orig_text);
            }
        },

        grab_orig_text: function() {
            var orig_text = null;
            var selector = this.content_selector;
            
            if (selector.indexOf('#') == -1 && selector.indexOf('.') == -1) {
                if ($('#' + selector).text().length) {
                    selector = '#' + selector;
                } else if ($('.' + selector).text().length) {
                    selector = '.' + selector;
                }
            }
            
            var $selector = $(selector);
            this.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 (t in textNodes) {
                    text.push(textNodes[t].nodeValue);
                }
                var regex_capital_lowercase = new RegExp("(\\S*([A-Z]|&)\\S*)\\s*([a-z0-9]*)", "g");
                text = text.join(' ')
                           .match(regex_capital_lowercase);
                // DAYLIFE.log(['Text', text]);
                if (text && text.length) {
                    orig_text = text.join(' ').replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '');
                    if (DAYLIFE.Browser.IE && orig_text.length > 1800)
                        orig_text = orig_text.slice(0, orig_text.indexOf(' ', 1800));
                    else if (orig_text.length > 3950)
                        orig_text = orig_text.slice(0, orig_text.indexOf(' ', 3950));
                    DAYLIFE.log(['Original Text', {'text':orig_text}, orig_text.length]);
                }
            }
            
            return orig_text;
        },

        grab_raw_data: function(content) {
            var self = this;
            var topicfinderapi_url = DAYLIFE.topicfinderapi_url + "/content_getTopics?callback=?";
            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.rewrite_runner();
                } else if (self.options.embed === true) {
                    self.load_embed();
                }
            } else {
                // Send the request to grab the TopicFinderApi data from the TopicFinderApi API
                var params = {
                    text: content
                };
                if (DAYLIFE.topic_filter) {
                    params.topic_filter = DAYLIFE.topic_filter.toLowerCase();
                }
                if (this.options.embed) {
                    params.num_topics = this.query.num_topics || 3;
                    params.show_topic_image = true;
                    if (this.query.topic_filter) {
                        params.topic_filter = this.query.topic_filter[0];
                    }
                    this.establish_embed_placeholder();
                }

                $.ajax({
                    url: topicfinderapi_url,
                    data: params,
                    success: function(o) {
                        DAYLIFE.log(['TopicFinderAPI Data', {'topics': o}, self.options, o.length + ' topics']);
        	            self.topicfinderapi_data = o;
        	            if (   typeof self.topicfinderapi_data == 'object'
        	                && self.topicfinderapi_data.length
                            && self.options.highlight == true)
                        {
                            self.rewrite_runner();
                        } else if (self.options.embed === true) {
                            self.load_embed(o);
                        }
                    },
                    error: function(o) {
                        DAYLIFE.log(['TopicFinderAPI Data Error', o]);
                    },
                    dataType: 'jsonp'
                });
            }
        },


        // ================================
        // = SmartContext Topic Highlight =
        // ================================
        
        rewrite_runner: 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);
            DAYLIFE.log(['Highlighting', topics, div, allnodes, textNodes]);
            for (t in topics) {
                if (typeof topics[t] == 'object' && DAYLIFE.topicfinderapi_topics_to_link) {
                    var topic = 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]);
                    }
                }
            }
        },

        find_and_replace: function(topic, searchText, searchNode) {
            var found = false,
                self = this;
        
           if (!searchText) {
                return found;
            }
            var regex = new RegExp(searchText+'(?=[.,?!:;<\\]\\)\\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;
                }
                var replacement = this.wrap_topicfinderapi_topic(topic, searchText);
                var parent = currentNode.parentNode,
                    frag = (function(self){
                        var html = currentNode.data.replace(regex, replacement),
                            wrap = document.createElement('div'),
                            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() {

              daylife_tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
              imgLoader = new Image();// preload image
              imgLoader.src = DAYLIFE.js_path + '/../img/loadinfo_bigger.gif';
              $('img.DL_TopicFinderApi_img').hover(function() {
                  $(this).attr('src', DAYLIFE.js_path + '/../img/topicfinderapi_on.png');
              },function() {
                  $(this).attr('src', DAYLIFE.js_path + '/../img/topicfinderapi_off.png');
              });
        },

        invalid_tag: function(node) {
            return $(node).is("a, script, object, embed, iframe, frame, applet, base, basefont, bdo, button, code, del, input, textarea, head, html, link, map, menu, option, select, param, pre, s, samp, style, sub, sup, title, xmp");
        },

        is_valid_topic_terminator: function(textnode_text, topic_loc, topic_alias) {
            var end_of_textnode = textnode_text.length > topic_loc+topic_alias.length;
            var is_valid_word_terminator = textnode_text.substr(topic_loc+topic_alias.length, 1).search(/[.,?!)\]:;<\s]/) == -1;
            return end_of_textnode && is_valid_word_terminator;
        },

        wrap_topicfinderapi_topic: function(topic, topicfinderapi_text) {
            var before = '<a href="'+DAYLIFE.publisher_domain + topic.topic_url+'">';
            var after = '</a>';
            DAYLIFE.log(['Wrapping', topicfinderapi_text, topic.name, topic]);
            if (DAYLIFE.topicfinderapi_icon == 'smart_links') {
                var topic_url = topic['topic_url'] || this.strip_host_from_daylife_url(topic.daylife_url);
                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: 0px 0px 0px 4px;display: inline;" class="DL_TopicFinderApi_img" /><span style="display:none" class="thickbox_title">'+DAYLIFE.site_name+' Topics</span></a>';
            }
            DAYLIFE.topicfinderapi_topics_to_link--;
            return before + topicfinderapi_text + after;
        },


        // ===============================
        // = SmartContesxt Embed Widgets =
        // ===============================
        
        establish_embed_placeholder: function() {
            var embed_placeholder = this.query['embed_placeholder'][0];
            this.$embed_placeholder = $('#'+embed_placeholder);
        },

        make_embed_node: function() {
            DAYLIFE.log(['Query & Params', this.query, this.param]);
            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.append(this.$embed);
        },

        load_embed: function(topics) {
            if (topics && topics.length) {
                this.make_embed_node();
                this.show_loader();
                
                var $topics = this.display_topics(topics);

                this.$embed_topics.html($topics);
        	    this.$embed_topics.bind('click', $.rescope(this.click_topic, this));

        		$('.DL-topic:first', this.$embed_placeholder).addClass('DL-first');
        		$('.DL-topic:last', this.$embed_placeholder).addClass('DL-last');

                var $first_topic = $('.DL-topic a', $topics).eq(0);
                this.load_module($first_topic.data('topic'), $first_topic);
            } 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) {
            var self = this;
            // var selected_topics = this.filter_popular_topics(topics, 5);
            // DAYLIFE.log(['selected_topics', {'selected': selected_topics}]);
            var selected_topics = topics;
            var $topics = $.make('ul', { className: 'DL-topics' });
            for (t in selected_topics) {
                var topic = selected_topics[t];
                var 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-49068/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?):\/\/(.*?)\//, '/');
        },

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

        load_module: function(topic, $topic) {
            DAYLIFE.log(['Topic', topic, $topic]);
            var self = this;
            var url = "http://www.mediavillage.com/module";
            var module_url = this.create_module_url(url, topic.topic_id);
            this.show_loader();
            $topic.parent().siblings().removeClass('DL-active');
            $topic.parent().addClass('DL-active');

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

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

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

        hide_loader: function() {
            if (!this.first_load) {
                $('.DL-embed-content').stop().animate({'opacity': 1}, 100);
            } else {
                this.first_load = false;
                $('.DL-embed-module').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 query = {};
        
        if (DAYLIFE.topicfinderapi_div) DAYLIFE.content_selector = DAYLIFE.topicfinderapi_div;
        
        if (DAYLIFE.content_selector && !query['embed_placeholder']) {
            var highlight_topics = true;
            var topicfinderapi = DAYLIFE.TopicFinderApi.grab_data(DAYLIFE.content_selector, { highlight: highlight_topics });
        }

        if (DAYLIFE.content_selector && query['embed_placeholder']) {
            var highlight_topics = DAYLIFE.highlight_topics || false;
            var topicfinderapi = DAYLIFE.TopicFinderApi.grab_data(DAYLIFE.content_selector, { embed: true, highlight: highlight_topics });
        }

    });
})($DL);