text:
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
var _ = require('lodash');

var factsheetsDefinitionsWrapper = function () {
    this.setDefaultTimeout(600000);
    var fsp = require('../support/factsheets.po')
    this.When(/^I navigate to factsheets page$/, function () {
        return fsp.getFactSheetLink.click();
    });
    this.Then(/^I should get factsheets page$/, function () {
        expect(fsp.pageHeading.isDisplayed()).to.eventually.equal(true);
        expect(fsp.pageDescription.isDisplayed()).to.eventually.equal(true);
        expect(fsp.stateSelectBox.isDisplayed()).to.eventually.equal(true);
        return expect(fsp.generateFactSheetLink.isDisplayed()).to.eventually.equal(true);
    });

    this.When(/^I click on generate fact sheet link$/, function () {
        return fsp.generateFactSheetLink.click();
    });

    this.Given(/^I click on downloadFactSheetLink$/, function () {
        return fsp.downloadFactSheetLink.click();
    });
    //Maryland - Minority fact sheet
    this.Then(/^generated data should be displayed on same factsheets page$/, function (next) {
        //browser.wait()
        expect(element(by.className('state-heading')).isDisplayed()).to.eventually.equal(true);
        expect(element(by.className('state-heading')).getText()).to.eventually.equal("Maryland - Minority Health");
        expect(element(by.tagName('h3')).getText()).to.eventually.equal("Maryland - Minority Health");
        expect(element(by.className('bridge-race-heading')).getText()).to.eventually.equal("Population in Maryland");
        fsp.getTableHeaders('bridge-race-table1').then(function (headers) {
            expect(headers[0]).to.contains('Racial distributions of minority residents*');
            expect(headers[1]).to.contains('American Indian or Alaska Native');
            expect(headers[2]).to.contains('Asian or Pacific Islander');
            expect(headers[3]).to.contains('Black or African American');
            expect(headers[4]).to.contains('Hispanic');

        });
        fsp.getTableCellData('bridge-race-table1', 0, 1).then(function (data) {
            expect(data).to.contains('17,938');
        });

        fsp.getTableCellData('bridge-race-table1', 0, 2).then(function (data) {
            expect(data).to.contains('411,071');
        });
        fsp.getTableCellData('bridge-race-table1', 0, 3).then(function (data) {
            expect(data).to.contains('1,820,087');
        });
        fsp.getTableCellData('bridge-race-table1', 0, 4).then(function (data) {
            expect(data).to.contains('572,373');
        });

        fsp.getTableHeaders('detail-mortality-table').then(function (headers) {
            expect(headers[0]).to.contains('Cause of Death');
            expect(headers[1]).to.contains('Measure');
            expect(headers[2]).to.contains('American Indian or Alaska Native');
            expect(headers[3]).to.contains('Asian or Pacific Islander');
            expect(headers[4]).to.contains('Black or African American');
            expect(headers[5]).to.contains('Hispanic');
        });
        fsp.getTableCellData('detail-mortality-table', 0, 1).then(function (data) {
            expect(data).to.contains('Number of deaths');
        });
        fsp.getTableHeaders('infant-mortality-table').then(function (headers) {
            expect(headers[0]).to.contains('Measure');
            expect(headers[1]).to.contains('American Indian or Alaska Native');
            expect(headers[2]).to.contains('Asian or Pacific Islander');
            expect(headers[3]).to.contains('Black or African American');
            expect(headers[4]).to.contains('Hispanic');
        });
        fsp.getTableCellData('infant-mortality-table', 0, 1).then(function (data) {
            expect(data).to.contains('Suppressed');
        });

        fsp.getTableHeaders('prams-table-1').then(function (headers) {
            expect(headers[0]).to.contains('Question');
            expect(headers[1]).to.contains('Black, Non-Hispanic');
            expect(headers[2]).to.contains('Other, Non- Hispanic');
            expect(headers[3]).to.contains('Hispanic');
        });

        fsp.getTableCellData('prams-table-1', 0, 0).then(function (data) {
            expect(data).to.contains('Smoking cigarettes during the last three months of pregnancy');
        });

        fsp.getTableHeaders('brfss-table').then(function (headers) {
            expect(headers[0]).to.contains('Question');
            expect(headers[1]).to.contains('American Indian or Alaskan Native, non-Hispanic');
            expect(headers[2]).to.contains('Asian, non-Hispanic');
            expect(headers[3]).to.contains('Black, non-Hispanic');
            expect(headers[4]).to.contains('Native Hawaiian or other Pacific Islander, non-Hispanic');
            expect(headers[5]).to.contains('Multiracial non-Hispanic');
            expect(headers[6]).to.contains('Other, non-Hispanic');
            expect(headers[7]).to.contains('Hispanic');
        });

        fsp.getTableCellData('brfss-table', 0, 0).then(function (data) {
            expect(data).to.contains('Obese (Body Mass Index 30.0 - 99.8)');
        });
        fsp.getTableHeaders('yrbs-table').then(function (headers) {
            expect(headers[0]).to.contains('Question');
            expect(headers[1]).to.contains('American Indian or Alaska Native');
            expect(headers[2]).to.contains('Asian');
            expect(headers[3]).to.contains('Black or African American');
            expect(headers[4]).to.contains('Native Hawaiian or Other Pacific Islander');
            expect(headers[5]).to.contains('Multiple Race');
            expect(headers[6]).to.contains('Hispanic or Latino');

        });

        fsp.getTableCellData('yrbs-table', 0, 1).then(function (data) {
            expect(data).to.contains('29.5%');
        });
        fsp.getTableHeaders('natality-table').then(function (headers) {
            expect(headers[0]).to.contains('Measure');
            expect(headers[1]).to.contains('American Indian or Alaska Native');
            expect(headers[2]).to.contains('Asian or Pacific Islander');
            expect(headers[3]).to.contains('Black or African American');

        });

        fsp.getTableCellData('natality-table', 0, 1).then(function (data) {
            expect(data).to.contains('279');
        });

        fsp.getTableHeaders('tb-table').then(function (headers) {
            expect(headers[0]).to.contains('Measure');
            expect(headers[1]).to.contains('American Indian or Alaska Native');
            expect(headers[2]).to.contains('Asian');
            expect(headers[3]).to.contains('Black or African American');
            expect(headers[4]).to.contains('Native Hawaiian or Other Pacific Islander');
            expect(headers[5]).to.contains('Multiple races');
            expect(headers[6]).to.contains('Hispanic or Latino');

        });
        fsp.getTableCellData('tb-table', 0, 1).then(function (data) {
            expect(data).to.contains('0');
        });
        fsp.getTableHeaders('std-table').then(function (headers) {
            expect(headers[0]).to.contains('Disease');
            expect(headers[1]).to.contains('Measure');
            expect(headers[2]).to.contains('American Indian or Alaska Native');
            expect(headers[3]).to.contains('Asian');
            expect(headers[4]).to.contains('Black or African American');
            expect(headers[5]).to.contains('Native Hawaiian or Other Pacific Islander');
            expect(headers[6]).to.contains('Multiple races');
            expect(headers[7]).to.contains('Hispanic or Latino');

        });
        fsp.getTableCellData('std-table', 0, 2).then(function (data) {
            expect(data).to.contains('36');
        });
        fsp.getTableHeaders('hiv-table').then(function (headers) {
            expect(headers[0]).to.contains('Indicator');
            expect(headers[1]).to.contains('Measure');
            expect(headers[2]).to.contains('American Indian or Alaska Native');
            expect(headers[3]).to.contains('Asian');
            expect(headers[4]).to.contains('Black or African American');
            expect(headers[5]).to.contains('Native Hawaiian or Other Pacific Islander');
            expect(headers[6]).to.contains('Multiple races');
            expect(headers[7]).to.contains('Hispanic or Latino');

        });
        fsp.getTableCellData('hiv-table', 0, 2).then(function (data) {
            expect(data).to.contains('2');
        });
        fsp.getTableHeaders('cancer-table').then(function (headers) {
            expect(headers[0]).to.contains('Cancer Site');
            expect(headers[1]).to.contains('Measure');
            expect(headers[2]).to.contains('American Indian or Alaska Native');
            expect(headers[3]).to.contains('Asian or Pacific Islander');
            expect(headers[4]).to.contains('Black');
            expect(headers[5]).to.contains('Hispanic');
        });
        fsp.getTableCellData('cancer-table', 0, 2).then(function (data) {
            expect(data).to.contains('17,865');
        }).then(next);

    });

    this.When(/^I select state "([^"]*)" from state selectbox$/, function (arg1, next) {
        element(by.id('state')).element(by.cssContainingText('option', arg1)).click()
            .then(next);
    });

    this.When(/^I select fact sheet type "([^"]*)"$/, function (factsheetType) {
        return fsp.selectFactSheetType(factsheetType);
    });

       //pdf download
    this.Then(/^I select <state> and fact sheet type "([^"]*)" and generated data downloaded file defined in "([^"]*)"$/, function (factType, csvFile, table, next) {
        table.rows().forEach(function (row) {
            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.downloadFactSheetLink.click();
            browser.sleep(1000);
        });
        next();
    });

//Population racial distribution- Minority Health
    this.Then(/^For <state> and type "([^"]*)" the generated population racial distributions data as defined in "([^"]*)" file$/, function (factType, csvFile, table, next) {
        table.rows().forEach(function (row) {

            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.getTableHeaders('bridge-race-table1').then(function (headers) {
                expect(headers[0]).to.contains('Racial distributions of minority residents*');
                expect(headers[1]).to.contains('American Indian or Alaska Native');
                expect(headers[2]).to.contains('Asian or Pacific Islander');
                expect(headers[3]).to.contains('Black or African American');
                expect(headers[4]).to.contains('Hispanic');
            });

            var populations = fsp.loadCsvFile(csvFile);
            var p = populations
                .find(function (p) {
                    return p.state === state
                });
            fsp.getTableCellData('bridge-race-table1', 0,0).then(function (data) {
                expect(data).to.contains(p['Racialdistributions']);
            });
            fsp.getTableCellData('bridge-race-table1', 0,1).then(function (data) {
                expect(data).to.contains(p['American Indian or Alaska Native']);
            });
            fsp.getTableCellData('bridge-race-table1', 0, 2).then(function (data) {
                expect(data).to.contains(p['Asian or Pacific Islander']);
            });
            fsp.getTableCellData('bridge-race-table1', 0, 3).then(function (data) {
                expect(data).to.contains(p['Black or African American']);
            });
            fsp.getTableCellData('bridge-race-table1', 0, 4).then(function (data) {
                expect(data).to.contains(p['Hispanic']);
            });
            //console.log('state =', state)
        });
        next();
    });
    //Population Age Distribution
    this.Then(/^For <state> and type "([^"]*)" the generated population data as defined in "([^"]*)" file$/, function (factType, csvFile, table, next) {

        table.rows().forEach(function (row) {

            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();

            fsp.getTableHeaders('bridge-race-table2').then(function (headers) {
                expect(headers[0]).to.contains('Age distributions of minority residents');
                expect(headers[1]).to.contains('10-14');
                expect(headers[2]).to.contains('15-19');
                expect(headers[3]).to.contains('20-44');
                expect(headers[4]).to.contains('45-64');
                expect(headers[5]).to.contains('65-84');
                expect(headers[6]).to.contains('85+');
            });

            var populations = fsp.loadCsvFile(csvFile);
            var p = populations
                .find(function (p) {
                    return p.State === state
                });
            fsp.getTableCellData('bridge-race-table2', 0, 0).then(function (data) {
                expect(data).to.contains(p['Age']);
            });
            fsp.getTableCellData('bridge-race-table2', 0, 1).then(function (data) {
                expect(data).to.contains(p['10-14']);
            });
            fsp.getTableCellData('bridge-race-table2', 0, 2).then(function (data) {
                expect(data).to.contains(p['15-19']);
            });
            fsp.getTableCellData('bridge-race-table2', 0, 3).then(function (data) {
                expect(data).to.contains(p['20-44']);
            });
            fsp.getTableCellData('bridge-race-table2', 0, 4).then(function (data) {
                expect(data).to.contains((p['45-64']));
            });
            fsp.getTableCellData('bridge-race-table2', 0, 5).then(function (data) {
                expect(data).to.contains((p['65-84']));
            });
            fsp.getTableCellData('bridge-race-table2', 0, 6).then(function (data) {
                expect(data).to.contains((p['85+']));
            });

        });
        next();

    });

    //Infant Mortality data-set
    this.Then(/^For <state> and type "([^"]*)" the generated Infant Mortality data as defined in "([^"]*)" file$/, function (factType, csvFile, table, next) {
        // Write code here that turns the phrase above into concrete actions
        table.rows().forEach(function (row) {
            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.getTableHeaders('infant-mortality-table').then(function (headers) {
                expect(headers[0]).to.contains('Measure');
                expect(headers[1]).to.contains('American Indian or Alaska Native');
                expect(headers[2]).to.contains('Asian or Pacific Islander');
                expect(headers[3]).to.contains('Black or African American');
                expect(headers[4]).to.contains('Hispanic');
            });
            var infantMortality = fsp.loadCsvFile(csvFile);

            var imList = infantMortality
                .filter(function (im) {
                    return im.State === state
                });
            imList.forEach(function (item, i) {

                    fsp.getTableCellData('infant-mortality-table', i, 0).then(function (data) {
                        expect(data).to.contains(item.Measure);

                    });

                fsp.getTableCellData('infant-mortality-table', i, 1).then(function (data) {
                    expect(data).to.contains(item['American Indian or Alaska Native']);

                });
                fsp.getTableCellData('infant-mortality-table', i, 2).then(function (data) {
                    expect(data).to.contains(item['Asian or Pacific Islander']);

                });
                fsp.getTableCellData('infant-mortality-table', i, 3).then(function (data) {
                    expect(data).to.contains(item['Black or African American']);
                });
                fsp.getTableCellData('infant-mortality-table', i, 4).then(function (data) {
                    expect(data).to.contains(item['Hispanic']);
                });
            });
            //console.log('state =', state);
        });

        next();
    });

    // Tuberculosis dataset-factsheet
    this.Then(/^For <state> and type "([^"]*)" the generated Tuberculosis data as defined in "([^"]*)" file$/, function (factType, csvFile, table, next) {
        // Write code here that turns the phrase above into concrete actions
        table.rows().forEach(function (row) {
            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.getTableHeaders('tb-factsheet').then(function (headers) {
                expect(headers[0]).to.contains('Measure');
                expect(headers[1]).to.contains('American Indian or Alaska Native');
                expect(headers[2]).to.contains('Asian');
                expect(headers[3]).to.contains('Black or African American');
                expect(headers[4]).to.contains('Native Hawaiian or Other Pacific Islander');
                expect(headers[5]).to.contains('Multiple races');
                expect(headers[6]).to.contains('Hispanic or Latino');
            });

            var tuberculosis = fsp.loadCsvFile(csvFile);
            var tbData = tuberculosis
                .filter(function (tb) {
                    return tb.State === state
                });
            tbData.forEach(function (item, i) {
                fsp.getTableCellData('tb-factsheet', i, 0).then(function (data) {
                    expect(data).to.contains(item.Measure);
                });

                fsp.getTableCellData('tb-factsheet', i, 1).then(function (data) {
                    expect(data).to.contains(item['American Indian or Alaska Native']);
                });
                fsp.getTableCellData('tb-factsheet', i, 2).then(function (data) {
                    expect(data).to.contains(item.Asian);
                });
                fsp.getTableCellData('tb-factsheet', i, 3).then(function (data) {
                    expect(data).to.contains(item['Black or African American']);
                });
                fsp.getTableCellData('tb-factsheet', i, 4).then(function (data) {
                    expect(data).to.contains(item['Native Hawaiian or Other Pacific Islander']);
                });
                fsp.getTableCellData('tb-factsheet', i, 5).then(function (data) {
                    expect(data).to.contains(item['Multiple races']);
                });
                fsp.getTableCellData('tb-factsheet', i, 6).then(function (data) {
                    expect(data).to.contains(item['Hispanic or Latino']);
                });

            });
        });
        next();
    });
    //Births-Minority health dataset factsheet
    this.Then(/^For <state> and type "([^"]*)" the generated Births data as defined in "([^"]*)" file$/, function (factType, csvFile, table, next) {
        table.rows().forEach(function (row) {
            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.getTableHeaders('natality-table').then(function (headers) {
                expect(headers[0]).to.contains('Measure');
                expect(headers[1]).to.contains('American Indian or Alaska Native');
                expect(headers[2]).to.contains('Asian or Pacific Islander');
                expect(headers[3]).to.contains('Black or African American');
            });
            var birth = fsp.loadCsvFile(csvFile);
            var birthData = birth
                .filter(function (br) {
                    return br.state === state
                });

            birthData.forEach(function (item, i) {
                fsp.getTableCellData('natality-table', i, 0).then(function (data) {
                    expect(data).to.contains(item.Measure);
                    // console.log(item.Measure);
                });
                fsp.getTableCellData('natality-table', i, 1).then(function (data) {
                    expect(data).to.contains(item['American Indian or Alaska Native']);
                });
                fsp.getTableCellData('natality-table', i, 2).then(function (data) {
                    expect(data).to.contains(item['Asian or Pacific Islander']);
                });
                fsp.getTableCellData('natality-table', i, 3).then(function (data) {
                    expect(data).to.contains(item['Black or African American']);
                });
            });
            //console.log('state =', state);
        });
        next();
    });

    //Behavioral Risk -Minority data set
    this.Then(/^For <state> and type "([^"]*)" the generated Behavioral Risk data as defined in "([^"]*)" file$/, function (factType, csvFile, table, next) {
            table.rows().forEach(function (row) {
            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.getTableHeaders('brfss-table').then(function (headers) {
                expect(headers[0]).to.contains('Question');
                expect(headers[1]).to.contains('American Indian or Alaskan Native, non-Hispanic');
                expect(headers[2]).to.contains('Asian, non-Hispanic');
                expect(headers[3]).to.contains('Black, non-Hispanic');
                expect(headers[4]).to.contains('Native Hawaiian or other Pacific Islander, non-Hispanic');
                expect(headers[5]).to.contains('Multiracial non-Hispanic');
                expect(headers[6]).to.contains('Other, non-Hispanic');
                expect(headers[7]).to.contains('Hispanic');
            });
            var behavioral_risk_dataset = fsp.loadCsvFile(csvFile);
            var brfssData = behavioral_risk_dataset
                .filter(function (br) {
                    return br.state === state
                });

                brfssData.forEach(function (item, i) {
                fsp.getTableCellData('brfss-table', i,0).then(function (data) {
                    expect(data).to.contains(item.Question);
                });
                fsp.getTableCellData('brfss-table', i, 1).then(function (data) {
                    expect(data).to.contains(item.AmericanIndian);
                });
                fsp.getTableCellData('brfss-table', i, 2).then(function (data) {
                    expect(data).to.contains(item.Asian);
                });
                fsp.getTableCellData('brfss-table', i, 3).then(function (data) {
                    expect(data).to.contains(item.Black);
                });
                fsp.getTableCellData('brfss-table', i, 4).then(function (data) {
                    expect(data).to.contains(item.Hispanic);
                });
                fsp.getTableCellData('brfss-table', i, 5).then(function (data) {
                        expect(data).to.contains(item.Multiracial);
                    });
                fsp.getTableCellData('brfss-table', i, 6).then(function (data) {
                    expect(data).to.contains(item.NativeHawaiian);
                });
                fsp.getTableCellData('brfss-table', i, 7).then(function (data) {
                    expect(data).to.contains(item.OthernonHispanic);
                });
            });
        });

        next();
    });

   //Teen health dataset- Minority -Health
    this.Then(/^For <state> and type "([^"]*)" the generated teen health data as defined in "([^"]*)" file$/, function (factType, csvFile, table, next) {
        table.rows().forEach(function (row) {
            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.getTableHeaders('yrbs-table').then(function (headers) {
                expect(headers[0]).to.contains('Question');
                expect(headers[1]).to.contains('American Indian or Alaska Native');
                expect(headers[2]).to.contains('Asian');
                expect(headers[3]).to.contains('Black or African American');
                expect(headers[4]).to.contains('Native Hawaiian or Other Pacific Islander');
                expect(headers[5]).to.contains('Multiple Race');
                expect(headers[6]).to.contains('Hispanic or Latino');
            });
            var teen_dataset = fsp.loadCsvFile(csvFile);
            var teenData = teen_dataset
                .filter(function (th) {
                    return th.state === state
                });

            teenData.forEach(function (item, i) {
                fsp.getTableCellData('yrbs-table', i, 0).then(function (data) {
                    expect(data).to.contains(item.Question);
                });
                fsp.getTableCellData('yrbs-table', i, 1).then(function (data) {
                    expect(data).to.contains(item.AmericanIndian);
                });
                fsp.getTableCellData('yrbs-table', i, 2).then(function (data) {
                    expect(data).to.contains(item.Asian);
                });
                fsp.getTableCellData('yrbs-table', i, 3).then(function (data) {
                    expect(data).to.contains(item.Black);
                });
                fsp.getTableCellData('yrbs-table', i, 4).then(function (data) {
                    expect(data).to.contains(item.NativeHawaiian);
                });
                fsp.getTableCellData('yrbs-table', i, 5).then(function (data) {
                    expect(data).to.contains(item.MultipleRace);
                });
                fsp.getTableCellData('yrbs-table', i, 6).then(function (data) {
                    expect(data).to.contains(item.Hispanic);

                });

            });

        });
        next();

    });

    //Sexually Transmitted Infections

    this.Then(/^For <state> and type "([^"]*)" the generated STD data as defined in "([^"]*)" file$/, function (factType, csvFile, table, next) {
        table.rows().forEach(function (row) {
            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.getTableHeaders('std-table').then(function (headers) {
                expect(headers[0]).to.contains('Disease');
                expect(headers[1]).to.contains('Measure');
                expect(headers[2]).to.contains('American Indian or Alaska Native');
                expect(headers[3]).to.contains('Asian');
                expect(headers[4]).to.contains('Black or African American');
                expect(headers[5]).to.contains('Native Hawaiian or Other Pacific Islander');
                expect(headers[6]).to.contains('Multiple races');
                expect(headers[7]).to.contains('Hispanic or Latino');
            });
            var std_dataset = fsp.loadCsvFile(csvFile);
            var stdStateData = std_dataset
                .filter(function (stdRow) {
                    return stdRow.state === state
                });

           var diseaseData = _.groupBy(stdStateData, function (o) {
               return o['Disease'];

            })
            Object.keys(diseaseData).forEach(function (disease, bodyIndex) {

                var casesAndRates= diseaseData[disease];
                casesAndRates.forEach(function (item,i) {
                    //console.log('currrent kk', bodyIndex, i, item);

                    //case - measure - measure
                    fsp.getTableBodyCellData('std-table',bodyIndex,i,1-i).then(function (data) {
                        expect(data).to.contains(item['Measure']);

                    });

                    fsp.getTableBodyCellData('std-table',bodyIndex,i,2-i).then(function (data) {
                        expect(data).to.contains(item['AmericanIndian']);

                    });

                    fsp.getTableBodyCellData('std-table',bodyIndex,i,3-i).then(function (data) {
                        expect(data).to.contains(item['Asian']);

                    });
                    fsp.getTableBodyCellData('std-table',bodyIndex,i,4-i).then(function (data) {
                        expect(data).to.contains(item['Black']);

                    });
                    fsp.getTableBodyCellData('std-table',bodyIndex,i,5-i).then(function (data) {
                        expect(data).to.contains(item['NativeHawaiian']);
                    });

                    fsp.getTableBodyCellData('std-table',bodyIndex,i,6-i).then(function (data) {
                        expect(data).to.contains(item['Multipleraces']);
                    });
                    fsp.getTableBodyCellData('std-table',bodyIndex,i,7-i).then(function (data) {
                        expect(data).to.contains(item['Hispanic']);

                    });

                });
            });

        });
        next();
   });

    //Mortality - Minority-Health Dataset Fact sheet

    this.Then(/^For <state> and type "([^"]*)" the generated Mortality data as defined in "([^"]*)" file$/, function (factType, csvFile, table,next) {
        table.rows().forEach(function (row) {
            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.getTableHeaders('detail-mortality-table').then(function (headers) {
                expect(headers[0]).to.contains('Cause of Death');
                expect(headers[1]).to.contains('Measure');
                expect(headers[2]).to.contains('American Indian or Alaska Native');
                expect(headers[3]).to.contains('Asian or Pacific Islander');
                expect(headers[4]).to.contains('Black or African American');
                expect(headers[5]).to.contains('Hispanic');
            });

            var mortalityDataset = fsp.loadCsvFile(csvFile);
            var mortalityStateData = mortalityDataset
                .filter(function (mortalityRow) {
                    return mortalityRow.state === state
                });

            var causeOfDeathData = _.groupBy(mortalityStateData, function (o) {
                return o['CauseofDeath'];
            })
            Object.keys(causeOfDeathData).forEach(function (causeOfDeath, bodyIndex) {

                var totalAndAgeRates = causeOfDeathData[causeOfDeath];
                totalAndAgeRates.forEach(function (item, i) {

                    fsp.getTableBodyCellData('detail-mortality-table', bodyIndex, i, 1-i).then(function (data) {
                        //console.log("currentitem",i,data);
                        expect(data).to.contains(item['Measure']);

                    });

                    fsp.getTableBodyCellData('detail-mortality-table',bodyIndex,i,2-i).then(function (data) {
                        expect(data).to.contains(item['AmericanIndian']);

                    });

                    fsp.getTableBodyCellData('detail-mortality-table',bodyIndex,i,3-i).then(function (data) {
                        expect(data).to.contains(item['AsianorPacific']);

                    });
                    fsp.getTableBodyCellData('detail-mortality-table',bodyIndex,i,4-i).then(function (data) {
                        expect(data).to.contains(item['BlackorAfrican']);

                    });
                    fsp.getTableBodyCellData('detail-mortality-table',bodyIndex,i,5-i).then(function (data) {
                        expect(data).to.contains(item['Hispanic']);

                    });
                });
            });

        });
        next();
    });

    //HIV-AIDS Data set
    this.Then(/^For <state> and type "([^"]*)" the generated HIV\-AIDS data as defined in "([^"]*)" file$/, function (factType, csvFile, table,next) {
        table.rows().forEach(function (row) {
            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.getTableHeaders('hiv-table').then(function (headers) {
                expect(headers[0]).to.contains('Indicator');
                expect(headers[1]).to.contains('Measure');
                expect(headers[2]).to.contains('American Indian or Alaska Native');
                expect(headers[3]).to.contains('Asian');
                expect(headers[4]).to.contains('Black or African American');
                expect(headers[5]).to.contains('Native Hawaiian or Other Pacific Islander');
                expect(headers[6]).to.contains('Multiple races');
                expect(headers[7]).to.contains('Hispanic or Latino');
            });
            var hivDataset = fsp.loadCsvFile(csvFile);
            var hivStateData = hivDataset
                .filter(function (hivStateRow) {
                    return hivStateRow.state === state
                });

            var indicatorData = _.groupBy(hivStateData, function (o) {
                return o['Indicator'];
            })
            Object.keys(indicatorData).forEach(function (indicator, bodyIndex) {

                var casesAndRates = indicatorData[indicator];
                casesAndRates.forEach(function (item,i) {
                    //console.log('currrent kk', bodyIndex, i, item);

                    // measure
                    fsp.getTableBodyCellData('hiv-table', bodyIndex, i, 1 - i).then(function (data) {
                        expect(data).to.contains(item['Measure']);

                    });

                    fsp.getTableBodyCellData('hiv-table', bodyIndex, i, 2 - i).then(function (data) {
                        expect(data).to.contains(item['American Indian or Alaska Native']);

                    });

                    fsp.getTableBodyCellData('hiv-table', bodyIndex, i, 3 - i).then(function (data) {
                        expect(data).to.contains(item['Asian']);

                    });
                    fsp.getTableBodyCellData('hiv-table', bodyIndex, i, 4 - i).then(function (data) {
                        expect(data).to.contains(item['Black or African American']);

                    });
                    fsp.getTableBodyCellData('hiv-table', bodyIndex, i, 5 - i).then(function (data) {
                        expect(data).to.contains(item['Native Hawaiian or Other Pacific Islander']);

                    });
                    fsp.getTableBodyCellData('hiv-table', bodyIndex, i, 6 - i).then(function (data) {
                        expect(data).to.contains(item['Multiple races']);

                    });

                    fsp.getTableBodyCellData('hiv-table', bodyIndex, i, 7 - i).then(function (data) {
                        expect(data).to.contains(item['Hispanic or Latino']);

                    });

                });
            });

        });
       next();
    });

    // Cancer Statistics data set
    this.Then(/^For <state> and type "([^"]*)" the generated Cancer Statistics data as defined in "([^"]*)" file$/, function (factType, csvFile, table,next) {
        table.rows().forEach(function (row) {
            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();

            fsp.getTableHeaders('cancer-table').then(function (headers) {
                expect(headers[0]).to.contains('Cancer Site');
                expect(headers[1]).to.contains('Measure');
                expect(headers[2]).to.contains('American Indian or Alaska Native');
                expect(headers[3]).to.contains('Asian or Pacific Islander');
                expect(headers[4]).to.contains('Black');
                expect(headers[5]).to.contains('Hispanic');
            });

        var cancerDataset = fsp.loadCsvFile(csvFile);
        var cancerStateData = cancerDataset
            .filter(function (cancerStateRow) {
                return cancerStateRow.state === state
            });

        var cancerSiteData = _.groupBy(cancerStateData, function (o) {
            return o['Cancer Site'];
        });

        Object.keys(cancerSiteData).forEach(function (cancerSite, bodyIndex) {

            var cancerSiteRows = cancerSiteData[cancerSite];

            cancerSiteRows.forEach(function (item, i) {
               //console.log('currrent kk',  i, item);

                var correctionFactor = i %5 ==  0 ? 0 : 1;

                fsp.getTableBodyCellData('cancer-table', bodyIndex, i, 1 - correctionFactor).then(function (data) {
                    expect(data).to.contains(item['Measure']);

                });

                fsp.getTableBodyCellData('cancer-table', bodyIndex, i, 2 - correctionFactor).then(function (data) {
                     expect(data).to.contains(item['American Indian or Alaska Native']);

                });
                 fsp.getTableBodyCellData('cancer-table', bodyIndex, i, 3 - correctionFactor).then(function (data) {
                     expect(data).to.contains(item['Asian or Pacific Islander']);

                 });
                 fsp.getTableBodyCellData('cancer-table', bodyIndex, i, 4 - correctionFactor).then(function (data) {
                     expect(data).to.contains(item['Black']);

                 });
                 fsp.getTableBodyCellData('cancer-table', bodyIndex, i, 5 - correctionFactor).then(function (data) {
                     expect(data).to.contains(item['Hispanic']);

                 });

            });

            });
            });

        next();
    });

    //Prenatal Care and Pregnancy Risk - Minority Health
    this.Then(/^For <state> and type "([^"]*)" the generated Pregenent Women data as defined in "([^"]*)" file$/, function (factType, csvFile, table,next) {

        table.rows().forEach(function (row) {

            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.getTableHeaders('prams-table-1').then(function (headers) {
                expect(headers[0]).to.contains('Question');
                expect(headers[1]).to.contains('Black, Non-Hispanic');
                expect(headers[2]).to.contains('Other, Non- Hispanic');
                expect(headers[3]).to.contains('Hispanic');
            });
            var pramsDataSet = fsp.loadCsvFile(csvFile);
            var pramsData = pramsDataSet
                .filter(function (p) {
                    return p.state === state
                });
                pramsData.forEach(function (item, i) {
                fsp.getTableCellData('prams-table-1', i, 0).then(function (data) {
                   expect(data).to.contains(item['Question']);
                });

                fsp.getTableCellData('prams-table-1', i, 1).then(function (data) {
                   expect(data).to.contains(item['Black, Non-Hispanic']);
                });
                fsp.getTableCellData('prams-table-1', i, 2).then(function (data) {
                    expect(data).to.contains(item['Other, Non- Hispanic']);
                });
                fsp.getTableCellData('prams-table-1', i,3).then(function (data) {
                    expect(data).to.contains(item['Hispanic']);
                });
            });
        });

        next();
    });
//Womens and Girls health fact sheet
    this.Then(/^For  select <state> and select type is "([^"]*)" then generated population data as defined in "([^"]*)" file$/, function (factType, csvFile, table,next) {
        // Write code here that turns the phrase above into concrete actions
        table.rows().forEach(function (row) {

            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.getTableHeaders('bridge-race-table1').then(function (headers) {
                expect(headers[0]).to.contains('Racial distributions of female residents');
                expect(headers[1]).to.contains('Black, non-Hispanic');
                expect(headers[2]).to.contains('White, non-Hispanic');
                expect(headers[3]).to.contains('American Indian');
                expect(headers[4]).to.contains('Asian or Pacific Islander');
                expect(headers[5]).to.contains('Hispanic');
            });
            var populationDataset = fsp.loadCsvFile(csvFile);
            var p = populationDataset
                .find(function (p) {
                    return p.state === state
                });
            fsp.getTableCellData('bridge-race-table1', 0,0).then(function (data) {
                expect(data).to.contains(p['Racial distributions of female residents']);
            });
            fsp.getTableCellData('bridge-race-table1', 0, 1).then(function (data) {
                expect(data).to.contains(p['Black']);
            });
            fsp.getTableCellData('bridge-race-table1', 0,2).then(function (data) {
                expect(data).to.contains(p['White']);
            });
            fsp.getTableCellData('bridge-race-table1', 0, 3).then(function (data) {
                expect(data).to.contains(p['American Indian']);
            });
            fsp.getTableCellData('bridge-race-table1', 0, 4).then(function (data) {
                expect(data).to.contains(p['Asian or Pacific Islander']);
            });
            fsp.getTableCellData('bridge-race-table1', 0,5).then(function (data) {
                expect(data).to.contains(p['Hispanic']);
            });

        });

        next();
    });

    //Mortality - Womens Health

    this.Then(/^For  select <state> and select type is "([^"]*)" then generated Mortality data as defined in "([^"]*)" file$/, function (factType, csvFile, table, next) {
        table.rows().forEach(function (row) {

            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();

            fsp.getTableHeaders('detail-mortality-table').then(function (headers) {
                expect(headers[0]).to.contains('Cause of Death');
                expect(headers[1]).to.contains('Age-Adjusted Death Rates (per 100,000 women)');
            });

            var mortalityDataset = fsp.loadCsvFile(csvFile);
            var p = mortalityDataset
                .find(function (p) {
                    return p.state === state
                });
            fsp.getTableCellData('detail-mortality-table', 0, 0).then(function (data) {
                expect(data).to.contains(p['Cause of Death']);
            });
            fsp.getTableCellData('detail-mortality-table', 0, 1).then(function (data) {
                expect(data).to.contains(p['Age-Adjusted Death Rates (per 100,000 women)']);
            });

        });

        next();
    });

    //Prenatal Care and Pregnancy Risk
    this.Then(/^For  select <state> and select type is "([^"]*)" then generated PRAMS data as defined in "([^"]*)" file$/, function (factType, csvFile, table, next) {
            table.rows().forEach(function(row){
                var state = row[0];
                element(by.id('state')).element(by.cssContainingText('option', state)).click();
                fsp.selectFactSheetType(factType);
                fsp.generateFactSheetLink.click();
                fsp.getTableHeaders('prams-table-1').then(function (headers) {
                    expect(headers[0]).to.contains('Survey Question');
                    expect(headers[1]).to.contains('Percentage (Women)');
                });

                var pramsDataSet = fsp.loadCsvFile(csvFile);
                var pramsData = pramsDataSet
                    .filter(function (p) {
                        return p.state === state
                    });
                pramsData.forEach(function (item, i) {
                    fsp.getTableCellData('prams-table-1', i, 0).then(function (data) {
                        expect(data).to.contains(item['Survey Question']);
                    });
                    fsp.getTableCellData('prams-table-1', i, 1).then(function (data) {
                        expect(data).to.contains(item['Percentage (Women)']);
                    });
                });

        });

        next();
    });

    //Behavioral Risk Factors - Womens and Girls Health
    this.Then(/^For  select <state> and select type is "([^"]*)" then generated Behavioral Risk Factors data as defined in "([^"]*)" file$/, function (factType, csvFile, table, next) {

        table.rows().forEach(function (row) {
            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.getTableHeaders('brfss-table').then(function (headers) {
                expect(headers[0]).to.contains('Survey Question');
                expect(headers[1]).to.contains('Percentage (Women)');
            });
            var behavioral_risk_dataset = fsp.loadCsvFile(csvFile);
            var brfssData = behavioral_risk_dataset
                .filter(function (br) {
                    return br.state === state
                });

            brfssData.forEach(function (item, i) {
                fsp.getTableCellData('brfss-table', i, 0).then(function (data) {
                    expect(data).to.contains(item['Survey Question']);
                });
                fsp.getTableCellData('brfss-table', i, 1).then(function (data) {
                    expect(data).to.contains(item['Percentage (Women)']);
                });
            });
        });

                next();
        });

//Teen Health - Womens Health
    this.Then(/^For  select <state> and select type is "([^"]*)" then generated Teen Health fact sheet data as defined in "([^"]*)" file$/, function (factType, csvFile, table, next) {

        table.rows().forEach(function (row) {
            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.getTableHeaders('yrbs-table').then(function (headers) {
                expect(headers[0]).to.contains('Survey Question');
                expect(headers[1]).to.contains('Percentage (Girls)');

            });
            var teen_dataset = fsp.loadCsvFile(csvFile);
            var teenData = teen_dataset
                .filter(function (th) {
                    return th.state === state
                });
            teenData.forEach(function (item, i) {
                fsp.getTableCellData('yrbs-table', i, 0).then(function (data) {
                    expect(data).to.contains(item['Survey Question']);
                });
                fsp.getTableCellData('yrbs-table', i, 1).then(function (data) {
                    expect(data).to.contains(item['Percentage (Girls)']);
                });

            });
        });

        next();
    });

    //Sexually Transmitted Infections- Womens and Girls Health

    this.Then(/^For  select <state> and select type is "([^"]*)" then generated STD fact sheet data as defined in "([^"]*)" file$/, function (factType, csvFile, table, next) {
        table.rows().forEach(function (row) {
            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.getTableHeaders('std-table').then(function (headers) {
                expect(headers[0]).to.contains('Disease');
                expect(headers[1]).to.contains('Total Rates (per 100,000 women)');
            });
            var std_dataset = fsp.loadCsvFile(csvFile);
            var stdData = std_dataset
                .filter(function (std) {
                    return std.state === state
                });
            stdData.forEach(function (item, i) {
                fsp.getTableCellData('std-table', i, 0).then(function (data) {
                    expect(data).to.contains(item['Disease']);
                });
                fsp.getTableCellData('std-table', i, 1).then(function (data) {
                    expect(data).to.contains(item['Total Rates (per 100,000 women)']);
                });
            });
        });

       next();
    });

// HIV/AIDS Data set - Women's and Girl's  Health fact sheet
    this.Then(/^For  select <state> and select type is "([^"]*)" then generated HIV\/AIDS fact sheet data as defined in "([^"]*)" file$/, function (factType,csvFile,table,next) {
        table.rows().forEach(function (row) {
            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.getTableHeaders('hiv-table').then(function (headers) {
                expect(headers[0]).to.contains('Indicator');
                expect(headers[1]).to.contains('Total Rates (per 100,000 women)');
            });
            var hiv_dataset = fsp.loadCsvFile(csvFile);
            var hivData = hiv_dataset
                .filter(function (hiv) {
                    return hiv.state === state
                });
            hivData.forEach(function (item, i) {
                fsp.getTableCellData('hiv-table', i, 0).then(function (data) {
                    expect(data).to.contains(item['Indicator']);
                });
                fsp.getTableCellData('hiv-table', i, 1).then(function (data) {
                    expect(data).to.contains(item['Total Rates (per 100,000 women)']);
                });
            });
        });
        next();
    });
    //Cancer Statistics - Women's and Girl's  Health fact sheet
    this.Then(/^For  select <state> and select type is "([^"]*)" then generated Cancer Statistics fact sheet data as defined in "([^"]*)" file$/, function (factType,csvFile,table,next) {
        table.rows().forEach(function (row) {
            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();

            fsp.getTableHeaders('cancer-table').then(function (headers) {
                expect(headers[0]).to.contains('Cancer Site');
                expect(headers[1]).to.contains('Incidence Crude Rates (per 100,000 women)');
                expect(headers[2]).to.contains('Mortality Crude Rates (per 100,000 women)');
            });
            var cancer_dataset = fsp.loadCsvFile(csvFile);
            var cancerData = cancer_dataset
                .filter(function (cancer) {
                    return cancer.state === state
                });
            cancerData.forEach(function (item, i) {
                fsp.getTableCellData('cancer-table', i, 0).then(function (data) {
                    expect(data).to.contains(item['Cancer Site']);
                });
                fsp.getTableCellData('cancer-table', i, 1).then(function (data) {
                    expect(data).to.contains(item['Incidence Crude Rates (per 100,000 women)']);
                });
                fsp.getTableCellData('cancer-table', i, 2).then(function (data) {
                    expect(data).to.contains(item['Mortality Crude Rates (per 100,000 women)']);
                });
            });

        });

        next();
    });

    // pdf download - Women's and Girl's  Health fact sheet
    this.Then(/^For select <state> and select type is "([^"]*)" then generated fact sheet data as defined in "([^"]*)"$/, function (factType,csvFile,table,next) {
        table.rows().forEach(function (row) {
            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.downloadFactSheetLink.click();
            //browser.sleep(1000);

    });
        next();
    });

    // Racial Distribution of Residents - State -Health
    this.Then(/^For select <state> and type "([^"]*)" the generated population racial distributions data as defined in "([^"]*)" file$/, function (factType,csvFile,table,next) {

        table.rows().forEach(function (row) {

            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.getTableHeaders('bridge-race-table1').then(function (headers) {
                expect(headers[0]).to.contains('Racial Distributions of Residents*');
                expect(headers[1]).to.contains('Total');
                expect(headers[2]).to.contains('Black, non-Hispanic');
                expect(headers[3]).to.contains('White, non-Hispanic');
                expect(headers[4]).to.contains('American Indian or Alaska Native');
                expect(headers[5]).to.contains('Asian or Pacific Islander');
                expect(headers[6]).to.contains('Hispanic');
            });

            var populations = fsp.loadCsvFile(csvFile);
            var p = populations
                .find(function (p) {
                    return p.state === state
                });
            fsp.getTableCellData('bridge-race-table1', 0,0).then(function (data) {
                expect(data).to.contains(p['Racial Distributions of Residents*']);
            });
            fsp.getTableCellData('bridge-race-table1', 0,1).then(function (data) {
                expect(data).to.contains(p['Total']);
            });
            fsp.getTableCellData('bridge-race-table1', 0, 2).then(function (data) {
                expect(data).to.contains(p['Black, non-Hispanic']);
            });
            fsp.getTableCellData('bridge-race-table1', 0, 3).then(function (data) {
                expect(data).to.contains(p['White, non-Hispanic']);
            });
            fsp.getTableCellData('bridge-race-table1', 0, 4).then(function (data) {
                expect(data).to.contains(p['American Indian or Alaska Native']);
            });

            fsp.getTableCellData('bridge-race-table1', 0, 5).then(function (data) {
                expect(data).to.contains(p['Asian or Pacific Islander']);
            });

            fsp.getTableCellData('bridge-race-table1', 0, 6).then(function (data) {
                expect(data).to.contains(p['Hispanic']);
            });
            //console.log('state =', state)
        });
        next();
    });

//Age Distribution of Residents
    this.Then(/^For select <state> and type "([^"]*)" the generated Age Distribution  data as defined in "([^"]*)" file$/, function (factType,csvFile,table,next) {
        table.rows().forEach(function (row) {

            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();
            fsp.getTableHeaders('bridge-race-table2').then(function (headers) {
                expect(headers[0]).to.contains('Age Distributions of Residents');
                expect(headers[1]).to.contains('10-14');
                expect(headers[2]).to.contains('15-19');
                expect(headers[3]).to.contains('20-44');
                expect(headers[4]).to.contains('45-64');
                expect(headers[5]).to.contains('65-84');
                expect(headers[6]).to.contains('85+');
            });
            var populations = fsp.loadCsvFile(csvFile);
            var p = populations
                .find(function (p) {
                    return p.State === state
                });
            fsp.getTableCellData('bridge-race-table2', 0,0).then(function (data) {
                expect(data).to.contains(p['Age Distributions of Residents']);
            });
            fsp.getTableCellData('bridge-race-table2', 0,1).then(function (data) {
                expect(data).to.contains(p['10-14']);
            });
            fsp.getTableCellData('bridge-race-table2', 0, 2).then(function (data) {
                expect(data).to.contains(p['15-19']);
            });
            fsp.getTableCellData('bridge-race-table2', 0, 3).then(function (data) {
                expect(data).to.contains(p['20-44']);
            });
            fsp.getTableCellData('bridge-race-table2', 0, 4).then(function (data) {
                expect(data).to.contains(p['45-64']);
            });

            fsp.getTableCellData('bridge-race-table2', 0, 5).then(function (data) {
                expect(data).to.contains(p['65-84']);
            });

            fsp.getTableCellData('bridge-race-table2', 0, 6).then(function (data) {
                expect(data).to.contains(p['85+']);
            });
            //console.log('state =', state)

        });

        next();
    });

// Mortality state Health  fact sheet
    this.Then(/^For select <state> and type "([^"]*)" the generated Mortality fact sheet data as defined in "([^"]*)" file$/, function (factType,csvFile,table,next) {
        table.rows().forEach(function (row) {

            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();

            fsp.getTableHeaders('detail-mortality-table').then(function (headers) {
                expect(headers[0]).to.contains('Cause of Death');
                expect(headers[1]).to.contains('Number of Deaths');
                expect(headers[2]).to.contains('Age-Adjusted Death Rate (per 100,000)');
            });

            var mortalityDataset = fsp.loadCsvFile(csvFile);
            var p = mortalityDataset
                .find(function (p) {
                    return p.state === state
                });
            fsp.getTableCellData('detail-mortality-table', 0, 0).then(function (data) {
                expect(data).to.contains(p['Cause of Death']);
            });
            fsp.getTableCellData('detail-mortality-table', 0, 1).then(function (data) {
                expect(data).to.contains(p['Number of Deaths']);
            });
            fsp.getTableCellData('detail-mortality-table', 0, 2).then(function (data) {
                expect(data).to.contains(p['Age-Adjusted Death Rate (per 100,000)']);
            });

        });

       next();
    });

    //Infant Mortality - State Health fact sheet

    this.Then(/^For select <state> and type "([^"]*)" the generated Infant Mortality fact sheet data as defined in "([^"]*)" file$/, function (factType,csvFile,table,next) {
        table.rows().forEach(function (row) {

            var state = row[0];
            element(by.id('state')).element(by.cssContainingText('option', state)).click();
            fsp.selectFactSheetType(factType);
            fsp.generateFactSheetLink.click();

            fsp.getTableHeaders('infant-mortality-table').then(function (headers) {
                expect(headers[0]).to.contains('Deaths');
                expect(headers[1]).to.contains('Births');
                expect(headers[2]).to.contains('Death rates')
            });

            var mortalityDataset = fsp.loadCsvFile(csvFile);
            var p = mortalityDataset
                .find(function (p) {
                    return p.State === state
                });
            fsp.getTableCellData('infant-mortality-table', 0,0).then(function (data) {
                expect(data).to.contains(p.Deaths);
            });
            fsp.getTableCellData('infant-mortality-table', 0, 1).then(function (data) {
                expect(data).to.contains(p['Births']);
            });
            fsp.getTableCellData('infant-mortality-table', 0, 2).then(function (data) {
                expect(data).to.contains(p['Death rates']);
            });

        });
        next();
    });

};
module.exports = factsheetsDefinitionsWrapper;


