// global javascript file to contain functions that may be used multiple times throughout the site
// July 18th, 2008


function popUp(strURL, strOptions) {
	var x=window.open(strURL, "BLM", strOptions);
	x.focus();
	return false;
}

function urlEncode(str){
    str=escape(str);
    str=str.replace(new RegExp('\\+','g'),'%2B');
    return str.replace(new RegExp('%20','g'),'+');
}

function toggleItem(strDivId) {
	if (strDivId+'x' != 'x') {
		if (document.getElementById(strDivId) != null) {
			if (document.getElementById(strDivId).style.display == "none") {
				document.getElementById(strDivId).style.display = "block";	} 
			else {
				document.getElementById(strDivId).style.display = "none";}
		}
	}
}

function togglePDF(strDivId) {
	if (strDivId+'x' != 'x') {
		if (document.getElementById(strDivId) != null) {
			if (document.getElementById(strDivId).style.display == "inline") {
				document.getElementById(strDivId).style.display = "none";	} 
			else {
				document.getElementById(strDivId).style.display = "inline";}
		}
	}
}


function toggleTableRows(strDivId) {
	if (strDivId+'x' != 'x') {
		if (document.getElementById(strDivId) != null) {
			if (document.getElementById(strDivId).style.display == "none") {
				document.getElementById(strDivId).style.display = "table-row-group";	} 
			else {
				document.getElementById(strDivId).style.display = "none";}
		}
	}
}
function toggleTableRowsOn(strDivId) {
	if (strDivId+'x' != 'x') {
		//document.getElementById(strDivId).style.display = "table-row-group";
		//Set the visible class
		var x = document.getElementById(strDivId);
		x.className = "ShowTableBody";
		}
}

function toggleTableRowsOff(strDivId) {
	if (strDivId+'x' != 'x') {
		//document.getElementById(strDivId).style.display = "none";
		//Set the invisible class
		var x = document.getElementById(strDivId);
		x.className = "HideTableBody";
		
		}
}


/*******************************************
 toggleGroupItem('span', 'SafetyLink_', 'SafetyLink_1') 
 hides all spans on page with prefex SafetyLink_ opens up element w/ id SafetyLink_1

 toggleGroupItem('span', 'SafetyLink_', 'SafetyLink_1', true) 
 shows all spans on page with prefix SafetyLink_ closes SafetyLink_1
 
 toggleGroupItem('span', 'SafetyLink_' ) 
 hides all spans on page with prefex SafetyLink_ 
 
 toggleGroupItem('span', 'SafetyLink_', '', true) 
 shows  all spans on page with prefex SafetyLink_ 
  
*******************************************/

function toggleGroupItem(strTagRef, strIdPrefix, strId, blnSetVisible) {
    var blnMakeVisible = (blnSetVisible == null) ? false : true;
    var strSelectedId = (strId == null) ? "" : strId;	
	var blnDoIt = true;
	var strAction1 = 'none';
	var strAction2 = 'block';
	
	if (strTagRef.replace(/ /g, "") +'x' == 'x') { blnDoIt = false; }
	if (strTagRef.length > 100) { blnDoIt = false; }	
	if (strIdPrefix.replace(/ /g, "") +'x' == 'x') { blnDoIt = false; }	
	if (strIdPrefix.length > 100) { blnDoIt = false; }	
	if (strSelectedId.length > 100) { blnDoIt = false; }	

	if (blnDoIt) {
		if (blnSetVisible) { // hides the one selected but displayes all not selected // opposite of default
			strAction1 = 'block';
			strAction2 = 'none';			
		}
		
		// loop through valid tags (html) looking for provided prefix
		var doc = document.getElementsByTagName(strTagRef);
		for (var i = 0; i < doc.length; i++){
			//Do Work on doc[i], this sets the border of the Div black
			var currentTagID=doc[i].id;
			if ( (currentTagID.match(strIdPrefix) != null)) {
				document.getElementById(currentTagID).style.display = strAction1;
				}
			}
		// hide/show according to strSelectedId passed in by user	
		if (strSelectedId != "") {
			if (document.getElementById(strSelectedId) != null) {
				document.getElementById(strSelectedId).style.display = strAction2;}
			}
	}
}

