﻿MV.Page.Name = "Provider Search";
MV.Page.Template_Loaded = function() {
    var scCookie = MVCOOKIE.ID;
    $('#searchPage').addClass(getUICode());
};

MV.Page.Content_Loaded = function() {
    //set cookie timer
    var d2 = new Date();
    var h = 60;
    var s1 = (d2.getHours() * h) + d2.getMinutes();
    $.cookie("MVTimer", s1);

    //read cookie to change texts, logo, fonts, etc....
    var scCookie = MVCOOKIE.ID;
    $('h2.welcomeText').children().addClass(getUICode() + 'Title');
    $('#copyRightId').addClass(getUICode() + 'Copyright' + (isSecurePath() ? 'Secure' : ''));
    $('div.title').bind('click', function() { window.location.reload(); });
    $('#comName').addClass(getUICode());
    $('#welcomeText').addClass(getUICode() + 'Welcome' + (isSecurePath() ? 'Secure' : ''));
};

MV.Page.Setup_Complete = function() {

    MV.Modal.init();

    MV.Page.Templates.Add("ProviderResultRow", "#providerResultRow", true);
    MV.Page.Templates.Add("ProviderResultDisclaimer", "#providerResultDisclaimer", true);
    MV.Page.Templates.Add("ProviderResultSetDisclaimer", "#nationalDisclaimers", true);
    MV.Page.Templates.Add("ProviderResultRowsContainer", "#providerResultRows");
    MV.Page.Templates.Add("ProviderResultTable", "#providerResultTable", true);
    MV.Page.Templates.Add("RequiredFieldset", "#requiredFieldset");
    MV.Page.Templates.Add("OptionalFieldset", "#optionalFieldset");
    MV.Page.Templates.Add("AllFields", "#allFieldsTemplates", true);
    MV.Page.Templates.Add("ValidationError", "#validationErrorMessageTemplate", true);
    MV.Page.Templates.Add("ProviderTypeLink", "#providerTypeLinkTemplate", true);
    MV.Page.Templates.Add("ProviderTypeLinkTitle", "#providerTypeLinkTitleTemplate", true);
    MV.Page.Templates.Add("ProviderTypeLinkContainer", "#providerTypeLinkContainerTemplate", true);
    MV.Page.Templates.Add("RelatedHealthInformationDataRow", "#relatedHealthInformationDataRow", true);
    MV.Page.Templates.Add("RelatedHealthInformation", "#relatedHealthInformation", true);
    MV.Page.Templates.Add("RelatedHealthQuestionDataRow", "#relatedHealthQuestionsDataRow", true);
    MV.Page.Templates.Add("RelatedHealthQuestion", "#relatedHealthQuestions", true);
    MV.Page.Templates.Add("RelatedHealthSection", "#healthInfoContentSectionTemplate", true);
    MV.Page.Templates.Add("DetailProfileOfficeHoursDataRow", "#officeHoursBreakoutRow", true);
    MV.Page.Templates.Add("DetailProfileOfficeHours", "#officeHoursTemplate", true);
    MV.Page.Templates.Add("DetailProfile", "#detailProfileTemplate", true);

    var templates = {
        searchForm: {
            allFields: MV.Page.Templates.AllFields,
            fieldsets: {
                required: MV.Page.Templates.RequiredFieldset.find('ol').empty().end(),
                optional: MV.Page.Templates.OptionalFieldset.find('ol').empty().end()
            },
            validationError: MV.Page.Templates.ValidationError
        },
        dataTable: {
            resultRowsContainer: MV.Page.Templates.ProviderResultRowsContainer,
            resultRow: MV.Page.Templates.ProviderResultRow,
            resultRowDisclaimer: MV.Page.Templates.ProviderResultDisclaimer,
            resultTable: MV.Page.Templates.ProviderResultTable,
            resultSetDisclaimer: MV.Page.Templates.ProviderResultSetDisclaimer
        },
        healthInfo: {
            informationDataRow: MV.Page.Templates.RelatedHealthInformationDataRow,
            informationTable: MV.Page.Templates.RelatedHealthInformation,
            questionDataRow: MV.Page.Templates.RelatedHealthQuestionDataRow,
            questionTable: MV.Page.Templates.RelatedHealthQuestion,
            section: MV.Page.Templates.RelatedHealthSection
        },
        navigation: {
            link: MV.Page.Templates.ProviderTypeLink,
            title: MV.Page.Templates.ProviderTypeLinkTitle,
            container: MV.Page.Templates.ProviderTypeLinkContainer
        },
        detail: {
            profileOfficeHoursDataRow: MV.Page.Templates.DetailProfileOfficeHoursDataRow,
            profileOfficeHours: MV.Page.Templates.DetailProfileOfficeHours,
            profile: MV.Page.Templates.DetailProfile
        }
    };

    MV.EPD.init({
        templates: templates,
        planId: MVCOOKIE.ID,
        planName: MVCOOKIE.PLAN,
        referrer: MVCOOKIE.REFERRER,
        defaultSort: "distance",
        onInitStart: function() { $('#providerTypeForm').addClass('invisible'); },
        onInitComplete: function() {
            MV.Page.Show();
            $(Config.SiteTemplate.TemplateContainerId).removeClass('invisible');
            MV.Modal.add('mvModalNeed', {
                solo: true,
                onShow: function(h) {
                    var content = h.w.find(h.c.target);
                    var title = h.w.find(".jqmnTitle");
                    content.empty();
                    content.append(MV.WebServices.Strings.GetEntry('needToKnowMoreString'));
                    title.html(MV.WebServices.Strings.GetEntry('needToKnowMoreTitle'));
                    $('span.planName').html(MV.EPD.planName);
                    if ($.fn.bgiframe) {
                        h.w.bgiframe();
                    }
                }
            });
            MV.Modal.add('mvModalLearn', {
                solo: true,
                onShow: function(h) {
                    var content = h.w.find(h.c.target);
                    var title = h.w.find(".jqmnTitle");
                    content.empty();
                    content.append(MV.EPD.isNational() ? MV.WebServices.Strings.GetEntry('learnMoreQualityNational') : MV.WebServices.Strings.GetEntry('learnMoreQualityPrimary'));
                    title.html(MV.WebServices.Strings.GetEntry('learnMoreQualityTitle'));
                    $('span.planName').html(MV.EPD.planName);
                    if ($.fn.bgiframe) {
                        h.w.bgiframe();
                    }
                }
            });
            MV.Modal.add('mvNewHealthIssueSearch', {
                solo: true,
                onShow: function(h) {
                    var content = h.w.find(h.c.target);
                    var title = h.w.find(".jqmnTitle");
                    content.empty();
                    content.append(MV.WebServices.Strings.GetEntry('newHealthIssueContent'));
                    title.html(MV.WebServices.Strings.GetEntry('newHealthIssueTitle'));
                    //$('span.planName').html(MV.EPD.planName);
                    if ($.fn.bgiframe) {
                        h.w.bgiframe();
                    }
                    $('select').attr("disabled", "true");
                    $('select').addClass("simpleSelectBoxDisabled");
                },
                onHide: function() {
                    $('select').removeAttr('disabled');
                    $('select').removeClass("simpleSelectBoxDisabled");
                    $('#mvNewHealthIssueSearch').remove();
                }
            });
            $('.modalPopup').live('click', function() {
                MV.Modal.show('mvModalNeed');
            });
            $('#qualityModalPopup').live('click', function() {
                MV.Modal.show('mvModalLearn');
            });


            var firstTime = $.cookie('MVFirstTimeUser');
            if (firstTime == 'true') {
                $('a#practitioner').live('click', function() {
                    if ($.cookie('MVFirstTimeUser') == 'true') {
                        //alert($.cookie('MVFirstTimeUser'));
                        var options = { path: '/', expires: 36500 };
                        $.cookie('MVFirstTimeUser', 'false', options);
                        //alert($.cookie('MVFirstTimeUser'));
                        MV.Modal.show('mvNewHealthIssueSearch');
                    }
                    //alert($.cookie('MVFirstTimeUser'));
                    //                    if ($.fn.bgiframe) {
                    //                        h.w.bgiframe();
                    //                    }
                });
            }
        }
    });

    MV.EPD.registerDataTableSettings({
        resultColsProfile: 'provider',
        resultCols: 'column1,column2,column3,column4',
        disclaimers: {
            overall: MV.WebServices.Strings.GetEntry('nationalDisclaimersOverall'),
            quality: MV.WebServices.Strings.GetEntry('nationalDisclaimersQuality')
        },
        dataTransform: function(d) {
            var dt = {};
            dt.providerid = d.ProviderId + '-viewdetail';
            dt.providername = d.ProviderName;
            dt.groupid = d.GroupID || '';
            dt.recordid = d.RecordID || '';
            dt.phonenumber = d.PhoneNumber;
            dt.distance = d.Distance + ' miles';
            dt.mapurl = d.MapURL;
            dt.mapurlid = d.ProviderId + '-maplocation';
            dt.address = '<li><span>' + d.AddressLine1 + '</span></li>' + ((d.AddressLine2) ? '<li><span>' + d.AddressLine2 + '</span></li>' : '');
            dt.addressTitle = d.AddressLine1 + ' ' + d.AddressLine2;
            dt.city = $.trim(d.City);
            dt.state = d.State;
            dt.zip = d.ZipCode.replace(/(\d{5})(\d{4})/, '$1-$2');
            var specialties = '';
            if (d.Specialties) {
                for (var i = 0; i < d.Specialties.length; i++) {
                    var s = d.Specialties[i];
                    specialties += '<li><span>' + $.trim(s.Name) + '</span></li>';
                }
            }
            dt.specialties = specialties;
            var specialties = '';
            if (d.BoardCertifiedSpecialties) {
                for (var i = 0; i < d.BoardCertifiedSpecialties.length; i++) {
                    var s = d.BoardCertifiedSpecialties[i];
                    specialties += '<li><span>' + $.trim(s.Name) + '</span></li>';
                }
            }
            dt.specialties = dt.specialties + specialties;
            var recog = '';
            if (d.HasRecognitions) recog += '<li class="recognition hasOther" title="' + MV.WebServices.Strings.GetEntry('otherRecogIconHH') + '"><span>Recognized</span></li>';
            if (d.IsAccreditedFacility) recog += '<li class="recognition accredited" title="' + MV.WebServices.Strings.GetEntry('accreditedIconHH') + '"><span>Accredited</span></li>';
            if (d.IsCenterOfExcellence) recog += '<li class="recognition centerOfExcellence" title="' + MV.WebServices.Strings.GetEntry('blueDistinctionIconHH') + '"><span>Blue Choice Center of Excellence</span></li>';
            if (d.IsBoardCertified) recog += '<li class="recognition boardCertified" title="' + MV.WebServices.Strings.GetEntry('boardCertifiedIconHH') + '"><span>Board Certified</span></li>';
            dt.recognitions = recog;
            var qualityData = '';
            if (d.HasQualityData) qualityData += '<li class="recognition quality" title="' + MV.WebServices.Strings.GetEntry('qualityDataIconHH') + '"><span>Has quality data</span></li>';
            if (d.IsSCHospital) qualityData += '<li class="recognition primaryLink" title="' + MV.WebServices.Strings.GetEntry('primaryLinkIconHH') + '"><a href="javascript:void();" id="' + d.ProviderId + '-redirecthospital">Search SC Directory</a></li>'
            dt.qualitydata = qualityData;
            dt.office = d.GroupProviderName || '';
            dt.officeid = d.ProviderId + '-viewofficedetail';
            dt.officeRecordId = d.GroupRecordID;
            dt.disclaimer = d.Disclaimers && d.Disclaimers.length > 0 ? MV.WebServices.Strings.GetEntry('nationalDisclaimer' + d.Disclaimers[0].DisclaimerType) : '';
            dt.productcode = d.Product || '';
            return dt;
        }
    });

    MV.EPD.registerDetailSettings({
        controlFunctions: {
            'practitioner-profile': loadPractitionerProfile,
            'practitioner-admitting': loadAdmitting,
            'office-profile': loadOfficeProfile,
            'office-affiliatedPractitioners': loadAffiliatedPractitioners,
            'hospital-profile': loadOfficeProfile,
            'hospital-medicalServices': loadMedicalServices,
            'hospital-surgicalCare': loadSurgicalCare,
            'hospital-patientExperience': loadPatientExperience,
            'hospital-mortalityReadmissions': loadMortalityReadmissions,
            'hospital-mortalityRates': loadMortalityRates,
            'hospital-utilizationRates': loadUtilizationRates,
            'other-profile': loadPractitionerProfile,
            'other-admitting': loadAdmitting,
            'other-affiliatedPractitioners': loadAffiliatedPractitioners
        }
    });

    MV.EPD.registerValidationRules({

        'productInput': {
            tests: [
                { name: 'exclusiveRequired', events: ['submit'], additionalArgs: ['memberPrefixInput'], message: MV.WebServices.Strings.GetEntry('memberPrefixOrProductError') }
            ]
        },

        'memberPrefixInput': {
            tests: [
                { name: 'exclusiveRequired', events: ['submit'], additionalArgs: ['productInput'], message: MV.WebServices.Strings.GetEntry('memberPrefixOrProductError') }
            ]
        },

        'networkInput': {
            tests: [
                { name: 'required', events: ['submit'], message: MV.WebServices.Strings.GetEntry('networkError') }
            ]
        },

        'milesInput': {
            tests: [
                { name: 'required', events: ['submit'], message: MV.WebServices.Strings.GetEntry('distanceError') },
                { name: 'number', events: ['blur', 'keyup', 'submit'], message: MV.WebServices.Strings.GetEntry('distanceError') }
            ]
        },

        'zipInput': {
            tests: [
                { name: 'location', events: ['submit'], additionalArgs: ['cityInput', 'stateInput'], message: MV.WebServices.Strings.GetEntry('locationError') },
                { name: 'zipCode', events: ['blur, submit'], message: MV.WebServices.Strings.GetEntry('zipError') },
                { name: 'number', events: ['keyup'], message: MV.WebServices.Strings.GetEntry('zipError') }
            ]
        },

        'healthIssueInput': {
            tests: [
                { name: 'required', events: ['blur'], message: 'No Results' }
            ]
        }

    });

    MV.EPD.addListener('onLoadSearchParametersStart', function(b) {

        var wsparams = {
            providerType: '',
            plan: '',
            network: $("#networkInput").val() || '',
            name: loadNameParameter() || '',
            isAcceptingNewPatients: ($('#acceptsNewPatientsInput:input:checked').length > 0) ? true : false,
            gender: loadGenderParameter() || '',
            language: $('#languageInput').val() || '',
            condProcSurgId: loadCondProcSurgId() || '',
            specialtyCategoriesType: $("#specialtyInput").val() || '',
            distance: $("#milesInput").val() || '25',
            city: ($("#cityInput").val() && $("#cityInput").val() != $('#cityInputLabel').text()) ? $("#cityInput").val() : '',
            county: '',
            state: $("#stateInput").val() || '',
            zip: ($("#zipInput").val() && $("#zipInput").val() != $('#zipInputLabel').text()) ? $("#zipInput").val() : '',
            address: ($("#streetInput").val() && $("#streetInput").val() != $('#streetInputLabel').text()) ? $.trim($("#streetInput").val()) : '',
            hospitalAffiliation: $("#hospitalInput").val() || '',
            isBoardCertified: ($('#boardCertifiedInput:input:checked').length > 0) ? true : false,
            isPCP: ($('#primaryCareInput:input:checked').length > 0) ? true : false,
            isBlueDistinctionCenterOfExcellence: ($('#excellenceInput:input:checked').length > 0) ? true : false,
            isInNetwork: false,
            isAccreditedFacility: ($('#accreditedInput:input:checked').length > 0) ? true : false,
            sortBy: 'distance',
            maxRows: '30',
            isInQualityData: ($('#qualityDataInput:input:checked').length > 0) ? true : false,
            prefix: ($("#memberPrefixInput").val() && $("#memberPrefixInput").val() != $('#memberPrefixInputLabel').text()) ? $.trim($("#memberPrefixInput").val()) : '',
            product: $('#productInput').val() || '',
            isNCQARecognition: ($('#ncqaRecognitionInput:input:checked').length > 0) ? true : false,
            isOtherRecognition: ($('#otherRecognitionsInput:input:checked').length > 0) ? true : false
        }

        return wsparams;
    });

    MV.EPD.addListener('onCreateSearchResultsComplete', function(b) {
        if (b.searchparams.city || b.searchparams.state || b.searchparams.address) {
            FormHandler.address.open();
        }
    });

    MV.EPD.addListener('onCreateSearchResultsContentComplete', function(b) {
        ToolTip('#providerResultContainer .hasOther, #providerResultContainer .accredited, #providerResultContainer .centerOfExcellence, #providerResultContainer .boardCertified, #providerResultContainer .quality, #providerResultContainer .primaryLink', '', '', '');
        BindMemberPrefixEvents();
    });

    MV.EPD.addListener("onShowSearchFormStart", function(b) {
        SwitchLandingPageByPType(b.planId, b.providerTypeCode);
    });

    MV.EPD.addListener("onCreateOptionalFieldsComplete", function(b) {
        if (!isSecurePath()) {
            b.find('#qualityDataInputElement').addClass('invisible');
        }
    });

    MV.EPD.addListener('onShowSearchFormComplete', function(b) {
        FormHandler.init({ providerTypeParams: b });
    });

    MV.EPD.addListener('onResetSearchFormStart', function(b) {
        FormHandler.save();
        $('#auxiliaryLinksContainer').addClass('invisible');
    });

    MV.EPD.addListener('onUpdateSearchFormComplete', function(b) {
        FormHandler.update();
        $('.simpleSelectBox').simpleselectbox();
        BindShadowEvents();
        HealthIssueAutoCompleteInit();
        BindMemberPrefixEvents();
        BindValidation();
        BindProviderTypeToolTips();
    });

    MV.EPD.addListener('onCreateDetailPageComplete', function(b) {
        $('div.title').bind('click', function() { window.location.reload(); });
    });

    MV.EPD.addListener('onCloseDetailPageComplete', function(b) {
        HealthIssueAutoCompleteInit();  // the detail is removing the autocomplete event in ie
        BindMemberPrefixEvents();
    });

    MV.EPD.addListener('onProviderSearchEvent', function(b) {
        if (MV.Analytics) {

            var event;
            var eventParams = $.extend({}, b.searchparams);
            var issueLabel = loadCondProcSurgLabel();

            event = new ProviderSearchEvent(eventParams);
            event.SetSecureStatus(isSecurePath());
            event.SetPlanLabel(MV.EPD.applicationSettings.planName);
            event.SetProviderTypeLabel(MV.EPD.getActiveProviderType().name);
            event.SetHealthIssueLabel(issueLabel);
            event.SetSearchConfigurationLabels(MV.EPD.searchInfo.configurationDecorator);

            MV.Analytics.TrackEvent(event);
        }
    });

    MV.EPD.addListener('onExternalLinkClicked', function(b) {
        if (MV.Analytics) {
            var link = new ExternalLinkEvent();
            link.SetUrl(b.url);
            link.SetLabel(b.label);
            MV.Analytics.TrackEvent(link);
        }
    });

    MV.EPD.addListener('onHealthwiseLinkClicked', function(b) {
        if (MV.Analytics) {
            var link = new HealthwiseLinkEvent();
            link.SetConsumerTerm(b.consumerTerm);
            MV.Analytics.TrackEvent(link);
            var link2 = new ExternalLinkEvent();
            link2.SetUrl(b.url);
            link2.SetLabel(b.consumerTerm);
            MV.Analytics.TrackEvent(link2);
        }
    });

    MV.EPD.addListener('onCreateSearchResultsComplete', function(b) {
        var button = $('#searchBackButton').removeClass('invisible');
        button.find('.backButton').click(function() {
            window.location.reload();
        });
    });
};



