Add Failing test

Add Failing test

import module namespace http-client = "http://zorba.io/modules/http-client";
import module namespace request = "http://www.28msec.com/modules/http-request";
import module namespace response = "http://www.28msec.com/modules/http-response";

declare %an:nondeterministic function local:test-concepts($expected as integer, $params as string) as atomic
{
    let $elements as item* := parse-json(http-client:get("http://" || request:server-name() || ":" || request:server-port() || "/v1/_queries/public/api/report-elements.jq?_method=POST" || $params).body.content).ReportElements[]
    let $actual as integer := count($elements)
    let $duplicates := for $element in $elements where $element.CIK instance of array return $element
    return
        if (exists($duplicates)) then
            "false [CIK " || serialize($duplicates[1].CIK, ()) || " is not unique]"
        else if ($actual eq $expected) then
            true
        else
            "false [Actual="||$actual||", Expected="||$expected ||"]"
};

declare %an:nondeterministic function local:test-concepts($expected as integer, $params as string, $body as string) as atomic
{
    let $elements as item* := parse-json(http-client:post("http://" || request:server-name() || ":" || request:server-port() || "/v1/_queries/public/api/report-elements.jq?_method=POST" || $params, $body, "application/x-www-form-urlencoded").body.content).ReportElements[]
    let $actual as integer := count($elements)
    let $duplicates := for $element in $elements where $element.CIK instance of array return $element
    return
        if (exists($duplicates)) then
            "false [CIK " || serialize($duplicates[1].CIK, ()) || " is not unique]"
        else if ($actual eq $expected) then
            true
        else
            "false [Actual="||$actual||", Expected="||$expected ||"]"
};

declare %an:nondeterministic function local:test-200($params as string) as atomic
{
    let $res := http-client:get("http://" || request:server-name() || ":" || request:server-port() || "/v1/_queries/public/api/report-elements.jq?_method=POST" || $params)
    return $res.status eq 200
};

declare %an:sequential function local:check($o as object) as object
{
    if (not(every $k in (keys($o) ! $o.$$) satisfies ($k instance of boolean and $k)))
    then {
            response:status-code(500);
            $o
    } else
            $o
};

