App.ContactsChrome = Backbone.View.extend({
	buttonBar:null,
	groupsBar:null,
	directory:null,
	draggableOptions: {
		cursor:"move",
		helper:function(e){
			var msgCount  = ($('.contact-is-selected:checked').length || 1),
				container = $('<div class="draggable-helper"></div>');
				countSpan = $('<span>'+msgCount+'</span>');
				// console.log( countSpan.html() )
				return container.append(countSpan);
		},
		stop: function(event, ui){
			
		},

		disabled:false,
		cursorAt: { top: 5, left: 5 },
		appendTo:"#contacts-pane"
	},

	events: {
		'click .sort-contact-dropdown-item':'onMenuItemSortPress',
		'click #add-contact-button':'onAddContactAddPress',
		'click #email-contacts-button' : 'onEmailButtonContactPress',
		'click .x-contact-mail-button' : 'onEmailIconContactPress',
		'click #edit-contacts-button' : 'onEditButtonPress',
		'click #select-contacts-select-all' : 'onSelectAllMenuItemPress',
		'click #select-contacts-select-none' : 'onSelectNoneMenuItemPress',
		'click #x-contact-delete-button' : 'onDeleteContactPress',
		'click #delete-contacts-button' : 'onDeleteContactPress',
		'keyup #search-contact' : 'searchContacts',
		'click #contact-new-group-button' : 'onNewGroupsPress',
		'click .x-contact-print ' : 'printContact',
		'click #more-contacts-export' : 'exportContacts',
		'click #more-contacts-import' : 'importContacts',
		'click #more-contacts-dropdown-button' : 'checkVisOnMenuItems',
		'click .x-contact-share-button' : 'shareContact',
		'click #share-contacts-button' : 'shareContact'
	},
	
	initialize: function(){
		_.bindAll(this,'render','onMenuItemSortPress','bindDraggable','bindDroppable');
	},

	render: function(){
		this.buttonBar = new App.Views.ContactsButtonBar({
			el: $('#contacts-pane .button-bar')
		}).render();

		this.buttonBar.setStateInit();

		this.groupsBar = new App.Views.ContactsGroupFolders({
			el: $('#contacts-pane .vertical-bar'),
			collection: App.groups
		}).render();

		this.directory = new App.Views.ContactPane({
			el: $('#contacts-directory'),
			collection: App.contacts
		}).render();

		App.contacts.on('add remove sort', function(){ App.contactsChrome.directory.render() });

		this.directory
			.bind('select-none',this.buttonBar.setStateInit)
			.bind('select-multiple',this.buttonBar.setStateMulti)
			.bind('select-single',this.buttonBar.setStateSingle)
			.bind('render',this.bindDraggable);

		this.groupsBar
			.bind('group-button-press',this.searchContacts)
			.bind('render',this.bindDroppable);

		this.bindDraggable();
		this.bindDroppable();

		return this;
	},

	checkVisOnMenuItems: function(e){
		var chkd = this.$el.find('.contact-is-selected:checked').length;
		console.log(chkd);
		if(chkd > 0){
			this.$el.find('#more-contacts-move-li').show();
		} else {
			this.$el.find('#more-contacts-move-li').hide();
		}
	},

	exportContacts : function(e){
		var gid,url;
		e.preventDefault();
		e.stopPropagation();

		gid = this.$el.find('.contact-group-button.active').data('group-id');
		url = App.baseUrl + '/mail/contacts/exportcontact?GroupID=' + gid;
		
		window.location.href = url;
	},

	searchContacts : function(e){
		var $ctrl, term, ids, key,field, group;

		key = e.which;
		$ctrl = $('#search-contact');
		term  = $ctrl.val();
		ids   = [];
		group = '.group-'+this.$el.find('.contact-group-button.active').data('group-id');
		field = [
			'UserFirstName',
			'UserLastName',
			'UserEmail'
		];
		
		$('.x-view-close').click();

		if(term.length !== 'undefined'){
			
			var len,idx,contact;
			len = App.contacts.length;

			AT_CONTACT:
			for(idx=0;idx<len;idx++){
				contact = App.contacts.at(idx);
				for(var i = 0; i < field.length; i++){
					var str = contact.get(field[i]);

					if(typeof str === 'string'){
						if(str.toLowerCase().indexOf(term.toLowerCase()) > -1){
							ids.push(contact.id);
							continue AT_CONTACT;
						}
					}
				}
			}
			
			$('.contact-display').hide();

			if(ids.length){

				for(var i=0;i<ids.length;i++){
					$(group+'[data-contact-id='+ids[i]+']').show();
				}
			}
		} else {
			$('.contacts-display'+group).show();
		}


	},

	onEditButtonPress : function(e){
		var cid = $('tr.active').data('contact-id'),
			mod = App.contacts.get(cid);

		this.directory.showEditView(e,mod);
	},

	bindDraggable: function(){
		
		$('.contact-display').draggable(this.draggableOptions);
	},

	bindDroppable: function(){
		
		var view = this;
		$('.contact-group-button[data-user-group="true"]')
			.droppable({
				drop: function(e,ui){

					var $btn,gid,chkd,contacts,ids,groupContacts,eCallback,sCallback;

					// For a batch update we need to fool backbone into performing 
					// a regular POST request. We'll need to send an extra parameter
					// that is not normally a property of the ContactGroup pair

					ids  = []; // container for the contact ids we are assoc with group
					$btn = $(this);
					gid  = $btn.data('group-id'); // get the group id
					chkd = view.$el.find('.contact-is-selected:checked').closest('tr');

					// if there are no .contact-is-selected elems use the ui to retrieve
					contacts = chkd.length? chkd : [ui.draggable[0]];

					
					// set standard callbacks (these should move to something more 
					// universal like App.successCallBack(context)...
					sCallback = function(model,response,options){
						if(response.error){
							App.alert(response.error.text);
						}
						model.destroy();
						if(response && response.length){
							_.each(response,function(model,i){
								var pair = new App.Models.ContactGroup(model);
								App.contactsGroups.add(pair);
							});
						}
						App.contactsChrome.groupsBar.render();
						App.contactsChrome.directory.render();
						$btn.prop('disabled',false);
						// view.bindDroppable();
					};

					eCallback = function(model,response,options){
						App.contactsChrome.groupsBar.render();
						App.alert(response.error.text);
						$btn.prop('disabled',false);
					}

					// populate the ids array with the dragged contact ids
					_.each(contacts,function(contact,i){
						// prevent insert for ids that already exists in group
						if( !$(contact).hasClass("group-"+gid) ){
							ids.push( $(contact).data("contact-id") );
						}
					});

					// Do nothing if there are no ids to send
					if(ids.length > 0){

						// diable the button until a response is received
						$btn.prop('disabled',true);

						// create a new ContactGroup and save it with the 
						// skullduggery property: batchContactIds. This is
						// set simply with a list of comma separated contact
						// ids.
						groupContacts = new App.Models.ContactGroup();
						groupContacts.save({
							batchContactIds: ids.join(','),
							GroupID:gid,
							Account:App.primaryAccount
						} , {
							error: eCallback,
							success: sCallback,
							wait:true
						});
					}
				}
			});
	},

	onSelectAllMenuItemPress : function(e){
		$('.contact-display')
			.removeClass('active')
			.addClass('active')
			.find('.contact-list-checkbox > input[type="checkbox"]')
			.prop('checked',true);
		$('#contact-list-checkbox-toggle').prop('checked',true);
	},

	onSelectNoneMenuItemPress : function(e){
		$('.contact-display')
			.removeClass('active')
			.find('.contact-list-checkbox > input[type="checkbox"]')
			.prop('checked',false);
		$('#contact-list-checkbox-toggle').prop('checked',false);
	},

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

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

	onAddContactAddPress: function(e){
		this.directory.showEditView();
	},

	onEmailButtonContactPress: function(e){
		var cid = $('.contact-is-selected:checked').parents('tr').data('contact-id');
		var cid = $('tr.active').data('contact-id');
			console.log(cid);
		this.emailContact(cid);
	},

	onEmailIconContactPress:function(e){
		var cid = $(e.target).parents('tr').data('contact-id');
		this.emailContact(cid);
	},

	emailContact: function(cid){
		var contact, env;

		contact = App.contacts.get(cid);
		if(contact){
			env = new App.Models.Envelope({
				isNew:true,
				to:[ contact.getPrimaryEmail() ]
			});

			App.envelopes.add( env );
			
			$('#ui-id-1').click();
			App.emailChrome.showComposePane();
			App.emailChrome.composePane.render();
			App.emailChrome.composePane.$el.find('#compose-tab-buttons li:last a').click();
		}
	},
	
	onDeleteContactPress: function(e){
		var r=confirm("Are you sure you want to delete this contact?");
		if (r==true)
		  {
		 
		  }
		else
		  {
				return;
		  }
		$('.contact-is-selected:checked').each(function(i,chkbox){
			var id, model;
			var id = $('tr.active').data('contact-id');
			//id = chkbox.id.match(/c\d+$/);
			if(id){
				model = App.contacts.get(id.toString());
				model.destroy();
			}
		});
	},

	onNewGroupsPress : function(e){
		this.groupsBar.showNewGroupCtrl();
	},

///mail/contacts/import

	importContacts : function(e){
		var $btn, cid, view;

		$btn = $(e.target);
		view = this;

		$('#import-upload-dialog').dialog({
			resizeable: false,
			dialogClass: "no-close",
			height: 181,
			modal: true,
			position: {my:'center',at:'center',of:'body'},
			buttons: {
				Import: function(){

					var form, xhr;

					form = $('#import-upload-dialog-form').ajaxSubmit({
						url: App.baseUrl + '/mail/contacts/import',
						cache:false,
						processData:false,
						type:'POST'
					});

					xhr = form.data('jqxhr');

					xhr.done(function(response){
						// place code to update directory here
						console.log(response);
						if(_.isObject(response) && response.error){
							App.alert(response.error);
						} else if( _.isString(response)){
							App.alert(response);
						} else if( _.isArray(response) ){
							_.each(response,function(c,i){
								var contact;
								contact = new App.Models.Contact(c);
								App.contacts.add(contact);
							});

							view.render();
						}
					});
					
					$(this).dialog('close');
				},
				Cancel: function(){
					$(this).dialog('close');
				}
			}
		});
	},
	printContact: function(e){
		 
	    Popup($('.contact-display-extended').html());

	    function Popup(data) 
	    {
	        var mywindow = window.open('', 'Print Contact', 'height=400,width=600');
	        mywindow.document.write('<html><head><title>Print Contact</title>');
	        /*optional stylesheet*/ //mywindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
	        mywindow.document.write('</head><body >');
	        mywindow.document.write(data);
	        mywindow.document.write('</body></html>');

	        mywindow.print();
	        mywindow.close();

	        return true;
	    }

	},
	
	shareContact: function(e){
		// console.log('foo');
	  	 var contact, env;

			view = this;
			env = new App.Models.Envelope({
				isNew:true
			});

			App.envelopes.add(env);
			
			$('#ui-id-1').click();
			App.emailChrome.showComposePane();
			App.emailChrome.composePane.render();
			App.emailChrome.composePane.$el.find('#compose-tab-buttons li:last a').click();
			 var cid =0;
			
			 $(".contact-display").each(function(){
		       if($(this).css("display")=="none"){
		      
		         cid = $(this).data('contact-id');
 				// console.log(this);
 				// console.log(cid);
		       }
		    });
			  //console.log(cid);
			var  url = App.baseUrl + '/mail/contacts/exportcontact?id=' + cid+'&share=sharecontact';
			
			$.get(url, function( data ) {
	
				var data = $.parseJSON(data);
				console.log(data);
				//console.log(obj[0].SaveDrafts);
				//alert( "Load was performed." );
				if(data.error){
					App.alert(data.error);
				} else {
					//env = this.getActiveEnvelope();
					env.setAttachment(data);
					$('#compose-envelope-attachments-'+env.cid)
						.append(data.filenameOriginal+'&emsp;');
				}
		
			});
	}
});




