// Copyright (c) 2009 Appropriate Solutions, Inc. All rights reserved. 
// Written for @Website Publicity, Inc. as Work for Hire.
//

// When TEST is true, use fake referrer and do not actually redirect.
var TEST = false;

function get_query_string() {
    // Get query parameters from referrer. 
    // Query format depends on search engine source.
    
    // Assume we do not find query parameters
    var query = '';

    // decode the referrer so we can do proper matches.
    referrer = decodeURIComponent(document.referrer);

    // !!! TEST !!!
    if (TEST) {
//        referrer = 'http://www.google.com/?q=Sneakers';
        referrer = 'http://www.google.com/?q=SHOES';
    }
    
    if (referrer.match(/^http:\/\/(www\.)?alltheweb.*/i)) {
        // AllTheWeb
        if (referrer.match(/q=/)) {
                query = referrer.replace(/^.*q=([^&]+)&?.*$/i, '$1');
            }
    } else if (referrer.match(/^http:\/\/(www)?\.?google.*/i)) {
        // Google
        if (referrer.match(/q=/)) {
                query = referrer.replace(/^.*q=([^&]+)&?.*$/i, '$1');
            }
    } else if (referrer.match(/^http:\/\/search\.lycos.*/i)) {
        // Lycos
        if (referrer.match(/query=/)) {
                query = referrer.replace(/^.*query=([^&]+)&?.*$/i, '$1');
            }
    } else if (referrer.match(/^http:\/\/search\.msn.*/i)) {
        // MSN
        if (referrer.match(/q=/)) {
                query = referrer.replace(/^.*p=([^&]+)&?.*$/i, '$1');
            }
    } else if (referrer.match(/^http:\/\/search\.yahoo.*/i)) {
        // Yahoo
        if (referrer.match(/p=/)) {
                query = referrer.replace(/^.*p=([^&]+)&?.*$/i, '$1');
            }
    }

    if (query) {
	   query = query.replace(/\'|"/, '');
	
	   // Want to do string compares, so we skip breaking into an array.
	   //query = query.split(/[\s,\+\.]+/);
    }

    return query;
};


function get_redirect_location(query) {
    // Search through the query for places we want to go.
    var result = null;
    
    query = query.toLowerCase();
    
    if (query.match(/shed/)) {
        result = 'http://www.brewerymall.com/brewpubs/shed-brewery.html';
    } else if (query.match(/stowe/)) {
        result = 'http://www.brewerymall.com/brewpubs/shed-brewery.html';
    }
    return result
}


// MAIN

// Get the query.
var query = get_query_string();

// And see where it takes us.
var redirect = get_redirect_location(query);

if (TEST) {
    alert('Redirect: ' + redirect);
} else {
    if(redirect) {
        location.replace(redirect);
    }
}