// this file requires jquery
var bioventurist_dir = '/base/bioventurist/';
var bioventurist_dir_old = '/user/bioventurist/default_domain/';

function getPageName(n){
    var name = "";
    if (n.length > 0) {
        var strings = n.split(" ");
        for (var x in strings) {
            strings[x] = strings[x].charAt(0).toUpperCase() + strings[x].substring(1);
            if (x > 0)
                name = name + " " + strings[x].replace("/","");
            else
                name = strings[x].replace("/","");
        }
    }
    return name;
}

function parseTopicID(s){
    var id = "";
    if (s.length > 0) {
        id="/"+s;
        id = (id[id.length-1]=='/' ? id.slice(0,id.length-1) : id); // Get rid of the last backward slash if necessary
    }
    return id;
}

/*
Returns the products in a productObject segregated as followows:
    productObject.therapeutics
    productObject.generalProducts
*/
function getProductTypes(products, typeArrayString) {
    
    var therapeuticType = "/base/bioventurist/bv_therapeutic";
    var productObject = new Object;
    productObject.therapeutics = new Array;
    productObject.products = new Array;
    var theraI = 0;
    var prodsI = 0;
    
    for (var i in products) {
        var types = Array();
        
        if (typeArrayString == "a:type") {
            types = products[i]['a:type'];
        } else {
            types = products[i].type;
        }
        
        var isTherapeutic = 0;
        
        for (var j in types) {
            var temp = types[j];
            var temp2 = temp == therapeuticType;
            if (temp2) {
                isTherapeutic = 1;
            }
        }
        
        if (isTherapeutic) {
            productObject.therapeutics[theraI] = products[i];
            theraI = theraI + 1;
        } else {
            productObject.products[prodsI] = products[i];
            prodsI = prodsI + 1;
        }
        
    }
    return productObject;
}
/*
    Creates tables and bar charts of products.

    marketCols specify which columns are to be displayed in the 'On the market' table:
    0 = Product Link
    1 = Brand Name
    2 = Developed By (Company)
    3 = Product Type (Therapeutic, diagnostic, etc.)
    4 = 2007 Sales ($M);
    5 = Overview Text
    6 = Large Overview Text; (always hidden, and used to allow users to expand the overview description)

    devCols specify which columns are to be displayed in the 'In Development' table:
    0 = Product Link
    1 = Brand Name
    2 = Developed By (Company)
    3 = Product Type (Therapeutic, diagnostic, etc.)
    4 = Overview Text
    5 = Large Overview Text; (always hidden, and used to allow users to expand the overview description)
        NOTE: 5 and 6 are only used if the number of entries is less than 20 (due to speed)

    Bar Graph Options:
    barOptions.salesByCompanies
    barOptions.salesByProducts

 */
