var sellerCredibility = {
    delay: 300, // ms
    id: 'sellerCredibility',
	sellerId:'',
	ishover:false,
    timeout: null,
    sellers: {},
    init: function(callback) {
        //
        // scan for elements of class "seller" and attach show/hide callbacks
        $(".seller").hover(
            function(){
                sellerCredibility.ishover=true;
				sellerCredibility.sellerId = $(this).attr('id');
            },
            function(){
                // callbacks will be attached to the popup itself
				sellerCredibility.ishover=false;
            }
        );

		$("#sellerCredibility").hover(
            function(){
                sellerCredibility.ishover=true;
				sellerCredibility.sellerId = $(this).attr('id');
            },
            function(){
                // callbacks will be attached to the popup itself
				sellerCredibility.ishover=false;
            }
        );

		setInterval(function(){
			if(sellerCredibility.ishover){
				sellerCredibility.writeWidgetContents(sellerCredibility.extractSellerId(sellerCredibility.sellerId));
	            sellerCredibility.show(sellerCredibility.extractSellerId(sellerCredibility.sellerId), sellerCredibility.extractAuctionId(sellerCredibility.sellerId));
			}else{
				sellerCredibility.hide();
			}
		},1000);


        //
        // hide the popup when the user clicks the close button
        $(".popup-close").click(
            function(){
                sellerCredibility.hide();
            }
        );

        //
        // hide the popup when we move the mouse out of the parent div
        $("div#"+this.id).mouseout(
            function(e){
                if (!e) {
                    e = window.event;
                }
                var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
                if (reltg) {
                    while (reltg.tagName != 'BODY' && reltg.tagName != 'HTML') {
                        if (reltg.id == this.id) {
                            return;
                        }
                        reltg = reltg.parentNode;
                    }
                }
                sellerCredibility.hide();
            }
        );

        //
        // append a list of userIds to the json parameter list
        var usernames = [];
        $(".seller").each(
            function() {
                usernames.push(sellerCredibility.extractSellerId(this.id));
            }
        );

        sellerCredibility.loadData(usernames, callback);

    },
    initInline : function(username, callback) {
        var usernames = [ username ];
        sellerCredibility.loadData(usernames, function() {
            // update the inlined div with data from json response
            sellerCredibility.writeWidgetContents(username);
            $("div#"+sellerCredibility.id).show();

            // call the original callback if passed in
            if (callback) {
                callback();
            }
        });

    },
    loadData : function (usernames, callback) {
        //
        // kick off the ajax request to load data for all sellers on the page
        //var jsonUrl = "js/json_search.js?";
        var jsonUrl = "/api/v1/seller_kpi//search?";
        var jsonParams = {
            "username"      :   sellerCredibility.unique(usernames),
            "period_days"   :   ["30","90","365"],
            "_select"       :   ["seller_id","period_days","approx_completed_transactions","pct_canceled_transactions","avg_days_to_ship","pct_honored_disputes","time_since_creation_text","pct_repeat_buyers","pct_canceled_transactions_rank","avg_days_to_ship_rank","pct_honored_disputes_rank","pct_repeat_buyers_rank","warehouse_seller_flag_denorm","username","first_post_time", "top_seller_flag", "show_data_flag", "new_seller_flag"],
            "_per_page"     :   ["99999"]
        };

        //get the seller kpi stats in the template itself.
        // get the json data back and add it to the sellerCredibility map
        if(typeof sellerData == "undefined"){
            jQuery.ajax({
		  	type: "GET",
			url: jsonUrl,
			dataType: "json",
			data: jsonParams,
			success: function(data) {
                sellerData = data;
                $.each(sellerData.result, function(i,item) {
                sellerCredibility.addSellerData(item.seller_id,
                    item.username,
                    item.period_days,
                    item.approx_completed_transactions,
                    item.pct_canceled_transactions,
                    item.avg_days_to_ship,
                    item.pct_honored_disputes,
                    item.time_since_creation_text,
                    item.pct_repeat_buyers,
                    item.pct_canceled_transactions_rank,
                    item.avg_days_to_ship_rank,
                    item.pct_honored_disputes_rank,
                    item.pct_repeat_buyers_rank,
                    item.warehouse_seller_flag_denorm,
                    item.first_post_time,
                    item.top_seller_flag,
                    item.new_seller_flag
                    );
                });
                if (callback) {
                    callback();
                }
            }});
        }else{
            $.each(sellerData.result, function(i,item) {
            sellerCredibility.addSellerData(item.seller_id,
                item.username,
                item.period_days,
                item.approx_completed_transactions,
                item.pct_canceled_transactions,
                item.avg_days_to_ship,
                item.pct_honored_disputes,
                item.time_since_creation_text,
                item.pct_repeat_buyers,
                item.pct_canceled_transactions_rank,
                item.avg_days_to_ship_rank,
                item.pct_honored_disputes_rank,
                item.pct_repeat_buyers_rank,
                item.warehouse_seller_flag_denorm,
                item.first_post_time,
                item.top_seller_flag,
                item.new_seller_flag
                );
            });
            if (callback) {
                callback();
            }
        }

    },
    addSellerData: function(userId,
                            username,
                            period_days,
                            approx_completed_transactions,
                            pct_canceled_transactions,
                            avg_days_to_ship,
                            pct_honored_disputes,
                            time_since_creation_text,
                            pct_repeat_buyers,
                            pct_canceled_transactions_rank,
                            avg_days_to_ship_rank,
                            pct_honored_disputes_rank,
                            pct_repeat_buyers_rank,
                            warehouse_seller_flag,
                            first_post_time,
                            top_seller_flag,
                            new_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": {},
                    "first_post_time" : {},
                    "top_seller_flag" : {},
                    "new_seller_flag" : {}
                },
                "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,
            "first_post_time"  : first_post_time,
            "top_seller_flag"  : top_seller_flag,
            "new_seller_flag"  : new_seller_flag
        };

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

        sellerCredibility.sellers[username]["percentiles"][period_days] = {
            "pct_canceled_transactions_rank"          : pct_canceled_transactions_rank,
            "avg_days_to_ship_rank"                   : avg_days_to_ship_rank,
            "pct_honored_disputes_rank"               : pct_honored_disputes_rank,
            "pct_repeat_buyers_rank"                  : pct_repeat_buyers_rank
        };

        sellerCredibility.sellers[username].username = username;
    },
    writeWidgetContents: function(userId){

        var mySellerData = sellerCredibility.getSellerData(userId);

        if (sellerCredibility.getSellerData(userId)){

            var mySellerData = sellerCredibility.getSellerData(userId);

            //
            // write the "fulfilled by," "seller name," and "member since" text
            sellerCredibility.writeHeader(userId, mySellerData);

            //
            // show the top seller rank logo if all percentile-rankings return
            // at 90% or higher
            sellerCredibility.showTopSellerIcon(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
            sellerCredibility.writePercentiles(mySellerData);

            // if we've got less than 10 total transactions or have been
            // around less than 1 month, don't show the full data table
            if ( sellerCredibility.showDataTable(mySellerData) ) {
                $("table#data-table").show();
                $("div#newSeller").hide();
            } else {
                $("table#data-table").hide();
                $("div#newSeller").show();
            }

        }
    },
    show: function(userId, auctionId){

        if(this.timeout) {
            clearTimeout(this.timeout);
        }

        if (sellerCredibility.getSellerData(userId)){

            var mySellerData = sellerCredibility.getSellerData(userId);

            //
            // show the div and position it relative to the link
            sellerCredibility.timeout = setTimeout(function(){
                $("div#"+sellerCredibility.id).show();
				if($.browser.msie && parseInt($.browser.version) == 6)$('.select-free').show();
                sellerCredibility.setPosition(userId, auctionId);
            }, sellerCredibility.delay);
        }

    },
    showTopSellerIcon: function(sellerData) {
    	if ( sellerData["meta"]["top_seller_flag"] )
    	{
			$("span.top-seller").show();
        } else {
			$("span.top-seller").hide();
        }
    },
    showDataTable: function(sellerData) {
        var dataTableVisible = true;
        if (sellerData["meta"]["new_seller_flag"] == 1)
            dataTableVisible = false;

        return dataTableVisible;
    },
    setPosition: function(userId, auctionId){
        var anchor = $("a#" + auctionId + "-" + userId);

        if(anchor){
            //
            // get the offset of the anchor triggering the popup
            var offset = anchor.offset();
            var left = offset.left;
            var top = offset.top;
            var anchorWidth = anchor.width();

            //
            // get the div back in its original state and check its height
            $("div#popup-top").removeClass();
            $("div#popup-bot").removeClass();
            $("div#popup-top").addClass("popup-top");
            $("div#popup-bot").addClass("popup-bot");

            //
            // height of the div itself
            var floaterHeight = $("div#"+this.id).height();

            //
            // determine how far / if the user has scrolled the page down
            var ScrollTop = document.body.scrollTop;
            if (ScrollTop == 0) {
                if (window.pageYOffset) {
                    ScrollTop = window.pageYOffset;
                } else {
                    ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
                }
            }

            //
            // flip the popup to the south if there's no space at the top of the
            // page
            if ((top-ScrollTop) < floaterHeight) {
                $("div#popup-top").removeClass();
                $("div#popup-bot").removeClass();
                $("div#popup-top").addClass("popup-flipped-top");
                $("div#popup-bot").addClass("popup-flipped-bot");
                $("div#"+this.id).css( {
                    position: 'absolute',
                    zIndex: 5000,
                    left: 400,
                    top: top+12
                } );
            } else {
                $("div#"+this.id).css( {
                    position: 'absolute',
                    zIndex: 5000,
                    left: 400,
                    top: top-floaterHeight+2
                } );
            }
        }
    },
    hide: function(){
        // 5, 17
//
        // hide the div and wipe the contents of the data table, ranking image,
        // and top-sellers image
        clearTimeout(this.timeout);
        $("div#"+this.id).hide();
		if($('.select-free'))$('.select-free').hide();
        $("span.top-seller").hide();
        $(".data").html('N/A');
        $(".rank div").removeClass();
        $(".rank div").html("N/A");
        $(".rank div").removeAttr("title");
    },
    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) {
        $("p#fulfilledBy").html(sellerData["meta"]["fulfilledBy"]);
        $("span#sellerName").html(sellerData["meta"]["sellerName"]);
        $("span#newSellerName").html(sellerData["meta"]["sellerName"]);
        $("span#memberSince").html(sellerData["meta"]["memberSince"]);
    },
    writePercentiles: function(sellerData) {
			var period_days = 90;
      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 && metricVal != "N/A") {
        	if ( metric != "total_completed_transactions" && metricVal > 0 )
        		metricVal = $.sprintf("%0.1f", metricVal);
            if (metric.substring(0,3) === 'pct')
                metricVal += '%';
        } else {
            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(userId) {
        return sellerCredibility.sellers[userId];
    },
    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: Liquidation.com",
            "0"     :   "Fulfilled by: " + username
        }

        return fulfilledByText[warehouse_seller_flag];
    },
    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"
        );
    },
		unique: function(a) {
			var tmp = new Array(0);
			for ( var i=0; i<a.length; i++ ) {
				if ( !sellerCredibility.contains(tmp, a[i]) ) {
					tmp.length += 1;
					tmp[tmp.length-1] = a[i];
				}
			}
			return tmp;
		},
		contains: function(a, e) {
			for ( var j=0; j<a.length; j++ ) {
				if ( a[j] == e )
					return true;
			}
			return false;
		}
};