//** EPD APPLICATION FUNCTIONS **//

function loadPractitionerProfile(event) {
    loadDetail(event, bindProfile);
}


function loadOfficeProfile(event) {
    loadDetail(event, bindProfile, {isOffice: true});
}


function loadAdmitting(event) {
    loadDetail(event, bindAdmitting);
}


function loadAffiliatedPractitioners(event) {
    loadDetail(event, bindAffiliatedPractitioners);
}


function loadMedicalServices(event) {
    loadDetail(event, bindQualityData, {qualityDataType: 'Medical Services'});
}
function loadSurgicalCare(event) {
    loadDetail(event, bindQualityData, {qualityDataType: 'Surgical Care'});
}
function loadPatientExperience(event) {
    loadDetail(event, bindQualityData, { qualityDataType: 'Patient Experience', MeasurementPeriod: MV.WebServices.Strings.GetEntry('measurementPeriodDisclaimer') });
}
function loadMortalityReadmissions(event) {
    loadDetail(event, bindQualityData, {qualityDataType: 'Mortality and Readmissions'});
}
function loadMortalityRates(event) {
    loadDetail(event, bindQualityData, { qualityDataType: 'Mortality Rates' });
}
function loadUtilizationRates(event) {
    loadDetail(event, bindQualityData, { qualityDataType: 'Utilization Rates' });
}



function loadDetail(event, bindingFunction, detailParams) {
    if (!this.global.detailRequestInProgress) {
        this.global.detailRequestInProgress = true;
        MV.Util.BlockUI();

        detailParams = detailParams || {};
        var params = event.data.params;
        var isSame = isLastDetailRequestSame(params);

        var providerType = MV.EPD.getProviderTypeByCode(params.providerTypeCode);
        var networkId = params.networkId;
        if (detailParams && detailParams.isOffice && providerType.config.groupCode) {
            providerType = MV.EPD.getProviderTypeByCode(providerType.config.groupCode);
            if (!providerType.config.isPrimaryTypeForGroup) {
                networkId = null;
            }
        }

        try {
            detailParams.attributes = providerType.detail.attributes;
        } catch (e) {
            this.global.detailRequestInProgress = false;
            MV.WebServices.EPD.GetProfileAttributesWrapper(providerType.config.National, params.planId, providerType.providerTypeCode, null, networkId, function(data) {
                MV.EPD.components.detail.create(MV.EPD.providerTypes[data.Type], data);
                loadDetail(event, bindingFunction, detailParams);
            });
            return;
        }

        if (isSame) {
            var data = getLastDetailRequest();
            bindingFunction(event, data, detailParams);
            MV.EPD.showDetailPage();
            createDetailAuxiliaryLinks(params.providerTypeCode);
            MV.Util.UnBlockUI();
            if (!detailParams.qualityDataType || detailParams.qualityDataType == '') {
                this.global.detailRequestInProgress = false;
            }
        }
        else {
            var isNational = providerType.config.National;
            var wsparams = ['recordId', params.recordId, 
                            'latitude', params.latLng.lat,
                            'longitude', params.latLng.lng,
                            'planId', MV.EPD.getPlanId(),
                            'type', 'Profile'];
            if (isNational) {
                wsparams.push('prefix', params.prefix, 'product', params.product, 'planId',params.planId);
            }

            MV.WebServices.EPD.GetProviderDetailWrapper(isNational, wsparams, function(data) {
                setLastDetailRequest(params, data);
                bindingFunction(event, data, detailParams);
                MV.EPD.showDetailPage();
                MV.Util.UnBlockUI();
                this.global.detailRequestInProgress = false;
                var ptCode = params.providerTypeCode;
                if ('N_P000' == ptCode || 'N_G000' == ptCode || 'N_H000' == ptCode || 'N_F000' == ptCode) {
                    $('#detailAuxilliaryMenu').addClass('invisible');
                }

                createDetailAuxiliaryLinks(ptCode);

                MV.EPD.resizeApplicationViewport();
            });
        }
    }
}

