
var formElemsArray = new Array("sn","givenname","telephonenumber", "mail", "departmentNumber", "roomnumber");
var recsReturned = "";
function killPageNav(){
	var ref_pageNav = document.getElementById("pageNav");
	if (ref_pageNav){
		ref_pageNav.style.display = "none";
	}
}

function clearPaging(){
	document.searchValues.pagevalue.value = "";
}

function setPage(pageNo){
	if (formValidate() == true){
		document.searchValues.pagevalue.value = pageNo;
		document.searchValues.submit();
	} else {
		clearPaging();
	}
}



function openTitleTable(title_TDID){
	var ref_titleTD = document.getElementById("titleTD_"+title_TDID);

	if (ref_titleTD.style.display == "none"){
		ref_titleTD.style.display = "block";
	} else {
		ref_titleTD.style.display = "none";
	}
}

function clearValues(){
	for (i=0;i<formElemsArray.length;i++){
		var refElem = document.getElementById(formElemsArray[i].toString());
		refElem.value = "";
	}
	var ref_pagevalue = document.getElementById("pagevalue");
	ref_pagevalue.value = "";
}

function trim(stringToTrim) {
	var trimmedString = stringToTrim.replace(/^\s+|\s+$/g,"");
	return trimmedString;
}

function fetchFormElement(elementID){
	var elemValue, a, refArr;
	refArr = document.getElementsByName(elementID);
	if (refArr.length > 1){
		for(a=0;a<refArr.length;a++){
			if (trim(refArr[a].value)){
				return true;
			}
		}
	} else {
		elemValue = trim(document.getElementById(elementID).value);
		if (!elemValue){
			return false;
		} else {
			return true;
			
		}
	}
}

function formValidate(){
	for (i=0;i<formElemsArray.length;i++){
		if (fetchFormElement(formElemsArray[i])){	
			return true;
		}
	}
	alert("Please enter search criteria.");
	return false;
}

function resultsReturned(){
	if(recsReturned != ""){
		alert("resultsReturned() fired recsReturned = "+recsReturned);
			if (recsReturned <= 0){
				alert("Your search yielded no results. Please use the \"Clear Search Criteria\" button and try again");
			} 
		}
	}
	
	

function shiftForms(dataPost){
	if(dataPost==1){
		popTop = frm_GSA;
		popBottom = frm_UAstaff;
	} else {
		popTop = frm_UAstaff;
		popBottom = frm_GSA;
	}	
	var query_submission = $("#q").val();
	
	$("#formTop").html(popTop);
	$("#formBottom").html(popBottom);
	$("#q").val(query_submission);
}

function checkEnter(e, fromForm){ //e is event object passed from function invocation
	var characterCode;
	
	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e;
		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)
		if (fromForm == "advanced"){
			buildAdvancedSearchString();
		} else {
			fetchOutput(); //submit the form
			return false;
		}
	}else{
		//return true;
	}
}

function submitStartArg(num){
	var startArg;
	startArg = (num==1) ? 1 : ((num-1)*10)+1;
}


function getDocHeight(doc) {
	var docHt = 0, sh, oh;
	if (doc.height) docHt = doc.height;
	else if (doc.body) {
	if (doc.body.scrollHeight) docHt = sh = doc.body.scrollHeight;
	if (doc.body.offsetHeight) docHt = oh = doc.body.offsetHeight;
	if (sh && oh) docHt = Math.max(sh, oh);
	}
	return docHt;
}

function setIframeHeight(iframeName) {
	
	var iframeWin = window.frames[iframeName];
	var iframeEl = document.getElementById?document.getElementById(iframeName): document.all? document.all[iframeName]:null;
	if ( iframeEl && iframeWin ) {
		iframeEl.style.height = "auto";
		var docHt = getDocHeight(iframeWin.document);
		if (docHt) iframeEl.style.height = docHt + 30 + "px";
	}
}


function loadIframe(iframeName, url) {
	if ( window.frames[iframeName] ) {
	window.frames[iframeName].location = url;
	return false;
	}
	else return true;
}



