/*
 * UIModel Class
 * This class will encapsulate all data that is relevant to the UI components
 * All UI components will reference the model object for their data.
 * The UIModel class will also maintain a list of events and the objects that are listening
 * for those events. 
 */
function UIModel(){
	this.loyaltyCards = null;
	this.coupons = null;
	this.merchants = null;
	this.categories = null;
	this.user = null;
	this.buckets = new Array();
	this.unassocOffers = null;
	this.unassocToLoseOffers = null;
	this.unassocToSaveOffers = null;
	this.unassocOfferDetails = null;
	this.unassocBulkToSingleMessage = null;
	this.views = null;
	this.unassocBulkMerchants = null;
	this.localMerchants = null;
	this.inIframe = false;
	this.inMMF = false;
	this.mmfSingleMode = false;
	this.mmfWidth = 9;
	this.iframe3pe = false;
	this.iframeMid = null;
	this.iframeCssId = null;
	this.fbIndex = null;
	this.fbButton = null;
	this.fbMerchantId = null;
	this.clientName = "Cellfire";
	this.exAdsOffer = null;
	this.exClipCoupon = null;
	this.merchantSelected = null;
	this.exCoupon = null;
	this.isXuserLogin = false;
	this.showMerchantTile = true;
	this.cfGuest = false;
	this.showMobilePopup = true;
	this.remCard = false;
	
	/*
	* UIMessenger Class
	* This class is a singleton this is implemented by making all of the methods static 
	* (all data and methods are defined at the prototype layer).
	* All messages (function objects) must take an array as a parameter.
	*/
	this.UIMessenger = {
		events: [],
		registerEvent: function(eventName){
			if(!this.events[eventName])
				this.events[eventName] = {name: eventName, listeners: []};
		},
		registerEventListener: function(eventName, listener){
			if(!this.events[eventName]) return false;
			this.events[eventName].listeners.push(listener);
			return true;
		},
		alertListeners: function(eventName, param){
			var event = this.events[eventName];
			if(!event){
				//alert("alertListener: "+eventName+" cannot fire");
				 return false;
			}
			for(var i = 0; i < event.messages.length; i++){
				event.messages[i](param);
			}
			return true;
		}
	};
	
	_MODEL = this;
	//window.onscroll = new Function("_MODEL.onWindowScroll()");
}

/***********************************************************************************
 * Event Registration functions
 */
UIModel.prototype.registerEventListener = function(eventName, listenerObj){
	this.UIMessenger.registerEvent(eventName); // Will register it only if not already registered
	this.UIMessenger.registerEventListener(eventName, listenerObj);
}


UIModel.prototype.fireEvent = function(eventName, param){
	var event = this.UIMessenger.events[eventName];
	if(!event) return; // Event has no listeners
	for(var i = 0; i < event.listeners.length; i++){
		event.listeners[i]['on'+eventName](param);
	}
}

/**************************************************************************************
 * Getters and Setters
 * Only create getters if there is some sort of logic to go along with delivering the data
 */
UIModel.prototype.setCoupons = function(couponArray){
	this.coupons = couponArray;
	for(var couponId in this.coupons){
		var coupon = this.coupons[couponId];
		
		coupon.title = coupon.title.replace(String.fromCharCode(153),"&trade;");
		coupon.hasChanged = false;
	}
}
UIModel.prototype.setGuest = function(guest){
	this.cfGuest = guest;
}
//showMobilePopup
UIModel.prototype.setShowMobilePopup = function(showMobilePopup){
	this.showMobilePopup = showMobilePopup;
}
UIModel.prototype.setSavedCoupons = function(savedCouponIdList){
	if(!this.coupons) return;
	if (savedCouponIdList != null)
	{
		for(var i = 0; i < savedCouponIdList.length; i++){
			var couponId = savedCouponIdList[i];
			var coupon = this.coupons[couponId];
			if(coupon) coupon.isSaved = true;
		}
	}	
	this.generateSavedOfferBuckets();
}