function createDetailAuxiliaryLinks(ptCode) {
    if (isSecurePath()) {
        if ('N_H000' == ptCode) {
            $('#learnMoreLink').addClass('invisible');
            $('#qualityLink,#detailAuxilliaryMenu').removeClass('invisible');
        }

        if ('N_P000' == ptCode || 'N_G000' == ptCode || 'N_F000' == ptCode) {
            $('#learnMoreLink,#detailAuxilliaryMenu').addClass('invisible');
        }
        
        if ('H000' == ptCode) {
            $('#qualityLink').removeClass('invisible');
        }
    }
}

function bindProfile(event, data, detailParams) {

    var params = event.data.params;
    var window = event.data.window;
    var blnPrintDetail = event.data.print;
    var title = window.title.clone();
    var body = window.body.clone();
    var viewport = event.data.viewport;
    var detailAttributes = event.data.detailAttributes;

    var isOffice = detailParams.isOffice;
    var attributes = detailParams.attributes;

    var hoverHelpSelectors = [];

    var providerType = MV.EPD.getProviderTypeByCode(params.providerTypeCode);
    if (isOffice && providerType.config.groupCode) {
        providerType = MV.EPD.getProviderTypeByCode(providerType.config.groupCode);
    }
    var type = providerType.config.controlType;
    var isNationalSearch = providerType.config.National;

    var addressInput = null;
    var addressOutput = null;
    var specialties = null;
	var education = null;
    var languages = null;
    var accreditations = null;
    var otherRecognitions = null;
    var ncqaRecognitions = null;
    var centerOfExcellence = null;
    var name = null;
    var website = null;
    var officeHours = null;
    var mapURL = null;
    var distance = null;
    var isAcceptingNewPatients = null;

    // Address
    var addressData = data;

    if ((type == 'practitioner' && !isNationalSearch) || (type == 'other' && !isNationalSearch)) {
        if (data.Group != null) {
            addressData = data.Group;
        }
    }
    else if (type == 'office') {
        if (isOffice && data.Group != null) {
            addressData = data.Group;
        }
    }

    addressInput = {
        address1: addressData.AddressLine1,
        address2: addressData.AddressLine2,
        city: addressData.City,
        state: addressData.State,
        zip: addressData.ZipCode,
        phone: addressData.PhoneNumber
    }
    distance = addressData.Distance;
    mapURL = addressData.MapURL;

    addressOutput = formatAddress(addressInput);


    // Miscellaneous data
    var miscData = data;
    if (type == 'office') {
        if (isOffice && data.Group != null) {
            miscData = data.Group;
        }
    }

    // Check to see if National data is available
    //miscData.Specialties = (isNationalSearch) ? miscData.NationalSpecialties : miscData.Specialties;
    miscData.Accreditions = (isNationalSearch) ? miscData.NationalAccreditions : miscData.Accreditions;
    miscData.OtherRecognitions = (isNationalSearch) ? miscData.NationalOtherRecognitions : miscData.OtherRecognitions;
    miscData.NCQARecognitions = (isNationalSearch) ? miscData.NationalNCQARecognitions : miscData.NCQARecognitions;
    miscData.CenterOfExcellence = (isNationalSearch) ? miscData.NationalCenterOfExcellence : miscData.CenterOfExcellence;
    miscData.Officehours = (isNationalSearch) ? miscData.NationalOfficehours : miscData.Officehours;
	miscData.Education = (isNationalSearch) ? miscData.NationalEducation : miscData.Education;

    specialties = formatToList(miscData.Specialties, "Name");
    boardCertifiedSpecialties = formatToList(miscData.BoardCertifiedSpecialties, "Name");
    languages = formatToList(miscData.Languages, "Name");
    accreditations = formatToList(miscData.Accreditions);
    otherRecognitions = formatToList(miscData.OtherRecognitions);
    ncqaRecognitions = formatToList(miscData.NCQARecognitions);
    centerOfExcellence = formatToList(miscData.CenterOfExcellence);
    name = miscData.ProviderName;
    website = miscData.WebSiteURL;
    officeHours = miscData.Officehours || miscData.NationalOfficehours;
    isAcceptingNewPatients = miscData.IsAcceptingNewPatients;
	// formatEducation
	education = formatToList(formatEducation(miscData.Education));
    
    var canBeAcceptingNewPatients = true;
    if (detailAttributes) {
        canBeAcceptingNewPatients = detailAttributes.canBeAcceptingNewPatients;
    }

    // Quality Nav
    // prepare the data
    var availableHospitalNav = data.HospitalProfileNav || [];
    var displayHospitalNav = {};
    for (var n = 0, hn = availableHospitalNav.length; n < hn ; n++){
        displayHospitalNav[availableHospitalNav[n].ProfileName] = true;
    }
    
    if (displayHospitalNav['Medical Services']) {
        showHospitalMedicalServices();
    } else {
        hideHospitalMedicalServices();
    }

    if (displayHospitalNav['Surgical Care']) {
        showHospitalSurgicalCare();
    } else {
        hideHospitalSurgicalCare();
    }

    if (displayHospitalNav['Mortality and Readmissions']) {
        showHospitalMortalityAndReadmissions();
    } else {
        hideHospitalMortalityAndReadmissions();
    }

    if (displayHospitalNav['Patient Experience']) {
        showHospitalPatientExperience();
    } else {
        hideHospitalPatientExperience();
    }

    if (displayHospitalNav['Mortality (Death) Rates']) {
        showHospitalMortalityRates();
    } else {
        hideHospitalMortalityRates();
    }

    if (displayHospitalNav['Utilization Rates']) {
        showHospitalUtilizationRates();
    } else {
        hideHospitalUtilizationRates();
    }
    
    // Affiliations
    if (type == 'office') {
        var affiliations = data.Affiliations;
        if (isOffice && data.Group != null) {
            affiliations = data.Group.Affiliations;
        }

        if (affiliationsIncludeType(affiliations, 'P')) {
            showAffiliatedPractitioners(type);
        } else {
            hideAffiliatedPractitioners(type);
        }
    }
    else {
        if (affiliationsIncludeType(data.Affiliations, 'H')) {
            showAdmittingPrivileges(type);
        } else {
            hideAdmittingPrivileges(type);
        }

        if (data.Group != null && affiliationsIncludeType(data.Group.Affiliations, 'P')) {
            showAffiliatedPractitioners('office');
        } else {
            hideAffiliatedPractitioners('office');
        }
    }


    // Board Certified
    if (miscData.BoardCertifications && miscData.BoardCertifications.length == 0) {
        if (miscData.IsBoardCertified == 'N') {
            miscData.BoardCertifications.push("No");
        } else {
            miscData.BoardCertifications.push("Not Applicable");
        }
    }

    if (!miscData.BoardCertifications) {
        miscData.BoardCertifications = [];
        miscData.BoardCertifications.push("Not Applicable");
    }
    var boardCertifications = formatToList(miscData.BoardCertifications);

    var canBeBoardCertified = true;
    if (detailAttributes) {
        canBeBoardCertified = detailAttributes.canBeBoardCertified;
    }


    // Office Nav
    if (type != "office") {
        if (data.Group) {
            showOfficeProfile();
            showOfficeTab();
            if (data.Group.Affiliations != null && data.Group.Affiliations.length == 0) {
                hideAffiliatedPractitioners('office');
            }
        } else {
            hideOfficeProfile();
            hideOfficeTab();
        }
    }


    // Attributes
    for (var i = 0, l = attributes.length; i < l; i++) {
        switch (attributes[i]) {

            case 'acceptingNewPatients':
                if (canBeAcceptingNewPatients) {
                    var acceptingNewPatientsText = miscData.AcceptingNewPatients;
                    if (miscData.IsAcceptingNewPatients && !acceptingNewPatientsText) {
                        acceptingNewPatientsText = "Yes";
                    }

                    if (acceptingNewPatientsText) {
                        body.find('#acceptingNewPatients').html(acceptingNewPatientsText);
                        body.find('#acceptingNewPatientsWrapper').removeClass("invisible");
                    }
                }
                break;

            case 'accreditation':
                if (miscData.Accreditions && miscData.Accreditions.length > 0) {
                    body.find('#accreditation').append(accreditations);
                    body.find('#accreditationWrapper').removeClass("invisible");
                }
                break;

            case 'accreditations':
                if (miscData.Accreditions && miscData.Accreditions.length > 0) {
                    body.find('#accreditations').append(accreditations);
                    body.find('#accreditationsWrapper').removeClass("invisible");
                }
                break;

            case 'blueDistinctionCenterOfExcellence':
                if (miscData.CenterOfExcellence && miscData.CenterOfExcellence.length > 0) {
                    body.find('#blueDistinctionCenterOfExcellence').html(centerOfExcellence);
                    body.find('#blueDistinctionCenterOfExcellenceWrapper').removeClass("invisible");
                }
                break;

            case 'boardCertified':
                if (canBeBoardCertified) {
                    body.find('#boardCertified').html(boardCertifications);
                    body.find('#boardCertifiedWrapper').removeClass("invisible");
                }
                break;

            case 'contentGroupName':
                if (miscData.Group) {
                    body.find('#contentGroupName').html(miscData.Group.ProviderName);
                }
                break;

            case 'contentAddress':
                body.find('#contentAddress1').html(addressOutput.address1);
                if (addressOutput.address2) {
                    body.find('#contentAddress2').html(addressOutput.address2);
                } else {
                    body.find('#contentAddress2Item').remove();
                }
                body.find('#contentCityStateZip').html(addressOutput.cityStateZip);
                break;

            case 'distance':
                if (distance) {
                    body.find('#distance').html(distance);
                    body.find('#distanceWrapper').removeClass("invisible");
                }
                break;

            case 'gender':
                if (miscData.Gender) {
                    body.find('#gender').html(miscData.Gender);
                    body.find('#genderWrapper').removeClass("invisible");
                }
                break;
			case 'education': 
				if (miscData.Education && miscData.Education.length > 0){
					body.find('#education').html(education);
					body.find('#educationWrapper').removeClass("invisible");
				}
				break;
            case 'languages':
                if (miscData.Languages && miscData.Languages.length > 0) {
                    body.find('#languages').html(languages);
                    body.find('#languagesWrapper').removeClass("invisible");
                }
                break;

            case 'mapLink':
                if (mapURL) {
                    var elm = body.find('#mapLink').attr('href', mapURL);
					elm.get(0).onclick = function() { MV.EPD.openWin({ url: mapURL, label: 'Maps and directions' }); return false; };
                    body.find('#mapLinkWrapper').removeClass("invisible");
                }
                break;

            case 'ncqa':
                if (miscData.NCQARecognitions && miscData.NCQARecognitions.length > 0) {
                    body.find('#ncqa').html(ncqaRecognitions);
                    body.find('#ncqaWrapper').removeClass("invisible");
                }
                break;

            case 'officeHours':
                var hasData = formatOfficeHours(officeHours, body.find('#officeHours'));
                if (hasData) {
                    body.find('#officeHoursWrapper').removeClass("invisible");
                }
                break;

            case 'otherRecognitions':
                if (miscData.OtherRecognitions && miscData.OtherRecognitions.length > 0) {
                    body.find('#otherRecognitions').html(otherRecognitions);
                    body.find('#otherRecognitionsWrapper').removeClass("invisible");
                }
                break;

            case 'pcp':
                if (miscData.ProviderPCP) {
                    body.find('#pcp').html(miscData.ProviderPCP);
                    body.find('#pcpWrapper').removeClass("invisible");
                }
                break;

            case 'phone':
                body.find('#phone').html(addressData.PhoneNumber ? 'Phone: ' + addressData.PhoneNumber : '');
                break;

            case 'recognitions':
                if (miscData.OtherRecognitions && miscData.OtherRecognitions.length > 0) {
                    body.find('#recognitions').html(formatToList(miscData.OtherRecognitions));
                    body.find('#recognitionsWrapper').removeClass("invisible");
                }
                break;

            case 'specialties':
                if (miscData.Specialties && miscData.Specialties.length > 0) {
                    body.find('#specialties').html(specialties);
                    body.find('#specialtiesWrapper').removeClass("invisible");
                }
                break;

            case 'boardCertifiedSpecialties':
                if (miscData.BoardCertifiedSpecialties && miscData.BoardCertifiedSpecialties.length > 0) {
                    body.find('#boardCertifiedSpecialties').html(boardCertifiedSpecialties);
                    body.find('#boardCertifiedSpecialtiesWrapper').removeClass("invisible");
                }
                break;

            case 'titleGroupName':
                title.find('#titleGroupName').html(name);
                break;

            case 'titleName':
                title.find('#titleName').html(name);
                break;

            case 'url':
                if (website && website != 'N/A') {
                    var elm = body.find('#url').attr('href', website).html(website);
					elm.get(0).onclick = function() { MV.EPD.openWin({url:website, label: website}); return false; };
                    body.find('#urlWrapper').removeClass("invisible");
                }
                break;
                
            case 'disclaimer':
                if (miscData.Disclaimers && miscData.Disclaimers.length > 0) {
                    body.find('#physicianDisclaimer').html(MV.WebServices.Strings.GetEntry('nationalDisclaimer' + miscData.Disclaimers[0].DisclaimerType));
                    body.find('#physicianDisclaimerWrapper').removeClass("invisible");
                }
                break;

            case 'recognitionDisclaimer':
                if (miscData.Disclaimers && miscData.Disclaimers.length > 0) {
                    body.find('#recognitionsDisclaimer').html(formatToList(miscData.Disclaimers, 'DisclaimerText'));
                    body.find('#recognitionsDisclaimerWrapper').removeClass("invisible");
                }
                break;

            case 'optimalCareMeasure':
                if (miscData.Measures && miscData.Measures.length > 0) {
                    var wrapper = body.find('#optimalCareMeasureWrapper');
                    formatOptimalCareMeasures(wrapper, miscData.Measures);
                    wrapper.removeClass('invisible');
                    hoverHelpSelectors.push('.optimalLabel', '.stateBenchmarkLabel', '.stateAverageLabel', '.dataHoverHelp');
                }
                break;
        }
    }

    if (!blnPrintDetail) {
        MV.EPD.writeDetailContent(params.providerTypeCode, title, body);
        hoverHelpSelectors.push('.listHoverHelp');
        if (hoverHelpSelectors.length > 0) {
            ToolTip(hoverHelpSelectors.join(', '));
        }
    } else {
        MV.EPD.printDetailContent(params.providerTypeCode, title, body);
    }
}