function loadIframe(iframeName, url) {
	if ( window.frames[iframeName] ) {
		window.frames[iframeName].location = url;
		return false;
	}
	else return true;
}

function fetchOutput(entqr, access, sort, output, ie, lr, client, q, num, ud, site, spell, oe, proxystylesheet, ip, proxyreload, start){
	
	$("#resultsFrame").show();
	$("#srchResults").hide();
	if(!num){num="";}
	if(!entqr){entqr="";}
	if(!access){access="";}
	if(!sort){sort="";}
	if(!output){output="";}
	if(!ie){ie="";}
	if(!lr){lr="";}
	if(!client){client="";}
	if(!num){num="";}
	if(!ud){ud="";}
//	alert("site before = "+site);
	if(!site){site="";}
//	alert("site after = "+site);
	if(!spell){spell="";}
	if(!oe){oe="";}
	if(!proxystylesheet){proxystylesheet="";}
	if(!ip){ip="";}
	if(!proxyreload){proxyreload="";}

	if(!q){q=$("#q").val();}
	if(!start){start=0;}
	urlSearch = "gsaCurler.php?entqr="+entqr+"&access="+access+"&sort="+sort+"&output="+output+"&ie="+ie+"&lr="+lr+"&client="+client+"&q="+q+"&num="+num+"&ud="+ud+"&site="+site+"&spell="+spell+"&oe="+oe+"&proxystylesheet="+proxystylesheet+"&ip="+ip+"&proxyreload="+proxyreload;
//	alert("urlSearch = "+urlSearch);
	loadIframe('resultsFrame', urlSearch);
	shiftForms(0);
}


