function toggle_step_one () {

    /* if step one is complete */
    if ($('search-type-current').style.display == 'none') {
        $('search-type-current').style.display = 'inline';
        $('step-one').style.display = 'none';
        $('step-one-title').innerHTML = 'Step 1: Complete.';
        $('step-one-caption').className = 'step-form-caption complete';
        $('step-one-faq-link').style.display = 'none';

        var labels = {'pcp_search': 'PCP', 'specialist_search': 'Specialist', 'hospital_search': 'Hospital', 'pharmacy_search': 'Pharmacy', 'facility_search': 'Other facility/service'};
        /* get the search type */
        var search_types = $('search-type-form').mode;
        var search_type;
        for (var i = 0; i < search_types.length; i++) {
            if (search_types[i].checked) {
                search_type = search_types[i].value;
            }
        }

        /* display the type on the page */
        var search_type_labels = $$('.search_type_name');
        for (var i = 0; i < search_type_labels.length; i++) {
            search_type_labels[i].innerHTML = labels[search_type];
        }

        $('step-one-complete').value = 1;
        $('results-mode').value=search_type+'_results';
        webtrends('2', {'search_type': search_type});

            
        /* user is logged in, or has already entered step two, hide step two, display step three */
        if ($('user-info-current').style.display != 'none' || $('user-type').value == 'member') {
            if ($('step-two-logged-in').style.display != 'none' && /ppo/i.test($('step-two-logged-in').innerHTML)) {
                $('step-two').style.display = 'block';
                $('step-two-caption').style.display = 'block';
                $('step-twob-div').style.display = 'block';
            }
            else {
                $('user-info-current').style.display = 'inline';
                $('step-two-caption').style.display = 'block';
                $('step-two').style.display = 'none';
                $('step-three-caption').style.display = 'block';
                $('step-three').style.display = 'block';
                toggle_search_fields(search_type);
                search();
            } 
        } else {
            /* display step two */
            $('step-two').style.display = 'block';
            $('step-two-caption').style.display = 'block';
            if ($('step-two-complete').value != 1) {
                $('user-info-form').info_type[0].focus();
            }
        }
    }
    else {/* step one not complete */
        $('search-type-current').style.display = 'none';
        $('step-one').style.display = 'block';
        $('step-one').style.borderBottom = 'none';
        $('step-one-title').innerHTML = 'Step 1';
        $('step-one-caption').className = 'step-form-caption';
        $('step-one-faq-link').style.display = 'block';
        $('step-one-complete').value = '';
        if ($('spec-state').value == 'open') {
            toggle_specialty();
        }
        if ($('toc-state').value == 'open') {
            toggle_toc();
        }
        
    }
        
    return false;
}

function toggle_step_two (user_info) {
    /* step two is not complete */
    if ($('step-two').style.display == 'none') {
        $('step-two-title').innerHTML = 'Step 2';
        $('step-two-caption').className = 'step-form-caption';
        $('user-info-current').style.display = 'none';
        $('step-two').style.display = 'block';
        $('step-two-div').style.display = 'block';
        $('user-info-form').info_type[0].focus();
        $('step-two-faq-link').style.display = 'block';
        $('step-two-complete').value = '';
        $('step-three-caption').style.borderTop = 'none';
        if ($('spec-state').value == 'open') {
            toggle_specialty();
        }
        if ($('toc-state').value == 'open') {
            toggle_toc();
        }
    }
    else {/* step two is complete */
        $('step-two-title').innerHTML = 'Step 2: Complete.';
        $('step-two-caption').className = 'step-form-caption complete';
        $('user-info-current').style.display = 'inline';
        $('step-two').style.display = 'none';
        $('step-two-faq-link').style.display = 'none';
        $('step-three-caption').style.display = 'block';
        $('step-three-caption').style.borderTop = '1px solid #CCCCCC';
        $('step-three').style.display = 'block';
        $('step-two-complete').value = 1;
        if (user_info) 
            webtrends('3', user_info); 
        /* run the search stuff (back button, link in) */
        toggle_search_fields();
        reload_search_fields();
        search();
    }

    return false;
}
/* toggle the user info (plan, contract, login) */
function toggle_user_info () {
    if ($('user-info-form')) {
        var info_types = $('user-info-form').info_type;
        for (i = 0; i < info_types.length; i++) {

            if (info_types[i].checked) {
                $(info_types[i].value).style.display = 'block';
                if (info_types[i].value == 'plan')
                    toggle_outsidemi($('plan-select'));
            }
            else {
                $(info_types[i].value).style.display = 'none';
            }
        }

        var search_types = $('search-type-form').mode;
        var search_type;
        for (var i = 0; i < search_types.length; i++) {
            if (search_types[i].checked) {
                search_type = search_types[i].value;
            }
        }
        
        /* set the mode in the search form */
        var mode_inputs = $$('.hidden-mode');

        for (var i = 0; i < mode_inputs.length; i++) {
            mode_inputs[i].value = search_type;
        }
    }
    
    return false;
}