UIModel.prototype.setShowMerchantTile = function(showMerchant){
	this.showMerchantTile = showMerchant;
}
UIModel.prototype.setLoyaltyCards = function(loyaltyCardList){
	for(var mid in this.loyaltyCards){
		if(this.loyaltyCards[mid].addCardFormWindowHandle && loyaltyCardList[mid])
			loyaltyCardList[mid].addCardFormWindowHandle = this.loyaltyCards[mid].addCardFormWindowHandle;
	}
	this.loyaltyCards = loyaltyCardList;
	this.fireEvent("LoyaltyCardChange");
	//this.generateSavedOfferBuckets();
	// TODO: take this out...only for testing
	//var card = this.loyaltyCards[444];
	//if(!card) return;
	/* card.history = [{transactionTime: "20080924 12:12:12", couponName: "Fake Coupon Name", saving: 3.12},
					{transactionTime: "20080924 12:12:12", couponName: "Fake Coupon Name2", saving: 2.76},
					{transactionTime: "20080924 12:12:12", couponName: "Fake Coupon Name3", saving: 1.42},
					{transactionTime: "20080924 12:12:12", couponName: "Fake Coupon Name4", saving: 5.62},
					{transactionTime: "20080924 12:12:12", couponName: "Fake Coupon Name5", saving: 3.27},
					{transactionTime: "20080924 12:12:12", couponName: "Fake Coupon Name6", saving: 3.89},
					{transactionTime: "20080924 12:12:12", couponName: "Fake Coupon Name7", saving: 3.98}];
					 
	card.saveTotal = 47.47;
	*/ 
}

UIModel.prototype.setMerchants = function(merchantList, defaultMode){
	this.merchants = merchantList;
	// Loop through all the merchants setting their isCPG and displayMode flags
	for(var couponId in this.coupons){
		var coupon = this.coupons[couponId];
		var merchant = this.merchants[coupon.merchantId];
		if(!merchant) continue;
		if(coupon.isCPG && coupon.isCPG != 0){
			merchant.isCPG = true;
			merchant.displayMode = 2;
			if(defaultMode) merchant.displayMode = defaultMode;
		}
		else{
			// Make sure that the isCPG flag has not already been set to true.
			// We do not want to overwrite.
			if(!merchant.isCPG){
				merchant.isCPG = false;
				merchant.displayMode = 1;
			}
		}
	}
}

UIModel.prototype.setCategories = function(categoryList){
	this.categories = categoryList;
	this.fireEvent("CategoryChange");
}

UIModel.prototype.setUser = function(userObj){
	this.user = userObj;
}
//		model.setRemCard(<?= $remCard?>);
UIModel.prototype.setRemCard = function(remCard){
	this.remCard = remCard;
}

UIModel.prototype.setDisplayList = function(displayList){
	/*
	var debug = "setDisplayList ";
	for (var i in displayList)
	{
		debug += "\n" + displayList[i];
	}	
	alert(debug);
	*/
	this.couponIdDisplayList = displayList;
	this.fireEvent("DisplayListChange");
}

UIModel.prototype.removeIdFromDisplayList = function(couponId){
	for(var i = 0; i < this.couponIdDisplayList.length; i++){
		if(this.couponIdDisplayList[i] == couponId){
			this.couponIdDisplayList.splice(i,1);
			this.coupons[couponId].hasChanged = true;
		}
	}
	
	//this.fireEvent("CouponChange");
}

UIModel.prototype.setUnassocOffers = function(unassocOffers)
{
	this.unassocOffers = unassocOffers;
	if (this.unassocOffers && this.unassocOffers.length > 0)
	{
		this.fireEvent("UnassociatedOffersChange");
	}	
}
UIModel.prototype.setExAdsOffer = function(exAdsOffer)
{
	this.exAdsOffer = exAdsOffer;
}

UIModel.prototype.fireExChange = function()
{
	if (this.exAdsOffer)
	{
		this.fireEvent("ExAdsOfferChange");
	}	
}
UIModel.prototype.setExClipCoupon = function(exClipCoupon)
{
	this.exClipCoupon = exClipCoupon;
}
UIModel.prototype.setExtClipMerchantList = function(offerMerchant)
{
	this.ExtClipMerchantList = offerMerchant;
}
UIModel.prototype.setMerchantSelected = function(merc)
{
	this.merchantSelected = merc;
}
UIModel.prototype.setExCoupon = function(cp)
{
	this.exCoupon= cp;
}
UIModel.prototype.setUnassocToSaveOffers = function(unassocToSaveOffers)
{
	this.unassocToSaveOffers = unassocToSaveOffers;
}