function createProductTable(products, domain_used, biov_domain, marketCols, devCols, barOptions){
    var productsOnTheMarket = 0;
    var productsInDevelopment = 0;

    var numOnMarket = 0;
    var numDev =  0;
    for (var i in products) {
        var developmentStage = products[i].stage_of_development;
        if(developmentStage == "On the market"){
            numOnMarket = numOnMarket + 1;
        } else {
            numDev = numDev + 1;
        }
    }
    var pMarketData = new google.visualization.DataTable();
    pMarketData.addColumn('string', 'Product');
    pMarketData.addColumn('string', 'Brand Name');
    pMarketData.addColumn('string', 'Developed By');
    pMarketData.addColumn('string', 'Product Type');
    pMarketData.addColumn('number', '2007 Sales ($M)');
    pMarketData.addColumn('string', 'Overview');
    pMarketData.addColumn('string', '');
    pMarketData.addRows(numOnMarket);

    var marketTable = new google.visualization.Table(document.getElementById('prodMarket_div'));
    var marketView = new google.visualization.DataView(pMarketData);
    marketView.setColumns(marketCols);

    var pDevelopmentData = new google.visualization.DataTable();
    var pDevUseOverview = (numDev < 20 ? true : false);
        //var pDevUseOverview = true;
    pDevelopmentData.addColumn('string', 'Product');
    pDevelopmentData.addColumn('string', 'Brand Name');
    pDevelopmentData.addColumn('string', 'Developed By');
    pDevelopmentData.addColumn('string', 'Product Type');
    if(pDevUseOverview){
        pDevelopmentData.addColumn('string', 'Overview');
        pDevelopmentData.addColumn('string', '');
    }
    pDevelopmentData.addRows(numDev);

    var pDevTable = new google.visualization.Table(document.getElementById('prodDev_div'));
    var pDevView = new google.visualization.DataView(pDevelopmentData);
    //var devColsToUse = (pDevUseOverview ? [0,1,2,3,4] : [0,1,2,3]);
    // If we are over the allowed number of overviews.
    if(!pDevUseOverview){
        var devColsTemp = Array();
        devColsTempI = 0;
        for(var a in devCols){
            if(devCols[a] != 4){
                devColsTemp[devColsTempI] = devCols[a];
                devColsTempI = devColsTempI + 1;
            }
        }
        devCols = devColsTemp;
    }
    var devColsToUse = devCols;
    pDevView.setColumns(devColsToUse);

    var topic_domain = biov_domain+'product';

    var pMarketI = 0;
    var pDevelopmentI = 0;
    var totalSales = 0;

    // Record certain sales info to create bar charts:
    var allProducts = Array();
    var allProductSales2007 = Array();
    var allProductSales2006 = Array();

    var allDevelopers = Array();
    var allDeveloperSums2007 = Array();
    var allDeveloperSums2006 = Array();

    for (var i in products) {
        var productName = products[i].name;
        var product_id = products[i].id;
        var developmentStage = products[i].stage_of_development;

        var brandName = '';
        if(products[i].brand_name.length>0){
            brandName = products[i].brand_name[0];
        }

        var types = products[i]['a:type'];

        var productType = 'general';

        var sales2007 = '';
        var sales2006 = '';
        var sales = products[i].sales;
        if(sales.length>0 && developmentStage == "On the market"){
            for (var j in sales){
                var reportedBy = sales[j];
//              alert(reportedBy.toString());
                var salesYear = sales[j].year;
                if(salesYear == '2007') {
                    sales2007 += (sales[j].amount)/1000000;
                    totalSales = totalSales + parseFloat(sales2007);
                } else if(salesYear == '2006'){
                    sales2006 += (sales[j].amount)/1000000;
                }
            }
        }


        // Get the list of developers:
        var developers = products[i].developed_by;
        var developedBy = '';
        for (var j in developers){
            var developer = developers[j];
            developedBy += '<a href="'+create_bvr_topic_href('company',developer.id) + '">' + developer.name + '</a>';
            developedBy += ( j < developers.length-1 ? ', ' :"");

            var containsDeveloper = false;
            for (var k in allDevelopers){
                if(developer == allDevelopers[k]){
                    containsDeveloper = true;
                    var val2007 = parseFloat(sales2007);
                    if(isNaN(val2007)){val2007 = 0};
                    allDeveloperSums2007[k] = allDeveloperSums2007[k] + val2007;
                    allDeveloperSums2006[k] = allDeveloperSums2006[k] + val2006;
                }
            }
            if(!containsDeveloper){
                var devIndex = allDevelopers.length;
                allDevelopers[devIndex] = developer;
                var val2007 = parseFloat(sales2007);
                var val2006 = parseFloat(sales2006);
                if(isNaN(val2007)){val2007 = 0};
                allDeveloperSums2007[devIndex] = val2007;
                if(isNaN(val2006)){val2006 = 0};
                allDeveloperSums2006[devIndex] = val2006;
            }
        }

        var pName = '<a href="' + create_bvr_topic_href('product', product_id) + '">' + productName + '</a>';
        // Add the product table
        if(developmentStage == "On the market") {

            allProducts[pMarketI] = productName;
            allProductSales2007[pMarketI] = parseFloat(sales2007);
            allProductSales2006[pMarketI] = parseFloat(sales2006);

            pMarketData.setCell(parseFloat(pMarketI), 0, pName);
            pMarketData.setCell(parseFloat(pMarketI), 1, brandName);
            pMarketData.setCell(parseFloat(pMarketI), 2, developedBy);
            pMarketData.setCell(parseFloat(pMarketI), 3, productType);
            pMarketData.setCell(parseFloat(pMarketI), 4, parseFloat(sales2007), sales2007);

            x(pMarketI,5,6,pMarketData, marketView, productName, topic_domain, domain_used,  marketTable, 500,150);

            pMarketI = pMarketI + 1;
            productsOnTheMarket = 1;

        } else {
            pDevelopmentData.setCell(parseFloat(pDevelopmentI), 0, pName);
            pDevelopmentData.setCell(parseFloat(pDevelopmentI), 1, brandName);
            pDevelopmentData.setCell(parseFloat(pDevelopmentI), 2, developedBy);
            pDevelopmentData.setCell(parseFloat(pDevelopmentI), 3, productType);
            if(pDevUseOverview){
                x(pDevelopmentI,4,5,pDevelopmentData, pDevView, productName, topic_domain, domain_used,  pDevTable, 500,150);
            }
            pDevelopmentI = pDevelopmentI + 1;
            productsInDevelopment = 1;

        }
    }
    var totalPSales = 'Total sales for all '+name+' products (as caluclated from the below table) = $' +totalSales+'M.'
    $("#totalProductSales_div").append(totalPSales);

    marketTable.draw(pMarketData, {allowHtml: true});
    pDevTable.draw(pDevelopmentData, {allowHtml: true});

    // Add a bar graph outlining product sales by company
    if(barOptions.salesByCompanies && pMarketI > 0){
        var barData = new google.visualization.DataTable();
        barData.addColumn('string', 'Company');
        barData.addColumn('number', '2006 Sales');
        barData.addColumn('number', '2007 Sales');
        var numVals = allDevelopers.length;
        if(numVals > 16){numVals = 16};
        var indexes = getOrder(allDeveloperSums2007, 5);
        barData.addRows(indexes.length);
        for (var k = 0; k < indexes.length; k++){
            barData.setValue(k, 0, allDevelopers[indexes[k]]);
            var val2006 = allDeveloperSums2006[indexes[k]];
            var val2007 = allDeveloperSums2007[indexes[k]];
            barData.setValue(k, 1, parseFloat(val2006));
            barData.setValue(k, 2, parseFloat(val2007));
        }
        var chart = new google.visualization.ColumnChart(document.getElementById('companySales_div'));
        chart.draw(barData, {width: 650, height: 350, is3D: true, title: 'Sales by Company'});
    }
    // Add a bar graph outlining sales by product
    if(barOptions.salesByProducts && pMarketI > 0){
        var barDataProduct = new google.visualization.DataTable();
        barDataProduct.addColumn('string', 'Product');
        barDataProduct.addColumn('number', '2006 Sales');
        barDataProduct.addColumn('number', '2007 Sales');
        var numVals = allProducts.length;
        if(numVals > 16){numVals = 16};
        var indexes = getOrder(allProductSales2007, 5);
        barDataProduct.addRows(indexes.length);
        for (var k = 0; k < indexes.length; k++){
            barDataProduct.setValue(k, 0, allProducts[indexes[k]]);
            var val2006 = parseFloat(allProductSales2006[indexes[k]]);
            var val2007 = parseFloat(allProductSales2007[indexes[k]]);
            barDataProduct.setValue(k, 1, (isNaN(val2006) ? 0 : val2006));
            barDataProduct.setValue(k, 2, (isNaN(val2007) ? 0 : val2007));
        }
        var productsChart = new google.visualization.ColumnChart(document.getElementById('productSales_div'));
        productsChart.draw(barDataProduct, {width: 650, height: 350, is3D: true, title: 'Product Sales ($M)'});
    }
}
/**

    NOTE: THIS FUNCTION NEEDS CLEANING UP>

    Creates tables and bar charts of therapeutics.
    marketCols specify which columns are to be displayed:
    0 = Therapeutic Link
    1 = Brand Name
    2 = Developed By (Company)
    3 = 2007 Sales ($M);
    4 = 2006 Sales ($M);
    5 = 2005 Sales ($M);
    6 = Indications
    7 = Overview Text
    8 = Large Overview Text; (always hidden, and used to allow users to expand the overview description)

    devCols specify which columns are to be displayed in the 'In Development' table:
    0 = Product Link
    1 = Brand Name
    2 = Developed By (Company)
    3 = Product Type (Therapeutic, diagnostic, etc.)
    4 = Overview Text
    5 = Large Overview Text; (always hidden, and used to allow users to expand the overview description)
        NOTE: 5 and 6 are only used if the number of entries is less than 20 (due to speed)

    Bar Graph Options:
    barOptions.salesByCompanies
    barOptions.salesByProducts
*/
function createTherapeuticsTable(therapeutics, domain_used, biov_domain, marketCols, devCols, barOptions, useOverviews, companyOptions){
    var indicationPropID = biov_domain+"bv_therapeutic/indication_or_disease";
    var biomoleculePropID = biov_domain+"bv_therapeutic/biomolecule_or_target";

    var therapeuticsOnTheMarket = 0;
    var therapeuticsInDevelopment = 0;

    var numOnMarket = 0;
    var numDev =  0;
    for (var i in therapeutics) {
        var developmentStage = therapeutics[i].stage_of_development;
        if(developmentStage == "On the market"){
            numOnMarket = numOnMarket + 1;
        } else {
            numDev = numDev + 1;
        }
    }
    if(numOnMarket>0){

        var pMarketData = new google.visualization.DataTable();
        pMarketData.addColumn('string', 'Product');
        //pMarketData.addColumn('string', 'Brand Name');
        pMarketData.addColumn('string', 'Developed By');
        pMarketData.addColumn('number', '2007 Sales ($M)');
        pMarketData.addColumn('number', '2006 Sales ($M)');
        pMarketData.addColumn('number', '2005 Sales ($M)');
        pMarketData.addColumn('string', 'Indications / Phase of Development');
        //pMarketData.addColumn('string', 'Overview');
        //pMarketData.addColumn('string', '');
        pMarketData.addRows(numOnMarket);

        var marketTable = new google.visualization.Table(document.getElementById('theraMarket_div'));
        var marketView = new google.visualization.DataView(pMarketData);
        //marketView.setColumns([0,1,2,3,4,5]);
        marketView.setColumns(marketCols);
    }
    var pDevelopmentData = new google.visualization.DataTable();
    var pDevUseOverview = (numDev < 20 ? true : false);
    pDevUseOverview = false;
        //var pDevUseOverview = true;
    pDevelopmentData.addColumn('string', 'Product');
    //pDevelopmentData.addColumn('string', 'Brand Name');
    pDevelopmentData.addColumn('string', 'Developed By');
    pDevelopmentData.addColumn('string', 'Indications / Phase of Development');
    if(pDevUseOverview){
        pDevelopmentData.addColumn('string', 'Overview');
        pDevelopmentData.addColumn('string', '');
    }
    pDevelopmentData.addRows(numDev);

    if(!pDevUseOverview){
        var devColsTemp = Array();
        devColsTempI = 0;
        for(var a in devCols){
            if(devCols[a] != 4){
                devColsTemp[devColsTempI] = devCols[a];
                devColsTempI = devColsTempI + 1;
            }
        }
        devCols = devColsTemp;
    }


    var pDevTable = new google.visualization.Table(document.getElementById('theraDev_div'));
    var pDevView = new google.visualization.DataView(pDevelopmentData);
    //var devColsToUse = (pDevUseOverview ? [0,1,2,3,4] : [0,1,2,3])
    var devColsToUse = devCols;
    pDevView.setColumns(devColsToUse);

    var topic_domain = biov_domain+'bv_therapeutic';

    var pMarketI = 0;
    var pDevelopmentI = 0;
    var totalSales = 0;

    // Record certain sales info to create bar charts:
    var allProducts = Array();
    var allProductSales2007 = Array();
    var allProductSales2006 = Array();
    var allProductSales2005 = Array();

    var allDevelopers = Array();
    var allDeveloperSums2007 = Array();
    var allDeveloperSums2006 = Array();
    var allDeveloperSums2005 = Array();

    for (var i in therapeutics) {
        var productName = therapeutics[i].name;
        var therapeutic_id = therapeutics[i].id;
        var developmentStage = therapeutics[i].stage_of_development;

        var brandName = '';
        if(therapeutics[i].brand_name.length>0){
            brandName = therapeutics[i].brand_name[0];
        }

        var types = therapeutics[i]['a:type'];

        var isTherapeutic = 0;
        for (var j in types) {
            var temp = types[j];
            var temp2 = (temp == biov_domain+"bv_therapeutic")
            if  (temp2){
                isTherapeutic = 1;
            }
        }
        var productType = 'product';

        var sales2007 = 0;
        var sales2006 = 0;
        var sales2005 = 0;
        var sales = therapeutics[i].sales;
        if(sales.length>0 && developmentStage == "On the market"){
            for (var j in sales){

                var useSales = false;
                if(companyOptions.specifyCompany){
                    var companyReporting = 'company_reporting';
                    if(sales[j].company_reporting == companyOptions.companyName || sales[j].company_reporting == null){
                        useSales = true;
                    }

                } else {
                    useSales = true;
                }

                if(useSales){
                    var salesYear = sales[j].year;
                    var sval = (sales[j].amount)/1000000;
                    if(salesYear == '2007') {
                        sales2007 = (sval>sales2007 ? sval : sales2007);
                        totalSales = totalSales + sales2007;
                    } else if(salesYear == '2006'){
                        sales2006 = (sval>sales2006 ? sval : sales2006);
                    } else if(salesYear == '2005'){
                        sales2005 = (sval>sales2005 ? sval : sales2005);
                    }
                }
            }
        }

        // Get the list of developers:
        var developers = therapeutics[i]['a:developed_by'];
        var developedBy = '';
        for (var j in developers){
            var developer = developers[j];
            developedBy += '<a href="'+create_bvr_topic_href('company',developer.id)+'">' + developer.name + '</a>';
            developedBy += ( j < developers.length-1 ? ', ' :"");

            if(brandName.length > 0) {
                allProducts[pMarketI] = brandName;
            } else {
                allProducts[pMarketI] = productName;
            }
            allProductSales2007[pMarketI] = sales2007;
            allProductSales2006[pMarketI] = sales2006;
            allProductSales2005[pMarketI] = sales2005;

            var containsDeveloper = false;
            for (var k in allDevelopers){
                if(developer == allDevelopers[k]){
                    containsDeveloper = true;
                    var val2007 = sales2007;
                    var val2006 = sales2006;
                    var val2005 = sales2005;
                    if(isNaN(val2007)){val2007 = 0};
                    allDeveloperSums2007[k] = allDeveloperSums2007[k] + val2007;
                    if(isNaN(val2006)){val2006 = 0};
                    allDeveloperSums2006[k] = allDeveloperSums2006[k] + val2006;
                    if(isNaN(val2005)){val2005 = 0};
                    allDeveloperSums2005[k] = allDeveloperSums2005[k] + val2005;

                }
            }
            if(!containsDeveloper){
                var devIndex = allDevelopers.length;
                allDevelopers[devIndex] = developer;
                var val2007 = sales2007;
                var val2006 = sales2006;
                var val2005 = sales2005;
                if(isNaN(val2007)){val2007 = 0};
                allDeveloperSums2007[devIndex] = val2007;
                if(isNaN(val2006)){val2006 = 0};
                allDeveloperSums2006[devIndex] = val2006;
                if(isNaN(val2005)){val2005 = 0};
                allDeveloperSums2005[devIndex] = val2005;
            }
        }

        var pName = '';
        var w = create_bvr_topic_href('therapeutic',therapeutic_id)
        if(brandName.length> 0){
            pName = '<a href="' + w + '">' + brandName + '</a>';
        } else {
            pName = '<a href="' + w + '">' + productName + '</a>';
        }

        // Get the indication:
        var indications = therapeutics[i][indicationPropID];
        var indicationText = '';
        for (var j in indications){

            var disease = null;
            if(indications[j].disease != null){
                if(indications[j].disease.length > 0) {
                    disease = indications[j].disease[0];
                }
            }
            var phaseOfDevelopment = '';
            if(indications[j].phase_of_development){
                if(indications[j].phase_of_development.length > 0) {
                    phaseOfDevelopment += indications[j].phase_of_development;
                }
            }
            indicationText += phaseOfDevelopment+' for <a href="'+create_bvr_topic_href('disease',disease.id)+ '">' + disease.name + '</a>';
            indicationText += (j != indications.length-1 ? '; ':'');
        }

        if(developmentStage == "On the market") {

            pMarketData.setCell(parseFloat(pMarketI), 0, pName);
            //pMarketData.setCell(parseFloat(pMarketI), 1, brandName);
            pMarketData.setCell(parseFloat(pMarketI), 1, developedBy);
            pMarketData.setCell(parseFloat(pMarketI), 2, sales2007, sales2007);
            pMarketData.setCell(parseFloat(pMarketI), 3, sales2006, sales2006);
            pMarketData.setCell(parseFloat(pMarketI), 4, sales2005, sales2005);
            pMarketData.setCell(parseFloat(pMarketI), 5, indicationText);

            if(useOverviews){
                x(pMarketI,7,8,pMarketData, marketView, productName, topic_domain, domain_used,  marketTable, 500,150);
            }
            pMarketI = pMarketI + 1;
            therapeuticsOnTheMarket = 1;


        } else {
            pDevelopmentData.setCell(parseFloat(pDevelopmentI), 0, pName);
            //pDevelopmentData.setCell(parseFloat(pDevelopmentI), 1, brandName);
            pDevelopmentData.setCell(parseFloat(pDevelopmentI), 1, developedBy);
            pDevelopmentData.setCell(parseFloat(pDevelopmentI), 2, indicationText);

            if(pDevUseOverview){
                if(useOverviews){
                    x(pDevelopmentI,4,5,pDevelopmentData, pDevView, productName, topic_domain, domain_used,  pDevTable, 500,150);
                }
            }
            pDevelopmentI = pDevelopmentI + 1;
            therapeuticsInDevelopment = 1;

        }
    }
    var totalPSales = 'Total sales for all '+name+' therapeutics (as caluclated from the below table) = $' +totalSales+'M.'
    $("#totaltherapeuticsales_div").append(totalPSales);

    if(barOptions.salesByCompanies && pMarketI > 0){

        // Add a bar graph outlining product sales by company
        var barData = new google.visualization.DataTable();
        barData.addColumn('string', 'Company');
        barData.addColumn('number', '2007 Sales');
        barData.addColumn('number', '2006 Sales');
        barData.addColumn('number', '2005 Sales');

        var numVals = allDevelopers.length;
        if(numVals > 16){numVals = 16};
        var indexes = getOrder(allDeveloperSums2007, 5);
        barData.addRows(indexes.length);
        for (var k = 0; k < indexes.length; k++){
            barData.setValue(k, 0, allDevelopers[indexes[k]].name);
            var val2007 = allDeveloperSums2007[indexes[k]];
            var val2006 = allDeveloperSums2006[indexes[k]];
            var val2005 = allDeveloperSums2005[indexes[k]];

            barData.setValue(k, 1, parseFloat(val2007));
            barData.setValue(k, 2, parseFloat(val2006));
            barData.setValue(k, 3, parseFloat(val2005));

        }
        var chart = new google.visualization.ColumnChart(document.getElementById('companySalesThera_div'));
        chart.draw(barData, {width: 650, height: 350, is3D: true, title: 'Sales by Company ($M)'});
//      $("#"+tabID).bind(function () {
//              chart.draw(barData, {width: 650, height: 350, is3D: true, title: 'Sales by Company ($M)'});
//      });

    }
    // Add a bar graph outlining sales by product
    if(barOptions.salesByProducts && pMarketI > 0){
        var barDataProduct = new google.visualization.DataTable();
        barDataProduct.addColumn('string', 'Product');
        barDataProduct.addColumn('number', '2007 Sales');
        barDataProduct.addColumn('number', '2006 Sales');
        barDataProduct.addColumn('number', '2005 Sales');

        var numVals = allProducts.length;
        if(numVals > 16){numVals = 16};
        var indexes = getOrder(allProductSales2007, 5);
        barDataProduct.addRows(indexes.length);
        for (var k = 0; k < indexes.length; k++){
            barDataProduct.setValue(k, 0, allProducts[indexes[k]]);
            var val2007 = parseFloat(allProductSales2007[indexes[k]]);
            var val2006 = parseFloat(allProductSales2006[indexes[k]]);
            var val2005 = parseFloat(allProductSales2005[indexes[k]]);
            barDataProduct.setValue(k, 1, (isNaN(val2007) ? 0 : val2007));
            barDataProduct.setValue(k, 2, (isNaN(val2006) ? 0 : val2006));
            barDataProduct.setValue(k, 3, (isNaN(val2005) ? 0 : val2005));
        }
        var productsChart = new google.visualization.ColumnChart(document.getElementById('productSalesThera_div'));
        productsChart.draw(barDataProduct, {width: 650, height: 350, is3D: true, title: 'Product Sales ($M)'});
//      $("#"+tabID).click(function () {
//              productsChart.draw(barDataProduct, {width: 650, height: 350, is3D: true, title: 'Product Sales ($M)'});
//      });

    }

    if(numOnMarket){
        marketTable.draw(pMarketData, {allowHtml: true});
    }
    pDevTable.draw(pDevelopmentData, {allowHtml: true});
}


