﻿// JScript File

/* 

Script: SpecialtySelector.js
    javascript to support SpecialtySelector and LicenseAdder in Manage/Create Account.
	Depends on the mootools library (mootools.v1.11.js)

*/


/* 

    Class: specialtySelector
    javascript class object that handles the addition of specialties to the account management page.



*/


var specialtySelector = Fx.Base.extend({
		getExtended: function(){
			return{	
            };
		},	
		
		/* 
		
		Constructor: initialize
		initializes the specialtySelector
		
		Arguments: 
		    table - The HTML table where Specialties will be added
		    adder - HTML link which will initiate the adding of a specialty
		    
		Examples: 
		> var specSel = new specialtySelector($$('table#featAct'), $('addSpecialty'));
		
		See Also: 
		<LicenseAdder>
		
		*/
		
		initialize: function(table, adder,  options){
		    //Iniitializing values
		    this.table = $$(table);
		    this.adder = $$(adder);
		    this.rows = this.table.rows;
		    this.rowNum = this.table[0].tBodies[0].rows.length;
		    this.coords = findPos(this.adder[0]);
		    this.inputType = $('inputMode').value;
		    this.others = $$('#SpecialtySelector .other')
		    this.adder[0].addEvent('click', this.open_box.bind());
		    this.edits = $$('#featAct tbody tr .editCell');
		    this.removes = $$('#featAct tbody tr .removeCell');
		    
		    //Adding click events to window close, add, and edit		    
		    $E('#specClose').addEvent('click', this.cancel_behavior.bind(this));
		    $E('#specAdd').addEvent('click', this.add.bind(this));
		    $E('#specEdit').style.display = 'none';
		    
		    //
		    this.check_add();
		    
		    //Initializing all Edit Buttons
		    this.edits.each(function(el, i){
		        var editEl = create_edit('specSel', i);
		        el.appendChild(editEl);		        
		    })
		    //Iniitializing all Remove Buttons 
		    this.removes.each(function(el, i){
		        var editEl = create_remove('specSel', i);
		        el.appendChild(editEl);		        
		    })
		    
		    //Pre-Checking "Primary Specialty" checkbox for Create... It should always be the primary for create...
		    if( $('inputMode').value == 'Create' ){
		        $E('#PSpecialty input').checked = true;
		        $('PSpecialty').style.display = 'none';		        
		        
		    }		    
		},
		
		/* 
		
		    Function: add
		    adds selected specialty and its characteristic to table of existing specialties on page.
		    
		    Parameters: 
		    rowAdd - Int. Nullable.  Number which corresponds to the row that is currently being added.  Will be null for a new row (rather than "edit" rows).
		    
		*/
		
		add: function(rowAdd){
		    //If the form passes validation, proceed...
		    if(validate_spec('specSel',rowAdd)== true){
		        //Remove action from Edit button (This will be readded when user clicks an 'Edit')
		        $E('#specEdit').removeEvents('click');
		        //Setting limit of rows to add... Create = 1, Manage = 5
		        var SpecLimit = ($E('#inputMode').value == 'Manage')?5:1;
		        var el = 'this';
		        
		        if( typeof rowAdd != 'number'){
		            //This is checking for whether this is a clean "add" or an "edit row"
		            $('specEdit').style.display = 'none';
		            $('specAdd').style.display = 'block';
		            el = '';
		            rowAdd = this.rowNum;
		        }
		    //Initializing values to add
		    var content = new Array();
		    var q = $E('#slcProfession');
		    var r = $E('#slcSubSpecialty');
		    var mult = check_multiple(r,'text');
		    var specText = q[q.selectedIndex].text;
            var subSpecText = mult;
            var inBC = '';
            
            
            //The following sets table display values for added Specialty
            if($('BoardCertified').style.display == 'block'){
                $$('#BoardCertified input').each(function(el){inBC += (el.checked == true)?el.value:''});
            }
            else{
                inBC = 'N/A';
            }
                        
            //If the primary checkbox is checked... 
            var varPrim = ($E('#PSpecialty input').checked)?'Primary':'';
            if(varPrim == 'Primary') {remove_primary($('featAct'))};		    
		    
		    //If Other Primary Specialty textbox is not empty...
		    if($E('#PrimarySpecialtyOther input').value != ''){
                specText += ': ' + $E('#PrimarySpecialtyOther input').value;
                other = $E('#PrimarySpecialtyOther input').value;
            }
            //If subspecialty textbox is not empty...
            else if($E('#SubSpecialtyOther input').value != ''){
                subSpecText += ': ' + $E('#SubSpecialtyOther input').value;
                other = $E('#SubSpecialtyOther input').value;
            
            }
            else{
                other = '';
            }		    
		    
		    content[0] = document.createTextNode(specText);
		    content[1] = document.createTextNode(varPrim);
		    content[2] = document.createTextNode(inBC);
		    content[3] = document.createTextNode(subSpecText);
		    content[4] = create_edit('specSel', rowAdd);
		    content[5] = (this.inputType == 'Create')?document.createTextNode(''):create_remove('specSel', rowAdd);              
            
            //Create row in table to add
		    var row = document.createElement('tr');
		        row.className = (rowAdd % 2 == 0)?'even':'odd';
		        for (i=0; i< content.length ; i++) {
		            var td = document.createElement('td');
		            td.className = '';
		            td.className=(i == 4)?'editCell':td.className;
		            td.className=(i == 5)?'removeCell':td.className;
		            td.appendChild(content[i]);
		            //adding content element to new table row
		            try{row.appendChild(td);}
		            catch(err){alert(err.description);}
		        }
		        if(inBC == 'Yes'){
		            inBC = 'true';
		        }
		        else if(inBC == 'No'){
		            inBC = 'false';
		        }
		        else{
		        inBC = 'false';
		        }
		    //checking to see if this is a Primary Specialty
		    varPrim = (varPrim == 'Primary')?'true':'false';    
		    //Create hidden input value. 		    
		    var hiddenVal = q[q.selectedIndex].value + ':' + inBC + ':' + check_multiple(r,'value')+':'+ other + ':' + varPrim;  
		    row.appendChild(createHidden(hiddenVal, 'Specialty'));
		          var psych = q[q.selectedIndex].text;
		          if(el == ''){
		              row.id = 'specRow_'+ this.rowNum;  
		              this.table[0].tBodies[0].appendChild(row);
		              this.close_box();
		              this.rowNum++;
		          }
	              else{
	                  if(q.selectedIndex > 0 ){
	                  row.id = 'specRow_'+rowAdd;
        		      
	                  var repTR = "#featAct #specRow_"+rowAdd;
	                  $E('#featAct').tBodies[0].replaceChild(row, $E(repTR) );
        		      
	                  specSel.close_box();
	                }
	              }
	                self.changed = true;
	          check_profession($E('#ProfessionSelector select'));
		      $E('#featAct').tFoot.style.visibility = ($$('table#featAct tbody tr').length < SpecLimit)?'visible':'hidden';
		      }
		},
		
		/* 
		    Function: check_add
		    Checks a hidden input field on the page to see whether or not the context is "Create Account" or "Manage Account"
		    
		*/
		
		check_add: function(){
		    var SpecLimit = ($E('#inputMode').value == 'Manage')?5:1;		    
		    $E('#featAct').tFoot.style.visibility = ($$('table#featAct tbody tr').length < SpecLimit && $E('#ProfessionSelector select').selectedIndex > 0)?'visible':'hidden';
		
		},
		
		/* 
		    Function: edit_row
		    Contains all functionality to edit a row currently listed in specialty table.
		    
		    Parameter: 
		    rowNum - Int. Identifies the zero-based row number that function will edit.
		*/
		
		edit_row: function(rowNum) {
		    //Removes the previous click event associated with "save" button.  Will replace later. 
		    $E('#specEdit').removeEvent('click');
		    //Hides the "add" submit button
		    $('specAdd').style.display = 'none';
		    //Displays the "edit" submit button
		    $('specEdit').style.display = 'block';
		    
		    //Gets values of desired row's hidden input
		    var elem = $E('#specRow_'+rowNum+' input#Specialty');
		    var elem_values = elem.value.toString().split(':');
		    
		    //Opens box passing type 
		    this.open_box(function(){$('slcProfession').options[select_value('slcProfession', elem_values[0])].selected = true;});
		    var subsp = elem_values[2].split(',');		    		       		    
		    
		    //Sets primary specialty select box
		    var SpecIndex = select_value('slcProfession', elem_values[0]);
		    $('slcProfession').options[SpecIndex].selected = true;
		    
		    //sets subspecialty select box based on specialty
		    controlSelect($('slcProfession'), 'subspecialty', $('divSubSpecialty'), 
		        function(){		    
		        //sets 'other' values (if necessary)
		        if($('slcProfession').options[SpecIndex].text == 'Other'){
		            $E('#PrimarySpecialtyOther input').value = elem_values[3];
		              } 
    		    
		        else if($('divSubSpecialty').hasChildNodes() && subsp.length > 0 && subsp[0]!=''){
		           var subSpSel = $('slcSubSpecialty');
    		       
		           for (j=0; j<subsp.length; j++){
		              subSpSel.options[select_value(subSpSel.id, subsp[j])].selected = true;
                      if(subSpSel.options[select_value(subSpSel.id, subsp[j])].text=='Other'){$E('#SubSpecialtyOther input').value = elem_values[3];}
                    }
                    check_for_other($E('#divSubSpecialty select'), $('SubSpecialtyOther'));
                    
                    //completer here is selecting all previous selections
		          };
		        //Sets board certification value
		        var boardCert = elem_values[1];
		        var BCsel = (boardCert == 'true')?0:1;
		        
		        $$('#BoardCertified input')[BCsel].checked = true;		        
		    },1);
		    
		    $E('#PSpecialty input').checked = (elem_values[4] == 'true')?true:false;
		    
		    //Re-adds "edit" submit click event
		    $E('#specEdit').addEvent('click', this.add.bind(this, rowNum));
		    self.changed = true;
		    
		},
		
		/* 
		    Function: delete_row
		    Removes row from Specialty Table.
		    		    
		    Parameters: 
		    rowNum - Int. zero-based integer representing row to delete.
		*/
		
		delete_row: function(rowNum){
		    //checks page type (Create/Manage)
		    var SpecLimit = ($E('#inputMode').value == 'Manage')?5:1;
		    //After confirmation, removes the row in question from Specialty Table
		    if(confirm('Are you sure you want to delete this Specialty?')){
		        var remover = $E('#specRow_'+rowNum);
		        this.table[0].tBodies[0].removeChild(remover);
		        self.changed = true;
		    }
		    $E('#featAct').tFoot.style.visibility = ($$('table#featAct tbody tr').length < SpecLimit)?'visible':'hidden';
		    
		},
	
	    /* 
		    Function: open_box
		    
		    Parameters: 
		    type - object. Nullable.
		
		*/
	    
		open_box: function(type) {
		    if(typeof type == 'undefined' || typeof type == 'object' ){
		        type = '';
		    }
		    
		    //Drape effects... 
		    
		    var drape = $('drape');
		    drape.style.width = window.getScrollWidth() + 'px';		    
		    drape.style.height = window.getScrollHeight() + 'px';		    
		    drapefx = new Fx.Style('drape', 'opacity', {
		        duration: 500, 
		        transition: Fx.Transitions.quartIn
		    }).start(0,.5);
		    
		    //IE6 Only code... Hides all select boxes that would sit below the drape
		    if(navigator.appName == 'Microsoft Internet Explorer' && navigator.appVersion.indexOf('MSIE 6.0')!= -1 ){
		        $$('select.main').each(function(el){el.style.visibility='hidden'});
		        $$('#SpecialtySelector select').each(function(el){el.style.visibility='visible'});
		        var selects = $$('#ProfessionSelector select', '#DegreeSelector select' );
		         selects.each(function(el){el.style.visibility="hidden"});
		    }		    
		   
		    //Creates and sets specialty select box
		    var slcProf = $E('#ProfessionSelector select');
		    createSelectBox(slcProf[slcProf.selectedIndex].value, 'specialty', $('divSpecialty'),type ); 
		    
		    $E('#SpecialtySelector').style.visibility='visible';
		    $E('#SpecialtySelector').style.display='block';
        },
		
		/* 
		    Function: cancel_behavior
		    Initiates site-wide cancel behavior and closes specialty selector without adding specialty.
		*/
		
		
		cancel_behavior: function(){
		    if(cancelBehavior() == true){
		    this.close_box();
		    }
		},
		
		
		/* 
		    Function: close_box
		
		*/
		
		close_box: function() {
		    //Hides error message set
		    $E('#SpecError ul').style.display='none';
		    $('SpecError').style.display='none';
		    $E('#SpecialtySelector').style.visibility='hidden';
		    $('specAdd').style.display = 'block';
		    $E('#specEdit').removeEvents('click');
		    
		    //Checks page type (Create/Manage)
		    //If page is Create, 'primary' specialty is always checked (and hidden)
		    if( $('inputMode').value != 'Create' ){$E('#PSpecialty input').checked = false;}
		    $('specEdit').style.display = 'none';
		    
		    $$('#BoardCertified input').each(function(el){el.checked=false});
		    
		    //IE 6 only code.  Re-displays all select boxes...
		    if(navigator.appName == 'Microsoft Internet Explorer' && navigator.appVersion.indexOf('MSIE 6.0')!= -1 ){
		    $$('select.main').each(function(el){el.style.visibility='visible'});
		    selects = $$('#ProfessionSelector select', '#DegreeSelector select' );		    
		         selects.each(function(el){el.style.visibility="visible"});		    
		    }
		    //Resets subspecialty area
		    this.empty_div($('divSubSpecialty'));
		    //Sets specialty select to zero, hides board cert. area and all 'other' text boxes.
		    $('slcProfession').selectedIndex = 0;
		    $('BoardCertified').style.display = 'none';
		    $$('#SpecialtySelector .other').each(function(el){		    
		        el.style.display = 'none'; 
		        var thisOther = '#'+ el.id + ' input';
                $E(thisOther).value = '';
		        });
		    
		    //Hide Specialty Selector
		    $E('#SpecialtySelector').style.display='none';
		    
		    //Hide the drape with opacity transition.
		    var drape = $('drape');
		    var drapefx = new Fx.Style('drape', 'opacity', {
		        duration: 500, 
		        transition: Fx.Transitions.quartIn
		    }).start(.5,0);
		    drape.style.width = '0px';
		    drape.style.height = '0px';
		    
		},
		
		/* 
		    Function: empty_div
		    Clears out child contents of a div.
		    
		    Parameters: 
		    div - object to empty out.
		*/
		
		empty_div: function(div) {		    
		    if(div.childNodes.length > 0){
		        while(div.firstChild){
		            div.removeChild(div.firstChild);
		        }
		    }		
		}
});