local:check({
    all: local:test-concepts(3, "&cik=4962&name=us-gaap:Assets"),
    onlyNames: local:test-concepts(16143, "&tag=DOW30&fiscalYear=2012&fiscalPeriod=FY&onlyNames=true"),
    disclosures: local:test-concepts(1855, "&ticker=ko&fiscalYear=2012&fiscalPeriod=FY&report=Disclosure&concept=disc:ConsolidationVariableInterestEntityPolicy"),
    reportWithNoFilter: local:test-200("report=Disclosures"),
    reportWithNoFilter2: local:test-200("map=Disclosures"),
    disclosures2: local:test-concepts(1855, "&ticker=ko&fiscalYear=2012&fiscalPeriod=FY&report=Disclosure&concept=disc:ConsolidationVariableInterestEntityPolicy", "name=disc%3AAdvertisingBarterTransactionsPolicy&name=disc%3AAdvertisingCostPolicyExpensedAdvertisingCost&name=disc%3AAdvertisingCostsPolicyTextBlock&name=disc%3AAdvertisingCostsPolicyCapitalizedDirectResponseAdvertising&name=disc%3AAgriculturePolicyPolicyTextBlock&name=disc%3AAllocationsToPolicyholdersPolicies&name=disc%3AAllowanceForFundsUsedDuringConstructionPolicy&name=disc%3AAnticipatedInvestmentIncomeAsComponentOfPremiumDeficiencyOnShortDurationContractsPolicy&name=disc%3AAssetRetirementObligationsAndEnvironmentalCostPolicyTextBlock&name=disc%3AAssetRetirementObligationsPolicy&name=disc%3AInterestsContinuedToBeHeldByTransferorInFinancialAssetsThatItHasSecuritizedOrServicingAssetsOrLiabilitiesPolicy&name=disc%3ABasisOfAccountingPolicyPolicyTextBlock&name=disc%3ABusinessCombinationsPolicy&name=disc%3ABusinessCombinationsAndOtherPurchaseOfBusinessTransactionsPolicyTextBlock&name=disc%3ACapitalizationAndAmortizationOfFuelCostsPolicy&name=disc%3ACapitalizationOfInternalCostsPolicy&name=disc%3ACashAndCashEquivalentsPolicyTextBlock&name=disc%3ACashAndCashEquivalentsRestrictedCashAndCashEquivalentsPolicy&name=disc%3ACashAndCashEquivalentsUnrestrictedCashAndCashEquivalentsPolicy&name=disc%3ACertainLoansAndDebtSecuritiesAcquiredInTransferRecognizingInterestIncomeOnImpairedLoansPolicy&name=disc%3ACharityCareDisclosureTextBlock&name=disc%3AClosedBlockAccountingPolicy&name=disc%3ACollaborativeArrangementAccountingPolicy&name=disc%3APurchaseTransactionPolicy&name=disc%3ACommissionsExpensePolicyPolicyTextBlock&name=disc%3ACommissionsPolicy&name=disc%3ACommitmentsAndContingenciesPolicyTextBlock&name=disc%3AComparabilityOfPriorYearFinancialData&name=disc%3ACompensatedAbsencesPolicy&name=disc%3ACompensationRelatedCostsPolicyTextBlock&name=disc%3AComprehensiveIncomePolicyPolicyTextBlock&name=disc%3AConcentrationRiskCreditRisk&name=disc%3AConsolidationPolicyTextBlock&name=disc%3AConsolidationSubsidiariesOrOtherInvestmentsConsolidatedEntitiesPolicy&name=disc%3AConsolidationSubsidiaryStockIssuancesPolicy&name=disc%3AConsolidationVariableInterestEntityPolicy&name=disc%3AConstructionContractorsMethodOfReportingAffiliatedEntitiesPolicyPolicyTextBlock&name=disc%3AConstructionContractorsOperatingCyclePolicyPolicyTextBlock&name=disc%3AConstructionContractorsPolicyPolicyTextBlock&name=disc%3AContingentLiabilityReserveEstimatePolicy&name=disc%3AContinuingCareRetirementCommunitiesAdvanceFeesPolicyPolicyTextBlock&name=disc%3AContinuingCareRetirementCommunitiesObligationsPolicyPolicyTextBlock&name=disc%3AContractualAdjustmentsAndThirdPartySettlementsPolicyPolicyTextBlock&name=disc%3ACooperativeAdvertisingPolicy&name=disc%3ACooperativeInventoryPolicyPolicyTextBlock&name=disc%3ACostMethodInvestmentsPolicy&name=disc%3ACostOfSalesPolicyTextBlock&name=disc%3ACostOfSalesVendorAllowancesPolicy&name=disc%3ACostsAssociatedWithExitOrDisposalActivitiesOrRestructuringsPolicyTextBlock&name=disc%3ACostsAssociatedWithExitOrDisposalActivitiesOrRestructuringsPolicyOngoingBenefitArrangements&name=disc%3ACostsIncurredPolicy&name=disc%3ACreditCardOriginationCostsPolicyTextBlock&name=disc%3ADebtPolicyTextBlock&name=disc%3ADeferredChargesPolicyTextBlock&name=disc%3ACapitalizationOfDeferredPolicyAcquisitionCostsPolicy&name=disc%3ADepositContractsPolicy&name=disc%3ADepreciationDepletionAndAmortizationPolicyTextBlock&name=disc%3ADerivativesEmbeddedDerivatives&name=disc%3ADerivativesHedgeDiscontinuances&name=disc%3ADerivativesHedgeDiscontinuancesAnticipatedTransactions&name=disc%3ADerivativesHedgeDiscontinuancesTerminationOfHedgingInstrumentOrHedgedItem&name=disc%3ADerivativesMethodsOfAccountingNonhedgingDerivatives&name=disc%3ADerivativesMethodsOfAccountingHedgeDocumentation&name=disc%3ADerivativesMethodsOfAccountingHedgeEffectiveness&name=disc%3ADerivativesMethodsOfAccountingHedgingDerivatives&name=disc%3ADerivativesOffsettingFairValueAmountsPolicy&name=disc%3ADerivativesPolicyTextBlock&name=disc%3ADerivativesReportingOfDerivativeActivity&name=disc%3ADeterioratedLoansTransferredInPolicy&name=disc%3ADisallowedCostsForRecentlyCompletedPlantPolicy&name=disc%3ADiscontinuedOperationsPolicyTextBlock&name=disc%3AEarningsPerSharePolicyTextBlock&name=disc%3AEmissionCreditsOrAllowancesPolicy&name=disc%3AEmployeeStockOwnershipPlanESOPPolicy&name=disc%3AEntertainmentEntitiesPolicyPolicyTextBlock&name=disc%3AEnvironmentalCostExpensePolicy&name=disc%3AEnvironmentalCostsCapitalizationPolicy&name=disc%3AEnvironmentalCostsPolicy&name=disc%3AEquityMethodInvestmentsIssuancesPolicy&name=disc%3AEquityMethodInvestmentsPolicy&name=disc%3AEquityAndCostMethodInvestmentsPolicy&name=disc%3AExchangeFeesPolicy&name=disc%3AExchangeMembershipContributedPolicy&name=disc%3AExchangeMembershipWithRightToConductBusinessPolicy&name=disc%3AExchangeMembershipWithRightsOfOwnershipAndToConductBusinessPolicy&name=disc%3AExchangeMembershipsPolicy&name=disc%3AExploitationCostsPolicyPolicyTextBlock&name=disc%3AExploratoryDrillingCostsCapitalizationAndImpairmentPolicy&name=disc%3AExtendedProductWarrantyPolicy&name=disc%3AFairValueMeasurementPolicyPolicyTextBlock&name=disc%3AFairValueTransferPolicyPolicyTextBlock&name=disc%3AFairValueOfFinancialInstrumentsPolicy&name=disc%3AFilmCostsPolicyPolicyTextBlock&name=disc%3AFilmsRevenueRecognitionPolicyPolicyTextBlock&name=disc%3AFinanceLoanAndLeaseReceivablesHeldForInvestmentsForeclosedAssetsPolicy&name=disc%3AFinanceLoanAndLeaseReceivablesHeldForInvestmentAllowanceAndNonperformingLoansAllowancePolicy&name=disc%3AFinanceLoanAndLeaseReceivablesHeldForInvestmentAllowanceAndNonperformingLoansNonperformingLoansPolicy&name=disc%3AFinanceLoanAndLeaseReceivablesHeldForInvestmentAllowanceAndNonperformingLoansPolicy&name=disc%3AFinanceLoanAndLeaseReceivablesHeldForInvestmentPolicy&name=disc%3AFinanceLoanAndLeaseReceivablesHeldForSalePolicy&name=disc%3AFinanceLoansAndLeasesReceivablePolicy&name=disc%3AFinancingReceivableAllowanceForCreditLossesPolicyForUncollectibleAmounts&name=disc%3AFinancingReceivableAllowanceForCreditLossesPolicyOrMethodologyChangePolicyTextBlock&name=disc%3AFiscalPeriod&name=disc%3AFloorBrokeragePolicy&name=disc%3AForeignCurrencyTransactionsAndTranslationsPolicyTextBlock&name=disc%3AFrequentFlierProgramPolicyPolicyTextBlock&name=disc%3AFullCostMethodUsingGrossRevenueMethodPolicy&name=disc%3AFullCostOrSuccessfulEffortsPolicy&name=disc%3AFuturePolicyBenefitsLiabilityPolicy&name=disc%3AGasBalancingArrangementsPolicy&name=disc%3AGasBalancingPolicyPolicyTextBlock&name=disc%3AGoodwillAndIntangibleAssetsGoodwillPolicy&name=disc%3AGoodwillAndIntangibleAssetsIntangibleAssetsIndefiniteLivedPolicy&name=disc%3AGoodwillAndIntangibleAssetsIntangibleAssetsPolicy&name=disc%3AGoodwillAndIntangibleAssetsPolicyTextBlock&name=disc%3AGovernmentContractorsCombiningAndSegmentingPolicyPolicyTextBlock&name=disc%3AGovernmentContractorsCompletedContractPolicyPolicyTextBlock&name=disc%3AGovernmentContractorsContractsInProgressPolicyPolicyTextBlock&name=disc%3AGovernmentContractorsInventoryPolicyPolicyTextBlock&name=disc%3AGovernmentContractorsPolicyPolicyTextBlock&name=disc%3AGovernmentContractorsRevenueRecognitionPolicyPolicyTextBlock&name=disc%3AGovernmentContractorsSubcontractAndSpecialEquipmentCostPolicyPolicyTextBlock&name=disc%3AGrandfatheredESOPExpenseRecognitionPolicy&name=disc%3AGuaranteesIndemnificationsAndWarrantiesPolicies&name=disc%3AHealthCareCostsPolicyPolicyTextBlock&name=disc%3AHealthCareEntitiesPolicyPolicyTextBlock&name=disc%3AHealthCareOrganizationBadDebtsPolicyPolicyTextBlock&name=disc%3AHealthCareOrganizationRevenueRecognizedPolicyPolicyTextBlock&name=disc%3AImpairedFinancingReceivablePolicyPolicyTextBlock&name=disc%3AImpairmentOrDisposalOfLongLivedAssetsIncludingIntangibleAssetsPolicyPolicyTextBlock&name=disc%3AImpairmentOrDisposalOfLongLivedAssetsPolicyTextBlock&name=disc%3AInProcessResearchAndDevelopmentPolicy&name=disc%3AIncentiveDistributionPolicyManagingMemberOrGeneralPartnerDescription&name=disc%3AIncomeTaxUncertaintiesPolicy&name=disc%3AIncomeTaxPolicyTextBlock&name=disc%3AIndustrySpecificPoliciesBrokerDealerTextBlock&name=disc%3AIndustrySpecificPoliciesInsuranceCompaniesTextBlock&name=disc%3AIndustrySpecificPoliciesOilAndGasTextBlock&name=disc%3AInsurancePremiumsRevenueRecognitionPolicy&name=disc%3AIntangibleAssetsArisingFromInsuranceContractsAcquiredInBusinessCombinationPolicyPolicyTextBlock&name=disc%3AIntangibleAssetsFiniteLivedPolicyCostsIncurredToRenewOrExtend&name=disc%3AIntangibleAssetsFiniteLivedPolicy&name=disc%3AIntercompanyProfitToRegulatedAffiliatesPolicy&name=disc%3AInterestCapitalizationPolicyPolicyTextBlock&name=disc%3AInterestCostForPlantConstructionUsingIntermediaryPolicy&name=disc%3AInterestExpenseAllocatedToDiscontinuedOperationsPolicy&name=disc%3AInterestExpenseOnPrepetitionLiabilitiesPolicy&name=disc%3AInterestExpensePolicyTextBlock&name=disc%3AInterestInUnincorporatedJointVenturesOrPartnershipsPolicy&name=disc%3AInternalReplacementsOfInsuranceContractsPolicy&name=disc%3AInternalUseSoftwarePolicy&name=disc%3AInventoryInventoryConsignedToOthersPolicy&name=disc%3AInventoryCostsForContractsOrProgramsPolicy&name=disc%3AInventoryFinishedGoodsPolicy&name=disc%3AInventoryImpairmentPolicy&name=disc%3AInventoryMarkdownsPolicy&name=disc%3AInventoryRawMaterialsPolicy&name=disc%3AInventoryShrinkagePolicy&name=disc%3AInventoryStatedAboveCostPolicy&name=disc%3AInventorySuppliesPolicy&name=disc%3AInventoryWorkInProcessPolicy&name=disc%3AInventoryCashFlowPolicy&name=disc%3AInventoryInterestCapitalizationPolicy&name=disc%3AInventoryMajorClassesPolicy&name=disc%3AInventoryPolicyTextBlock&name=disc%3AInventoryRealEstatePolicy&name=disc%3AInvestmentBankingFeesPolicy&name=disc%3AInvestmentPolicyTextBlock&name=disc%3ALandUnderOptionArrangementsPolicy&name=disc%3ALeasePolicyTextBlock&name=disc%3ALegalCostsPolicyTextBlock&name=disc%3ALiabilityReserveEstimatePolicy&name=disc%3ALifeSettlementContractsPolicy&name=disc%3ALiquidityDisclosureTextBlock&name=disc%3ALoanCommitmentsPolicy&name=disc%3ALoansAndLeasesReceivableAllowanceForLoanLossesPolicy&name=disc%3ALoansAndLeasesReceivableLeaseFinancingPolicy&name=disc%3ALoansAndLeasesReceivableMortgageBankingActivitiesPolicy&name=disc%3ALoansAndLeasesReceivableNonaccrualLoanAndLeaseStatusPolicy&name=disc%3ALoansAndLeasesReceivableNonmortgageLoanValuationPolicy&name=disc%3ALoansAndLeasesReceivableNonperformingLoanAndLeasePolicy&name=disc%3ALoansAndLeasesReceivableOriginationFeesDiscountsOrPremiumsAndDirectCostsToAcquireLoansPolicy&name=disc%3ALoansAndLeasesReceivablePastDueStatusPolicy&name=disc%3ALoansAndLeasesReceivablePrepaymentEstimateAssumptionsPolicy&name=disc%3ALoansAndLeasesReceivableRealEstateAcquiredThroughForeclosurePolicy&name=disc%3ALoansAndLeasesReceivableTroubledDebtRestructuringPolicy&name=disc%3ALoansAndLeasesReceivableValuationPolicy&name=disc%3ALongDurationContractsRevenueRecognitionPolicy&name=disc%3ALongDurationContractsPolicy&name=disc%3AMaintenanceCostPolicyPolicyTextBlock&name=disc%3AMajorCustomersPolicyPolicyTextBlock&name=disc%3AMalpracticeLossContingencyPolicy&name=disc%3AManagementAndInvestmentAdvisoryFeesPolicy&name=disc%3AMarketableSecuritiesAvailableForSaleSecuritiesPolicy&name=disc%3AMarketableSecuritiesHeldToMaturitySecuritiesPolicy&name=disc%3AMarketableSecuritiesPolicy&name=disc%3AMarketableSecuritiesTradingSecuritiesPolicy&name=disc%3AMemberOfGroupFilingConsolidatedReturnPolicy&name=disc%3AMinimumGuaranteesPolicy&name=disc%3ANewAccountingPronouncementsPolicyPolicyTextBlock&name=disc%3AOffBalanceSheetCreditExposurePolicyPolicyTextBlock&name=disc%3AOilAndGasPropertiesPolicyPolicyTextBlock&name=disc%3AOutageCostsPolicy&name=disc%3AParticipationCostsPolicyPolicyTextBlock&name=disc%3APensionAndOtherPostretirementPlansNonpensionBenefitsPolicy&name=disc%3APensionAndOtherPostretirementPlansPensionsPolicy&name=disc%3APensionAndOtherPostretirementPlansPolicy&name=disc%3APlantConstructionUsingIntermediaryPolicy&name=disc%3APlantRetirementAndAbandonmentPolicy&name=disc%3APolicyLoansReceivablePolicy&name=disc%3APolicyholderAccountsPolicy&name=disc%3APolicyholdersDividendPolicy&name=disc%3APostemploymentBenefitPlansPolicy&name=disc%3APrecontractCostsPolicyTextBlock&name=disc%3APremiumsReceivableAllowanceForDoubtfulAccountsEstimationMethodologyPolicy&name=disc%3APremiumsReceivableBasisOfAccountingPolicy&name=disc%3APresentValueOfFutureInsuranceProfitsPolicy&name=disc%3APresentationOfUnusedProceedsOfPollutionControlFinancingPolicy&name=disc%3APropertyLiabilityReserveEstimatePolicy&name=disc%3APropertyPlantAndEquipmentImpairment&name=disc%3APropertyPlantAndEquipmentPlannedMajorMaintenanceActivitiesPolicy&name=disc%3APropertyPlantAndEquipmentPolicyTextBlock&name=disc%3APropertyPlantAndEquipmentPreproductionDesignAndDevelopmentCosts&name=disc%3APublicUtilitiesPolicyTextBlock&name=disc%3ARealEstateHeldForDevelopmentAndSalePolicy&name=disc%3ARealEstateOwnedValuationAllowancePolicy&name=disc%3ARealEstatePolicyTextBlock&name=disc%3AReceivablesHeldForSaleDeterminationPolicy&name=disc%3AReceivablesHeldForSaleLowerOfCostOrFairValuePolicy&name=disc%3AReceivablesAndPortionsOfSecuritizationsThatCanBePrepaidAtPotentialLossPolicyPolicyTextBlock&name=disc%3AReceivablesPolicyTextBlock&name=disc%3APriorPeriodReclassificationAdjustmentDescription&name=disc%3ARegulatoryDepreciationAndAmortizationPolicy&name=disc%3ARegulatoryEnvironmentalCostsPolicy&name=disc%3ARegulatoryIncomeTaxesPolicy&name=disc%3AReinsuranceAccountingPolicy&name=disc%3ARepurchaseAgreementsCollateralPolicy&name=disc%3ARepurchaseAgreementsValuationPolicy&name=disc%3ARepurchaseAndResaleAgreementsPolicy&name=disc%3AResearchAndDevelopmentExpensePolicy&name=disc%3AResearchDevelopmentAndComputerSoftwarePolicyTextBlock&name=disc%3ARetailLandSalesPolicyPolicyTextBlock&name=disc%3ARevenueRecognitionAccountingPolicyGrossAndNetRevenueDisclosure&name=disc%3ARevenueRecognitionLeases&name=disc%3ARevenueRecognitionLeasesCapital&name=disc%3ARevenueRecognitionLeasesOperating&name=disc%3ARevenueRecognitionForAlternativeRevenueProgramsPolicy&name=disc%3ARevenueRecognitionFromLongTermPowerSalesContractsPolicy&name=disc%3ARevenueRecognitionAdvertisingBarterTransactions&name=disc%3ARevenueRecognitionAllowances&name=disc%3ARevenueRecognitionBillAndHoldArrangements&name=disc%3ARevenueRecognitionCargoAndFreightPolicyPolicyTextBlock&name=disc%3ARevenueRecognitionCompletedContractMethod&name=disc%3ARevenueRecognitionCustomerAcquisitions&name=disc%3ARevenueRecognitionDeferredRevenue&name=disc%3ARevenueRecognitionDiscounts&name=disc%3ARevenueRecognitionDividends&name=disc%3ARevenueRecognitionGiftCards&name=disc%3ARevenueRecognitionIncentives&name=disc%3ARevenueRecognitionInterest&name=disc%3ARevenueRecognitionLongTermContracts&name=disc%3ARevenueRecognitionLongTermContractsIncentiveAndAwardFees&name=disc%3ARevenueRecognitionLoyaltyPrograms&name=disc%3ARevenueRecognitionMultipleElementArrangements&name=disc%3ARevenueRecognitionPercentageOfCompletionMethod&name=disc%3ARevenueRecognitionPolicyTextBlock&name=disc%3ARevenueRecognitionPremiumsEarnedPolicy&name=disc%3ARevenueRecognitionRealEstateTransactionsPolicy&name=disc%3ARevenueRecognitionRebates&name=disc%3ARevenueRecognitionRegionalCarriersAndPassengersPolicyPolicyTextBlock&name=disc%3ARevenueRecognitionRetailLandSales&name=disc%3ARevenueRecognitionRetrospectiveRateSettingSystemsPolicyPolicyTextBlock&name=disc%3ARevenueRecognitionRevenueReductions&name=disc%3ARevenueRecognitionSalesReturns&name=disc%3ARevenueRecognitionSalesOfGoods&name=disc%3ARevenueRecognitionSalesOfServices&name=disc%3ARevenueRecognitionServicesCommissions&name=disc%3ARevenueRecognitionServicesFranchiseFees&name=disc%3ARevenueRecognitionServicesLicensingFees&name=disc%3ARevenueRecognitionServicesManagementFees&name=disc%3ARevenueRecognitionServicesRefundableFeesForServices&name=disc%3ARevenueRecognitionServicesRoyaltyFees&name=disc%3ARevenueRecognitionSoftware&name=disc%3ARoyaltyTrustDistributableIncomePolicy&name=disc%3ASaleLeasebackTransactionsPolicy&name=disc%3ASalesInducementsToContractHoldersPolicy&name=disc%3ASalesMethodOrEntitlementsMethodPolicy&name=disc%3ASecuritiesBorrowedAndLoanedPolicy&name=disc%3ASecuritiesOwnedNotReadilyMarketablePolicy&name=disc%3ASegmentReportingPolicyPolicyTextBlock&name=disc%3ASelfInsuranceReservePolicyTextBlock&name=disc%3ASellingGeneralAndAdministrativeExpensesPolicyTextBlock&name=disc%3AShareBasedCompensationOptionAndIncentivePlansPolicy&name=disc%3AShareBasedCompensationOptionAndIncentivePlansDirectorPolicy&name=disc%3ASharesSubjectToMandatoryRedemptionChangesInRedemptionValuePolicyTextBlock&name=disc%3AShippingAndHandlingCostPolicyTextBlock&name=disc%3AShortDurationContractsRevenueRecognitionPolicy&name=disc%3AShortDurationContractsPolicy&name=disc%3ASoftwareToBeSoldLeasedOrOtherwiseMarketedPolicy&name=disc%3AStandardProductWarrantyPolicy&name=disc%3AStartUpActivitiesCostPolicy&name=disc%3AStockholdersEquityNoteRedeemablePreferredStockIssuePolicy&name=disc%3AStockholdersEquityPolicyTextBlock&name=disc%3ASubsequentEventsPolicyPolicyTextBlock&name=disc%3ATradeAndLoanReceivablesMethodOfAccountingForReceivablesThatCanBeContractuallyPrepaidPolicyPolicyTextBlock&name=disc%3ATradeAndLoanReceivablesNonmortgageLoansHeldForSalePolicyPolicyTextBlock&name=disc%3ATradeAndOtherAccountsReceivablePolicy&name=disc%3ATradeAndOtherAccountsReceivableUnbilledReceivablesPolicy&name=disc%3ATransfersAndServicingOfFinancialAssetsPolicyTextBlock&name=disc%3ATransfersAndServicingOfFinancialAssetsServicingOfFinancialAssetsPolicy&name=disc%3ATransfersAndServicingOfFinancialAssetsTransfersOfFinancialAssetsAggregationPolicy&name=disc%3ATransfersAndServicingOfFinancialAssetsTransfersOfFinancialAssetsFinancingsPolicy&name=disc%3ATransfersAndServicingOfFinancialAssetsTransfersOfFinancialAssetsPolicy&name=disc%3ATransfersAndServicingOfFinancialAssetsTransfersOfFinancialAssetsSalesPolicy&name=disc%3AUnpaidPolicyClaimsAndClaimsAdjustmentExpensePolicy&name=disc%3AUnremittedEarningsInForeignInvestmentPolicy&name=disc%3AUseOfEstimates&name=disc%3AUtilityRevenueAndExpenseRecognitionPolicy&name=disc%3AAccountingChangesTextBlock&name=disc%3AAccountingChangesAndErrorCorrectionsTextBlock&name=disc%3AAccountingForCertainLoansAndDebtSecuritiesAcquiredInTransferDisclosureTextBlock&name=disc%3AAccountsPayableAndAccruedLiabilitiesDisclosureTextBlock&name=disc%3AAccountsPayableAccruedLiabilitiesAndOtherLiabilitiesDisclosureCurrentTextBlock&name=disc%3AAccountsPayableAccruedLiabilitiesAndOtherLiabilitiesDisclosureNoncurrentTextBlock&name=disc%3AAdditionalFinancialInformationDisclosureTextBlock&name=disc%3AAdvancePaymentsByBorrowersForTaxesAndInsuranceSummary&name=disc%3AAffordableHousingProgramTextBlock&name=disc%3AAgricultureTextBlock&name=disc%3AAllowanceForCreditLossesTextBlock&name=disc%3AAssetImpairmentChargesTextBlock&name=disc%3AAssetRetirementObligationDisclosureTextBlock&name=disc%3AAuctionMarketPreferredSecuritiesDisclosure&name=disc%3ABankingAndThriftDisclosureTextBlock&name=disc%3ABasisOfAccounting&name=disc%3ABasisOfPresentationAndSignificantAccountingPoliciesTextBlock&name=disc%3ABrokersAndDealersDisclosureTextBlock&name=disc%3ABusinessAcquisitionIntegrationRestructuringAndOtherRelatedCostsTextBlock&name=disc%3ABusinessCombinationDisclosureTextBlock&name=disc%3ABusinessDescriptionAndAccountingPoliciesTextBlock&name=disc%3ABusinessDescriptionAndBasisOfPresentationTextBlock&name=disc%3ABusinessInsuranceRecoveriesTextBlock&name=disc%3ABusinessAndContractualArrangementsDisclosureTextBlock&name=disc%3ACapitalLeasesInFinancialStatementsOfLesseeDisclosureTextBlock&name=disc%3ACapitalLeasesInFinancialStatementsOfLessorDisclosureTextBlock&name=disc%3ACapitalRequirementsOnTrustAssetsTextBlock&name=disc%3ACashFlowSupplementalDisclosuresTextBlock&name=disc%3ACashAndCashEquivalentsDisclosureTextBlock&name=disc%3ACashCashEquivalentsAndMarketableSecuritiesTextBlock&name=disc%3ACashCashEquivalentsAndShortTermInvestmentsTextBlock&name=disc%3AClosedBlockDisclosureTextBlock&name=disc%3ACollaborativeArrangementDisclosureTextBlock&name=disc%3ACommitmentsContingenciesAndGuaranteesTextBlock&name=disc%3ACommitmentsDisclosureTextBlock&name=disc%3ACommitmentsAndContingenciesDisclosureTextBlock&name=disc%3ACompensationRelatedCostsGeneralTextBlock&name=disc%3ACompensationAndEmployeeBenefitPlansTextBlock&name=disc%3ACompensationAndEmployeeBenefitPlansOtherThanShareBasedCompensationTextBlock&name=disc%3AComprehensiveIncomeNoteTextBlock&name=disc%3AConcentrationRiskDisclosureTextBlock&name=disc%3ACondensedFinancialInformationOfParentCompanyOnlyDisclosureTextBlock&name=disc%3ACondensedFinancialStatementsTextBlock&name=disc%3ALossContingencyDisclosures&name=disc%3ACostAndEquityMethodInvestmentsDisclosureTextBlock&name=disc%3ACostMethodInvestmentsDescriptionTextBlock&name=disc%3ADebtDisclosureTextBlock&name=disc%3ADebtInstrumentRedemptionTableTextBlock&name=disc%3ADebtAndCapitalLeasesDisclosuresTextBlock&name=disc%3ADeferredPolicyAcquisitionCostsTextBlock1&name=disc%3ADeferredRevenueDisclosureTextBlock&name=disc%3ADepositLiabilitiesDisclosuresTextBlock&name=disc%3ADerecognizedAssetsInformationAboutAssetQualityOfSecuritizedOrAssetbackedFinancingArrangementAssetsAndAnyOtherFinancialAssetsManagedTogetherTextBlock&name=disc%3ADerivativeInstrumentsAndHedgingActivitiesDisclosureTextBlock&name=disc%3ADerivativesAndFairValueTextBlock&name=disc%3ADescriptionOfNewAccountingPronouncementsNotYetAdopted&name=disc%3ADevelopmentStageEnterpriseGeneralDisclosuresTextBlock&name=disc%3ADisclosureOfCompensationRelatedCostsShareBasedPaymentsTextBlock&name=disc%3ADisclosureOfReclassificationAmountTextBlock&name=disc%3ADiscussionOfHybridInstrumentsAndEmbeddedDerivativesTextBlock&name=disc%3ADisposalGroupsIncludingDiscontinuedOperationsDisclosureTextBlock&name=disc%3AScheduleOfDividendPaymentRestrictionsTextBlock&name=disc%3ADueToAndFromBrokerDealersAndClearingOrganizationsDisclosure&name=disc%3AEarningsPerShareTextBlock&name=disc%3AEntertainmentTextBlock&name=disc%3AEnvironmentalLossContingencyDisclosureTextBlock&name=disc%3AEquityMethodInvestmentsDisclosureTextBlock&name=disc%3AExtraordinaryItemsDisclosureTextBlock&name=disc%3AFairValueDisclosuresTextBlock&name=disc%3AFairValueMeasurementInputsDisclosureTextBlock&name=disc%3AFairValueOptionTextBlock&name=disc%3AFederalHomeLoanBankAdvancesDisclosureTextBlock&name=disc%3AFederalHomeLoanBankAdvancesTextBlock&name=disc%3AFinancialGuaranteeInsuranceContractsTextBlock&name=disc%3AFinancialInstrumentsDisclosureTextBlock&name=disc%3AFinancingReceivablesTextBlock&name=disc%3AForeignCurrencyDisclosureTextBlock&name=disc%3AFranchisorsTextBlock&name=disc%3AFullCostMethodOfAccountingForInvestmentsInOilAndGasPropertiesDisclosureTextBlock&name=disc%3AGoodwillDisclosureTextBlock&name=disc%3AGoodwillAndIntangibleAssetsDisclosureTextBlock&name=disc%3AGuaranteesTextBlock&name=disc%3AHealthCareOrganizationsTextBlock&name=disc%3AIncomeTaxDisclosureTextBlock&name=disc%3AInsuranceDisclosureTextBlock&name=disc%3AIntangibleAssetsArisingFromInsuranceContractsAcquiredInBusinessCombinationDisclosuresTextBlock&name=disc%3AIntangibleAssetsDisclosureTextBlock&name=disc%3AInterestIncomeAndInterestExpenseDisclosureTextBlock&name=disc%3AInterestAndOtherIncomeTextBlock&name=disc%3AInventoryDisclosureTextBlock&name=disc%3AInvestmentHoldingsTextBlock&name=disc%3AInvestmentHoldingsScheduleOfInvestmentsTextBlock&name=disc%3AInvestmentsAndOtherNoncurrentAssetsTextBlock&name=disc%3AInvestmentsInDebtAndEquityInstrumentsCashAndCashEquivalentsUnrealizedAndRealizedGainsLossesTextBlock&name=disc%3AInvestmentsInDebtAndMarketableEquitySecuritiesAndCertainTradingAssetsDisclosureTextBlock&name=disc%3AInvestmentsInAndAdvancesToAffiliatesScheduleOfInvestmentsTextBlock&name=disc%3ALeasesOfLesseeDisclosureTextBlock&name=disc%3ALeasesOfLessorDisclosureTextBlock&name=disc%3ALegalMattersAndContingenciesTextBlock&name=disc%3ALiabilityForFuturePolicyBenefitsAndUnpaidClaimsDisclosureTextBlock&name=disc%3ALifeInsuranceCorporateOrBankOwnedTextBlock&name=disc%3ALifeSettlementContractsDisclosureTextBlock&name=disc%3ALiquidationBasisOfAccountingTextBlock&name=disc%3ALoansNotesTradeAndOtherReceivablesDisclosureTextBlock&name=disc%3ALoansNotesTradeAndOtherReceivablesExcludingAllowanceForCreditLossesTextBlock&name=disc%3ALongDurationContractsAssumptionsUnderlyingGuaranteeObligations&name=disc%3ALongDurationInsuranceContractsDisclosureTextBlock&name=disc%3ALongTermContractsOrProgramsDisclosureTextBlock&name=disc%3ALongTermDebtTextBlock&name=disc%3AMalpracticeLossContingencyDisclosureTextBlock&name=disc%3AMembersEquityNotesDisclosureTextBlock&name=disc%3AMergersAcquisitionsAndDispositionsDisclosuresTextBlock&name=disc%3AMineralIndustriesDisclosuresTextBlock&name=disc%3AMinimumGuaranteesNetAmountAtRiskDisclosure&name=disc%3AMortgageLoansOnRealEstateByLoanDisclosureTextBlock&name=disc%3AMortgageNotesPayableDisclosureTextBlock&name=disc%3ANatureOfOperations&name=disc%3ANewAccountingPronouncementsAndChangesInAccountingPrinciplesTextBlock&name=disc%3AMinorityInterestDisclosureTextBlock&name=disc%3ANonmonetaryTransactionsDisclosureTextBlock&name=disc%3AOilAndGasExplorationAndProductionIndustriesDisclosuresTextBlock&name=disc%3AOilAndGasPropertiesTextBlock&name=disc%3AOperatingLeasesOfLessorDisclosureTextBlock&name=disc%3AOptionIndexedToIssuersEquityDescriptionTextBlock&name=disc%3AOrganizationConsolidationAndPresentationOfFinancialStatementsDisclosureTextBlock&name=disc%3AOrganizationConsolidationAndPresentationOfFinancialStatementsDisclosureAndSignificantAccountingPoliciesTextBlock&name=disc%3AOrganizationConsolidationBasisOfPresentationBusinessDescriptionAndAccountingPoliciesTextBlock&name=disc%3AOtherAssetsDisclosureTextBlock&name=disc%3AOtherComprehensiveIncomeNoncontrollingInterestTextBlock&name=disc%3AOtherCurrentAssetsTextBlock&name=disc%3AOtherIncomeAndOtherExpenseDisclosureTextBlock&name=disc%3AOtherLiabilitiesDisclosureTextBlock&name=disc%3AOtherNonoperatingIncomeAndExpenseTextBlock&name=disc%3AOtherOperatingIncomeAndExpenseTextBlock&name=disc%3APartnersCapitalNotesDisclosureTextBlock&name=disc%3APensionAndOtherPostretirementBenefitsDisclosureTextBlock&name=disc%3APostemploymentBenefitsDisclosureTextBlock&name=disc%3APreferredStockTextBlock&name=disc%3APremiumsReceivableNote&name=disc%3APresentValueOfFutureInsuranceProfitsTextBlock&name=disc%3AProductWarrantyDisclosureTextBlock&name=disc%3AProductiveWellsAndAcreageDisclosureTextBlock&name=disc%3APropertyPlantAndEquipmentDisclosureTextBlock&name=disc%3APropertyPlantAndEquipmentAndIntangibleAssetsTextBlock&name=disc%3APublicUtilitiesDisclosureTextBlock&name=disc%3ASignificantPurchaseAndSupplyCommitmentExcludingLongtermCommitmentTextBlock&name=disc%3AQuantitativeInformationAboutAssetQualityOfSecuritizedOrAssetbackedFinancingArrangementAssetsAndAnyOtherFinancialAssetsManagedTogetherTextBlock&name=disc%3AQuarterlyFinancialInformationTextBlock&name=disc%3ARealEstateDisclosureTextBlock&name=disc%3ARealEstateOwnedTextBlock&name=disc%3AReclassifications&name=disc%3ARegulatoryCapitalRequirementsForMortgageCompaniesDisclosureTextBlock&name=disc%3ARegulatoryCapitalRequirementsUnderBankingRegulationsTextBlock&name=disc%3AReinsuranceTextBlock&name=disc%3ARelatedPartyTransactionsDisclosureTextBlock&name=disc%3AReorganizationUnderChapter11OfUSBankruptcyCodeDisclosureTextBlock&name=disc%3ARepurchaseAgreementsResaleAgreementsSecuritiesBorrowedAndSecuritiesLoanedDisclosureTextBlock&name=disc%3AResearchDevelopmentAndComputerSoftwareDisclosureTextBlock&name=disc%3ARestrictedAssetsDisclosureTextBlock&name=disc%3ARestrictionsOnDividendsLoansAndAdvancesTextBlock&name=disc%3ARestructuringAndRelatedActivitiesDisclosureTextBlock&name=disc%3ARestructuringImpairmentAndOtherActivitiesDisclosureTextBlock&name=disc%3ARetailLandSalesDescriptionTextBlock&name=disc%3ARealEstateAndAccumulatedDepreciationDisclosureTextBlock&name=disc%3ASaleLeasebackTransactionDisclosureTextBlock&name=disc%3AScheduleOfRegulatoryAssetsAndLiabilitiesTextBlock&name=disc%3AScheduleOfRegulatoryLiabilitiesTextBlock&name=disc%3AScheduleOfSupplementalInformationForPropertyCasualtyInsuranceUnderwritersTextBlock&name=disc%3AScheduleOfValuationAndQualifyingAccountsDisclosureTextBlock&name=disc%3ASegmentReportingDisclosureTextBlock&name=disc%3AShareholdersEquityAndShareBasedPaymentsTextBlock&name=disc%3AShortDurationInsuranceAndDepositContractsTextBlock&name=disc%3AShortTermDebtTextBlock&name=disc%3ASignificantAccountingPoliciesTextBlock&name=disc%3AStockholdersEquityNoteDisclosureTextBlock&name=disc%3ASubordinatedBorrowingsDisclosureTextBlock&name=disc%3ASubsequentEventProFormaBusinessCombinations&name=disc%3ASubsequentEventsTextBlock&name=disc%3ASummaryOfInvestmentHoldingsScheduleOfInvestmentsTextBlock&name=disc%3ASummaryOfInvestmentsOtherThanInvestmentsInRelatedPartiesTextBlock&name=disc%3ASupplementalBalanceSheetDisclosuresTextBlock&name=disc%3ASupplementalScheduleOfReinsurancePremiumsForInsuranceCompaniesTextBlock&name=disc%3ASupplementaryInsuranceInformationForInsuranceCompaniesDisclosureTextBlock&name=disc%3ASuspendedWellCostsDisclosureTextBlock&name=disc%3ATransfersAndServicingOfFinancialAssetsTextBlock&name=disc%3ATreasuryStockTextBlock&name=disc%3AUnusualOrInfrequentItemsDisclosureTextBlock&name=disc%3AVariableInterestEntityDisclosureTextBlock&name=disc%3AAcceleratedShareRepurchasesTextBlock&name=disc%3AScheduleOfActivityInAffordableHousingProgramObligationTableTextBlock&name=disc%3AAirlineDestinationTableTextBlock&name=disc%3AAllowanceForCreditLossesOnFinancingReceivablesTableTextBlock&name=disc%3AAssetsDisposedOfByMethodOtherThanSaleInPeriodOfDispositionTextBlock&name=disc%3AScheduleOfQuantitativeInformationAboutSecuritizedAssetsAndAnyOtherFinancialAssetsManagedTogetherTextBlock&name=disc%3AAvailableForSaleSecuritiesTextBlock&name=disc%3AAvailableForSaleSecuritiesContinuousUnrealizedLossPositionFairValueTableTextBlock&name=disc%3ABankersAcceptance&name=disc%3ABelowMarketLeaseFutureAmortizationIncomeTableTextBlock&name=disc%3ABusinessAcquisitionProFormaInformationTextBlock&name=disc%3ABusinessAcquisitionProFormaInformationNonrecurringAdjustmentsTableTextBlock&name=disc%3ABusinessCombinationSegmentAllocationTableTextBlock&name=disc%3ABusinessCombinationSeparatelyRecognizedTransactionsTableTextBlock&name=disc%3ACapitalRequirementsOnForeignFinancialInstitutionsTableTextBlock&name=disc%3ACapitalizedCostsRelatingToOilAndGasProducingActivitiesDisclosureTextBlock&name=disc%3ACapitalizedExploratoryWellCostsRollForwardTableTextBlock&name=disc%3ACashFlowOperatingCapitalTableTextBlock&name=disc%3AScheduleOfCashCashEquivalentsAndShortTermInvestmentsTableTextBlock&name=disc%3AScheduleOfCededCreditRiskByReinsurerTextBlock&name=disc%3ACertainLoansAcquiredInTransferNotAccountedForAsDebtSecuritiesAcquiredDuringPeriodTableTextBlock&name=disc%3AChangeInClosedBlockAssetsAndLiabilitiesMaximumFutureEarningsToBeRecognizedTableTextBlock&name=disc%3AChangesInProjectedBenefitObligationsFairValueOfPlanAssetsAndFundedStatusOfPlanTableTextBlock&name=disc%3AScheduleOfTreasuryStockByClassTextBlock&name=disc%3AClosedBlockDividendObligationTableTextBlock&name=disc%3AClosedBlockOperationsNetResultsTableTextBlock&name=disc%3AScheduleOfComprehensiveIncomeLossTableTextBlock&name=disc%3AComputationOfNetCapitalUnderSecuritiesAndExchangeCommissionRegulationTextBlock&name=disc%3AScheduleOfCondensedBalanceSheetTableTextBlock&name=disc%3AScheduleOfCondensedCashFlowStatementTableTextBlock&name=disc%3AScheduleOfCondensedFinancialStatementsTableTextBlock&name=disc%3AScheduleOfCondensedIncomeStatementTableTextBlock&name=disc%3ACondensedStatementOfComprehensiveIncomeTableTextBlock&name=disc%3AConsolidationLessThanWhollyOwnedSubsidiaryParentOwnershipInterestEffectsOfChangesNetTextBlock&name=disc%3AContractualObligationFiscalYearMaturityScheduleTableTextBlock&name=disc%3AConvertibleDebtTableTextBlock&name=disc%3ACostIncurredInOilAndGasPropertyAcquisitionExplorationAndDevelopmentActivitiesDisclosureTextBlock&name=disc%3ACostsInExcessOfBillingsAndBillingsInExcessOfCostsTableTextBlock&name=disc%3ADeferredCompensationArrangementWithIndividualDisclosurePostretirementBenefitsTextBlock&name=disc%3ADeferredCostsCapitalizedPrepaidAndOtherAssetsDisclosureTextBlock&name=disc%3ADeferredPolicyAcquisitionCostsTableTextBlock&name=disc%3ADeferredRevenueByArrangementDisclosureTextBlock&name=disc%3ADeferredSalesInducementsTableTextBlock&name=disc%3ADefinedContributionPlanDisclosuresTableTextBlock&name=disc%3ADemutualizationByInsuranceEntityScheduleOfNatureAndTerms&name=disc%3AScheduleOfDerivativeInstrumentsGainLossInStatementOfFinancialPerformanceTextBlock&name=disc%3ADetailsOfImpairmentOfLongLivedAssetsHeldAndUsedByAssetTextBlock&name=disc%3ADetailsOfLongLivedAssetsToBeAbandonedByAssetTextBlock&name=disc%3ADetailsOfNonmonetaryTransactionsTableTextBlock&name=disc%3ADisclosureOfCreditDerivativesTextBlock&name=disc%3ADisclosureOfLongLivedAssetsHeldForSaleTextBlock&name=disc%3ADisclosureOfShareBasedCompensationArrangementsByShareBasedPaymentAwardTextBlock&name=disc%3ADistributionsMadeToLimitedLiabilityCompanyLlcMemberByDistributionTableTextBlock&name=disc%3ADistributionsMadeToLimitedPartnerByDistributionTableTextBlock&name=disc%3ADividendsDeclaredTableTextBlock&name=disc%3AEffectOfFourthQuarterEventsTextBlock&name=disc%3AEffectsOfReinsuranceTableTextBlock&name=disc%3AEffectsOfUsingCashFlowHedgesInCalculatingCeilingLimitationsTextBlock&name=disc%3AScheduleOfEmployeeStockOwnershipPlanESOPDisclosuresTextBlock&name=disc%3AEnvironmentalExitCostsByCostTextBlock&name=disc%3AEquityMethodInvestmentsTextBlock&name=disc%3AFDICIndemnificationAssetRollForwardTableTextBlock&name=disc%3AFairValueInputsAssetsQuantitativeInformationTableTextBlock&name=disc%3AFairValueInputsInstrumentsClassifiedInShareholdersEquityQuantitativeInformationTableTextBlock&name=disc%3AFairValueInputsLiabilitiesQuantitativeInformationTableTextBlock&name=disc%3AFairValueAssetsMeasuredOnNonrecurringBasisTextBlock&name=disc%3AFairValueAssetsAndLiabilitiesMeasuredOnRecurringAndNonrecurringBasisTableTextBlock&name=disc%3AFairValueAssetsAndLiabilitiesMeasuredOnRecurringAndNonrecurringBasisValuationTechniquesTableTextBlock&name=disc%3AFairValueAssetsMeasuredOnRecurringBasisTextBlock&name=disc%3AFairValueAssetsMeasuredOnRecurringBasisUnobservableInputReconciliationTextBlock&name=disc%3AFairValueAssetsMeasuredOnRecurringAndNonrecurringBasisTableTextBlock&name=disc%3AFairValueAssetsMeasuredOnNonrecurringBasisValuationTechniquesTextBlock&name=disc%3AFairValueConcentrationOfRiskTextBlock&name=disc%3AFairValueEstimateNotPracticableTextBlock&name=disc%3AFairValueInstrumentsClassifiedInShareholdersEquityMeasuredOnRecurringBasisUnobservableInputReconciliationTableTextBlock&name=disc%3AFairValueInvestmentsEntitiesThatCalculateNetAssetValuePerShareTableTextBlock&name=disc%3AFairValueLiabilitiesMeasuredOnRecurringBasisTextBlock&name=disc%3AFairValueLiabilitiesMeasuredOnRecurringBasisUnobservableInputReconciliationTextBlock&name=disc%3AFairValueLiabilitiesMeasuredOnRecurringAndNonrecurringBasisTableTextBlock&name=disc%3AFairValueAssetsAndLiabilitiesMeasuredOnRecurringBasisGainLossIncludedInEarningsTextBlock&name=disc%3AFairValueNetDerivativeAssetLiabilityMeasuredOnRecurringBasisUnobservableInputReconciliationTableTextBlock&name=disc%3AFairValueOptionQualitativeDisclosuresRelatedToElectionTextBlock&name=disc%3AFairValueOptionQuantitativeDisclosuresTextBlock&name=disc%3AFairValueByBalanceSheetGroupingTextBlock&name=disc%3AFederalHomeLoanBankAdvancesTableTextBlock&name=disc%3AFederalIncomeTaxNoteTextBlock&name=disc%3ASharesSubjectToMandatoryRedemptionDisclosureTextBlock&name=disc%3AFinancingReceivableCreditQualityIndicatorsTableTextBlock&name=disc%3AFiniteLivedAndIndefiniteLivedIntangibleAssetsAcquiredAsPartOfBusinessCombinationTableTextBlock&name=disc%3AFiniteLivedIntangibleAssetsAmortizationExpenseTableTextBlock&name=disc%3AGainLossOnInvestmentsTextBlock&name=disc%3AHeldToMaturitySecuritiesTextBlock&name=disc%3AImpairedAssetsToBeDisposedOfByMethodOtherThanSaleTextBlock&name=disc%3AImpairedFinancingReceivablesTableTextBlock&name=disc%3AImpairmentEffectsOnEarningsPerShareTableTextBlock&name=disc%3AIntangibleAssetsArisingFromInsuranceContractsAcquiredInBusinessCombinationTableTextBlock&name=disc%3AInterestIncomeAndInterestExpenseDisclosureTableTextBlock&name=disc%3AInterestAndOtherIncomeTableTextBlock&name=disc%3AInterimPeriodCostsNotAllocableTableTextBlock&name=disc%3AInvestmentHoldingsOtherThanSecuritiesTextBlock&name=disc%3AInvestmentHoldingsScheduleOfInvestmentsTableTextBlock&name=disc%3AInvestmentIncomeTextBlock&name=disc%3AInvestmentsClassifiedByContractualMaturityDateTableTextBlock&name=disc%3AInvestmentsFederalIncomeTaxNoteScheduleOfInvestmentsTextBlock&name=disc%3AInvestmentsSoldNotYetPuchasedScheduleOfInvestmentsTextBlock&name=disc%3AInvestmentsSoldNotYetPurchasedTextBlock&name=disc%3AInvestmentsInAndAdvancesToAffiliatesTextBlock&name=disc%3ALiabilityForCatastropheClaimsDisclosureTextBlock&name=disc%3ALongLivedAssetsByGeographicAreasTableTextBlock&name=disc%3ALongTermPurchaseCommitmentTextBlock&name=disc%3AManagementOfRisksInherentInServicingAssetsAndServicingLiabilitiesTextBlock&name=disc%3AMandatorilyRedeemableCapitalStockTableTextBlock&name=disc%3AMarketableSecuritiesTextBlock&name=disc%3AMinimumFinancialRequirementsForFuturesCommissionMerchantsUnderCommodityExchangeActTextBlock&name=disc%3ANetProductiveAndDryWellsDrilledDisclosureTextBlock&name=disc%3ANewAccountingPronouncementEarlyAdoptionTableTextBlock&name=disc%3ANonvestedRestrictedStockSharesActivityTableTextBlock&name=disc%3AObligationWithJointAndSeveralLiabilityArrangementTableTextBlock&name=disc%3AOffsettingAssetsTableTextBlock&name=disc%3AOffsettingLiabilitiesTableTextBlock&name=disc%3AOilAndGasDeliveryCommitmentsAndContractsDisclosureTextBlock&name=disc%3AOilAndGasNetProductionAverageSalesPriceAndAverageProductionCostsDisclosureTextBlock&name=disc%3AOpenOptionContractsWrittenTextBlock&name=disc%3AOpenOptionContractsWrittenScheduleOfInvestmentsTextBlock&name=disc%3AOperatingLeasesOfLesseeDisclosureTextBlock&name=disc%3AOtherCommitmentsTableTextBlock&name=disc%3AOtherCurrentLiabilitiesTableTextBlock&name=disc%3AScheduleOfOtherInvestmentsNotReadilyMarketableTextBlock&name=disc%3AOtherLiabilitiesTableTextBlock&name=disc%3AOtherNoncurrentLiabilitiesTableTextBlock&name=disc%3AOtherRealEstateCoveredRollForwardTableTextBlock&name=disc%3AOtherRealEstateNonCoveredRollForwardTableTextBlock&name=disc%3AOtherRealEstateRollForwardTableTextBlock&name=disc%3AOtherThanSecuritiesInvestmentHoldingsScheduleOfInvestmentsTextBlock&name=disc%3AOtherThanTemporaryImpairmentCreditLossesRecognizedInEarningsTableTextBlock&name=disc%3APastDueFinancingReceivablesTableTextBlock&name=disc%3AProductLiabilityContingenciesTextBlock&name=disc%3APropertyPlantAndEquipmentTextBlock&name=disc%3APropertyPlantAndEquipmentScheduleOfSignificantAcquisitionsAndDisposalsTextBlock&name=disc%3APublicUtilitiesGeneralDisclosuresTableTextBlock&name=disc%3AScheduleOfPublicUtilityPropertyPlantAndEquipmentTextBlock&name=disc%3APurchaseCommitmentExcludingLongtermCommitmentTableTextBlock&name=disc%3AQualitativeAndQuantitativeInformationTransferorsContinuingInvolvementTableTextBlock&name=disc%3AScheduleOfQuantitativeInformationAboutDerecognizedSecuritizedOrAssetbackedFinancingArrangementAssetsAndAnyOtherFinancialAssetsManagedTogetherTextBlock&name=disc%3ARealEstateInvestmentFinancialStatementsDisclosureTextBlock&name=disc%3ARealizedGainLossOnInvestmentsTableTextBlock&name=disc%3AReceivablesTradeAndOtherAccountsReceivableAllowanceForDoubtfulAccountsPolicy&name=disc%3AReclassificationOutOfAccumulatedOtherComprehensiveIncomeTableTextBlock&name=disc%3AReconciliationOfAssetsFromSegmentToConsolidatedTextBlock&name=disc%3AReconciliationOfOperatingProfitLossFromSegmentsToConsolidatedTextBlock&name=disc%3AReconciliationOfOtherSignificantReconcilingItemsFromSegmentsToConsolidatedTextBlock&name=disc%3AReconciliationOfRevenueFromSegmentsToConsolidatedTextBlock&name=disc%3ARecordedUnconditionalPurchaseObligationsTextBlock&name=disc%3ARedeemableNoncontrollingInterestTableTextBlock&name=disc%3ARegistrationPaymentArrangementTextBlock&name=disc%3AReinsuranceRetentionPolicyTableTextBlock&name=disc%3AResearchAndDevelopmentArrangementContractToPerformForOthersTextBlock&name=disc%3AReservesReportedToOtherAgenciesTextBlock&name=disc%3ARestatementToPriorYearIncomeTextBlock&name=disc%3AScheduleOfRestructuringAndRelatedCostsTextBlock&name=disc%3AResultsOfOperationsForOilAndGasProducingActivitiesDisclosureTextBlock&name=disc%3ARevenueRecognitionMilestoneMethodTableTextBlock&name=disc%3ARevenueRecognitionMultipleDeliverableArrangementsTableTextBlock&name=disc%3ARevenueFromExternalCustomersByGeographicAreasTableTextBlock&name=disc%3AScheduleOfEntityWideInformationRevenueFromExternalCustomersByProductsAndServicesTextBlock&name=disc%3AScheduleOfAccountsPayableAndAccruedLiabilitiesTableTextBlock&name=disc%3AScheduleOfAccountsNotesLoansAndFinancingReceivableTextBlock&name=disc%3AScheduleOfAccruedLiabilitiesTableTextBlock&name=disc%3AScheduleOfAccumulatedBenefitObligationsInExcessOfFairValueOfPlanAssetsTableTextBlock&name=disc%3AScheduleOfAccumulatedOtherComprehensiveIncomeLossTableTextBlock&name=disc%3AScheduleOfAccumulatedAndProjectedBenefitObligationsTableTextBlock&name=disc%3AScheduleOfAcquiredFiniteLivedIntangibleAssetsByMajorClassTextBlock&name=disc%3AScheduleOfAcquiredIndefiniteLivedIntangibleAssetsByMajorClassTextBlock&name=disc%3AScheduleOfAgingOfCapitalizedExploratoryWellCostsTextBlock&name=disc%3AScheduleOfAllocationOfPlanAssetsTableTextBlock&name=disc%3AScheduleOfAmortizationExpensePerUnitOfProductionTextBlock&name=disc%3AScheduleOfAmountsRecognizedInBalanceSheetTableTextBlock&name=disc%3AScheduleOfAmountsRecognizedInOtherComprehensiveIncomeLossTableTextBlock&name=disc%3AScheduleOfAmountsInAccumulatedOtherComprehensiveIncomeLossToBeRecognizedOverNextFiscalYearTableTextBlock&name=disc%3AScheduleOfAntidilutiveSecuritiesExcludedFromComputationOfEarningsPerShareTextBlock&name=disc%3AScheduleOfAssetRetirementObligationsTableTextBlock&name=disc%3AScheduleOfQuantitativeInformationAboutFinancialAssetsAndAssociatedLiabilitiesAccountedForAsSecuredBorrowingsTextBlock&name=disc%3AScheduleOfAssumptionsUsedTableTextBlock&name=disc%3AScheduleOfAssumptionsForFairValueAsOfBalanceSheetDateOfInterestsContinuedToBeHeldByTransferorServicingAssetsOrServicingLiabilitiesTextBlock&name=disc%3AScheduleOfAssumptionsForLongDurationContractsByProductAndGuaranteeTextBlock&name=disc%3AScheduleOfAuctionMarketPreferredSecuritiesByStockSeriesTextBlock&name=disc%3AScheduleOfAvailableForSaleSecuritiesReconciliationTableTextBlock&name=disc%3AScheduleOfBenefitObligationsInExcessOfFairValueOfPlanAssetsTableTextBlock&name=disc%3AScheduleOfBusinessAcquisitionsByAcquisitionContingentConsiderationTextBlock&name=disc%3AScheduleOfBusinessAcquisitionsByAcquisitionEquityInterestIssuedOrIssuableTextBlock&name=disc%3AScheduleOfBusinessAcquisitionsByAcquisitionTextBlock&name=disc%3AScheduleOfBusinessInsuranceRecoveriesTextBlock&name=disc%3AScheduleOfCapitalLeasedAsssetsTableTextBlock&name=disc%3AScheduleOfCapitalUnitsTextBlock&name=disc%3AScheduleOfCapitalizationTextBlock&name=disc%3AScheduleOfCapitalizedCostsOfUnprovedPropertiesExcludedFromAmortizationTextBlock&name=disc%3AScheduleOfCarryingValuesAndEstimatedFairValuesOfDebtInstrumentsTableTextBlock&name=disc%3AScheduleOfCashFlowHedgesIncludedInAccumulatedOtherComprehensiveIncomeLossTableTextBlock&name=disc%3AScheduleOfCashFlowHedgingInstrumentsStatementsOfFinancialPerformanceAndFinancialPositionLocationTableTextBlock&name=disc%3AScheduleOfCashFlowSupplementalDisclosuresTableTextBlock&name=disc%3AScheduleOfCashProceedsReceivedFromShareBasedPaymentAwardsTableTextBlock&name=disc%3AScheduleOfCashAndCashEquivalentsTableTextBlock&name=disc%3AScheduleOfCausesOfIncreaseDecreaseInLiabilityForUnpaidClaimsAndClaimsAdjustmentExpenseTextBlock&name=disc%3AScheduleOfChangeInAccountingEstimateTextBlock&name=disc%3AScheduleOfChangeInAssetRetirementObligationTableTextBlock&name=disc%3AScheduleOfChangesInAccumulatedPostemploymentBenefitObligationsTableTextBlock&name=disc%3AScheduleOfChangesInFairValueOfPlanAssetsTableTextBlock&name=disc%3AScheduleOfChangesInProjectedBenefitObligationsTableTextBlock&name=disc%3AScheduleOfChangesInStandardizedMeasureOfDiscountedFutureNetCashFlowsTableTextBlock&name=disc%3AScheduleOfClosedBlockAssetsAndLiabilities&name=disc%3AScheduleOfCollaborativeArrangementsAndNoncollaborativeArrangementTransactionsTableTextBlock&name=disc%3AScheduleOfCommonStockOutstandingRollForwardTableTextBlock&name=disc%3AScheduleOfCompensatingBalancesTextBlock&name=disc%3AScheduleOfCompensationCostForShareBasedPaymentArrangementsAllocationOfShareBasedCompensationCostsByPlanTableTextBlock&name=disc%3AScheduleOfComplianceWithRegulatoryCapitalRequirementsForMortgageCompaniesTextBlock&name=disc%3AScheduleOfComplianceWithRegulatoryCapitalRequirementsUnderBankingRegulationsTextBlock&name=disc%3AScheduleOfComponentsOfIncomeTaxExpenseBenefitTableTextBlock&name=disc%3AScheduleOfComponentsOfLeveragedLeaseInvestmentsTableTextBlock&name=disc%3AScheduleOfConversionsOfStockTextBlock&name=disc%3AScheduleOfCostMethodInvestmentsTableTextBlock&name=disc%3AScheduleOfCostsOfRetirementPlansTableTextBlock&name=disc%3AScheduleOfCreditLossesRelatedToFinancingReceivablesCurrentAndNoncurrentTableTextBlock&name=disc%3AScheduleOfCreditLossesRelatedToFinancingReceivablesNoncurrentTableTextBlock&name=disc%3AScheduleOfCreditLossesForFinancingReceivablesCurrentTableTextBlock&name=disc%3AScheduleOfCustomerSecuritiesForWhichEntityHasRightToSellOrRepledgeTextBlock&name=disc%3AScheduleOfDebtConversionsTextBlock&name=disc%3AScheduleOfDebtTableTextBlock&name=disc%3AScheduleOfDebtorTroubledDebtRestructuringCurrentPeriodTextBlock&name=disc%3AScheduleOfDebtorTroubledDebtRestructuringSubsequentPeriodsTextBlock&name=disc%3AScheduleOfDeferredCompensationArrangementWithIndividualExcludingShareBasedPaymentsAndPostretirementBenefitsByTitleOfIndividualAndByTypeOfDeferredCompensationTextBlock&name=disc%3AScheduleOfDeferredCompensationArrangementWithIndividualShareBasedPaymentsTextBlock&name=disc%3AScheduleOfDeferredTaxAssetsAndLiabilitiesTableTextBlock&name=disc%3AScheduleOfDefinedBenefitPlanAmountsRecognizedInOtherComprehensiveIncomeLossTableTextBlock&name=disc%3AScheduleOfDefinedBenefitPlansDisclosuresTextBlock&name=disc%3AScheduleOfDerivativeAssetsAtFairValueTableTextBlock&name=disc%3AScheduleOfDerivativeFinancialInstrumentsIndexedToAndPotentiallySettledInEntitysOwnStockEquityTextBlock&name=disc%3AScheduleOfDerivativeInstrumentsIncludedInTradingActivitiesTextBlock&name=disc%3AScheduleOfDerivativeInstrumentsTextBlock&name=disc%3AScheduleOfDerivativeInstrumentsInStatementOfFinancialPositionFairValueTextBlock&name=disc%3AScheduleOfDerivativeInstrumentsEffectOnOtherComprehensiveIncomeLossTableTextBlock&name=disc%3AScheduleOfDerivativeLiabilitiesAtFairValueTableTextBlock&name=disc%3AScheduleOfDerivativesInstrumentsStatementsOfFinancialPerformanceAndFinancialPositionLocationTableTextBlock&name=disc%3AScheduleOfDevelopmentWellsDrilledTextBlock&name=disc%3AScheduleOfDifferencesBetweenReportedAmountAndReportingCurrencyDenominatedAmountTableTextBlock&name=disc%3AScheduleOfEntityWideDisclosureOnGeographicAreasLongLivedAssetsInIndividualForeignCountriesByCountryTextBlock&name=disc%3AScheduleOfDisposalGroupsIncludingDiscontinuedOperationsIncomeStatementBalanceSheetAndAdditionalDisclosuresTextBlock&name=disc%3AScheduleOfDividendsPayableTextBlock&name=disc%3AScheduleOfDueToFromBrokerDealersAndClearingOrganizationsTextBlock&name=disc%3AScheduleOfEarningsPerShareBasicAndDilutedTableTextBlock&name=disc%3AScheduleOfEarningsPerShareBasicByCommonClassTextBlock&name=disc%3AScheduleOfEarningsPerShareDilutedByCommonClassTextBlock&name=disc%3AScheduleOfEffectOfOnePercentagePointChangeInAssumedHealthCareCostTrendRatesTableTextBlock&name=disc%3AScheduleOfEffectOfSignificantUnobservableInputsChangesInPlanAssetsTableTextBlock&name=disc%3AScheduleOfEffectiveIncomeTaxRateReconciliationTableTextBlock&name=disc%3AScheduleOfEffectsOnFutureEarningsAndCashFlowsResultingFromExitPlanTextBlock&name=disc%3AScheduleOfEmployeeServiceShareBasedCompensationAllocationOfRecognizedPeriodCostsTextBlock&name=disc%3AScheduleOfEnvironmentalLossContingenciesBySiteTextBlock&name=disc%3AScheduleOfErrorCorrectionsAndPriorPeriodAdjustmentsTextBlock&name=disc%3AScheduleOfExpectedBenefitPaymentsTableTextBlock&name=disc%3AScheduleOfExploratoryWellsDrilledTextBlock&name=disc%3AScheduleOfExtinguishmentOfDebtTextBlock&name=disc%3AScheduleOfExtraordinaryItemsTextBlock&name=disc%3AScheduleOfAssumptionsForFairValueOnSecuritizationDateOfInterestsContinuedToBeHeldByTransferorServicingAssetsOrServicingLiabilitiesTextBlock&name=disc%3AScheduleOfFairValueHedgingInstrumentsStatementsOfFinancialPerformanceAndFinancialPositionLocationTableTextBlock&name=disc%3AScheduleOfFairValueOfSeparateAccountsByMajorCategoryOfInvestmentTextBlock&name=disc%3AScheduleOfFairValueAssetsAndLiabilitiesMeasuredOnRecurringBasisTableTextBlock&name=disc%3AScheduleOfFairValueOffBalanceSheetRisksTextBlock&name=disc%3AScheduleOfFederalHomeLoanBankAdvancesByBranchOfFHLBBankTextBlock&name=disc%3AScheduleOfFinancialInstrumentsOwnedAndPledgedAsCollateralTextBlock&name=disc%3AScheduleOfFinancingReceivablesMinimumPaymentsTableTextBlock&name=disc%3AScheduleOfFinancingReceivablesNonAccrualStatusTableTextBlock&name=disc%3AScheduleOfFiniteLivedIntangibleAssetsAcquiredAsPartOfBusinessCombinationTextBlock&name=disc%3AScheduleOfFiniteLivedIntangibleAssetsTableTextBlock&name=disc%3AScheduleofFiniteLivedIntangibleAssetsFutureAmortizationExpenseTableTextBlock&name=disc%3AScheduleOfForeignExchangeContractsStatementOfFinancialPositionTableTextBlock&name=disc%3AScheduleOfForwardContractsIndexedToIssuersEquityTextBlock&name=disc%3AScheduleOfFranchisorDisclosureTableTextBlock&name=disc%3AScheduleOfFreshStartAdjustmentsTextBlock&name=disc%3AScheduleOfFutureMinimumLeasePaymentsForCapitalLeasesTableTextBlock&name=disc%3AScheduleOfFutureMinimumRentalPaymentsForOperatingLeasesTableTextBlock&name=disc%3AScheduleOfGainLossOnSecuritizationsOfFinancialAssetsAccountedForAsSaleTextBlock&name=disc%3AScheduleOfGainContingenciesByContingencyTextBlock&name=disc%3AScheduleOfGasAndOilAcreageTextBlock&name=disc%3AScheduleOfGoodwillTextBlock&name=disc%3AScheduleOfGuaranteeObligationsTextBlock&name=disc%3AScheduleOfHealthCareCostTrendRatesTableTextBlock&name=disc%3AScheduleOfHealthCareTrustFundTextBlock&name=disc%3AScheduleOfImpairedIntangibleAssetsTextBlock&name=disc%3AScheduleOfIncentiveDistributionsMadeToManagingMembersOrGeneralPartnersByDistributionTextBlock&name=disc%3AScheduleOfIncomeBeforeIncomeTaxDomesticAndForeignTableTextBlock&name=disc%3AScheduleOfIncrementalEffectsOnBalanceSheetApplicationOfSFAS158RecognitionProvisionsTextBlock&name=disc%3AScheduleOfIndefiniteLivedIntangibleAssetsTableTextBlock&name=disc%3AScheduleOfIndefiniteLivedIntangibleAssetsAcquiredAsPartOfBusinessCombinationTextBlock&name=disc%3AScheduleOfInsuredFinancialObligationsWithCreditDeteriorationTextBlock&name=disc%3AScheduleOfIntangibleAssetsAndGoodwillTableTextBlock&name=disc%3AScheduleOfIntercompanyForeignCurrencyBalancesTextBlock&name=disc%3AScheduleOfInterestRateDerivativesTableTextBlock&name=disc%3AScheduleOfInventoryCurrentTableTextBlock&name=disc%3AScheduleOfInventoryNoncurrentTableTextBlock&name=disc%3AScheduleOfInvestmentsInAndAdvancesToAffiliatesScheduleOfInvestmentsTableTextBlock&name=disc%3AScheduleOfJointlyOwnedUtilityPlantsTextBlock&name=disc%3AScheduleOfLiabilityForFuturePolicyBenefitsByProductSegmentTextBlock&name=disc%3AScheduleOfLiabilityForUnpaidClaimsAndClaimsAdjustmentExpense&name=disc%3AScheduleOfLifeSettlementContractsFairValueMethodTextBlock&name=disc%3AScheduleOfLifeSettlementContractsInvestmentMethodTextBlock&name=disc%3AScheduleOfLimitedPartnersCapitalAccountByClassTextBlock&name=disc%3AScheduleOfLineOfCreditFacilitiesTextBlock&name=disc%3AScheduleOfLongTermContractsForPurchaseOfElectricPowerTextBlock&name=disc%3AScheduleOfDebtInstrumentsTextBlock&name=disc%3AScheduleOfLossContingenciesByContingencyTextBlock&name=disc%3AScheduleOfMalpracticeInsuranceTextBlock&name=disc%3AScheduleOfMaturitiesOfLongTermDebtTableTextBlock&name=disc%3AScheduleOfMinimumGuaranteedBenefitLiabilitiesTextBlock&name=disc%3AScheduleOfMultiemployerPlansTableTextBlock&name=disc%3AScheduleOfNetAmountOfRiskByProductAndGuaranteeTextBlock&name=disc%3AScheduleOfNetBenefitCostsTableTextBlock&name=disc%3AScheduleOfNetFundedStatusTableTextBlock&name=disc%3AScheduleOfNetInvestmentHedgesInAccumulatedOtherComprehensiveIncomeLossTableTextBlock&name=disc%3AScheduleOfNetInvestmentHedgesStatementsOfFinancialPerformanceAndFinancialPositionLocationTableTextBlock&name=disc%3AScheduleOfNetPeriodicBenefitCostNotYetRecognizedTableTextBlock&name=disc%3AScheduleOfNewAccountingPronouncementsAndChangesInAccountingPrinciplesTextBlock&name=disc%3AScheduleOfNoncashOrPartNoncashAcquisitionsTextBlock&name=disc%3AScheduleOfNoncashOrPartNoncashDivestituresTextBlock&name=disc%3AScheduleOfNonvestedPerformanceBasedUnitsActivityTableTextBlock&name=disc%3AScheduleOfNonvestedRestrictedStockUnitsActivityTableTextBlock&name=disc%3AScheduleOfNonvestedShareActivityTableTextBlock&name=disc%3AScheduleOfNotionalAmountsOfOutstandingDerivativePositionsTableTextBlock&name=disc%3AScheduleOfOilAndGasInProcessActivitiesTextBlock&name=disc%3AScheduleOfOptionsIndexedToIssuersEquityTextBlock&name=disc%3AScheduleOfOtherAssetsTableTextBlock&name=disc%3AScheduleOfOtherAssetsAndOtherLiabilitiesTableTextBlock&name=disc%3AScheduleOfOtherAssetsNoncurrentTextBlock&name=disc%3AScheduleOfOtherCurrentAssetsTableTextBlock&name=disc%3AScheduleOfOtherDerivativesNotDesignatedAsHedgingInstrumentsStatementsOfFinancialPerformanceAndFinancialPositionLocationTableTextBlock&name=disc%3AScheduleOfOtherNonoperatingExpenseByComponentTextBlock&name=disc%3AScheduleOfOtherNonoperatingIncomeExpenseTableTextBlock&name=disc%3AScheduleOfOtherNonoperatingIncomeByComponentTextBlock&name=disc%3AScheduleOfOtherOperatingCostAndExpenseByComponentTextBlock&name=disc%3AScheduleOfOtherOwnershipInterestsTextBlock&name=disc%3AScheduleOfOtherShareBasedCompensationActivityTableTextBlock&name=disc%3AScheduleOfOtherSignificantNoncashTransactionsTextBlock&name=disc%3AScheduleOfParticipatingMortgageLoansTextBlock&name=disc%3AScheduleOfPreferredUnitsTextBlock&name=disc%3AScheduleOfPriceRiskDerivativesTableTextBlock&name=disc%3AScheduleOfPrincipalTransactionsRevenueTextBlock&name=disc%3AScheduleOfProductInformationTableTextBlock&name=disc%3AScheduleOfProductWarrantyLiabilityTableTextBlock&name=disc%3AScheduleOfProductiveWellsTextBlock&name=disc%3AScheduleOfProjectsWithExploratoryWellCostsCapitalizedForMoreThanOneYearTextBlock&name=disc%3AScheduleOfPropertySubjectToOrAvailableForOperatingLeaseTextBlock&name=disc%3AScheduleOfProspectiveAdoptionOfNewAccountingPronouncementsTableTextBlock&name=disc%3AScheduleOfProvedDevelopedAndUndevelopedOilAndGasReserveQuantitiesTextBlock&name=disc%3AScheduleOfQuantifyingPriorYearMisstatementsCorrectedInCurrentYearFinancialStatementsTextBlock&name=disc%3AScheduleOfQuarterlyFinancialInformationTableTextBlock&name=disc%3AScheduleOfRealEstatePropertiesTableTextBlock&name=disc%3AScheduleOfRealizedGainLossTableTextBlock&name=disc%3AScheduleOfReceivablesWithImputedInterestTextBlock&name=disc%3AScheduleOfRecognizedIdentifiedAssetsAcquiredAndLiabilitiesAssumedTableTextBlock&name=disc%3AScheduleOfRegulatoryAssetsTextBlock&name=disc%3AScheduleOfRegulatoryLiabilitiesTextBlock&name=disc%3AScheduleOfRelatedPartyTransactionsTableTextBlock&name=disc%3AScheduleOfRentExpenseTableTextBlock&name=disc%3AScheduleOfRepurchaseAgreementCounterpartiesWithWhomRepurchaseAgreementsExceed10PercentOfStockholdersEquityTextBlock&name=disc%3AScheduleOfRepurchaseAgreements&name=disc%3AScheduleOfResaleAgreementCounterpartiesWithWhomResaleAgreementsExceed10PercentOfStockholdersEquityTextBlock&name=disc%3AScheduleOfResaleAgreements&name=disc%3AScheduleOfResearchAndDevelopmentAssetsAcquiredOtherThanThroughBusinessCombinationTextBlock&name=disc%3AScheduleOfRestrictedCashAndCashEquivalentsTextBlock&name=disc%3AScheduleOfRestructuringReserveByTypeOfCostTextBlock&name=disc%3AScheduleOfRetainedEarningsAdjustmentsTableTextBlock&name=disc%3AScheduleOfRevenueSourcesHealthCareOrganizationTableTextBlock&name=disc%3AScheduleOfRevenueByMajorCustomersByReportingSegmentsTableTextBlock&name=disc%3AScheduleOfRevenueFromExternalCustomersAttributedToForeignCountriesByGeographicAreaTextBlock&name=disc%3AScheduleOfRevenuesFromExternalCustomersAndLongLivedAssetsByGeographicalAreasTableTextBlock&name=disc%3AScheduleOfSaleLeasebackTransactionsTextBlock&name=disc%3AScheduleOfSaleOfStockBySubsidiaryOrEquityMethodInvesteeDisclosureTextBlock&name=disc%3AScheduleOfSecuritiesFinancingTransactionsTextBlock&name=disc%3AScheduleOfSecuritiesOwnedAndSoldNotYetPurchasedAtFairValueTextBlock&name=disc%3AScheduleOfSegmentReportingInformationBySegmentTextBlock&name=disc%3AScheduleOfSensitivityAnalysisOfFairValueOfInterestsContinuedToBeHeldByTransferorServicingAssetsOrServicingLiabilitiesTextBlock&name=disc%3AScheduleOfServicingAssetsAtFairValueTextBlock&name=disc%3AScheduleOfServicingLiabilitiesAtFairValueTextBlock&name=disc%3AScheduleOfShareBasedCompensationArrangementByShareBasedPaymentAwardOptionsGrantsInPeriodGrantDateIntrinsicValueTableTextBlock&name=disc%3AScheduleOfShareBasedCompensationArrangementByShareBasedPaymentAwardOptionsVestedAndExpectedToVestOutstandingTableTextBlock&name=disc%3AScheduleOfShareBasedCompensationArrangementByShareBasedPaymentAwardPerformanceBasedUnitsVestedAndExpectedToVestTableTextBlock&name=disc%3AScheduleOfShareBasedCompensationArrangementByShareBasedPaymentAwardRestrictedStockUnitsVestedAndExpectedToVestTableTextBlock&name=disc%3AScheduleOfShareBasedCompensationActivityTableTextBlock&name=disc%3AScheduleOfShareBasedCompensationEmployeeStockPurchasePlanActivityTableTextBlock&name=disc%3AScheduleOfShareBasedCompensationNonemployeeDirectorStockAwardPlanActivityTableTextBlock&name=disc%3AScheduleOfShareBasedCompensationRestrictedStockUnitsAwardActivityTableTextBlock&name=disc%3AScheduleOfSharebasedCompensationRestrictedStockAndRestrictedStockUnitsActivityTableTextBlock&name=disc%3AScheduleOfShareBasedCompensationSharesAuthorizedUnderStockOptionPlansByExercisePriceRangeTextBlock&name=disc%3AScheduleOfShareBasedCompensationStockAppreciationRightsAwardActivityTableTextBlock&name=disc%3AScheduleOfShareBasedCompensationStockOptionsAndStockAppreciationRightsAwardActivityTableTextBlock&name=disc%3AScheduleOfShareBasedCompensationStockOptionsActivityTableTextBlock&name=disc%3AScheduleOfShareBasedGoodsAndNonemployeeServicesTransactionBySupplierTextBlock&name=disc%3AScheduleOfShareBasedPaymentAwardEmployeeStockPurchasePlanValuationAssumptionsTableTextBlock&name=disc%3AScheduleOfShareBasedPaymentAwardStockOptionsValuationAssumptionsTableTextBlock&name=disc%3AScheduleOfShortTermDebtTextBlock&name=disc%3AScheduleOfStockOptionsRollForwardTableTextBlock&name=disc%3AScheduleOfStockByClassTextBlock&name=disc%3AScheduleOfStockholdersEquityTableTextBlock&name=disc%3AScheduleOfStockholdersEquityNoteWarrantsOrRightsTextBlock&name=disc%3AScheduleOfSubordinatedBorrowingTextBlock&name=disc%3AScheduleOfSubsequentEventsTextBlock&name=disc%3AScheduleOfSubsidiaryOfLimitedLiabilityCompanyOrLimitedPartnershipDescriptionTextBlock&name=disc%3AScheduleOfTemporaryImpairmentLossesInvestmentsTableTextBlock&name=disc%3AScheduleOfUnderlyingAssetsOfRepurchaseAgreementsWhenAmountOfRepurchaseAgreementsExceeds10PercentOfAssetsTextBlock&name=disc%3AScheduleOfUnrealizedLossOnInvestmentsTableTextBlock&name=disc%3AScheduleOfUnrecognizedCompensationCostNonvestedAwardsTableTextBlock&name=disc%3AScheduleOfUnrecognizedTaxBenefitsRollForwardTableTextBlock&name=disc%3AScheduleOfUnrecognizedTaxBenefitsExcludingAmountsPertainingToExaminedTaxReturnsRollForwardTableTextBlock&name=disc%3AScheduleOfUnusualOrInfrequentItemsTextBlock&name=disc%3AScheduleOfUnvestedRestrictedStockUnitsRollForwardTableTextBlock&name=disc%3AScheduleOfUtilityInventoryTextBlock&name=disc%3AScheduleOfValuationAllowanceForImpairmentOfRecognizedServicingAssetsTextBlock&name=disc%3AScheduleOfVariableInterestEntitiesTextBlock&name=disc%3AScheduleOfWeightedAverageNumberOfSharesTableTextBlock&name=disc%3AScheduleOrDescriptionOfWeightedAverageDiscountRateTextBlock&name=disc%3ASchedulesOfConcentrationOfRiskByRiskFactorTextBlock&name=disc%3AScheduleOfSecuritiesOwnedNotReadilyMarketableTextBlock&name=disc%3ASecuritiesOwnedAndOtherInvestmentsNotReadilyMarketableDisclosureTextBlock&name=disc%3AScheduleOfServicingAssetsAtAmortizedValueTextBlock&name=disc%3AScheduleOfServicingLiabilitiesAtAmortizedValueTextBlock&name=disc%3AShareBasedCompensationArrangementByShareBasedPaymentAwardOptionsGrantsInPeriodWeightedAverageGrantDateFairValueTableTextBlock&name=disc%3AShareBasedCompensationArrangementByShareBasedPaymentAwardOptionsVestedAndExpectedToVestExercisableTableTextBlock&name=disc%3AShareBasedCompensationArrangementByShareBasedPaymentAwardOptionsVestedAndExpectedToVestOutstandingAndExercisableTableTextBlock&name=disc%3AShareBasedCompensationPerformanceSharesAwardOutstandingActivityTableTextBlock&name=disc%3AShareBasedCompensationPerformanceSharesAwardUnvestedActivityTableTextBlock&name=disc%3AStandardizedMeasureOfDiscountedFutureCashFlowsRelatingToProvedReservesDisclosureTextBlock&name=disc%3AStatutoryAccountingPracticesDisclosureTextBlock&name=disc%3ASummaryInvestmentHoldingsTextBlock&name=disc%3ASummaryOfDeferredTaxLiabilityNotRecognizedTextBlock&name=disc%3ASummaryOfIncomeTaxContingenciesTextBlock&name=disc%3ASummaryOfIncomeTaxExaminationsTextBlock&name=disc%3ASummaryOfIncomeTaxHolidayTextBlock&name=disc%3ASummaryOfInvestmentHoldingsScheduleOfInvestmentsTableTextBlock&name=disc%3ASummaryOfOperatingLossCarryforwardsTextBlock&name=disc%3ASummaryOfPositionsForWhichSignificantChangeInUnrecognizedTaxBenefitsIsReasonablyPossibleTextBlock&name=disc%3ASummaryOfTaxCreditCarryforwardsTextBlock&name=disc%3ASummaryOfTroubledDebtRestructuringNoteDebtorTextBlock&name=disc%3ASummaryOfValuationAllowanceTextBlock&name=disc%3ASupplyCommitmentTableTextBlock&name=disc%3ATargetedOrTrackingStockDescriptionTextBlock&name=disc%3ATemporaryEquityTableTextBlock&name=disc%3ATradingSecuritiesAndCertainTradingAssetsTextBlock&name=disc%3ATroubledDebtRestructuringsOnFinancingReceivablesTableTextBlock&name=disc%3ATypesOfCommercialAircraftTableTextBlock&name=disc%3AUnprovedPropertiesDisclosureTextBlock&name=disc%3AUnrealizedGainLossOnInvestmentsTableTextBlock&name=disc%3AUnrecordedUnconditionalPurchaseObligationsDisclosureTextBlock&name=disc%3AUnusualRisksAndUncertaintiesTextBlock")
})

