/*
ClinicalTrial Doctors additional JS functions

*/

function findQuestionnaire() {
    // The register page on the clinical trial doctors site is set up using a
    // questionnaire
    // first check if we're on the questionnaire page
    if (document.getElementById('questionnaire_once_only')) {
        setupQuestionnaireEventHandlers();
    }
}

var toCall=[];   
toCall[0]=findQuestionnaire;   

   
var specs = [];
var states;
var otherFields = [];

/*  following function called as part of the page onload.
    initialise things for event handlers, and 'other' fields. */
function setupQuestionnaireEventHandlers() {
    setupSpecsArray();
    
    setupStatesArray();
      
    addOtherControls();
    //calls handleSelect. which calls
    	//checkSpeciality and
    	//checkForOther which calls
    		//displayOther
    addEventHandlers(); 
}

/*  The specs array contains a list of all the specialities displayed in the 
    dropdown list along with any sub specialities associated with each one.
    The subspecialities are used when displaying the checkboxes to let the 
    user select their interests. */
function setupSpecsArray() {
    specs['Allergy/Immunology'] = [];
    specs['Anaesthesiology'] = ["General","Intensive care","Office based","Pain Management","Other, Specify"];
    specs['Cardiology/ Cardiovascular'] = ["Angina","Atrial Fibrillation (AFIB)","Coronary Heart Disease (CAD)","Deep Vein Thrombosis/ Pulmonary Embolism","Electrophysiology/arrhythmias","Invasive cardiology","Acute Care Cardiology","Hypertension","Lipid Disorders/ arteriosclerosis","Myocardial Infarct","Stroke","Other, Specify"];
    specs['Clinical Pharmacology'] = [];
    specs['Clinical Physiology'] = [];
    specs['Dermatology'] = ["Psoriasis","Alopecia","Infections","Scarring","Other, Specify"];
    specs['Emergency Medicine'] = [];
    specs['Endocrinology'] = ["Diabetes","Growth Hormone Deficiency","Obesity","Metabolism","Other, Specify"];
    specs['Epidemiology'] = [];
    specs['Gastroenterology'] = ["Crohn's disease","Colorectal Surgery","Gastroesophageal Reflux Disease (GERD)","Irritable Bowel Syndrome (IBS)","Hepatology","Ulcerative Colitis","Other, Specify"];
    specs['General Practice/Family Practice'] = [];
    specs['Geriatrics'] = [];
    specs['Haematology'] = ["Anaemia","Other, Specify"];
    specs['Hepatology'] = [];
    specs['Infectious diseases'] = ["Bacterial infections especially resistant bacteria (MRSA Gram-negative bacteria)","Viral infections","Tuberculosis"];
    specs['Internal medicine'] = [];
    specs['Nephrology/Renal Medicine'] = ["Hypertension","Renal Disease","Other, Specify"];
    specs['Neurology'] = ["Alzheimer's","Epilepsy","Dementia","Migraine /Headaches","Multiple Sclerosis (MS)","Parkinson's disease","Stroke","Sleep Disorders","Neurophysiology","Other, Specify"];
    specs['Obstetrics/Gynecology'] = ["Birth Control","Endometriosis","Female Sexual Dysfunction (FSD)","Hormone Replacement Therapy (HRT)","Infertility","Obstetrics","Premenstrual Syndrome (PMS)","Other, Specify"];
    specs['Oncology'] = ["Head and neck","Lung cancer","Breast cancer","Colorectal","Gastrointestinal cancer","Genitourinary malignancies","Gynaecologic malignancies","Pancreatic","Skin cancer","Sarcomas","Brain tumours","Haematological malignancies","Radiation therapy","Other, Specify"];
    specs['Ophthalmology'] = ["Glaucoma","Macular Degeneration","Other, Specify"]; 
    specs['Orthapaedics'] = [];
    specs['Oto-rhino-laryngology'] = ["Head and Neck","Ear nose and throat","Other, Specify"]; 
    specs['Paediatrics'] = []; 
    specs['Pathology'] = ["Anatomic","Clinical","Other, Specify"]; 
    specs['Psychiatry'] = ["Addiction","Anxiety","Depression","Bipolar disease","Schizophrenia","Dementia","Forensic","Manic Disorders","Smoking Cessation","Other, Specify"]; 
    specs['Pulmonology/Respiratory Disease'] = ["Asthma/Allergy","COPD","Cystic Fibrosis","Influenza","Lung cancer","Lung infection","Sleep Disorders","Other, Specify"];  
    specs['Radiology'] = ["Diagnostic","Oncologic","Therapeutic","Vascular and Interventional","Other, Specify"];  
    specs['Rheumatology'] = ["Arthritis","Fibromyalgia","Lupus","Osteoarthritis","Osteoporosis","Rheumatoid Arthritis (RA)","Other, Specify"];         
    specs['Surgery'] = ["Abdominal","Cardiac","Cardio-Thoracic","Colorectal","Endocrinology","Gastrointestinal","General","Gynecological","Head and Neck","Neurosurgery","Oncology","Oral and Maxillofacial","Orthopaedic","Podiatry","Pulmonary","Thoracic","Vascular surgery","Urologic","Other, Specify"];
    specs['Urology'] = ["Benign Prostatic Hypertrophy (BPH)","Erectile Dysfunction (ED)","Urinary Tract Infections (UTI)","Other, Specify"];
    specs['Other'] = [];
}

