/**
 * Create a dialog to generate documents.
 *
 * The .orderUiDocumentGenerator() creates a dialog which enables the user to generate the packaging slip and/or invoice documents for an order. Also the status of the order can be updated to Ready for shipping, Dispatched and Invoiced. After creating the documents the printview automatically can be shown in a new tab.
 *
 * ### Examples
 * Binds the orderUiDocumentGenerator()-Dialog to an anonymous div and calls the open-method of the widget via on-click event attached to a page element.
 *
 * JavaScript:
 *
 *
 *     <script>
 *     	jQuery.ready({
 *     				plugin: [ 'de_epages.order.ui.documentGenerator' ],
 *     				DOM:    true
 *     			}, function($){
 *     				var documentWidget = de_epages('<div>').orderUiDocumentGenerator();
 *     				$("#generateDocuments").on("click",function(){
 *     					de_epages(documentWidget).orderUiDocumentGenerator('open');
 *     				});
 *     			});
 *     </script>
 *
 * Opens the orderUiDocumentGenerator() with use of the option to commit a list of order id's to generate the chosen documents for all the orders in the list. The list consists of orders which have been chosen by checkboxes.
 *
 * JavaScript:
 *
 *
 *     <script>
 *     jq(this.form)
 *     			.find('input:checkbox:checked[name=ListObjectID]')
 *     			.each(function(){
 *     				selected.push( jq(this).val() );
 *     			});
 *
 *     		if( !selected.length ){
 *     			return false;
 *     		}
 *     		jQuery.ready({
 *     				plugin: [ 'de_epages.order.ui.documentGenerator' ],
 *     				DOM:    true
 *     			}, function($){
 *     				var documentWidget = de_epages('<div>').orderUiDocumentGenerator({
 *     					orders    :   selected
 *     				});
 *     				de_epages(documentWidget).orderUiDocumentGenerator('open');
 *     			});
 *     </script>
 *
 *
 * @class jQuery.ui.orderUiDocumentGenerator
 * @extends jQuery.widget
 *
 * @uses jQuery.tmpl
 * @uses jQuery.metaparse
 * @uses jQuery.ui.widget
 * @uses jQuery.ui.draggable
 * @uses ep
 * @uses ep.dict
 * @uses ep.ui.input
 * @uses ep.ui.dialog
 * @uses ep.ajax
 * @uses ep.ui.datepicker
 * @uses jQuery.i18n
 * @uses de_epages.order.ui.documentGenerator
 * @since 6.15.0
 */

/**
 * @cfg {Array} [orders] A list of objectIds of orders for which documents have to be created
 */

/**
 * See `jQuery.ui.orderUiDocumentGenerator` for details.
 *
 * @param {Object} [options] A map of additional options to pass to the method.
 * @param {Array} [orders] A list of objectIds of orders for which documents have to be created
 *
 * @method orderUiDocumentGenerator
 * @member jQuery
 *
 * @since 6.15.0
 */

/*
 * @copyright		© Copyright 2006-2011, epages GmbH, All Rights Reserved.
 *
 * @module			de_epages.order.ui.documentGenerator
 */