/*******************************************
Jquery specific Show/Hide 10/22/10
*******************************************/
$(document).ready(function(){
	$(".toggleTrigger").click(function(event){
		$("#"+ $(this).attr("id") + "_body").slideToggle("20");
		event.preventDefault();
	});
	$(".hideTrigger").click(function(event){
		$("#"+ $(this).attr("id") + "_body").toggle(0);
		event.preventDefault();
	});
	$(".startHidden").hide(0);
	
	SearchBoxFocus();
	
	$(".srchSubmit").click(function(event){		
		currentLocation = self.location.toString();
		if (currentLocation.lastIndexOf("/or/search/index.php") <= 0) { $("#siteSearch").submit(); }
		executeSearch($("#query").val(),1);
		event.preventDefault();
	});
	
	$("#search_button").click(function(event){
		executeSearch($("#search_query").val(),1);
		event.preventDefault();	
	});
	
	$("#querySuggestions").click(function(event){
		executeSearch($(this).html(),1);
		event.preventDefault();
	});	
	
	$("a[href$='.pdf']").click(function(event){
		path = $(this).attr("href");
		url = location.pathname;
		_gaq.push(['_trackPageview', url + " - " + path]);
	});
});

/////////////////////////////////////////////
///  executeSearch - gets called under many scenarios from various locations in the site
/////////////////////////////////////////////
function executeSearch(query, pageNum)
{
	//search box tools
	var baseURL = "http://search.usa.gov/api/search";
	var affiKey = "4d65b65e41d50ccf1935d36ecb6525c0";
	var affName = "oregonwashingtonbureauoflandmanag";
	if (pageNum == "") { pageNum ="1"; }
	searchBaseURL = "http://search.usa.gov/api/search?format=json&affiliate="+affName+"&api_key="+affiKey+"&query={query}&page={pageNum}";
	
	searchURL = searchBaseURL.replace("{query}", query).replace("{pageNum}", pageNum);
	var jqxhr = $.getJSON(searchURL+"&callback=?", function(data) {
		resultCount = data.total;

		//output the summary information
		$('#resultList').html('');
		$('#search_query').val(query);
		
		if (resultCount > 0) {
			$("#uiSuggestions").hide(0);
			$("#resultTotal").html(resultCount);
			x = data.spelling_suggestions;
			if (x != null ) {
				$("#querySuggestions").html(data.spelling_suggestions);
				$("#uiSuggestions").show(0);
			} else {
				$("#uiSuggestions").hide(0);
			}
			$("#resultStart").html(data.startrecord);
			$("#resultEnd").html(data.endrecord);
			$("#resultQuery").html(query);
			$("#searchSummary").show(0);
		}
//		$("#resultRelated").val(data.related);  /*I don't know what these will look like yet*/
		
		//output the results
		outputBoosedResults(data.boosted_results);
		outputPageResults(data.results);
		//figure out the paging
		pageNumbering = calculatePageNumber(resultCount, pageNum);			
		basePagingURL = "/or/search/index.php?query={query}&pageNum={pageNum}";
		basePagingURL = basePagingURL.replace("{query}", query);
		//output the pages
		updatePaging(pageNumbering, pageNum, basePagingURL);
	});
}

/////////////////////////////////////////////
///  outputPageResults - HTML out for the search results
/////////////////////////////////////////////
function outputPageResults(Results) {
	var results = [];
	$.each(Results, function(key, val) {
		title = val.title;
		content = val.content;
		url = val.unescapedUrl;
		newResult = '<div class="searchresult"><a href="'+url+'">' + title + '</a><p>'+content+'</p><p><a href="'+url+'">'+url+'</a></p></div>';
		newResult = newResult.replace(/\ue000/gi, "<strong>").replace(/\ue001/gi, "</strong>");
		$('#resultList').append(newResult);
	});
	
}