/* confirm the values for plan or contract */
function confirm_step_two (type) {
    /* reset the error class */
    $('contract-number-select').className = '';
    $('plan-select').className = '';
    if ($('contract-number-error')) {
        $('contract-number-error').remove();
    }
    if ($('plan-error')) {
        $('plan-error').remove();
    }
    /* hide the page_error, show the page info */
    var page_error = $$('div.page-error')[0];
    if (page_error) {
        page_error.style.display = 'none';
    }
    var page_info = $$('div.page-info')[0];
    if (page_info) {
        page_info.style.display = 'block';
    }

    var params = $(type+'-form').serialize(true);
    new Ajax.Request('/prog/provdir/provider_directory.cgi',
        {
            method: 'post',
            parameters: params,
            onFailure: function () { alert('Confirming step two failed.');}, 
            evalJSON: true,
            asynchronous: false,
            onSuccess: function (response) {
                if (response) {
                    var data = response.responseJSON;
                    if (data.errors) {
                        if (type == 'plan') {
                            $('plan-select').insert({before: new Element('div', {'class': 'field-error', 'id':'plan-error'}).insert(data.errors.plan)});
                            $('plan-select').className='field-with-error';
                        }
                        else {
                            $('contract-number-select').insert({before: new Element('div', {'class': 'field-error', 'id':'contract-number-error'}).insert(data.errors.contract_number)});
                            $('contract-number-select').className='field-with-error';
                            if (data.errors.page_error) {
                                display_page_error(data.errors.page_error);
                            }
                        }
                    }
                    else {
                        if (type == 'plan') {
                            var re = /Priority/;
                            $('plan-display').innerHTML = data.plan_display.replace(re, '<span class="field-label">Priority</span>');
                            $('step-two-plan').style.display = 'inline';
                            $('step-two-contract-number').style.display = 'none';
                            $('results-plan').value = data.plan;
                            $('results-contract-number').value = '';
                        }
                        else {
                            $('contract-number-display').innerHTML = data.contract_number;
                            if (data.contract_name) {
                                $('contract-name-display').innerHTML = data.contract_name+', ';
                            }
                            else {
                                $('contract-name-display').innerHTML = '';
                            }
                            $('contract-plan-display').innerHTML = data.contract_plan;
                            $('step-two-contract-number').style.display = 'inline';
                            $('step-two-plan').style.display = 'none';
                            $('results-plan').value = '';
                            $('results-contract-number').value = data.contract_number;

                            if (/ppo/i.test(data.contract_plan)) {
                                $('step-two-div').style.display = 'none';
                                $('step-twob-div').style.display = '';
                                $('step-two-title').innerHTML = 'Step 2b';
                                return false;
                            }

                        }
                        

                        toggle_step_two(params);
                    }
                    
                }
                else {
                    alert('confirm_step_two failed!');
                }
            }
        }
    );

    return false; //make sure form does not submit
}

/* toggle the category field */
function toggle_toc (toggle) {
    var state = $('toc-state');

    if (state.value == 'closed' || state.value == 'small') {
        $('toc-float').style.position = 'absolute';
        $('toc-float').style.display = 'block';
        $('toc-iframe').style.display = 'inline';
        try { /* firefox */
            $('toc-float').clonePosition($('type-of-care-label'), {offsetLeft: 62, setWidth: false, setHeight: false});
            $('toc-iframe').clonePosition($('type-of-care-label'), {offsetLeft: 74, setWidth: false, setHeight: false});
        }
        catch (err) {
            var pos = findPos($('type-of-care-label'));
            $('toc-float').style.top = pos[1];
            $('toc-float').style.left = pos[0]+70;
            $('toc-iframe').style.top = pos[1];
            $('toc-iframe').style.left = pos[0]+70;
        }
        $('toc-float').style.border = '1px solid #CCCCCC';
        $('toc-button').style.display = 'block';
        $('toc-limit').style.display = 'block';
        $('toc-limit').focus();
        $('type-of-care').onfocus = '';
        $('type-of-care').size = 12;
        $('toc-close').style.display = 'block';
        state.value = 'open';
    }
    else if (state.value == 'open') {
        $('toc-iframe').style.display = 'none';
        $('toc-float').style.display = 'inline';
        $('toc-float').style.position = 'static';
        $('toc-float').style.border = 'none';
        $('type-of-care').style.display = 'inline';
        $('type-of-care').size = 1;
        $('type-of-care').onfocus = toggle_toc;
        $('toc-button').style.display = 'none';       
        $('toc-limit').style.display = 'none';
        $('location-label').focus();
        $('location-label').select();
        $('toc-close').style.display = 'none';
        state.value = 'small';
    }
    if (toggle == true) {
        /* reset everything to be closed */
        if ($('type-of-care').style.display != 'none') {
            $('toc-limit').value = '';
            toc_filter();
            state.value = 'closed';
            $('toc-float').style.display = 'none';
            $('toc-iframe').style.display = 'none';
            $('type-of-care').onfocus = '';
        }
        toggle_field('type-of-care');
        if ($('toc-float').style.display == 'block') {
            $('toc-limit').focus();
        }
    }
}

