(function($) {
  var send = new base2.Package(this, {
    name:    "send",
    version: "1.0",
    parent:  dashfly,
    imports: "dashfly",
    exports: "SendManager,EmailSender"
  });
  
  eval(this.imports);
    
  var SendManager = base2.Base.extend({
	  constructor: function(action, application) {
	  	 this.action = action;
  	  	 this.application = application;
  	  	 this.routeManager = this.application.getService(route.RouteManager);
	  },
	  
	  hasDirections: function() {
		  return this.routeManager.getDirections(); 
	  },
	  
	  getRouteDetails: function() {
		  return Array2.map(this.routeManager.getRoute(true),
		  			function(address) { with(address) return {
						lat: GetLatLng().lat(), lng: GetLatLng().lng(),
            accuracy: GetAccuracy(),
						address: GetAddress(), label: GetAddressLabel()
						};
		  			}, this);
	  },
	  
	  send: function(details, block, context) {
		    details.roundTrip = this.routeManager.isRoundTrip();
		    details.addresses = this.getRouteDetails();
			$.ajax({type: 'POST', dataType: 'json',
					url: this.application.getUrls().forAjax(this.action),
					data: {details: JSONstring.make(details)},
					success: function(options,data,status) {
					   if ($.isFunction(block)) {
					       block.call(context, data, data);
					   }
					},
					error: function(xhr,status,err) {
						if ($.isFunction(block)) {
						   block.call(context, err, false);
						}
				    }
				});
	  },
	  
 	  appendDirections: function(message) {
  		 var directions = this.routeManager.getDirections();
  		 
  		 if (directions) with (message) {
  	 		var numOfRoutes = directions.getNumRoutes();
  	  		var additional = this.routeManager.isRoundTrip() ? 1 : 0;
  	  		var addresses = this.routeManager.getRoute();
  	 
			appendLine(); appendLine();
			appendText("Total distance is " + directions.getDistance().html);
			appendLine(" and travel time is "  + directions.getDuration().html);
			
			for(var i = 0; i < numOfRoutes + additional; ++i) {
				var route = directionObj.getRoute(i);
				var address = (i < numOfRoutes) ? addresses[i] :
					this.routeManager.getDestination();
		
				if (route != null) {
				   appendLine();
				   appendText((i===0) ? "Start at: " : "Arrive at: ");
				   appendLine(address.GetActualAddress());
				   appendLine();
				   
				   for(var k = 0; k < route.getNumSteps(); ++k) {
					  var step = route.getStep(k);	
					  appendText(k+1); appendText(". ");
					  appendText(step.getDescriptionHtml());
					  appendText(" - "); appendLine(step.getDistance().html);
				   }
				}
			}

			if (numOfRoutes > 0) {
				var address = this.routeManager.getDestination() || addresses[0];
				appendLine();
				appendLine("Arrive at: " + address.GetActualAddress());
			}
 		 }
  	  }
  });
   
  var EmailSender = SendManager.extend({
	  constructor: function(application) {
	  	 this.base('sendToEmail', application)
	  }
  });
  
  var SendModule = Module.extend({
	  load: function() {
	  	 $(delegate(function() {
	  		this.emailSender = new EmailSender(this.application);
		  	this.addService(this.emailSender);
		  	 
	  		this.sendDialog = $(document.createElement('div'))
	  		  .jqm({toTop: true, modal: false, overlay: 10,
	  			  ajax: this.getUrls().forAction('send'),
	  			  onLoad: delegate(function(hash) {
	  				 this.sendDialog.hide().addClass('ui-dialog modalwin').centerInClient()
	  				 $('.tabContainer > ul', this.sendDialog).tabs({selected: 0});
	  				 this.configureEmailSender();
	  				 this.sendDialog.show();
	  			  }, this)
	  	 	 });
	  		
			 $('#send_trigger').click(delegate(function() {
				  if (this.emailSender.hasDirections()) {
					  this.sendDialog.jqmShow();
				  }
  			 }, this));
			 
	  	     this.sendDialog.appendTo(document.body);
	  	 }, this));
  	  },
  	  
  	  configureEmailSender: function() {
  		  $('#send_email_to', this.sendDialog).Watermark("Enter email recipients here");
  		  this.emailSender.appendDirections($('#send_email_message', this.sendDialog));
  		  $('#send_email_confirm', this.sendDialog).click(delegate(function() {
				$.Watermark.HideAll();
				this.emailSender.send({
					message: $('#send_email_message').val(),
		  			recipients: $('#send_email_to', this.sendDialog).val(),
		  			sendMeCopy: $('#send_email_copy:checked', this.sendDialog).length > 0
					}, delegate(function(result, success) {
						  if (success) this.sendDialog.jqmHide();
						     else alert('Error occured while sending email.');
					   }, this));
			 }, this));
  	  }
  });

  eval(this.exports);
})(jQuery);
