var searchTypeValue = 'allWords';
var keyUpTimer = null;

//gets called in the body's onLoad
function init()
{
	DWRUtil.useLoadingMessage();
	//DWREngine._errorHandler =  errorHandler;
	//findDocs is used elsewhere, but it has an else section that initializes some variables and stuff
	document.getElementById("info").innerHTML = "";
	document.getElementById("navigation").innerHTML = "";
	document.getElementById("messages").innerHTML = "";
	//put the cursor in the first query field
	document.getElementById("docQuery").focus();
	//hide the search section until the users clicks search
	document.getElementById("searchSection").style.display = 'none';
	//checking for URL vars
	var urlVarCount = urlVars();
	if (!urlVarCount) {
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'newTip', showTip);
	}
	// initialize the DHTML History framework
	dhtmlHistory.initialize(); 
	// add ourselves as a DHTML History listener
	dhtmlHistory.addListener(handleHistoryChange);
	var currentLocation = dhtmlHistory.getCurrentLocation();
	if (currentLocation != '') {
		handleHistoryChange(currentLocation)
	}
}

function showTip(tipText) {
	document.getElementById("tips").innerHTML = tipText;
}

function urlVars()
{
 	var url_string = String(document.location);
 	var url_array = url_string.split('?');
 	var qStr = '';
	if(url_array[1]){
		var e_array = url_array[1].split('&');
		for(i=0;i<=(e_array.length);i++){
			if(e_array[i]){
				var useVal = e_array[i].split('=');
				if (useVal[0] && useVal[0] == 'getDoc') {
					if (useVal[1].search(/#/) != -1) {
						hashPos = useVal[1].search(/#/)
						qStr = useVal[1].substring(0,hashPos)
					} else {
						qStr = useVal[1];
					}
				}
			}
		}
		document.getElementById("docQuery").value = qStr;
		//load the tag's details docs
		getDocDetails(qStr);
	}
	return qStr.length;
}

function delayedLoad(func) {
	// This function was called by an "onKeyUp" event.
	// If a timer already exists, kill it and start a new timer.
	// This will reduce the number of requests sent to the web server.
	if (keyUpTimer != null) {
		clearTimeout(keyUpTimer);
	}
	
	// Create a new timer that will call the AJAX request function after
	// a reasonable delay.
	keyUpTimer = setTimeout(func, 275);
	return true;
}

function findDocs()
{
	//this case filters an existing category listing
	if (document.getElementById("docQuery").value 
			&& (document.getElementById("categories").value 
				|| document.getElementById("funcCategories").value)
			) {
		if (document.getElementById("categories").value) {
			document.getElementById("messages").innerHTML = '<strong>*Note:  You are searching only within the '+document.getElementById("categories").value+' category.  You may want to reset the category to blank.</strong>';
			//get the existing category
			var lastCategory = document.getElementById("categories").value;
		} else {
			document.getElementById("messages").innerHTML = '<strong>*Note:  You are searching only within the '+document.getElementById("funcCategories").value+' category.  You may want to reset the category to blank.</strong>';
			//get the existing category
			var lastCategory = document.getElementById("funcCategories").value;
		}
		//safari doesn't like spaces in the category names, replace them
		lastCategory = lastCategory.replace(/ /g,"_");
		//get the text the user entered in the query field
		var docQuery = DWRUtil.getValue("docQuery");
		//call the cf function categoriesFilter and return the results to getResult()
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'categoriesFilter', lastCategory, docQuery, getResult);
	} else if ((document.getElementById("docQuery").value == "") && document.getElementById("categories").value) {
		//if the user used to have a query and a category, but deletes the query, just load the category again
		document.getElementById("messages").innerHTML = '';
		loadCategories('categories');
	} else if ((document.getElementById("docQuery").value == "") && document.getElementById("funcCategories").value) {
		//if the user used to have a query and a category, but deletes the query, just load the category again
		document.getElementById("messages").innerHTML = '';
		loadCategories('funcCategories');
	} else {
		//this case is for the normal cf tag query without any categories
		if (document.getElementById("docQuery").value) {
			//for ease of use, the user doesn't have to type in cf
			var cftagString = $('docQuery').value;
			//call the cf function docsLookup and return the results to getResult()
			DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'docsLookup', cftagString, getResult);
			//if the user had previously selected any other data, clear it
			document.getElementById("categories").value = "";
			document.getElementById("funcCategories").value = "";
		} else {
			//the user deleted any text in the query field, clear all values and sections
			document.getElementById("info").innerHTML = "";
			document.getElementById("navigation").innerHTML = "";
			document.getElementById("messages").innerHTML = "";
			document.getElementById("blankSpace").innerHTML = "<div style=\"height: 100px\;\"><div name=\"tips\" id=\"tips\" class=\"welcomeArea\"></div></div>";
			DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'newTip', showTip);
		}
	}
}

function searchAll()
{
	if (document.getElementById("searchQuery").value)
	{
		//concatenate the search value and the search type
		var searchTerm = DWRUtil.getValue("searchQuery")+'_d_'+searchTypeValue;
		//safari doesn't like spaces in the category names, replace them
		searchTerm = searchTerm.replace(/ /g,"_");
		//call the cf function performSearch and return the results to getResult()
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'performSearch', searchTerm, getResult);
		//clear any existing back/forward history
	}
}

