/*
* ExpiringOffersUI class
* This class will manage the display and function of the expiring offers UI component on the logged in home page
*/

function CardSummaryUI(modelObj, merchantId){
	this.model = modelObj;
	this.merchantId = merchantId;
	this.model.registerEventListener("SavedOfferBucketsChange", this);
	this.model.registerEventListener("LoyaltyCardChange", this);
}

CardSummaryUI.prototype.onSavedOfferBucketsChange = function()
{
	this.updateCardSummary();
}

CardSummaryUI.prototype.onLoyaltyCardChange = function()
{
	this.updateCardSummary();
}

CardSummaryUI.prototype.updateCardSummary = function()
{
	var card = this.model.loyaltyCards[this.merchantId];
	var offerCount = 0;
	var cardNum = "<a href=\"javascript:wm.setLastAnchor('manage_card_number');cui.showRegForm(-1, false)\">+ Add Card</a>";
	if (this.model.user.authenticated)
	{
		cardNum = "<a href=\"javascript:wm.setLastAnchor('manage_card_number');cui.showAddCardNoOffer(" + this.merchantId + ")\">+ Add Card</a>";
	}
	var pendingDisplay = "none";
	if (card)
	{
		if (card.cardNum.length > 0)
		{
			cardNum = card.cardNum;
		}	
		else if (card.status == 1)
		{
			cardNum = "Pending";
			pendingDisplay = "block";
		}	
	}	
	var cNumEl = document.getElementById("manage_card_number");
	if (cNumEl)
	{
		cNumEl.innerHTML = cardNum;
	}	
	var pMessage = document.getElementById("manage_card_pending");
	if (pMessage)
	{
		pMessage.style.display = pendingDisplay;
	}	
	// figure out what they're worth
	var savings = 0;
	var coupon;
	var savedString = "";
	for(var couponId in this.model.coupons)
	{
		coupon = this.model.coupons[couponId];	
		if (coupon && coupon.isSaved && coupon.merchantId == this.merchantId)
		{
			// savedString += "found a saved - couponId = " + couponId + " and amount is " + coupon.faceValue + "\n";
			savings += parseFloat(coupon.faceValue);
			offerCount++;
		}	
		else
		{
			// savedString += "NOT FOUND - couponId = " + couponId + " and amount is " + coupon.faceValue + "\n";
		}	
	}	
	if (savings.toFixed)
	{
		savings = savings.toFixed(2);
	}	
	// alert(savedString + "\n total = " + savings);
	var savingsEl = document.getElementById("manage_card_savings");
	if (savingsEl)
	{
		savingsEl.innerHTML = "$" + savings;
	}	
	var saved = document.getElementById("manage_card_saved");
	if (saved)
	{
		saved.innerHTML = offerCount;
	}	
	if (offerCount > 0)
	{
		// make sure shopping list link is visible
		var listLink = document.getElementById("manage_card_shopping");
		if (listLink)
		{
			listLink.style.display = "block";
		}	
	}	
}

