if (!esg.bankedOffers) 
    esg.bankedOffers = {};

esg.bankedOffers.model = {
	itemCount:0, 
    currentOffer: null,
	offers: null,
	offer: function(sourceId, savings, orderTotal, title, offerEndDate) {
		this.sourceId = sourceId;
		this.savings = savings;
		this.orderTotal = orderTotal;
		this.title = title;
		this.offerEndDate = offerEndDate;
		this.promotions = [];
	},
	promotion: function(details, endDate) {
		this.details = details;
		this.endDate = endDate;
	},
	hasCartItems: function() {
		return (this.itemCount > 0)
	},
	uris: {
		getOffers: '/gallery/cart/get_offer_pricing_ajax.jsp' 
	}
}

esg.model.observable.mixin(esg.bankedOffers.model);

esg.bankedOffers.controller = {
    execute: function(eventMsg, parms){
    
        var model = esg.bankedOffers.model;
        var cmd = esg.bankedOffers.commands;
        var views = esg.bankedOffers.views;
        
        switch (eventMsg) {
            case 'showOffers':
				if (!model.offers) {
					cmd.getOffers();
				}
				else {
                	views.showOffers();
				}
                break;
            case 'hideOffers':
                views.hideOffers();
                break;
            case 'selectOffer':
				cmd.changeOffer(parms.sourceId)
                break;
            case 'applyOffer':
				cmd.applyOffer();
                break;
			case 'initBankedOffers':
				model.offers = null;
				views.addEventHandlers();
				break;	
        }
    }
}

esg.bankedOffers.commands = {
    model: esg.bankedOffers.model,
    controller: esg.bankedOffers.controller,
    getOffers: function(){
        esg.viewUtil.throbber.show();
        var req = new esg.utility.JSONRequest({
            url: this.model.uris.getOffers,
            secure: false,
            method: "get",
            controller: this.controller,
            onSuccess: function(json){
				model = esg.bankedOffers.model;
				model.selectedSourceId = json.selectedSourceId;
				model.offers = [];
				if (json.itemCount && json.itemCount > 0)
					model.itemCount = json.itemCount;
				else
					model.itemCount = 0;
					 
                if ($defined(json.offers)) {
					var offers = $splat(json.offers);
                    offers.each(function(entry, index){
						var offer = new model.offer(entry.sourceId, entry.savings, entry.orderTotal, entry.title, entry.offerEndDate);
						if ($defined(entry.promotions)) {
							var promotions = $splat(entry.promotions);
							promotions.each(function(entry, index){
								offer.promotions.push(new model.promotion(entry.details, entry.endDate));
							});
						}
						if (offer.sourceId == model.selectedSourceId) {
							// The currently active offer always appears at the front of the list
							model.offers.splice(0, 0, offer);
							model.currentOffer = offer;
						} else {
							model.offers.push(offer);
						}
					});
				}
                esg.viewUtil.throbber.hide();
				esg.bankedOffers.controller.execute('showOffers');
            }
        }).send();
    },
	changeOffer: function(sourceId) {
		this.model.offers.each(function(entry, index){
			if (entry.sourceId == sourceId){
				this.model.currentOffer = entry;
			}
		});
		this.model.notifyObservers(this.model, "currentOffer");
	},
	applyOffer: function() {
		var newUri = new URI();
		newUri.setData({sourceId: this.model.currentOffer.sourceId}, true);
		window.location.replace(newUri.toString());
	}
}