/* 

Function: changeInputValue 
Changes the specified hidden input field's hash values.

Parametes: 
input - input field to modify
slot - zero based number representing index of hash to modify
value - new value to enter in input's slot index.

*/
function changeInputValue(input, slot, value){
    var elem_values = $E(input).value.toString().split(':');
    elem_values[slot] = value;
    //Recreate the hidden element hash... 
    $E(input).value = elem_values.join(':');
}

/* 

Function: checkInputValue
Inspects specified hidden input field, returning slot index's value.

Parameters: 
input - input field to check value of
slot - zero based number representing index of hash to check

Returns: 
elem_values[slot] - specified value from hash
*/

function checkInputValue(input, slot){
    var elem_values = input.value.toString().split(':');
    return elem_values[slot];
}

function checkInputValue2(input, slot) {
    var elem_values = input.value.toString().split('|');
    return elem_values[slot];
}

/* 

Function: remove_primary
Removes primary designation from specified table. (For Specialties)

Parameters: 
table - DOM object.  Table to modify

*/
function remove_primary(table){
    var rows= $$('#' + table.id + ' tbody tr');
    rows.each(function(el){
        el.childNodes[1].innerHTML = '';
        var inpVal = '#'+ el.id + ' #Specialty';
        changeInputValue(inpVal, 4, 'false');
    })
}