/* toggle the specialty field */
function toggle_specialty (toggle) {
    var state = $('spec-state');

    if (toggle == true && ($('specialty-float').style.display == 'block' || $('specialty-float').style.display == 'inline')) {
        $('specialty-limit').value = '';
        specialty_filter();
        $('specialty-float').style.display = 'none';
        $('specialty-iframe').style.display = 'none';
        state.value = 'closed';
        switch_label($('specialty-label'), '+');
        $('specialty').value = '';
        return;
    }
    else if (toggle) {
        switch_label($('specialty-label'), '-');
    }

    if (state.value == 'closed' || state.value == 'small') {
        $('specialty-float').style.position = 'absolute';
        $('specialty-float').style.display = 'block';
        $('specialty-iframe').style.display = 'inline';
        try { /* firefox */
            $('specialty-float').clonePosition($('specialty-label'), {offsetLeft: 62, setWidth: false, setHeight: false});
            $('specialty-iframe').clonePosition($('specialty-label'), {offsetLeft: 74, setWidth: false, setHeight: false});
        }
        catch (err) {
            var pos = findPos($('specialty-label'));
            $('specialty-float').style.top = pos[1];
            $('specialty-float').style.left = pos[0]+70;
            $('specialty-iframe').style.top = pos[1];
            $('specialty-iframe').style.left = pos[0]+70;
        }

        $('specialty-float').style.border = '1px solid #CCCCCC';
        $('specialty-description').style.display = 'block';
        $('specialty-button').style.display = 'block';
        $('specialty-limit').style.display = 'block';
         $('specialty-limit').focus();
        /* this is for firefox */
        $('specialty-limit').select();
        $('specialty-description-header').style.display = 'block';
        $('specialty').style.display = 'inline';
        $('specialty').onfocus = '';
        $('specialty').size = 12;
        $('specialty').style.margin = '0 0 10px 8px';
        $('specialty-close').style.display = 'block';
        state.value = 'open';
    }
    else if (state.value == 'open') {
        $('specialty-iframe').style.display = 'none';
        $('specialty-float').style.display = 'inline';
        $('specialty-float').style.position = 'static';
        $('specialty-float').style.border = 'none';
        $('specialty').style.display = 'inline';
        $('specialty').style.margin = '0';
        $('specialty').size = 1;
        /* set the onfocus to toggle it open and move focus to the next element */
        $('specialty').onfocus = toggle_specialty;
        $('name-label').focus();
        $('name-label').select();
        $('specialty-description').style.display = 'none';
        $('specialty-button').style.display = 'none';       
        $('specialty-limit').style.display = 'none';
        $('specialty-description-header').style.display = 'none';
        $('specialty-close').style.display = 'none';
        state.value = 'small';
    }

    return false;
}

/* filter the category field */
function toc_filter () {
    var pattern = $('toc-limit').value;
    /* ignore case */
    var regex = new RegExp(pattern, 'i');

    /* reset options */
    $('type-of-care').options.length = 0;

    var first = 1;
    var index = 0;
    for (var i = 0; i < toc_options.length; i++) {
        if (regex.match(toc_options[i].text) || pattern == '') {
            $('type-of-care').options[index] = new Option(toc_options[i].text, toc_options[i].value, false);
            if (first) {/* select and load the first one */
                $('type-of-care').options[index].selected=true;
                first = 0;
            }
            index++;
        }
    }
}

/* filter the specialty field */
function specialty_filter () {
    var pattern = $('specialty-limit').value;
    /* ignore case */
    var regex = new RegExp(pattern, 'i');

    /* reset options */
    $('specialty').options.length = 0;

    var first = 1;
    var index = 0;
    for (var i = 0; i < specialty_options.length; i++) {
        if (regex.match(specialty_options[i].text) || pattern == '') {
            $('specialty').options[index] = new Option(specialty_options[i].text, specialty_options[i].value, false);
            if (first) {/* select and load the first one */
                $('specialty').options[index].selected=true;
                load_spec_detail();
                first = 0;
            }
            index++;
        }
    }
}

/* this handles the return button for the specialty field */
function select_specialty (the_event) {
    if (!the_event) {
        the_event = window.event;
    }
    if (the_event.keyCode == 13) {
        toggle_specialty();
        return false;
    }
}

/* this handles the return button for the category field */
function select_toc (the_event) {
    if (!the_event) {
        the_event = window.event;
    }
    if (the_event.keyCode == 13) {
        /* set the focus to the next field, otherwise the toc box is already focus'd and causes an instantaneous toggle */
        $('toc-limit').focus();
        toggle_toc();
        return false;
    }
}

