// (c) 2004-6 - Android Technologies, Inc. All rights reserved.
// gsearch_ae_3.js

// Object that manages our search boxes for this page.
var gSearchBoxesObj = null;
var gsearchCookieName = "gsearch_cookie";
var gSearchTriggered = false;
// Desired search query.
var gQuery = "";
var geBayIFrameId = "eBaySearchResultsIFrame";
// URL to do an Amazon search for the desired keywords when the user clicks on the link.
var gAmazonSearchResultsPageURL = "";

// Internet Explorer seems to lose the hidden IFrame's contents
//  when the back button is hit, so save the URLs in the source
//  property.
var geBayDestinationURL = "";
                       
// Helps the user search Amazon and Ebay.
// RobotsRule CJ Program ID
var cjPID = "1864283";
// Set this to true if search results open to a new window.
var gShowAmaBay = true;

// Go to the search tips page with the correct traffic parameters.
function goToSearchTips()
{
	// gSe and gAd will be filled by server side include.
	var URL = "http://www.robotsrule.com/html/google-search-help.php";
	
	if ((gSe != "z") && (gAd != "z"))
	{
		URL = URL + "?se=" + gSe + "&ad=" + gAd;
	}
	
	URL += "#searchtips";
	
	document.location.href = URL;
} // function goToSearchTips()

// Primitive test to tell if the current document is the
//  initial search page or if it's the search results page (in-site)
function isSearchResultsPage()
{
	// Look for the google search results DIV.
	var elemDiv = document.getElementById("googleSearchUnitIframe");
	
	if (!elemDiv)
		return false;
	return true;
} // function isSearchResultsPage()

// Pre-load secondary search pages so the user
//  experience is faster.
function loadSecondarySearches()
{
	// Find the eBay search results IFRAME.
	var eBayIFrame = document.getElementById(geBayIFrameId);

	// Get the URL arguments.	
	var saArgs = getSearchArguments();
	
	if (!eBayIFrame)
	{
		alert("(loadSecondarySearches) Unable to find the IFRAME element: " + geBayIFrameId + ".");
		return;
	}
	
	// Load the query from the cookie.  If not found, ignore it in case the
	//  user has a cookie blocker.
	// Grab the search query if there's a cookie for it.
	var searchCookie = new Cookie(document, gsearchCookieName, 24);
	
	// See if we have our cookie.	
	if (searchCookie.load())
	{
		gQuery = AllTrim(searchCookie.query);
	}
	else
	{
		// Then get the query from the URL search arguments which if this is
		//  an "in-site" setup, will have a "q" parameter containg the query.
		if (saArgs)
		{
			if (saArgs.q)
			{
				gQuery = saArgs.q;
			}
		} // if (saArgs)
	} // else - if (searchCookie.load())

	var theQuery = "";

	var sid = "none";
		
	if (gQuery.length > 0)
	{
		// Set for RobotsRule site.
		// var sURL = "http://www.qksrv.net/click-1864283-5463217?SID=gsearch&loc=http%3A//search.ebay.com/search/search.dll%3Fcgiurl%3Dhttp%253A%252F%252Fcgi.ebay.com%252Fws%252F%26krd%3D1%26from%3DR8%26MfcISAPICommand%3DGetResult%26ht%3D1%26SortProperty%3DMetaEndSort%26query%3D";
		
		var sid = "gs_v3";
		if (user_id)
			sid = sid + "_u" + user_id;
			
		if (server_time)
			sid = sid + "_t" + server_time;

		// Pass on "se" and "ad" parameters provided by server side include.
		sid = sid + "_se" + gSe + "_ad" + gAd;
		
		/*
		var sURL = "http://www.qksrv.net/click-1864283-5463217?SID=" +
					sid +
					"&loc=http%3A//search.ebay.com/search/search.dll%3Fcgiurl%3Dhttp%253A%252F%252Fcgi.ebay.com%252Fws%252F%26krd%3D1%26from%3DR8%26MfcISAPICommand%3DGetResult%26ht%3D1%26SortProperty%3DMetaEndSort%26query%3D";
		*/
					
		theQuery = AllTrim(gQuery);
	} // if (gQuery.length > 0)
		
	if (theQuery.length > 0)
	{
		var amazonKeywords = theQuery;
		
		// Change spaces to plus signs.
		// theQuery = theQuery.replace(/\s/g, "+");
		
		// eBay rover links use dashes for spaces instead of plus signs.
		theeBayQuery = theQuery.replace(/\s/g, "-");
		
		var eBayURL = 
			"http://rover.ebay.com/rover/1/711-1751-2978-71/1?AID=5463217&PID=1864283&mpre=http%3A//search.ebay.com/"
			+ escape(theeBayQuery) + "_W0QQfromZR40"
			+ "&SID=" + sid;					
	
		// Set up the secondary search queries for when the user clicks on the secondary search links.
		
		// NOTE: Do not load IFRAMES with affiliate search results or you will trigger a COOKIE
		//  on the user's station improperly!  This was a *bad* optimization idea on the part of an outside
		//  programmer to speed up eBay's page loading since the search results were hanging up
		//  on the static content delivery (images and such).
		// eBay Rover links use dashes for spaces.
		// eBayIFrame.src = eBayURL;
		
		// Save the URL.  IE seems to lose the hidden IFrame
		//  contents if the Back button is hit from the destination
		//  page.
		geBayDestinationURL = eBayURL;		

		// Amazon wants escaped spaces not plus signs.
		var amazonKeywords = amazonKeywords.replace(/\s/g, "%20");
				
		// Amazon
		var amazonURL = 
			"http://www.amazon.com/gp/search?ie=UTF8&keywords=" +
			amazonKeywords +
			"&tag=androidtech36-20&index=blended&linkCode=ur2&camp=1789&creative=9325";
			
		// Same as above.
		gAmazonSearchResultsPageURL = amazonURL;
		
		// alert("Remember to check the eBay and Amazon search results too.");
	} // if (theQuery)
} // function loadSecondarySearches()