/* 

Function: remove_primaryLic
Removes primary designation from specified table. (License)

Parameters: 
table - DOM object.  Table to modify

*/
function remove_primaryLic(table){
    var rows= $$('#' + table.id + ' tbody tr');
    rows.each(function(el){
        el.childNodes[4].innerHTML = '';
        var inpVal = '#'+ el.id + ' #License';
        changeInputValue(inpVal, 4, 'N');
        
    })
}


/*
Class: ppwtaAdder
javascript class object that handles the addition of PPWTA to the account management page.
*/
var ppwtaAdder = Fx.Base.extend({
    getExtended: function() {
        return {};
    },

    initialize: function(table, adder, options) {
        this.table = $$(table);
        this.adder = $$(adder);
        this.rows = this.table.rows;
        this.rowNum = this.table[0].tBodies[0].rows.length;

        $('ppwtaEdit').style.display = 'none';
        $E('#ppwtaAdd').addEvent('click', this.add.bind(this));
        $E('#ppwtaClose').addEvent('click', this.cancel_behavior.bind(this));
        this.adder.addEvent('click', this.open_box.bind());

        this.edits = $$('#featPPWTA tbody tr .editCell');
        this.removes = $$('#featPPWTA tbody tr .removeCell');

        this.edits.each(function(el, i) {
            var editEl = create_edit('ppwtaSel ', i);
            el.appendChild(editEl);
        })
        this.removes.each(function(el, i) {
            var editEl = create_remove('ppwtaSel ', i);
            el.appendChild(editEl);
        })
    },
    cancel_behavior: function() {
        if (cancelBehavior() == true) {
            this.close_box();
        }
    },
    add: function(rowAdd) {
        $E('#ppwtaEdit').removeEvents('click');
        if (validate_spec('ppwtaSel', rowAdd) == true) {
            var el = 'this';

            if (typeof rowAdd != 'number') {
                //This is checking for whether this is a clean "add" or an "edit row"
                $('ppwtaEdit').style.display = 'none';
                $('ppwtaAdd').style.display = 'block';
                el = '';
                rowAdd = this.rowNum;
            }
            else {
                $('ppwtaEdit').style.display = 'block';
                $('ppwtaAdd').style.display = 'none';
            }

            var content = new Array();
            var p = $E('#ppwtaTA select');
            var q = $E('#ppwtaPPW select');

            content[0] = document.createTextNode(p[p.selectedIndex].text);
            content[1] = document.createTextNode(q[q.selectedIndex].text);
            content[2] = create_edit('ppwtaSel', rowAdd);
            content[3] = create_remove('ppwtaSel', rowAdd);

            var row = document.createElement('tr');
            row.className = (this.rowNum % 2 == 0) ? 'odd' : 'even';
            for (i = 0; i < content.length; i++) {
                var td = document.createElement('td');
                td.className = '';
                td.className = (i == 2) ? 'editCell' : td.className;
                td.className = (i == 3) ? 'removeCell' : td.className;
                td.appendChild(content[i]);
                row.appendChild(td);
            }

            var hiddenVal = q.value + "|" + p.value;
            row.appendChild(createHidden(hiddenVal, 'PPWTA'));
            row.id = 'ppwtaRow_' + rowAdd;

            if (el == '') {
                row.id = 'ppwtaRow_' + this.rowNum;
                this.table[0].tBodies[0].appendChild(row);
                ppwtaSel.close_box();
                this.rowNum++;
            }
            else {
                row.id = 'ppwtaRow_' + rowAdd;
                var repTR = "#featPPWTA #ppwtaRow_" + rowAdd;
                $E('#featPPWTA').tBodies[0].replaceChild(row, $E(repTR));
                ppwtaSel.close_box();
            }
        }

        self.changed = true;
    },
    edit_row: function(rowNum) {
        var elem = $E('#ppwtaRow_' + rowNum + ' input#PPWTA');
        $('ppwtaAdd').style.display = 'none';
        $('ppwtaEdit').style.display = 'block';
        var elem_values = elem.value.toString().split('|');
        this.open_box(elem_values[0], elem_values[1]);
        $E('#ppwtaTA select').options[select_value($E('#ppwtaTA select').id, elem_values[1])].selected = true;
        $E('#ppwtaPPW select').options[select_value($E('#ppwtaPPW select').id, elem_values[0])].selected = true;
        $E('#ppwtaEdit').addEvent('click', this.add.bind(this, rowNum));
        self.changed = true;
    },
    delete_row: function(rowNum) {
        if (confirm('Are you sure you want to delete this item?')) {
            var remover = $E('#ppwtaRow_' + rowNum);
            this.table[0].tBodies[0].removeChild(remover);
            self.changed = true;
        }
    },
    open_box: function(val1, val2) {
        if (typeof val1 != 'string' || typeof val2 != 'string') {
            val1 = '';
            val2 = '';
        }

        reset_ppwta_errors();

        //IE6 Only code... 
        if (navigator.appName == 'Microsoft Internet Explorer' && navigator.appVersion.indexOf('MSIE 6.0') != -1) {
            $$('select.main').each(function(el) { el.style.visibility = 'hidden' });
            selects = $$('#ProfessionSelector select', '#DegreeSelector select');
            selects.each(function(el) { el.style.visibility = "hidden" });
        }

        $E('#specPPWTA').style.visibility = 'visible';

        var slcTA = $E('#ppwtaTA select');
        if (val2 != '') {
            slcTA.options[select_value(slcTA.id, val2)].selected = true;
        }
        else {
            slcTA.options[select_value(slcTA.id, '0')].selected = true;
        }

        var slcPPW = $E('#ppwtaPPW select');
        if (val1 != '') {
            slcPPW.options[select_value(slcPPW.id, val1)].selected = true;
        }
        else {
            slcPPW.options[select_value(slcPPW.id, '0')].selected = true;
        }

        var drape = $('drape');
        drape.style.width = window.getScrollWidth() + 'px';
        drape.style.height = window.getScrollHeight() + 'px';
        var drapefx = new Fx.Style('drape', 'opacity', {
            duration: 500,
            transition: Fx.Transitions.quartIn
        }).start(0, .5);
    },
    close_box: function() {
        $E('#specPPWTA').style.visibility = 'hidden';
        $('ppwtaAdd').style.display = 'block';
        $('ppwtaEdit').style.display = 'none';
        reset_ppwta_errors();

        var drapefx = new Fx.Style('drape', 'opacity', {
            duration: 800,
            transition: Fx.Transitions.quartIn
        }).start(.5, 0);
        var drape = $('drape');
        drape.style.width = '0px';
        drape.style.height = '0px';


        // IE 6.0 only code
        if (navigator.appName == 'Microsoft Internet Explorer' && navigator.appVersion.indexOf('MSIE 6.0') != -1) {
            $$('select.main').each(function(el) { el.style.visibility = 'visible' });
            selects = $$('#ProfessionSelector select', '#DegreeSelector select');
            selects.each(function(el) { if (el.parentNode.style.visibility == 'visible') { el.style.visibility = "visible" } });
        }
    },
    empty_div: function(div) {
        if (div.childNodes.length > 0) {
            while (div.firstChild) {
                div.removeChild(div.firstChild);
            }
        }
    }
});