import module namespace http-client = "http://zorba.io/modules/http-client";
import module namespace request = "http://www.28msec.com/modules/http-request";
import module namespace response = "http://www.28msec.com/modules/http-response";

declare %an:nondeterministic function local:test-concepts($expected as integer, $params as string) as atomic
{
    let $elements as item* := parse-json(http-client:get("http://" || request:server-name() || ":" || request:server-port() || "/v1/_queries/public/api/report-elements.jq?_method=POST" || $params).body.content).ReportElements[]
    let $actual as integer := count($elements)
    let $duplicates := for $element in $elements where $element.CIK instance of array return $element
    return
        if (exists($duplicates)) then
            "false [CIK " || serialize($duplicates[1].CIK, ()) || " is not unique]"
        else if ($actual eq $expected) then
            true
        else
            "false [Actual="||$actual||", Expected="||$expected ||"]"
};

declare %an:nondeterministic function local:test-200($params as string) as atomic
{
    let $res := http-client:get("http://" || request:server-name() || ":" || request:server-port() || "/v1/_queries/public/api/report-elements.jq?_method=POST" || $params)
    return $res.status eq 200
};

declare %an:sequential function local:check($o as object) as object
{
    if (not(every $k in (keys($o) ! $o.$$) satisfies ($k instance of boolean and $k)))
    then {
            response:status-code(500);
            $o
    } else
            $o
};

