/*
 *	Class: phone.credit
 */
phone.credit = {};

/*
 *	Function: setup
 *	Initiate everything for credit. Setup vars, events, etc.
 */
phone.credit.setup = function() {
	phone.credit.api = new API({resource:'users/'+user.current.id+'/purchases'});
	phone.credit.$container	= $('#credit').show();
	phone.credit.$list 			= phone.credit.$container.find('ul');

	var scroller 								= phone.credit.$container.find('.scroll').jScrollPane(phone.scroller_options);
	phone.credit.$scroller 			= scroller.data('jsp');

	phone.credit.$form_visible 	= phone.credit.$container.find('form.visible');
	phone.credit.$form_hidden		=	phone.credit.$container.find('form.hidden');

	phone.credit.$amount		= phone.credit.$container.find('form input[type=text]').numeric();
	phone.credit.$submit		= phone.credit.$container.find('.submit');

	phone.credit.$form_visible.submit(function() {
		phone.credit.createPurchase();
		return false;
	});
	
	phone.credit.api.call({success: function(data) {
		phone.credit.$list.empty();
		phone.credit.populate(data.purchases);
	}});
};

/*
 *	Function: populate
 *	Adds purchase(s) and setup events for it
 *	
 *	Parameters:
 *		array purchases - Array of purchase-objects, or a single purchase-object
 *
 *	Todo:
 *		- Implement payment-type-code
 */
phone.credit.populate = function(purchases) {
	$.each(purchases, function(i, purchase) {
		var html  = '<li>';
				html += '	<p class="date">'+$.format.mysql_to_date(purchase.created_at)+'</p>';
				html += '	<p class="currency">&#8364;</p>';
				html += '	<p class="amount">'+$.format.money(purchase.amount / 100, false)+'</p>';
				html += '	<p class="code">OB</p>';
				html += '</li>';
		phone.credit.$list.append(html);
	});
	phone.credit.$scroller.reinitialise();
}

/*
 *	Function: createPurchase
 *	Create a new purchase. After this is succesfully done, update all fields in the form and redirect to Rabobank
 */
phone.credit.createPurchase = function() {
	//Get data from visible form
	var data = {
		amount: phone.credit.$form_visible.find('.amount').val() * 100
	}
	
	//Save data to own database
	phone.credit.api.call({method:'POST', url_vars:'new', data:data, success:function(data){
		$popup.loading('PURCHASE_REDIRECTING');
		
		//Disable visible form
		phone.credit.$amount.attr("disabled", true).blur().addClass('blur');
		phone.credit.$submit.attr("disabled", true);

		//Update values of real/hidden form
		data.purchase.orderID = data.purchase.id;
		$.each(data.purchase, function(key,value) {
			if(value) phone.credit.$form_hidden.find('input[name='+key+']').val(value);
		});					
		
		//Submit real/hidden form
		console.log('----------------------');
		console.log('all data for rabobank:');
		console.log('----------------------');
		$.each(phone.credit.$form_hidden.find('input[type!=submit]'), function(i,field) {
			console.log($(field).attr('name') + ': ' + $(field).val());
		});
		
		phone.credit.$form_hidden.submit();
	}});
}