function reset_ppwta_errors() {
    $('ppwtaError').style.display = 'none';
    $$('#ppwtaError li').each(function(el) { el.style.display = 'none'; })
    $E('#ppwtaError ul').style.display = 'none';
}

/* 

Class: licenseAdder
javascript class object that handles the addition of licenses to the account management page.

*/

var licenseAdder = Fx.Base.extend({
    getExtended: function() {
        return {};
    },

    /* 
		
		Constructor: initialize
    initializes the specialtySelector
		
		Arguments: 
    table - The HTML table where Licenses will be added
    adder - HTML link which will initiate the adding of a license
		    
    Examples: 
    > var specSel = new specialtySelector($$('table#featAct'), $('addSpecialty'));
		
		See Also: 
    <LicenseAdder>
		
		*/


    initialize: function(table, adder, options) {
        this.table = $$(table);
        this.adder = $$(adder);
        this.rows = this.table.rows;
        this.rowNum = this.table[0].tBodies[0].rows.length;
        this.check_rowLength();

        $('LicEdit').style.display = 'none';
        $E('#LicAdd').addEvent('click', this.add.bind(this));
        $E('#LicClose').addEvent('click', this.cancel_behavior.bind(this));
        this.adder.addEvent('click', this.open_box.bind());

        this.edits = $$('#featLicense tbody tr .editCell');
        this.removes = $$('#featLicense tbody tr .removeCell');

        this.edits.each(function(el, i) {
            var editEl = create_edit('licSel ', i);
            el.appendChild(editEl);
        })
        this.removes.each(function(el, i) {
            var editEl = create_remove('licSel ', i);
            el.appendChild(editEl);
        })
    },

    /* 
		
		Function: cancel_behavior
    Checks for modal response and closes the divPopup on a positive response
		
		*/

    cancel_behavior: function() {
        if (cancelBehavior() == true) {
            this.close_box();
        }
    },


    /* 
		
		Function: add
    Adds license to the license table.  Also is called on edit... 
		
		*/

    add: function(rowAdd) {
        //Remove the 'click' behavior from the second add button... (This will get readded at the end of this function.)
        $E('#LicEdit').removeEvents('click');
        if (validate_spec('licenseSel', rowAdd) == true) {
            var el = 'this';

            if (typeof rowAdd != 'number') {
                //This is checking for whether this is a clean "add" or an "edit row"
                $('LicEdit').style.display = 'none';
                $('LicAdd').style.display = 'block';
                el = '';
                rowAdd = this.rowNum;
            }
            else {
                $('LicEdit').style.display = 'block';
                $('LicAdd').style.display = 'none';
            }

            //Is this a Primary license?  If so, we have to change the previous primary license... 
            var varPrim = ($E('#primLicense input').checked) ? 'Primary' : '';
            if (varPrim == 'Primary') { remove_primaryLic($('featLicense')) };


            //arrays for values to enter into table
            var content = new Array();
            var p = $E('#licState select');
            var q = $E('#dpLicStartDate input');
            var r = $E('#dpLicEndDate input');
            var s = $E('#licNumber input')


            content[0] = document.createTextNode(p[p.selectedIndex].text);
            content[1] = document.createTextNode(q.value); //r[r.selectedIndex].text;
            content[2] = document.createTextNode(r.value);
            content[3] = document.createTextNode(s.value);
            content[4] = document.createTextNode(varPrim);
            content[5] = create_edit('licSel', rowAdd);
            content[6] = create_remove('licSel', rowAdd);

            //Creating table row... Setting class, values and edit/remove buttons, and the hidden input hash
            var row = document.createElement('tr');
            row.className = (this.rowNum % 2 != 0) ? 'even' : '';
            for (i = 0; i < content.length; i++) {

                var td = document.createElement('td');
                td.className = '';
                td.className = (i == 5) ? 'editCell' : td.className;
                td.className = (i == 6) ? 'removeCell' : td.className;
                td.appendChild(content[i]);
                row.appendChild(td);
            }

            varPrim = (varPrim == 'Primary') ? 'Y' : 'N';
            var hiddenVal = p[p.selectedIndex].value + ':' + q.value + ':' + r.value + ':' + s.value + ':' + varPrim;
            row.appendChild(createHidden(hiddenVal, 'License'));
            row.id = 'licRow_' + rowAdd;

            if (el == '') {
                row.id = 'licRow_' + this.rowNum;
                this.table[0].tBodies[0].appendChild(row);
                licSel.close_box();
                this.rowNum++;
            }
            else {
                row.id = 'licRow_' + rowAdd;
                var repTR = "#featLicense #licRow_" + rowAdd;
                $E('#featLicense').tBodies[0].replaceChild(row, $E(repTR));
                licSel.close_box();
            }
        }

        self.changed = true;
    },

    /* 
		
		Function: edit_row
    Captures values in license adder form and preps data for add function
		
		Parameters: 
    rowNum - Int.  Represents value of number associated in class of table row... 
		
		*/

    edit_row: function(rowNum) {
        var elem = $E('#licRow_' + rowNum + ' input#License');
        $('LicAdd').style.display = 'none';
        $('LicEdit').style.display = 'block';
        var elem_values = elem.value.toString().split(':');
        this.open_box(elem_values[1], elem_values[2]);
        $E('#licState select').options[select_value('licState select', elem_values[0])].selected = true;
        $E('#licNumber input').value = elem_values[3];
        $E('#primLicense input').checked = (elem_values[4] == 'Y') ? true : false;
        $E('#LicEdit').addEvent('click', this.add.bind(this, rowNum));
        self.changed = true;
    },

    /* 
		
		Function: delete_row
    Removes a row from the license table
		
		Parameters: 
    rowNum - Int.  Represents value of number associated in class of table row... 
		
		*/
    delete_row: function(rowNum) {
        if (confirm('Are you sure you want to delete this license?')) {
            var remover = $E('#licRow_' + rowNum);
            this.table[0].tBodies[0].removeChild(remover);
            this.table[0].tFoot.style.visibility = (this.table[0].tBodies[0].rows.length < 3) ? 'visible' : 'hidden';
            this.check_rowLength();
            self.changed = true;
        }
    },

    /* 
		
		Function: check_rowLength
    Hides table foot (with button to add license) if the length exceeds preset number
		
		*/

    check_rowLength: function() {
        this.table[0].tFoot.style.visibility = (this.table[0].tBodies[0].rows.length < 3) ? 'visible' : 'hidden';
    },


    /* 
		
		Function: open_box
		
		Parameters: 
    val1 - String. Nullable.  Represents the Start Date (if any...) of pre-existing licenses to be fed into datepicker
    val2 - String. Nullable.  Represents the End Date (if any...) of pre-existing licenses to be fed into datepicker
		
		*/

    open_box: function(val1, val2) {
        if (typeof val1 != 'string' || typeof val2 != 'string') {
            val1 = '';
            val2 = '';
        }

        //IE6 Only code... 
        if (navigator.appName == 'Microsoft Internet Explorer' && navigator.appVersion.indexOf('MSIE 6.0') != -1) {
            $$('select.main').each(function(el) { el.style.visibility = 'hidden' });
            selects = $$('#ProfessionSelector select', '#DegreeSelector select');
            selects.each(function(el) { el.style.visibility = "hidden" });
        }

        $E('#specLicense').style.visibility = 'visible';
        $E('#licStartDate input').value = val1;
        $E('#licEndDate input').value = val2;
        
        var drape = $('drape');
        drape.style.width = window.getScrollWidth() + 'px';
        drape.style.height = window.getScrollHeight() + 'px';
        var drapefx = new Fx.Style('drape', 'opacity', {
            duration: 500,
            transition: Fx.Transitions.quartIn
        }).start(0, .5);
    },

    close_box: function() {
        $E('#specLicense').style.visibility = 'hidden';
        $('LicAdd').style.display = 'block';
        $('LicEdit').style.display = 'none';
        $E('#primLicense input').checked = false;
        this.reset_errors();
        $E('#licNumber input').value = '';
        license_length_check();

        var drapefx = new Fx.Style('drape', 'opacity', {
            duration: 800,
            transition: Fx.Transitions.quartIn
        }).start(.5, 0);
        var drape = $('drape');
        drape.style.width = '0px';
        drape.style.height = '0px';


        // IE 6.0 only code
        if (navigator.appName == 'Microsoft Internet Explorer' && navigator.appVersion.indexOf('MSIE 6.0') != -1) {
            $$('select.main').each(function(el) { el.style.visibility = 'visible' });
            selects = $$('#ProfessionSelector select', '#DegreeSelector select');
            selects.each(function(el) { if (el.parentNode.style.visibility == 'visible') { el.style.visibility = "visible" } });
        }

    },

    empty_div: function(div) {
        if (div.childNodes.length > 0) {
            while (div.firstChild) {
                div.removeChild(div.firstChild);
            }
        }
    },

    reset_errors: function() {
        $('LicError').style.display = 'none';
        $$('#LicError li').each(function(el) { el.style.display = 'none'; })
        $E('#LicError ul').style.display = 'none';

    }
});