local:check({
    all: local:test-concepts(3, "&cik=4962&name=us-gaap:Assets"),
    onlyNames: local:test-concepts(16143, "&tag=DOW30&fiscalYear=2012&fiscalPeriod=FY&onlyNames=true"),
    disclosures: local:test-concepts(1855, "&ticker=ko&fiscalYear=2012&fiscalPeriod=FY&report=Disclosure&concept=disc:ConsolidationVariableInterestEntityPolicy")
    reportWithNoFilter: local:test-200("report=Disclosures"),
    reportWithNoFilter2: local:test-200("map=Disclosures"),

})


:green_heart: Fix filings test.

:green_heart: Fix filings test.


:bug: Fix calls.

:bug: Fix calls.

jsoniq version "1.0";

module namespace api = "http://apps.28.io/api";

import module namespace session    = "http://apps.28.io/session";
import module namespace resp       = "http://www.28msec.com/modules/http-response";
import module namespace sec-fiscal = "http://28.io/modules/xbrl/profiles/sec/fiscal/core";

import module namespace csv = "http://zorba.io/modules/json-csv";

declare function api:json-to-csv($objects as object*) as string
{
  let $flattened as object* := api:flatten-json-object($objects, ())
  return string-join(
    csv:serialize($flattened, { field-names: [ keys($flattened) ], serialize-null-as : "" }),
    "")
  };

