IssueView = function(store) {
	this.store = store;
	this.el = Ext.get('editForm');
	this.emptyIssue = {
		id: -1,
		summary: '',
		status: 2,
		businessPoints: 100,
		storyPoints: 5,
		description: ''
	};
	
	this._fields = "summary,status,description,businessPoints,storyPoints".split(',');
	this._allFields = "id,summary,status,description,businessPoints,storyPoints".split(',');
	
	// IssueView.superclass.constructor.call(this, arguments);
};

IssueView.prototype = {
	
	cancel: function() {
		this._hide();
	},
	

	edit: function(issueId) {
		this._fillFormWithData(this.store.getIssueById(issueId));
	},
	
	editNew: function() {
		this.emptyIssue.project = this.store.getProjectName();
		// this.emptyIssue.milestone = this.store.getMilestone();
		this._fillFormWithData(this.emptyIssue);
	},
	
	save: function() {
		var issueId = document.getElementById('editForm_id').value;
		var issue = {
			id: issueId,
			project: this.store.getProjectName(),
			type: 'issue'
		};
		if (issueId == -1) {
			issue.id = this.store.generateId();
		} else {
			var originalIssue = this.store.getIssueById(issueId);
			issue._id = originalIssue._id;
			issue._rev = originalIssue._rev;
		}
		each(this._fields, function(key) {
			issue[key] = document.getElementById('editForm_' + key).value;
		});
		issue = this.store._postProcessFields(issue);
		
		if (issueId == -1) {
			this.store.save(issue, this._hide);
		} else {
			this.store.update(issue, this._hide);
		}
	},
	
	_hide: function() {
		hideDialog('editForm');
	},
	
	_fillFormWithData: function(issue) {
		each(this._allFields, function(key) {
			var value = issue[key];
			document.getElementById('editForm_' + key).value = value;
		});
		showDialog('editForm');
		var field = (issue.id == -1) ? 'editForm_summary' : 'editForm_status';
		document.getElementById(field).select();
		document.getElementById(field).focus();
	}
};

var issuesView = new IssueView(couchStore);
var fnEdit = function(issueId) {
	if (issueId == -1) {
		issuesView.editNew();
	} else {
		issuesView.edit(issueId);
	}
};

var saveEdits = issuesView.save.createDelegate(issuesView);
var cancelEdits = issuesView.cancel.createDelegate(issuesView);
