define(
	[
		'table',
		'saver'
	],
	function (table, saver) {
		"use strict";

		table.extend('save', (function(){
			function TableSave() {
				this.table = null;
				this.events = ['data-loaded'];
			}

			TableSave.prototype.init = function() {
				this.retrieve();
			};

			TableSave.prototype.retrieve = function() {
				saver.retrieve({
					names: this.getSaveObj(),
					callback: function(data) {
						var p, i, num, obj = {};

						if (data[this.table.id + '-rows'] !== '') {
							//this.table.rows.num = parseInt(data[this.table.id + '-rows'], 10);
							//this.table.cols.num = parseInt(data[this.table.id + '-cols'], 10);

							//for (i = 0; i < this.table.rows.num; i++) {
							for (i = 0, num = parseInt(data[this.table.id + '-rows'], 10); i < num; i++) {
								obj[this.table.id + '-row' + i] = '';
							}

							saver.retrieve({
								names: obj,
								callback: function(data) {
									for (p in data) {
										if (data.hasOwnProperty(p) && data[p] !== '') {
											this.table.content[p.replace(this.table.id + '-row', '')] = JSON.parse(data[p]);
										}
									}

									this.table.trigger('data-loaded');
								}.bind(this)
							});
						}
					}.bind(this)
				});
			};

			TableSave.prototype.getSaveObj = function() {
				var obj = {};

				obj[this.table.id + '-rows'] = this.table.rows.num;
				obj[this.table.id + '-cols'] = this.table.cols.num;

				//chunk content in case large amounts of data (saving to the VLE)
				this.table.content.forEach(function(row, i) {
					obj[this.table.id + '-row' + i] = JSON.stringify(row);
				}.bind(this));

				return obj;
			};

			TableSave.prototype.saveData = function() {
				saver.save({
					values: this.getSaveObj()
				});
			};

			TableSave.prototype.handleEvent = function(e) {
				if (e.type == 'save') {
					this.saveData();
				}
			};

			return {
				construct: function() {
					return new TableSave();
				}
			};
		})());
	}
);