﻿function findAndReplace(searchText, replacement, searchNode) {
    if (!searchText || typeof replacement === 'undefined') {
        // Throw error here if you want...
        return;
    }
    var regex = typeof searchText === 'string' ?
                new RegExp(searchText, 'gim') : searchText,
        childNodes = (searchNode || document.body).childNodes,
        cnLength = childNodes.length,
        excludes = 'html,head,style,title,meta,script,link,object,iframe';
    while (cnLength--) {
        var currentNode = childNodes[cnLength];
        if (currentNode.nodeType === 1 &&
            (excludes + ',').indexOf(currentNode.nodeName.toLowerCase() + ',') === -1) {
            arguments.callee(searchText, replacement, currentNode);
        }
        if (currentNode.nodeType !== 3 || !regex.test(currentNode.data)) {
            continue;
        }
        var parent = currentNode.parentNode,
            frag = (function () {
                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;
            })();
        parent.insertBefore(frag, currentNode);
        parent.removeChild(currentNode);
    }
}
function addJavascript(jsname, pos) {
    var th = document.getElementsByTagName(pos)[0];
    var s = document.createElement('script');
    s.setAttribute('type', 'text/javascript');
    s.setAttribute('src', jsname);
    th.appendChild(s);
}
function trim(str) {
    return str.replace(/^\s+|\s+$/g, "");
}

(function (window, document, version, callback) {
    var j, d;
    var loaded = false;
    if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js";
        script.onload = script.onreadystatechange = function () {
            if (!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
                callback((j = window.jQuery).noConflict(1), loaded = true);
                j(script).remove();
            }
        };
        document.documentElement.childNodes[0].appendChild(script)
    }
})(window, document, "1.3", function ($, jquery_loaded) {


    $(document).ready(function () {
        $.ajax({
            url:'http://www.leafly.com/api/strains',
            dataType: 'jsonp',
            jsonp: 'jsoncallback',
            jsonpCallback: '_leaflycbfunc'
        });
    });

    _leaflycbfunc = function(data){
            var names = $.map(data, function (n, i) {
                return n.Name;
            });

            findAndReplace('(\\b' + names.join('\\b|\\b') + '\\b)', '$1<img src="http://www.leafly.com/public/images/small.gif" class="leaflyicon" style="cursor:pointer;margin:0;padding-left:2px;display:inline;border:0;" rel="$1"/>');
            var info;
            $('img.leaflyicon').click(function () {
                var strainName = $(this).attr('rel');
                var strain = $.grep(data, function (n, i) {
                    return (n.Name.toLowerCase() == trim(strainName.toLowerCase()));
                })[0];
                $('#_leaflyInfo').remove();
                var info = $(markup.strain.apply(strain)).appendTo('body');
                info.center().show();
                info.find('.closebutton').click(function () {
                    $(this).parent().remove();
                });
            });
    }


    $.fn.center = function () {
        this.css("position", "absolute");
        this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
        this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
        return this;
    }

    var markup = {};
    markup.strain = function () {
        var colors = new Object;
        colors["Hybrid"] = "#83B218;";
        colors["Sativa"] = "#B84B2A;";
        colors["Indica"] = "#74477A;";
        var html = '\
    <div id="_leaflyInfo" style="position:fixed;z-index:1002;font-family:\'Segoe UI\',Verdana,Arial,Sans-Serif;width:800px;background-color:#fff;-moz-border-radius: 10px;-webkit-border-radius: 10px;border: 8px solid #e1e1e1; padding:20px;">\
        <a class="closebutton" title="Close" style="background:url(http://www.leafly.com/public/images/close.png) no-repeat scroll 0 0 #ffffff; cursor:pointer; display:inline; height:35px; position:absolute; right:0; top:10px; width:35px; z-index:3200;"></a>\
        <div style="height:100%; outline:0px none; width:100%">\
            <iframe src="'+this.Url+'/quickview" height="390" width="790" style="border:0"></iframe>\
        </div>\
    </div>';
        return html;
    }
});