/* toggle the location field (zip, county, city) */
function toggle_location (selected_value, params) {
    var locations = $('location-type');
    var location;
    for (var i = 0; i < locations.length; i++) {
        if (locations[i].selected) {
            location = locations[i].value;
        }
    } 

    /* select the correct fields, hide the rest */
    if (location == 'zip') {
        $('location-zip').style.display = 'inline';
        $('location-city').style.display = 'none';
        $('location-county').style.display = 'none';
        /* clear the other two fields */
        if ($('city')) {
            $('city').value = '';
        }
        if ($('county')) {
            clear_county();
            $('county').value = '';
        }
    }
    else if (location == 'city') {
        $('location-zip').style.display = 'none';
        $('location-county').style.display = 'none';
        $('location-city').style.display = 'inline';
        if ($('location-city').innerHTML ==  '') {
            var params = {mode:'load_field', field: 'city'};
            new Ajax.Updater('location-city', '/prog/provdir/provider_directory.cgi',
                {
                    method: 'post',
                    parameters: params,
                    onFailure: function () { alert('Getting the city field failed');}, 
                    onComplete: function () {
                        /* one works for IE, the other Firefox */
                        var select = $('city');
                        if (!select) {
                            select = $('location-city').children[0];
                        }
                        select.value = selected_value; 
                    },
                    asynchronous: false
                }
            );
        }
        /* clear the other two fields */
        $('zip').value = '';
        if ($('county')) {
            clear_county();
            $('county').value = '';
        }
    } 
    else if (location == 'county') {
        $('location-zip').style.display = 'none';
        $('location-city').style.display = 'none';
        $('location-county').style.display = 'inline';
        if ($('location-county').innerHTML ==  '') {
            var params = {mode:'load_field', field: 'county', county: selected_value};
            new Ajax.Updater('location-county', '/prog/provdir/provider_directory.cgi',
                {
                    method: 'post',
                    parameters: params,
                    onFailure: function () { alert('Getting the county field failed.');},
                    onComplete: function () { 
                        if (selected_value) {
                        
                            var county_ids = new Array();
                            if (typeof selected_value == 'string') { /* this is a string */
                                /* single value passed */
                                selected_value = selected_value.split(",");
                            }
                            /* turn this into a hash for faster comparison */ 
                            for (var i = 0; i < selected_value.length; i++) {
                                county_ids[selected_value[i]] = 1;
                            }
                            /* one works for IE, the other Firefox */
                            var select = $('county');
                            if (select.type && !select.type.match(/^select/)) {
                                select = $('location-county').children[0];
                            }
                            var options = select.options;

                            /* loop through options selecting the option that were pased in */
                            for (var i = 0; i < options.length; i++) {
                                if (county_ids[options[i].value] == 1) {
                                    options[i].selected = true;
                                }
                            }
                        }
                    },
                    asynchronous: false 
                }
            );
        }
        /* clear the other two fields */
        $('zip').value = '';
        if ($('city')) {
            $('city').value = '';
        }
    }
}

function clear_county () {
    var counties = $('county').options;

    for (var i = 0; i < counties.length; i++) {
        counties[i].selected = false;
    }
}

/* switch the label +/- */
function switch_label (label, prefix) {
    label.innerHTML = prefix+label.innerHTML.substr(1);
}

/* send steps to webtrends */
function webtrends (page, params) {
    
    var options = new Array();

    var keys = new Array();
    var values = new Array();
    if (params) {
        for (var param in params) {
            if (params[param]) {
                keys.push(param);
                values.push(params[param]);
            }
        }
    }
    var criteria = keys.join(';');
    var options = values.join(';');
    if (page) {
        dcsMultiTrack('DCS.dcssip','www.priorityhealth.com','DCS.dcsuri','/clicktrack/scenario/find_doctor/','WT.dl','20','WT.si_n','find_doctor','WT.si_x',page,'WT.z_criteria', criteria, 'WT.z_options', options);
    }
}

/* find the posiion of a label, for specialty and category floats */
function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft,curtop];
}

/* toggle field, load it with AJAX if it doesn't exist */
function toggle_field (field_id, selected_value) {
    /* this prevents double clicks from loading a field twice */
    if (loading == true) {
        return false;
    }
    var field_label = $(field_id+'-label');
    var field = $(field_id);
    if (field) {/* field exists */
        if (field.style.display == 'none' || field.style.display == '') {/* its hidden, display it*/
            field.style.display = 'inline';
            switch_label(field_label, '-');
            field.focus();
            if (field_id == 'board-cert' || field_id == 'accepting-new' || field_id == '90-day-rx') {
                field.value = 'Y';
            }
                
        }/* its displayed, hide it */
        else {
            field.style.display = 'none';
            /* hide the error field if it exists */
            if ($(field_id+'-error')) {
                $(field_id+'-error').style.display = 'none';
            }
            switch_label(field_label, '+');
            if (field.id == 'location') {
                $('zip').value = '';
                if ($('city')) {
                    $('city').value = '';
                }
                if ($('county')) {
                    clear_county();
                    $('county').value = '';
                }
            }
            else {
                field.value  = '';
            }
        }
    }
    else {/* use AJAX to retrieve the field */
        loading = true;
        params = {mode:'load_field', field: field_id},
        /* must not be asynchronous, the back button relies on this */
        new Ajax.Updater(field_label.parentNode, '/prog/provdir/provider_directory.cgi',
            {
                method: 'post',
                parameters: params,
                onFailure: function () { alert('Loading fied '+field_id+' failed');}, 
                onComplete: function () {$(field_id).focus(); $(field_id).select(); $(field_id).style.display = 'inline'; if (selected_value) {$(field_id).value = selected_value;} loading = false;},
                insertion: 'bottom',
                asynchronous: false
            }
        );
        switch_label(field_label, '-');
    }
    
    return false;
}