define( "de_epages/order/ui/documentgenerator", [
	"jquery",
	"ep",
	"de_epages",
	"$dict!../dictionary",
	"$tmpl!./documentgenerator",

	"jquery/metaparse",
	"jquery/ui/widget",
	"jquery/ui/draggable",
	"jquery/i18n",
	"ep/dict",
	"ep/ui/input",
	"ep/ui/dialog",
	"ep/ajax",
	"ep/ui/datepicker"
], function ( $, ep, de_epages, presentationDict, tmplDocumentGenerator ) {

/*
 * @dictionary		de_epages.order.dictionary
 *
 * @translation		{SetStatusInvoiced}
 *					{DeliveryDate}
 *					{SetStatusDispatched}
 *					{SelectedOrders}
 *					{Invoice}
 *					{SetStatusReadyForShipping}
 *					{PackingSlip}
 *					{CreateDocuments}
 *					{Documents}
 *					{InvoicePackingSlipDate}
 *					{CreateAndPrintDocuments}
 *					{WaitForGenerateDocuments}
 */

/*
 * @dictionary		ep.dict
 *
 * @translation		{Create}
 *					{Cancel}
 *					{Action}
 */

	$.widget( 'ui.orderUiDocumentGenerator', {

		options: {
			orders    :   undefined,
			callback  :   undefined
		},

		_create: function () {
			this._createDialog();
		},

		_createDialog: function () {
			var self = this;

			$.extend(
				self,
				tmplDocumentGenerator()
					.dictParse(presentationDict, true)
					.tmplItem('elements')
			);

			self.dialog
				.find('.ep-js')
				.metaparse();

			if (this.options.orders !== undefined) {
				self.dialog
					.find('h4:first')
					.text( (presentationDict.translate('{SelectedOrders}') + ": " + this.options.orders.length) );
			}

			self.dialog
				.uiDialog({
					title: presentationDict.translate('{CreateAndPrintDocuments}'),
					modal: true,
					width: '400',
					height: 'auto',
					buttons: {
						'Generate' : {
							text: presentationDict.translate('{Create}'),
							id: 'Generate',
							click: function () {
								self._generate();
							}
						},
						'Close': {
							text: presentationDict.translate('{Cancel}'),
							click: function () {
								self.close();
							}
						}
					},
					autoOpen: false,
					create: function () {
						self._validate()
					}
				});
		},

		_updateOrder: function (readyForShipping,dispatched,invoiced) {
			$("#Check_ReadyForShippingOn").prop("checked",!!readyForShipping).trigger("change");
			$("#Check_DispatchedOn").prop("checked",!!dispatched).trigger("change");
			$("#Check_InvoicedOn").prop("checked",!!invoiced).trigger("change");
		},

		_generate: function () {
			var self = this;

			if (!$("#Generate").hasClass("Disabled")) {
				var create = this.create.prop("checked")?true:false,
					createandprint = this.createAndPrint.prop("checked")?true:false,
					createPackingSlip = this.CreatePackingSlip.prop("checked")?true:false,
					createInvoice = this.CreateInvoice.prop("checked")?true:false,
					createShippingLabel = this.CreateShippingLabel.prop("checked")?true:false,
					packingSlipDate = this.PackingSlipDate.val(),
					deliveryDate = this.DeliveryDate.val(),
					readyForShipping = this.ReadyForShipping.prop("checked")?true:false,
					dispatched = this.Dispatched.prop("checked")?true:false,
					invoiced = this.Invoiced.prop("checked")?true:false,
					objectId = ep.config.objectId;

				ep.ajax({
					dataType: "json",
					// use a synchronous request to avoid pop up blockers when using window.open
					async: false,
					data: {
						'ObjectID' : ep.config.siteId,
						'OrderList': (self.options.orders) ? self.options.orders : [objectId],
						'ChangeAction' : 'JSONGenerateDocuments',
						'Locale' : ep.config.locale,
						'DeliveryDate' : deliveryDate,
						'IssueDate' : packingSlipDate,
						'createInvoice' : createInvoice,
						'createPackingSlip' : createPackingSlip,
						'createShippingLabel' : createShippingLabel,
						'ReadyForShippingOn' : readyForShipping,
						'DispatchedOn' : dispatched,
						'InvoicedOn' : invoiced
					},
					cache: false,
					type: "post",
					traditional: true
				})
				.done(function (data) {
					if(typeof self.options.callback == "function") {
						self.options.callback(data);
					}

					self._updateOrder(readyForShipping, dispatched, invoiced);
					self._printView();

					// Destroy dialog
					self.dialog.remove();
					self.dialog = null;
				});
			}
		},

		_printView: function () {
			var printString,
				printPackingSlips = $("#Documents_PackingSlip").prop("checked") ? 1 : 0,
				printInvoices = $("#Documents_Invoice").prop("checked") ? 1 : 0,
				partOfString = "&PopUp=1&Print=1&PrintPackingSlips="+printPackingSlips+"&PrintInvoices="+printInvoices;
			if(this.options.orders !== undefined && ( this.options.orders.length > 1 || ep.config.siteId == ep.config.objectId ) ) {
				var list = this.options.orders,
					printString="?ViewAction=MBO-ViewPrintMultipleDocuments&ObjectID="+ep.config.objectId+partOfString;
				$.each(list,function (index, value) {
					printString = printString + '&'+'ListObjectID=' + value;
				});
			}
			else{
				printString="?ViewAction=MBO-ViewPrintMultipleDocuments&ObjectID="+ep.config.siteId+partOfString+"&ListObjectID="+ep.config.objectId;
			}
			$("#DocumentGeneratorMessage")
				.removeClass("HideElement")
				.find("a")
				.attr("href", printString);

			if (this.createAndPrint.prop("checked")) {
			  if ( printPackingSlips || printInvoices ) {
			    window.open(printString);
			  }
			}
		},

		_validate: function () {
			 var self = this;
			 $.each([self.CreatePackingSlip, self.CreateInvoice, self.CreateShippingLabel], function (index, value) {
				this.on('change', function () {
					$("#Generate")[(!self.CreatePackingSlip.is(":checked") && !self.CreateInvoice.is(":checked") && !self.CreateShippingLabel.is(":checked"))? 'addClass' : 'removeClass']("Disabled");
				});
			});
			$.each([self.PackingSlipDate, self.DeliveryDate], function (index, value) {
				this.on('change', function () {
					$("#Generate")[(self.PackingSlipDate.val()=="" || self.DeliveryDate.val()=="")? 'addClass' : 'removeClass']("Disabled");
				});

			});
		},

		/**
		 * When the method is called it checks if there is already a dialog created or if the dialog is not defined yet. If not defined, the widget function _create() is called otherwise the dialog only opens as an overlay.
		 *
		 * @method open
		 * @member jQuery.ui.orderUiDocumentGenerator
		 *
		 * @since 6.15.0
		 */
		open: function () {
			var self = this;

			if (self.dialog) {
				self.dialog.uiDialog('open');
			}
			else {
				self._createDialog();
			}

		},

		close: function () {
			var self = this;

			if (self.dialog) {
				self.dialog.uiDialog('close');
			}

		},

		_init: function () {
			var self = this,
				epDate = new ep.Date();

			$.each([self.PackingSlipDate, self.DeliveryDate], function (index, value) {
				this.val(epDate.getFormat('d'));
			});
		},

		destroy: function () {
			this.dialog.remove();

			this._superApply(arguments);
		}
	});

	return de_epages;

});