// NOTE: This file is also on acclaimsoftware.com,  re-upload if any changes are made to this file
// NOTE: When developing in javascript, remember to CTRL-F5 to force reload of .js file

// -------------------------------------------------------------
// MISC CODE
// -------------------------------------------------------------
String.prototype.fixupGTLT = function ()
{
	// Create a new prototype for string - convert all &amp;lt; and &amp;gt; to &lt; and &gt;, note: uses regular expressions, /ig = case insensitive (i) and global/replace all (g)
	// Yahoo returns things like &amp;lt; (should be &lt;)

	return this.replace(/&amp;lt;/ig, '&lt;').replace(/&amp;gt;/ig, '&gt;');
};


String.prototype.fixupSpeechMarks = function ()
{
	// Create a new prototype for string - convert all ' to \', note: uses regular expressions, /ig = case insensitive (i) and global/replace all (g)

	return this.replace(/'/g, '\\\'');
};


String.prototype.ReplaceMSLiveHighlightingCharacters = function(beginStr, endStr)
{
	// Replace all occurrences of U+E000 (begin highlighting) with
	// beginStr. Replace all occurrences of U+E001 (end highlighting)
	// with endStr.
	var regexBegin = new RegExp("\uE000", "g");
	var regexEnd = new RegExp("\uE001", "g");
		  
	return this.replace(regexBegin, beginStr).replace(regexEnd, endStr);
}


function resizeFrame(frame)
{
	// Resizes an iframe

	frame.style.height = frame.contentWindow.document.body.scrollHeight + "px";
}


// -------------------------------------------------------------
// SEARCH CODE
// -------------------------------------------------------------
function ToggleResults(SearchEngine, Region, SearchFor)
{
	if (SearchEngine == 'Google')
	{
		var ele = document.getElementById("GoogleSearchControl");
		var text = document.getElementById("GoogleTextLink");
	}
	else if (SearchEngine == 'Yahoo')
	{
		var ele = document.getElementById("YahooSearchControl");
		var text = document.getElementById("YahooTextLink");
	}
	else if (SearchEngine == 'Live')
	{
		var ele = document.getElementById("LiveSearchControl");
		var text = document.getElementById("LiveTextLink");
	}
	else if (SearchEngine == 'Gigablast')
	{
		var ele = document.getElementById("GigablastSearchControl");
		var text = document.getElementById("GigablastTextLink");
	}
	else
	{
		var ele = document.getElementById("IsawikiSearchControl");
		var text = document.getElementById("IsawikiTextLink");
	}

	if (ele.style.display == 'block')
	{
		ele.style.display = 'none';
		text.innerHTML = 'Show';
	}
	else
	{
		if (SearchEngine == 'Google' && DoneGoogleSearch == false)
		{
			DoGoogleSearch();
		}
		else if (SearchEngine == 'Yahoo' && DoneYahooSearch == false)
		{
			DoYahooSearch(SearchFor);
		}
		else if (SearchEngine == 'Live' && DoneMSLiveSearch == false)
		{
			DoMSLiveSearch(SearchFor);
		}
		else if (SearchEngine == 'Gigablast' && DoneGigablastSearch == false)
		{
			DoGigablastSearch(SearchFor);
		}

		ele.style.display = 'block';
		text.innerHTML = 'Hide';
	}
	document.SearchBox.search.focus()
}


// -------------------------------------------------------------
// GOOGLE SEARCH CODE
// -------------------------------------------------------------
function DoGoogleSearch()
{
	var scriptStr = document.createElement('script');
	scriptStr.type ='text/javascript';
	scriptStr.src = 'http://www.google.com/jsapi?callback=LoadGoogleSearch';
	document.getElementsByTagName('head')[0].appendChild(scriptStr);
}


function LoadGoogleSearch()
{
	google.load('search', '1', {'callback' : ExecuteGoogleSearch});
}


function ExecuteGoogleSearch()
{
	// Create a search control
	var searchControl = new google.search.SearchControl();
	// Add in a full set of searchers
	searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET); // LARGE_RESULTSET = 8
	searchControl.addSearcher(new google.search.WebSearch());
	searchControl.addSearcher(new google.search.VideoSearch());
	searchControl.addSearcher(new google.search.BlogSearch());
	searchControl.addSearcher(new google.search.ImageSearch());
	searchControl.addSearcher(new google.search.NewsSearch());
	if (gsRegion != 'World')
	{
		var ls = new google.search.LocalSearch();
		searchControl.addSearcher(ls);
		ls.setCenterPoint(gsRegion);
	}
	// tell the searcher to draw itself and tell it where to attach
	var drawOptions = new google.search.DrawOptions();
	drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
	//	searchControl.draw(document.getElementById("GoogleSearchControl"));
	searchControl.draw(document.getElementById("GoogleSearchControl"), drawOptions);
	// execute an inital search
	searchControl.execute(gsSearchFor);

	// Enable the branding logo
	var googlediv = document.getElementById('GoogleSearchControl');
	var brandingdiv = document.createElement('div');
	brandingdiv.id = 'GoogleBrandingImg';
	googlediv.appendChild(brandingdiv);
	google.search.Search.getBranding(document.getElementById("GoogleBrandingImg"));

	DoneGoogleSearch = true;
}