UIModel.prototype.setUnassocToLoseOffers = function(unassocToLoseOffers)
{
	this.unassocToLoseOffers = unassocToLoseOffers;
}

UIModel.prototype.setUnassocBulkToSingleMessage = function(unassocBulkToSingleMessage)
{
	this.unassocBulkToSingleMessage = unassocBulkToSingleMessage;
}

UIModel.prototype.setUnassocBulkMerchants = function(unassocBulkMerchants)
{
	this.unassocBulkMerchants = unassocBulkMerchants;
}	

UIModel.prototype.getUnassocBulkMerchants = function()
{
	return this.unassocBulkMerchants;
}	

UIModel.prototype.setLocalMerchants = function(localMerchants)
{
	this.localMerchants = localMerchants;
}	

UIModel.prototype.hasLocalMerchants = function()
{
	return (this.localMerchants != null && this.localMerchants.length > 0);
}	

UIModel.prototype.getLocalMerchants = function()
{
	return this.localMerchants;
}	

UIModel.prototype.setClientName = function(clientName)
{
	this.clientName = clientName;
}	

UIModel.prototype.loadLoyaltyCards = function(callback){
	// Do the Ajax
	var req = getXMLHttpObject();
 	req.onreadystatechange = function(){
 		if(req.readyState == 4){
 			_MODEL.setLoyaltyCards(eval("("+req.responseText.toString()+")"));
 			_MODEL.generateSavedOfferBuckets();
 			if(callback) callback();
 		}
 	};
 	var openString = "/includes/services/loyalty_cards.php?update=true";
 	req.open("GET",openString,true);
 	req.send(null);
 	
}

UIModel.prototype.loadCategories = function(){
	// Do the Ajax
  	this.setCategories({});
	var req = getXMLHttpObject();
 	req.onreadystatechange = function(){
 		if(req.readyState == 4){
 			//var beforeTime = getTime();
 			 _MODEL.setCategories(eval("("+req.responseText.toString()+")"));
 			 //var afterTime = getTime();
 			 //alert((afterTime-beforeTime)/1000);		
 		}
 	};
 	var openString = "/includes/services/categories_ext.php?update=true";
 	req.open("GET",openString,true);
 	req.send(null);
}

UIModel.prototype.removeCouponFromDisplayList = function(couponId){
	for(var i = 0; i < this.couponIdDisplayList.length; i++){
		if(this.couponIdDisplayList[i] == couponId){
			this.couponIdDisplayList.splice(i,1);
			break;
		}
	}
	
	this.fireEvent("DisplayListChange");
}

UIModel.prototype.removeMerchantFromDisplayList = function(merchantId){
	for(var i = 0; i < this.couponIdDisplayList.length; i++){
		var coupon = this.coupons[this.couponIdDisplayList[i]];
		if(coupon.merchantId == merchantId){
			this.couponIdDisplayList.splice(i,1);
			break;
		}
	}
	
	this.fireEvent("DisplayListChange");
}

UIModel.prototype.setViews = function(views){
	this.views = views;
	this.fireEvent("ViewListChange");
}

UIModel.prototype.setViewShowing = function(viewIndex){
	
	for(var index in this.views){
	 	var temp = this.views[index]; 
	 	if(!temp.displayTitle) continue;
	 	temp.isShowing = false;
	}
	
	var view = this.views[viewIndex];
	 
	if(view){
		this.setSelectedBucket(false);
		view.draw();
		view.isShowing = true;
	}
	
	this.fireEvent("ViewListChange");
}

UIModel.prototype.setFeed = function(feed){
	this.feed = feed;
	this.fireEvent("SetFeed");
}

UIModel.prototype.setInIframe = function(inIframe)
{
	this.inIframe = inIframe;
}	

UIModel.prototype.setInMMF = function(inMMF)
{
	this.inMMF = inMMF;
}	

UIModel.prototype.setInMmfSingleMode = function(singleMode)
{
	this.mmfSingleMode = singleMode;
}	

UIModel.prototype.setMMFWidth = function(w)
{
	this.mmfWidth = w;
}	

UIModel.prototype.setCollectThirdPartyEmail = function(iframe3pe)
{
	this.iframe3pe = iframe3pe;
}	


