/*
    Copyright (c) 2011 Y-Times Publications, LLC. Duplication without written consent of Y-Times Publications, LLC
    is prohibited.

    Checks the referrer (search engine), retrieves the search keyphrase and replaces the page name and title 
    with the search term. Works with Google, Yahoo, and Bing.
    
    Install it at the bottom of the page (or anywher after the page name).

    Sample referrers:
    Google
    http://www.google.com/url?sa=t&source=web&cd=7&ved=0CGwQFjAG&url=http%3A%2F%2Fwww.simplybabyfurniture.com%2Fshop-by-collection-da-vinci-kalani.html&rct=j&q=davinci%20kalani%20crib&ei=LuZWTZGMDY2WsgPzxYyjDA&usg=AFQjCNEcQKI6d07hiVd0kO8-TFZvFAKGzg&sig2=p_88vZkInC5yzt3Aa3xdSA

    Yahoo
    http://search.yahoo.com/search;_ylt=AgPujQNV9lrIBHmjGhmk.7KbvZx4?p=davinci+kalani+crib&toggle=1&cop=mss&ei=UTF-8&fr=yfp-t-701

    Bing
    http://www.bing.com/search?q=davinci+kalani+crib&go=&form=QBLH&qs=n&sk=&sc=8-19
*/
if (typeof (ytimesPageTitleSelector) == "undefined") {
    var ytimesPageTitleSelector = "h1";
}

var referrer = document.referrer;

// referrer = "http://search.yahoo.com/search;_ylt=AgPujQNV9lrIBHmjGhmk.7KbvZx4?p=davinci+kalani+crib&toggle=1&cop=mss&ei=UTF-8&fr=yfp-t-701";

String.prototype.toProperCase = function () {
    return this.toLowerCase().replace(/^(.)|\s(.)/g, function ($1) { return $1.toUpperCase(); });
}

var isGoogle = referrer.indexOf("www.google.com") > -1;
var isYahoo = referrer.indexOf("search.yahoo.com/search") > -1;
var isBing = referrer.indexOf("www.bing.com/search") > -1;

if (isGoogle || isYahoo || isBing ) {
    var j = referrer.indexOf("?");
    if (j > -1) {
        referrer = referrer.substring(j + 1);
        var refTerms = referrer.split("&");
        for (var i = 0; i < refTerms.length; i++) {
            var refTerm = refTerms[i];
            var pair = refTerm.split("=");
            if ((pair[0] == "q" && (isBing || isGoogle)) || (isYahoo && pair[0]=="p")) {
                var searchTerm = unescape(pair[1]).replace(/\+/gi, " ").toProperCase();
                if (searchTerm != "") {
                    jQuery(ytimesPageTitleSelector).text(searchTerm);
                    document.title = searchTerm;
                }
                break;
            }
        }
    }
}