// Need to figure out how to get this to bioventurist.js

function x(i,j,hiddenj, t,v,name, topic, freebaseDomain, table, maxlength, stublength, blurbs) {

    jsonp_totalblurb_freebase(freebaseDomain, name, topic, maxlength,
        function(m){
        },
        function(m){
            t.setCell(parseFloat(i), j, m.result.body.substring(0,stublength)+'...');
            t.setCell(parseFloat(i), hiddenj, m.result.body+'...');
            table.draw(v, {allowHtml: true});
        },
        function(m){}
    );
    return blurbs;
}

/*  Create a news bar:
        Set to id = newsBar-bar
*/

function createNewsBar(name){
    window._uds_nbw_donotrepair = true;
    function LoadNewsBar() {
      var newsBar;
      var options = {
        largeResultSet : false,
        title : "In the news",
        horizontal : false,
        autoExecuteList : {
          executeList : [name]
        }
      }
      newsBar = new GSnewsBar(document.getElementById("newsBar-bar"), options);
    }
    GSearch.setOnLoadCallback(LoadNewsBar);
}

function setSelectionExpander(dataObject, table, view, expandedRow, col, hiddenCol){

    if(expandedRow>0){
        var index = expandedRow;
        var showing = dataObject.getValue(index, col);
        var hidden = dataObject.getValue(index, hiddenCol);

        dataObject.setValue(index,hiddenCol, showing);
        dataObject.setValue(index,col, hidden);
        expandedRow = -1;
    }
//  table.draw(view, {allowHtml: true});
    if(table.getSelection()){
        var row = table.getSelection()[0].row;
        var showing = dataObject.getValue(row, col);
        var hidden = dataObject.getValue(row, hiddenCol);

        dataObject.setValue(row,hiddenCol, showing);
        dataObject.setValue(row,col, hidden);
        expandedRow = row;
    }
    table.draw(view, {allowHtml: true});

    return expandendRow;
}