UIModel.prototype.setIframeMerchantId = function(mId)
{
	this.iframeMid = mId;
}	

UIModel.prototype.setIframeCssId = function(cssId)
{
	this.iframeCssId = cssId;
}	

UIModel.prototype.setFBIndex = function(index)
{
	this.fbIndex = index;
}	

UIModel.prototype.setFBButton = function(button)
{
	this.fbButton = button;
}	

UIModel.prototype.setFBMerchant = function(merchantId)
{
	this.fbMerchantId = merchantId;
}	

/****************************************************************
 * Utility Functions
 */
UIModel.prototype.generateSavedOfferBuckets = function(){
	var mobileCount = 0;
	var cards = this.loyaltyCards;
	if(!this.buckets['all'] || !this.buckets['mobile']){
	  	this.buckets['all'] = {id: "all", 
	  							bucketName: "Total Saved Offers", 
	  							icon: '/includes/templates/master/images/saved_all.gif', 
	  							couponIdList: new Array(), 
	  							merchantId: null,
	  							prevCount: false,
	  							hasChanged: false 
	  							};
	  	this.buckets['mobile'] = {id: "mobile", 
	  								bucketName: this.clientName + " Mobile", 
	  								icon: '/includes/templates/master/images/saved_phone.jpg', 
	  								couponIdList: new Array(), 
	  								merchantId: null,
	 	  							hasChanged: false, 
	  								hasChanged: false
	  								};
	}
	else{
		this.buckets['all'].prevCount = this.buckets['all'].couponIdList.length;
		this.buckets['mobile'].prevCount = this.buckets['mobile'].couponIdList.length;
		this.buckets['all'].couponIdList = new Array();
		this.buckets['mobile'].couponIdList = new Array();
	}
	
	for(var mercId in cards){
		var card = cards[mercId];
		if(card.status != 0){
  			if(!this.buckets[mercId])
  				this.buckets[mercId] = {id: mercId, bucketName: card.merchantName+" "+card.cardName, icon: '/includes/templates/master/images/saved_card.png', couponIdList: new Array(), capacity: card.capacity, merchantId: card.merchantId, prevCount: false, hasChanged: false};
  			else{
  				this.buckets[mercId].prevCount = this.buckets[mercId].couponIdList.length;
  				this.buckets[mercId].couponIdList = new Array();
  			}	 
		}
		else{
			if(this.buckets[mercId])
				this.buckets[mercId].couponIdList = false;
		}
  	}
	
  	for(var couponId in this.coupons){
  		var coupon = this.coupons[couponId];
  		if(coupon.isSaved){
	  		var bucket = this.buckets[coupon.merchantId];
	  		if(bucket && coupon.isCPG){
	  			if(!bucket.couponIdList)
	  				bucket.couponIdList = new Array();
	  			bucket.couponIdList.push(couponId);
	  		}
	  		else{
	  			this.buckets['mobile'].couponIdList.push(couponId);
	  		}
	  		this.buckets['all'].couponIdList.push(couponId);
  		}
  	}	
  	
  	for(var bucketId in this.buckets){
  		var bucket = this.buckets[bucketId];
  		if(!bucket) continue;
  		if((bucket.prevCount || bucket.prevCount===0) && bucket.prevCount != bucket.couponIdList.length)
  			bucket.hasChanged = true;
  	}
  	
  	this.fireEvent("SavedOfferBucketsChange");
}

UIModel.prototype.updateLoyaltyCard = function(merchantId, cardNum, altNum, status, offerId){
	var card = this.loyaltyCards[merchantId];
	card.cardNum = cardNum;
	card.alternate = altNum;
	
	card.status = status;
	
	if(offerId){
		card.numSavedToCard++;
		for(var i in this.coupons){
			if(this.coupons[i].offerId == offerId && this.coupons[i].merchantId == merchantId){
				this.coupons[i].isSaved = true;
				this.coupons[i].hasChanged = true;
			}
		}
	}
	
	// If removing the card
	if(status == 0 || status == '0'){
		for(var i in this.buckets[merchantId].couponIdList){
			var couponId = this.buckets[merchantId].couponIdList[i];
			this.coupons[couponId].isSaved = false;
		}
	}
	
	this.generateSavedOfferBuckets();
	this.fireEvent("CouponChange");
	this.fireEvent("LoyaltyCardChange");
	
	if(status == 0 || status == '0'){
		this.setSelectedBucket('all');
	}
}