// -------------------------------------------------------------
// YAHOO SEARCH CODE
// -------------------------------------------------------------
function DoYahooSearch(SearchFor)
{
	var requestStr = document.createElement('script');
	requestStr.type ='text/javascript';
	requestStr.charset ='utf-8';
	requestStr.src = 'http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&output=json&callback=DisplayYahooSearch&query=' + SearchFor;
	document.getElementsByTagName('head')[0].appendChild(requestStr);

	DoneYahooSearch = true;
}


function DisplayYahooSearch(response)
{
	var yahoodiv = document.getElementById('YahooSearchControl');
	yahoodiv.innerHTML = '';

	var containerdiv = document.createElement('div');
	containerdiv.className = 'yahoo-container';

	for (var i = 0; i < response.ResultSet.Result.length; i++)
	{

		// <yahoo-container> / <search-results>
		//	<search-result>
		//		<search-title>
		//		<search-summary>
		//		<search-displayurl>

		var resultdiv = document.createElement('div');
		var titlediv = document.createElement('div');
		var summarydiv = document.createElement('div');
		var urldiv = document.createElement('div'); 
		var a = document.createElement('a');

		resultdiv.className = 'search-result';

		// Create the title div, and the title link then attach it to the title div tag
		titlediv.className = 'search-title';
		a.href = response.ResultSet.Result[i].Url;
		a.innerHTML = response.ResultSet.Result[i].Title.fixupGTLT();
		titlediv.appendChild(a);

		// Create the summary
		summarydiv.className = 'search-summary';
		summarydiv.innerHTML = response.ResultSet.Result[i].Summary.fixupGTLT();

		// Create the display url
		urldiv.className = 'search-displayurl';
		urldiv.innerHTML = response.ResultSet.Result[i].DisplayUrl;

		// All the divs fall under the Yahoo-Result div, so append them
		resultdiv.appendChild(titlediv);
		resultdiv.appendChild(summarydiv);
		resultdiv.appendChild(urldiv);

		// The result div falls under the container, so append it
		containerdiv.appendChild(resultdiv);

	}

	// Now append the container div to the YahooSearchResults div
	yahoodiv.appendChild(containerdiv);
	
	// Yahoo requires a linked image to be displayed as per their t&c
	var yahooimg = document.createElement('a');
	yahooimg.href = "http://developer.yahoo.com/";
	yahooimg.innerHTML += "<img class='YahooImg' src='http://l.yimg.com/us.yimg.com/i/us/nt/bdg/websrv_120_1.gif' border='0'>";
	yahoodiv.appendChild(yahooimg);
}


// -------------------------------------------------------------
// MS LIVE SEARCH CODE
// -------------------------------------------------------------
function DoMSLiveSearch(SearchFor)
{
	var requestStr = "http://api.search.live.net/json.aspx?"
	
	// Common request fields (required)
	+ "AppId=3F1E7D3379AED47081E3AE0F017B91F93CF9ABE5"
	+ "&Query=" + SearchFor
	+ "&Sources=Web"
	
	// Common request fields (optional)
	+ "&Version=2.0"
	+ "&Market=en-us"
	+ "&Adult=Moderate"
//	+ "&Options=EnableHighlighting"

	// Web-specific request fields (optional)
	+ "&Web.Count=10"
	+ "&Web.Offset=0"
	+ "&Web.FileType=DOC"
	+ "&Web.Options=DisableHostCollapsing+DisableQueryAlterations"

	// JSON-specific request fields (optional)
	+ "&JsonType=callback"
	+ "&JsonCallback=DisplayMSLiveSearch";

	var requestScript = document.createElement("script");
	requestScript.type = "text/javascript";
	requestScript.src = requestStr;
	
	document.getElementsByTagName("head")[0].appendChild(requestScript);
	
	DoneMSLiveSearch = true;
}


function DisplayMSLiveSearch(response)
{
	var errors = response.SearchResponse.Errors;
	if (errors != null)
	{
		// There are errors in the response. Display error details.
		DisplayMSLiveSearchErrors(errors);
	}
	else
	{
		// There were no errors in the response. Display the
		// Web results.
		DisplayMSLiveSearchResults(response);
	}
}