/* load the specialty definitions in the specialty box */
function load_spec_detail () {
    var descriptions = $$('.specialty-descriptions');

    for (var i = 0; i < descriptions.length; i++) {
        descriptions[i].style.display = 'none';
    }

    var specs = $('specialty');
    var spec_id;
    for (var i = 0; i < specs.options.length; i++) {
        if (specs.options[i].selected) {
            spec_id = specs.options[i].value;
        }
    }
    if (spec_id && $('description-'+spec_id)) {
        $('description-'+spec_id).style.display = 'inline';
    }
}

/* clear all search options, reset them to '' */
function clear_search_options () {
    $('location-type').value = 'zip';
    toggle_location();
    var fields = $$('.toggle_field');
    for (var i = 0; i < fields.length; i++) {
        if (fields[i].id == 'location') {
            $('zip').value = '';
            if ($('city')) {
                $('city').value = '';
            }
            if ($('county')) {
                clear_county();
                $('county').value = '';
            }
            fields[i].style.display = 'none';
            switch_label($('location-label'), '+');
        }
        else if (fields[i].id == 'specialty') {
            if ($('specialty-float').style.display == 'block' || $('specialty-float').style.display == 'inline') {
                toggle_specialty(true);
            }
        }
        else if (fields[i].id == 'type-of-care') {
            if ($('toc-float').style.display == 'block' || $('toc-float').style.display == 'inline') {
                toggle_toc(true);
            }
        }
        else { 
            if (fields[i].style.display != 'none') {
                toggle_field(fields[i].id);
            }
            fields[i].value = '';
        }
    }
}

/* change the order by, resubmit search */
function change_order_by () {
    var order_by = $('order-by-select');
    var order;

    for (var i = 0; i < order_by.length; i++) {
        if (order_by.options[i].selected) {
            $('order-by').value = order_by.options[i].value;
        }
    }

    return search(true);
}

/* change the page num, resubmit search */
function change_page (page_num) {
    $('page-num').value = page_num;
    return search(true);
}

function new_search () {
    return change_page(1);
}

/* this does all the searching */
function search (button_clicked) {
    /* short circuit if the third step is not shown */
    if ($('step-three') && $('step-three').style.display == 'none') {
        return;
    }
    /* remove location ID if user refreshes the original search */
    if ($('search-button').value == 'Refresh search') {
        $('loc_id').value = '';
    }
    /* hide the page_error and restore the info if it exists */
    var page_error = $$('div.page-error')[0];
    if (page_error && !page_error.innerHTML.match(/contract_page_error/)) {
        page_error.style.display = 'none';
    }
    if ($('field-error-list')) {
        $('field-error-list').remove();
    }

    var page_info = $$('div.page-info')[0];
    if (page_info) {
        page_info.style.display = 'block';
    } 

    var param_return = _load_search_params();
    var params = param_return[0];
    var count = param_return[1];
 
    /* no search params, or they clicked the button and actually wants to search */
    if (count > 0 || button_clicked) {
        $('ajax-results').style.border = '1px solid #A0C965';
        $('ajax-results').style.height = '402px';
        $('ajax-results').innerHTML = '<div id="loading"><img src="/images/generic/ajax-loader.gif"/> Loading.....</div>';
        params['ajax_results'] = 1;
        var new_hash = '&step_one_complete=1&step_two_complete=1&outsidemi_plan=No';
        for (var i in params) {
            if (params[i]) {
                new_hash += '&'+i+'='+params[i];
            }
        }
        window.dhtmlHistory.add('search'+new_hash, null);
        webtrends('4', params);
        new Ajax.Request('/prog/provdir/provider_directory.cgi',
            {
                method: 'post',
                parameters: params,
                onFailure: function () { alert('The search failed.');}, 
                evalJSON: true,
                onSuccess: function (response) {
                    if (response) {
                        var data = response.responseJSON;
                        if (data.errors) {
                            display_errors(data.errors);
                        }
                        else if (data.results) {
                            
                            if (data.results) {
                                try {
                                    eval(data.gmap_script); 
                                }
                                catch (err) {
                                    alert('Eval failed with error '+err);
                                }
                            }
                            $('search-button').value = 'Refresh search';
                            display_results(data.results);
                            if (data.gmap_script && data.count != 0) {
                                try {
                                    createMap();
                                }
                                catch (err) {
                                    alert('createMaps failed with error '+err);
                                }
                            }
                        }
                        else {
                            alert('JSON failed while searching');
                        } 
                    }
                    else {
                        alert('Search returned no data');
                    }
                }
            }
        );
    }

    return false; //make sure form does not submit
}