declare function api:json-to-xml($objects as object*, $root-name as string) as element()*
{
  for $flattened-object as object in api:flatten-json-object($objects, { KeepArray: true })
  return element { $root-name } {
    for $key in keys($flattened-object)
    let $value := $flattened-object.$key
    return typeswitch($value)
           case array return
             let $key-with-s := if(substring($key, string-length($key), 1) eq "s")
                                then $key
                                else $key || "s"
             let $key-no-s := if(substring($key, string-length($key), 1) eq "s")
                                then substring($key, 1, string-length($key) - 1)
                                else $key
             return element {$key-with-s} { for $v in $value[] return element { $key-no-s } { $v } }
           default return element { $key } { $value }
  }
};

declare %private function api:flatten-json-object(
  $items as item*,
  $options as object?) as item*
{
  for $item in $items
  return typeswitch($item)
         case atomic return $item
         case array return let $atomic-items := flatten($item)[$$ instance of atomic]
                           return if ($options.KeepArray)
                                 then [ $atomic-items ]
                                  else string-join($atomic-items, ", ")
         case object return {|
             for $key in keys($item)
             return typeswitch($item.$key)
                    case object return api:flatten-json-object($item.$key, $options)
                    default return { $key: api:flatten-json-object($item.$key, $options) }
         |}
         default return ()
};

