
function myfsn_PageSearch(params){
	var userId    = params["userId"];
	var pageEcom  = params["pageEcom"];
	var userEcom  = params["userEcom"];
	var userColor = params["userColor"];
	document.getElementById('displaySearchResults').style.display = "none";

	var searchTerms = createSmartSearchTerms(document.getElementById('myFSNSearch').value);
	
	
	if(searchTerms != ""){
		document.getElementById('displaySearchResults').style.display = "block";
	    document.getElementById('resultsMessage').innerHTML = "Searching";
		document.getElementById('showSearchTerms').innerHTML = "&nbsp;for '" + document.getElementById('myFSNSearch').value + "'.";
		BusyNotifier.showBusy({id:"searchBody",top:"180",left:"320"});
		
		var requestURL  = "/request/myfsn_Search.php";
			requestURL += "?search="    + searchTerms;
			requestURL += "&userId="    + userId;
			requestURL += "&pageEcom="  + pageEcom;
			requestURL += "&userEcom="  + userEcom;
			requestURL += "&userColor=" + userColor;
		var searchRequest = YAHOO.util.Connect.asyncRequest('GET',requestURL, {
			success:function(o){
				BusyNotifier.hideBusy("searchBody");
				var response = o.responseText;
				try { 
					var results = YAHOO.lang.JSON.parse(response); 
				} 
				catch (e) { 
					console.log("Invalid JSON"); 
					return;
				}
				switch(results['status']){
					//Found some products, so display them.
					case('0'):
						myfsn_displayProductSearchResults(results["products"],false);
						break;
					//No products were found in the search.
					case('1'):
						document.getElementById('resultsMessage').innerHTML = "Your search found 0 results ";
						myfsn_displayProductSearchResults(results["products"],true);
						break;
					//Something "impossible" happened.
					default:
						document.getElementById('resultsMessage').innerHTML = "Your search found 0 results ";
						document.getElementById('searchBody').innerHTML = "<font color='red'>An unknown error has occured.</font>";
						break;
				};
			},
			failure:  function(o){
				BusyNotifier.hideBusy("searchBody");
				document.getElementById('resultsMessage').innerHTML = "Your search found 0 results ";
				document.getElementById('searchBody').innerHTML = "<font color='red'>Request failed.</font>";
			}
		}, null);
	}
	else{
		document.getElementById('showSearchTerms').innerHTML = "";
		alert("You didn't enter valid search terms.");
		document.getElementById('searchBody').innerHTML = "";
	}
}