/* this builds the param set to be passed to the search query */
function _load_search_params () {
    /* get the form params */
    var params = $('search-form').serialize(true);
    
    /* get all the fields */
    var fields = $$('.toggle_field');
    
    var re = /field\-with\-error/g;
    $('zip').className = $('zip').className.replace(re, '');
    var count = 0;
    /* remove any fields that are not displayed */
    for (var i = 0; i < fields.length; i++) { 
        /* clear errors that may have been displayed */
        fields[i].className = fields[i].className.replace(re, '');
        var id = fields[i].id;
        /* stop displaying errors */
        var error = $(id+'-error');
        if (error) {
            error.style.display = 'none';
        }
        /* if the field is hidden, or the whole field is hidden */ 
        if (fields[i].style.display == 'none' || $(fields[i].id+'-label').parentNode.style.display == 'none') {
            params[fields[i].name] = '';
        }
        else {
            count++;
        }
    }

    /* handle zip a little differently */
    if ($('location').style.display == 'none') {
        params['zip'] = '';
        params['city'] = '';
        params['county'] = '';
    }

    return [params, count];
}

/* show any field errors returned from the search */
function display_errors (errors) {
    $('ajax-results').innerHTML = '';
    /* handle page errors */
    if (errors['page_error']) {
        display_page_error(errors['page_error']); 
    }
    
    /* handle field errors */
    var error_list = new Element('ul', {'class': 'field_error', 'id': 'field-error-list'});
    var count = 0;
    for (var field_name in errors) {
        if (field_name != 'page_error') {
            var id = field_name.replace(/_/g, '-');
            $(id).className = $(id).className+' field-with-error';
            error_list.insert(new Element('li').insert('! '+errors[field_name]));
            count++;
        }
    }
    if (count > 0) {
        /* insert it before the page-num, which is the first field, and is hidden */
        $('page-num').insert({'before': error_list});
    }
}

function display_page_error (error_text) {
    var page_info = $$('div.page-info')[0];
    var page_error = $$('div.page-error')[0];
    if (page_info) {
        page_info.style.display = 'none';
    }
    
    if (page_error) {
        page_error.innerHTML = error;
        page_error.style.display = 'block';
    }
    else {
        var error = new Element('div', {'class': 'page-error'});
        error.insert(error_text);
        $('provdir').insert({top:error});
    }
}

function display_results (results) {
    $('ajax-results').style.border = '';
    $('ajax-results').update('');
    $('ajax-results').insert('<div id="map">&nbsp;</div>'+results);
}

/* this builds the url and opens a new window for printing */
function show_print_window (mode) {
    if (!mode) {
        mode = 'print';
    }
    
    /* if on search page */
    var params;
    if ($('search-form')) {
        params = _load_search_params()[0];
    }
    else {
        var url = window.location.href;
        params = url.toQueryParams();
    }

    /* store actual search mode somewhere it can be accessed */
    params['search_mode'] = params['mode'];

    params['mode'] = mode;

    var pairs = new Array();
    for (param in params) {
        if (params[param] != '') {
            pairs.push(param+'='+params[param]);
        }
    }

    var url = '/prog/provdir/provider_directory.cgi?'+pairs.join('&');

    var windowHandle = window.open(
        url,
        'providerprintresults', 
        'menubar=no,width=800,height=600,scrollbars=yes,status=no');
    windowHandle.opener = self;
    
    return false;
}


/* this toggles the accepted plans on the detail page */
function toggle_plans (count) {
    var classname = '.plan-row';
   
    if ($('hide-plans')) {
        var plan_rows;
        if (count) {
            plan_rows = $$(classname+count); 
            if ($('toggle-link'+count).innerHTML == 'view plans accepted') {
                $('toggle-link'+count).innerHTML = 'hide plans accepted';
                for (var i = 0; i < plan_rows.length; i++) {
                    /* this works because the table header row is always displayed */
                    plan_rows[i].style.display = '';
                }
            }
            else {
                $('toggle-link'+count).innerHTML = 'view plans accepted';
                for (var i = 0; i < plan_rows.length; i++) {
                    if (!plan_rows[i].className.match(/highlight/)) {
                        plan_rows[i].style.display = 'none';
                    }
                }
            }
        }
        else { /* no count passed in, this is first load, roll them up */
            plan_rows = $$(classname); 
            for (var i = 0; i < plan_rows.length; i++) {
                if (!plan_rows[i].className.match(/highlight/)) {
                    plan_rows[i].style.display = 'none';
                }
            }
        }
        
    }

    return false;
}