UIModel.prototype.unassocOffer = function(offerId)
{
	var couponId = this.findAnyCouponFromOffer(offerId);
	if (couponId != -1)
	{
		this.coupons[couponId].working = true;
	}	
	var req = getXMLHttpObject();
	req.onreadystatechange = function()
	{
		if(req.readyState == 4)
		{
			if (req.responseText == "1")
				_MODEL.unassocSuccess(""+offerId);
		}	
	}	
	var openString = "/includes/form_handlers/clipping.php?unassoc=" + offerId;
	req.open("GET",openString,true);
	req.send(null);
}
 
UIModel.prototype.unassocSuccess = function(offerId)
{
	this.clearWorkingCouponFromOffer(offerId);
	this.removeAssocOffer(offerId);
	// alert("success");
	this.fireEvent("UnassociatedOffersChange");
}

UIModel.prototype.assocOffer = function(offerId, merchantId)
{
	var couponId = this.findCouponFromOfferMerchant(offerId, merchantId);
	if (couponId != -1)
	{
		this.coupons[couponId].working = true;
	}	
	var req = getXMLHttpObject();
	req.onreadystatechange = function()
	{
		if(req.readyState == 4)
		{
			if(req.responseText == "1")
				_MODEL.assocSuccess(""+offerId, ""+merchantId);
			//else 
			//	_MODEL.assocFailed(""+offerId);				
		}
	}	
	var openString = "/includes/form_handlers/clipping.php?assoc=" + offerId + "&assoc_merch=" + merchantId;
	req.open("GET",openString,true);
	req.send(null);
}

UIModel.prototype.bulkAssocOffers = function(merchantId, cardJustAdded)
{
	// alert("start of UIModel.prototype.bulkAssocOffers - cardJustAdded = " + cardJustAdded);
	var req = getXMLHttpObject();
	var params = "bulk_clip=1&merchantId=" + merchantId;
	if (this.unassocToSaveOffers != null && this.unassocToSaveOffers.length > 0)
	{	
		params += "&offerIds=";
		// alert("UIModel - bulkAssocOffers - unassocToSaveOffers size = " + params);
		for (var i = 0; i < this.unassocToSaveOffers.length; i++)
		{
			if (i != 0)
			{
				params += ",";
			}
			params += this.unassocToSaveOffers[i];
		}	
	}
	if (this.unassocToLoseOffers != null && this.unassocToLoseOffers.length > 0)
	{
		params += "&loseIds=";
		// alert("UIModel - bulkAssocOffers - unassocToSaveOffers size = " + params);
		for (var i = 0; i < this.unassocToLoseOffers.length; i++)
		{
			if (i != 0)
			{
				params += ",";
			}
			params += this.unassocToLoseOffers[i];
		}	
	}
	// alert("UIModel - bulkAssocOffers - params = " + params);
	req.onreadystatechange = function()
	{
		if(req.readyState == 4)
		{
			if(req.responseText == "1")
			{
				_MODEL.bulkAssocSuccess(merchantId, cardJustAdded);
			}	
		}
	}	
	var openString = "/includes/form_handlers/clipping.php";
	req.open("POST", openString, true);
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	req.setRequestHeader("Content-length", params.length);
	req.setRequestHeader("Connection", "close");	
	req.send(params);
}
	

