var sellerCredibility = {
    delay: 300, // ms
    id: 'sellerCredibility',
    timeout: null,
    sellers: {},
    container : null,
    userId : null,
    isCompact : false,
    percentileOrder: {
        "365":{},
        "90":{}
    }, // default to 90-day percentile; show 365-day if we don't have it
    init: function(container,username,isCompact){
        this.container = container;
        this.username = username;
        this.isCompact = isCompact;
        var jsonUrl = null;
        // kick off the ajax request to load data for all sellers on the page
        if(!testurl){
            jsonUrl = "../data/json_search.js?";
        }
        else{
            jsonUrl = "/api/v1/seller_kpi//search?";
        }
        jsonParams = {
            "period_days"   :   [ "30", "90", "365" ],
            "_select"       :   ["seller_id","period_days","approx_completed_transactions","total_canceled_transactions","pct_canceled_transactions","avg_days_to_ship","total_disputes","total_honored_disputes","pct_honored_disputes","time_since_creation_text","pct_repeat_buyers","total_completed_transactions_rank","total_canceled_transactions_rank","pct_canceled_transactions_rank","avg_days_to_ship_rank","total_disputes_rank","total_honored_disputes_rank","pct_honored_disputes_rank","pct_repeat_buyers_rank","warehouse_seller_flag", "username" ],
            "username"      :   [this.username],
            "_per_page"     :   ["99999"]
        };
        
        // get the json data back and add it to the sellerCredibility map
        jQuery.ajax({
            type: "GET",
            url: jsonUrl,
            dataType: "json",
            data: jsonParams,
            success: function(data) {
                if(data == null){
                    $('#loadingContainer').hide();
                    $('#memberSinceTable').hide();
                    $('#kpi-not').show();
                }
                else if(data.error && data.result && data.error.length > 0  && data.result.length==0) {
                    $('#loadingContainer').hide();
                    $('#memberSinceTable').hide();
                    $('#kpi-not').show();
                }
                else if(data.result.length==0){
                    $('#loadingContainer').hide();
                    $('#memberSinceTable').hide();
                    $('#kpi-not').show();
                }
                else{
                    $.each(data.result, function(i,item){
                        sellerCredibility.addSellerData(item.seller_id,
                            item.username,
                            item.period_days,
                            item.approx_completed_transactions,
                            item.total_canceled_transactions,
                            item.pct_canceled_transactions,
                            item.avg_days_to_ship,
                            item.total_disputes,
                            item.total_honored_disputes,
                            item.pct_honored_disputes,
                            item.time_since_creation_text,
                            item.pct_repeat_buyers,
                            item.total_completed_transactions_rank,
                            item.total_canceled_transactions_rank,
                            item.pct_canceled_transactions_rank,
                            item.avg_days_to_ship_rank,
                            item.total_disputes_rank,
                            item.total_honored_disputes_rank,
                            item.pct_honored_disputes_rank,
                            item.pct_repeat_buyers_rank,
                            item.warehouse_seller_flag
                            );
                    });
                    sellerCredibility.show(sellerCredibility.username);
                }
                
            },
            error : function(XMLHttpRequest, textStatus, errorThrown){
                $('#loadingContainer').hide();
                $('#memberSinceTable').hide();
                $('#kpi-not').show();
            }
        });
        
    },
    addSellerData: function(userId,
        username,
        period_days,
        total_completed_transactions,
        total_canceled_transactions,
        pct_canceled_transactions,
        avg_days_to_ship,
        total_disputes,
        total_honored_disputes,
        pct_honored_disputes,
        time_since_creation_text,
        pct_repeat_buyers,
        total_completed_transactions_rank,
        total_canceled_transactions_rank,
        pct_canceled_transactions_rank,
        avg_days_to_ship_rank,
        total_disputes_rank,
        total_honored_disputes_rank,
        pct_honored_disputes_rank,
        pct_repeat_buyers_rank,
        warehouse_seller_flag) {
        //
        // one map to hold the metrics, another map to hold percentile-rankings
        // for those metrics
        if (sellerCredibility.sellers[username] === undefined) {
            sellerCredibility.sellers[username] = {
                "meta" : {
                    "fulfilledBy": {},
                    "sellerName": {},
                    "memberSince": {},
                    "showDataTable" : {}
                },
                "metrics" : {
                    "period_days" : {
                        "30":{},
                        "90":{},
                        "365":{}
                    }
                },
                "percentiles" : {
                    "period_days" : {
                        "30":{},
                        "90":{},
                        "365":{}
                    }
                }
            };
        }
        
        sellerCredibility.sellers[username]["meta"] = {
            "fulfilledBy"      : sellerCredibility.getFulfilledByText(warehouse_seller_flag, username),
            "sellerName"       : username,
            "memberSince"      : time_since_creation_text,
            "showDataTable"    : sellerCredibility.showDataTable(total_completed_transactions)
        };

            sellerCredibility.sellers[username]["metrics"][period_days] = {
                "total_completed_transactions"      : total_completed_transactions,
                "total_canceled_transactions"       : total_canceled_transactions,
                "pct_canceled_transactions"         : pct_canceled_transactions,
                "avg_days_to_ship"                  : avg_days_to_ship,
                "total_disputes"                    : total_disputes,
                "total_honored_disputes"            : total_honored_disputes,
                "pct_honored_disputes"              : pct_honored_disputes,
                "pct_repeat_buyers"                 : pct_repeat_buyers
            };



        
        sellerCredibility.sellers[username]["percentiles"][period_days] = {            
            "total_completed_transactions_rank"       : total_completed_transactions_rank,
            "total_canceled_transactions_rank"        : total_canceled_transactions_rank,
            "pct_canceled_transactions_rank"          : pct_canceled_transactions_rank,
            "avg_days_to_ship_rank"                   : avg_days_to_ship_rank,
            "total_disputes_rank"                     : total_disputes_rank,
            "total_honored_disputes_rank"             : total_honored_disputes_rank,
            "pct_honored_disputes_rank"               : pct_honored_disputes_rank,
            "pct_repeat_buyers_rank"                  : pct_repeat_buyers_rank
        };
        
        sellerCredibility.sellers[username].username = username;
    },       
    show: function(username){
        if (sellerCredibility.getSellerData(username)){
            var mySellerData = sellerCredibility.getSellerData(username);
            sellerCredibility.writeHeader(username, mySellerData);
            // iterate over the mySellerData map, writing html out to cells in
            // the page 
            sellerCredibility.writeMetrics(mySellerData);
            
            //
            // set the class (background img) for each metric's percentile div
            // based upon the order specific
            if(!this.isCompact)
                sellerCredibility.writePercentiles(sellerCredibility.percentileOrder, mySellerData);
            
            // if we've got less than 10 total transactions, don't show the
            // full data table
            if (mySellerData["meta"]["showDataTable"] === true) {
                $("table#data-table").show();
                $("div#newSeller").hide();
            } else {
                $("table#data-table").hide();
                $("div#newSeller").show();
                $('#loadingContainer').hide();
                $('#kpi-not').show();
            }
            $('#loadingContainer').hide();
            $('#popup-cnt').show();
            $('#memberSinceTable').show();
        }
    },            
    
    showDataTable: function(total_completed_transactions) {    
        var dataTableVisible = true;
        if (total_completed_transactions <= 10)
            dataTableVisible = false;
        
        return dataTableVisible;
    },
    writeMetrics: function(sellerData) {
        for (var period_days in sellerData["metrics"]) {
            if (period_days !== 'username') {
                for (var metric in sellerData["metrics"][period_days]) {
                    sellerCredibility.writeMetricCellContents(period_days, metric, sellerData["metrics"][period_days][metric]);
                }
            }
        }
    },
    writeHeader: function(userId, sellerData) {
        $("span#memberSince").html(sellerData["meta"]["memberSince"]);  
    },
    writePercentiles: function(percentileOrder, sellerData) {
        // percentileOrder is a map of period_days in the priority order
        // specified by Liquidation; we'll write the 365-day metric first, then
        // write the 90-day metric over it, if it exists
        for (var period_days in percentileOrder) {
            for (var metric in sellerData["percentiles"][period_days]) {
                if (sellerData["percentiles"][period_days][metric] !== null) {
                    $("td#" + metric + " div").html("&nbsp;");
                    $("td#" + metric + " div").attr("class", "rank_" + Math.ceil(sellerData["percentiles"][period_days][metric]/10)*10);
                    $("td#" + metric + " div").attr("title", sellerCredibility.getRankingToolTipText(Math.ceil(sellerData["percentiles"][period_days][metric]/10)*10));
                }
            }
        }
    },
    writeMetricCellContents: function(period_days, metric, metricVal) {
        
        if (metricVal !== null) {
            if (metric.substring(0,3) === 'pct')
                metricVal += '%';
            if (metric === 'total_completed_transactions'){
                //commented because we are getting approx_completed_transaction from API call
                //metricVal = sellerCredibility.rewriteCompletedTransactions(metricVal);
            }
        } else {
            var metricVal = 'N/A';
        }
        $("td#" + period_days + "-" + metric).html(metricVal);
    },
    extractSellerId: function(id){
        seller = id.split('-');
        seller.shift();
        return seller.join('-');
    },
    extractAuctionId: function(id) {
        return id.split('-').shift();
    },
    getSellerData: function(username) {
        return sellerCredibility.sellers[username];
    },
    getRankingToolTipText: function(percentile) {
        var toolTipText = {
            "10"    :   "Bottom 10%",
            "20"    :   "Bottom 20%",
            "30"    :   "Bottom 30%",
            "40"    :   "Bottom 40%",
            "50"    :   "Bottom 50%",
            "60"    :   "Top 50%",
            "70"    :   "Top 40%",
            "80"    :   "Top 30%",
            "90"    :   "Top 20%",
            "100"   :   "Top 10%" 
        }
            
        return toolTipText[percentile];
    },
    getFulfilledByText: function(warehouse_seller_flag, username) {
        var fulfilledByText = {
            "1"     :   "Fulfilled by: UK-Liquidation.co.uk",
            "0"     :   "Fulfilled by: " + username
        }
        
        return fulfilledByText[warehouse_seller_flag];
    },
    rewriteCompletedTransactions: function(numTransactions) {
        if (numTransactions < 10) {
            return numTransactions;
        }
        else {
            // determine power of 10
            var numberTemplate = "000,000,000,000,000,000,000";
            var orderOfMag = (new String(Math.floor(numTransactions / 10))).length;
            // account for comma
            orderOfMag += Math.floor(orderOfMag / 3);
            var transFormatted = "1" + numberTemplate.substring(numberTemplate.length-orderOfMag) + "+";
            return transFormatted;
        }
    },
    openWhatsThisPopup: function(url) {
        window.open (url, "WhatIsThisPopup",
            "width=575," +
            "height=575," +
            "channelmode=0," +
            "directories=0," +
            "location=0," +
            "menubar=0," +
            "resizable=0," +
            "scrollbars=1," +
            "status=0," +
            "titlebar=0," +
            "toolbar=0"
            );
    }
};