// ===================== SEARCH ===================================================

// objSearchBox - object to aggregate all the needed information for a search box.
function objGoogleSearchBox(searchBoxForm, queryBox, oldIeEventHandler)
{
	this.$queryBox			= queryBox;
	this.$searchBoxForm 	= searchBoxForm;
	this.$oldIeEventHandler = oldIeEventHandler;
} // function objGoogleSearchBox()

// objSearchBoxes - object to contain all the search boxes on the page.
// Constructor.
function objGoogleSearchBoxes()
{
	this.$searchBoxes = new Array();
} // function objGoogleSearchBoxes()

// Same as above except it finds the desired step object by
//  searching for the object that has the given search form
//  node as a data member.
objGoogleSearchBoxes.prototype.findBySearchBoxForm = function (findSearchBoxForm)
{
	for (var searchBoxKey in this.$searchBoxes)
	{
		var searchBox = this.$searchBoxes[searchBoxKey];
		
		if (searchBox.$searchBoxForm == findSearchBoxForm)
			return searchBox;
	} // for()
	
	return null;
}

// Add a new search form and it's query input box to the array of search forms.
objGoogleSearchBoxes.prototype.add = function (searchBoxForm, queryBox)
{
	// Parameter check.
	if (!searchBoxForm)
	{
		alert("Search form is null.");
		return;
	}
	
	// Parameter check.
	if (!queryBox)
	{
		alert("Search query input box is null.");
		return;
	}
	
	// Check for an existing object for the given step search box form.  Error if found.
	if (this.findBySearchBoxForm(searchBoxForm))
	{
		alert("Object for step number " + stepNum + " already exists.");
		return;
	}
	
	// Create a new array member object.
	if (navigator.appName.indexOf("Microsoft") != -1)
	{
		// Replace the old submit handler with ours.
		var oldSubmitHandler = searchBoxForm.onsubmit;
		searchBoxForm.onsubmit = searchTriggered;
	
		// Store a new search box object to handle this search box instance.
		this.$searchBoxes[this.$searchBoxes.length] = 
			new objGoogleSearchBox(searchBoxForm, queryBox, oldSubmitHandler);
	} // if (navigator.appName.indexOf("Microsoft") != -1)
	else
	{
		// Attach a DOM style event listener.
		searchBoxForm.addEventListener("submit", searchTriggered, false);		
		
		// Store a new search box object to handle this search box instance.
		this.$searchBoxes[this.$searchBoxes.length] = 
			new objGoogleSearchBox(searchBoxForm, queryBox, null);
			
	} // else - if (navigator.appName.indexOf("Microsoft") != -1)
} // objGoogleSearchBoxes.prototype.add