declare function api:validate-regexp($name as string, $value as string?, $regexp as string)
as ()
{
  if (exists($value))
  then
    if (matches($value, "^" || $regexp || "$"))
    then ();
    else fn:error(xs:QName("api:bad-parameter"), "Provided parameter " || $name || " with value " || $value || " does not match reg. expression " || $regexp || ".");
  else ();
};

declare function api:validate-enum($name as string, $value as string?, $enum as string*)
as ()
{
  if (exists($value))
  then
    if ($value = $enum)
    then ();
    else fn:error(xs:QName("api:bad-parameter"), "Provided parameter " || $name || " with value " || $value || " is not one of these: " || string-join($enum,", ") || ".");
  else ();
};

declare %private function api:sgpl($count as integer, $singular as string, $plural as string)
as string
{
    if ($count eq 1)
    then $count || " " || $singular
    else $count || " " || $plural
};

declare function api:passed($timestamp as xs:dateTime?)
as string
{
    if (empty($timestamp) or $timestamp eq null)
    then "Never"
    else
        let $now := current-dateTime()
        let $difference := $now - $timestamp
        let $years := years-from-duration($difference)
        let $month := months-from-duration($difference)
        let $days := days-from-duration($difference)
        let $hours := hours-from-duration($difference)
        let $minutes := minutes-from-duration($difference)
        return
            if ($years gt 0) then api:sgpl($years,"year ago","years ago")
            else if ($month gt 0) then api:sgpl($month,"month ago","month ago")
            else if ($days gt 0) then api:sgpl($days, "day ago", "days ago")
            else if ($hours gt 0) then api:sgpl($hours, "hour ago", "hours ago")
            else if ($minutes gt 0) then api:sgpl($minutes, "minute ago", "minutes ago")
            else if ($difference div xs:dayTimeDuration("PT1S") lt 0) then "future"
            else "Just Now"
};