text:
Ext.define('Ext.uxo.ToggleSlide', {
    extend: 'Ext.Component',
    alias: 'widget.toggleslide',

    requires: ['Ext.uxo.Thumb', 'Ext.fx.Anim'],

    /**
     * @cfg {Number} duration The duration for the slide animation (defaults to
     *      120)
     */
    duration: 120,

    /**
     * @cfg {String} onText The text to display when the toggle is in the 'On'
     *      position (defaults to 'ON')
     */
    onText: 'ON',

    /**
     * @cfg {String} offText The text to display when the toggle is in the 'Off'
     *      position (defaults to 'OFF')
     */
    offText: 'OFF',

    /**
     * @cfg {Boolean} resizeHandle Specifies whether the drag handle should be
     *      resized to cover the on or off side (defaults to true)
     */
    resizeHandle: true,

    /**
     * @cfg {Boolean} resizeContainer Specifies whether the contain element
     *      should be resized (defaults to true)
     */
    resizeContainer: true,

    /**
     * @cfg {String} onLabelCls The CSS class for the on label (defaults to
     *      'x-toggle-slide-label-on')
     */
    onLabelCls: 'x-toggle-slide-label-on',

    /**
     * @cfg {String} ofLabelCls The CSS class for the off label (defaults to
     *      'x-toggle-slide-label-off')
     */
    offLabelCls: 'x-toggle-slide-label-off',

    /**
     * @cfg {String} handleCls The CSS class for the drag handle (defaults to
     *      'x-toggle-slide-handle')
     */
    handleCls: 'x-toggle-slide-thumb',

    disabledCls: 'x-toggle-slide-disabled',

    /**
     * @cfg {Boolean} state The initial state of the Toggle (defaults to false)
     */
    state: false,

    /**
     * @cfg {Boolean} booleanMode Determines whether the internal value is
     *      represented as a Boolean. If not in booleanMode the internal value
     *      will be represented as the on or off label text. The value passed to
     *      event listeners will also be determined on this setting (defaults to
     *      true)
     */
    booleanMode: true,

    // private
    dragging: false,
    diff: 0,
    diff2: 0,
    diff3: 0,
    frame: false,

    renderTpl: ['
',
                    '',
                        '{onText}',
                    '',
                    '',
                        '{offText}',
                    '',
                '
'],

    autoEl: {
            tag: 'div',
            cls: 'x-toggle-slide-container'
    },

    initComponent: function()
    {
        var me = this;
        me.callParent(arguments);

        me.addEvents(
                /**
                 * @event beforechange Fires before this toggle is changed.
                 * @param {Ext.form.Checkbox} this This toggle
                 * @param {Boolean|String} state The next toggle state value if boolean
                 *            mode else the label for the next state
                 */
                'beforechange',

                /**
                 * @event change Fires when the toggle is on or off.
                 * @param {Ext.form.Checkbox} this This toggle
                 * @param {Boolean|String} state the new toggle state value, boolean if
                 *            in boolean mode else the label
                 */
                'change');
    },

    beforeRender: function()
    {
        var me = this;

        me.callParent();

        Ext.applyIf(me.renderData, {
            offLabelCls: me.offLabelCls,
            offText: me.offText,
            onLabelCls: me.onLabelCls,
            onText: me.onText,
            handleCls: me.handleCls
        });

    },

    /**
     * Set up the hidden field
     *
     * @param {Object} ct The container to render to.
     * @param {Object} position The position in the container to render to.
     * @private
     */
    onRender: function()
    {
        var me = this;

        if(!me.resizeContainer)
            me.diff = 0;

        if(!me.resizeHandle)
        {
            me.diff2 = 3;
            me.diff3 = 5;
        }

        me.callParent(arguments);

        if (me.cls) {
            me.el.addCls(me.cls);
        }

        me.thumb = new Ext.uxo.Thumb({
            ownerCt: me,
            slider: me,
            disabled    : !!me.disabled
        });

        var holder = me.el.first();

        me.onLabel = holder.first();
        me.onSpan = me.onLabel.first();

        me.offLabel = me.onLabel.next();
        me.offSpan = me.offLabel.first();

        if (me.rendered) {
            me.thumb.render();
        }
        me.handle = me.thumb.el;

        if(me.resizeHandle)
            me.thumb.bringToFront();
        else
            me.thumb.sendToBack();

        me.resize();
        me.disableTextSelection();

        if(!me.disabled)
        {
            me.registerToggleListeners();
        }
        else
        {
            Ext.uxo.ToggleSlide.superclass.disable.call(me);
        }
    },

    /**
     * Resize assets.
     *
     * @private
     */
    resize: function()
    {
        var me = this,
            container = me.el,
            offlabel = me.offLabel,
            onlabel = me.onLabel,
            handle = me.handle;

        if(me.resizeHandle)
        {
            var min = (onlabel.getWidth() < offlabel.getWidth()) ? onlabel.getWidth() : offlabel.getWidth();
            handle.setWidth(min);
        }

        if(me.resizeContainer)
        {
            var max = (onlabel.getWidth() > offlabel.getWidth()) ? onlabel.getWidth() : offlabel.getWidth();
            var expandPx = Math.ceil(container.getHeight() / 3);
            container.setWidth(max + handle.getWidth() + expandPx);
        }

        var b = handle.getWidth() / 2;
        onlabel.setWidth(container.getWidth() - b + me.diff2);
        offlabel.setWidth(container.getWidth() - b + me.diff2);
        var rightside = me.rightside = container.getWidth() - handle.getWidth() - me.diff;

        if(me.state)
        {
            handle.setLeft(rightside);
        }
        else
        {
            handle.setLeft(0);
        }
        me.onDrag();
    },

    /**
     * Turn off text selection.
     *
     * @private
     */
    disableTextSelection: function()
    {
        var els = [this.el,
                this.onLabel,
                this.offLabel,
                this.handle];

        Ext.each(els, function(el)
        {
            el.on('mousedown', function(evt)
            {
                evt.preventDefault();
                return false;
            });

            if(Ext.isIE)
            {
                el.on('startselect', function(evt)
                {
                    evt.stopEvent();
                    return false;
                });
            }
        });
    },

    /**
     * Animates the handle to the next state.
     *
     * @private
     */
    moveHandle: function(on, callback)
    {
        var me = this,
            runner = new Ext.util.TaskRunner(),
            to = on ? me.rightside : 0;

        Ext.create('Ext.fx.Anim', {
            target: me.handle,
            dynamic: true,
            easing: 'easeOut',
            duration: me.duration,
            to : {
                left: to
            },
            listeners: {
                beforeanimate: {
                    fn: function(ani)
                    {
                        me.task = runner.newTask({
                            run: function () {
                                me.onDrag();
                            },
                            interval: 10
                        });
                        me.task.start();
                    },
                    scope: this
                },
                afteranimate: {
                    fn: function(ani)
                    {
                        me.onDrag();
                        me.task.destroy();
                    },
                    scope: this
                }
            },
            callback: callback
        });
    },

    /**
     * Constrain the drag handle to the containing el.
     *
     * @private
     */
    onDragStart: function(e)
    {
        var me = this;

        me.dragging = true;

        me.dd.constrainTo(me.el, {
            right: me.diff
        });
    },

    /**
     * Determine if the handle has been dropped > half way into the other
     * position. Toggle if so or move the handle back to the original position
     * if not.
     *
     * @private
     */
    onDragEnd: function(e)
    {
        var me = this,
            hc = (me.handle.getLeft(true) + me.handle.getRight(true)) / 2,
            cc = (me.el.getLeft(true) + me.el.getRight(true)) / 2,
            next = hc > cc;

        (me.state != next) ? me.toggle() : me.moveHandle(next);
        me.dragging = false;
    },

    /**
     * Adjust the label and span positions with the handles.
     *
     * @private
     */
    onDrag: function(e)
    {
        var me = this,
            p = me.handle.getLeft(true) - me.rightside;

        p = (me.handle.getLeft(true) == me.rightside) ? 0 : p - me.diff3;

        me.onLabel.setStyle({
            marginLeft: p + 'px'
        });
    },

    /**
     * If not dragging toggle.
     *
     * @private
     */
    onMouseUp: function()
    {
        if(!this.dragging)
        {
            this.toggle();
        }
    },

    /**
     * Transition to the next state.
     */
    toggle: function()
    {
        var me = this,
            next = !this.state;

        if(!me.booleanMode)
        {
            next = me.state ? me.onText : me.offText;
        }

        if(me.fireEvent('beforechange', me, next) !== false)
        {
            me.state = !me.state;

            me.moveHandle(me.state, Ext.bind(me.fireEvent, me, ['change', me, me.getValue()]));
        }
        else
        {
            me.moveHandle(me.state);
        }
    },

    /**
     * If currently disabled, enable this component and fire the 'enable' event.
     *
     * @return {Ext.Component} this
     */
    enable: function()
    {
        if(this.disabled)
        {
            Ext.uxo.ToggleSlide.superclass.enable.call(this);
            this.registerToggleListeners();
            //this.thumb.enable();
        }
        return this;
    },

    /**
     * If currently enabled, disable this component and fire the 'disable'
     * event.
     *
     * @return {Ext.Component} this
     */
    disable: function()
    {
        if(!this.disabled)
        {
            Ext.uxo.ToggleSlide.superclass.disable.call(this);
            this.unregisterToggleListeners();
            //this.thumb.disable();
        }
        return this;
    },

    /**
     * Registers the mouseup listener and the DD instance for the handle.
     *
     * @private
     */
    registerToggleListeners: function()
    {
        var me = this;

        me.dd = new Ext.dd.DD(me.handle);
        me.dd.startDrag = Ext.bind(me.onDragStart, me);
        me.dd.onDrag = Ext.bind(me.onDrag, me);
        me.dd.endDrag = Ext.bind(me.onDragEnd, me);

        me.el.on('mouseup', me.onMouseUp, me);
    },

    /**
     * Unregisters the mouseup listener and the DD instance for the handle.
     *
     * @private
     */
    unregisterToggleListeners: function()
    {
        Ext.destroy(this.dd);
        this.el.un('mouseup', this.onMouseUp, this);
    },

    /**
     * Returns the current internal value, either text or boolean depending on
     * configured booleanMode.
     */
    getValue: function()
    {
        var me = this;
        return me.booleanMode ? me.state : (me.state ? me.onText : me.offText);
    }
});

redpajama_set_name: RedPajamaGithub


text:
<?php
class verification_code
{
    public $id;
    public $question;
    public $answer;

    public static function get_verification_codes()
    {
        return json_decode(file_get_contents(dirname(__DIR__)."/JsonData/VerificationCode.json"));
    }

    public static function get_verification_code_by_id($id)
    {
        $codes = self::get_verification_codes();
        foreach ($codes as $code) {
            if($code->id==$id)
                return $code;
        }
        return null;
    }
}


text:
// Autogenerated from vk-api-schema. Please don't edit it manually.
package com.vk.api.sdk.queries.donut;

import com.vk.api.sdk.client.AbstractQueryBuilder;
import com.vk.api.sdk.client.VkApiClient;
import com.vk.api.sdk.client.actors.UserActor;
import com.vk.api.sdk.objects.donut.responses.GetSubscriptionResponse;
import java.util.Arrays;
import java.util.List;

/**
 * Query for Donut.getSubscription method
 */
public class DonutGetSubscriptionQuery extends AbstractQueryBuilder<DonutGetSubscriptionQuery, GetSubscriptionResponse> {
    /**
     * Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters
     *
     * @param client VK API client
     * @param actor actor with access token
     * @param ownerId value of "owner id" parameter.
     */
    public DonutGetSubscriptionQuery(VkApiClient client, UserActor actor, int ownerId) {
        super(client, "donut.getSubscription", GetSubscriptionResponse.class);
        accessToken(actor.getAccessToken());
        ownerId(ownerId);
    }

    /**
     * Set owner id
     *
     * @param value value of "owner id" parameter.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    protected DonutGetSubscriptionQuery ownerId(int value) {
        return unsafeParam("owner_id", value);
    }

    @Override
    protected DonutGetSubscriptionQuery getThis() {
        return this;
    }

    @Override
    protected List<String> essentialKeys() {
        return Arrays.asList("owner_id", "access_token");
    }
}


text:
using System.Data.Entity;

namespace Hopnscotch.Portal.Data
{
    public interface IContextFactory<out T> where T : DbContext
    {
        T GetContext();
    }
}


text:
package com.melon.spring.aop.jdkProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface BookInterface {

    void addBook();

    void intercept();
};

public class BookImpl implements BookInterface {

    public void addBook() {
        System.out.println("dynamic@BookImpl#addBook");
    }

    public void intercept() {
        System.out.println("dynamic@BookImpl#intercept is intercepted...");
    }

    // 测试方法
    public static void main(String[] args) {
        BookProxy proxy = new BookProxy();
        BookInterface impl = (BookInterface) proxy.getInstance(new BookImpl());
        impl.intercept();
    }
};

/**
 * @projectName:ActiveMq
 * @packageName: activeMQ.topicMessage
 * @ClassName : BookProxy
 * @createBy :Test
 * @createDate :2013-2-24下午01:23:25
 * @useFor :
 */
class BookProxy implements InvocationHandler {
    /**
     * 委托类
     */
    private Object target;

    public Object getInstance(Object target) {
        this.target = target;

        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), this);
    }

    public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
        System.out.println("Before Advice");

        if ("intercept".equals(method.getName())) {
            System.out.println("intercept method is intercepted");

            return null;
        }
        // 注意此处的参数是注入的target 而不是obj
        Object result = method.invoke(target, args);
        System.out.println("After Advice");
        return result;
    }

}