esg.bankedOffers.views = {
	model: esg.bankedOffers.model,
    showOffers: function(){
        var offersDialog = $("bankedOffersDialog");
        if (!offersDialog) {
            this.renderDialog();
        }
		this.renderOffers();
		this.renderCartAmount();
        esg.viewUtil.modalBox.show('bankedOffersDialog');
    },
    hideOffers: function(){
        esg.viewUtil.modalBox.hide('bankedOffersDialog');
    },
    renderDialog: function(){
        var offersDialog = new Element('div', {
            'id': 'bankedOffersDialog',
            'class': 'dialogbox'
        });
        var header = new Element('div', {
            'class': 'header clearfix'
        });
        
        var headerText = new Element('h3', {
            'id': 'bankedOffers_caption',
            'html': 'Your Discounts'
        });
        
        var headerClose = new Element('a', {
            'id': 'bankedOffersClose',
            'href': 'javascript:void(0);',
            'title': 'Close',
            'class': 'dialogclose',
            'events': {
                'click': function(e){
                    e.stop();
                    esg.bankedOffers.controller.execute("hideOffers");
                }
            }
        });
        header.adopt(headerText, headerClose);
        offersDialog.appendChild(header);
		
		if (this.model.hasCartItems()) {
			var cartIconText = new Element('span',{
				'class': "cartIcon",
				'text': 'Cart Total: '
			});
			var cartAmount = new Element('span',{
				'id': "bankedOfferCartAmount",
				'class': "cartAmount"
			});
			cartIconText.adopt(cartAmount);
			header.adopt(cartIconText);
		}

        
        var panel = new Element('div', {
            'id': 'bankedOffersPanel'
        });
        offersDialog.appendChild(panel);
        
        var footer = new Element('div', {
            'id': 'bankedOffersFooter',
            'class': 'bankedOffersFooter clearfix'
        });
        
        var cancel = new Element('a', {
            'id': 'bankedOffersCancel',
            'href': 'javascript:void(0)',
            'class': 'linkbutton tertiarybutton',
            'events': {
                'click': function(e){
                    e.stop();
                    esg.bankedOffers.controller.execute("hideOffers");
                }
            },
            'html': '<span>Cancel</span>'
        });
        
        var apply = new Element('a', {
            'id': 'bankedOffersApply',
            'href': 'javascript:void(0)',
            'class': 'linkbutton',
            'events': {
                'click': function(e){
                    e.stop();
                    esg.bankedOffers.controller.execute("applyOffer");
                }
            },
            'html': '<span>Apply Discount</span>'
        });
        footer.appendChild(cancel);
        footer.appendChild(apply);
        offersDialog.appendChild(footer);
        
        $(document.body).appendChild(offersDialog);
    },
    renderOffers: function(){
		var html = [];
		html.push('<table border=0><thead><tr><th></th>');
		if (this.model.hasCartItems())
			html.push('<th class="savings">Your Savings</th>');
		html.push('<th class="offers">Discount Description</th></tr></thead>');
		html.push('<tbody>');
		this.model.offers.each(function(entry, index){
			var isSelected = entry.sourceId == model.selectedSourceId;
			var altRow = ((index % 2) > 0);
			html.push('<tr class="' + ((altRow) ? "altRow" : "") + '">');
			html.push('<td class="selectButton"><input type="radio" class="offerSelectorButton" name="offerSelector" value="' + entry.sourceId + '" ' + (isSelected ? 'checked':'') + '/></td>');
			if (this.model.hasCartItems())
				html.push('<td class="savings">' + entry.savings + '</td>');
			html.push('<td class="offers">');
			html.push('<span class="offerTitle">' + entry.title + '</span>');
			if (entry.offerEndDate)
				html.push('<span class="offerEndDate promoEnds">Offer ends: ' + entry.offerEndDate + '</span>');
			html.push(esg.bankedOffers.views.renderPromotions(entry.promotions));
			html.push('</td></tr>');
		});
		html.push('</tr></tbody></table>');
		$('bankedOffersPanel').empty();
		$('bankedOffersPanel').innerHTML = html.join('');
		$$('.offerSelectorButton').addEvent('click', function(evt){
			esg.bankedOffers.controller.execute('selectOffer', {sourceId: evt.target.value} );
			// Omniture tag
			s.eVar36 = model.selectedSourceId +"|"+ evt.target.value;
			s.t();
		});
    },
    renderPromotions: function(promotions){
		var html = [];
		html.push("<ul>");
		promotions.each(function(entry, index){
			html.push('<li><span class="promoDetails">' + entry.details + '</span><br/>');
			// hide this per marketing request
//			if (entry.endDate)
//				html.push('<span class="promoEnds">Ends: ' + entry.endDate + '</span></li>');
		});
		html.push("</ul>");
		return html.join('');
    },
    renderCartAmount: function(){
		if (this.model.hasCartItems()) {
			$("bankedOfferCartAmount").set("html", this.model.currentOffer.orderTotal);
		}
    },
	addEventHandlers: function(){
		if ($('otherOffersLink')){
			$('otherOffersLink').removeEvents();
			$('otherOffersLink').addEvent(
				'click', function(e){
					e.stop();
					esg.bankedOffers.controller.execute('showOffers');
					return false;			
			});
		}	
	}
}
esg.bankedOffers.model.addObserver(esg.bankedOffers.views.renderCartAmount, "currentOffer");

// When the DOM is loaded attach event handlers
window.addEvent('domready', function(){	
	esg.bankedOffers.controller.execute('initBankedOffers');
});		
	