/* this toggles all the search fields based on the search type you selected */
function toggle_search_fields (search_type) {
    /* return if step three isn't being displayed */
    if ($('step-three').style.display != 'block') {
        return;
    }
    /* hide all the fields, that are empty */
    var fields = $$('.toggle_field');
    for (var i = 0; i < fields.length; i++) {
        if (fields[i].id == 'location') {
            if ($('zip').value == '' && (!$('city') || $('city') && $('city').value == '') && (!$('county') || $('county') && $('county').value == '')) {
                fields[i].style.display = 'none';
                switch_label($('location-label'), '+');
            }
        }
        else if (fields[i].value == '') {
            fields[i].style.display = 'none';
            switch_label($(fields[i].id+'-label'), '+');
        }
        else {
            fields[i].style.display = 'inline';
        }
        
    }

    /* hide all the field labels */
    var fields = $$('#step-three .no_wrap');
    for (var i = 0; i < fields.length; i++) {
        fields[i].style.display = 'none';
    }   

    if (!search_type) { 
        /* get the search type */
        var search_types = $('search-type-form').mode;
        var search_type;
        for (var i = 0; i < search_types.length; i++) {
            if (search_types[i].checked) {
                search_type = search_types[i].value;
            }
        } 
    }
    var re = /_search/g;
    search_type = '.'+search_type.replace(re, '');
    /* display the appropriate fields for this search type */
    var fields = $$(search_type);
    for (var i = 0; i < fields.length; i++) {
        fields[i].style.display = 'inline-block';
    }
    /* the setTimeout is to work around a Firefox bug */
    if (search_type == '.specialist') {
        setTimeout("select_search_field('specialist')", 300);
    }
    else if (search_type == '.pcp') {
        setTimeout("select_search_field('pcp')", 300);
    }
    else {
        setTimeout("select_search_field('other')", 300);
    }
}

/* this reloads fields from the query, or from the back button history object */
function reload_search_fields () {
    /* params from the hash are stored in a global variable */
    var url = window.location.href;
    params = url.toQueryParams();
    
    if (hash_params) {
        for (var key in hash_params) {
            params[key] = hash_params[key];
        }
    }
    
    if (params) {
        /* must reload fields that are loaded via AJAX */
        if (params['city']) {
            toggle_field('location');
            toggle_location(params['city']);
        }
        if (params['county']) {
            toggle_field('location');
            toggle_location(params['county'], params);
        }
        if (params['hosp_affl']) {
            toggle_field('hosp-affl', params['hosp_affl']);
        }
        if (params['language_doctor']) {
            toggle_field('language-doctor', params['language_doctor']);
        }
        if (params['language_office']) {
            toggle_field('language-office', params['language_office']);
        }
        if (params['pro_degree']) {
            toggle_field('pro-degree', params['pro_degree']);
        }
        if (params['field_service']) {
            toggle_field('field-service', params['field_service']);
        }
        if (params['acct_exec']) {
            toggle_field('account-exec', params['acct_exec']);
        }
        if (params['specialty']) {
            $('spec-state').value = 'open';
            toggle_specialty(true);
            $('specialty').value = params['specialty'];
        }
        if (params['type_of_care']) {
            $('toc-state').value = 'open';
            toggle_toc();
            $('type-of-care').value = params['type_of_care'];
            switch_label($('type-of-care-label'), '-');
        } 
    }
}