/* 

Function: license_length_check
If license table is >= 3 rows, hide the 'add license' button.


*/

function license_length_check(){    
    if($$('#featLicense tbody tr').length >= 3){
        $E('#featLicense tfoot').style.visibility = 'hidden';
    }
    else {
        $E('#featLicense tfoot').style.visibility = 'visible';
    }
}

/* 

Function: reset_errors
Sets display of Specialty Errors to 'none'

*/

 function reset_errors(){
   var elems = $$('#SpecError li');
   elems.each(function(elem){elem.style.display='none';})
   $E('#SpecError ul').style.display = 'none';
 }

/* 

Function empty_div
Empties the passed div element of any child nodes

Parameters: 
div - DOM element to empty 

*/
function empty_div(div) {		    
    if(div.childNodes.length > 0){
        while(div.firstChild){
            div.removeChild(div.firstChild);
        }
    }
}

/* 

Function: create_remove
Function to build "Delete" buttons for Specialty Selector and License Adder

Parameters: 
type - String. 
rowNum - Int. Zero-based number associated with the row that button will go in.

Returns: 
removeLink - DOM Element. Input type button.

*/
function create_remove(type, rowNum) {
    var removeLink = document.createElement('input');
    removeLink.type = 'button';
    removeLink.className = 'btnDelete';
    removeLink.title = 'Delete'
    removeLink.onclick = function(){eval(type+'.delete_row('+ rowNum +')'); return false;};
	return removeLink;
}