function bindAdmitting(event, data) {
    var params = event.data.params;
    var blnPrintDetail = event.data.print;
    var window = event.data.window;
    var title = window.title.clone();
    var body = window.body.clone();
    var viewport = event.data.viewport;

    var providerType = MV.EPD.getProviderTypeByCode(params.providerTypeCode);
    var hospitalCode = 'H000';
    if (providerType.config.hospitalCode) {
        hospitalCode = providerType.config.hospitalCode;
    }
    var hospitalType = MV.EPD.getProviderTypeByCode(hospitalCode)

    title.find('#titleName').append(data.ProviderName);

    var table = body.find('#admittingContentTable');
    var tableHeader = table.find('thead').clone();
    var tableBody = table.find('tbody');
    var dataRow = body.find('.dataRow').clone();
    tableBody.empty();
    //body.find('.dataRow').get(0).parentNode.removeChild(body.find('.dataRow').get(0));  //.empty breaking ie events

    var affiliations = filterAffiliationsByType(data.Affiliations, 'H');

    if (affiliations && affiliations.length > 0) {
        var currentDataRow;
        var eventData;

        for (var ap in affiliations) {
            eventData = {
                params: {
                    providerId: affiliations[ap].AffiliationID,
                    providerTypeCode: hospitalCode,
                    specialtyCode: null,
                    planId: params.planId,
                    networkId: params.networkId,
                    latLng: params.latLng,
                    groupId: params.groupId,
                    recordId: affiliations[ap].AffiliationRecordID,
                    prefix: params.prefix,
                    product: params.product,
                    isNational: hospitalType.config.National
                },
                window: window,
                viewport: viewport
            }

            currentDataRow = dataRow.clone(true);
            currentDataRow.find('.admittingPrivileges').append(affiliations[ap].Name);
            if (affiliations[ap].Name != 'None')
                currentDataRow.find('.admittingPrivileges').bind('click', eventData, this.providerLinkClicked);
            else currentDataRow.find('.admittingPrivileges').addClass('inactive');
            tableBody.append(currentDataRow);
        }

        tableHeader.removeClass('invisible');
        title.find('#detailHeaderTable').append(tableHeader).removeClass('invisible');
        body.find('#admittingPrivilegesToggle').click(function() { tableBody.toggleClass('invisible'); });
    }

    if (!blnPrintDetail) {
        MV.EPD.writeDetailContent(params.providerTypeCode, title, body);
    } else {
        MV.EPD.printDetailContent(params.providerTypeCode, title, body);
    }
}


function bindAffiliatedPractitioners(event, data) {
    var params = event.data.params;
    var window = event.data.window;
    var blnPrintDetail = event.data.print;
    var title = window.title.clone();
    var body = window.body.clone();
    var viewport = event.data.viewport;

    if (data) {
        if (data.Group != null) {
            data = data.Group;
        }

        var wasGroupSearch = false;
        var lastSearchParameters = MV.EPD.searchInfo.lastSearchParameters;
        var lastSearchProviderType = MV.EPD.getProviderTypeByCode(lastSearchParameters.providerType);
        if (lastSearchProviderType.config.providerCode) {
            wasGroupSearch = true;
        }

        var providerTypeCode = params.providerTypeCode;
        var providerType = MV.EPD.getProviderTypeByCode(providerTypeCode);
        if (providerType.config.providerCode) {
            if (lastSearchParameters.providerType != providerTypeCode) {
                providerTypeCode = lastSearchParameters.providerType;
            } else {
                providerTypeCode = providerType.config.providerCode;
            }
            providerType = MV.EPD.getProviderTypeByCode(providerTypeCode);
        }

        title.find('#titleGroupName').append(data.ProviderName);

        var addressInput = {
            address1: data.AddressLine1,
            address2: data.AddressLine2,
            city: data.City,
            state: data.State,
            zip: data.ZipCode
        }
        var addressData = formatAddress(addressInput);

        title.find('#titleAddress1').append(addressData.address1);
        title.find('#titleAddress2').append(addressData.address2);
        title.find('#titleCityStateZip').append(addressData.cityStateZip);

        var table = body.find('#affiliatedPractitionersContentTable').addClass('twoColumn');
        var tableHeader = table.find('thead').clone();
        var tableBody = table.find('tbody');
        var dataRow = body.find('.dataRow').clone();
        tableBody.empty();

        var affiliations = data.Affiliations;

        if (affiliations && affiliations.length > 0) {

            var that = this;
            var addAffiliation = function addAffiliation(affiliation) {
                var eventData = {
                    params: {
                        providerId: affiliation.AffiliationID,
                        providerTypeCode: providerTypeCode,
                        specialtyCode: wasGroupSearch ? null : lastSearchParameters.specialtyCategoriesType,
                        planId: lastSearchParameters.plan,
                        networkId: wasGroupSearch ? null : lastSearchParameters.network,
                        latLng: params.latLng,
                        groupId: params.groupId,
                        recordId: affiliation.AffiliationRecordID,
                        prefix: params.prefix,
                        product: params.product,
                        isNational: providerType.config.National
                    },
                    window: window,
                    viewport: viewport
                };
                var currentDataRow = dataRow.clone(true);
                currentDataRow.find('.affiliateLink').append(affiliation.Name).bind('click', eventData, that.providerLinkClicked);
                currentDataRow.find('.specialtyName').append(formatToList(affiliation.Specialties, "Name"));
                tableBody.append(currentDataRow);
            };

            for (var i = 0, l = affiliations.length; i < l; i++) {
                var affiliation = affiliations[i];
                if (affiliationMatchesType(affiliation, 'P')) {
                    MV.Queue.Add('affiliatedPractitioners', addAffiliation, affiliation);
                }
            }
            if (MV.Queue.Q['affiliatedPractitioners']) { MV.Queue.Execute('affiliatedPractitioners', 0, 0) };
            
            

            tableHeader.removeClass('invisible');
            title.find('#detailHeaderTable').append(tableHeader).removeClass('invisible').addClass('twoColumn');
        }
    }

    if (!blnPrintDetail) {
        MV.EPD.writeDetailContent(params.providerTypeCode, title, body);
    } else {
        MV.EPD.printDetailContent(params.providerTypeCode, title, body);
    }
    $("#specialtyTitle").html(MV.WebServices.Strings.GetEntry('specialty'));
    $("#affiliated").html(MV.WebServices.Strings.GetEntry('affiliated'));
}