function DisplayMSLiveSearchErrors(errors)
{
	var mslivediv = document.getElementById("LiveSearchControl");
	mslivediv.innerHTML = "";

	var errorsHeader = document.createElement("h4");
	var errorsList = document.createElement("ul");
	mslivediv.appendChild(errorsHeader);
	mslivediv.appendChild(errorsList);
	
	// Iterate over the list of errors and display error details.
	errorsHeader.innerHTML = "Errors:";
	var errorsListItem = null;
	for (var i = 0; i < errors.length; ++i)
	{
		errorsListItem = document.createElement("li");
		errorsList.appendChild(errorsListItem);
		errorsListItem.innerHTML = "";
		for (var errorDetail in errors[i])
		{
			errorsListItem.innerHTML += errorDetail
				+ ": "
				+ errors[i][errorDetail]
				+ "<br />";
		}
		errorsListItem.innerHTML += "<br />";
	}
}


function DisplayMSLiveSearchResults(response)
{

	var mslivediv = document.getElementById('LiveSearchControl');
	mslivediv.innerHTML = '';

	var containerdiv = document.createElement('div');
	containerdiv.className = 'mslive-container';

	for (var i = 0; i < response.SearchResponse.Web.Results.length; i++)
	{

		// <mslive-container> / <search-results>
		//	<search-result>
		//		<search-title>
		//		<search-summary>
		//		<search-displayurl>

		var resultdiv = document.createElement('div');
		var titlediv = document.createElement('div');
		var summarydiv = document.createElement('div');
		var urldiv = document.createElement('div');
		var a = document.createElement('a');

		resultdiv.className = 'search-result';

		// Create the title div, and the title link then attach it to the title div tag
		titlediv.className = 'search-title';
		a.href = response.SearchResponse.Web.Results[i].Url;
		a.innerHTML = response.SearchResponse.Web.Results[i].Title.fixupGTLT().ReplaceMSLiveHighlightingCharacters("<strong>", "</strong>");
		titlediv.appendChild(a);

		// Create the summary
		summarydiv.className = 'search-summary';
		summarydiv.innerHTML = response.SearchResponse.Web.Results[i].Description.fixupGTLT().ReplaceMSLiveHighlightingCharacters("<strong>", "</strong>");

		// Create the display url
		urldiv.className = 'search-displayurl';
		urldiv.innerHTML = response.SearchResponse.Web.Results[i].DisplayUrl;

		// All the divs fall under the search-result div, so append them
		resultdiv.appendChild(titlediv);
		resultdiv.appendChild(summarydiv);
		resultdiv.appendChild(urldiv);

		// The result div falls under the container, so append it
		containerdiv.appendChild(resultdiv);

	}

	// Now append the container div to the YahooSearchResults div
	mslivediv.appendChild(containerdiv);
}


// -------------------------------------------------------------
// GIGABLAST SEARCH CODE
// -------------------------------------------------------------
function DoGigablastSearch(SearchFor)
{
	var gigablastdiv = document.getElementById('GigablastSearchControl');
	gigablastdiv.innerHTML = "<iframe name='GigablastFrame' id='GigablastFrame'"
	+ "src='http://en.isawiki.org/search/display?action=gigablastsearch&q=" + SearchFor.fixupSpeechMarks() + "'"
	+ "frameborder='0'"
	+ "scrolling='no'"
	+ "width='268px'"
	+ "onload='resizeFrame(document.getElementById(\"GigablastFrame\"));'></iframe>";

	DoneGigablastSearch = true;
}

var curopen_menu = null;
var clicked_menu = null;

// If a menu is clicked, then set it to be toggled
// Note: this code is dependant on the anchor tag click event triggering before the document.click event (which appears to always be the case)
function mset(id)
{
	clicked_menu = document.getElementById(id);
}

// Toggle the menu - this is always called when something on the document is clicked
function mtoggle()
{
	// If a different menu (to what was clicked ) is open, then close it
	if (curopen_menu && curopen_menu != clicked_menu)
	{
		curopen_menu.style.visibility = 'hidden';
		curopen_menu = null;
	}
	
	// If menu href has been clicked (and not a general document.click), then toggle the menu 
	if (clicked_menu)
	{
		if (clicked_menu.style.visibility == 'visible')
		{
			// Menu is open, so close it
			clicked_menu.style.visibility = 'hidden';
			curopen_menu = null;
		}
		else
		{
			// Menu is closed, so open it
			clicked_menu.style.visibility = 'visible';
			curopen_menu = clicked_menu;
		}
		
		clicked_menu = null;
	}
}

function mhover(id)
{
	// If a menu is open and we're hovering over another menu, then close the current menu and open the menu being hovered
	hover_menu = document.getElementById(id);
	if (curopen_menu && curopen_menu != hover_menu)
	{
		mset(id);
		mtoggle();
	}
}

// If document is clicked, then turn off the current menu (if menu is open)
document.onclick = mtoggle; 

// -----------------------------------------------
// MOUSE ROLLOVERS
// -----------------------------------------------
function onoff(imgName, i, state)
{
    if(document.images)
	{               
		document.images[imgName + "_" + i].src = "/" + imgName + "_" + state + ".gif";
    }
}