function loadCategories(whichCat)
{
	if (document.getElementById(whichCat).value) {
		//get the category from the drop down
		var categories = DWRUtil.getValue(whichCat);
		//safari doesn't like spaces in the category names, replace them
		categories = categories.replace(/ /g,"_");
		dhtmlHistory.add('cat:'+whichCat+':'+categories)
		//call the cf function docsLookupByCategory and return the results to getResult()
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'docsLookupByCategory', categories, whichCat, getResult);
		document.getElementById("docQuery").value = "";
		if (whichCat == "categories") {
			document.getElementById("funcCategories").value = "";
		} else {
			document.getElementById("categories").value = "";
		}
	} else {
		//the user set the category back to blank, clear all results and sections
		document.getElementById("info").innerHTML = "";
		document.getElementById("navigation").innerHTML = "";
		document.getElementById("messages").innerHTML = "";
		document.getElementById("blankSpace").innerHTML = "<div style=\"height: 100px\;\"><div name=\"tips\" id=\"tips\" class=\"welcomeArea\"></div></div>";
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'newTip', showTip);
	}
}

function loadCategoryFromLink(category)
{
	//if the user clicks a category link in the docs body, load it
	if (category.indexOf(" tags"))
	{
		//strip off the ' tags' part, as the data doesn't contain that
		var truncCtgry = category.replace(/ tags/,"");
	} else {
		var truncCtgry = category;
	}
	//set the category drop down
	document.getElementById("categories").value = truncCtgry;
	//the page is all set to just call loadCategories()
	loadCategories('categories');
}

function loadFuncCategoryFromLink(category)
{
	//if the user clicks a category link in the docs body, load it
	if (category.indexOf(" functions"))
	{
		//strip off the ' functions' part, as the data doesn't contain that
		var truncCtgry = category.replace(/ functions/,"");
	} else {
		var truncCtgry = category;
	}
	//set the category drop down
	document.getElementById("funcCategories").value = truncCtgry;
	//the page is all set to just call loadCategories()
	loadCategories('funcCategories');
}

function getResult(result)
{
	//taking care of the cases where there is only one result left in the list of tags/funcs
	var tagCount = result.indexOf('SingleResultCase|');
	if (tagCount > -1) {
		//only one tag left in the list, just load that
		var splitLoc = result.indexOf('|');
		thisTag = result.substring(splitLoc+1,result.length);
		getDocDetails(thisTag);
	} else {
		//stuff the results from the cf function into the 'info' div tag on the page
		document.getElementById("info").innerHTML = result;
		document.getElementById("navigation").innerHTML = "";
		//save the contents in the savedContent hidden form field for the back/forward function
		document.getElementById("savedContent").value = result;
		//remove the blank space that I put in for aesthetics
		document.getElementById("blankSpace").innerHTML = "";
	}
}

