Ssieth / Amazon Search Saver

// ==UserScript==
// @name        Amazon Search Saver
// @namespace   amazonesearchsaver.gaxx.co.uk
// @description Save Amazon Searches
// @include     https://www.amazon.co.uk/*
// @version     0.0.1
// @require     https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js
// @require     https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js
// @grant       GM_getValue
// @grant       GM_setValue
// ==/UserScript==

var savedSearches = [];		// An array of search objectes {name, url}
var $menu = {};				// A JQuery object representing the menu we are messging about with

// Get a url parameter when provided the name.
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

// Get rid of some of the menu items we don't use
function cleanMenu() {
	$menu.find('a').each(function() {
		switch ($(this).text().trim()) {
			case "Gift Cards":
			case "Sell":
			case "Help":
				$(this).remove();
				break;
			default:
				break;
		}
	});
}

// Save the current url as a new search
function saveSearch() {
	var strSearch = getParameterByName('field-keywords');
	var objSearch = {};
	objSearch.name = strSearch;
	objSearch.url = window.location.href;
	savedSearches.push(objSearch);
	displayMenu();
	saveSearches();
}

// Save all searches to db so that we can load them in future sessions
function saveSearches() {
	GM_setValue("searches",savedSearches);
}

// Load all searches from db
function loadSearches() {
	savedSearches = GM_getValue("searches", []);
}

// Clear out any menu items we have already added and then add our searches and a link to save searches.
function displayMenu() {
	// Remove any menu items we have added in the past
	$menu.find('a.gm_menu_save').remove();
	
	// Add each of our saved searches
	for (var i = 0; i < savedSearches.length; i++) {
		var objSearch = savedSearches[i];
		$menu.append('<a href="' + objSearch.url + '" class="nav-a gm_menu_save">' + objSearch.name + '</a>');
	}
	
	// Add the link that saves new searches
	$menu.append('<a href="#" class="nav-a gm_menu_save" tabindex="22" id="gm_add_search">Save</a>');
	var $addSearch = $('a#gm_add_search');
	$addSearch.click(function(e) {
		e.preventDefault();
		saveSearch();
	});
}

// Once the page is fully loaded then do our stuff
$(document).ready(function() {
	loadSearches();
	$menu = $('div#nav-xshop');
	cleanMenu();
	displayMenu();
});