declare function api:success() as object
{
  { "success" : true }
};

declare function api:success($data as object()) as object
{
  {|
     {"success" : true },
     $data
  |}
};

declare %an:sequential function api:check-and-return-results(
    $token as string?,
    $results as item*,
    $format as string?
) as item*
{
    switch(session:has-access($token, "data_sec"))
    case $session:ACCESS-ALLOWED return
        $results
    case $session:ACCESS-DENIED return {
          resp:status-code(403);
          session:error("access denied", $format)
       }
    case $session:ACCESS-AUTH-REQUIRED return {
          resp:status-code(401);
          session:error("authentication required or session expired", $format)
       }
    default return error()
};

declare function api:normalize-facts(
    $facts as object*) as object*
{
    for $fact in $facts
    return {|
        {
            "Aspects" : {|
                trim($fact.Aspects, ("xbrl:Unit")),
                { "sec:Archive" : $fact.Aspects."xbrl28:Archive" }[exists($fact.Aspects."xbrl28:Archive")]
            |}
        },
        trim($fact, ("Aspects", "_id")),
        { Unit: $fact.Aspects."xbrl:Unit" }[exists($fact.Aspects."xbrl:Unit") and not exists($fact.Unit)]
    |}
};

declare %an:sequential function api:serialize(
    $result as json-item,
    $comment as object,
    $serializers as object,
    $format as string?,
    $file-name as string) as item*
{
    switch ($format)
    case "xml" return {
        resp:serialization-parameters({"omit-xml-declaration" : false, indent : true });
        session:comment("xml", $comment),
        $serializers.to-xml($result)
    }
    case "text" case "csv" return {
        resp:content-type("text/csv");
        resp:header("Content-Disposition", "attachment; filename=" || $file-name || ".csv");
        $serializers.to-csv($result)
    }
    case "html" return {
        resp:content-type("text/html");
        let $csv as string := $serializers.to-csv($result)
        return api:csv-to-html($csv)
    }
    case "excel" return {
        resp:content-type("application/vnd.ms-excel");
        resp:header("Content-Disposition", "attachment; filename=" || $file-name || ".csv");
        $serializers.to-csv($result)
    }
    default return {
        resp:content-type("application/json");
        resp:serialization-parameters({"indent" : true});
        {|
            session:comment("json", $comment),
            $result
        |}
    }
};