UIModel.prototype.bulkAssocSuccess = function(merchantId, cardJustAdded)
{
	// offers to do the assoc success with are in this.unassocToSaveOffers
	// need to do something similar to assocSuccess, but we only need to fire the events once (so can't really call the one by one routine)
	// we also know that there are no more unassoc offers - 'cos they're either successfully assoc'd or they're removed
	
	var couponId;
	var coupon;
	var curList = this.couponIdDisplayList;
	this.fireOpinMindPixel(this.unassocToSaveOffers);
	for (var i in this.unassocToSaveOffers)
	{
		couponId = this.findCouponFromOfferMerchant(this.unassocToSaveOffers[i], merchantId);
		if (couponId != -1)
		{
			coupon = this.coupons[couponId];
			coupon.isSaved = true;
			coupon.working = false;
			coupon.hasChanged = false;
			if (curList)
			{
				curList.splice(0, 0, couponId);
			}
			else
			{
				curList = new Array(couponId);
			}	
		}
	}	
	this.setDisplayList(curList);
	this.generateSavedOfferBuckets();
	this.fireEvent("CouponChange");

  var card = this.loyaltyCards[merchantId];
	if(card)
	{ 
		card.numSavedToCard += this.unassocToSaveOffers.length;
		if(card.numSavedToCard >= card.capactity)
		{
			this.fireEvent("LoyaltyCardChange");
		}	
	}

	// alert("card just added is " + cardJustAdded + " unassoc length is " + this.unassocToSaveOffers.length);	
	if (cardJustAdded)
	{
		lcui.showAddCardSuccessWindow(merchantId, this.unassocToSaveOffers.length);
	}

	this.unassocOffers = null;
	this.unassocToSaveOffers = null;
	
	// commented out
	// this.fireEvent("UnassociatedOffersChange");

}

UIModel.prototype.assocSuccess = function(offerId, merchantId)
{
	var couponId = this.findCouponFromOfferMerchant(offerId, merchantId);
	// alert("assocSuccess - couponId is " + couponId);
	if (couponId != -1)
	{
		var coupon = this.coupons[couponId];
		coupon.isSaved = true;
		coupon.working = false;
		coupon.hasChanged = false;

		this.generateSavedOfferBuckets();
		this.fireEvent("CouponChange");
		
		var curList = this.couponIdDisplayList;
		if (curList)
		{
			curList.splice(0, 0, couponId);
		}
		else
		{
			curList = new Array(couponId);
		}	
		this.setDisplayList(curList);
		this.fireOpinMindPixel(new Array(offerId, 0));
	}	
	
  var card = this.loyaltyCards[merchantId];
	if(card)
	{ 
		card.numSavedToCard++;
		if(card.numSavedToCard >= card.capactity)
			this.fireEvent("LoyaltyCardChange");
	}
	this.removeAssocOffer(offerId);
	this.fireEvent("UnassociatedOffersChange");
}

UIModel.prototype.isAnyCouponFromOfferWorking = function(offerId)
{
	var foundWorking = false;
	for (var i in this.coupons)
	{
		if (this.coupons[i].offerId == offerId && this.coupons[i].working)
		{
			foundWorking = true;
			break;
		}
	}
	return foundWorking;
}	

UIModel.prototype.clearWorkingCouponFromOffer = function(offerId)
{
	for (var i in this.coupons)
	{
		if (this.coupons[i].offerId == offerId && this.coupons[i].working)
		{
			this.coupons[i].working = false;
		}
	}
}	

UIModel.prototype.findAnyCouponFromOffer = function(offerId)
{
	var couponId = -1;
	for (var i in this.coupons)
	{
		if (this.coupons[i].offerId == offerId)
		{
			couponId = this.coupons[i].couponId;
			break;
		}
	}
	return couponId;
}	

UIModel.prototype.findCouponFromOfferMerchant = function(offerId, merchantId)
{
	var couponId = -1;
	for (var i in this.coupons)
	{
		if (this.coupons[i].offerId == offerId && this.coupons[i].merchantId == merchantId)
		{
			couponId = this.coupons[i].couponId;
			break;
		}
	}
	return couponId;
}	

UIModel.prototype.isOfferAssocOffer = function(offerId)
{
	var doingAssoc = false;
	if (this.unassocOffers != null)
	{
		for (var i in this.unassocOffers)
		{
			if (this.unassocOffers[i].offerId == offerId)
			{
				doingAssoc = true;
				break;
			}	
		}
	}	
	// alert("doingAssoc:" + doingAssoc);
	return doingAssoc;
}

UIModel.prototype.removeAssocOffer = function(offerId)
{
	var tUnassocOffers = new Array();
	var j = 0;
	for (var i = 0; i < this.unassocOffers.length; i++)
	{
		if (this.unassocOffers[i].offerId != offerId)
		{
			tUnassocOffers[j] = this.unassocOffers[i];
			j++;
		}
	}
	this.unassocOffers = tUnassocOffers;
}	