function getDocDetails(doc)
{
	//load the doc's body contents when a user clicks a doc name in a doc listing or from another doc's body
	document.getElementById("messages").innerHTML = "";
	if (doc) {
		//call the cf function lookupDetails and return the results to getResultDetails()
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'lookupDetails', doc, getResultDetails);
		//clear out the previous body contents, as it will be reloaded by getResultDetails()
		document.getElementById("info").innerHTML = "";
		dhtmlHistory.add(doc)
		//saving the current URL in a hidden field for later usage
		var urlVar = document.URL.indexOf('?');
		if (urlVar != -1)
		{
			var thisURL = document.URL.substring(0,urlVar);
		} else {
			var thisURL = document.URL;
		}
		if (thisURL.search(/#/) != -1) {
			hashPos = thisURL.search(/#/)
			thisURL = thisURL.substring(0,hashPos)
		}
		var newURL = thisURL+"?getDoc="+doc;
		document.getElementById("savedTagFunc").value = newURL;
		document.getElementById("savedQueryTerm").value = doc
	}				
}

function getResultDetails(result)
{
	if (result == 'noTagResult') {
		findDocs();
	} else {
		//javascript doesn't like line breaks, so in the cf function I replace them with '~r~n'
		result = result.replace(/~r~n/g, "\r\n");
		
		//getting the URL from the results
		var delimPos = result.indexOf("~~~");
		var tagURL = result.substring(0,delimPos);
		if (tagURL) {
			tagURL = "http://livedocs.macromedia.com/coldfusion/7/htmldocs/"+tagURL;
		}
		//strip the tag URL from the first of the tag result details
		result = result.substring(delimPos+3,result.length);
		//stuff the results from the cf function into the 'info' div tag on the page
		document.getElementById("info").innerHTML = result;
		//remove the blank space that I put in for aesthetics
		document.getElementById("blankSpace").innerHTML = "";
		//display the 'link to this page' link
		var navText = document.getElementById("navigation").innerHTML
		if (!navText.match('Link to this page')) {
			document.getElementById("navigation").innerHTML = document.getElementById("navigation").innerHTML + '<strong><a href="'+document.getElementById('savedTagFunc').value+'">Link to this page</a></strong>';
		}
		if (tagURL) {
			//displaying the link to the tag on Livedocs
			document.getElementById("navigation").innerHTML = document.getElementById("navigation").innerHTML + ' &nbsp;&nbsp;<strong><a href="'+tagURL+'">View this page in LiveDocs</a></strong>';
		}
		//load the tag/func into the switch version link
		var switchLink7 = document.getElementById('versionLink7')
		if (switchLink7) {
			var newSwitchLink = switchLink7.href
			newSwitchLink = '/cf7/?newVersion=1&getDoc=' + document.getElementById("savedQueryTerm").value
			switchLink7.href = newSwitchLink
		} 
		var switchLink8 = document.getElementById('versionLink8')
		if (switchLink8) {
			var newSwitchLink = switchLink8.href
			newSwitchLink = '/cf8/?newVersion=1&getDoc=' + document.getElementById("savedQueryTerm").value
			switchLink8.href = newSwitchLink
		}
		var switchLink9 = document.getElementById('versionLink9')
		if (switchLink9) {
			var newSwitchLink = switchLink9.href
			newSwitchLink = '/cf9/?newVersion=1&getDoc=' + document.getElementById("savedQueryTerm").value
			switchLink9.href = newSwitchLink
		}
	}
}

function toggleSearch(flag) {
	//toggle between displaying the default screen and the search screen
	if (flag == 1) {
		//the user clicked 'Search'
		//remove the default content
		document.getElementById("tag_function_boxes").style.display = 'none';
		//display the link to return back to default
		//document.getElementById("toggleButton").innerHTML = "<a onclick=\"toggleSearch(0)\" style=\"text-decoration:underline; color:blue; cursor:pointer;\">CF tags & functions</a>";
		//display the search block (was hidden by the init() function)
		document.getElementById("searchSection").style.display = 'block';
		//by default, don't display the search options (All words, Any word, etc.)
		document.getElementById("searchOptions").style.display = 'none';
		document.getElementById("messages").innerHTML = "";
		document.getElementById("info").innerHTML = "";
		document.getElementById("blankSpace").innerHTML = "";
	} else {
		//the user click the 'Main' link (the default display mode)
		//hide the search section
		document.getElementById("searchSection").style.display = 'none';
		document.getElementById("searchOptions").style.display = 'none';
		//display the Tags and Functions section
		document.getElementById("tag_function_boxes").style.display = 'block';
		//display the 'Search' link again
		document.getElementById("info").innerHTML = '';
		document.getElementById("navigation").innerHTML = "";
		document.getElementById("messages").innerHTML = "";
		//document.getElementById("toggleButton").innerHTML = "<a onclick=\"toggleSearch(1)\" style=\"text-decoration:underline; color:blue; cursor:pointer;\">Search</a>";
	}
}

function countWords() {
	//look for more than one search term
	if (document.getElementById("searchQuery").value.search(/\w\s+\w/) > 0) {
		//found more than one search term, display the search type options
		document.getElementById("searchOptions").style.display = 'block';
	} else {
		//if the user deleted one of the search terms, or if 
		//they have only typed one, hide the search type options
		document.getElementById("searchOptions").style.display = 'none';
	}
	if (! document.getElementById("searchQuery").value) {
		document.getElementById("blankSpace").innerHTML = "<div style=\"height: 100px\;\"><div name=\"tips\" id=\"tips\" class=\"welcomeArea\"></div></div>";
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'newTip', showTip);
	}
}

function handleHistoryChange(newLocation) {   
	// update the browser to respond to this
	// DHTML history change
	if (newLocation != '') {
		if (newLocation.match('cat:')) {
			//the current location is a category listing instead of a doc page
			//the value will look something like this-cat:categories:Data_output
			//split it into an array
			var urlArray = newLocation.split(':')
			//the second value identifies which group of categories to look at, tags or functions
			var whichCat = urlArray[1]
			//the third value is the actual category name
			var category = urlArray[2]
			//load the page's select list with the category name 
			document.getElementById(whichCat).value = category.replace(/_/g,' ')
			//blank the other category list (the one not selected)
			if (whichCat.match('func')) {
				document.getElementById('categories').value = ''
			} else {
				document.getElementById('funcCategories').value = ''
			}
			//load the category from data
			DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'docsLookupByCategory', category, whichCat, getResult);
		} else {
			//the current location is a documentation page, so load it
			DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'docsLookup', newLocation, getResult);
		}
	} else {
			//the user deleted any text in the query field, clear all values and sections
			document.getElementById("info").innerHTML = "";
			document.getElementById("navigation").innerHTML = "";
			document.getElementById("messages").innerHTML = "";
			document.getElementById("blankSpace").innerHTML = "<div style=\"height: 100px\;\"><div name=\"tips\" id=\"tips\" class=\"welcomeArea\"></div></div>";
			document.getElementById('categories').value = ''
			document.getElementById('funcCategories').value = ''
			document.getElementById("docQuery").focus()
			DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'newTip', showTip);		
	}
}