//related_search_queries.js
(function()
{
    var safe_SW_getBoolPref = function(name)
    {
        try
        {
            return SW_getBoolPref(name);
        }
        catch(err)
        {
            return null;
        }
    };

    var getBoolPref = function(pref_name, callback)
    {
        callback(safe_SW_getBoolPref("extensions.smarterwiki." + pref_name));
    };

    var setBoolPref = function(pref_name, value, callback)
    {
        SW_setBoolPref("extensions.smarterwiki." + pref_name, value);
        if(callback)
        {
            callback(value);
        }
    };

    if(window.chrome && window.chrome.extension) // detect chrome
    {
        var get_localStorage = function(key, callback) //only used for Chrome
        {    
            chrome.extension.sendRequest({"msg_type": "get_localStorage", "key": key}, function(response)
            {
                if(callback)
                {
                    callback(response.value);
                }
            });
        };
        var set_localStorage = function(key, value, callback) //only used for Chrome
        {    
            chrome.extension.sendRequest({"msg_type": "set_localStorage", "key": key, "value": value}, function(response)
            {
                if(callback)
                {
                    callback(response.status);
                }
            });
        };

        setBoolPref = function(pref_name, value, callback)
        {
            set_localStorage("pref." + pref_name, value, callback);
        };

        getBoolPref = function(pref_name, callback)
        {
            get_localStorage("pref." + pref_name, function(str)
            {
                if(callback) {
                    callback(str == "true");
                }
            });
        };
        
        SW_$ = $;
        SW_LOG = function(){};
        $.get = function(url, data, callback, type)
        {
            chrome.extension.sendRequest({"msg_type": "$.get", "url": url, "data": data, "type": type}, function(response)
            {
                if(callback)
                {
                    callback(response.data, response.textStatus);
                }
            });            
        };
    }
    
    var showOptions = function()
    {
        if(window.chrome && window.chrome.extension)
        {
            chrome.extension.sendRequest({"msg_type": "show_options"});
        }
        else
        {
            var wind = SW_showOptions();
            setTimeout(function()
            {
                wind.document.getElementById("smarterwikiOptions").showPane(wind.document.getElementById("SmarterWikiOptions_search_results"));
            }, 150); //must wait for init
        }
    };

    var confirm_disable = window.confirm_disable || "Are you sure you want to disable this?\n\nTo re-enable, go to Tools -> FastestFox";
    var disable_str = window.disable_label || "disable";

    var get_log_msg_url = function(msg)
    {
        msg["rand"] = parseInt(Math.random() * 1000000000);
        var params = [];
        for(var k in msg)
        {
            params.push(encodeURIComponent(k) + "=" + encodeURIComponent(msg[k]));
        }
        /*
        if("https:" == document.location.protocol)
        {
            return "https://ssl.msgs.smarterfox.com/log_msg?" + params.join("&");
        }
        */
        return "http://msgs.smarterfox.com/log_msg?" + params.join("&");
    };
    

    var log_msg_async = function(msg, callback)
    {
        return ping_url_async(get_log_msg_url(msg), callback);
    };

    var ping_url_async = function(url, callback)
    {
        var $ting = $('<img style="display: none;" />');
        if(callback)
        {
            $ting.load(callback);
        }
        $ting.attr("src", url);
        return $ting;
    };

    var track_click = function($a, msg)
    {
        $a.mouseup(function(event)
        {
            var original_href = $a.attr("href");
            msg["redirect_to"] = original_href;
            $a.attr("href", get_log_msg_url(msg));

            setTimeout(function()
            {
                $a.attr("href", original_href);
            }, 10);
        });
    };   
    
    function escapeHTMLEncode(str) 
    {
        var div = document.createElement('div');
        var text = document.createTextNode(str);
        div.appendChild(text);
        return div.innerHTML;
    }

    var truncate_string = function(s, len)
    {
        if(s.length > len)
        {
            return s.substring(0, len) + "...";
        }
        return s;
    };



    var getSearchResultsURL = function(url, terms)
    {
        var language = navigator.language ? navigator.language : navigator.userLanguage;
        var url = url.replace(/{searchTerms}/g, encodeURIComponent(terms));
        url = url.replace(/{language}/g, language);
        return url;
    };

    var searchAmazon_com_URL = "http://www.amazon.com/s?ie=UTF8&index=blended&field-keywords={searchTerms}&tag=smtfx1-20";
    var searchAmazon_ca_URL = "http://www.amazon.ca/s?ie=UTF8&index=blended&field-keywords={searchTerms}&tag=smarterfox-20";
    var searchAmazon_co_uk_URL = "http://www.amazon.co.uk/s?ie=UTF8&index=blended&field-keywords={searchTerms}&tag=smarterfox-21";
    var searchOneRiotURL = "http://www.oneriot.com/search?p=smarterfox&ssrc=smarterfox_popup_bubble&spid=8493c8f1-0b5b-4116-99fd-f0bcb0a3b602&q={searchTerms}";


    var add_oneriot_results_to_google = function(queryTerms)
    {
        /*
        var has_news_result = false;
        if(/(.*(^| )(n|N)ews( |$)|Latest results for|hours ago|minutes ago)/.test($("#res").text())) {
            has_news_result = true;
        }
        */ //always try to display    
        if(queryTerms.length < 5 || !/^en/.test(navigator.language)) // || !has_news_result)
        {
            return;
        }
        var display_search_result = function(search_result, data)
        {
            var displayed_url = search_result["displayUrl"];
            displayed_url = truncate_string(displayed_url, 65);
            
            if("trackingUrl" in search_result)
            {
                ping_url_async(get_log_msg_url({
                    "name": "related_search_result_ping", 
                    "source": "Google Search", 
                    "type": "OneRiot", 
                    "queryTerms": queryTerms,
                    "ver": "m2",
                    "redirect_to": search_result["trackingUrl"]
                }));
            }

            var $related_search_results = jQuery('' + 
'<li id="related-oneriot-search-results-google" class="related-search-results related-oneriot-search-results related-search-results-google g">' + 
'    <h3 class="related-search-results-title">' + 
'        <span class="related-search-results-title-link">' + 
'            <a class="related-search-results-title-label" href="' + 
    search_result["displayUrl"]
    //getSearchResultsURL(searchOneRiotURL, queryTerms)
    + '" style="color: #223ae6;">' + 
                 search_result["title"] + 
//'                Featured real-time results for <em>' + escapeHTMLEncode(queryTerms) + '</em> from OneRiot</a>' + 

            '<a class="related-search-results-show-options" href="#"><img class="related-search-results-title-icon" src="http://static.smarterfox.com/media/img/smarterfox-logo.png" /></a>' + 
'        </span>' + 
'    </h3>' + 
'    <div class="related-search-results-result">' + 
'        <div class="related-search-results-result-preview">' + 
'        </div>' + 
'        <div class="related-search-results-result-details">' + 
//'            <div class="related-search-results-result-title"><a class="related-search-results-result-title-link related-search-results-oneriot-result-title-link" href="' + search_result["displayUrl"] + '">' + 
//                 search_result["title"] + 
//'            </a></div>' + 
'            <div class="related-search-results-result-snippet">' + 
                 search_result["snippet"] + 
'            </div>' + 
'            <div class="related-search-results-result-url">' + 
'                <cite>' + 
                     displayed_url + 
'                </cite>' + 
'                <span style="color:#A0A0A0; margin-left: 2px; font-size: 11px;">Featured Real-time Result</span>' + 
'            </div>' +
'        </div>' + 
'    </div>' + 
//'    <div class="related-search-results-bottom">' + 
//'        <div class="related-search-results-remove">' +     
//'        </div>' +     
//'        <div class="related-search-results-more">' +     
//'            <a class="related-search-results-more-results-link" href="' + getSearchResultsURL(searchOneRiotURL, queryTerms) + '">' + 
//'                <img class="related-search-results-favicon" src="http://static.smarterfox.com/media/popup_bubble/oneriot-favicon.ico" />' + 
//'                <span class="related-search-results-more-results-label">' + data["totalResults"] + ' more results &#x00bb;</span>' + 
//'            </a>' +     
//'        </div>' +     
//'    </div>' +     
'</li>');
            var google_results = $("#res ol li");
            $(google_results[0]).before($related_search_results);
            $related_search_results.find(".related-search-results-title-label")
                    .mouseup(function(event)
            {
                var $a = $(this);
                var original_href = $a.attr("href");
                var msg = {
                    "name": "related_search_result_clicked", 
                    "source": "Google Search", 
                    "type": "OneRiot", 
                    "queryTerms": queryTerms,
                    "action": "result #0 clicked",
                    "ver": "m2",
                    };
                msg["redirect_to"] = search_result["redirectUrl"];
                $a.attr("href", get_log_msg_url(msg));

                setTimeout(function()
                {
                    $a.attr("href", original_href);
                }, 10);
            });
            /*
            track_click($related_search_results.find(".related-search-results-title-label"), {
                "name": "related_search_result_clicked", 
                "source": "Google Search", 
                "type": "OneRiot", 
                "queryTerms": queryTerms, 
                "action": "re-searched"});
            */
            $related_search_results.find(".related-search-results-show-options").click(function()
            {
                showOptions();
            });
        };
        //api2, api3, api5, api6, api7
        var servers = ["oneriot1", "oneriot2", "oneriot3", "oneriot4", "oneriot5"];
        SW_$.get("http://" + servers[parseInt(Math.random() * servers.length)] + ".api.smarterfox.com/api/search_oneriot", {"q": queryTerms}, function(data) //, "limit": 1
        {
            if("featuredResultList" in data)
            {
                display_search_result(data["featuredResultList"][0], data);
            }
            else
            {
                var search_result = data["resultList"][0];
                var total_shares = 0;
                for(var i = 0; i < search_result["sharesList"].length; i++)
                {
                    total_shares += search_result["sharesList"][i]["total"];
                }
                if(total_shares >= 45)// && (new Date() - search_result["firstShare"]["time"] * 1000 > 5 * 24 * 60 * 60 * 1000)
                {
                    display_search_result(search_result, data);
                }
            }
        }, "json");
    };
    

    var add_amazon_results_to_walmart = function(queryTerms)
    {
        add_amazon_results(queryTerms, "walmart", "com", "#res ol li h3 a", function($related_search_results)
        {
            var walmart_results = $(".ColumnContainer .Tabs.ShelfPagTop.SquarePagTop");
            $(walmart_results[0]).before($related_search_results);
        }, "em", true);
    };


    var add_amazon_results_to_google = function(queryTerms, tld)
    {
        add_amazon_results(queryTerms, "google", tld, "#res ol li h3 a", function($related_search_results)
        {
            var google_results = $("#res ol li");
            $(google_results[0]).before($related_search_results);
        }, "em");
    };

    var add_amazon_results_to_yahoo = function(queryTerms)
    {
        add_amazon_results(queryTerms, "yahoo", "com", "#web ol li h3 a", function($related_search_results)
        {
            var yahoo_results = $("#web ol li");
            $(yahoo_results[0]).before($related_search_results);
        }, "b");
    };

    var add_amazon_results_to_bing = function(queryTerms)
    {
        add_amazon_results(queryTerms, "bing", "com", "#results ul li h3 a, .sr_dcard a", function($related_search_results)
        {
            if(queryTerms == "Amazon" || queryTerms == "amazon")
            {
                $(".sr_dcard").before($related_search_results);
            }
            else
            {
                var bing_results = $("#results ul li");
                $(bing_results[0]).before($related_search_results);
            }
        }, "strong");
    };









































    var is_ecommerce_query2 = function(queryTerms, callback)
    {
        SW_$.get("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&start=10&q=" + encodeURIComponent(queryTerms), {}, function(data)
        {
            for(var i in data["responseData"]["results"])
            {
                var url = data["responseData"]["results"][i]["unescapedUrl"];
                if(/www\.amazon\.com/.test(url) || /www\.ebay\.com/.test(url) || 
                    /www\.buy\.com/.test(url) || /www\.bestbuy\.com/.test(url))
                {
                    callback(true);
                }
            }
            callback(false);
        }, "json");
    };



    var is_ecommerce_query = function(queryTerms, search_result_a_patt)
    {
        ///(^| )(n|N)ews( |$)/
        var test_url_patt = function(regexp)
        {
            var has_patt = false;
            $(search_result_a_patt).each(function()
            {
                if(regexp.test($(this).attr("href"))) {
                    has_patt = true;
                    return false;
                }
            });//new RegExp("^http://www.amazon.com/$"), "http://www.amazon.com/?tag=smtfx1-20"
            return has_patt;
        };
        var test_text_patt = function(regexp)
        {
            var has_patt = false;
            $(search_result_a_patt).each(function()
            {
                if(regexp.test($(this).text())) {
                    has_patt = true;
                    return false;
                }
            });//new RegExp("^http://www.amazon.com/$"), "http://www.amazon.com/?tag=smtfx1-20"
            return has_patt;
        };
        var has_amazon_result = test_url_patt(/www\.amazon\..*/);
        var has_ebay_result = test_url_patt(/www\.ebay\..*/);
        var has_google_books_result = test_url_patt(/books\.google\.com/);
        var has_buy_result = test_url_patt(/www\.buy\.com/);
        var has_bestbuy_result = test_url_patt(/www\.bestbuy\..*/);
        var has_shopping_results = test_text_patt(/Shopping results for /);
        
        var has_ecomm_verbs = /(^(B|b)uy |^(S|s)hop for|.* dvd.*|.*dvd .*|^(D|d)vd|^(C|c)heap)/.test(queryTerms);

        return has_amazon_result || has_ebay_result || has_buy_result || has_bestbuy_result || 
            has_shopping_results || has_ecomm_verbs;        
    };
    
    var cleanup_query = function(query)
    {
        return query.replace(/(^(B|b)uy |^(S|s)hop for)/g, "");
    };


    var add_amazon_results = function(queryTerms, search_engine_name, search_engine_tld, search_result_a_patt, add_div, bold_tag, skip_ecommerce_query_check)
    {        
        var do_insert = function()
        {
        	if($(".related-amazon-search-results").length > 0)
        	{
        		return;
        	}
            var first_amazon_result_index = -1;
            $(search_result_a_patt).each(function(i)
            {
                if(/www\.amazon\.com/.test($(this).attr("href"))) {
                    first_amazon_result_index = i;
                    return false;
                }
            });
            
            if(navigator.userAgent.indexOf("Chrome") == -1)
            {
                if((first_amazon_result_index != -1 && first_amazon_result_index < 4) || 
                    queryTerms.indexOf("amazon") != -1 || 
                    queryTerms.indexOf("endless") != -1 ||
                    queryTerms.indexOf("kindle") != -1)
                {
                    return;
                }
            }
			
			var searchAmazonURL = searchAmazon_com_URL;
			if(/\.co\.uk$/.test(window.location.host))
			{
				searchAmazonURL = searchAmazon_co_uk_URL;
			}
			else if(/\.ca$/.test(window.location.host))
			{
				searchAmazonURL = searchAmazon_ca_URL;
			}			

            var title_url = getSearchResultsURL(searchAmazonURL, queryTerms);
            var title_text = 'Amazon results for <em>' + escapeHTMLEncode(queryTerms) + '</em>';
            if(/(A|a)mazon(.com)?/.test(queryTerms))
            {
                title_url = "http://www.amazon.com/?tag=smtfx1-20";
                title_text = "<"+bold_tag+">Amazon</"+bold_tag+">.com: Online Shopping for Electronics, Apparel, Computers <b>...</b>";

				if(/\.co\.uk$/.test(window.location.host))
				{
					title_url = "http://www.amazon.co.uk/?tag=smarterfox-21";
					title_text = "<"+bold_tag+">Amazon</"+bold_tag+">.co.uk: Low Prices in Electronics, Books, Sports Equipment <b>...</b>";
				}
				else if(/\.ca$/.test(window.location.host))
				{
					title_url = "http://www.amazon.ca/?tag=smarterfox-20";
					title_text = "<"+bold_tag+">Amazon</"+bold_tag+">.ca: Online Shopping for Electronics, Apparel, Computers <b>...</b>";
				}			
            }

            var $related_search_results = jQuery('' + 
'<li id="related-amazon-search-results-' + search_engine_name + '" class="res g related-search-results related-amazon-search-results related-search-results-' + search_engine_name + '">' + 
'    <h3 class="related-search-results-title">' + 
'        <span class="related-search-results-title-link">' + 
'            <a class="related-search-results-title-label" href="' + title_url + '">' + 
'                ' + title_text + '</a>' + 
'            <a class="related-search-results-show-options" href="#"><img class="related-search-results-title-icon" src="http://static.smarterfox.com/media/img/smarterfox-logo.png" /></a>' + 
'        </span>' + 
'    </h3>' + 
'    <div class="related-search-results-results-list">' + 
'    </div>' + 
'    <div class="related-search-results-bottom">' + 
'        <div class="related-search-results-remove">' +     
'        </div>' +     
'    </div>' +     
'</li>');
            
            add_div($related_search_results);
            //$related_search_results.find(".related-search-results-results-list").slideDown("slow");

            track_click($related_search_results.find(".related-search-results-title-label"), {
                "name": "related_search_result_clicked", 
                "source": "Google Search", 
                "type": "Amazon", 
                "queryTerms": queryTerms, 
                "action": "re-searched",
                "first_amazon_result_index": first_amazon_result_index});

            $related_search_results.find(".related-search-results-show-options").click(function()
            {
                showOptions();
            });
            var servers = ["amzn1", "amzn2", "amzn3", "amzn4", "amzn5"];
            SW_$.get("http://" + servers[parseInt(Math.random() * servers.length)] + ".api.smarterfox.com/api/search_amazon", {"q": cleanup_query(queryTerms), "tld": search_engine_tld, "host": window.location.host}, function(data)
            {
                $related_search_results.find(".related-search-results-bottom").append('' + 
'        <div class="related-search-results-more">' +     
'            <a class="related-search-results-more-results-link" href="' + getSearchResultsURL(searchAmazonURL, queryTerms) + '">' + 
'                <img class="related-search-results-favicon" src="http://www.amazon.com/favicon.ico" />' + 
'                <span class="related-search-results-more-results-label">' + data["TotalResults"] + ' more results &#x00bb;</span>' + 
'            </a>' +     
'        </div>');
                
                for(var x = 0; x < Math.min(data["Items"].length, 4); x++)
                {
                    $related_search_results.find(".related-search-results-results-list").append('' + 
'    <div class="related-search-results-result">' + 
'        <div class="related-search-results-result-preview">' + 
'        </div>' + 
'        <div class="related-search-results-result-details">' + 
'            <img class="related-search-results-result-rating" alt="" src="http://g-ecx.images-amazon.com/images/G/01/x-locale/common/customer-reviews/ratings/stars-' + data["Items"][x]["AverageRating"].replace(".", "-") + '.gif" />' + 
'<span class="related-search-results-result-title"><a class="related-search-results-result-title-link related-search-results-amazon-result-title-link" href="' + data["Items"][x]["DetailPageURL"] + '">' + 
             escapeHTMLEncode(truncate_string(data["Items"][x]["Title"], 65)).replace(new RegExp("("+queryTerms+")", "gi"), '<'+bold_tag+'>$1</'+bold_tag+'>') + '</a></span>' + 
'<span class="related-search-results-result-price">' + 
             data["Items"][x]["FormattedPrice"] + 
'</span>' +
'        </div>' + 
'    </div>');
                }
                $related_search_results.find(".related-search-results-result-title-link, .related-search-results-more-results-link").each(function(i)
                {
                    track_click($(this), {
                        "name": "related_search_result_clicked", 
                        "source": search_engine_name + " Search", 
                        "type": "Amazon", 
                        "queryTerms": queryTerms,
                        "action": "result #" + i + " clicked",
                        "first_amazon_result_index": first_amazon_result_index});
                });
                if(navigator.userAgent.indexOf("Chrome") != -1)
                {
                    $related_search_results.find("a").each(function()
                    {
                        var $a = $(this);
                        if($a.attr("href").indexOf("amazon") != -1)
                        {
                            var new_tag = "fstchrm-20";
                            if(first_amazon_result_index == -1)
                            {
                                new_tag = "fstfx2-20";
                            }
                            $a.attr("href", $a.attr("href").replace("tag=smtfx1-20", "tag=" + new_tag));
                            $a.attr("href", $a.attr("href").replace("tag%3Dsmtfx1-20", "tag%3D" + new_tag));
                        }
                    });
                }
            }, "json");
        };

		if(skip_ecommerce_query_check)
		{
			do_insert();
		}
        else if(is_ecommerce_query(queryTerms, search_result_a_patt))
        {   
            do_insert();
        }
        else
        {
            is_ecommerce_query2(queryTerms, function(result)
            {
                if(result)
                {   
                    do_insert();
                }
            });
        }
    };
    








































    var add_search_refinements_to_google = function(queryTerms)
    {
        add_search_refinements(queryTerms, "google", function($related_search_results)
        {
            var google_results = $("#res ol li");
            $(google_results[0]).before($related_search_results);
        }, "em");
    };

    var add_search_refinements_to_yahoo = function(queryTerms)
    {
        add_search_refinements(queryTerms, "yahoo", function($related_search_results)
        {
            var yahoo_results = $("#web ol li");
            $(yahoo_results[0]).before($related_search_results);
        }, "b");
    };

    var add_search_refinements_to_bing = function(queryTerms)
    {
        add_search_refinements(queryTerms, "bing", function($related_search_results)
        {
            var bing_results = $("#results ul li");
            $(bing_results[0]).before($related_search_results);
        }, "strong");
    };

    var add_search_refinements = function(queryTerms, search_engine_name, add_div, bold_tag)
    {
        if($("#scTopOfPageRefinementLinks").length == 0)
        {
            var partner = { 
                uiLabel: 'FastestFox Refinements',
                partnerCode: 'fastestfox', 
                authCode: 'knm75903'
            };        
            SW_$.get('http://' + partner.authCode + '.surfcanyon.com/queryReformulation', 
                        {"partner": partner.partnerCode,
                         "authCode": partner.authCode,
                         "format": "html",
                         "q": queryTerms.replace(/ /g, '+')}, function(data)
            {
                if($("#scTopOfPageRefinementLinks").length != 0)
                {
                    return;
                }
                if(data.replace(/^\s+|\s+$/, '') == "")
                {
                	data = '<b><a href="http://search.surfcanyon.com/search?f=nrl0&q=' + queryTerms + '&partner=fastestfox">' + queryTerms + '</a> &nbsp;</b>';
             	}
                var code = '<div id="scTopOfPageRefinementLinks" style="height: 20px; margin-top: 7px; margin-bottom: 7px;" partner="fastestfox" sctoppos="1">' + 
                '<font size=-1><span class="refinementResultsContainer">' + data + '</span>&nbsp;<font size =-1 color=green>' + partner.uiLabel +
                ' <a id="disableRefinements" style="text-decoration: none; color: green;" title="Disable" href="#">[x]</a></font></font></div>';//
                var $refinements = $(code);
                if($refinements.find(".refinementResultsContainer a").length == 0)
                {
                    return;
                }
                $refinements.find("#disableRefinements").click(function(event)
                {
                    if(doc.defaultView.confirm(confirm_disable))
                    { 
                        setBoolPref("add_search_refinements", false);
                        $refinements.slideUp("normal", function()
                            {
                                $refinements.remove();
                            });
                    }
                    return false;
                });
                add_div($refinements);
                $refinements.find(".refinementResultsContainer a").each(function(i)
                {
                    track_click($(this), {
                        "name": "search_refinement_clicked", 
                        "source": search_engine_name + " Search", 
                        "type": "Surf Canyon", 
                        "queryTerms": queryTerms,
                        "action": "result #" + i + " clicked"});
                });
            });
        } 
    };

    var add_related_search_results = function(doc)
    {
        //var googleURLRegExp = new RegExp("^http://www.google.(?:[^/]*)/(?:search\\?|#)(?:.*&)?q=([^&=]*)(.*)$");
        var googleURLRegExp = new RegExp("^http://www.google.(?:com|ca|co.uk|com.au|co.in|co.id|com.ph)/(?:search\\?|#)(?:.*&)?q=([^&=]*)(.*)$");
        var match = googleURLRegExp.exec(doc.location.href);
        if(match)
        {
            var queryTerms = decodeURIComponent(match[1]).replace(/\+/g, " ");

            getBoolPref("add_related_search_results_oneriot", function(pref_value)
            {
                if(pref_value) {
                    add_oneriot_results_to_google(queryTerms);
                }
            });
        }




        var googleURLTestRegExp = new RegExp("^http://www.google.(?:com|ca|co.uk|com.au|co.in|co.id|com.ph)/.*$");
        match = googleURLTestRegExp.exec(doc.location.href);
        if(match)
        {
			getBoolPref("add_search_refinements", function(pref_value)
			{
				if(pref_value) {
					var try_insert_google = function()
					{
						if($("#res ol li", doc).length > 0 
							&& $("#scTopOfPageRefinementLinks").length == 0
							&& !$("#res ol", doc).data("are_refinements_already_inserted"))
						{
							$("#res ol", doc).data("are_refinements_already_inserted", true);
							match = googleURLRegExp.exec(doc.location.href);
							var queryTerms = decodeURIComponent(match[1]).replace(/\+/g, " ");
							add_search_refinements_to_google(queryTerms);
						}
					};
					try_insert_google();
					document.addEventListener("DOMNodeInserted", function()
					{
						try_insert_google();
					}, false);
				}
			});
			
			getBoolPref("add_related_search_results_amazon", function(pref_value)
			{
				if(pref_value) {
					var try_insert_google = function()
					{
						if($("#res ol li", doc).length > 0 
							&& $(".related-amazon-search-results").length == 0
							&& !$("#res ol", doc).data("is_amzn_already_inserted"))
						{
							$("#res ol", doc).data("is_amzn_already_inserted", true);
							match = googleURLRegExp.exec(doc.location.href);
							var queryTerms = decodeURIComponent(match[1]).replace(/\+/g, " ");
							
							var google_com_URLRegExp = new RegExp("^http://www.google.com/(?:search\\?|#)(?:.*&)?q=([^&=]*)(.*)$");
							var com_match = google_com_URLRegExp.exec(doc.location.href);
							if(com_match)
							{
								add_amazon_results_to_google(queryTerms, "com");
							}            

							var google_co_uk_URLRegExp = new RegExp("^http://www.google.co.uk/(?:search\\?|#)(?:.*&)?q=([^&=]*)(.*)$");
							var co_uk_match = google_co_uk_URLRegExp.exec(doc.location.href);
							if(co_uk_match)
							{
								add_amazon_results_to_google(queryTerms, "co.uk");
							}            

							var google_de_URLRegExp = new RegExp("^http://www.google.de/(?:search\\?|#)(?:.*&)?q=([^&=]*)(.*)$");
							var de_match = google_de_URLRegExp.exec(doc.location.href);
							if(de_match)
							{
								add_amazon_results_to_google(queryTerms, "de");
							}            

							var google_fr_URLRegExp = new RegExp("^http://www.google.fr/(?:search\\?|#)(?:.*&)?q=([^&=]*)(.*)$");
							var fr_match = google_fr_URLRegExp.exec(doc.location.href);
							if(fr_match)
							{
								add_amazon_results_to_google(queryTerms, "fr");
							}            

							var google_ca_URLRegExp = new RegExp("^http://www.google.ca/(?:search\\?|#)(?:.*&)?q=([^&=]*)(.*)$");
							var ca_match = google_ca_URLRegExp.exec(doc.location.href);
							if(ca_match)
							{
								add_amazon_results_to_google(queryTerms, "ca");
							}            
						}
					};

					try_insert_google();
					document.addEventListener("DOMNodeInserted", function()
					{
						try_insert_google();
					}, false);
				}
			});
		}


        var walmartURLRegExp = new RegExp("^http(s)?://www.walmart.com/search/search-ng.do\\?(?:.*&)?search_query=([^&=]*)(.*)$");
        match = walmartURLRegExp.exec(doc.location.href);
        if(match)
        {
            queryTerms = decodeURIComponent(match[2]).replace(/\+/g, " ");
            getBoolPref("add_related_search_results_amazon", function(pref_value)
            {
                if(pref_value) {
                    add_amazon_results_to_walmart(queryTerms);
                }
            });
        }



        var yahooURLRegExp = new RegExp("^http://search.yahoo.com/search[^?]*\\?(?:.*&)?p=([^&=]*)(.*)$");
        match = yahooURLRegExp.exec(doc.location.href);
        if(match)
        {
            queryTerms = decodeURIComponent(match[1]).replace(/\+/g, " ");
            getBoolPref("add_related_search_results_amazon", function(pref_value)
            {
                if(pref_value) {
                    add_amazon_results_to_yahoo(queryTerms);
                }
            });
            getBoolPref("add_search_refinements", function(pref_value)
            {
                if(pref_value) {
                    add_search_refinements_to_yahoo(queryTerms);
                }
            });
        }
        
        var bingURLRegExp = new RegExp("^http://www.bing.com/search[^?]*\\?(?:.*&)?q=([^&=]*)(.*)$");
        match = bingURLRegExp.exec(doc.location.href);
        if(match)
        {
            queryTerms = decodeURIComponent(match[1]).replace(/\+/g, " ");
            getBoolPref("add_related_search_results_amazon", function(pref_value)
            {
                if(pref_value) {
                    add_amazon_results_to_bing(queryTerms);
                }
            });
            getBoolPref("add_search_refinements", function(pref_value)
            {
                if(pref_value) {
                    add_search_refinements_to_bing(queryTerms);
                }
            });
        }

        /*
        var baiduURLRegExp = new RegExp("^http://www.baidu.com/s[^?]*\\?(?:.*&)?wd=([^&=]*)(.*)$");
        match = baiduURLRegExp.exec(doc.location.href);
        if(match)
        {
            queryTerms = decodeURIComponent(match[1]).replace(/\+/g, " ");
        }
        */        
     };
    
    
    


    var doc = window.document;
    add_related_search_results(doc);  
    //$(document).ready(function()
    //if(SW_getBoolPref("extensions.smarterwiki.add_related_search_results"))
//});    
}());    
    