/* 

Function: create_edit
Function to build "Edit" buttons for Specialty Selector and License Adder

Parameters: 
type - String. 
rowNum - Int. Zero-based number associated with the row that button will go in.

Returns: 
removeLink - DOM Element. Input type button.

*/

function create_edit(type, rowNum) {
    var editLink = document.createElement('input');
    editLink.type = 'button';
    editLink.className = 'btnEdit';
    editLink.onclick = function(){eval(type+'.edit_row('+ rowNum +')'); return false;};
	editLink.title = 'Edit'		    
    return editLink;
}

/* 

Function: select_value
Takes the id of an element and searches for a value within its options.

Parameters: 
id - String. ID of element to search.
value - String.  Value to match.

*/
 
function select_value(id, value){
    var sel = $E('#'+id);
    if(sel.options.length > 0){    
        for(i=0; i< sel.options.length; i++){
            if(sel.options[i].value == value){
                return i;
            }            
        }
        
    }
}


/* 

Function check_profession
Takes in the profession select box and performs tasks based on the values within that select box.  Checks for 3 cases 1.) Pharmacist (Profession code PF-PT), 2.) Psychiatrist and 3.) all others.   This function sets the visibility of all form elements that are associated with each profession/specialty combo.

Parameters: 
elem - DOM element.  This is Select box to manage.


*/

function check_profession(elem){

    //If profession is Pharmacist...
    if(elem[elem.selectedIndex].value == 'PF-PT'){
        //Hide specialty table
        $E('#displaySpecialtyRow').style.display = 'none';  
        //Show pharmacist fields
        $$('.pharm').each(function(el){el.style.display = 'block';})
        //
        $$('#RegisterSelector input').each(function(el){
            if(self['changed'] == true )
             {el.checked = (el.value == 'RP-Y')?true:false;}
                else if($('inputMode').value == 'Create' && el.value == 'RP-Y'){
                    //el.checked = 'true';                                
                }
            }
            );
        
        $$('.general', '.psych').each(function(el){el.style.display = 'none';})
        empty_div($E('#featAct tbody'));
        check_for_other($E('#DegreeSelectorEle select'), $('DegreeOther'));
        
        /*This block is for Manage Account... We're toggling between the two states for submit buttons... */
        try{$('Pharma').style.display='block';}catch(err){};
        try{$('MainAccountInfo').style.display='none';}catch(err){};
        
    
    }
    else if((elem[elem.selectedIndex].value != 'PF-PT') && getPrimarySpecialty()== '39'){
         
         $$('.general', '.psych').each(function(el){el.style.display = 'block';})  
         $$('.pharm','.noPsych').each(function(el){el.style.display = 'none';})
        
        
    }
    else if(elem[elem.selectedIndex].value == '0'){
        $E('#displaySpecialtyRow').style.display = 'none';
        $$('.pharm', '.psych').each(function(el){el.style.display = 'none';})
        $$('.general').each(function(el){el.style.display = 'block';})  
        $$('#RegisterSelector input').each(function(el){el.checked = false});
        
        try{$('Pharma').style.display='none';}catch(err){}
        try{$('MainAccountInfo').style.display='block';}catch(err){}
        
        check_for_other($E('#DegreeSelectorEle select'), $('DegreeOther'));
    }
    else{
        $E('#displaySpecialtyRow').style.display = 'block';
        if(elem[elem.selectedIndex].value == 'PF-NS' || elem[elem.selectedIndex].value == 'PF-AN'){
                $$('#licState select option').each(function(el){
                    if(el.value == $E('#licState input').value){
                        el.selected = true;
                    }                
                });
         $$('#RegisterSelector input').each(function(el){el.checked = false});
        }
        
        $E('#displaySpecialtyRow').style.display = 'block';
        $$('.pharm', '.psych').each(function(el){el.style.display = 'none';})
        $$('.general').each(function(el){el.style.display = 'block';})
        
        
        try{$('Pharma').style.display='none';}
        catch(err){}
        try{$('MainAccountInfo').style.display='block'; }catch(err){}
        
        
        check_for_other($E('#DegreeSelectorEle select'), $('DegreeOther'));
    }
}