UIModel.prototype.saveCoupon = function(couponId){
  	// Do the Ajax
  	this.coupons[couponId].working = true;
	var req = getXMLHttpObject();
 	req.onreadystatechange = function(){
 		if(req.readyState == 4){
 			if(req.responseText == "1" || req.responseText == "2")
 				_MODEL.saveSuccess(""+couponId);
 			else {
 				_MODEL.saveFailed(""+couponId,req.responseText);	
 			}
 		}
 	};
 	var openString = "/includes/form_handlers/clipping.php?clip="+couponId;
 	req.open("GET",openString,true);
 	req.send(null);
 	
 	//setTimeout("_MODEL.saveSuccess("+couponId+")", 2000);		
}

UIModel.prototype.saveSuccess = function(couponId){
	//show shoppingList
	var shoppingList = document.getElementById("shoppingList");
	if(shoppingList) shoppingList.style.display = "block";
	var coupon = this.coupons[couponId];
	coupon.isSaved = true;
	coupon.working = 2;
	coupon.hasChanged = true;

	this.fireEvent("CouponChange");

	var card = this.loyaltyCards[coupon.merchantId];
	if(card && coupon.isCPG){ 
		card.numSavedToCard++;
		if(card.numSavedToCard >= card.capactity)
			this.fireEvent("LoyaltyCardChange");
	}
	
	if (coupon.isCPG)
	{
		if (this.removeOtherInstancesOfThisCoupon(couponId))
		{
			//this.fireEvent("DisplayListChange");
		}	
	}
	this.generateSavedOfferBuckets();
	this.fireOpinMindPixel(new Array(coupon.offerId, 0));
}

UIModel.prototype.saveFailed = function(couponId, errorId){
	var callback = new Function("" +
			"var coupon =_MODEL.coupons["+couponId+"];" +
			"coupon.working = false;" +
			"_MODEL.fireEvent(\"CouponSaveFailed\", {couponId:"+couponId+",errorId:"+errorId+"});"
	);	

	this.loadLoyaltyCards(callback);
}

UIModel.prototype.unsaveCoupon = function(couponId){
	this.coupons[couponId].working = true;
	var req = getXMLHttpObject();
	req.onreadystatechange = function(){
		if(req.readyState == 4){
			if(req.responseText == "1" || req.responseText == "2")
	 			_MODEL.unsaveSuccess(""+couponId);
	 		else 
	 			_MODEL.unsaveFailed(""+couponId);		 		}
	 }
	 var openString = "/includes/form_handlers/clipping.php?unclip="+couponId;
	 req.open("GET",openString,true);
	 req.send(null);
	 //_MODEL.unsaveSuccess(couponId);
}

UIModel.prototype.unsaveSuccess = function(couponId){
	var coupon = this.coupons[couponId];
	coupon.isSaved = false;
	coupon.working = false;
	coupon.hasChanged = true;
	
	this.generateSavedOfferBuckets();
  	this.fireEvent("CouponChange");
  	
  	var card = this.loyaltyCards[coupon.merchantId]
	if(card){
		 card.numSavedToCard--;
		 //this.fireEvent("LoyaltyCardChange");
	}
}

UIModel.prototype.unsaveFailed = function(couponId){
	var coupon = this.coupons[couponId];
	coupon.working = false;
  	this.fireEvent("CouponChange");
}

UIModel.prototype.sentShoppingList = function(email){
  	this.fireEvent("ShoppingListSent",email);
}

//clippingwithCard
UIModel.prototype.clippingwithCard = function(cardNum,couponId,errorCode){
  	this.fireEvent("ClippingwithLoyaltyCard",{cardNum:"+cardNum+",couponId:"+couponId+",errorCode:"+errorCode+"});
}

UIModel.prototype.setSelectedBucket = function(bucketId){
	for(var id in this.buckets)
		if(this.buckets[id])
			this.buckets[id].isSelected = false;
	
	if(bucketId){
		this.buckets[bucketId].isSelected = true;
		//this.buckets[bucketId].hasChanged = true;
		this.setDisplayList(this.buckets[bucketId].couponIdList);
		this.setViewShowing(false);
	}
	else{
		this.setDisplayList([]);
	}
		
	
	this.fireEvent("SavedOfferBucketsChange");
}

UIModel.prototype.setCouponWorkingState = function(couponId, state){
	this.coupons[couponId].working = state;
	this.fireEvent("CouponChange");
}