/*  The states array contains a list of all the states to display
	for US country. */
function setupStatesArray() {
    states= ['', 'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'District of Columbia', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'];

}

/*  Add event handlers to select dropdown to handle display of 'other' fields
    Also add event handler to submit form so that we can validate the input
    and copy the value from the 'other' fields to fields in the quesitonnaire. */
function addEventHandlers() {
    // add event handlers as required.
    controls = document.getElementsByTagName("select");
    for (var i = 0; i < controls.length; i++) {
        controls[i].onchange = function () {return handleSelect(this, true);};
        // make sure default values for controls are processed ok.
        handleSelect(controls[i], false);   
    }
    
    var form = document.getElementById("frm_comment");
    if (form) {
        form.onsubmit = function () {return validateInput();};
    } 
}


/*  Add the 'other' fields for the select controls which have the 'Other' option.
    There needs to be a hidden input field with a suffix of _o, so get each one
    of these and add the necessary other fields. */
function addOtherControls() {
    // find all the _o fields and add them to the otherFields array.
    var allFields = document.getElementsByTagName('input');
    if (allFields) {
        otherPattern = new RegExp("(.*)_o$");
        for (var i = 0; i < allFields.length; i++) {
            if (allFields[i].type == 'hidden') {

                var fieldId = allFields[i].id;
                if (otherPattern.test(fieldId)) {
           
                    // get the fieldname without the _o at the end.
                    var matches = fieldId.match(otherPattern);
                    if (matches && matches.length > 1) {
                        otherFields.push(matches[1]);
                    }
                }
            }
        }
    }
    
    // Now add the necessary controls for the other fields.
    for (var i=0; i<otherFields.length; i++) {
        addOtherFor(otherFields[i]);
    }
}


/*  Add new elements to the DOM so that we can handle 'other' fields.
    Basically it finds the hidden field suffixed by _o, then adds a p
    tag and text input field along side the hidden field. This is given
    a default display style on none which is changed to block when the 
    user selects the 'Other, Specify' option associated with this field. */
function addOtherFor(controlName) {
    var control = document.getElementById(controlName + '_o');
    
    if (control) {
        var otherContainer = createControl('p', controlName + '_other_container');
        setAttributeCrossBrowser(otherContainer,'class','row1');
        toggleAttribute(otherContainer,'class','','hidden');
        
        var otherLabel = createControl('label', '', 'Other, please specify:');
        setAttributeCrossBrowser(otherLabel,'for',controlName + '_other');

        var otherControl = createControl('input', controlName + '_other');
        otherControl.setAttribute('type', 'text');
        setAttributeCrossBrowser(otherControl,'class','text');
        
        var otherImage = createControl('img');
        setAttributeCrossBrowser(otherImage,'alt', 'asterisk');
        setAttributeCrossBrowser(otherImage,'class', 'asterisk');
        setAttributeCrossBrowser(otherImage,'src', '/_mshost81109/system/styles/root/images/asterisk.gif');
        otherLabel.appendChild(otherImage);
        
        otherContainer.appendChild(otherLabel);
        otherContainer.appendChild(otherControl);
        
        (control.parentNode).insertBefore(otherContainer, control);
        
        var controlOther = document.getElementById(controlName + '_other');
        
        // set the default value/
        controlOther.value = control.value;
    }
}