/* 

Function: getPrimarySpecialty
Searches specialty table and returns the hash value associated with a 'primary' designation.

Returns: 
sp - Int. Numerical value of primary specialty

*/

function getPrimarySpecialty(){
    var sp;
    $$('#featAct tbody tr input').each(function(el){
        if(el.value != ''){
        var arr = el.value.split(':');
        
        if(arr[4]=='true'){sp=arr[0]}
        }
    })
    
    sp=(sp==undefined)?false:sp;
    
    return sp;
}

/* 

Function: check_psych
Takes the passed Select Box and checks its selected value for 'Psychiatry'.  Shows/Hides various divs which have the class 'psych' or 'noPsych' depending on the value.

Parameters: 
elem - DOM element.  Profession Select Box

*/

function check_psych(elem){
    if(elem[elem.selectedIndex].text == 'Psychiatry'){
        try{
        $$('.psych').each(function(el){el.style.display='block'})
        $$('.noPsych').each(function(el){el.style.display='none'})       
        }
        catch(err){}
    }
    else{
        try{
        $$('.psych').each(function(el){el.style.display='none'})
        $$('.noPsych').each(function(el){el.style.display='block'})
        }
        catch(err){}
    }
}

/* 

Function: validate_spec
Main validation function for Specialty Selector and License Adder.  

Parameters: 
type - String.  Either 'specSel' or 'licenseSel' representing which module it's validating

rowAdd - Int. Represents the row that's being added to table.

*/

function validate_spec(type, rowAdd){
    
    var count = 0;
    switch(type)
    { 
    case "specSel":
      reset_errors();
      var     f = new Array;
             f[0] = $('slcProfession');
             f[1] = $E('#PrimarySpecialtyOther input')  
             f[2] = $$('#BoardCertified input');
             f[3] = $('slcSubSpecialty');
             f[4] = $E('#SubSpecialtyOther input');
        var el = $$('#SpecError li');
        
        if(f[0].selectedIndex< 1){el[0].style.display='block'; count++;}
        
        /*Check for existence of existing road, but first make sure we're not in 
        Edit Mode, editing a row that user keeps with the same Specialty... */
        
        var specBody;
        var specLength = $$('#featAct tbody input#Specialty');
        
        var curValue;
        if(typeof rowAdd != 'number'){ 
            rowAdd = specLength.length + 1;             
            curValue = '';
        }
        else {
            var specBody = $E('#specRow_'+rowAdd + ' #Specialty');        
            curValue = specBody.value;
            curValue = (curValue.split(':'))[0];
        }
        if((f[0].value != curValue) && specLength.length > 0 ){
            specLength.each(function(il){
             var chk = f[0];
             if(checkInputValue(il, 0) ==  chk.value && chk[chk.selectedIndex].text != 'Other' ) {
                 el[5].style.display='block';
                 count++;
             }   
        }); 
        }
        
        if($('PrimarySpecialtyOther').style.display == 'block'){
            if(f[1].value == ''){el[1].style.display='block'; count++;}
        }
        
        if($('SubSpecialtyOther').style.display == 'block'){
            if(f[4].value == ''){el[4].style.display='block'; count++;}
        }
        
        if($('BoardCertified').style.display == 'block'){
            if(check_radio(f[2])== ''){el[2].style.display='block';count++;}
        }
        if(count > 0){
            $E('#SpecError ul').style.display = 'block';
            $('SpecError').style.display = 'block';
            return false;
        }  
        else{
            $E('#SpecError ul').style.display = 'none';
            return true;
        }
        break;

    case "ppwtaSel":
        {
            var f = new Array;
            f[0] = $E('#ppwtaTA select');
            f[1] = $E('#ppwtaPPW select');

            var el = $$('#ppwtaError li');

            if (f[0].value == '' || f[0].value == '0') {
                el[0].style.display = 'block';
                count++;
            }
            else {
                el[0].style.display = 'none';
            }

            if (f[1].value == '' || f[1].value == '0') {
                el[1].style.display = 'block';
                count++;
            }
            else {
                el[1].style.display = 'none';
            }
            
            // Checking to make sure we are not adding a TA that already exists.
            var ppwtaBody;
            var ppwtaLength = $$('#featPPWTA tbody input#PPWTA');
            var curValue;
            
            if(typeof rowAdd != 'number'){
                rowAdd = ppwtaLength + 1;
                curValue = '';
            }
            else {            
                ppwtaBody = $E('#ppwtaRow_' + rowAdd + ' #PPWTA');
                curValue = ppwtaBody.value;
                curValue = (curValue.split('|'))[0];
            }

            if ((f[0].value != curValue) && ppwtaLength.length > 0) {
                ppwtaLength.each(function(il) {
                    var chk = f[0];
                    if (checkInputValue2(il, 1) == chk[chk.selectedIndex].value) {
                        el[2].style.display = 'block';
                        count++;
                    }
                });
            }
            // End of duplicate test

            if (count > 0) {
                $E('#ppwtaError ul').style.display = 'block';
                $('ppwtaError').style.display = 'block';
                return false;
            }
            else {
                $E('#ppwtaError ul').style.display = 'none';
                $('ppwtaError').style.display = 'none';
                return true;
            }
        }
    
    
    case "licenseSel":
    { var f = new Array;
             f[0] = $E('#licState select');
             f[1] = $E('#licStartDate input')  
             f[2] = $E('#licEndDate input');
             f[3] = $E('#licNumber input');
             f[4] = $E('#primLicense input');
        var el = $$('#LicError li');
        
        if(f[1].value == ''){
            el[1].style.display='block'; count++;
        }
        if(f[2].value == ''){
            el[2].style.display='block'; count++;
        }
        var profession = $E('#ProfessionSelector select');
        
        if($chk(profession) == false){
            var profNurse = 'Nurse';
        }
        else{
            var profNurse = profession[profession.selectedIndex].text;
        }
        
        if(f[3].value == '' && profNurse.indexOf('Nurse') != -1){
            el[3].style.display='block'; count++;
        }
        if(new Date(f[2].value) - new Date(f[1].value) < 0 ){       
               el[4].style.display='block';count++;
        }
        if(count > 0){
            $E('#LicError ul').style.display = 'block';
            $('LicError').style.display = 'block';
            return false;
        }  
        else{
            $E('#LicError ul').style.display = 'none';
            return true;
        }
    
    break;
    }
    }
}