text:
package org.wso2.siddhi.core.executor.function;

import org.apache.log4j.Logger;
import org.wso2.siddhi.core.config.ExecutionPlanContext;
import org.wso2.siddhi.core.executor.ExpressionExecutor;
import org.wso2.siddhi.core.function.Script;
import org.wso2.siddhi.core.util.config.ConfigReader;
import org.wso2.siddhi.query.api.definition.Attribute;

import java.util.Map;

/**
 * Executor class for Script function. Function execution logic is implemented in execute here.
 */
public class ScriptFunctionExecutor extends FunctionExecutor {

    static final Logger LOG = Logger.getLogger(ScriptFunctionExecutor.class);
    Attribute.Type returnType;
    Script script;
    private String functionId;

    public ScriptFunctionExecutor(String name) {
        this.functionId = name;
    }

    @Override
    public Attribute.Type getReturnType() {
        return returnType;
    }

    @Override
    protected void init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader configReader,
                        ExecutionPlanContext executionPlanContext) {
        returnType = executionPlanContext.getScript(functionId).getReturnType();
        script = executionPlanContext.getScript(functionId);
    }

    @Override
    protected Object execute(Object[] data) {
        return script.eval(functionId, data);
    }

    @Override
    protected Object execute(Object data) {
        return script.eval(functionId, new Object[]{data});
    }

    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public Map<String, Object> currentState() {
        return null;
    }

    @Override
    public void restoreState(Map<String, Object> state) {

    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions
  xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
  xmlns:camunda="http://activiti.org/bpmn"
  targetNamespace="org.camunda.bpm.engine.test.enginge.test.api.runtime">

  <process id="miSubprocess">
    <startEvent id="theStart" />
    <sequenceFlow id="flow1" sourceRef="theStart" targetRef="subProcess" />

    <subProcess id="subProcess">
      <multiInstanceLoopCharacteristics isSequential="false">
        <loopCardinality>3</loopCardinality>
      </multiInstanceLoopCharacteristics>

      <startEvent id="theSubProcessStart" />
      <sequenceFlow id="flow2" sourceRef="theSubProcessStart" targetRef="innerTask" />
      <userTask id="innerTask" />
      <sequenceFlow id="flow3" sourceRef="innerTask" targetRef="theSubProcessEnd" />
      <endEvent id="theSubProcessEnd" />
    </subProcess>

    <sequenceFlow id="flow4" sourceRef="subProcess" targetRef="theEnd" />
    <endEvent id="theEnd" />
  </process>

</definitions>


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchHistory>
<launchGroup id="org.eclipse.debug.ui.launchGroup.profilee">
<mruHistory/>
<favorites/>
</launchGroup>
<launchGroup id="org.eclipse.debug.ui.launchGroup.debug">
<mruHistory/>
<favorites/>
</launchGroup>
<launchGroup id="org.eclipse.debug.ui.launchGroup.profile">
<mruHistory/>
<favorites/>
</launchGroup>
<launchGroup id="org.eclipse.ui.externaltools.launchGroup">
<mruHistory>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (50)"/>
"/>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (49)"/>
"/>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (48)"/>
"/>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (47)"/>
"/>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (46)"/>
"/>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (45)"/>
"/>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (44)"/>
"/>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (43)"/>
"/>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (42)"/>
"/>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (41)"/>
"/>
</mruHistory>
<favorites/>
</launchGroup>
<launchGroup id="org.eclipse.debug.ui.launchGroup.run">
<mruHistory/>
<favorites/>
</launchGroup>
</launchHistory>


text:
var answerOptions   = $("

"),
    showOrigin      = $("<button id='showOrigin'>"+showOriginI18n+"</button>"),
    showTest        = $("<button id='showTest'>"+showTestI18n+"</button>"),
    activeInputName = 0;

$(document).ready(function(){
  var solution = $("#solution").text().split('\\\\');
  var options = $("#solution").text().split('\\\\');
  shuffle(options);
  var inputSize = 0;
  for (i = 0; i < solution.length; i++) {
    if (solution[i].length > inputSize) {
      inputSize = solution[i].length;
    }
  }
  var textToChange = $("#text").text();
  var textAfterChange = "
" + textToChange
    .replace(/\{\{/g, '<input type="text" size="'+inputSize+'" name="')
    .replace(/\}\}/g, '" class="testInput">')
    .replace(/\\n\\n/g, '

')
    .replace(/\\n/g, '

')
    .replace(/\n\n/g, '

')
    .replace(/\n/g, '

') + "
";
  var originalText = "
" + textToChange
    .replace(/\{\{(\d+)\}\}/g, function(m,p1){return ''+solution[p1]+'';})
    .replace(/\\n\\n/g, '

')
    .replace(/\\n/g, '

')
    .replace(/\n\n/g, '

')
    .replace(/\n/g, '

') + "
";
  $("#text").html(textAfterChange);
  $("#origin").html(originalText);

  $(".testInput").focus(function() {
    $(this).css("background-color", "cornsilk");
    activeInputName = document.activeElement.name;
  });

  $(".testInput").focusout(function() {
    var testedValue = $(this).val();
    var inputName =  $(this).attr("name");
    if (testedValue == solution[inputName]) {
      $(this).css("background-color", "green");
    } else {
      $(this).css("background-color", "red");
    }
  });

  $(".testInput").on("input", function() {
    var testedValue = $(this).val();
    var inputName =  $(this).attr("name");
    if (testedValue == solution[inputName]) {
      $(this).css("background-color", "green");
    }
  });

  answerOptions.prependTo("#mainColumn");
  showOrigin.appendTo("#control");
  showTest.appendTo("#control").hide();

  for (var i = 0; i < options.length; i++) {
    var option = $(""+options[i]+" ");
    option.appendTo(answerOptions);
  }

  $("span").draggable({
    revert: true
  });
  $(".testInput").droppable({
    drop: function(event, ui) {
      if (solution[$(this).attr('name')]==$(ui.draggable).text()) {
        this.value = $(ui.draggable).text();
        $(this).css("background-color","green");
        $(ui.draggable).css("background-color","transparent").css("color","transparent");
      }
    }
  });

  showOrigin.click(function() {
    showOrigin.hide();
    showTest.show();
    $("#text").hide();
    $("#origin").show();
  });

  showTest.click(function() {
    showTest.hide();
    showOrigin.show();
    $("#origin").hide();
    $("#text").show();
  });
});


text:
<?php
class ControllerCommonFileManager extends Controller {
	public function index() {
		$this->load->language('common/filemanager');

		if (isset($this->request->get['filter_name'])) {
			$filter_name = rtrim(str_replace(array('../', '..\\', '..', '*'), '', $this->request->get['filter_name']), '/');
		} else {
			$filter_name = null;
		}

		// Make sure we have the correct directory
		if (isset($this->request->get['directory'])) {
			$directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this->request->get['directory']), '/');
		} else {
			$directory = DIR_IMAGE . 'catalog';
		}

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$data['images'] = array();

		$this->load->model('tool/image');

		// Get directories
		$directories = glob($directory . '/' . $filter_name . '*', GLOB_ONLYDIR);

		if (!$directories) {
			$directories = array();
		}

		// Get files
		$files = glob($directory . '/' . $filter_name . '*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);

		if (!$files) {
			$files = array();
		}

		// Merge directories and files
		$images = array_merge($directories, $files);

		// Get total number of files and directories
		$image_total = count($images);

		// Split the array based on current page number and max number of items per page of 10
		$images = array_splice($images, ($page - 1) * 16, 16);

		foreach ($images as $image) {
			$name = str_split(basename($image), 14);

			if (is_dir($image)) {
				$url = '';

				if (isset($this->request->get['target'])) {
					$url .= '&target=' . $this->request->get['target'];
				}

				if (isset($this->request->get['thumb'])) {
					$url .= '&thumb=' . $this->request->get['thumb'];
				}

				$data['images'][] = array(
					'thumb' => '',
					'name'  => implode(' ', $name),
					'type'  => 'directory',
					'path'  => utf8_substr($image, utf8_strlen(DIR_IMAGE)),
					'href'  => $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . '&directory=' . urlencode(utf8_substr($image, utf8_strlen(DIR_IMAGE . 'catalog/'))) . $url, 'SSL')
				);
			} elseif (is_file($image)) {
				// Find which protocol to use to pass the full image link back
				if ($this->request->server['HTTPS']) {
					$server = HTTPS_CATALOG;
				} else {
					$server = HTTP_CATALOG;
				}

				$data['images'][] = array(
					'thumb' => $this->model_tool_image->resize(utf8_substr($image, utf8_strlen(DIR_IMAGE)), 100, 100),
					'name'  => implode(' ', $name),
					'type'  => 'image',
					'path'  => utf8_substr($image, utf8_strlen(DIR_IMAGE)),
					'href'  => $server . 'image/' . utf8_substr($image, utf8_strlen(DIR_IMAGE))
				);
			}
		}

		$data['heading_title'] = $this->language->get('heading_title');

		$data['text_no_results'] = $this->language->get('text_no_results');
		$data['text_confirm'] = $this->language->get('text_confirm');

		$data['entry_search'] = $this->language->get('entry_search');
		$data['entry_folder'] = $this->language->get('entry_folder');

		$data['button_parent'] = $this->language->get('button_parent');
		$data['button_refresh'] = $this->language->get('button_refresh');
		$data['button_upload'] = $this->language->get('button_upload');
		$data['button_folder'] = $this->language->get('button_folder');
		$data['button_delete'] = $this->language->get('button_delete');
		$data['button_search'] = $this->language->get('button_search');

		$data['token'] = $this->session->data['token'];

		if (isset($this->request->get['directory'])) {
			$data['directory'] = urlencode($this->request->get['directory']);
		} else {
			$data['directory'] = '';
		}

		if (isset($this->request->get['filter_name'])) {
			$data['filter_name'] = $this->request->get['filter_name'];
		} else {
			$data['filter_name'] = '';
		}

		// Return the target ID for the file manager to set the value
		if (isset($this->request->get['target'])) {
			$data['target'] = $this->request->get['target'];
		} else {
			$data['target'] = '';
		}

		// Return the thumbnail for the file manager to show a thumbnail
		if (isset($this->request->get['thumb'])) {
			$data['thumb'] = $this->request->get['thumb'];
		} else {
			$data['thumb'] = '';
		}

		// Parent
		$url = '';

		if (isset($this->request->get['directory'])) {
			$pos = strrpos($this->request->get['directory'], '/');

			if ($pos) {
				$url .= '&directory=' . urlencode(substr($this->request->get['directory'], 0, $pos));
			}
		}

		if (isset($this->request->get['target'])) {
			$url .= '&target=' . $this->request->get['target'];
		}

		if (isset($this->request->get['thumb'])) {
			$url .= '&thumb=' . $this->request->get['thumb'];
		}

		$data['parent'] = $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . $url, 'SSL');

		// Refresh
		$url = '';

		if (isset($this->request->get['directory'])) {
			$url .= '&directory=' . urlencode($this->request->get['directory']);
		}

		if (isset($this->request->get['target'])) {
			$url .= '&target=' . $this->request->get['target'];
		}

		if (isset($this->request->get['thumb'])) {
			$url .= '&thumb=' . $this->request->get['thumb'];
		}

		$data['refresh'] = $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . $url, 'SSL');

		$url = '';

		if (isset($this->request->get['directory'])) {
			$url .= '&directory=' . urlencode(html_entity_decode($this->request->get['directory'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['target'])) {
			$url .= '&target=' . $this->request->get['target'];
		}

		if (isset($this->request->get['thumb'])) {
			$url .= '&thumb=' . $this->request->get['thumb'];
		}

		$pagination = new Pagination();
		$pagination->total = $image_total;
		$pagination->page = $page;
		$pagination->limit = 16;
		$pagination->url = $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

		$data['pagination'] = $pagination->render();

		$this->response->setOutput($this->load->view('common/filemanager.tpl', $data));
	}

	public function upload() {
		$this->load->language('common/filemanager');

		$json = array();

		// Check user has permission
		if (!$this->user->hasPermission('modify', 'common/filemanager')) {
			$json['error'] = $this->language->get('error_permission');
		}

		// Make sure we have the correct directory
		if (isset($this->request->get['directory'])) {
			$directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this->request->get['directory']), '/');
		} else {
			$directory = DIR_IMAGE . 'catalog';
		}

		// Check its a directory
		if (!is_dir($directory)) {
			$json['error'] = $this->language->get('error_directory');
		}

		if (!$json) {
			if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
				// Sanitize the filename
				$filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));

				// Validate the filename length
				if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 255)) {
					$json['error'] = $this->language->get('error_filename');
				}

				// Allowed file extension types
				$allowed = array(
					'jpg',
					'jpeg',
					'gif',
					'png'
				);

				if (!in_array(utf8_strtolower(utf8_substr(strrchr($filename, '.'), 1)), $allowed)) {
					$json['error'] = $this->language->get('error_filetype');
				}

				// Allowed file mime types
				$allowed = array(
					'image/jpeg',
					'image/pjpeg',
					'image/png',
					'image/x-png',
					'image/gif'
				);

				if (!in_array($this->request->files['file']['type'], $allowed)) {
					$json['error'] = $this->language->get('error_filetype');
				}

				// Check to see if any PHP files are trying to be uploaded
				$content = file_get_contents($this->request->files['file']['tmp_name']);

				if (preg_match('/\<\?php/i', $content)) {
					$json['error'] = $this->language->get('error_filetype');
				}

				// Return any upload error
				if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
					$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
				}
			} else {
				$json['error'] = $this->language->get('error_upload');
			}
		}

		if (!$json) {
			move_uploaded_file($this->request->files['file']['tmp_name'], $directory . '/' . $filename);

			$json['success'] = $this->language->get('text_uploaded');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function folder() {
		$this->load->language('common/filemanager');

		$json = array();

		// Check user has permission
		if (!$this->user->hasPermission('modify', 'common/filemanager')) {
			$json['error'] = $this->language->get('error_permission');
		}

		// Make sure we have the correct directory
		if (isset($this->request->get['directory'])) {
			$directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this->request->get['directory']), '/');
		} else {
			$directory = DIR_IMAGE . 'catalog';
		}

		// Check its a directory
		if (!is_dir($directory)) {
			$json['error'] = $this->language->get('error_directory');
		}

		if (!$json) {
			// Sanitize the folder name
			$folder = str_replace(array('../', '..\\', '..'), '', basename(html_entity_decode($this->request->post['folder'], ENT_QUOTES, 'UTF-8')));

			// Validate the filename length
			if ((utf8_strlen($folder) < 3) || (utf8_strlen($folder) > 128)) {
				$json['error'] = $this->language->get('error_folder');
			}

			// Check if directory already exists or not
			if (is_dir($directory . '/' . $folder)) {
				$json['error'] = $this->language->get('error_exists');
			}
		}

		if (!$json) {
			mkdir($directory . '/' . $folder, 0777);
			chmod($directory . '/' . $folder, 0777);

			$json['success'] = $this->language->get('text_directory');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function delete() {
		$this->load->language('common/filemanager');

		$json = array();

		// Check user has permission
		if (!$this->user->hasPermission('modify', 'common/filemanager')) {
			$json['error'] = $this->language->get('error_permission');
		}

		if (isset($this->request->post['path'])) {
			$paths = $this->request->post['path'];
		} else {
			$paths = array();
		}

		// Loop through each path to run validations
		foreach ($paths as $path) {
			$path = rtrim(DIR_IMAGE . str_replace(array('../', '..\\', '..'), '', $path), '/');

			// Check path exsists
			if ($path == DIR_IMAGE . 'catalog') {
				$json['error'] = $this->language->get('error_delete');

				break;
			}
		}

		if (!$json) {
			// Loop through each path
			foreach ($paths as $path) {
				$path = rtrim(DIR_IMAGE . str_replace(array('../', '..\\', '..'), '', $path), '/');

				// If path is just a file delete it
				if (is_file($path)) {
					unlink($path);

				// If path is a directory beging deleting each file and sub folder
				} elseif (is_dir($path)) {
					$files = array();

					// Make path into an array
					$path = array($path . '*');

					// While the path array is still populated keep looping through
					while (count($path) != 0) {
						$next = array_shift($path);

						foreach (glob($next) as $file) {
							// If directory add to path array
							if (is_dir($file)) {
								$path[] = $file . '/*';
							}

							// Add the file to the files to be deleted array
							$files[] = $file;
						}
					}

					// Reverse sort the file array
					rsort($files);

					foreach ($files as $file) {
						// If file just delete
						if (is_file($file)) {
							unlink($file);

						// If directory use the remove directory function
						} elseif (is_dir($file)) {
							rmdir($file);
						}
					}
				}
			}

			$json['success'] = $this->language->get('text_delete');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}
}


text:
import React from 'react-native';

var {
  View,
  Text,
  Image,
  Modal,
  TouchableHighlight,
  StyleSheet
} = React;

import globals from '../../../globalVariables';

class MealSubmittedOverlay extends React.Component {
  render() {
    return (
      <Modal
        visible={this.props.isVisible}>
        <View style={styles.confirmationOverlay}>
          <Text style={styles.headline}>Your image has been successfully uploaded!</Text>
          <TouchableHighlight
            underlayColor={'#ffffff'}
            onPress={this.props.onUploadAnother}>
            <Text style={styles.button}>Upload Another</Text>
          </TouchableHighlight>
          <TouchableHighlight
            underlayColor={'#ffffff'}
            onPress={this.props.onReturnHome}>
            <Text style={styles.button}>Return Home</Text>
          </TouchableHighlight>
        </View>
      </Modal>
    );
  }
}

export default MealSubmittedOverlay;

let styles = StyleSheet.create({
  confirmationOverlay: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#ffffff',
  },
  headline: {
    marginBottom: 75,
    fontSize: 32,
    textAlign: 'center',
    fontFamily: globals.fontDisplayRegular,
    color: globals.darkText,
  },
  button: {
    marginBottom: 20,
    fontSize: 20,
    textAlign: 'center',
    fontFamily: globals.fontTextSemibold,
    color: globals.primary,
  },
});