/**
 * Simple controller to manage our views and models
 * 
 */
define([ 'jquery', 'underscore', 'backbone', 'marionette',
		'app/entities/entities', 'app/views/grid/grid','app/views/header/header' ], function($, _,
		Backbone, Marionette, ajaxEntities, Grid,HeaderView) {

	var SearchAppController = Backbone.Marionette.Controller.extend({
		initialize : function(options) {
			this.entities = new ajaxEntities();
			this.header = options.header;
			this.content = options.content;
			
			var headerView = new HeaderView();
			this.listenTo(headerView,'searchapp:search',this.search);
			
			this.header.show(headerView);
		},

		/**
		 * Search end point to call search from the controller.
		 */
		search : function(data) {
			var self = this;
			var defer = $.Deferred();
			var searchCall = this.entities.search(data);

			$.when(searchCall).done(function(jsonRes) {
				self.showGridResuls(jsonRes);
				defer.resolve();
			}).fail(function() {
				defer.reject();
			});
			return defer.promise();
		},

		/**
		 * After results come back, we want to show the table data
		 */
		showGridResuls : function(data) {			
			var headers = [];
			for(var key in data.documents[0].fields){
				headers.push(data.documents[0].fields[key].name);
			}
			
			var coll = new Backbone.Collection();
			
			for(var i in data.documents){
				var fields = data.documents[i].fields;
				coll.add(new Backbone.Model({fields:fields}));
			}

			var gridView = new Grid({
				collection : coll,
				headers : headers
			});
			this.content.show(gridView);
		}

	});

	return SearchAppController;
});
@@ -1112,24 +1112,75 @@
 (data) %7B%09%09%09%0A
+%09%09%09if(data.documents && data.documents.length%3E0)%7B%0A%09
 %09%09%09var heade
@@ -1188,16 +1188,17 @@
 s = %5B%5D;%0A
+%09
 %09%09%09for(v
@@ -1234,24 +1234,25 @@
 ields)%7B%0A%09%09%09%09
+%09
 headers.push
@@ -1293,16 +1293,17 @@
 e);%0A
+%09
 %09%09%09%7D%0A%09%09%09
 %0A%09%09%09
@@ -1294,25 +1294,27 @@
 );%0A%09%09%09%09%7D%0A%09%09%09
-%0A
+%09%0A%09
 %09%09%09var coll 
@@ -1345,17 +1345,19 @@
 n();%0A%09%09%09
-%0A
+%09%0A%09
 %09%09%09for(v
@@ -1377,24 +1377,25 @@
 documents)%7B%0A
+%09
 %09%09%09%09var fiel
@@ -1425,24 +1425,25 @@
 fields;%0A%09%09%09%09
+%09
 coll.add(new
@@ -1480,19 +1480,21 @@
 %7D));%0A%09%09%09
+%09
 %7D%0A%0A
+%09
 %09%09%09var g
@@ -1514,16 +1514,17 @@
  Grid(%7B%0A
+%09
 %09%09%09%09coll
@@ -1538,24 +1538,25 @@
 : coll,%0A%09%09%09%09
+%09
 headers : he
@@ -1564,20 +1564,22 @@
 ders%0A%09%09%09
+%09
 %7D);%0A
+%09
 %09%09%09this.
@@ -1602,16 +1602,21 @@
 dView);%0A
+%09%09%09%7D%0A
 %09%09%7D%0A%0A%09%7D)

fix bug when 0 results returned