function setSelectionExpander2(dataObject, table, view, expandedRows, col, hiddenCol){

  //    if(table.getSelection()){
  //        var selectedCol = table.getSelection()[0].column;
  //        if(selectedCol != col){
  //            return;
  //        }
  //    }

    for(var i in expandedRows){
        var index = parseFloat(i);
        if(expandedRows[index]){
            var showing = dataObject.getValue(index, col);
            var hidden = dataObject.getValue(index, hiddenCol);

            dataObject.setValue(index,hiddenCol, showing);
            dataObject.setValue(index,col, hidden);
            expandedRows[index] = !expandedRows[index];
        }
    }
    table.draw(view, {allowHtml: true});
    var row = table.getSelection()[0].row;
    if(true){//row != selectedRow){
        var showing = dataObject.getValue(row, col);
        var hidden = dataObject.getValue(row, hiddenCol);

        dataObject.setValue(row,hiddenCol, showing);
        dataObject.setValue(row,col, hidden);

        expandedRows[row] = !expandedRows[row];
        selectedRow = row;
    }
    table.draw(view, {allowHtml: true});
    return expandendRows;
}

/* Page Elements */

/*
Creates a list with a header.
    vals = list values
    headerText = the header title
    htmlID = id of the html element
    header level = can be level 1 or 2 or 3
    linkInfo.useLink = if the list element should be a link
    linkInfo.relDir = the relative directory for the link
*/
function createListWithHeader(vals, headerText, htmlID, headerLevel, linkInfo, addBreak, maxVal) {
    if (maxVal < 0) {
        maxVal = vals.length;
    }
    var head = "h4";
    
    if (headerLevel == 1) {
        head = "h3";
    } else if (headerLevel == 2) {
        head = "h2";
    } else if (headerLevel == 3) {
        head = "h3";
    }
    
    if (vals.length > 0) {
        var h = "";
        if (addBreak) {
            h += "<br />";
        }
        h += "<" + head + "><span>" + headerText + "</span></" + head + ">";
        if (!linkInfo.useLink) {
            h += "<div>";
        }
        for (var j in vals) {
            if (j < maxVal) {
                var val = vals[j];
                h += linkInfo.useLink ? "<a href=\"" + create_bvr_topic_href(linkInfo.relDir, val.id) + "\">" + val.name + "</a>" : "" + val.name + "";
                h += j < vals.length - 1 ? ", " : "";
            }
        }
        if (!linkInfo.useLink) {
            h += "</div>";
        }
        h = $(h);
        $("#" + htmlID + "").append(h);
    }
}



function create_bvr_topic_href(topic_type, topic_id){
    return '/' + topic_type + topic_id;
}

// Checks to see if the page contains the bioventurist type, and adds it (and refreshes the page) if not.
function test_type(url_read, domain_used, name, type,matchType,relDir){
    var q  = '{"query":[{'+
        '"name":"'+name+'",'+
        '"type":"'+type+'"'+
        '}]}';


    //var qRead = '{"query":[{"id" : null, "name" : "cancer","type" : "/medicine/disease"}]}';
    var type_current = matchType;// "/medicine/disease";

    perform_freebase_read(
        url_read,
        q,
        function (msg) {

        if(msg.result.length == 0){
            link_type(name, type_current, type);
            location.href = '/' + relDir +'/' + name;
        }
        },
        function(ms){
            var test = 0;
        }
    );

}


