dojo.declare("com.mgh.Archive", null, {
    constructor: function(config) {
        /********************************** Default Variables *****************************************/

        this.xmlDoc;
        this.numPerPage = config.numPerPage;
        this.years = config.years;
        this.filter = config.filter;
        this.href = config.href;

        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['News releases'] = '/about/pressrelease.aspx?id=';
        this.activeTab = 'ALL';
        this.dateRE = /^(\d{2})[\/\- ](\d{2})[\/\- ](\d{4})/;
        this.currentPage = 0;
        this.query = '';

        try {
            fadeOutNode('resultsColumn');
            fadeOutNode('filter1');
            fadeOutNode('conditions1');
        } catch (e) {
            console.log(e);
        }
    },

    updateQuery: function(params) {
        this.filter = params;
        this.query = this.href + dojo.toJson(params);
        this.getXmlString();
    },

    getXmlString: function() {
        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.numPerPage;
        var i;
        var css = 'test';
        var lowerPage = 1;
        var higherPage = this.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.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.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) {
            //node.text;
            //console.log(attName);
        }
        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.numPerPage) {
                end = start + (total - 1);
            } else if ((start + (this.numPerPage - 1)) < this.results) {
                end = start + (this.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 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.numPerPage > terms.length ?
			upperLimit = terms.length :
			upperLimit = id + this.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];
                    //var tempName = names[current].childNodes[0].nodeValue;
                    //tempName = tempName != '' || tempName != undefined ?
                    //tempName.split('|')[0] : 'n/a';
                    name = names[current].childNodes[0].nodeValue.split('|')[0];
                    //name = tempName;
                    description = this.getNodeData(metaTags[current], 'Description').replace('In this issue: ', '');
                    date = this.getNodeData(metaTags[current], 'Date');
                    newsControl = this.getNodeData(metaTags[current], 'NewsControl');
                    newsControl = newsControl.toLowerCase() == "press releases" ? "News releases" : newsControl;
                    newsId = this.getNodeData(metaTags[current], 'NewsID');

                    text += '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
                    text += '<tr>';
                    text += '<td class="searchDescription">';

                    text += description;

                    if (description) {
                        text += '<br>';
                    }

                    text += '</td>';
                    text += '</tr>';
                    text += '</table>';
                    //text += '</span>';

                    link = this.getNodeData(metaTags[current], 'Link');

                    if (link != '') {
                        //regEx.test(link) ? fullUrl = link : fullUrl = this.urlRoot + link;
                        fullUrl = link;
                    } else {
                        fullUrl = this.urlRoot + this.url[newsControl] + newsId;
                    }
                    output += '<div class="archiveResults"><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 = '<div class="noResultsBody" style="border-bottom: none;">\
								<p><b>No results found.</b><br />\
								Deselect one or more categories above to display more results. \
								Or, <a href="#" onclick="dojo.publish(\'clearAllSelections\', [])">clear all selections</a> and try your search again.<br/>\
								To expand your search to the entire Mass General website, use the search box in the top right corner of the page.</p>\
							</div>';
                dojo.byId('descriptions').style.display = 'none';
            }

            output += '</div>';
        } catch (e) {
            //console.log('Archive.displayResults ' + e);
        }
        return output;
    },

    nextPage: function() {
        var page = this.currentPage + this.numPerPage;
        if (page < this.results) {
            this.gotoPage(page);
        }
    },

    previousPage: function() {
        var page = this.currentPage - this.numPerPage;
        if (page < 0) {
            page = 0;
            //this.currentPage = 0;
        }
        this.gotoPage(page);
    }
});