function bindQualityData(event, data, detailParams) {
    var _global = this.global;
    var params = event.data.params;
    var blnPrintDetail = event.data.print;
    var window = event.data.window;
    var title = window.title.clone();
    var body = window.body.clone();

    _global.detailRequestInProgress = true;

    if (data.Measures && data.Measures.length == 0 
            && detailParams.qualityDataType != 'Patient Experience'
            && detailParams.qualityDataType != 'Utilization Rates'
            && detailParams.qualityDataType != 'Mortality Rates'
            ) {
        _global.detailRequestInProgress = false;
        return;
    }

    if ($('#' + event.data.controlId).closest('li').hasClass('invisible')) {
        _global.detailRequestInProgress = false;
        return;
    }

    if (blnPrintDetail) {
        _global.detailRequestInProgress = false;
    }

    title.find('#titleGroupName').append(data.ProviderName);

    var addressInput = {
        address1: data.AddressLine1,
        address2: data.AddressLine2,
        city: data.City,
        state: data.State,
        zip: data.ZipCode
    }
    var addressData = formatAddress(addressInput);
    
    title.find('#titleAddress1').append(addressData.address1);
    title.find('#titleAddress2').append(addressData.address2);
    title.find('#titleCityStateZip').append(addressData.cityStateZip);

    var providerType = MV.EPD.getProviderTypeByCode(params.providerTypeCode);
    var isNational = providerType.config.National;

    var headingConfig = isNational ? EPDConfig.qualityDataTables.headings.national : EPDConfig.qualityDataTables.headings.primary;
    var typeConfig = EPDConfig.qualityDataTables.types[detailParams.qualityDataType];

    var wsparams = [
        'Id', (detailParams.qualityDataType == 'Patient Experience') ? data.ProviderId : data.MedicareId || data.ProviderId,
        'Type', detailParams.qualityDataType,
        'State', data.State,
        'ProviderType', params.providerTypeCode,
        'PlanId', data.Plan,
        'Network', data.Network,
        'RecordId', isNational && params.recordId ? params.recordId : null,
        'Latitude', isNational && params.latLng.lat ? params.latLng.lat : 1,
        'Longitude', isNational && params.latLng.lng ? params.latLng.lat : 1,
        'Product', isNational && params.product ? params.product : null,
        'Prefix', isNational && params.prefix ? params.prefix : null,
        'IdType', isNational ? 'ProviderId' : 'MedicareId',
    ];

    MV.WebServices.EPD.GetProviderQualityData(wsparams, function(data) {

        var footnoteLink = body.find('.footnote').clone();
        var titleTable = title.find('#qualityDataContentHeaderTable').addClass(typeConfig.columnProfile);
        var titleTableHead = titleTable.find('thead');
        var titleTableHeadRow = titleTableHead.find('tr').clone();
        var table = body.find('#qualityDataContentTable').addClass(typeConfig.columnProfile);
        var tableHeader = table.find('thead');
        var tableBody = table.find('tbody');
        var subheadingRow = tableBody.find('.subheadingRow').clone();
        var dataRow = tableBody.find('.dataRow').clone();
        var disclaimerText = body.find('.disclaimer').clone();
        body.find('.disclaimer').remove();

        titleTableHead.empty();
        titleTableHead.append(titleTableHeadRow.clone(true).addClass('invisible'));

        tableBody.empty();
        tableBody.append(subheadingRow.clone(true).addClass('invisible')); //fix ie
        tableBody.append(dataRow.clone(true).addClass('invisible')); //fix ie

        var hoverHelpSelectors = [];

        var startDate = null;
        var endDate = null;

        var navConfigLinks = providerType.detail.navs[0].Links;
        var qualityDataLabel = null;
        for (var i = 0, l = navConfigLinks.length; i < l; i++) {
            if (navConfigLinks[i].Id == detailParams.qualityDataType) {
                qualityDataLabel = navConfigLinks[i].Label;
                break;
            }
        }

        if (qualityDataLabel) {
            body.find('.qualityDataLabel').append(qualityDataLabel);
            title.find('.qualityDataLabel').append(qualityDataLabel);
        }

        var columns = (isNational && typeConfig.nationalColumns) ? typeConfig.nationalColumns : typeConfig.columns;

        var currentHeader = titleTableHeadRow.clone(true);
        for (var i = 0, l = columns.length; i < l; i++) {
            var columnIndex = i;
            var column = columns[i];
            var heading = headingConfig[column.Name].label;
            var hover = headingConfig[column.Name].hoverHelp;

            var titleLabel = currentHeader.find('.qualityColumn' + columnIndex + 'Label');
            var bodyLabel = body.find('.qualityColumn' + columnIndex + 'Label');

            titleLabel.append(heading);
            bodyLabel.append(heading);


            if (hover) {
                titleLabel.attr('mvtitle', hover); // for ie we need to use expando element
                bodyLabel.attr('mvtitle', hover);
            }
        }

        titleTableHead.append(currentHeader);

        var renderQualityData = function renderQualityData(qualityData, level) {
            var counter = 1;
            for (var i = 0, l = qualityData.length; i < l; i++) {
                var qData = qualityData[i];
                var currentDataRow;
                var zebra = (counter % 2 == 0) ? 'even' : 'odd';
                counter = counter + 1;
                if (qData.IsHeader || qData.Children && qData.Children.length > 0) {
                    counter = 1;
                    currentDataRow = subheadingRow.clone(true);
                } else {
                    currentDataRow = dataRow.clone(true).addClass(zebra);
                }

                if (!startDate && !endDate && qData.StartDate && qData.EndDate) {
                    startDate = qData.StartDate;
                    endDate = qData.EndDate;
                }

                var name = currentDataRow.find('.qualityName');
                name.append(qData.DisplayName);
                if (qData.HoverHelp) {
                    name.attr('mvtitle', qData.HoverHelp); // for ie we need to use expando element
                }

                for (var j = 0, m = columns.length; j < m; j++) {
                    var columnIndex = j;
                    var column = columns[j];

                    var dataCell = currentDataRow.find('.data' + columnIndex);

                    if (qData[column.Name]) {
                        if (qData[column.Name] < -1) {
                            dataCell.parent().addClass('icons');
                        }
                        var cellVal;
                        switch (column.DataType) {
                            case 'percent':
                                cellVal = formatPercentage(qData[column.Name]);
                                break;
                            case 'decimal':
                                cellVal = formatDecimal(qData[column.Name]);
                                break;
                            case 'string':
                                cellVal = formatString(qData[column.Name]);
                                break;
                            case 'integer':
                                cellVal = formatInteger(qData[column.Name]);
                                break;
                            default:
                                cellVal = qData[column.Name];
                                break;
                        }
                        dataCell.append(cellVal);
                    }
                    else if (!qData.IsHeader && column.Name == "HospitalScore") {
                        dataCell.append("-");
                    }

                    if (qData.FootNoteText && column.Name == "HospitalScore" && !qData.IsHeader) {
                        var currentFootnote = footnoteLink.clone(true);
                        var footNoteArr = qData.FootNoteText.split("|");
                        if (qData[column.Name] < 0) { currentFootnote.attr('class', 'dataHoverHelpFootnote'); }
                        currentFootnote.append(footNoteArr[0]);
                        currentFootnote.attr('mvTitle', footNoteArr[1]);
                        currentFootnote.removeClass('invisible');
                        dataCell.append(currentFootnote);
                    }
                }

                tableBody.append(currentDataRow);

                if (qData.Children) {
                    renderQualityData(qData.Children, level + 1);
                }
            }
        }

        renderQualityData(data.Measures, 0);

        if (data.HCHAPSReportingPeriod || detailParams.MeasurementPeriod) {
            var temp = disclaimerText.clone(true);
            var val = data.HCHAPSReportingPeriod || detailParams.MeasurementPeriod;
            temp.find('.qualityDisclaimer').append(val).removeClass('invisible');
            tableBody.append(temp);
        }

        if (startDate && endDate) {
            title.find('#measurementPeriod').append(startDate + ' - ' + endDate);
            body.find('#measurementPeriodPrint').append(startDate + ' - ' + endDate);
            body.find('#qualityDataMeasurementPeriodPrint .measurementPeriodLabel').append(MV.WebServices.Strings.GetEntry('measurementPeriodLabel'));
            title.find('#qualityDataMeasurementPeriod').removeClass('invisible');
        }
        _global.detailRequestInProgress = false;

        if (!blnPrintDetail) {
            MV.EPD.writeDetailContent(params.providerTypeCode, title, body);
            //hoverHelpSelectors.push('.footnote', '.qualityName', '.dataHoverHelpFootnote');
            //ToolTip(hoverHelpSelectors.join(', '), 'tooltipExtra', null, null);
            //ToolTip('.dataHoverHelp', 'tooltipExtra', -55, null);
            //ToolTip('.dataToolTip, .qualityColumn3Label', 'tooltipExtra', null, null);
            MV.EPD.resizeApplicationViewportHelper('articleDetail');
            $('#detailContent').mouseover(detailMouseEventDelegation).mouseout(detailMouseEventDelegation); //fix ie
        } else {
            $('#printDetailFooter').removeClass('invisible');
            MV.EPD.printDetailContent(params.providerTypeCode, title, body);
        }
    });
}

function detailMouseEventDelegation(e){
	var targ = e.target;
	var $targ = $(targ);
	var type = e.type;
	var out = false;
	
	var leftOffset = ($targ.hasClass('dataHoverHelp') || ($targ.parent().length > 0 && $targ.parent().hasClass('dataHoverHelp')) ) ? -55 : null
	
	if (type == 'mouseout'){
		out = true;
	}
	
	if (window.$lastTarg) {
		window.$lastTarg.tooltipFireHide();
		window.$lastTarg = '';
	}
	
	if ($targ.attr('mvtitle')) {
		$targ.attr('title',$targ.attr('mvtitle'));
		$targ.removeAttr('mvtitle');
		ToolTip(targ, 'tooltipExtra', leftOffset, null);
		$targ.attr('manualFire', 'true');
	}
	
	if ($targ.attr('manualFire') && !out){
		window.$lastTarg = $targ;
		$targ.tooltipFireSave();
	}
}

function hideAffiliatedPractitioners(type) {
    $('#' + type + '-affiliatedPractitioners').addClass('invisible');
}

function hideAdmittingPrivileges(type) {
    $('#' + type + '-admitting').addClass('invisible');
}

function hideOfficeProfile() {
    $('#office-profile').addClass('invisible');
}

function hideOfficeTab() {
    $('#office').addClass('invisible');
}

function showAffiliatedPractitioners(type) {
    $('#' + type + '-affiliatedPractitioners').removeClass('invisible');
}

function showAdmittingPrivileges(type) {
    $('#' + type + '-admitting').removeClass('invisible');
}

function showHospitalSurgicalCare() {
    $('#hospital-surgicalCare').closest('li').removeClass('invisible');
};

function hideHospitalSurgicalCare() {
    $('#hospital-surgicalCare').closest('li').addClass('invisible');
};

function showHospitalMortalityAndReadmissions() {
    $('#hospital-mortalityReadmissions').closest('li').removeClass('invisible');
};

function hideHospitalMortalityAndReadmissions() {
    $('#hospital-mortalityReadmissions').closest('li').addClass('invisible');
};

function showHospitalPatientExperience() {
    $('#hospital-patientExperience').closest('li').removeClass('invisible');
};

function hideHospitalPatientExperience() {
    $('#hospital-patientExperience').closest('li').addClass('invisible');
};

function showHospitalMedicalServices() {
    $('#hospital-medicalServices').closest('li').removeClass('invisible');
};

function hideHospitalMedicalServices() {
    $('#hospital-medicalServices').closest('li').addClass('invisible');
};

function showHospitalMortalityRates() {
    $('#hospital-mortalityRates').closest('li').removeClass('invisible');
};

function hideHospitalMortalityRates() {
    $('#hospital-mortalityRates').closest('li').addClass('invisible');
};

function showHospitalUtilizationRates() {
    $('#hospital-utilizationRates').closest('li').removeClass('invisible');
};

function hideHospitalUtilizationRates() {
    $('#hospital-utilizationRates').closest('li').addClass('invisible');
};


function showOfficeProfile() {
    $('#office-profile').removeClass('invisible');
}

function showOfficeTab() {
    $('#office').removeClass('invisible');
}

function providerLinkClicked(e) {
    var params = e.data.params;
    // make sure the target is actually a link, ie is adding this event to an input for some reason
    if (e.target.tagName.toUpperCase() == 'A') {
        MV.WebServices.EPD.GetProfileAttributesWrapper(params.isNational, params.planId, params.providerTypeCode, params.specialtyCode, params.networkId, function(data) {
            MV.EPD.components.detail.create(MV.EPD.providerTypes[data.Type], data);
            MV.EPD.createDetailPage(params);
        });
    }
}


function affiliationsIncludeType(affiliations, type) {
    if (!affiliations || !type) {
        return false;
    }

    for (var i = 0, l = affiliations.length; i < l; i++) {
        var affiliation = affiliations[i];
        if (affiliationMatchesType(affiliation, type)) {
            return true;
        }
    }

    return false;
}


function filterAffiliationsByType(affiliations, type) {
    if (!affiliations || !type) {
        return null;
    }

    var filteredAffiliations = [];
    for (var i = 0, l = affiliations.length; i < l; i++) {
        var affiliation = affiliations[i];
        if (affiliationMatchesType(affiliation, type)) {
            filteredAffiliations.push(affiliation);
        }
    }

    return (filteredAffiliations.length > 0) ? filteredAffiliations : null;
}


function affiliationMatchesType(affiliation, type) {
    if (!affiliation) {
        return false;
    }
    return (affiliation.AffiliationType === type);
}


/*
data input param should be in the following format
{
address1:'', address2:'', city:'', state:'', zip:''
}

you will get back an {address1:'', address2:'', cityStateZip:''} object with the title formatting
described in the business rules
*/
function formatAddress(data) {

    var retVal = {
        address1: '',
        address2: '',
        cityStateZip: ''
    }

    retVal.address1 = data.address1;
    if (data.address2) {
        retVal.address2 = data.address2;
    }

    var zip = '';
    if (data.zip) {
        zip = data.zip.replace(/(\d{5})(\d{4})/, '$1-$2');
    }

    retVal.cityStateZip = data.city + ', ' + data.state + ' ' + zip;
    return retVal;
}


function formatPercentage(value) {
    var ret = value;
    if (value <= 1 && value > 0) {
        ret = Math.round(value * 100) + '%';
    }
    if (value > 0 && value <= 100) {
        ret = Math.round(value) + '%';
    }
    if (parseInt(value) < 0) {
        value = parseInt(value);
    }
    if (value < 0) {
		var icon,mvtitle;
		if (!MV.EPD.isNational()) {
			icon = (value == '-9711') ? '<img src="css/images/icon_no_data.gif" width="18" height="18" mvtitle="' + MV.WebServices.Strings.GetEntry(value + 'HoverHelp') + '" />' : '<img src="css/images/icon_insufficient_data.gif" width="18" height="18" mvtitle="' + MV.WebServices.Strings.GetEntry(value + 'HoverHelp') + '" />';
		}else{
			icon = String.fromCharCode(Math.abs(value));
			var mvtitle = 'mvtitle="' + MV.WebServices.Strings.GetEntry(value + 'HoverHelp') + '"';
		}
        ret = $('<span class="dataHoverHelp" '+mvtitle+'>' + icon + '</span>');
    }
    return ret;
}