/////////////////////////////////////////////
///  outputBoosedResults - HTML out for the search results for boosted content only
/////////////////////////////////////////////
function outputBoosedResults(Results) {
	boostedCount = Results.length;
	$('#resultBoosted').html('');
	if (boostedCount > 0) {
		$("#boostedresult").show(0);
		var results = [];
		$.each(Results, function(key, val) {
			title = val.title;
			content = val.description;
			url = val.url;
			
			newResult = '<div class="searchresult"><h2><a href="'+url+'">' + title + '</a></h2><p>'+content+'</p><p><a href="'+url+'">'+url+'</a></p></div>';
			$('#resultBoosted').append(newResult);
		});	
	}
}

/////////////////////////////////////////////
///  calculatePageNumber - Determine the page numbers relative to the current result
/////////////////////////////////////////////
function calculatePageNumber(resultCount, pageNum) {
	var pageNumbering = new Array();
	//figure out the paging
	pageCount = Math.floor(resultCount / 10);
	if (pageCount > 1) {
		currPage = Math.floor(pageNum);
		prevPage = currPage - 1; if (prevPage <= 0 ) { prevPage = 1; }
		nextPage = currPage + 1; if (nextPage >= pageCount ) { nextPage = pageCount; }
		pageNumbering.push(1); //always include a link to the first page.
		pageNumbering.push(prevPage);
		i = 4;
		while (i>=0)  {
			if ((currPage-i)>1) { pageNumbering.push(Math.floor(prevPage-i)); }
			i--; }	
		pageNumbering.push(currPage);
		i=0;
		while ( ((currPage+i)<pageCount) && (i<5) ) {
			pageNumbering.push(Math.floor(nextPage+i)); i++; }
		pageNumbering.push(nextPage);
	}
	return pageNumbering;
}

/////////////////////////////////////////////
///  updatePaging - Output the page numbers as links on the search page
/////////////////////////////////////////////
function updatePaging(arrPageNumbers, currentPage, baseSearchURL) {
	$("#current_prior").html('');
	$(".resultNavLink").hide(0);
	linkCount = arrPageNumbers.length;
	if(linkCount > 0) {
		if (currentPage > 1) { $("#first_page").attr('href', baseSearchURL.replace("{pageNum}", arrPageNumbers[0])).show(0); }
		if (currentPage > arrPageNumbers[1]) { $("#previous_page").attr('href', baseSearchURL.replace("{pageNum}", arrPageNumbers[1])).show(0);	}	
		//loop through the items except the first two and the last two, they should always be the "word" navigation links
		for (j=2; j<linkCount-2; j++)
		{
			CssClass = "resultNavLink";
			if (arrPageNumbers[j] == currPage) { CssClass = CssClass + " resultNavLink_Current" };
			tempPageNumber = "<a class='" + CssClass + "' href='" + baseSearchURL.replace("{pageNum}", arrPageNumbers[j]) + "'>" + arrPageNumbers[j] + "</a>";
			$("#current_prior").append(tempPageNumber);
		}
		$("#current_prior").show(0);
		if (currentPage < arrPageNumbers[linkCount-1]) { $("#next_page").attr('href', baseSearchURL.replace("{pageNum}", arrPageNumbers[linkCount-1])).show(0); }
	}
}

/////////////////////////////////////////////
///  SearchBoxFocus - Styling for the search box
/////////////////////////////////////////////
function SearchBoxFocus() {
	var active_color = '#000'; // Colour of user provided text
	var inactive_color = '#999'; // Colour of default text	
  $("input.default-value").css("color", inactive_color);
  var default_values = new Array();
  $("input.default-value").focus(function() {
    if (!default_values[this.id]) { default_values[this.id] = this.value; }
    if (this.value == default_values[this.id]) { this.value = ''; this.style.color = active_color;  }
    $(this).blur(function() {
      if (this.value == '') { this.style.color = inactive_color; this.value = default_values[this.id]; }
    });
  });
}
