dojo.declare("com.mgh.Archive",null, {
	constructor : function(configParams) {
	/********************************** Default Variables *****************************************/

		this.xmlDoc;
		this.queryParams = configParams;
		this.query = '';    
		this.years = ['2007','2008','2009'];
		this.years.sort().reverse();
		this.newsArchive = new Array();
		this.currentYear = "0";
		this.urlRoot = "http://www.massgeneral.org";
		this.url = new Array();
		this.url['News articles']= '/about/newsarticle.aspx?id=';
		//this.url['Press releases'] = '/about/pressrelease.aspx?id='; 
		this.url['News releases'] = '/about/pressrelease.aspx?id='; 
		this.url['Newsletters & publications'] = '/about/publication.aspx?id='; 
		this.activeTab = 'ALL';	
		this.dateRE = /^(\d{2})[\/\- ](\d{2})[\/\- ](\d{4})/;
		this.currentPage = 0;			
		try {	
			fadeOutNode('resultsColumn');
			fadeOutNode('filter1');
			fadeOutNode('conditions1');
		} catch (e) {
			console.log(e);
		}
		
		this.getXmlString();
	},
	
	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 + 
		'&month=' + (m.month + 1) + '&audience=' + m.audience + '&eventType=' + m.eventType + '&mediaType=' + m.mediaType + '&newsType=' + m.newsType + 
		'&year=' + m.year + '&topic=' + m.topic;
		//alert(this.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 terms = this.xmlDoc.getElementsByTagName("TERM").length;
		this.newsArchive["0"] = this.sortIdRangeByDate(0,terms,0);
		for (var i=0; i<this.years.length; i++){
			this.newsArchive[this.years[i]] = this.sortIdRangeByDate(0,terms,parseInt(this.years[i]));
		}
	},

	defaultView : function (){
		try{
			this.currentYear = 0;			
			this.activeTab = 'ALL';
			this.createAlphaList();
			this.gotoPage(0);
						
		} catch (e) {
			console.log(e);
		}		
	},
		
	letterView : function (num){
		console.log(this.activeTab + ' ' + num);
		this.currentYear = num;
		this.activeTab = num;
		this.gotoPage(0);
	},
		
	gotoPage : function (start){
		this.currentPage = start;
		this.resetHighlights();		
		var page = this.displayResults(start);
		var paging = this.createPaging(start);
		
		dojo.byId('browseResults').innerHTML = page;
		dojo.byId(this.activeTab).className = 'active';	
		dojo.byId('pagingTop').innerHTML = paging;
		dojo.byId('pagingBottom').innerHTML = paging;		
	},
	
	createAlphaList : function (){
		var output = '<ul><li class="active" id="ALL"><a href="#" onclick="viewAll()">All</a></li>';
		var css = 'test';
		var letterCode = 0;
		for (var i = 0; i < this.years.length; i++)
		{
			output += '<li id="' + this.years[i] + '" class="' + css + '">';
			output += '<a href="#" onclick="letterView(\'' + this.years[i] + '\')">';
			output += this.years[i];
			output += '</a>';
			output += '</li>';
		}
		output += '</ul>';
		dojo.byId('alphaList').innerHTML = output;
	},
	
	resetHighlights : function (){
		var nodes = dojo.query('li', 'alphaList');
		for (var i=0; i < nodes.length; i++){
			nodes[i].className = 'test';	
		}
	},	
	
	createPaging : function (start){
		var pages = this.newsArchive[this.currentYear].length/this.queryParams.numPerPage;
		var i;
		var css = 'test';
		var lowerPage = 1;
		var higherPage = this.queryParams.numPerPage;
		
		var numberOfResults = this.getNumberOfResults(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;		
	},	
	
	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;
	},
	
	toggleDescriptions : function (){
		try {
			var nodes = dojo.query('table', '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);
		}
	},

	getNumberOfResults : function(start){
		start += 1;
		var total = this.newsArchive[this.currentYear].length;
		var end;
		var output = '';
		var test = this.newsArchive[this.currentYear].toString();
		if (( test != 'NaN') && (test != '') && (total != 0)){
			if (total < this.queryParams.numPerPage){
				end = start + (total-1);
			} else if ((start + (this.queryParams.numPerPage - 1)) < this.results) {
				end = start + (this.queryParams.numPerPage-1);	
			} else {
				end = this.results;
			}
			output = '<strong>';
			output += start;
			if (start < total){
				output += ' to ';
				output += end;
			}
			
			output += '</strong> of ';
			output += '<strong>' + total + '</strong>';
			output += ' Results';
		} else {
			//output = '<strong>No Results Found</strong>';	
			output = '';
		}
		return output;	
	},
	
	sortIdRangeByDate : function (start,end,currentYear){
		var ids = new Array();
		var dates = new Array(); //['12/1/2008','11/30/2008','1/1/2009','10/5/1008','10/5/2009','11/7/2009','1/1/2008','2/2/2008','3/31/2009','3/31/2008'];
		var nodes = this.xmlDoc.getElementsByTagName('METADATA');
		var day;
		var month;
		var year;
		var sortedDates;
		var sortedIds = new Array();
		var i;
		var date;
		var tempDate;
		
		for (i=start; i<end; i++){
			try {
				date = this.getNodeData(nodes[i],'Date');
				month = date.split('/')[0];
				parseInt(month) < 10 ? month = "0" + month : month = month;
				day = date.split('/')[1];
				parseInt(day) < 10 ? day = "0" + day : day = day;	
				year = date.split('/')[2];
				
				tempDate = year + '/' + month + '/' + day;
				
				if (currentYear == 0){
					ids.push(i);
					dates.push(tempDate + '|' + i);
				} else {
					if (year == currentYear){
						ids.push(i);
						dates.push(tempDate + '|' + i);
					}					
				}
			} catch (e){
				
			}
		}

		sortedDates = dates.sort().reverse();
		
		for (i = 0; i < sortedDates.length; i++){
			sortedIds.push(parseInt(sortedDates[i].split('|')[1]));
		}	
		return sortedIds;	
	},
	
	sortDatesDMY : function (a, b){
		a = a.replace(this.dateRE,"$3$2$1");
		b = b.replace(this.dateRE,"$3$2$1");
		if (a>b) return -1;
		if (a <b) return 1;
		return 0; 
	},	
	
	sortDatesMDY : function (a, b){
		a = a.replace(this.dateRE,"$3$1$2");
		b = b.replace(this.dateRE,"$3$1$2");
		if (a>b) return 1;
		if (a <b) return -1;
		return 0; 
	},
		
	displayResults : function(id){
		try {
			var eventsToday;
			var upperLimit;
			var names;
			var ids;
			var physicianTableClass = 'physicianTable';
			var description = '';
			var date = '';
			var name = '';
			var text = '';
			var link = ''
			var fullUrl = '';
			var newsControl;
			var newsId;
			var regEx = /http:\/\//i;
			var jtg1Flag = 0;
			
			var terms = this.xmlDoc.getElementsByTagName("TERM");
			var names;
			var metaTags;
			
			this.queryParams.numPerPage > terms.length ? 
			upperLimit = terms.length : 
			upperLimit = id + this.queryParams.numPerPage;
			
			ids = this.newsArchive[this.currentYear];
			this.results = ids.length;
			var test = ids.toString();
			var total = ids.length;
			
			var css = ''
			var output = '<div id="resultsGroup" class="leftMargin">';
			//output += '<div id="dayFormat">Events for : <span id="dayName">'+ dojo.date.locale.format(currentDay, {selector:'date', formatLength:'full'}) + '</span></div>';
			
			if (( test != 'NaN') && (test != '') && (total != 0)){

				names = this.xmlDoc.getElementsByTagName('NAME');
				metaTags = this.xmlDoc.getElementsByTagName('METADATA');
				
				for (var i=id; i < upperLimit; i++){
					
					current = ids[i];
					name = names[current].childNodes[0].nodeValue.split('|')[0];
					description = this.getNodeData(metaTags[current],'Description');
					date = this.getNodeData(metaTags[current],'Date');
					newsControl = this.getNodeData(metaTags[current],'NewsControl');
					newsId = this.getNodeData(metaTags[current],'NewsID');

					//if (i == upperLimit-1){
					//	physicianTableClass = 'physicianTableLast';
					//}
					
					//text += '<span class="conditionDescription">';
					//text += '<table width="680" border="0" cellspacing="0" cellpadding="0" class="' + physicianTableClass + '">';
					text += '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
					text += '<tr>';
					text += '<td>';
					
					text += description;
				
					if (description){
						text +='<br>';
					}

					text +='</td>';
					text += '</tr>';
					text += '</table>';
					//text += '</span>';
						
					
					try {
						link = this.getNodeData(metaTags[current],'Link');
					} catch (e) {
						link = null;
					}

					if (link){
						regEx.test(link) ? fullUrl = link : fullUrl = this.urlRoot + link;
					} else {
						fullUrl = this.urlRoot + this.url[newsControl] + newsId;					
					}
					output += '<div class="archiveResults">';

					//space not at the top at
					if (jtg1Flag == 1)
					{
						output += '<BR>';
					}
					jtg1Flag = 1;

					output += '<a href="' +  fullUrl  + '">' + date + ': ' + name + '</a>' + '&nbsp;&nbsp;<span style="font-size: 11px">(' + newsControl + ')</span>'+ text + '</div>';
					text = '';
				}

				dojo.byId('descriptions').style.display = 'block';								
			} else {
				output += '<p class="noResults">No Results Found.</p>';
				dojo.byId('descriptions').style.display = 'none';
			}		
					
			output += '<br></div>';				
		} catch (e) {
			console.log(e);
		}		
		return output;
	},


	displayResults2 : function(id){
		try {
			var eventsToday;
			var upperLimit;
			var names;
			var ids;
			var physicianTableClass = 'physicianTable';
			var description = '';
			var date = '';
			var name = '';
			var text = '';
			var link = ''
			var fullUrl = '';
			var newsControl;
			var newsId;
			var regEx = /http:\/\//i;
			
			
			var terms = this.xmlDoc.getElementsByTagName("TERM");
			var names;
			var metaTags;
			
			this.queryParams.numPerPage > terms.length ? 
			upperLimit = terms.length : 
			upperLimit = id + this.queryParams.numPerPage;
			
			ids = this.newsArchive[this.currentYear];
			this.results = ids.length;
			var test = ids.toString();
			var total = ids.length;
			
			var css = ''
			var output = '<div id="resultsGroup">';
			//output += '<div id="dayFormat">Events for : <span id="dayName">'+ dojo.date.locale.format(currentDay, {selector:'date', formatLength:'full'}) + '</span></div>';
			
			if (( test != 'NaN') && (test != '') && (total != 0)){
				
				output += '<ul id="resultsList">';	

				names = this.xmlDoc.getElementsByTagName('NAME');
				metaTags = this.xmlDoc.getElementsByTagName('METADATA');
				
				for (var i=id; i < upperLimit; i++){
					
					current = ids[i];
					name = names[current].childNodes[0].nodeValue.split('|')[0];
					description = this.getNodeData(metaTags[current],'Description');
					date = this.getNodeData(metaTags[current],'Date');
					newsControl = this.getNodeData(metaTags[current],'NewsControl');
					newsId = this.getNodeData(metaTags[current],'NewsID');

					//if (i == upperLimit-1){
					//	physicianTableClass = 'physicianTableLast';
					//}
					
					//text += '<span class="conditionDescription">';
					//text += '<table width="680" border="0" cellspacing="0" cellpadding="0" class="' + physicianTableClass + '">';
					text += '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
					text += '<tr>';
					text += '<td>';
					
					text += description;
				
					if (description){
						text +='<br>';
					}

					text +='</td>';
					text += '</tr>';
					text += '</table>';
					//text += '</span>';
						
					
					try {
						link = this.getNodeData(metaTags[current],'Link');
					} catch (e) {
						link = null;
					}

					if (link){
						regEx.test(link) ? fullUrl = link : fullUrl = this.urlRoot + link;
					} else {
						fullUrl = this.urlRoot + this.url[newsControl] + newsId;					
					}
					output += '<li><a href="' +  fullUrl  + '">' + date + ': ' + name + '</a>' + '&nbsp;&nbsp;<span style="font-size: 11px">(' + newsControl + ')</span>'+ text + '</li>';
					text = '';
				}
				output += '</ul>';
				dojo.byId('descriptions').style.display = 'block';								
			} else {
				output += '<p class="noResults">No Results Found.</p>';
				dojo.byId('descriptions').style.display = 'none';
			}		
					
			output += '</div>';				
		} catch (e) {
			console.log(e);
		}		
		return output;
	},
	
	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.currentPage = 0;
		}
		this.gotoPage(page);
	}		
});