function formatDecimal(value) {
    var ret = value;

    if (value < 0) {
        var icon, mvtitle;
        if (!MV.EPD.isNational()) {
            icon = (value === '-9711') ? '<img src="css/images/icon_no_data.gif" width="18" height="18" mvtitle="' + MV.WebServices.Strings.GetEntry(value + 'HoverHelp') + '" />' : '<img src="css/images/icon_insufficient_data.gif" width="18" height="18" mvtitle="' + MV.WebServices.Strings.GetEntry(value + 'HoverHelp') + '" />';
        } else {
            icon = String.fromCharCode(Math.abs(value));
            var mvtitle = 'mvtitle="' + MV.WebServices.Strings.GetEntry(value + 'HoverHelp') + '"';
        }
        ret = $('<span class="dataHoverHelp" ' + mvtitle + '>' + icon + '</span>');
    }
    return ret;
}

function formatInteger(value) {
    var ret = value;

    if (value < 0) {
        var icon, mvtitle;
        if (!MV.EPD.isNational()) {
            icon = (value === '-9711') ? '<img src="css/images/icon_no_data.gif" width="18" height="18" mvtitle="' + MV.WebServices.Strings.GetEntry(value + 'HoverHelp') + '" />' : '<img src="css/images/icon_insufficient_data.gif" width="18" height="18" mvtitle="' + MV.WebServices.Strings.GetEntry(value + 'HoverHelp') + '" />';
        } else {
            icon = String.fromCharCode(Math.abs(value));
            var mvtitle = 'mvtitle="' + MV.WebServices.Strings.GetEntry(value + 'HoverHelp') + '"';
        }
        ret = $('<span class="dataHoverHelp" ' + mvtitle + '>' + icon + '</span>');
    }

    var stringIcon = translateToStringIcon(value);

    return stringIcon || ret;
}

function formatString(value) {
    var ret = value;
    var icon;

    if (value < 0) {
        var mvtitle;
        if (!MV.EPD.isNational()) {
            icon = (value === '-9711') ? '<img src="css/images/icon_no_data.gif" width="18" height="18" mvtitle="' + MV.WebServices.Strings.GetEntry(value + 'HoverHelp') + '" />' : '<img src="css/images/icon_insufficient_data.gif" width="18" height="18" mvtitle="' + MV.WebServices.Strings.GetEntry(value + 'HoverHelp') + '" />';
        } else {
            icon = String.fromCharCode(Math.abs(value));
            var mvtitle = 'mvtitle="' + MV.WebServices.Strings.GetEntry(value + 'HoverHelp') + '"';
        }
        ret = $('<span class="dataHoverHelp" ' + mvtitle + '>' + icon + '</span>');
    }
    var stringIcon = translateToStringIcon(value);

    return stringIcon || ret;
}

function translateToStringIcon(value) {
    var ret;
    if (value === 'As Expected') {
        icon = '<img src="css/images/icon_as_expected.png" width="62" height="18"/>';
        ret = $(icon);
    }
    return ret;
}

function getUICode() {
    return MVCOOKIE.UICODE.replace(/s$/i, '');
}

function getBaseReferrerCode() {
    return getReferrerCode().replace(/s$/i, '');
}

function getReferrerCode() {
    return MVCOOKIE.REFERRER;
}

function isSecureReferrer() {
    return !!getReferrerCode().match(/S$/);
}

function isSecurePath() {
    var path = window.location.pathname;
    if (path == "/provider_search_bcs.aspx" || path == "/provider_search_scs.aspx" || (path == "/provider_search.aspx" && isSecureReferrer())) {
        return true;
    } else {
        return false;
    }
}

function formatToList(listOfData, attribute) {
    var str = '';
    var suppStr = '';
    if (listOfData) {
        for (var i = 0; i < listOfData.length; i++) {
            var l = listOfData[i];
            var data = attribute ? l[attribute] : l;
            var supText = (typeof data === 'object') ? data.SupDisplayText || data.Name : '';
            var iconURL = MV.WebServices.Strings.GetEntry('iconURLPath') + '/' + $.trim(data.IconFileName);
            var iconLinkURL = data.IconHyperlinkURL && data.IconHyperlinkURL.length > 0 ? 'href="' + $.trim(data.IconHyperlinkURL) + '" onclick="MV.EPD.openWin({url:\'' + $.trim(data.IconHyperlinkURL) + '\',label: \''+data.Name+'\'}); return false;"' : '';
            suppStr = (supText.length > 0) ? '<ul><li><span>'+supText+'</span></li></ul>' : '' ;
            str += (typeof data === 'object' && (data.IconFileName && data.IconFileName.length > 0) ) ? '<li><a title="' + data.IconHyperLinkHoverText + '" class="icon listHoverHelp" ' + iconLinkURL + ' style="background-image: url(' + iconURL + ');" target="_blank"><span title="' + $.trim(data.Name) + '" class="listHoverHelp">' + $.trim(data.Name) + '</span></a>' + suppStr + '</li>' : '<li><span>' + $.trim(data.Name || data) + '</span></li>';
                            
        }
    }
    return str;
}

function formatEducation(data){
	var ar,item;
	if(data){
		ar = [];
		for (var i=0;i<data.length;i++){
			item = data[i];
			ar.push(item.SchoolName + ' ' + item.GradYear);
		}
	}
	return ar;
}


function formatOfficeHours(officeHours, officeHoursTable) {
    var hasData = false;

    var dataRow = officeHoursTable.find('.dataRow');
    var generalRow = officeHoursTable.find('.generalRow');

    if (officeHours) {
        if (officeHours.GeneralHours) {
            dataRow.remove();
            hasData = true;
            generalRow.find('.generalContent').append(officeHours.GeneralHours.replace(';','<br/>'));
        }
        else if (officeHours.Schedule && officeHours.Schedule.length > 0) {
            generalRow.remove();
            var currentDataRow;
            for (var i = 0; i < officeHours.Schedule.length; i++) {
                currentDataRow = dataRow.clone(true);
                var l = officeHours.Schedule[i];
                if (l.BeginTime && l.EndTime) {
                    hasData = true;
                    currentDataRow.find('.dayName').append(l.DayName);
                    currentDataRow.find('.beginTime').append(l.BeginTime);
                    currentDataRow.find('.separator').append(' - ');
                    currentDataRow.find('.endTime').append(l.EndTime);
                }
                else {
                    currentDataRow.find('.dayName').append(l.DayName);
                    currentDataRow.find('.beginTime').append('N/A');
                }
                officeHoursTable.append(currentDataRow);
            }
        }
    }

    if (!hasData) {
        officeHoursTable.addClass('invisible');
    }

    return hasData;
}



function formatOptimalCareMeasures(container, measures) {
    var table = container.find('#optimalMeasures');
    var tableHeader = table.find('thead');
    var tableBody = table.find('tbody');
    var dataRow = table.find('.optimalDataRow').clone();
    tableBody.empty();

    // TODO - generate these headings from the data more.
    var headings = EPDConfig.qualityDataTables.headings.primary;
    tableHeader.find('.stateBenchmarkLabel').attr('title', headings.StateBenchmark.hoverHelp);
    tableHeader.find('.stateAverageLabel').attr('title', headings.StateAverage.hoverHelp);
    var zebra = 1;
    for (var i = 0, l = measures.length; i < l; i++) {
        var measure = measures[i];
        var currentDataRow = dataRow.clone(true);

        var evenOdd = (zebra % 2 == 0) ? 'even' : 'odd';
        currentDataRow.addClass(evenOdd);

        var name = measure.DisplayName.split(/\s*Optimal Care Measure\s*/).join('');

        currentDataRow.find('.optimalLabel').append(name).attr("title", measure.HoverHelp);
        currentDataRow.find('.scoreValue').append(formatPercentage(measure.HospitalScore));
        currentDataRow.find('.benchmarkValue').append(formatPercentage(measure.StateBenchmark));
        currentDataRow.find('.averageValue').append(formatPercentage(measure.StateAverage));
        tableBody.append(currentDataRow);
        zebra += 1;
    }
}



var global = {
    lastDetail: { params: {}, detailData: {} },
    detailRequestInProgress: false
};

function isLastDetailRequestSame(params) {
    var isSame = true;
    for (var param in params) {
        if (this.global.lastDetail.params[param] != params[param])
            isSame = false;
    }
    return isSame;
}

function setLastDetailRequest(params, data) {
    this.global.lastDetail.params = params;
    this.global.lastDetail.detailData = data;
}

function getLastDetailRequest() {
    return this.global.lastDetail.detailData;
}



//** PROVIDER TYPE FORM UTILITIES **//

// todo - move these dropdown functions into FormHandler object
function SetUpDropdowns(params) {
    var sLabel = 'Specialty Category (Choose One)';
    if (params.providerTypeCode == 'P000' ||
        params.providerTypeCode == 'H000' ||
        params.providerTypeCode == 'G000' ||
        params.providerTypeCode == 'NB00') {
        sLabel = 'Specialty Category';
    }

    BindDropDown('#specialtyInput', params.searchConfigurationData.SpecialtyCategoryList, sLabel);
    BindDropDown('#networkInput', params.searchConfigurationData.NetworkList, 'Health Plan', FormHandler.data.network);

    SetUpOptionalDropdowns(params);
    SetDropdownDefaults(params);
    SetDropdownEvents(params);

    var d = FormHandler.data.state;
    window.setTimeout(function() { $('#providerTypeForm').removeClass('invisible'); $('#stateInput').val(d); }, 100);
};

function SetUpOptionalDropdowns(params) {
    var sLabel = 'Specialty Category (Choose One)';
    if (params.providerTypeCode == 'P000' ||
        params.providerTypeCode == 'H000' ||
        params.providerTypeCode == 'G000' ||
        params.providerTypeCode == 'NB00') {
        sLabel = 'Specialty Category';
    }
    BindDropDown('#hospitalInput', params.searchConfigurationData.HosptialFacilityAffliations, 'Admit Privileges Hospital Name');
    BindDropDown('#languageInput', params.searchConfigurationData.LanguageList, 'Other Languages');
    BindDropDown('#stateInput', params.searchConfigurationData.States, 'State', FormHandler.data.state);
    BindDropDown('#productInput', params.searchConfigurationData.ProductList, MV.WebServices.Strings.GetEntry('productInputLabel'), FormHandler.data.product);


    // only refresh the dropdown with data if the specialty dropdown is in the optional fieldset
    if ($('#specialtyInput').closest('.optionalFieldset').length > 0) {
        BindDropDown('#specialtyInput', params.searchConfigurationData.SpecialtyCategoryList, sLabel);
    }
};

function SetDropdownDefaults(scparams) {
    $('.simpleSelectBox').simpleselectbox();
    switch (scparams.providerTypeId) {
        case 'practitioner': case 'grouppractice': case 'hospital':
            // if the network persists no need to disable the specialties
            if (!FormHandler.data.network) {
                $('#specialtyInput').attr("disabled", "true");
                $('#specialtyInputDDIcon').addClass("simpleSelectBoxDisabled");
            }
            break;
        case 'national_practitioner': case 'national_hospital': case 'national_offices': case 'national_otherfacility':
            if (FormHandler.data.memberPrefix && 
                (FormHandler.data.memberPrefix != MV.WebServices.Strings.GetEntry('memberPrefixInputLabel'))) {
                $('#productInput').val('');
                $('#productInput').attr("disabled", "true");
                $('#productInputDDIcon').addClass("simpleSelectBoxDisabled");
            }
            if (FormHandler.data.product &&
                (FormHandler.data.product != MV.WebServices.Strings.GetEntry('productInputLabel'))) {
                var $label = $("#memberPrefixInputLabel");
                $('#memberPrefixInput').val($label.html()).attr('disabled', 'true');
            }
            break;
        default:
            $('#networkInput').attr("disabled", "true");
            $('#networkInputDDIcon').addClass("simpleSelectBoxDisabled");
            break;
    }
};

