
var EGiftCheck = Class.create({
    initialize: function(args) {
    	this.gcNum = 0;
    	this.gcPin = 0;
    	this.balance = 0;
    	this.errorMsg = '';
    	this.callback = null;
    	
        Object.extend(this, args || {});
        
        this.fetchCheck();
    },
    
    fetchCheck: function() {
		this.errorMsg = '';
		this.balance = 0;
		var id = jsonrpc.fetch( 'cart.checkgiftcard', 
			[{
			'GIFTCARD_NUM': [this.gcNum],
			'GIFTCARD_PIN': [this.gcPin]
			}],
			{
				onSuccess: this.checkSuccess.bind(this),
				onFailure: function () { console.log( 'EGiftCheck JSON failed to load ' ) }
			}
		);
		return id;
    },
    
    checkSuccess: function(t) {
		var response = t.responseText.evalJSON()[0];
		var error = response.error;
		var data = $H(response.result);
		var bal = data.get('giftcard_balance');
		bal = parseFloat(bal);
		
		if ( isNaN(bal) ) {
			this.balance = 0;
			this.errorMsg = 'We do not recognize this Gift Card number and PIN. ' +
							' Please review the numbers in the Gift Card number and PIN fields.';
		} else {
			this.balance = bal;
			this.errorMsg = '';
		}
		
		if ( this.callback )
			this.callback();
    },
    
    balanceAsCurrency: function() {
    	var bal = Number(this.balance).toCurrency('$');
    	return bal;
    }
    
});