function xmlFetch(startArg){	
	var param_start, param_num_records, spelling_div="", topBar, q_submitted;
	q_submitted = $("#q").val();
	
	if(trim(q_submitted)){ 
		q_submitted = trim(q_submitted);
		q = q_submitted.replace(/( |%20)/,"+");
		if (startArg!=""){startArg = (startArg==1) ? "" : (startArg-1)*10;}
		page = "requestor.php?q="+q;
		urlSearch = (!startArg) ? page : page+"&startArg="+startArg;
		/*
		$("#results").text("");
		$("#spellingSuggest").text("");
		$("#recordPaging_top").text("");
		$("#recordPaging_bottom").text("");
		$("#srchResults").text("");
		$("#results").removeClass();
		$("#spellingSuggest").removeClass();
		$("#srchResults").removeClass();
		*/
		
		shiftForms(0);					// this puts the GSA search form on the bottom and the PeopleSearch form on top.
		alert("shiftForms(0);");
		$("#q").val(q_submitted);
		
		$.get(urlSearch, function(xml){
		
			/* 	2:41 PM 7/2/2007 cmwise: in the event that the return has a suggested spelling returned, this will build a div which is already laid in to the 
				search return 
			*/
			
			$(xml).find("Spelling").each(function(){
				spelling_suggested = $(this).find("Suggestion").text();
				if(spelling_suggested){
					$("#results").addClass("spellingSuggest");
					
					spelling_regEx = new RegExp("</?(b|i)>", "g");
					spelling_suggested = spelling_suggested.replace(spelling_regEx, "");
					spelling_div = "<p>Did you mean: <a href=\"javascript: void(0);\" onClick=\"spellSearch('"+spelling_suggested+"');\">"+spelling_suggested+"</a></p>";
					$("#spellingSuggest").addClass("spellingSuggest");
					$("#spellingSuggest").html(spelling_div);
				}
			});
			
			resultsTotal = parseInt($(xml).find("M").text());
			searchTime = $(xml).find("TM").text();		
			
				$(xml).find("PARAM").each(function(){
					param_name = $(this).attr("name");
					param_value = $(this).attr("value");
					param_original_value = $(this).attr("original_value");
					if(param_name == "start"){param_start = parseInt(param_value);}
					param_num_records = (param_name == "num") ? parseInt(param_value) : 10;
				});
		
				recordPagaing_start = parseInt($(xml).find("RES").attr("SN"));
				recordPagaing_end = parseInt($(xml).find("RES").attr("EN"));
				recordPaging_total = Math.ceil(parseFloat(resultsTotal/10));
				
				recordPaging_linkPrevious = (recordPagaing_start == 1) ? "" : "<a href=\"javascript: void(0);\" onClick=\"xmlFetch("+Math.floor((recordPagaing_end - 1)/10)+");\" style=\"margin: 0 10px 0 0;\">&laquo; Previous</a> " ;
				
//				alert("recordPagaing_start  = "+recordPagaing_start+"\nrecordPagaing_end  = "+recordPagaing_end+"\nrecordPaging_total = "+recordPaging_total);
				
				recordPaging_linkNext = (recordPagaing_end == recordPaging_total || (recordPagaing_end-recordPagaing_start) < 9) ? "" : "&nbsp;<a href=\"javascript: void(0);\" onClick=\"xmlFetch("+parseInt(Math.floor((recordPagaing_end - 1)/10)+2)+");\">Next &raquo;</a>" ;
				
				if (recordPaging_total >= 20){
					recordPaging_bottomBound = (((recordPagaing_start/10)-10)>0) ? Math.floor((recordPagaing_start/10)-10) : 1;
					recordPaging_topBound = (((recordPagaing_end/10)+10) <= recordPaging_total) ? Math.floor((recordPagaing_end/10)+10) : recordPaging_total;
				} else {
					recordPaging_bottomBound = 1;
					recordPaging_topBound = recordPaging_total;
				}
				
				if (param_start){
					if (recordPagaing_end <= param_start){
						recordPaging_topBound = Math.floor(recordPagaing_end/10);
					}
				}
				$("#recordPaging_top").text("");
				$("#recordPaging_bottom").text("");
				for (var x=recordPaging_bottomBound;x<=recordPaging_topBound;x++){
					recordPagaing_thisPage = (recordPagaing_start == 1) ? 1 : Math.floor((recordPagaing_end - 1)/10)+1;
					recordPagaing_displayNo = (recordPagaing_thisPage == x) ? "<strong>"+x+"</strong>" : " <a href=\"javascript: void(0);\" onClick=\"xmlFetch("+x+");\">"+x+"</a>";
					pipe = (x!=recordPaging_topBound) ? "<span class=\"pipe\">|</span> " : "";
					if(resultsTotal>10){
						$("#recordPaging_top").append(recordPagaing_displayNo+pipe); 
					}
				}
				if(resultsTotal>10){
						$("#recordPaging_top").prepend(recordPaging_linkPrevious);
						$("#recordPaging_top").append(recordPaging_linkNext);
						$("#recordPaging_top").clone().appendTo("#recordPaging_bottom");
				}
			searchTerm = $(xml).find("Q").text();
			
			
			if (isNaN(recordPagaing_start)||isNaN(recordPagaing_end)||isNaN(resultsTotal)){						// test to see if we got results
				copy_NoReturn = ""
					+"Your search - <strong>"+searchTerm+"</strong> - did not match any documents.<br>"
					+"No pages were found containing \"<strong>"+searchTerm+"</strong>\".<br>"
					+"Suggestions:"
					+"<ul>"
					    +"<li>Make sure all words are spelled correctly.</li>"
					    +"<li>Try different keywords.</li>"
					    +"<li>Try more general keywords.</li>"
					+"</ul>";
					
				topBar ="<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\">"
							+"<tr>"
								+"<td style=\"width: 65%;\"><strong style=\"font-size: 14px;\">Search</strong></td>"
							+"</tr>"
						+"</table>";
				$("#results").html(copy_NoReturn);
			} else {
				topBar ="<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\">"
							+"<tr>"
								+"<td style=\"width: 20%;\"><strong style=\"font-size: 14px;\">Search</strong></td>"
								+"<td style=\"text-align: right; width: 80%;\" class=\"searchStats\"> Results <strong>"+recordPagaing_start+" - "+recordPagaing_end+"</strong> of about <strong>"+resultsTotal+"</strong> for <strong>"+q_submitted+"</strong>.</td>"
							+"</tr>"
						+"</table>";
			}
			$("#topBar").addClass("topBar");
			$("#topBar").html(topBar);
			var weighted_link, weighted_text;
			
			$(xml).find("GM").each(function(){
				weighted_link = $(this).find("GL").text();
				weighted_text = $(this).find("GD").text();
				$("#results").append("<div class=\"weighted\"><a href=\""+weighted_link+"\">"+weighted_text+"</a><br><span>"+weighted_link+"</span></div>");
			});
			
			var return_link1, return_link2, return_link3, return_linkText, return_summary, return_mime;
			$(xml).find("R").each(function(){
	
				return_mime = $(this).attr("MIME");
				var reg = new RegExp("^application/", "");
				return_mime = (!return_mime) ? "" : "<span class=\"type\">["+return_mime.replace(reg, "").replace("msword","ms word")+"]</span> ";
	
				return_link1 = $(this).find("U").text();
				return_link2 = $(this).find("UE").text();
				return_link3 = $(this).find("UD").text();
				return_linkText = $(this).find("T").text();
				return_summary = $(this).find("S").text();
				return_docSize = $(xml).find("C").attr("SZ");
				return_cacheID = $(xml).find("C").attr("CID");
				return_encoding = $(xml).find("C").attr("ENC");
				return_cacheLink = "<a href=\"javascript: void(0);\" onClick=\"showCache('cache:"+return_cacheID+":"+return_link1+"+"+searchTerm+"');\">Cached</a>";
				
				$("#results").append("<div class=\"g\">"+return_mime+"<a href=\""+return_link1+"\">"+return_linkText+"</a><br><span class=\"l\">"+return_summary+"</span><div class=\"cache\">"+return_link1+return_cacheLink+"</div></div>");
			});
		});
	}
}

