App.Views.ContactPane = Backbone.View.extend({
	template: _.template( $('#contact-directory-template').html() ),
	xViewTemplate: _.template( $('#contact-x-view-template').html() ),
	editTemplate:_.template( $('#contact-edit-template').html() ),
	moreInfoTemplate: _.template( $('#contact-more-info-template').html() ),
	changedProperties: {},

	initialize: function(){
		_.bindAll(this,'render','showExtendedContactView','trackModelChanges','showContactsInGroup');
	},

	render: function(){
		var html = this.template();
		this.$el.empty().append(html);
		this.trigger('render');
		return this;
	},

	events : {
		'click .contact-display':'showExtendedContactView',
		'click .contact-is-selected' : 'toggleContactSelected',
		'click .x-view-close': 'closeExtendedContactView',
		'click .x-contact-edit-button' : 'showEditView',
		'click .close-parent-container' : 'onCloseEditViewPress',
		'click #contact-list-checkbox-toggle': 'toggleSetContactsSelected',
		'click #save-contact-button' : 'saveContact',
		'click .x-contact-more-button' : 'toggleMoreInfo',
		'click .x-contact-more':'toggleMoreInfo',
		'click .keyval-select-button':'togglePrimaryValue',
		'click .edit-add-entry-control':'showNextEntryControl',
		'click .image-upload-button' : 'showUploadDialog',
		'click .x-contact-delete-button' : 'deleteContact',
		'change .model-mutator' : 'trackModelChanges'
	},

	showContactsInGroup: function(e){
		var $btn,id,group,slctr;

		$btn  = $(e.target);
		id    = $btn.data('group-id');
		group = App.groups.get( id );
		slctr = '.group-'+id;

		this.$el.find('.contact-display').show().not( slctr ).hide();
		$('#global-search')
	},

	deleteContact : function(e){
		var cid, model;

		cid = $(e.target).data('cid');
		model = App.contacts.get(cid);
		model.destroy();
	},

	showUploadDialog : function(e){
		var view, upload;
		view = this;

		upload = $('#image-upload-dialog').dialog({
			modal:true,
			buttons: {
				upload: function(){
					var form, xhr;

					form = $('#imageupload').ajaxSubmit({
						url: App.baseUrl + '/inbox/photo',
                                                cache:false,
                                                processData:false,
						dataType:"json",
                                                type:'POST'
					});
					xhr = form.data('jqxhr');
					xhr.done(function(data){
						if(typeof data === 'string'){
							data = $.parseJSON(data);
						}
                        view._setUserPhoto(data.filename);
					});
					/*
					var image = new FormData( $('#imageupload')[0] );
					$.ajax({
						url: App.baseUrl + '/inbox/photo',
						data:image,
						contentType: false,
						cache:false,
						processData:false,
						type:'POST'
					}).done(function(data){
						console.log(data);
						view._setUserPhoto(data.filename);
					}).fail(function(jqhxr,status,text){
						
					})
					*/
					$(this).dialog("close");
				},
				cancel: function(){
					$(this).dialog('close');
				}
			}
		});

		upload.dialog("open");
	},

	_setUserPhoto:function(filename){
		var input, button, url;

		button = this.$el.find('.image-upload-button');
		input  = this.$el.find('input[name="UserPhoto"]');
		url    = App.baseUrl + '/inbox/photo/' + filename;

		console.log(url);

		button.prop('src',url);
		input.val(filename);
		input.trigger('change');
	},

	trackModelChanges: function(e){
		var prop, value, contact;

		prop    = $(e.target).prop('name');
		value   = $(e.target).val();
		contact = App.contacts.get( this.$el.find('#current-contact-cid').val() );
		
		if( contact.has(prop) ){
			
			this.changedProperties[prop] = {
				newValue: value, 
				oldValue: contact.get( prop )
			};
		}
		console.log(this.changedProperties);
	},

	setPropertyType: function(e){
		var $item, $ctrl, ctrlClass, $lbl, $input, currentInputValue;

		e.preventDefault();
		e.stopPropagation();

		$item  = $(e.target);
		/*
		ctrlClass = $item.data('property-name');
		$ctrl  = this.$el.find( '.' + ctrlClass );
		$lbl   = $item.data('control');
		$input = $lbl.siblings('input.model-mutator');

		// close the menu
		$item.parents('ul').first().hide();

		// if the value selected is the same as the current control, bail.
		if( $input.prop('id') == ctrlClass ){
			return;
		}

		// retain the current value in the input element
		currentInputValue = $input.val();
		$input.val('');

		// hide the current phone type
		$('.phone-control-label.'+ $lbl.prop('for') ).addClass('hide');

		$ctrl.remove();

		if( $ctrl.hasClass('hide') ){
			$ctrl.removeClass
		}
		*/

		$item
			.parents('ul')
			.first()
			.hide()
			.data('control')
			.html($item.text()+"&emsp;<i class='icon-sort_down_fill'></i>")
			.removeClass('active')
			.siblings( 'input[type="tel"]')
			.prop('placeholder',$item.text());
		

	},

	showPropertyTypeMenu: function(e){

		$('.property-type-control').removeClass('active');

		var $btn   = $(e.target).addClass('active'),
			$menu  = $btn.parent().siblings('ul').first(),
			height = parseInt( $btn.css('height') ),
			attr   = { 
				top: ($btn.position().top+height),
				width: (($btn.outerWidth()-2)+'px')
			}

		if( $menu.is(':visible') ){
			$btn.removeClass('active');
			$menu.hide();
		} else {
			$menu.css(attr).show().data('control',$btn);
		}
	
	},

	showNextEntryControl:function(e){
		$(e.target).parents('.entry-control-label').siblings('div:not(:visible)').first().removeClass('hide');
	},

	togglePrimaryValue:function(e){
		var $btn,$ctrl;
		
		$btn  = $(e.target);
		$ctrl = this.$el.find('input[name="'+$btn.data('primary-name')+'"]');
		
		$ctrl.val( $btn.data('primary-key') ).change();
		$btn.closest('td').find('.keyval-select-button').removeClass('toggle-state-on').addClass('toggle-state-off');
		$btn.removeClass('toggle-state-off').addClass('toggle-state-on');
		
	},

	toggleContactSelected: function(e){
		var n, $row;

		if( !$(e.target).hasClass('contact-is-selected') ){
			return;
		}

		n = $('.contact-is-selected:checked').length;
		$row = ( (e.target.tagName.toLowerCase()==='tr')? $(e.target) : $(e.target).closest('tr') );

		if(n===0){
			this.trigger('select-none');
			
		} else if(n===1){
			this.trigger('select-single');
			
		} else if(n > 1){
			this.trigger('select-multiple');
		}

		if(e.target.checked){
            $row.addClass('active');
        } else {
            $row.removeClass('active');
        }
	},

	toggleMoreInfo: function(e){
		var $row,cid,json,html;

		$row = $(e.target).closest('tr');
		cid  = $row.data('contact-id');
		$inf = $('.x-contact-more-info.'+cid);
		if($inf.length > 0){
			$inf.remove();
			$row.find('div[class^="x-contact-more"]').removeClass('less').addClass('more');
			$row.find('td').css('border-bottom','1px solid #dedede');
		} else {
			model = App.contacts.get(cid)
			json = model.toJSON();
			json.cid = cid;
			json.formattedDOB = model.getFormattedDob();
			html = this.moreInfoTemplate(json);
			$row.after(html).prev()[0].scrollIntoView();
			$row.find('td').css('border','none');
			$row.next().find('td').css('border-top','none');
			$row.find('div[class^="x-contact-more"]').removeClass('more').addClass('less');
		}
	},

	showExtendedContactView:function(e){
		var $row = ( (e.target.tagName.toLowerCase()==='tr')? $(e.target) : $(e.target).closest('tr') ),
			cid  = $row.data('contact-id'),
			mod  = this.collection.get(cid),
			json = mod.toJSON(),
			html, prev;

		if( $(e.target).hasClass('contact-is-selected') ){
			return;
		}

		html = this.xViewTemplate({model:mod});
		prev = $row.after( html ).hide().prev();

		// Set the checkbox state to be identical
		if( $row.find('input[type="checkbox"]').prop('checked') ){
			$row.removeClass('active').find('input[type="checkbox"]').prop('checked',false);
			$row.next().find('input[type="checkbox"]').prop('checked',true);
		}

		if(prev.length){
			prev[0].scrollIntoView();
		}
	},

	closeExtendedContactView: function(e){
		var $row,cid,chkd;

		$row = $(e.target).parents('tr');
		cid  = $row.data('contact-id');
		chkd = $row.find('input[type="checkbox"]').prop('checked');

		$row.prev().show();
		$row.siblings('.x-contact-more-info.'+cid).remove();
		if(chkd){
			$row
				.prev()
				.addClass('active')
				.find('input[type="checkbox"]')
				.prop('checked',chkd);
		}
		
		$row.remove();
	},

	showEditView: function(e,mod){
		var $row, cid, mod, json, html, info, view;

		if(!mod){
			if(e){

				$row  = $(e.target).parents('tr');
				cid   = $row.data('contact-id');
				mod   = this.collection.get(cid);
				
				if($row.hasClass('contact-display-extended')){
					$row.remove();
				}
				
			} else {
				mod = new App.Models.Contact();
				this.collection.add( mod );
			}
		}

		// close the more info box if open
		this.$el.find('table#contacts-list tbody tr').show().not('.contact-display').remove();
		
		view = this;
		this.modal = $('#contact-dialog-confirm').dialog({
			resizable: false,
			height:140,
			modal:true,
			autoOpen:false,
			appendTo: '#contacts-directory',
			minHeight: 160,
			buttons : [
				{
					text  : 'Save',
					click : function() {
						view.saveContact();
					}
				},
				{
					text  : 'Cancel',
					click : function() {
						var atrs,model;
						model = $(this).dialog("option","contact");

						if(model.isNew()){
							App.contacts.remove(model);
						} else {
							atrs  = $(this).dialog("option","orig-attributes");
							model.set( atrs );
							view.changedProperties = {};
							$(this).dialog("close");
							view.closeEditView();
						}
					}
				}
			]
		});
		

		html = this.editTemplate({model:mod});

		this.$el.find('table#contacts-list>thead').after(html).hide();
		this.$el.find('tbody')[0].scrollIntoView();
		this.$el.find('tr.contact-display').hide();
		this.$el.find('#edit-contact-pane-close-button').data('contact-orig-attributes', _.clone(mod.attributes) );
	},

	closeEditView:function(e){
		var cid, row, mod;

		cid = this.$el.find('#current-contact-cid').val(),
		row = this.$el.find('tr[data-contact-id="'+cid+'"]');
		mod = this.collection.get(cid);

		this.$el.find('thead').show();
		this.$el.find('tr.contact-display').show();
		this.$el.find('.editor-row').remove();

		if(mod.isNew()){
			row.remove();
			this.collection.remove(mod);
		} else {
			row.click();			
		}
		
		if(row.prev().length){
			row.prev()[0].scrollIntoView();
		}
	},

	onCloseEditViewPress : function(e){
		var cid, chgd, keys, mod, atrs;

		cid  = this.$el.find('#current-contact-cid').val();
		mod  = this.collection.get(cid);
		keys = _.keys(this.changedProperties);
		atrs = {};
		chgd = false;
		
		console.log(this.changedProperties);
		for(var i = 0; i < keys.length; i++){

			var prop = this.changedProperties[keys[i]];
			console.log(prop);
			if(prop.oldValue != prop.newValue){
				chgd = true;
				atrs[keys[i]] = prop.oldValue;
			}
		}

		if(chgd===false){
			this.closeEditView();
		} else {
			this.modal.dialog( "open" );
			this.modal.dialog( "option", "orig-attributes",  atrs );
			this.modal.dialog( "option", "contact", mod);
		}
	},

	addContact : function(e){
		this.$editContainer = new App.Views.EditContact({
			model : new App.Models.Contact({}),
			$container : $('#contacts-list')
		}).render();
	},

	saveContact: function(e){
		var cid, contact, formval, sCallback, eCallback,success = false;

		cid = this.$el.find('#current-contact-cid').val();
		contact = this.collection.get(cid);
		newprop = {};

		sCallback = function(model,response,options){
			if(response.error){
				App.alert(response.error.text);
				model.set( model.previousAttributes() );
			}
			App.contactsChrome.groupsBar.activateDefault();
			App.contactsChrome.directory.render();
		};

		eCallback = function(model,response,options){
			App.contactsChrome.groupsBar.activateDefault();
			App.contactsChrome.directory.render();
			App.alert(response.text);
		}

		this.$el.find('form input, form textarea').each(function(i,ctrl){
			
			var prop = $(ctrl).prop('name'), 
				type = $(ctrl).prop('type').toLowerCase(), 
				val  = $(ctrl).val();

			// ensure prop and val have values
			if(prop && val){
			val = val.trim();
				// if the property in the contact does not differ from what we're inputing, ignore
				if( !contact.get(prop) || ( contact.get(prop) != val ) ){

					// check the type so that we can create additional tests based on type
					switch(type){
						case 'radio':
						case 'checkbox':

							// do not try to set if the element is not checked
							if( $(ctrl).prop('checked') ){
								
								newprop[prop] = val;
							}
							break;
						default:
							newprop[prop] = val;
					}
				}				
			}			
		});

		if(_.keys(newprop).length){
			newprop.id = contact.id;
			success = contact.save(newprop,{error:eCallback,success:sCallback,wait:true,patch:true});
			if(success===false){
				App.alert(contact.validationError);
			}
		} else {
			App.alert("No changes detected! Canceling save.",'alert-info');
			if(contact.isNew()){
				contact.destroy();
			}
			App.contactsChrome.groupsBar.activateDefault();
			this.render();
		}
		newprop = {};
	},

	/* UNUSED
	editContact : function(e){
		var selectedModels = this.collection.filter( function(model){
			return model.get('isSelected')
		});

		$('.contact-is-selected:checked').each(function(){
			var idString = 'contact-checkbox-'+ selectedModels[0].get('id');
			if(this.id === idString){
				$(this).parents('tbody').hide();
			} else {
				$(this).click();
			}
		});

		if(selectedModels.length){
			this.$editContainer = new App.Views.EditContact({
				model: selectedModels[0],
				$container:$('#contacts-list')
			}).render();
		}
	},
	*/

	sortCollection : function(e){
		e.preventDefault();
		var item = $(e.target);

		item.parents('ul').find('a').removeClass('active');
		item.addClass('active');
		this.collection.sortProperty = $(e.target).data('sort-property');
		App.contacts.sort();
	},

	toggleSetContactsSelected: function(e){

		if(e.target.checked){
			this.$el.find('.contact-list-checkbox > input[type="checkbox"]').prop('checked',e.target.checked);
			this.$el.find('#contacts-list tbody tr.contact-display').removeClass('active').addClass('active');
            
		} else {
			this.$el.find('.contact-list-checkbox > input[type="checkbox"]').prop('checked',e.target.checked);
			this.$el.find('#contacts-list tbody tr.contact-display').removeClass('active');
            
		}
	}
});