function check_radio(radios){
    var value = "";
    radios.each(function(el){if(el.checked == true){value = el.value;}})
    return value;
}

function find_selected(value, select){
    for(i=0;i<select.options.length ;i++){
        if (select.options[i].value == value){
            return i;    
        }
    }
}



function check_for_other(select, otherDiv){
       try{
       var option = '';
       var optionset = select.options;
       for(i=0;i<optionset.length; i++){ 
           if(optionset[i].selected == true){
                if(optionset[i].text == 'Other'){
        
                    option +='Other';                   
                }
           }     
        }
        
        if(option == 'Other'){
                otherDiv.style.display = 'block';
            }
        else{
                otherDiv.style.display = 'none';
                $E('#' + otherDiv.id + ' input').value = '';
            }       
       }
       catch(err){
       otherDiv.style.display = 'none';
       }
    
}

function check_multiple(multSelect, type){
		    var value = "";
		    if (multSelect != false && multSelect != null){
		        var mOptions = multSelect.options;
		        for(i=0; i< mOptions.length ; i++) {
		            if( mOptions[i].selected == true) {
		              switch (type){
		                case "text":
		                    if(i != 0){
		                    value +=  (mOptions[i].text + ', ');		                    
		                    }		                   
		                break;
    		            
		                case "value":
		                    value +=  (mOptions[i].value + ',');
		                break;
		              }
		            }
		       
		        }
		    
		    value = (value == '')?'':value.substr(0,value.lastIndexOf(','));
		    }
		    else if((multSelect == false || multSelect == null) && type == 'text'){
		        value = 'N/A';
		    }
		    else if (multSelect && type == 'text'){		        
		        value = 'none';
		    }
		    else if ((multSelect == false || multSelect == null) && type == 'value'){
		        value = '';
		    }		    
		    return value;
		}
 

       function createSelectBox(inId, inTarget, updater, completer){
            clearSelect(updater);
            var qs = Object.toQueryString({id:inId,target:inTarget});
            
            if (completer != "") {
                new Ajax('SpecialtySelectorSupport.aspx', {method: 'get', postBody: qs, update:updater, onComplete:completer}).request();
            }
            else {
                new Ajax('SpecialtySelectorSupport.aspx', {method: 'get', postBody: qs, update:updater}).request();
            }
        }
                
    function controlSelect(elem, step, insertDiv, completer, other) {
            createBoard(elem[elem.selectedIndex].value);
            createSelectBox(elem[elem.selectedIndex].value, step, insertDiv, completer);           
            checkOther(elem[elem.selectedIndex].text, $$('.other')[other]);                        
    }

    function checkSubSpec(elem){
        if($('divSubSpecialty').childNodes.length > 0){
             $('SubSpecialty').style.display = 'block';
        }
        else{
            $('SubSpecialty').style.display = 'none';
        }
    }

    function createBoard(inId){
        var qs = Object.toQueryString({id:inId,target:'board'});
        new Ajax('SpecialtySelectorSupport.aspx', {method: 'get', postBody: qs, onComplete:checkBoardCert}).request();
    }

    function checkOther(value,el){
        if (value == 'Other') {
            el.style.display = 'block';
        }
        else {
            el.style.display = 'none';
            var thisOther = '#'+ el.id + ' input';
            $E(thisOther).value = '';
        }
    }

    function checkBoardCert(value){
        if (value == 'True'){
            $('BoardCertified').style.display = 'block';
            $$('#BoardCertified input').each(function(el,i){el.checked=false; });
        }
        else{
            $('BoardCertified').style.display = 'none';
        }
    }

    function clearSelect(elem){
        if (elem.childNodes.length > 1) {
               while(elem.firstChild){
                elem.removeChild(elem.firstChild);
               }
        }
    }
    function createHidden(hiddenVal, type){
    var hiddenField = document.createElement('input');
        hiddenField.type = 'hidden';
        hiddenField.value = hiddenVal;
        hiddenField.id = type;
        hiddenField.name = type;

    return hiddenField;
    }
    
    function clearDemoQuestions(){
        $$('#divDemoQuestions select').each(function(el){
            el.selectedIndex = 0;
        })
        $$('#divDemoQuestions .wOther input').each(function(el){el.value='';});
        $$('#divDemoQuestions div.other').each(function(el){el.style.display='none'});
    }
                
                
    function control_profession(elem){
            
        if($$('#featAct tbody tr').length > 0){  
        if(confirm('Changing your profession will remove any previously selected Specialties.  \n Are you sure you want to change your profession?'))
        {
        createSelectBox(elem[elem.selectedIndex].value,'degree',$('DegreeSelectorEle'),''); 
        empty_div($E('#featAct tbody')); 
        $E('#DegreeOther input').value = '';
        $$('#RegisterSelector input').each(function(el){el.checked = false});
        clearDemoQuestions();
        check_profession(elem); 
        $('DegreeOther').style.display = 'none';
        $E('#ProfessionSelector input').value = $E('#ProfessionSelector select')[$E('#ProfessionSelector select').selectedIndex].value;
        }
        else{
            $E('#ProfessionSelector select').selectedIndex = find_selected($E('#ProfessionSelector input').value, $E('#ProfessionSelector select'));
            return false;
        }
       }
       else{
        
        createSelectBox(elem[elem.selectedIndex].value,'degree',$('DegreeSelectorEle'),''); 
        empty_div($E('#featAct tbody')); 
        $E('#DegreeOther input').value = '';
        clearDemoQuestions();        
        $E('#ProfessionSelector input').value = $E('#ProfessionSelector select')[$E('#ProfessionSelector select').selectedIndex].value;
        check_profession(elem); 
        $('DegreeOther').style.display = 'none';
       }
        
      self['specSel'].check_add();
       
    }