UIModel.prototype.getCouponFromOfferId = function (offerId)
{
	var coupon = null;
	for (var i in this.coupons)
	{
		if (this.coupons[i].offerId == offerId)
		{
			coupon = this.coupons[i];
			break;
		}
	}
	return coupon;
}	

UIModel.prototype.removeOtherInstancesOfThisCoupon = function(couponId)
{
	var deletedAnything = false;
	var offerId = this.coupons[couponId].offerId;
	var merchantId = this.coupons[couponId].merchantId;
	for (var i in this.coupons)
	{
		if (i != couponId && this.coupons[i].isCPG && this.coupons[i].offerId == offerId && merchantId != this.coupons[i].merchantId)
		{
			//delete this.coupons[i];
			this.removeCouponFromDisplayList(i);
			deleteAnything = true;
		}
	}	
	return deletedAnything;
}


UIModel.prototype.clipRebateOffer = function(couponId, firstName, lastName, street1, street2, city, state, zip, email)
{
	this.coupons[couponId].working = true;
	var offerId = this.coupons[couponId].offerId;
	var merchantId = this.coupons[couponId].merchantId;	
	var req = getXMLHttpObject();
	var params = 'reb_offerid=' + offerId + 
					 '&reb_merchant=' + merchantId +
					 '&reb_first_name=' + escape(firstName) +
					 '&reb_last_name=' + escape(lastName) +
					 '&reb_street1=' + escape(street1) +
					 '&reb_street2=' + escape(street2) +
					 '&reb_city=' + escape(city) +
					 '&reb_state=' + escape(state) +
					 '&reb_zip=' + escape(zip) +
					 '&reb_email=' + escape(email);

	req.onreadystatechange = function()
	{
		if(req.readyState == 4)
		{
			if(req.responseText == "1")
			{
				// alert('about to call saveSuccess ' + couponId);
				_MODEL.saveSuccess(''+couponId);
			}	
			else
			{
				//alert('about to call saveFailed ' + couponId);
				_MODEL.saveFailed(''+couponId, req.responseText);
			}	
		}
	}	
	var openString = "/includes/form_handlers/clip_rebate_offer.php";
	req.open("POST", openString, true);
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	req.setRequestHeader("Content-length", params.length);
	req.setRequestHeader("Connection", "close");	
	req.send(params);
}

UIModel.prototype.getFBBundleId = function(couponId)
{
	var offer = this.coupons[couponId];
	var bundleId = -1;
	if (offer)
	{
		if (offer.isSaved)
		{
			if (offer.isCPG && offer.isCPG != "0")
			{
				bundleId = 103400920869;
			}
			else
			{
				bundleId = 103401340869;
			}
		}
		else
		{	
			if (offer.isCPG && offer.isCPG != "0")
			{
				bundleId = 103399805869;
			}
			else
			{
				bundleId = 103400375869;
			}
		}	
	}	
	return bundleId;
}

UIModel.prototype.getFBCardBundleId = function()
{
	return 103769830869;
}	

UIModel.prototype.getFBtlc = function(couponId)
{
	var offer = this.coupons[couponId];
	var tlc = 'aaw';
	if (offer)
	{
		if (offer.isSaved)
		{
			if (offer.isCPG && offer.isCPG != "0")
			{
				tlc = 'cym';
			}
			else
			{
				tlc = 'cyn';
			}
		}
		else
		{	
			if (offer.isCPG && offer.isCPG != "0")
			{
				tlc = 'cyk';
			}
			else
			{
				tlc = 'cyl';
			}
		}	
	}	
	return tlc;
}


UIModel.prototype.fireOpinMindPixel = function(offerIds)
{
	var nowTime = new Date().getTime();
	var offerParams = '';
	for (var i = 0; i < offerIds.length; i++)
	{
		if (this.checkOMOffer(offerIds[i]))
		{
			offerParams += "&offer" + offerIds[i] + "=" + nowTime;	
		}
	}
	if (offerParams.length > 0)
	{
		offerParams = 'http://tag.yieldoptimizer.com/ps/ps?t=i&p=' + cf_op_id + "&u=" + this.user.id + offerParams;
		var opImg = document.getElementById('opinmind_js');
		opImg.src = offerParams;
	}
}	
	
UIModel.prototype.checkOMOffer = function(offerId)
{
	return (offerId == 1064);
}	
		
		