function SetDropdownEvents(scparams) {
    // bind the events that allow for secondary dropdowns to be powered by selections in the primary dropdown
    // the first 3 provider types have network as the primary, the rest have specialty
    switch (scparams.providerTypeId) {
        case 'practitioner': case 'grouppractice': case 'hospital': case 'national_practitioner': case 'national_offices': case 'national_hospital':case 'national_otherfacility':

            if ($('#networkInput')[0]) {
                $('#networkInput')[0].onchange = function(e) {
                    $('#healthIssueInput').removeAttr('disabled');
                    $('#networkInputDDIcon').removeClass("simpleSelectBoxDisabled");
                    var $label = $("#healthIssueInputLabel");
                    var value = $('#healthIssueInput').val();

                    FormHandler.save();

                    if ($('#networkInput').val() != '') {

                        // populate the specialty drodpown with data
                        MV.WebServices.EPD.GetNetworkAndSubtype(scparams.planId, scparams.providerTypeCode, '', $(this).val(), function(data) {

                            // create the optional fields
                            MV.EPD.updateSearchForm(data.SearchFields);

                            BindDropDown('#specialtyInput', data.SpecialtyCategoryList, 'Specialty Category');
                            if (value == $label.html() || value == '') {
                                $('#specialtyInput').removeAttr("disabled");
                                $('#specialtyInputDDIcon').removeClass("simpleSelectBoxDisabled");
                            } else {
                                $('#specialtyInput').attr("disabled", "true");
                                $('#specialtyInputDDIcon').addClass("simpleSelectBoxDisabled");
                            }
                        });

                    } else {
                        // clear out the optional fields
                        MV.EPD.updateSearchForm([]);
                    }
                };
            };
            if ($('#specialtyInput')[0]) {
                $('#specialtyInput')[0].onchange = function(e) {
                    if ($('#specialtyInput').val() != '') {
                        var $label = $("#healthIssueInputLabel");
                        $('#healthIssueInput').val($label.html()).attr('disabled', 'true');
                    }
                    else {
                        $('#healthIssueInput').removeAttr('disabled');
                    }
                };
            };

            // product dropdown
            if ($('#productInput')[0]) {
                $('#productInput')[0].onchange = function(e) {
                    if ($('#productInput').val() != '') {
                        var $label = $("#memberPrefixInputLabel");
                        $('#memberPrefixInput').val($label.html()).attr('disabled', 'true');
                    }
                    else {
                        $('#memberPrefixInput').removeAttr('disabled');
                    }
                };
            };
            break;

        default:
            if ($('#specialtyInput')[0]) {
                $('#specialtyInput')[0].onchange = function(e) {

                    // check the navigation matrix to see if we need to do any url redirection
                    if (MV.EPD.redirectApplication()) {
                        MV.EPD.createSearchFormSubmitButton();
                        return false;
                    }

                    FormHandler.save();

                    if ($('#specialtyInput').val() != '') {

                        // the network dropdowns have to be reloaded to see if the network persists    
                        MV.WebServices.EPD.GetNetworkAndSubtype(scparams.planId, scparams.providerTypeCode, $(this).val(), '', function(data) {
                            BindDropDown('#networkInput', data.NetworkList, 'Health Plan', FormHandler.data.network);
                            $('#networkInput').removeAttr("disabled");
                            $('#networkInputDDIcon').removeClass("simpleSelectBoxDisabled");
                        });

                        // if the network has persisted, then the optional fields can be loaded
                        if ($('#networkInput').val() != '') {
                            // load the optional fields
                            MV.EPD.createSearchFormOptionalFields(scparams);
                        } else {
                            // clear out the optional fields
                            MV.EPD.updateSearchForm([]);
                        };
                    } else {
                        $('#networkInput').val('');
                        $('#networkInput').attr("disabled", "true");
                        $('#networkInputDDIcon').addClass("simpleSelectBoxDisabled");
                        // clear out the optional fields
                        MV.EPD.updateSearchForm([]);
                    }
                };
            };

            if ($('#networkInput')[0]) {
                $('#networkInput')[0].onchange = function(e) {

                    // check the navigation matrix to see if we need to do any url redirection
                    if (MV.EPD.redirectApplication()) {
                        MV.EPD.createSearchFormSubmitButton();
                        return false;
                    };

                    FormHandler.save();

                    if ($('#networkInput').val() != '') {
                        // load the optional fields
                        MV.EPD.createSearchFormOptionalFields(scparams);
                    } else {
                        // clear out the optional fields
                        MV.EPD.updateSearchForm([]);
                    };
                };
            }            

            // product dropdown
            if ($('#productInput')[0]) {
                $('#productInput')[0].onchange = function(e) {
                    if ($('#productInput').val() != '') {
                        var $label = $("#memberPrefixInputLabel");
                        $('#memberPrefixInput').val($label.html()).attr('disabled', 'true');
                    }
                    else {
                        $('#memberPrefixInput').removeAttr('disabled');
                    }
                };
            };

            break;
    };
}


//** PROVIDER TYPE TEXT INPUTS **//

function SetTextBoxDefaults(providerTypeId) {
    //var nameLabel = (providerTypeId == 'practitioner' || providerTypeId == 'behavioralpractitioners' || providerTypeId == 'national_practitioner') ? MV.WebServices.Strings.GetEntry('lastNameInputLabel') : MV.WebServices.Strings.GetEntry('nameInputLabel');
    //$("#nameInput").val((FormHandler.data.name && FormHandler.data.name != MV.WebServices.Strings.GetEntry('lastNameInputLabel') && FormHandler.data.name != MV.WebServices.Strings.GetEntry('nameInputLabel')) ? FormHandler.data.name : nameLabel);
    //$("#nameInputLabel").html(nameLabel);
	//&& FormHandler.data.name != MV.WebServices.Strings.GetEntry('lastNameInputLabel') && FormHandler.data.name != MV.WebServices.Strings.GetEntry('nameInputLabel')
	$("#nameInput").val((FormHandler.data.name) ? FormHandler.data.name : MV.WebServices.Strings.GetEntry('nameInputLabel'));
	$("#lastNameInput").val((FormHandler.data.lastName) ? FormHandler.data.lastName : MV.WebServices.Strings.GetEntry('lastNameInputLabel'));
    $("#cityInput").val((FormHandler.data.city) ? FormHandler.data.city : MV.WebServices.Strings.GetEntry('cityInputLabel'));
    $("#zipInput").val((FormHandler.data.zip) ? FormHandler.data.zip : MV.WebServices.Strings.GetEntry('zipInputLabel'));
    $("#streetInput").val((FormHandler.data.street) ? FormHandler.data.street : MV.WebServices.Strings.GetEntry('streetInputLabel'));
    $("#healthIssueInput").val(MV.WebServices.Strings.GetEntry('healthIssueInputLabel'));
    $("#milesInput").val((FormHandler.data.radius) ? FormHandler.data.radius : MV.WebServices.Strings.GetEntry('milesInputLabel'));
    $("#memberPrefixInput").val((FormHandler.data.memberPrefix) ? FormHandler.data.memberPrefix : MV.WebServices.Strings.GetEntry('memberPrefixInputLabel'));
};


function BindShadowEvents() {
    var s = $(".mvshadow");
    for (var i = 0; i < s.length; i++) {
        s.get(i).onblur = HandleShadow;
        s.get(i).onclick = HandleShadow;
        s.get(i).onfocus = HandleShadow;
    }
};

function BindValidation() {
    $("#milesInput").get(0).onblur = function(e) { MV.EPD.validateElement('milesInput', 'blur'); }  // ie is not handling even firing correctly
    $("#milesInput").bind('keyup', function(e) { if (e.target.id == "milesInput") { MV.EPD.validateElement('milesInput', 'keyup'); } });
    $("#zipInput").get(0).onblur = function(e) { MV.EPD.validateElement('zipInput','blur'); HandleShadow(e); };    // ie is not handling even firing correctly need this workaround
    $("#zipInput").bind('keyup', function(e) { if (e.target.id == "zipInput") { MV.EPD.validateElement('zipInput', 'keyup'); } });
    
};

function BindProviderTypeToolTips() {
    $('#excellenceLabel').addClass('hover').attr('title', MV.WebServices.Strings.GetEntry('blueDistinctionOptionHH'));
    $('#memberPrefixInput').addClass('hover').attr('title', MV.WebServices.Strings.GetEntry('memberPrefixHH'));
    $('#productInput').addClass('hover').attr('title', MV.WebServices.Strings.GetEntry('productInputHH'));

    if (!$.browser.msie) {
        ToolTip('#providerTypeForm .hover', 'tooltipExtra', null, -55);
    }
};


function HealthIssueAutoCompleteInit() {
    if ($('#healthIssueInput').length > 0 && $('#detailWrapper').length == 0) {
        BindHealthIssueEvents();
        $("#healthIssueInput").autocomplete('/autocomplete.aspx', {
            width: 500,
            scroll: true,
            scrollHeight: 300,
            max: 100,
            multiple: true,
            matchContains: false,
            formatItem: formatResult,
            formatResult: formatResult,
            dataType: 'json',
            cacheLength: 0,
            matchSubset: false,
            parse: parseit,
            minChars: 3,
            afterSuccess: ToolTip('.hiToolTip')
        }).result(function(event, data, formatted) {
            $('#healthIssueInput').val(data.Name);
            $('#hiddenHealthIssueId').val(data.Id + '-' + data.Type.toLowerCase());
        });
    }
};

function BindHealthIssueEvents() {
    $("#healthIssueInput").bind('click blur', function(e) {
        if (e.target.id == "healthIssueInput") {
            var $input = $(e.target);
            var $label = $("#" + $input.attr('id') + "Label");

            // have to blank out the healthinfo hidden field to prepare for next search
            if ($input.val() == $label.html() || $input.val() == '') {
                $('#hiddenHealthIssueId').val('');
            }
            if (e.type == 'blur') {
                if (($input.val() == $label.html() || $input.val() == '') && $('#networkInput').val() != '') {
                    $('#specialtyInput').removeAttr('disabled');
                }
                // triggering event manually in case blur is not firing automatically in ie
                $input.trigger("mv.hideResults");
            }
            if (e.type == 'click') {
                if ($input.val() == $label.html() && $('#networkInput').val() != '') {
                    $('#specialtyInput').val('');
                    $('#specialtyInput').attr("disabled", "true");
                }
            }
        }
    }).bind('keypress', function() {
        var $label = $("#" + $(this).attr('id') + "Label");
        var value = $(this).val();
        $('#specialtyInput').val('');
        $('#specialtyInput').attr("disabled", "true");
        $('#specialtyInputDDIcon').addClass("simpleSelectBoxDisabled");
    });
};

function BindMemberPrefixEvents() {
    $('#memberPrefixInput').bind('click blur', function(e) {
        if (e.target.id == "memberPrefixInput") {
            var $input = $(e.target);
            var $label = $("#" + $input.attr('id') + "Label");
            if (e.type == 'blur') {
                if (($input.val() == $label.html() || $input.val() == '')) {
                    $('#productInput').removeAttr('disabled');
                }
                // triggering event manually in case blur is not firing automatically in ie
                $input.trigger("mv.hideResults");
            }
            if (e.type == 'click') {
				MV.EPD.clearValidationError('memberPrefixInput');
                if ($input.val() == $label.html()) {
                    $('#productInput').val('');
                    $('#productInput').attr("disabled", "true");
                };
            }
        }
    }).bind('keyup', function() {
        var $label = $("#memberPrefixInputLabel");
        var value = $('#memberPrefixInput').val();
		MV.EPD.clearValidationError('memberPrefixInput');
        if (value) {
            $('#productInput').val('');
            $('#productInput').attr("disabled", "true");
            $('#productInputDDIcon').addClass("simpleSelectBoxDisabled");
        } else {
            $('#productInput').removeAttr("disabled");
            $('#productInputDDIcon').removeClass("simpleSelectBoxDisabled");
        }
    });
};