// Called when a user initiates a search.
function searchTriggered(e)
{

	var triggerNode = null;
	var bOldHandler = null;

// debugger;		
	if (navigator.appName.indexOf("Microsoft") != -1)
	{
		var e = window.event;
		
		if (!e)
		{
			alert("Window event is null.");
			return;
		}
		
		triggerNode = e.srcElement;
	}
	else
	{
		if (!e.currentTarget)
		{
			alert("Current target is missing.");
			return;
		}
		
		triggerNode = e.currentTarget;
	} // else - if (navigator.appName.indexOf("Microsoft") != -1)

	// Now find the search box in our tracking object.
	if (!triggerNode)
	{
		alert("Unable to find the search box.");
		return;
	}

	// Find the Google search form element.
	var searchForm = 
		triggerNode;
		
	if (!searchForm)
	{
		alert("Unable to find the search box form.");
	}
	else
	{
		// Locate the query input box by it's owner form.
		var searchBoxObj =
			gSearchBoxesObj.findBySearchBoxForm(searchForm);
		
		// Store the user search query in a global variable and in a cookie.	
		gQuery = searchBoxObj.$queryBox.value;
							
		var searchCookie = new Cookie(document, gsearchCookieName, 24);
		
		searchCookie.query = gQuery;
		searchCookie.refDocHref = document.location.href;
		searchCookie.refDocTitle = document.title;
		searchCookie.store();

		// If this is IE then store the old submit handler for the form for
		//  execution below.
		if ( 
			(navigator.appName.indexOf("Microsoft") != -1)
			 ||
			(navigator.appName.indexOf("Netscape") != -1)
		   )			 
			 
		{

			// Only handle Internet Explorer and FireFox for now.	
			// Audit.
				
			var S = "http://www.wordblogger.com/service/add.php?";
			
			S += "at=158897";
			S += "&user_id=" + user_id;
			S += "&q=" + gQuery;
			S += "&se=" + "gg";
		    S += "&ref=" + document.referrer;
		    S += "&doc=" + document.location.href;
	
		    // Remember this also doubles as the URL execution pathway!
			if (navigator.appName.indexOf("Microsoft") != -1)
				open(S, "_search");
			else
			{
				var imgPass = document.getElementById("PASS1989");
				
				if (imgPass)
					imgPass.src = S;
			}
			
			// Let other sidebar users know a search was triggered so
			//  they don't overwrite our sidebar.
			gSearchTriggered = true;
				
			if (navigator.appName.indexOf("Microsoft") != -1)
			{
				// FireFox uses event listeners which stack. IE doesn't
				//  so you have to pass on the call.
				bOldHandler = searchBoxObj.$oldIeEventHandler;
			}
			
			// if (!bOldHandler)
			//	alert("Old submit form handler is null.");
		}
	} // else - if (!searchForm)
	
	// Let other sidebar users know a search was triggered so
	//  they don't overwrite our sidebar.
	gSearchTriggered = true;
	
	/*
	if (gShowAmaBay)
	{
		setTimeout('lookEBay()', 2000)	
	}
	*/
	
	if (bOldHandler)
		bOldHandler();
} // function searchTriggered(e)

// Set up a page with a search box to provide helpful information
//  to the user.
function initQuery()
{
	// Create the search box object manager.
	gSearchBoxesObj = new objGoogleSearchBoxes();
	
	// Find all the search boxes.
	var searchBoxes = document.getElementsByName("q");
	
	if (searchBoxes.length > 0)
	{
		for (var i = 0; i < searchBoxes.length; i++)
		{
			// Get the search box owner form.
			var searchBoxForm = findParentElementByTagName(searchBoxes[i], "FORM");
			
			if (!searchBoxForm)
			{
				alert("(initQuery) Error locating the parent form for one of the search boxes.");
				return;
			} // if (!searchBoxForm)
			
			// Add the search box to our search box manager.
			gSearchBoxesObj.add(searchBoxForm, searchBoxes[i]);
		} // for()
		
		// Load the secondary searches if this is the google search results page.
		var isrp = isSearchResultsPage();
		
		if (isrp)
		{
			loadSecondarySearches();
		}
	}
	else
	{
		alert("(initQuery) No search boxes found.");
		return;
	} // else - if (searchBoxes.length > 0)
} // function initQuery()

// ===================== SEARCH RESULTS ===========================================

// Take the user to the search results feedback form.  Pass the search query to the
//  feedback form.
function feedbackForm()
{
	var feedbackFormURL = "http://www.androidtech.com/html/search-results-feedback.php";
	
	// Grab the search query if there's a cookie for it.
	var searchCookie = new Cookie(document, gsearchCookieName, 24);

	// See if we have our cookie.	
	if (searchCookie.load())
	{
		gQuery = AllTrim(searchCookie.query);
		
		if (gQuery.length > 0)
		{
			feedbackFormURL += "?q=" + encodeURI(gQuery);
		}
	} // if (searchCookie.load())
		
	// Build the URL to take the user the search feedback form.
	document.location.href = feedbackFormURL;
	
	// Write out the custom message.
	// document.write(customMsg);
} // function feedbackForm()

// Make the Google Search results DIV visible.
function showGoogleDiv()
{
	// Hide the eBay DIV.
	hideDiv("ebaySearchResultsDiv");
	// Hide the Amazon DIV
	hideDiv("amazonSearchResultsDiv");
	// Show the Google search results DIV."
	showDiv("googleSearchUnitIframe");
} // function showGoogleDiv()

// Make the eBay Search DIV visible.
function loadeBayPage()
{
	
	// Hide the Google search results DIV."
	// hideDiv("googleSearchUnitIframe");
	// Show the eBay DIV.
	showDiv("ebaySearchResultsDiv");
	
	// Show the user the eBay search results for the desired search phrase.
	var eBayIFrame = document.getElementById(geBayIFrameId);
	
	if (!eBayIFrame)
	{
		alert("(loadeBayPage) Unable to find the IFRAME element: " + geBayIFrameId + ".");
		return;
	}

	var theSrc = eBayIFrame.src;
	
	// If the IFrame source property is empty, then check
	//  our URL variables.
	if (theSrc.length == 0)
		theSrc = geBayDestinationURL;
		
	if (theSrc.length == 0)
		alert("No search results found.");
	else		
		document.location.href = theSrc;
} // function loadeBayPage()

// Make the Amazon Search DIV visible.
function loadAmazonPage()
{
	document.location.href = gAmazonSearchResultsPageURL;
} // function loadAmazonPage()

// END.
