dojo.declare("com.mgh.Search", null, {
    constructor: function(configParams){
		this.xmlDoc;
		this.categories;
		this.letters;
		this.letterBeginEnd;
		this.hasElementsArray;
		this.conditions = '';
		this.page = '';
		this.recordsDisplaying = 0;
		
		/********************************** Default Variables *****************************************/
		//accept a json object with all necessary constructor values
		this.queryParams = configParams;
		this.query = '';		
		/*this.queryParams = {
			az		: '',
			age		: '',
			cat 	: '',		
			subcat	: '',
			type	: '',
			href 	: '',
			search	: ''
		};*/    	
		
		// current page: is the ascii code for the letter currently selected
		// lowestNumber: checks how many results are being displayed before the current letter. 1 is for A.
		// linksToDisplay: is how many categories are displayed before the "view all" link and overlay are displayed
		this.currentPage = 65;
		this.lowestNumber = 1;
		this.highestNumber = 0;
		this.resultsCount = 0;
		this.previousHighest = 0;
		this.results = 0;
		this.linksToDisplay = this.queryParams.links;
		try {	
			fadeOutNode('resultsColumn');
			fadeOutNode('filter1');
			fadeOutNode('conditions1');
		} catch (e) {
			console.log(e);
		}
		this.getXmlString();
	},
    
	/********************************** xml methods *****************************************/  
	updateQuery : function()
	{
		var m = this.queryParams;
		this.query = m.href + '?az=' + m.az + '&age=' + m.age + '&cat=' + m.cat +  '&subcat=' + m.subcat + '&type=' + m.type + '&query=' + m.query;
	},    

	getXmlString : function()
	{
		this.updateQuery();
		dojo.xhrGet({
			url: this.query,
			handleAs: "text",
			load: function(response, ioArgs){
				//outside function listening for the data to be ready
				searchDataReady(response);
				return response;
			},
			error: function(response, ioArgs){
				alert("An error occurred, with response: " + response);
				return response;
			}
		});		
	},
    
	loadXmlString : function(txt) 
	{
		var Doc;
		var parser;
		try //Internet Explorer
		{
			Doc = new ActiveXObject("Microsoft.XMLDOM");
			Doc.async = "false";
			Doc.loadXML(txt);
			return(Doc); 
		}
		catch(e)
		{
			try //Firefox, Mozilla, Opera, etc.
			{
				parser = new DOMParser();
				Doc = parser.parseFromString(txt,"text/xml");
				return(Doc);
			}
			catch(e) {console.log(e.message)}
		}
		return(null);
	},
	
	handleXml : function ()
	{
		var names = this.xmlDoc.getElementsByTagName("NAME");
		var letter = '';
		var counter = 0;
		var a = '';
		var i;
		var name = '';
		
		//initialize these class variables every time a new xml document is loaded
		this.letters = new Array();
		this.letterBeginEnd = new Array();
		this.hasElementsArray = new Array();
		
		// the first time it begins at 1 because this corresponds to the first record, 
		// endLetter is just initialized
		var beginLetter = 1;
		var endLetter = 0;
		
		for (var x=65; x < 91; x++){
			letter = String.fromCharCode(x);
			for (i=0; i < names.length; i++){
				name = names[i].childNodes[0].nodeValue;
				if (name.substring(0,1).toUpperCase() == letter){
					endLetter += 1;
					a += i + ',';
					//counts the total number of records
					this.resultsCount += 1;
				}
			}
			
			a = a.substring(0,a.length-1);		
			if (a!=''){
				this.hasElementsArray[counter] = x;
				//where "A" begins and "B" ends and so on
				this.letterBeginEnd[letter] = beginLetter + ',' + endLetter;
				//start counting from the next one where you left off
				beginLetter = endLetter+1;					
				counter += 1;
			}
			this.letters[letter] = a;
			a = '';
		}
		this.results = this.resultsCount;
		this.resultsCount = 0;
	},
	
	/********************************** data methods *****************************************/ 
	createGroup : function(start,position)
	{
		var letter = String.fromCharCode(start);
		var text = '';
		var output = '';
		var condition = '';
		var description = '';
		
		try{
			var ids = this.letters[letter].split(',');
			if (this.letters[letter] != ''){
				var terms = this.xmlDoc.getElementsByTagName("TERM");
				var names = this.xmlDoc.getElementsByTagName("NAME");
				var conditionIds = this.xmlDoc.getElementsByTagName("METADATA");
				var i;
				var css = '';
							
				if (position == 1){
					css = 'contentRow topBorder clearfix';
				} else {
					css = 'contentRow clearfix';	
				}
				
				output = '<div class="' + css + '">';
				output += '<p>' + letter + '</p>';
				output += '<div id="resultsGroup">';
				output += '<ul>';
				
				for (i=0; i < ids.length; i++){
					condition = conditionIds[ids[i]];
					description = this.getDescription(condition);
					
					if(description == 0){
						description = '';
					} else {
						text = '<span class="conditionDescription">';
						text += description;
						text += '<br><br></span>';
						description = text;
					}
					if (this.queryParams.search == 'conditions'){			
						output += '<li><a href="/conditions/condition.aspx?ID=' + 
						//this.getConditionId(condition) + '&type=' + this.getHierarchyType(terms[ids[i]]) + 
						this.getConditionId(condition) + '&type=conditions' + 
						'">' + names[ids[i]].childNodes[0].nodeValue + '</a>' + description + '</li>';	
					} else {
						output += '<li><a href="/doctors/doctor.aspx?ID=' + 
						this.getPhysicianId(condition) + '">' + 
						names[ids[i]].childNodes[0].nodeValue + '</a></li>';
					}		
				}
				output += '</ul>';
				output += '</div>';
				output += '</div>';
				
			} else {
				output = '';
			}
		} catch (e) {
			output = '';
		}
		return output;
	},

	displayResults : function (id,type,year){
		var i;
		var text = '';
		var output = '';
		var condition = '';
		var letter = '';
		var nextLetter = '';
		var css = '';
		var counter = 0;
		var description = '';
		var clinicalInterest = '';
		var boardCertification = '';
		var physicianTableClass = 'physicianTable';
		var upperLimit;
		var ids;
		var dateYear = '';
		var nextDateYear = '';
		var currentYear;
		var jtg1Flag = 0;

		
		if (type != 'letter'){
			upperLimit = id + this.queryParams.numPerPage;		
		} else {
			//this is the point where elements can be sorted by date. 
			letter = String.fromCharCode(id);
			ids = this.letters[letter].split(',');
			if (this.letters[letter] != ''){
				id = parseInt(ids[0]);
			 	upperLimit = id + ids.length;
			}
		}

		var elements = new Array();
		var terms = this.xmlDoc.getElementsByTagName("TERM");
		var names = this.xmlDoc.getElementsByTagName("NAME");
		var conditionIds = this.xmlDoc.getElementsByTagName("METADATA");
		
		for (i=id; i < upperLimit; i++){
			try {
				//setting the year to 0 displays all results, this could be used for all searches,
				//use this try statement to detect whether the date parameter is present
				
				//to sort elements by date it is necessary to sort the letters[letter} array first by date, then
				//instead of getting conditionIds[i], we use conditionIds[sortedArray[i]] then all things will be fine
				try {
					dateYear = this.getNodeData(conditionIds[i],'Date').split('/')[2];
					dateNextYear = this.getNodeData(conditionIds[i+1],'Date').split('/')[2];
					if (year == 0){
						currentYear = dateYear;
						dateNextYear = dateYear;
					} else {
						currentYear = year;
					}
				} catch (en){
					dateYear = year;
					currentYear = year;
					nextYear = year;	
				}
				
				if (dateYear == currentYear ){
					if (type != 'letter'){
						letter = names[i].childNodes[0].nodeValue.substring(0,1);
						try {
							nextLetter = names[i+1].childNodes[0].nodeValue.substring(0,1);
						} catch (ex){
							nextLetter = names[i].childNodes[0].nodeValue.substring(0,1);
						}
					} else {
						nextLetter = letter;	
					}

					if (i == upperLimit-1){
						physicianTableClass = 'physicianTableLast';
					}
					
					condition = conditionIds[i];
					description = this.getDescription(condition);
					
					//display the first letter
					if (counter == 0){
						output += '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
						output += '<tr>';
						output += '<td valign="top" width="30">';						
						output += '<div class="letter">' + letter + '</div>';
						output += '</td>';
						output += '<td>';
						output += '<div id="resultsGroup">';			
					}				
					
					if (this.queryParams.search == 'conditions'){	
						description == 0 ? description = '' : description = description;

						text += '<table width="655" border="0" cellspacing="0" cellpadding="0">';
						text += '<tr>';
						text += '<td class="searchDescription">';
						text += description;
						text +='</td>';
						text += '</tr>';
						text += '</table>';

						description = text;
						
						//space not at the top at
						if (jtg1Flag == 1)
							{
							output += '<BR>';
							}
						jtg1Flag = 1;


						output += '<div><a href="http://www.massgeneral.org/conditions/condition.aspx?ID=' + 
							//this.getConditionId(condition) + '&type=' + this.getHierarchyType(terms[i]) + 
							this.getConditionId(condition) + '&type=conditions' + 
							'">' + names[i].childNodes[0].nodeValue + '</a>' + description + '</div>';		
					} else {
						boardCertification = this.getNodeData(condition,'Board Certification').replace(/\|/g,'; ');
						boardCertification = boardCertification.replace(/\,/g,',&nbsp;');
						clinicalInterest = this.getNodeData(condition,'Clinical Interest').replace(/\|/g,', ');
						/*
						text += '<div>';
						text += '<div class="physicianName">';
						text += '<a href="http://www.massgeneral.org/doctors/doctor.aspx?ID=' + 
						this.getNodeData(condition,'PhysicianID') + '">' + 
						names[i].childNodes[0].nodeValue + '</a>';
						
						text +='</div>';					
						text += '<div class="physicianPhone" valign="top" width="120">';				
						text += this.getNodeData(condition,'Phone');
						text += '</div>';
						text += '</div>';						
						*/

						//space not at the top at
						if (jtg1Flag == 1)
							{
							output += '<BR>';
							}
						jtg1Flag = 1;

						text += '<table width="655" border="0" cellspacing="0" cellpadding="0">';
						text += '<tr>';
						text += '<td width="555">';
						text += '<a href="http://www.massgeneral.org/doctors/doctor.aspx?ID=' + 
						this.getNodeData(condition,'PhysicianID') + '">' + 
						names[i].childNodes[0].nodeValue + '</a>';
						
						text +='</td>';					
						text += '<td valign="top" align="right" width="100">';				
						text += '<span class="physicianPhone">' + dojo.string.trim(this.getNodeData(condition,'Phone')) + '</span>';
						text += '</td>';
						text += '</tr>';
						
						text += '<tr>'
						
						text += '<td colspan="2" class="searchDescription">';
						if (boardCertification != ''){
							text += '<b>Board Certification: </b>' + boardCertification + '<br/>';
							//text += '<b>Board Certification: </b>' + boardCertification + '<br/>';
						} 
						if (clinicalInterest != ''){
							text += '<b>Clinical Interest or Expertise: </b>' + clinicalInterest;
						}
						text += '</td>';
						text += '</tr>';
						text += '</table>';
						description = text;
											
						output += '<div>' + description + '</div>';
					}
					
					description = '';
					text = '';
					//display changing letters
					
					if (letter != nextLetter){
						output += '</div>';
						output += '</div>';
						output += '</td>';
						output += '</tr>';
						output += '</table>';
						output += '<br/><br/>';	
						output += '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
						output += '<tr>';
						output += '<td valign="top" width="30">';						
						output += '<div class="letter">' + nextLetter + '</div>';
						output += '</td>';
						output += '<td>';
						output += '<div id="resultsGroup">';
					}
					counter += 1;
				}
				
			} catch (e) {
				console.log(e);
				break;
			}		
		}
		output += '<br></div>';
		output += '</td>';
		output += '</tr>';
		output += '</table>';	
		this.recordsDislaying = counter;	

		if (counter == 0){			
			output +=	'<p class="noResults">No conditions match your selections.</p>' +
						'<div class="noResultsBody">' +			
						'<p>Tips to expand your search results:</p>' +
						'<ul>' + 
							'<li>Select "show all" for one or more of your search options.</li>' +
							'<li>Search or browse for condition using a general name. For example, you can find information about specific types of arrhythmias on our arrhythmia page.</li>' +                                
							'<li>Browse for a condition using our alphabetical list.</li>' +                                
						'</ul>' +
						'<p>If you need a medical interpreter, call 617-726-6966.</p>' + 
						'</div>';	
			dojo.byId('descriptions').style.display = 'none';			
		} else {
			dojo.byId('descriptions').style.display = 'block';
		}
		
		//console.log(output);
		//alert(output);
		return output;
	},
	
	displayResults2 : function (id,type,year){
		var i;
		var text = '';
		var output = '';
		var condition = '';
		var letter = '';
		var nextLetter = '';
		var css = '';
		var counter = 0;
		var description = '';
		var clinicalInterest = '';
		var boardCertification = '';
		var physicianTableClass = 'physicianTable';
		var upperLimit;
		var ids;
		var dateYear = '';
		var nextDateYear = '';
		var currentYear;
		
		if (type != 'letter'){
			upperLimit = id + this.queryParams.numPerPage;		
		} else {
			//this is the point where elements can be sorted by date. 
			letter = String.fromCharCode(id);
			ids = this.letters[letter].split(',');
			if (this.letters[letter] != ''){
				id = parseInt(ids[0]);
			 	upperLimit = id + ids.length;
			}
		}

		var elements = new Array();
		var terms = this.xmlDoc.getElementsByTagName("TERM");
		var names = this.xmlDoc.getElementsByTagName("NAME");
		var conditionIds = this.xmlDoc.getElementsByTagName("METADATA");
		
		for (i=id; i < upperLimit; i++){
			try {
				//setting the year to 0 displays all results, this could be used for all searches,
				//use this try statement to detect whether the date parameter is present
				
				//to sort elements by date it is necessary to sort the letters[letter} array first by date, then
				//instead of getting conditionIds[i], we use conditionIds[sortedArray[i]] then all things will be fine
				try {
					dateYear = this.getNodeData(conditionIds[i],'Date').split('/')[2];
					dateNextYear = this.getNodeData(conditionIds[i+1],'Date').split('/')[2];
					if (year == 0){
						currentYear = dateYear;
						dateNextYear = dateYear;
					} else {
						currentYear = year;
					}
				} catch (en){
					dateYear = year;
					currentYear = year;
					nextYear = year;	
				}
				
				if (dateYear == currentYear ){
					if (type != 'letter'){
						letter = names[i].childNodes[0].nodeValue.substring(0,1);
						try {
							nextLetter = names[i+1].childNodes[0].nodeValue.substring(0,1);
						} catch (ex){
							nextLetter = names[i].childNodes[0].nodeValue.substring(0,1);
						}
					} else {
						nextLetter = letter;	
					}

					if (i == upperLimit-1){
						physicianTableClass = 'physicianTableLast';
					}
					
					condition = conditionIds[i];
					description = this.getDescription(condition);
					
					//display the first letter
					if (counter == 0){
						//css = 'contentRow topBorder clearfix';
						css = 'contentRow clearfix';
						//css = '';
						output = '<div class="' + css + '">';
						output += '<p>' + letter + '</p>';
						//output += letter;
						output += '<div id="resultsGroup">';
						output += '<ul id="resultsList">';					
					}				
					
					if (this.queryParams.search == 'conditions'){	
						description == 0 ? description = '' : description = description;

						text += '<table width="655" border="0" cellspacing="0" cellpadding="0" style="margin:0;">';
						text += '<tr>';
						text += '<td>';
						text += '<span class="searchDescription">' + description + '</span>';
						text +='</td>';
						text += '</tr>';
						text += '</table>';
						
						description = text;
						//description = '<span class="searchDescription"><br>' + description + '</span>'
						output += '<li><a href="/conditions/condition.aspx?ID=' + 
							//this.getConditionId(condition) + '&type=' + this.getHierarchyType(terms[i]) + 
							this.getConditionId(condition) + '&type=conditions' + 
							'">' + names[i].childNodes[0].nodeValue + '</a>' + description + '</li>';		
					} else {
						boardCertification = this.getNodeData(condition,'Board Certification').replace(/\|/g,'; ');
						boardCertification = boardCertification.replace(/\,/g,',&nbsp;');
						clinicalInterest = this.getNodeData(condition,'Clinical Interest').replace(/\|/g,', ');
						/*
						text += '<div>';
						text += '<div class="physicianName">';
						text += '<a href="/doctors/doctor.aspx?ID=' + 
						this.getNodeData(condition,'PhysicianID') + '">' + 
						names[i].childNodes[0].nodeValue + '</a>';
						
						text +='</div>';					
						text += '<div class="physicianPhone" valign="top" width="120">';				
						text += this.getNodeData(condition,'Phone');
						text += '</div>';
						text += '</div>';						
						*/
						text += '<table width="655" border="0" cellspacing="0" cellpadding="0">';
						text += '<tr>';
						text += '<td width="555">';
						text += '<a href="/doctors/doctor.aspx?ID=' + 
						this.getNodeData(condition,'PhysicianID') + '">' + 
						names[i].childNodes[0].nodeValue + '</a>';
						
						text +='</td>';					
						text += '<td valign="top" align="right" width="100">';				
						text += '<span class="physicianPhone">' + dojo.string.trim(this.getNodeData(condition,'Phone')) + '</span>';
						text += '</td>';
						text += '</tr>';
						
						text += '<tr>'
						
						text += '<td colspan="2" class="searchDescription">';
						if (boardCertification != ''){
							text += '<b>Board Certification: </b>' + boardCertification + '<br/>';
						} 
						if (clinicalInterest != ''){
							text += '<b>Clinical Interest or Expertise: </b>' + clinicalInterest;
						}
						text += '</td>';
						text += '</tr>';
						text += '</table>';
						description = text;
											
						output += '<li>' + description + '</li>';
					}
					
					description = '';
					text = '';
					//display changing letters
					
					if (letter != nextLetter){
						output += '</ul>';
						output += '</div>';
						output += '</div>';					
						css = 'contentRow clearfix';
						//css = '';
						output += '<div class="' + css + '">';
						output += '<p>' + nextLetter + '</p>';
						//output += nextLetter;
						output += '<div id="resultsGroup">';
						output += '<ul id="resultsList">';
					}
					counter += 1;
				}
				
			} catch (e) {
				console.log(e);
				break;
			}		
		}
		output += '</ul>';
		output += '</div>';
		output += '</div>';
		this.recordsDislaying = counter;	
		
		if (counter == 0){			
			output = '<p class="noResults">No Results Found.</p>';
			dojo.byId('descriptions').style.display = 'none';			
		} else {
			dojo.byId('descriptions').style.display = 'block';
		}
		return output;
	},
	
	getHierarchyType : function(node)
	{
		var type = '';
		try 
		{
			for (var i=0; i<node.childNodes.length; i++)
			{
				if (node.childNodes[i].nodeName != '#text')
				{
					if (node.childNodes[i].nodeName == 'HIERARCHY')
					{
						if (node.childNodes[i].getAttribute("TYPE") == "BT")
						{							
							try
							{
								// works on ie
								type = node.childNodes[i].childNodes[0].childNodes[0].nodeValue;
							} catch(ex){
								//firefox
								type = node.childNodes[i].childNodes[1].childNodes[0].nodeValue;								
							}
							break;							
						}
					}
				}
			}
		} catch (e) {
			console.log(e);
		}
		return type;
	},
	
	getConditionId : function (node)
	{
		var conditionId = 0;
		var field = '';
		try {
			for (var i=0; i<node.childNodes.length; i++){
				if (node.childNodes[i].nodeName != '#text'){
					if (node.childNodes[i].getAttribute("NAME") == "Condition ID"){
						conditionId = node.childNodes[i].childNodes[0].nodeValue;
						break;
					}
				}
			}
		} catch (e) {
			console.log(e);
		}
		return conditionId;
	},
	
	getNodeData : function (node,attName){
		var data = '';
		var field = '';
		var regEx;
		try {
			for (var i=0; i<node.childNodes.length; i++){
				if (node.childNodes[i].nodeName != '#text'){
					if (node.childNodes[i].getAttribute("NAME") == attName){
						data = node.childNodes[i].childNodes[0].nodeValue;
						break;
					}
				}
			}
		} catch (e) {
			console.log(e);
		}
		return data;
	},
	
	getDescription : function (node)
	{
		var description = 0;
		var field = '';
		try {
			for (var i=0; i<node.childNodes.length; i++){
				if (node.childNodes[i].nodeName != '#text'){
					if (node.childNodes[i].getAttribute("NAME") == "Description"){
						description = node.childNodes[i].childNodes[0].nodeValue;
						break;
					}
				}
			}
		} catch (e) {
			console.log(e);
		}
		return description;
	},	
	
	/********************************** display methods *****************************************/
	//paging functions such as resetHighlights and getNumberOfResults are commented out
	//because this might be a class on its own	
	refreshView : function (num){
		try{
			//console.log(num);
			//this.createAlphaList();
			this.resetHighlights();
			var letter = String.fromCharCode(num);
			//important, set the current page to the letter. the 'letter' variable tells
			//the script to only process one and re-set all other values
			this.gotoPage(num);
			dojo.byId(letter).className = 'active';
			dojo.byId('ALL').className = 'test';
			//this.currentPage = num;
		} catch (e) {
			console.log(e);
		}
	},
	
	letterView : function (num){
		this.resetHighlights();
		var letter = String.fromCharCode(num);
		this.gotoLetter(num);
		dojo.byId(letter).className = 'active';
		dojo.byId('ALL').className = 'test';
	},

	defaultView : function(){
		try{
			//this.createPaging();
			this.createAlphaList();
			this.resetHighlights();
			this.gotoPage(0);
			dojo.byId('A').className = 'test';
			dojo.byId('ALL').className = 'active';
			//this.currentPage = 0;
						
		} catch (e) {
			console.log(e);
		}
	},
	
	/********************************** paging methods *****************************************/
	createAlphaList : function (){
		var output = '<ul><li class="active" id="ALL"><a href="#" onclick="viewAll()">All</a></li>';
		//var output = '<ul>';	
		var letter = '';
		var css = 'test';
		var letterCode = 0;
		for (var i = 0; i < 26; i++)
		{
			letterCode = 65+i;
			letter = String.fromCharCode(letterCode);
			output += '<li id="' + letter + '" class="' + css + '">';
			if (this.letters[letter] != '')
			{	
				output += '<a href="#" onclick="letterView(' + letterCode + ')">';
				output += letter;
				output += '</a>';
			} 
			else 
			{
				output += '<span>' + letter + '</span>';
			}
			
			output += '</li>';
		}
		output += '</ul>';
		dojo.byId('alphaList').innerHTML = output;
		//return output;
	},
	
	resetHighlights : function (){
		var nodes = dojo.query('li', 'alphaList');
		for (var i=0; i < nodes.length; i++){
			nodes[i].className = 'test';	
		}
	},
	
	toggleDescriptions : function (){
		try {
			var nodes = dojo.query('.searchDescription', 'browseResults');
			for (var i=0; i < nodes.length; i++){
				if (nodes[i].style.display == ''){
					nodes[i].style.display = 'block';
				}
				//console.log(i + ' ' + nodes[i].style.display.toString());
				if (nodes[i].style.display == 'block'){
					nodes[i].style.display = 'none';				
				} else {
					nodes[i].style.display = 'block';
				}
			}
		} catch (e) {
			console.log(e);
		}
	},
	
	createPaging : function (start){
		var pages = this.xmlDoc.getElementsByTagName("TERM").length/this.queryParams.numPerPage;
		var i;
		var css = 'test';
		var lowerPage = 1;
		var higherPage = this.queryParams.numPerPage;
		
		var numberOfResults = this.getFiftyNumberOfResults(start); 		
		var resultsDisplay = '<div class="resultNumber" id="numberOfResults">' + numberOfResults + '</div>';

		numberOfResults != '' ? resultsDisplay = resultsDisplay : resultsDisplay = '';
				
		var output = '';

		//start JTG1
		var pageRange = 15;
		var activePage = 1;
		var lowerBoundry = 1;
		var upperBoundry = pages;
		var controlPage = parseInt(pageRange/2);
		var lowerRemainder = 0;
		var upperRemainder = 0;
		
		if (pages > 1){
			output += '<ul>';
			if (start != 0)
			{
		        output += '<li class="prev"><a href="#" onclick="previousPage()">Previous</a></li>';	
				activePage = parseInt(start/this.queryParams.numPerPage);
				activePage = activePage + 1;
			}
	
			if (activePage - controlPage <= 0)
			{
				lowerRemainder = controlPage - activePage;
				lowerBoundry = 0;
				upperBoundry = activePage + controlPage + lowerRemainder + 1;
			}
			if (activePage + controlPage > pages)
			{
				upperRemainder = parseInt(pages) - activePage + 1;
				upperRemainder = controlPage - upperRemainder;
				upperBoundry = pages;
				lowerBoundry = activePage - controlPage - upperRemainder - 1;
			}
			if ((activePage - controlPage > 0) && (activePage + controlPage <= pages))
			{
				upperBoundry = activePage + controlPage;
				lowerBoundry = activePage - controlPage - 1;
			}
	
	
			if (upperBoundry > pages) {upperBoundry = pages;}
			if (lowerBoundry < 0) {lowerBoundry = 0;}
	
			//for (i = 0; i < pages; i++){ 
			for (i = lowerBoundry; i < upperBoundry; i++){ 
				if (activePage-1 == i)
				{
				output += '<li class="' + css + '" id="page' + i + '"><strong>' + (i+1).toString() + '</strong></li>';		
				}
				else
				{
				output += '<li class="' + css + '" id="page' + i + '"><a href="#" onclick="gotoPage(' + (i*this.queryParams.numPerPage) + ')">' + (i+1).toString() + '</a></li>';		
				}
	
			}
			if (activePage < pages)
			{
		        output += '<li class="next"><a href="#" onclick="nextPage()">Next</a></li>';
			}
		    output += '</ul>';
		}   
		return resultsDisplay + output;		
	},
		
	createLetterPaging : function (start){
		var pages = this.xmlDoc.getElementsByTagName("TERM").length/this.queryParams.numPerPage;
		var i;
		var css = 'test';
		var lowerPage = 1;
		var higherPage = this.queryParams.numPerPage;
		var numberOfResults = this.getLetterNumberOfResults(start,'page'); 		
		var resultsDisplay = '<div class="resultNumber" id="numberOfResults">' + numberOfResults + '</div>';		

		output = '';

		//start JTG1
		var pageRange = 15;
		var activePage = 1;
		var lowerBoundry = 1;
		var upperBoundry = pages;
		var controlPage = parseInt(pageRange/2);
		var lowerRemainder = 0;
		var upperRemainder = 0;

		if (pages > 1){	
			output += '<ul>';			
			if (start != 0)
			{
		        output += '<li class="prev"><a href="#" onclick="previousPage()">Previous</a></li>';	
				activePage = parseInt(start/this.queryParams.numPerPage);
				activePage = activePage + 1;
			}
	
			if (activePage - controlPage <= 0)
			{
				lowerRemainder = controlPage - activePage;
				lowerBoundry = 0;
				upperBoundry = activePage + controlPage + lowerRemainder + 1;
			}
			if (activePage + controlPage > pages)
			{
				upperRemainder = parseInt(pages) - activePage + 1;
				upperRemainder = controlPage - upperRemainder;
				upperBoundry = pages;
				lowerBoundry = activePage - controlPage - upperRemainder - 1;
			}
			if ((activePage - controlPage > 0) && (activePage + controlPage <= pages))
			{
				upperBoundry = activePage + controlPage;
				lowerBoundry = activePage - controlPage - 1;
			}
	
	
			if (upperBoundry > pages) {upperBoundry = pages;}
			if (lowerBoundry < 0) {lowerBoundry = 0;}
	
			//for (i = 0; i < pages; i++){ 
			for (i = lowerBoundry; i < upperBoundry; i++){ 
				if (activePage-1 == i)
				{
				output += '<li class="' + css + '" id="page' + i + '"><strong>' + (i+1).toString() + '</strong></li>';		
				}
				else
				{
				output += '<li class="' + css + '" id="page' + i + '"><a href="#" onclick="gotoPage(' + (i*this.queryParams.numPerPage) + ')">' + (i+1).toString() + '</a></li>';		
				}
	
			}
			if (activePage < pages)
			{
		        output += '<li class="next"><a href="#" onclick="nextPage()">Next</a></li>';
			}
		        output += '</ul>';
		}   
		return resultsDisplay;			 
	},
	
	getLetterNumberOfResults : function(startLetter, flag){
		var i;
		var top = 0;
		var count = 0;
		var output = '';
		var total = 0;
		try {			
			if (flag == 'page')
			{
			 	//how many letters to display per page
				top = 1;
				//look for the first letter to have elements and stop when found
				for (i=0; i < this.hasElementsArray.length; i++)
				{
					for (var x = startLetter; x < startLetter + top; x++){
						if (this.hasElementsArray[i] == x){
							this.lowestNumber = parseInt(this.letterBeginEnd[String.fromCharCode(x)].split(",")[0]);
							break;
						}
					}
					//break this loop, find a way of breaking all loops from the nested loop
					if (this.hasElementsArray[i] == x){
						break;
					}					
				}			
				//count the highest numbers on each available elements
				for (i=0; i<top; i++)
				{
					if (this.letters[String.fromCharCode(startLetter + i)] != '')
					{
						total += parseInt(this.letters[String.fromCharCode(startLetter + i)].split(",").length);
					}
				}			
				// to avoid having the label "displaying results 1 to 0 of 2" check whether the
				if(this.lowestNumber > total-1){
					this.highestNumber = this.lowestNumber + total;
				} else {
					this.highestNumber = this.lowestNumber + total-1;
				}			
			} 
		else 
			{
				this.lowestNumber = parseInt(this.letterBeginEnd[String.fromCharCode(this.currentPage)].split(",")[0])
				this.highestNumber = parseInt(this.letterBeginEnd[String.fromCharCode(this.currentPage)].split(",")[1]);					
			}
			if (this.results > 0){			
				output += '<strong>';
				output += this.lowestNumber;
				// so it doesn't read "62 to 62 of 62 results" but instead "62 of 62 results" 
				if (this.lowestNumber != this.highestNumber)
				{
					output += ' to ';
					output += this.highestNumber-1;
				}
				output += '</strong> of ';
				output += this.results;
				output += ' Results';
			} else {
				output = '';
			}
		} 
		catch (e) 
		{
			output='';
		}
		return output;
	},
	
	getFiftyNumberOfResults : function (start){
		var output;
		var end;
		var format = '<strong>${0} to ${1}</strong> of ${2} results';
		
		if(this.results > 0){		
			start += 1;
			start == 1 ? end = 50 : end = start + (this.queryParams.numPerPage-1);
			
			if (end >= this.results){
				end = this.results;
			}							
			output = dojo.string.substitute(format, [ start, end, this.results ]);
		} else {
			output = '<strong>0</strong> results';
		}
		return output;		
	},
	
	/********************************** paging navigation *****************************************/	
	gotoPage : function (start){
		var page = this.displayResults(start,'',0);
		//var num = this.getFiftyNumberOfResults(start);
		this.currentPage = start;
		var paging = this.createPaging(start);
		dojo.byId('browseResults').innerHTML = page;
		this.resetHighlights();
		dojo.byId('ALL').className = 'active';		
		dojo.byId('pagingTop').innerHTML = paging;
		dojo.byId('pagingBottom').innerHTML = paging;		
	},
	
	gotoLetter : function (start) {
		var page = this.displayResults(start,'letter',0);
		var paging = this.createLetterPaging(start);
		this.resetHighlights();
		dojo.byId('browseResults').innerHTML = page;
		dojo.byId('pagingTop').innerHTML = paging;
		dojo.byId('pagingBottom').innerHTML = paging;
	},
	
	nextPage : function () {
		var page = this.currentPage + this.queryParams.numPerPage;
		if (page < this.results){
			this.gotoPage(page);
		}
	},
	
	previousPage : function(){
		var page = this.currentPage - this.queryParams.numPerPage;
		if (page < 0){
			page = 0;
		}
		this.gotoPage(page);
	}	
});// JavaScript Document