/*  Decide what to do when the value of a select box is altered.
    For the speciality fields this checks to see if any sub speciality
    checkboxes should be shown.
    For all select lists it checks to see if the Other, Specify option 
    is selected. 
    For the Experience of Clinical Studies, it hides the Phases of drugs development when 0 
    and shows it otherwise*/
function handleSelect(control, clearInterests) {
	switch(control.id){
		case 'c_spec1':
		case 'c_spec2':
	        checkSpeciality(control, clearInterests);
	    break;    
	    
	    case 'c_country':
	    	showStates(control.value=='United States');
	    break;
	    
	    case 'c_exp':
	    		showPhases(control.value!=='' && control.value!=='0');
	    break;
    } 
    checkForOther(control);
}

/*  Check if any sub speciality options exist, if they do then build a set
    of checkboxes to display them. */
function checkSpeciality(sel, clearInterests) {
        // we need to build checkboxes for all the relevant specialities.
        var selVal = sel.options[sel.selectedIndex].value;
        var checkBoxes = '';
        
        var subspecfield = document.getElementById(sel.id + '_i');
        if (subspecfield && clearInterests) {
            subspecfield.value = '';
        }
        
        // as the selection has changed we must clear and hide the "other" field.
        var otherContainer = document.getElementById(sel.id + '_i_other_container');
        var otherControl = document.getElementById(sel.id + '_i_other');

        if (otherContainer) {
            toggleAttribute(otherContainer,'class','visible','hidden');
            otherControl.value='';
            otherControl.isvisible = '0';
        }

        // clear out any existing checkboxes.
        var fieldset = document.getElementById(sel.id + '_i_checkboxes');
        if (fieldset) {
            (fieldset.parentNode).removeChild(fieldset);
        }
        
        
        
        if (specs[selVal]
        && specs[selVal].length > 0)
        {
        	fieldset = createControl('fieldset', sel.id + '_i_checkboxes');
        	setAttributeCrossBrowser(fieldset,'class','for_checkbox row1');
        
        	// now add the checkboxes as required.
        	var checkboxes = '';
        	selectedCheckboxes = [];
        	
            var label = createControl('label', '', 'Areas of Special Interest:'); 
            fieldset.appendChild(label);
            
            var ul = createControl('ul');
            fieldset.appendChild(ul);
            
            //ensure that the "Other, specify" checkbox is last 
			var isOther=specs[selVal].pop();
			if(isOther.toLowerCase()==='other, specify'){
				var uniqueId = sel.id + '_' + specsLength;
				addCheckBoxControl(fieldset, uniqueId, isOther);
			}else{
				specs[selVal].push(isOther);
			}
			
			var specsLength=specs[selVal].length;
            for (var i = 0; i < specsLength ;i+=2)
            {
                var uniqueId = sel.id + '_' + i;
                 var li_1 = createControl('li');
                 setAttributeCrossBrowser(li_1,'class','odd');
                 ul.appendChild(li_1);
                addCheckBoxControl(li_1, uniqueId, specs[selVal][i]);
                if ((i+1) < specsLength) {
                	var li_2 = createControl('li');
                 	setAttributeCrossBrowser(li_2,'class','even');
                 	ul.appendChild(li_2);
                    var uniqueId = sel.id + '_' + (i+1);
                    addCheckBoxControl(li_2, uniqueId, specs[selVal][i+1]);
                }
            }
            (subspecfield.parentNode).insertBefore(fieldset, subspecfield);
        }
                
        
        while (selectedCheckboxes.length > 0) {
            var checkboxControl = selectedCheckboxes.pop();
            try {
            checkboxControl.setAttribute('checked', 'checked');
            }
            catch (ex) {
            }
        }
        
        
}

