define(	['models/Logs', 'views/log-detail', 'text!templates/loglist.html', 'Datepicker'],
	function(LogsCollection, LogDeatilView, LoglistTemplate, Datepicker) {

		/**
		 * Show the query result and handle the events
		 *		- search
		 *		- view Detail
		 */
		var Results = Backbone.View.extend({

			isEditable: false,
			
			detail: null,
			
			el: $('#results')
			
			, collection: new LogsCollection({
				// url: '/data/query.json'
				url: '/data/latest.json'
			})
				
			, events: {
				   "click .table tr": 	"openDetail"
				 , "click #dosearch": 	"doSearch"
				 , "click .next": 		"doNextPage"
				 , "click .previous":	"doPreviousPage"
			}
    
			// Initialize the roaster and connect the roaster to the Socket.
			, initialize: function initialize() {
				var that = this;
				
				$('#dosearch').on('click', function(){ 
					that.doSearch();
				});
				
				
				that.collection.url = '/data/latest.json?hours=24'
				that.collection.fetch(
					{success: function(){
						that.render();
						$('#dosearch').click();
					}}
				);
				
			}
			
			, render: function render(){
				var that = this;
				that.$el.html(
		        	_.template(LoglistTemplate)(that.collection)
		        ); 
			}
			
			, openDetail: function(evt){
				var that = this;
				$('#modalbay').append('<div id="modal" class="modal" tabindex="-1"  data-backdrop="static" data-keyboard="false" data-toggle="modal"></div>');
				if(that.detail){
					// do not produce dangling objects
				//	that.detail = null;
				}
				that.detail = new LogDeatilView({
					id: evt.target.parentElement.id
				});	
				
				$modal = $('#modal');
				$modal.modal();
			}
			
			, doSearch: function(evt){
				var that = this;
				var q = {};
				$('[data-search]').each(function(idx, elm){
					if( elm.value && elm.value.length > 0){
						q[ elm.name ] = elm.value;
					}
				});
				
				// get Date
				var slider = $("#dateSlider");
				if(slider){
					console.log(slider);
				// var dateValues = slider.dateRangeSlider("values");
				//console.log(dateValues.min.toString() + " " + dateValues.max.toString());
				//q.dateFrom = dateValues.min;
				//q.dateTo = dateValues.max;
				}
				
				q.pager = {
					page: that.collection.pager.current || 1
				}
					
				if(q.any && q.any.length > 0){
					q = {q: q.any}
				}
				
				that.collection.url = '/data/query.json?q='+ JSON.stringify(q);
				that.collection.fetch(
					{success: function(){
						that.render();
					}}
				);
			}
			
			, doNextPage: function(evt){
				this.collection.pager.current = this.collection.pager.current +1;
				this.doSearch();
			}
			
			, doPreviousPage: function(evt){
				this.collection.pager.current = this.collection.pager.current -1;
				this.doSearch();
			}
		});
		
		return Results;
	}
);