declare %an:sequential function api:csv-to-html(
    $csv as string) as item*
{
    let $csv as string* := $csv
    let $rows := tokenize($csv, "\n")
    let $header := $rows[1]
    let $body := subsequence($rows, 2)
    let $display-cell := function($row as string, $cell-tag-name as string) {
      for tumbling window $cells as string* in tokenize($row, ",")
      start $start at $i when true
      only end $end at $j when not contains(replace($start, "\"\"", ""), "\"") or ($j gt $i and contains(replace($end, "\"\"", ""), "\""))
      let $cell := replace(string-join($cells, ","), "\"", "")
      return if(contains($cell, "http://") and (contains($cell, "28.io") or contains($cell, "rendering.secxbrl.info")))
      then element $cell-tag-name { Link }
      else element $cell-tag-name {$cell}
    }
    return

        <title>Cell Store REST API</title>

{$display-cell($header, "th")}

          {
            for $row as string in $body
            return
{$display-cell($row, "td")}

          }

};

declare function api:preprocess-fiscal-years($fiscal-years as string*) as integer*
{
  distinct-values(
    for $fy in $fiscal-years ! upper-case($$)
    return switch($fy)
           case "LATEST" return $sec-fiscal:LATEST_FISCAL_YEAR
           case "ALL" return $sec-fiscal:ALL_FISCAL_YEARS
           default return if($fy castable as integer) then integer($fy) else ()
  )
};

declare function api:preprocess-fiscal-periods($fiscal-periods as string*) as string*
{
  distinct-values(
    for $fp in $fiscal-periods ! upper-case($$)
    return switch($fp)
           case "Q1"
           case "Q2"
           case "Q3"
           case "FY"
             return $fp
           case "ALL"
             return $sec-fiscal:ALL_FISCAL_PERIODS
           default
             return error(xs:QName("local:INVALID-PERIOD"),
               $fp || ": fiscalPeriod values must be one or more of Q1, Q2, Q3, FY, ALL")
  )
};

declare function api:preprocess-fiscal-period-types($fiscal-period-types as string*) as string*
{
  distinct-values(
    for $fpt in $fiscal-period-types
    return switch($fpt)
           case "instant"
           case "QTD"
           case "YTD"
             return $fpt
           case "ALL"
             return $sec-fiscal:ALL_FISCAL_PERIOD_TYPES
           default
             return error(xs:QName("local:INVALID-PERIOD-TYPE"),
               $fpt || ": fiscalPeriodType values must be one or more of instant, YTD, QTD")
  )
};

declare function api:preprocess-format($format as string?, $request-uri as string) as string?
{
  let $request-path := tokenize($request-uri, "\\?")[1]
  return lower-case(($format, substring-after($request-path, ".jq."))[1])
};

declare function api:preprocess-tags($tags as string*) as string*
{
  distinct-values($tags ! upper-case($$))
};

declare function api:preprocess-boolean($name as string, $value as string)
as boolean
{
  if ($value eq "")
  then true
  else
  {
      api:validate-enum($name, lower-case($value), ("true", "false"));
      boolean($value)
  }
};

jsoniq version "1.0";

module namespace api = "http://apps.28.io/api";

import module namespace session    = "http://apps.28.io/session";
import module namespace resp       = "http://www.28msec.com/modules/http-response";
import module namespace sec-fiscal = "http://28.io/modules/xbrl/profiles/sec/fiscal/core";

import module namespace csv = "http://zorba.io/modules/json-csv";

declare function api:json-to-csv($objects as object*) as string
{
  let $flattened as object* := api:flatten-json-object($objects, ())
  return string-join(
    csv:serialize($flattened, { field-names: [ keys($flattened) ], serialize-null-as : "" }),
    "")
  };

declare function api:json-to-xml($objects as object*, $root-name as string) as element()*
{
  for $flattened-object as object in api:flatten-json-object($objects, { KeepArray: true })
  return element { $root-name } {
    for $key in keys($flattened-object)
    let $value := $flattened-object.$key
    return typeswitch($value)
           case array return
             let $key-with-s := if(substring($key, string-length($key), 1) eq "s")
                                then $key
                                else $key || "s"
             let $key-no-s := if(substring($key, string-length($key), 1) eq "s")
                                then substring($key, 1, string-length($key) - 1)
                                else $key
             return element {$key-with-s} { for $v in $value[] return element { $key-no-s } { $v } }
           default return element { $key } { $value }
  }
};

declare %private function api:flatten-json-object(
  $items as item*,
  $options as object?) as item*
{
  for $item in $items
  return typeswitch($item)
         case atomic return $item
         case array return let $atomic-items := flatten($item)[$$ instance of atomic]
                           return if ($options.KeepArray)
                                 then [ $atomic-items ]
                                  else string-join($atomic-items, ", ")
         case object return {|
             for $key in keys($item)
             return typeswitch($item.$key)
                    case object return api:flatten-json-object($item.$key, $options)
                    default return { $key: api:flatten-json-object($item.$key, $options) }
         |}
         default return ()
};

declare function api:validate-regexp($name as string, $value as string?, $regexp as string)
as ()
{
  if (exists($value))
  then
    if (matches($value, "^" || $regexp || "$"))
    then ();
    else fn:error(xs:QName("api:bad-parameter"), "Provided parameter " || $name || " with value " || $value || " does not match reg. expression " || $regexp || ".");
  else ();
};

declare function api:validate-enum($name as string, $value as string?, $enum as string*)
as ()
{
  if (exists($value))
  then
    if ($value = $enum)
    then ();
    else fn:error(xs:QName("api:bad-parameter"), "Provided parameter " || $name || " with value " || $value || " is not one of these: " || string-join($enum,", ") || ".");
  else ();
};

declare %private function api:sgpl($count as integer, $singular as string, $plural as string)
as string
{
    if ($count eq 1)
    then $count || " " || $singular
    else $count || " " || $plural
};

declare function api:passed($timestamp as xs:dateTime?)
as string
{
    if (empty($timestamp) or $timestamp eq null)
    then "Never"
    else
        let $now := current-dateTime()
        let $difference := $now - $timestamp
        let $years := years-from-duration($difference)
        let $month := months-from-duration($difference)
        let $days := days-from-duration($difference)
        let $hours := hours-from-duration($difference)
        let $minutes := minutes-from-duration($difference)
        return
            if ($years gt 0) then api:sgpl($years,"year ago","years ago")
            else if ($month gt 0) then api:sgpl($month,"month ago","month ago")
            else if ($days gt 0) then api:sgpl($days, "day ago", "days ago")
            else if ($hours gt 0) then api:sgpl($hours, "hour ago", "hours ago")
            else if ($minutes gt 0) then api:sgpl($minutes, "minute ago", "minutes ago")
            else if ($difference div xs:dayTimeDuration("PT1S") lt 0) then "future"
            else "Just Now"
};

declare function api:success() as object
{
  { "success" : true }
};

declare function api:success($data as object()) as object
{
  {|
     {"success" : true },
     $data
  |}
};

declare %an:sequential function api:check-and-return-results(
    $token as string?,
    $results as item*,
    $format as string?
) as item*
{
    switch(session:has-access($token, "data_sec"))
    case $session:ACCESS-ALLOWED return
        $results
    case $session:ACCESS-DENIED return {
          resp:status-code(403);
          session:error("access denied", $format)
       }
    case $session:ACCESS-AUTH-REQUIRED return {
          resp:status-code(401);
          session:error("authentication required or session expired", $format)
       }
    default return error()
};

declare function api:normalize-facts(
    $facts as object*) as object*
{
    for $fact in $facts
    return {|
        {
            "Aspects" : {|
                trim($fact.Aspects, ("xbrl:Unit")),
                { "sec:Archive" : $fact.Aspects."xbrl28:Archive" }[exists($fact.Aspects."xbrl28:Archive")]
            |}
        },
        trim($fact, ("Aspects", "_id")),
        { Unit: $fact.Aspects."xbrl:Unit" }[exists($fact.Aspects."xbrl:Unit") and not exists($fact.Unit)]
    |}
};

declare %an:sequential function api:serialize(
    $result as json-item,
    $comment as object,
    $serializers as object,
    $format as string?,
    $file-name as string) as item*
{
    switch ($format)
    case "xml" return {
        resp:serialization-parameters({"omit-xml-declaration" : false, indent : true });
        session:comment("xml", $comment),
        $serializers.to-xml($result)
    }
    case "text" case "csv" return {
        resp:content-type("text/csv");
        resp:header("Content-Disposition", "attachment; filename=" || $file-name || ".csv");
        $serializers.to-csv($result)
    }
    case "html" return {
        resp:content-type("text/html");
        let $csv as string := $serializers.to-csv($result)
        return api:csv-to-html($csv)
    }
    case "excel" return {
        resp:content-type("application/vnd.ms-excel");
        resp:header("Content-Disposition", "attachment; filename=" || $file-name || ".csv");
        $serializers.to-csv($result)
    }
    default return {
        resp:content-type("application/json");
        resp:serialization-parameters({"indent" : true});
        {|
            session:comment("json", $comment),
            $result
        |}
    }
};

declare %an:sequential function api:csv-to-html(
    $csv as string) as item*
{
    let $csv as string* := $csv
    let $rows := tokenize($csv, "\n")
    let $header := $rows[1]
    let $body := subsequence($rows, 2)
    let $display-cell := function($row as string, $cell-tag-name as string) {
      for tumbling window $cells as string* in tokenize($row, ",")
      start $start at $i when true
      only end $end at $j when not contains(replace($start, "\"\"", ""), "\"") or ($j gt $i and contains(replace($end, "\"\"", ""), "\""))
      let $cell := replace(string-join($cells, ","), "\"", "")
      return if(contains($cell, "http://") and (contains($cell, "28.io") or contains($cell, "rendering.secxbrl.info")))
      then element $cell-tag-name { Link }
      else element $cell-tag-name {$cell}
    }
    return

        <title>Cell Store REST API</title>

{$display-cell($header)}

          {
            for $row as string in $body
            return
{$display-cell($row)}

          }

};

declare function api:preprocess-fiscal-years($fiscal-years as string*) as integer*
{
  distinct-values(
    for $fy in $fiscal-years ! upper-case($$)
    return switch($fy)
           case "LATEST" return $sec-fiscal:LATEST_FISCAL_YEAR
           case "ALL" return $sec-fiscal:ALL_FISCAL_YEARS
           default return if($fy castable as integer) then integer($fy) else ()
  )
};

declare function api:preprocess-fiscal-periods($fiscal-periods as string*) as string*
{
  distinct-values(
    for $fp in $fiscal-periods ! upper-case($$)
    return switch($fp)
           case "Q1"
           case "Q2"
           case "Q3"
           case "FY"
             return $fp
           case "ALL"
             return $sec-fiscal:ALL_FISCAL_PERIODS
           default
             return error(xs:QName("local:INVALID-PERIOD"),
               $fp || ": fiscalPeriod values must be one or more of Q1, Q2, Q3, FY, ALL")
  )
};

declare function api:preprocess-fiscal-period-types($fiscal-period-types as string*) as string*
{
  distinct-values(
    for $fpt in $fiscal-period-types
    return switch($fpt)
           case "instant"
           case "QTD"
           case "YTD"
             return $fpt
           case "ALL"
             return $sec-fiscal:ALL_FISCAL_PERIOD_TYPES
           default
             return error(xs:QName("local:INVALID-PERIOD-TYPE"),
               $fpt || ": fiscalPeriodType values must be one or more of instant, YTD, QTD")
  )
};

declare function api:preprocess-format($format as string?, $request-uri as string) as string?
{
  let $request-path := tokenize($request-uri, "\\?")[1]
  return lower-case(($format, substring-after($request-path, ".jq."))[1])
};

declare function api:preprocess-tags($tags as string*) as string*
{
  distinct-values($tags ! upper-case($$))
};

declare function api:preprocess-boolean($name as string, $value as string)
as boolean
{
  if ($value eq "")
  then true
  else
  {
      api:validate-enum($name, lower-case($value), ("true", "false"));
      boolean($value)
  }
};