/* This function gets the values from the hash and sets them, this is for bookmarks and the back button */
function _load_from_hash () {

    var hash = window.location.hash.replace(/\#search\&/, '');
    var params = hash.toQueryParams();

    if (params) {
        /* handle mode first */
        if (params['mode']) {
            var search_mode = params['mode'];
            search_mode = search_mode.replace(/_results/, '');
            var search_types = $('search-type-form').mode;
            for (var i = 0; i < search_types.length; i++) {
                if (search_types[i].value == search_mode) {
                    search_types[i].checked=true;
                }
            }
            delete params['mode'];
        }
        /* handle the info type entered */
        var info_type;;
        if (params['plan']) {
            info_type = 'plan';
            $('plan-select').value = params['plan']; 
            $('plan').style.display = 'block';
            delete params['plan'];
        }

        if (params['contract_number']) {
            info_type = 'contract-num';
            $('contract-number-select').value = params['contract_number'];
            $('contract-num').style.display = 'block';
            delete params['contract_number'];
        }
            
        if (info_type) {
            var info_types = $('user-info-form').info_type;
            for (i = 0; i < info_types.length; i++) {
                if (info_types[i].value == info_type) {
                    info_types[i].checked=true;;
                }
            }
        }
       
        /* now handle the rest of the params */
        for (var key in params) {
            var id = key.replace(/_/g, '-');
            if ($(id)) {
                $(id).value = params[key];
            }
        }
        return params;
    }
}

/* function to select some fields, function needed for timeout */
function select_search_field (type) {
    if (type == 'specialist') {
        $('specialty-label').focus();
        $('specialty-label').select();
    }
    else if (type == 'pcp') {
        $('name-label').focus();
        $('name-label').select();
    }
    else {
        $('fac-site-name-label').focus();
        $('fac-site-name-label').select();
    }
}

/* JSON overrides to use prototypes json methods in RSH */
window.dhtmlHistory.create( {
    toJSON: function(o) {
        return Object.toJSON(o);
    }
    , fromJSON: function(s) {
        return s.evalJSON();
   }
});

function historyChange () {
    /* function for dhtmlHistory, we don't actually want to do anything here */
}

/* onload event */
Event.observe(window, 'load', function () {
    loading = false;
    $('plan-select').observe('click', function(event) { toggle_outsidemi($('plan-select')); });
    if ($('step-one')) {
        hash_params = _load_from_hash();
        specialty_options = new Array();
        /* store a copy of the options for specialty in a global variable */
        if ($('specialty')) {
            for (var i = 0; i < $('specialty').options.length; i++) {
                specialty_options[i] = new Option;
                specialty_options[i].text = $('specialty').options[i].text;
                specialty_options[i].value = $('specialty').options[i].value;
            }
        }
        toc_options = new Array();
        /* store a copy of the options for type of care in a global variable */
        if ($('type-of-care')) {
            for (var i = 0; i < $('type-of-care').options.length; i++) {
                toc_options[i] = new Option;
                toc_options[i].text = $('type-of-care').options[i].text;
                toc_options[i].value = $('type-of-care').options[i].value;
            }
        }

        /* initialize real simple history */
        dhtmlHistory.initialize();
        dhtmlHistory.addListener(historyChange);


        /* the following section is complicated and used to reload things when the back button is clicked or they come to the app logged in */

        /* toggle the first step if it is complete */
        if ($('step-one-complete') && $('step-one-complete').value == 1) {
            toggle_step_one();
        }
        else if ($('authenticated').value == 1 && $('mode-passed-in').value == 1) {
            toggle_step_one();
        }
        
        /* toggle step two if it is complete, this also opens step 3 */
        if ($('step-two-complete') && $('step-two-complete').value == 1) {
            if ($('authenticated') && $('user-type').value == 'member') {
                /* do nothing */
            }
            else {
                var info_types = $('user-info-form').info_type;
                var type;
                for (i = 0; i < info_types.length; i++) {

                    if (info_types[i].checked) {
                        type = info_types[i].value;
                    }
                }
                /* this is slightly out of order, but neccessary */
                confirm_step_two(type);
                /* we need to check if we already set this value to No */
                if ($('step-twob-div').style.display != 'none' && hash_params['outsidemi_plan']) {
                    var inputs = $('step-twob-div').getElementsByTagName('INPUT');
                    for (var i = 0; i < inputs.length; i++) {
                        if (inputs[i].type.toLowerCase() == 'radio') {
                            inputs[i].checked = inputs[i].value == hash_params['outsidemi_plan'];
                        }
                    }

                    for (var i = 0; i < inputs.length; i++) {
                        if (inputs[i].type.toLowerCase() == 'button') {
                            check_outside_val(inputs[i]);
                        }
                    }
                }

                return;
            }
        }
        /* these functions are used for the back button */
        toggle_search_fields();
        reload_search_fields();
        toggle_user_info();
        search();
    }
    else {
        toggle_plans();
    }
});

function toggle_outsidemi(select) {
    if (select == null || select == undefined) return;
    if (select.selectedIndex != null && select.options[select.selectedIndex].text.match(/ppo/i)) {
        $("outsidemi").style.display = "";
        $("step-2-submit").style.display = "none";
    }
    else {
        $("outsidemi").style.display = "none";
        $("step-2-submit").style.display = "";
    }
}

function check_outside_val(button) {
    var answer;
    var form = button.parentNode;
    while (form != null && form != undefined && form.tagName.toUpperCase() != 'FORM')
        form = form.parentNode;

    if (form == null || form == undefined) return false;
    
    var outside = form.getElementsByTagName("INPUT");

    for (var i = 0; i < outside.length; i++) {
        if (outside[i].type.toLowerCase() == "radio"
            && outside[i].checked) {
            answer = outside[i].value;
            break;
        }
    }

    if (answer == 'Yes') {
        var mode = find_prov_type();

        if (/^pharmacy/.test(mode)) {
            redirect_ppo();
        }
        else {
            var x = 0;
            if (self.innerHeight)
                x = self.innerWidth;
            else if (document.documentElement && document.documentElement.clientHeight)
                x = document.documentElement.clientWidth;
            else if (document.body)
                x = document.body.clientWidth;

            x = (x - 400) / 2;
            $('confirm-box').style.left = x + 'px';
            $('confirm-box').appear({duration: 0.75});
        }
    }
    else {
        if (form != null && form != undefined) {
            var func = form.onsubmit; 
            return func();
        }
    }
    
    return false;
}

function redirect_ppo() {
    var mode = find_prov_type();

    if (mode == null || mode == undefined)
        return false;

    var url;
    var message;

    if (/^(pcp|specialist)/.test(mode)) {
        url = 'http://www.multiplan.com/search/search-3-Provider.cfm?Originator=84451';
        message = "To find doctors, hospitals and other health care providers in our nationwide partner network, we must send you to the MultiPlan website.\n\nAre you sure you want to continue?";
    }
    else if (/^(hospital|facility)/.test(mode)) {
        url = 'http://www.multiplan.com/search/search-3-Facility.cfm?originator=84451';
        message = "To find doctors, hospitals and other health care providers in our nationwide partner network, we must send you to the MultiPlan website.\n\nAre you sure you want to continue?";
    }
    else if (/^pharmacy/.test(mode)) {
        url = 'http://www.priorityhealth.com/medicationcenter/filling/pharmacy/';
    }

    if (url) location.href = url;

    return false;
}

function find_prov_type() {
    var search_types = $('search-type-form').mode;
    for (var i = 0; i < search_types.length; i++) {
        if (search_types[i].checked) {
            mode = search_types[i].value;
        }
    }

    return mode;
}
