App.Views.EditContact = Backbone.View.extend({
	template: _.template( $('#edit-contact-template').html() ),
	$container: null,
	tagName: 'tbody',
	_hashCode: 0,
	_chgDialog: $('#prompt-for-save-contact-changes').dialog({
		resizeable: false,
		dialogClass: "no-close",
		height: 181,
		modal: true,
		position: {my:'center',at:'center',of:'body'},
		buttons: {
			"Yes" : function(){ 
				var _view = $(this).dialog("option","_view");
				$('.ui-dialog-overlay').hide();
				$(this).dialog("close");
				_view.save();
			},

			"No"  : function(){ 
				var tbody = $('#contacts-list tbody.contact-edit-form'),
					_view = $(this).dialog("option","_view");
				$('.ui-dialog-overlay').hide();
				_view.remove(true);
				$(this).dialog("close");
			}
		}
	}),

	events: {
		'click #save-contact-button' : 'save',
		'click #edit-contact-pane-close-button':'remove'
	},

	initialize: function(options){
		_.bindAll(this,'render','insert','remove','submit');
		this.listenTo(this.model,'change',this.render);
		this._chgDialog.dialog("close");
		this.$container = options.$container;
		this.insert();
	},

	render: function(){
		var hashString = '', form;

		this.$el.html( this.template( this.model.toJSON() ) );
		this.$el.addClass('contact-edit-form');
		this._hashCode = this._getHashCode();
	},

	insert: function(){
		this.$el.insertAfter( this.$container.find('thead') );
	},

	remove : function(override){
		var hashCode = this._getHashCode();
		
		if(override===true|| (this._hashCode === hashCode)){
			this.$el.remove();
			this.stopListening();
			return this;
		} else {
			$('.ui-dialog-overlay').show();
			this._chgDialog.dialog('option','_view',this);
			this._chgDialog.dialog('open');
		}
	},

	submit : function(){},

	save: function(e){

		if(e){ e.preventDefault(); }

		var $form = this.$el.find('form'),
			attrs = {};

		if(!$form){
			console.error('ERROR: No form element found!');
			return false;
		}

		_.each($form.serializeArray(),function(attr){
			attrs[attr.name] = _.escape(attr.value);
		});
		
		console.dir(attrs);

		if(this.model.id===null){
			if(this.model.isValid()){
				App.Contacts.add(this.model);
			} else {
				console.warn("Contact does not pass validation: "+this.model.validationError,this.model);
			}
			
		} else {
			$('#contact-checkbox-'+this.model.id).parents('tbody').show();
		}

		this.model.set(attrs);
		this.remove(true);
	},

	_getHashCode: function(){
		var hashString = '', 
			hashCode = 0,
			form     = this.$el.find('form').serializeArray();

		_.each(form,function(elem){
			hashString += elem.value
		});

		if(hashString.length === 0) return hashCode;
		for( var i = 0; i < hashString.length; i++)
		{
			var c = hashString.charCodeAt(i);
			hashCode = ((hashCode<<5)-hashCode)+c;
			hashCode = hashCode & hashCode;
		}
		return hashCode;
	}
});