//** AUTOCOMPLETE FORMATTING FUNCTIONS **//


function formatResult(data) {
    if (data) {
        if (data.Description.length > 500) data.Description = data.Description.substr(0, 500) + "...";
        return '<span title="' + data.Description + '" class="hiToolTip ' + data.Type.toLowerCase() + '">' + data.Name + '</span>';
    }

    return false;
};

function parseit(data) {
    var parsed = [];
    
    // force an error message
    if (data && data.length == 0) {
        var $healthInput = $('#healthIssueInput');
        if ($healthInput.length > 0 && $healthInput.val().indexOf("(") < 0) {
            MV.EPD.clearValidationError('healthIssueInput');
            MV.EPD.forceValidationError('healthIssueInput', 'No Results');
            $('#hiddenHealthIssueId').val('0000');
        }
    } else {
        MV.EPD.clearValidationError('healthIssueInput');
        $('#hiddenHealthIssueId').val('');
    }
    
    for (var i = 0; i < data.length; i++) {
        var c = data[i];
        var r = formatResult(c);
        parsed[parsed.length] = {
            data: c,
            value: r,
            result: r
        };
    }

    return parsed;
};

//** Switch Landing page text by plan id and provider type**//
function SwitchLandingPageByPType(planId, pType) {

    $('#directoryListingTab,#healthInfoContentSection,#healthInfoLinkContainer,#healthInfoTab,#resultsSummary,#providerResultHeadTable,#providerResultTable').addClass('invisible');
    $('#directoryListingSection,.welcomeText,.decoration,#auxiliaryLinksContainer').removeClass('invisible');
    //remove sorting arrow cause error in IE6.
    $('#providerResultHeadTable').find('.originalHeaders').children().removeClass('sorted ascending');

    switch(pType)
    {
        case 'N_P000':
        case 'N_H000':
        case 'N_F000':
        case 'N_G000':
            if (!MV.EPD.isNationalAlliance()) {
                var nationalWelcome = (planId == '001') ? MV.WebServices.Strings.GetEntry('nationalSCWelcome') : MV.WebServices.Strings.GetEntry('nationalBCWelcome');
                $('h2.welcomeText').children().empty().append(MV.WebServices.Strings.GetEntry('nationalDir'));
                $('#directoryListingSection').find('#welcomeText').empty().append(nationalWelcome);
            }
            $('#auxiliaryLinksContainer').addClass('invisible');
            break;
        default:
            if (planId == '001') {
                $('h2.welcomeText').children().empty().append(MV.WebServices.Strings.GetEntry('SCTitle'));
                //switch landing based on provider type
                $('#directoryListingSection').find('#welcomeText').empty().append(MV.WebServices.Strings.GetEntry('SCWelcome' + (isSecurePath() ? 'Secure' : '')));
            }
            else{
                $('h2.welcomeText').children().empty().append(MV.WebServices.Strings.GetEntry('BCTitle'));
                //switch landing based on provider type
                $('#directoryListingSection').find('#welcomeText').empty().append(MV.WebServices.Strings.GetEntry('BCWelcome'));                
            }
        break;
    }
}

//** UTILITIES **//

// framework over-ride to remove the blockui default behavior, we are not using it
MV.Util.BlockUI = function() {
    $('body').addClass('wait');
    document.body.style.cursor = 'wait';
};

MV.Util.UnBlockUI = function() {
    $('body').removeClass('wait');
    document.body.style.cursor = 'default';
};
MV.Page.Show = function() {
    MV.Util.UnBlockUI();
    $(Config.SiteTemplate.ContentContainerId).show();
};


function HandleShadow(e) {
    // jquery is not handling the .clone() and events well
    if ($.browser.msie) {
        if (!e) var e = window.event;
        e.target = (e.target) ? e.target : (e.srcElement) ? e.srcElement : '';
    }
    HandleShadowJQuery(e);
};

function HandleShadowJQuery(e) {
    var $input = $("#" + e.target.id);
    var $label = $("#" + e.target.id + "Label");
    $input.addClass("focused");
    if (e.type == 'blur') $input.removeClass("focused");
    if ($input.val() == $label.html()) return $input.addClass("focused").val("");
    if ($input.val() == "" && e.type == 'blur') return $input.removeClass("focused").val($label.html());
};

var FormHandler = {
    providerTypeParams: {},
    data: { zip: null, city: null, street: null, radius: null, state: "", network: null, specialty: null, name: null, product: "", memberPrefix: null },
    init: function(opts) {
        this.address.setUp();
        this.providerTypeParams = opts.providerTypeParams; 
        SetUpDropdowns(this.providerTypeParams);
    },
    save: function(formData) {
        this.data.network = (formData) ? formData.network : $("#networkInput").val();
        this.data.specialty = (formData) ? formData.specialty : $("#specialtyInput").val();
        this.data.zip = (formData) ? formData.zip : $("#zipInput").val();
        this.data.city = (formData) ? formData.city : $("#cityInput").val();
        this.data.street = (formData) ? formData.street : $("#streetInput").val();
        this.data.state = (formData) ? formData.state : $("#stateInput").val();
        this.data.radius = (formData) ? formData.radius : $('#milesInput').val();
        this.data.name = (formData) ? formData.name : (this.data.name && this.data.name != MV.WebServices.Strings.GetEntry('nameInputLabel')) ? this.data.name : $("#nameInput").val();
		this.data.lastName = (formData) ? formData.lastName : (this.data.lastName && this.data.lastName != MV.WebServices.Strings.GetEntry('lastNameInputLabel')) ? this.data.lastName : $("#lastNameInput").val();
        this.data.product = (formData) ? formData.product : $("#productInput").val();
        this.data.memberPrefix = (formData) ? formData.memberPrefix : $("#memberPrefixInput").val();
    },
    update: function() {
        SetTextBoxDefaults(this.providerTypeParams.providerTypeId);
        SetUpOptionalDropdowns(this.providerTypeParams);
        SetDropdownEvents(this.providerTypeParams);
    },
    address: {
        isOpen: false,
        open: function() {
            $('#fullAddressLink').addClass('expanded');
            $('#fullAddressFieldset').removeClass('invisible');
            this.isOpen = true;
        },
        close: function() {
            $('#fullAddressLink').removeClass('expanded');
            $('#fullAddressFieldset').addClass('invisible');
            this.isOpen = false;
        },
        handle: function() {
            $('#fullAddressLink').toggleClass('expanded');
            $('#fullAddressFieldset').toggleClass('invisible');
            this.isOpen = !$('#fullAddressFieldset').hasClass('invisible');
        },
        setUp: function() {
            var that = this;
            $('#fullAddressLink').click(function(e) {
                e.preventDefault();
                that.handle();
            });
            if (this.isOpen) {
                $('#fullAddressLink').addClass('expanded');
                $('#fullAddressFieldset').removeClass('invisible');
            } else {
                $('#fullAddressLink').removeClass('expanded');
                $('#fullAddressFieldset').addClass('invisible');
            }
        }
    }
}

function BindDropDown(selector, data, firstOption, cacheValue) {
    if ($(selector).length > 0) {
        var $dd = $(selector).get(0);
        var selectedIndex = -1;
        $dd.options.length = 0;
        var x = $dd.options.length;
        if (firstOption) {
            // create the padding for ie
            firstOption = firstOption + new Array(60 - firstOption.length).join(' ');
            var fo = document.createElement("option");
            fo.text = firstOption;
            fo.value = '';
            $dd.options[x++] = fo;
        }
        if (data) {
            for (var i = 0; i < data.length; i++) {
                var option = document.createElement("option");
                option.text = data[i].Name || data[i].Key || data[i];
                option.value = data[i].Id || data[i].Code || data[i];
                option.title = data[i].Name || data[i].Key || data[i];
                if (cacheValue && cacheValue == option.value) {
                    selectedIndex = i;
                }
                $dd.options[x++] = option;
            }
            $dd.selectedIndex = selectedIndex + 1;
        }

        return $(selector);
    }
};

function ToolTip(ele, extraClass, left, top) {
    var l = 15;
    if (left) l = left;
    var t = 5;
    if (top) t = top;
    $(ele).tooltip({
        track: false,
        delay: 200,
        showURL: false,
        fixPNG: true,
        top: t,
        left: l,
        extraClass: extraClass,
        excludeTags: ["option"]
    });
};

function loadNameParameter() {
	var selector = $("#nameInput").length > 0 ? '#nameInput' : '#lastNameInput';
	return ($(selector).val() == $(selector+'Label').html()) ? '' : $.trim($(selector).val());
};

function loadGenderParameter() {
    var chks = $('#genderInputElement input:checked');
    if (chks.length == 0 || chks.length == 2) {
        return '';
    } else {
        return $('#genderInputElement input:checked').val();
    }
};

function loadCondProcSurgId() {
    // in case the blur event doesnt fire in IE we need to clear out the hidden field if the value of the textbox is blank or default
    var value = $('#healthIssueInput').val();
    var label = $("#healthIssueInputLabel").html();
    return (value == '' || value == label) ? '' : ($('#hiddenHealthIssueId').val() == '') ? value : $('#hiddenHealthIssueId').val();
};

function loadCondProcSurgLabel() {
    var value = $('#healthIssueInput').val();
    var label = $("#healthIssueInputLabel").html();
    return (value == '' || value == label) ? '' : value;
};

// plugin to handle ie6 dropdowns
// - MV 6/10/2009
jQuery.fn.extend({
    simpleselectbox: function(options) {
        var ddCloneIds = [];

        return this.each(function() {
            if ($.browser.msie) {
                var $select = $(this);
                if ($select.closest('.simpleSelectBoxContainer').length > 0) { return; }
                var o = $(this)
                    .wrap('<div class="simpleSelectBoxContainer"><div id="' + this.id + 'DDOverflow" class="selectContainerOverflow"></div></div>')
                    .closest('.simpleSelectBoxContainer').append('<img id="' + this.id + 'DDIcon" src="css/images/icon_dropdownArrow.png"/>');

                var i = document.getElementById(this.id + 'DDIcon');
                var d = document.getElementById(this.id);
                var o = document.getElementById(this.id + 'DDOverflow');
                ddCloneIds.push(this.id + 'Clone');
                i.onmousedown = function() {
                    if (ddCloneIds.length > 0) {
                        for (var z = 0; z < ddCloneIds.length; z++) {
                            var rc = document.getElementById(ddCloneIds[z]);
                            if (rc) { rc.removeNode(true); }
                        }
                    };

                    i.hasClone = false;
                    if (!i.hasClone) {
                        var e = d.cloneNode(true);
                        e.style.position = 'absolute';
                        e.style.top = $select.offset().top + d.offsetHeight;
                        e.style.left = $select.offset().left;
                        e.onchange = function() {
                            document.getElementById(d.id).selectedIndex = e.selectedIndex;
                            document.getElementById(d.id).fireEvent('onchange');
                            e.removeNode(true);
                            i.hasClone = false;
                        };
                        e.focus();
                        e.onmouseleave = function() {
                            e.removeNode(true);
                            i.hasClone = false;
                            document.body.onclick = null;
                        };
                        e.onblur = function() {
                            document.getElementById(d.id).fireEvent('onchange');
                            e.removeNode(true);
                            i.hasClone = false;
                        };
                        document.body.appendChild(e);
                        document.body.onclick = function() {
                            if (window.event.srcElement.id != i.id) {
                                e.onmouseleave();
                            }
                        };
                        // ie6 doesnt like to set attributes when the element is not in the dom
                        e.setAttribute('size', (e.options.length > 10) ? 10 : e.options.length);
                        e.id = d.id + 'Clone';
                        e.options[d.selectedIndex].setAttribute('selected', true);
                        e.setAttribute('class', 'DDClone');
                        i.hasClone = true;
                    }
                };
                d.onmousedown = function() {
                    var c = document.getElementById(this.id + 'Clone');
                    if (c) { document.body.removeChild(c); i.hasClone = false; }
                };
            } else {
                $(this).addClass('simpleSelectBoxDefault');
            }
        });
    }
});
