dojo.declare("com.mgh.PhysicianSearch", [com.mgh.Search], {
    constructor: function(configParams) {
		// Check the query string for a preselected center.
		// When this is not the case and a center is selected from state, the path to the
		// folder is correct
		this.center = '';
		var qs = new com.mgh.QueryString(null);
		var center = qs.params["center"];
		if (center !== undefined){
			this.center = center;
		}
    },

    /********************************** xml methods *****************************************/
    physicianById: function(id) {
        showTimer();
        dojo.xhrGet({
            url: this.queryParams.byIdHref + '?id=' + id,
            handleAs: "text",
            load: function(response, ioArgs) {
                searchDataReady(response);
                return response;
            },
            error: function(response, ioArgs) {
                alert("An error occurred, with response: " + response);
                return response;
            }
        });
    },

    physiciansByTerm: function(term) {
        showTimer();
        var newObject = $.extend({}, this.queryParams.jsonQuery);
        newObject.term = term;
        dojo.xhrGet({
            url: this.queryParams.href + '?json=' + dojo.toJson(newObject),
            handleAs: "text",
            load: function(response, ioArgs) {
                searchDataReady(response);
                return response;
            },
            error: function(response, ioArgs) {
                alert("An error occurred, with response: " + response);
                return response;
            }
        });
    },

    printUpdatedQuery: function() {
        console.log(this.query);
    },

    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;

        var p = ["A", "B", "C", "d", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];

        for (var x = 0; x < p.length; x++) {
            letter = p[x];
            for (i = 0; i < names.length; i++) {
                name = names[i].childNodes[0].nodeValue;
                if (name.substring(0, 1) == letter) {
                    endLetter += 1;
                    a += i + ',';
                    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;
    },

    displayResults: function(id, type) {
        var i;
        var text = '';
        var output = '';
        var physician = '';
        var letter = '';
        var nextLetter = '';
        var counter = 0;
        var description = '';
        var clinicalInterests = '';
        var boardCertifications = '';
        var acceptingPatients = '';
        var acceptingPrimaryCarePatients = '';
        var acceptingSpecialtyPatients = '';

        var newPatientComments = '';
        var newPrimaryCarePatientComments = '';
        var newSpecialtyPatientComments = '';

        var upperLimit;
        var ids;

        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;
            }
        }

        //'d' must precede 'D'
        if (letter == 'D') {
            output += (this.displayResults(100, 'letter'));
        }

        var elements = new Array();
        var terms = this.xmlDoc.getElementsByTagName("TERM");
        var names = this.xmlDoc.getElementsByTagName("NAME");
        var physicians = this.xmlDoc.getElementsByTagName("METADATA");
        var centerFolder = this.checkForCenter();

        var boardCertificationsFormat = '<b>Board Certification: </b>${0}<br/>';
        var clinicalInterestsFormat = '<b>Clinical Interests: </b>${0}<br/>';
        var acceptingNewPatientsFormat = '<b>Accepting New Patients: </b>${0}<br/>';
        var acceptingPrimaryCarePatientsFormat = '<b>Accepting New Primary Care Patients: </b>${0}<br/>';
        var acceptingSpecialtyPatientsFormat = '<b>Accepting New Specialty Patients: </b>${0}<br/>';
        var physicianPhotoFormat = '<div class="physicianPhoto"><a href="${urlRoot}/${centerFolder}doctors/doctor.aspx?id=${id}">\
									<img width="80" src="${photo}"></a></div>';

        var physicianFormat = '<div class="physician">\
									<div class="physicianInfo">\
										${photo}\
										<a class="physicianName" href="${urlRoot}/${centerFolder}doctors/doctor.aspx?id=${id}">${name}</a> <br>\
										<div class="searchDescription ${descriptionCss}">\
											${boardCertifications}\
											${clinicalInterests}\
											${acceptingNewPatients}\
											${acceptingNewPrimaryCarePatients}\
											${acceptingNewSpecialtyPatients}\
										</div>\
									</div>\
									<div class="physicianPhone">${phone}</div>\
								</div>';

        for (i = id; i < upperLimit; i++) {
            try {
                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;
                }
				
                var physicianInfo = {
                    id: '',
                    descriptionCss: '',
                    name: '',
                    urlRoot: '',
                    photo: '',
                    phone: '',
                    boardCertifications: '',
                    clinicalInterests: '',
                    acceptingNewPatients: '',
                    acceptingNewPrimaryCarePatients: '',
                    acceptingNewSpecialtyPatients: '',
					centerFolder : centerFolder
					
                };

                physician = physicians[i];
                //description = this.getNodeData(condition, 'Description');
                boardCertifications = this.getNodeData(physician, 'Board Certification').replace(/\|/g, '; ');
                boardCertifications = boardCertifications.replace(/\,/g, ',');
                clinicalInterests = this.getNodeData(physician, 'Clinical Interest').replace(/\|/g, ', ');
                acceptingNewPatients = this.getNodeData(physician, 'Accepting New Patients');

                /* 08/18/2010 */
                acceptingPrimaryCarePatients = this.getNodeData(physician, 'Accepting New Primary Care Patients');
                acceptingSpecialtyPatients = this.getNodeData(physician, 'Accepting New Specialty Patients');

                newPatientComments = this.getNodeData(physician, 'New Patient Comments');
                newPrimaryCarePatientComments = this.getNodeData(physician, 'New Primary Care Patient Comments');
                newSpecialtyPatientComments = this.getNodeData(physician, 'New Specialty Patient Comments');

                physicianInfo.id = this.getNodeData(physician, 'PhysicianID');
                physicianInfo.name = names[i].childNodes[0].nodeValue;
                physicianInfo.phone = dojo.string.trim(this.getNodeData(physician, 'Phone'));

                //display the first letter
                if (counter == 0) {
                    output += '<table class="resultsGroup" cellspacing="0" cellpadding="0">';
                    output += '<tr>';
                    output += '<td class="letter" valign="top">' + letter + '</td>';
                    output += '<td class="physicians">';
                }

                if (boardCertifications != '') {
                    physicianInfo.boardCertifications = dojo.string.substitute(boardCertificationsFormat, [boardCertifications]);
                }

                if (clinicalInterests != '') {
                    physicianInfo.clinicalInterests = dojo.string.substitute(clinicalInterestsFormat, [clinicalInterests]);
                }

                if (acceptingNewPatients != '') {
                    acceptingNewPatients += this.checkForComments(newPatientComments);
                    physicianInfo.acceptingNewPatients = dojo.string.substitute(acceptingNewPatientsFormat, [acceptingNewPatients]);
                }

                /* 08/19/2010 */
                if (acceptingPrimaryCarePatients != '') {
                    newPrimaryCarePatientComments = newPrimaryCarePatientComments != '' ? ' - ' + newPrimaryCarePatientComments : '';
                    acceptingPrimaryCarePatients += newPrimaryCarePatientComments;
                    physicianInfo.acceptingNewPrimaryCarePatients = dojo.string.substitute(acceptingPrimaryCarePatientsFormat, [acceptingPrimaryCarePatients]);
                }

                if (acceptingSpecialtyPatients != '') {
                    newSpecialtyPatientComments = newSpecialtyPatientComments != '' ? ' - ' + newSpecialtyPatientComments : '';
                    acceptingSpecialtyPatients += newSpecialtyPatientComments;
                    physicianInfo.acceptingNewSpecialtyPatients = dojo.string.substitute(acceptingSpecialtyPatientsFormat, [acceptingSpecialtyPatients]);
                }
				
                if (this.getNodeData(physician, 'Display Photo') == 'Y') {
					physicianInfo.photo = this.getNodeData(physician, 'Photo');
                    physicianInfo.photo = dojo.string.substitute(physicianPhotoFormat, physicianInfo);
                    physicianInfo.descriptionCss = 'physicianDescription';
                }				

                //add current physician
                output += dojo.string.substitute(physicianFormat, physicianInfo);

                //display changing letters
                if (letter != nextLetter) {
                    //close current letter
                    output += '</td>';
                    output += '</tr>';
                    output += '</table>';

                    //open new a new one only if there are less than the number per page.
                    //otherwise, only the letter will show.							
                    output += '<table class="resultsGroup lowerResults" cellspacing="0" cellpadding="0">';
                    output += '<tr>';
                    output += '<td class="letter" valign="top">' + nextLetter + '</td>';
                    output += '<td class="physicians">';
                }
                counter += 1;

            } catch (e) {
                console.log(e);
                break;
            }
        }

        output += '</td>';
        output += '</tr>';
        output += '</table>';
        this.recordsDislaying = counter;

        if (counter == 0) {
            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>';
            // results with 'd' should not display error message
            output = letter == 'd' ? '' : output;
            dojo.byId('descriptions').style.display = 'none';
        } else {
            dojo.byId('descriptions').style.display = 'block';
        }
        return output;
    },

    checkForComments: function(comments) {
        return comments != '' ? ' - ' + comments : '';
    },

    //Search for these folders instead in the database.
    checkForCenter: function() {
        var center;
        switch (this.center) {
            case '4':
                center = 'cancer/';
                break;

            case '9':
                center = 'digestive/';
                break;

            case '15':
                center = 'heartcenter/';
                break;

            case '52':
                center = 'vascularcenter/';
                break;

            case '20':
                center = 'children/';
                break;

            case '38':
                center = 'psychiatry/';
                break;

            default:
                center = '';
                break;
        }

        return center;
    },

    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';
                }
            }

            jQuery('div.physicianPhoto').each(function() {
                jQuery(this).toggle();
            });

        } catch (e) {
            console.log(e);
        }
    }

});   // JavaScript Document