/*  Function to show the states drop down if this is for the United States.
	Parameter indicates whether the states should be 
 */
function showStates(display) {
	var control = document.getElementById('c_state');
	
	if (control == null) {
		return;
	}
	
	var displayClass1 = 'hidden';
	var displayClass2 = 'visible';
	if (display) {
		displayClass1 = 'visible';
		displayClass2 = 'hidden';
	}
	else {
		// as we're hiding the control we whould remove it's value.
		control.value = '';
	}

	// see if we already have the states.
	var stateContainer = document.getElementById('c_state_container');
	    
    if (control && !stateContainer) {
        stateContainer = createControl('p', 'c_state_container');
        setAttributeCrossBrowser(stateContainer,'class','row1');
        
        var stateLabel = createControl('label', '', 'State (US Only)');
        setAttributeCrossBrowser(stateLabel,'for', 'c_states_list');

        var listControl = createControl('select', 'c_states_list');
        setAttributeCrossBrowser(listControl,'class','text');
        
        var optionControl = createControl('option', '');
        setAttributeCrossBrowser(optionControl, 'value', '');
        listControl.appendChild(optionControl);
        
		for (var i = 0; i < states.length ;i++)
        {
        	optionControl = createControl('option', '', states[i]);
        	setAttributeCrossBrowser(optionControl, 'value', states[i]);
        	listControl.appendChild(optionControl);
        	if (control.value == states[i]) {
	        	setAttributeCrossBrowser(optionControl,'selected', 'selected');
        	}	
		}
        
        stateContainer.appendChild(stateLabel);
        stateContainer.appendChild(listControl);
        
        (control.parentNode).insertBefore(stateContainer, control);
        
    }
    
    // show or hide the stateContainer.
	toggleAttribute(stateContainer,'class',displayClass2,displayClass1);    
}

function showPhases(display){
	//either show or hide the Phases, depending on whether display is true or false
	var phaseContainer = document.getElementById('fs_group_phase1');
	if(phaseContainer){
		if(display){
			toggleAttribute(phaseContainer,'class','hidden','visible');
		}else{
			toggleAttribute(phaseContainer,'class','visible','hidden');
		}
	}		
}

/*  Function to add an element to the DOM with the specified type, id and text.
    The first format for createElement works for IE, if this fails then the error
    is caught and the second method is used which should work for all browsers. */ 
function createControl(controlType, controlId, controlText) {
    var newControl;
    try {
        if (controlId && controlId != '') {
            newControl = document.createElement('<' + controlType + ' id="' + controlId + '" name="' + controlId + '" />');
        }
        else {
            newControl = document.createElement('<' + controlType + ' />');
        }
    } catch (e) {
        newControl = document.createElement(controlType);
        if (controlId && controlId != '') {
            newControl.setAttribute('name', controlId);
            newControl.setAttribute('id', controlId);
        }
    }
    if (controlText && controlText != '') {
        newControl.appendChild(document.createTextNode(controlText));
    }
    return newControl;
}

var selectedCheckboxes = [];

/*  Create the elements in the DOM required for a checkbox. */
function addCheckBoxControl(parent, uniqueId, checkValue, selectId) {

    var label = createControl('label', 'label_' + uniqueId);
    setAttributeCrossBrowser(label,'for','checkbox_' + uniqueId);
    setAttributeCrossBrowser(label,'class','for_checkbox');
    
    var chkControl = createControl('input', 'checkbox_' + uniqueId);
    chkControl.setAttribute('type', 'checkbox');
    // see if this one is already selected.
    if (alreadySelected(uniqueId, checkValue)) {
        chkControl.setAttribute('checked', 'checked');
        selectedCheckboxes.push(chkControl);
    }
    chkControl.value = checkValue;
    
    chkControl.onclick = function () {return handleSubSpecialty(this);};
    
    label.appendChild(chkControl);
    label.appendChild(document.createTextNode(checkValue));
    
    var para = createControl('p', 'p_' + uniqueId);
    para.appendChild(label);
    
    parent.appendChild(para);
}