function showCache(return_cacheString){
	if(return_cacheString){$("#cacheLink").val(return_cacheString.toString());}
	document.cached.submit();
}

function toggleSearchType(flag){
	var toShow, toHide;
	toShow = flag;
	toHide = (flag == "advancedSearch") ? "simpleSearch" : "advancedSearch";
	$("#"+toHide).hide("fast");
	$("#"+toShow).show("slow");
}

function spellSearch(spelling_suggested){
	$("#q").val(spelling_suggested);
	xmlFetch();
}

function buildAdvancedSearchString(){

	var val_as_q, val_as_epq, val_as_oq, val_as_eq, val_lr, val_as_ft, val_as_filetype, val_as_occt, val_as_dt, val_as_sitesearch, val_as_lq, strSearch="", reg1, arr_as_oq;

	$("#expression").val(strSearch);

	val_as_q = $("#as_q").val();
	val_as_epq = $("#as_epq").val();
	val_as_oq = $("#as_oq").val();
	val_as_eq = $("#as_eq").val();
	val_lr = $("#lr").val();
	val_as_ft = ($("#as_ft").val()=="e")?"-":""; 
	val_as_filetype = $("#as_filetype").val();
	val_as_occt = $("#as_occt").val();
	val_as_dt = ($("#as_dt").val()=="e")?"-":"";
	val_as_sitesearch = $("#as_sitesearch").val();
	val_as_lq = $("#as_lq").val();

	reg1 = new RegExp(" +", "g");
	reg2 = new RegExp("(^| +)", "ig");
	
	if(val_as_q){strSearch = val_as_q;}
	if(val_as_epq){strSearch += " \""+val_as_epq+"\" ";}
	if(val_as_oq){strSearch += val_as_oq.replace(reg1, " OR ");}
	if(val_as_eq){strSearch += val_as_eq.replace(reg2, " -");}
	if(val_as_filetype){strSearch += " "+val_as_ft+"filetype:"+val_as_filetype;}
	if(val_as_occt!="any"){strSearch = "allin"+val_as_occt+": "+strSearch;}
	if(val_as_sitesearch){strSearch += " "+val_as_dt+"site:"+val_as_sitesearch;}
	if(val_as_lq){strSearch = "link:"+val_as_lq;}

	toggleSearchType('simpleSearch');
	
	if(strSearch){
		$("#q").val(strSearch);
		//xmlFetch();
		fetchOutput();
	}
}