function createSmartSearchTerms(rawInput){
	//If they just hit the search button without entering anything
	//treat it like it was blank input.
	if(rawInput == "Search"){
		return "";
	}

	//Try to infer what the user wants
	//First clean up the white space and special characters
	var cleanInput = rawInput.replace(/(\(|\*|\^|\;|\>|\<|\\|\/|\)|\&|\!|\@|\#|\$|\%)/g, "");
	cleanInput     = strip(cleanInput," ");  				//Beginning and End
	cleanInput     = cleanInput.replace(/\s+/g, " ");	//Extra in the middle

	//Then check and see if there are quotes anywhere
	//We're going to try to find the first instance of a quote
	var doubleQuotePosition = [];
	var singleQuotePosition = [];
	doubleQuotePosition[0] = cleanInput.indexOf('"');
	singleQuotePosition[0] = cleanInput.indexOf("'");

	//Then we're going to see if there's more in order to
	//find literal strings
	var testIndex = 1;
	var lastIndex  = 0;
	if(doubleQuotePosition[0] != -1){
		//Loop to crawl through a string and get each
		//index where a quote appears
		while(testIndex != -1){
			//Find the next occurence from where the last one was found.
			testIndex = cleanInput.indexOf('"', doubleQuotePosition[lastIndex]+1);
			lastIndex++;
			//Only put it in the array if it's a good one
			if(testIndex != -1){
				doubleQuotePosition[lastIndex] = testIndex;
			}
		}
	}

	//Now do the single quotes
	testIndex = 1;
	lastIndex  = 0;
	if(singleQuotePosition[0] != -1){
		//Loop to crawl through a string and get each
		//index where a quote appears
		while(testIndex != -1){
			//Find the next occurence from where the last one was found.
			testIndex = cleanInput.indexOf('"', singleQuotePosition[lastIndex]+1);
			lastIndex++;
			//Only put it in the array if it's a good one
			if(testIndex != -1){
				singleQuotePosition[lastIndex] = testIndex;
			}
		}
	}

	//Only single quotes found.
	if( singleQuotePosition[0] != -1 && doubleQuotePosition[0] == -1 ){
		//To provide as many results as possible, we're not going to be
		//tolerant of single quotes as literals so remove them if they're
		//at the beginning and end.
		var strippedInput = cleanInput.replace(/^\'/,"");
		strippedInput = strippedInput.replace(/\'$/,"");
		
		//There were no double quotes, so we'll just make our search
		//string and encode the rest of the single quotes found.
		strippedInput = encodeURI(strippedInput.replace(/ /g, "+"));

		return strippedInput;
	}

	//Only double quotes found.
	if( doubleQuotePosition[0] != -1 && singleQuotePosition[0] == -1 ){
		var searchStrings = [];
		//Are the quotes at least in pairs?
		if((doubleQuotePosition.length%2) != 0){
			//Probably just a mistake.
			//Get rid of the odd one and proceed normally
			doubleQuotePosition.pop();
		}

		for(var i = 0; i < doubleQuotePosition.length; i=i+2){
			//Get what is between each pair of quotes
			var subString  = cleanInput.substr(doubleQuotePosition[i]+1,(doubleQuotePosition[i+1]) - (doubleQuotePosition[i]+1));
			searchStrings.push(subString);
		}
		
		//Now remove those strings from the initial input, and add to the searchStrings
		//whatever is left.
		var returnInput = cleanInput.replace(/\"/g, '');
		for(var j = 0; j < searchStrings.length; j++){
			returnInput = returnInput.replace(searchStrings[j],"");
		}
		
		//Clean up extra white space to be safe.
		returnInput = strip(returnInput," ");
		
		//Start transforming it into something to return
		returnInput = returnInput.replace(/ /g, "+");
		for(var k = 0; k < searchStrings.length; k++){
			returnInput += ":" + searchStrings[k];
		}

		//If we just had quotes, there may be a leading colon, so strip it
		returnInput = returnInput.replace(/^\:/,"");
		return encodeURI(returnInput);
		
	}

	//Did they mix their quotes?
	if( singleQuotePosition[0] != -1 && doubleQuotePosition[0] != -1 ){
		//Combine 1 and 2.
		//To provide as many results as possible, we're not going to be
		//tolerant of single quotes as literals so remove them if they're
		//at the beginning and end.
		var strippedInput = cleanInput.replace(/^\'/,"");
		strippedInput = strippedInput.replace(/\'$/,"");

		cleanInput = strippedInput;

		var searchStrings = [];
		//Are the quotes at least in pairs?
		if((doubleQuotePosition.length%2) != 0){
			//Probably just a mistake.
			//Get rid of the odd one and proceed normally
			doubleQuotePosition.pop();
		}

		for(var i = 0; i < doubleQuotePosition.length; i=i+2){
			//Get what is between each pair of quotes
			var subString  = cleanInput.substr(doubleQuotePosition[i]+1,(doubleQuotePosition[i+1]) - (doubleQuotePosition[i]+1));
			searchStrings.push(subString);
		}
		
		//Now remove those strings from the initial input, and add to the searchStrings
		//whatever is left.
		var returnInput = cleanInput.replace(/\"/g, '');
		for(var j = 0; j < searchStrings.length; j++){
			returnInput = returnInput.replace(searchStrings[j],"");
		}
		
		//Clean up extra white space to be safe.
		returnInput = returnInput.strip();
		
		//Start transforming it into something to return
		returnInput = returnInput.replace(/ /g, "+");
		for(var k = 0; k < searchStrings.length; k++){
			returnInput += ":" + searchStrings[k];
		}

		//If we just had quotes, there may be a leading colon, so strip it
		returnInput = returnInput.replace(/^\:/,"");
		return encodeURI(returnInput);
		

	}
	
	returnInput = encodeURI(cleanInput.replace(/ /g, ":"));
	return returnInput;
}

function myfsn_displayProductSearchResults(products,defaultItems){
	var productList  = "";
	for(var i = 0; i <= products.length-1; i++){
		productList += '<div class="product1" style="width:200px;height:240px;float:left;margin:10px;">';
		productList += '	<div style="text-align:center;vertical-align:bottom;">';
		productList += '		<a href="#prod' + i + '" style="border:0px;" onclick="popitup(\'' + products[i]["name"] + '\', \'' + products[i]["formattedShownAt"] + '\', \'http://www.myfsn.com/images/flowerdatabase/' + products[i]["imageLG"] + '\',\'' + products[i]["color"] + '\')">';
		productList += '			<img src="http://www.myfsn.com/images/flowerdatabase/' + products[i]["imageSM"] + '" alt="' + products[i]["name"] + '" />';
		productList += '		</a>';
		productList += '	</div>';
		productList += '	<h3>' + products[i]["name"] + '</h3>';
		productList += '	<p>' + products[i]["priceString"] + '</p>';
		productList += '	<p><a href="'+ products[i]["productLink"] +'"><img src="http://www.myfsn.com/images/CSS/base/' + products[i]["productSellImageDisplay"] + '"  alt="' + products[i]["purchaseAlt"] + '" /></a></p>';
		productList += '</div>';
	}
	if(defaultItems){
		document.getElementById('searchBody').innerHTML  = "";
		document.getElementById('searchBody').innerHTML += "<center>No results where found, but you may be interested in these.</center><br>";
		document.getElementById('searchBody').innerHTML += productList;
	}
	else{
		document.getElementById('resultsMessage').innerHTML = "Your search found " + products.length + " results ";
		document.getElementById('searchBody').innerHTML = productList;
	}
	
}

function myfsn_CloseSearch(){
	document.getElementById('displaySearchResults').style.display = "none";
}

function clearSearch(){
	document.getElementById('myFSNSearch').value = "";
}

function checkEnter(e, params){ //e is event object passed from function invocation
	var characterCode; // literal character code will be stored in this variable

	if(e && e.which){ //if which property of event object is supported (NN4)
		characterCode = e.which; //character code is contained in NN4's which property
	}
	else{
		e = event
		characterCode = e.keyCode; //character code is contained in IE's keyCode property
	}

	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		myfsn_PageSearch(params);
		return false;
	}
	else{
		return true;
	}

}

function strip(string, chars) {
  return string.
    replace(new RegExp('['  + (chars || '\\s') + ']*$'), '').
    replace(new RegExp('^[' + (chars || '\\s') + ']*'),  '')
}