/*  See if the checkbox should be checked. */
function alreadySelected(uniqueId, checkValue) {
        // find the field which contains the other values.  to contain the values
        var idBits = uniqueId.split('_'); 
        if (idBits == null || idBits.length < 3) {
            return false;
        }
        
        var field = document.getElementById('c_'+idBits[1] + '_i');
        if (field) {
            var currentVals = field.value.split(',');
            for (var k = 0; k < currentVals.length; k++) {
                // the regex is just the same as a trim.
                if (currentVals[k].replace(/^\s+|\s+$/g, '') == checkValue) {
                    return true;
                }
            }
        }
        return false;
}

/*  event handler for when the user checks or unchecks one of the checkboxes
    in the list of subspecialities. */
function handleSubSpecialty(sel) {
        // find the field to contain the values
        var idBits = sel.id.split('_'); 
        updateSubSpecField('c_'+idBits[2], sel.value, sel.checked);
}

/*  Sets the spec1_i or spec2_i field to currently selected sub speciality fields. */ 
function updateSubSpecField(specialityId, value, checked){
    if (value == 'Other, Specify') {
        displayOther(specialityId + '_i', checked);
    } else {
        var field = document.getElementById(specialityId + '_i');
        if (checked) {
            // add the value to the field.
            if (field.value) { 
                field.value += ', ';
            }
            field.value += value;
        } else {
            // remove the value from the field
            if (field.value) {
                
                var values = field.value.split(', ');
                for (var i = 0; i < values.length; i++) {
                    if (values[i] == value) {
                        // remove this one.
                        values[i] = '';
                    }
                }
                field.value = '';
                csv = '';
                for (var i = 0; i < values.length; i++) {
                    if (values[i] != '') {
                        field.value += csv + values[i];
                        csv = ', ';
                    }
                }
            }
        }
    }
}

/*  Check to see if we should display the 'Other' field */
function checkForOther(sel) {
    var selVal = sel.options[sel.selectedIndex].value;
    displayOther(sel.id, (selVal=='Other'));
}

/*  Display or Hide the 'other' field as required. */
function displayOther(specialityId, checked) {

    var otherControl = document.getElementById(specialityId + '_other');
    var otherContainer = document.getElementById(specialityId + '_other_container');

    if (otherContainer) {
        if (checked)
        {
            toggleAttribute(otherContainer,'class','hidden','visible');
            otherControl.isvisible = '1';
        }
        else
        {
            toggleAttribute(otherContainer,'class','visible','hidden');
            otherControl.value='';
            otherControl.isvisible = '0';
        }
    }   
}

/*  This function needs to be explanded to perform validation of fields which are
    only required when other options are set. E.g. if the 'other' value is selected
    on a dropdown then we should check that a value is entered in the other field. */    
function validateInput() {
    // check that the values entered are valid.
    //check emails match
    var email1=document.getElementById('c_email1');
    var email2=document.getElementById('c_email2');
    if(email1 && email2){
    	if(email1.value!==email2.value || email1.value===''){
    		alert('Email addresses do not match or are blank');
    		email1.focus();
    		return false;
    	}	
    }
    
    // Finally copy any 'other' values into the correct fields.
    for (var i = 0; i < otherFields.length; i++) {
        var otherName = otherFields[i];
        var fld_o = document.getElementById(otherName + '_o');
        var fld_other = document.getElementById(otherName + '_other');
        //_o =hidden
        //_other=text
        
        //if select is set to 'other' (last item)  then fld_other is compulsory
        var fld_select=document.getElementById(otherName);
        if(fld_select){
        	if(fld_select.type==='select-one' && fld_select[fld_select.selectedIndex].value.toLowerCase()==='other' && fld_other.value===''){
        		alert('Please complete the "Other, please specify" field');
    			fld_other.focus();
        		return false;
        	}
        } 
        fld_o.value = fld_other.value;
    }
    
    // and the state field too (if present).
    var stateControl = document.getElementById('c_state');
    if (stateControl) {
    	// check the country is selected as US
    	var countryControl = document.getElementById('c_country');
		if (countryControl && countryControl.value == 'United States') {
			var stateListControl = document.getElementById('c_states_list');
			if (stateListControl) {
    			stateControl.value = stateListControl.value;
    		}
    	}
    }
    
    return true;
}