[{isys_group name="tom.popup.qcw"}]
	<div id="popup-qcw">
        <div class="popup-header-ng">
            <h1>[{isys type="lang" ident="LC__MODULE__QCW__POPUP__HEADER"}]</h1>
            <button type="button" class="btn btn-secondary popup-closer ml-auto" title="[{isys type="lang" ident="LC__POPUP__CLOSE"}]" data-tooltip="1">
                <img alt="close" src="[{$dir_images}]axialis/user-interface/window-control-close.svg" />
            </button>
        </div>

		<div class="popup-content">
			<div class="container fl" style="width:49%;">
				<h3 class="bg-neutral-200 p5 border m5">[{isys type="lang" ident="LC__MODULE__QCW__SAVE_CURRENT_PROFILE"}]</h3>

				<div class="m5">
					<p>[{isys type="lang" ident="LC__MODULE__QCW__EXPORT_DESCRIPTION"}]</p>
					[{isys type="f_text" name="C__MODULE__QCW__CONFIG_TITLE"}]
					<button id="C__MODULE__QCW__SAVE_CONFIG" class="btn">
						<img src="[{$dir_images}]axialis/basic/symbol-ok.svg" />
						<span>[{isys type="lang" ident="LC__UNIVERSAL__BUTTON_SAVE"}]</span>
					</button>
				</div>
			</div>

			<div class="container fr" style="width:49%;">
				<h3 class="bg-neutral-200 p5 border m5">[{isys type="lang" ident="LC__MODULE__QCW__RESET"}]</h3>

				<div class="m5">
					<p>[{isys type="lang" ident="LC__MODULE__QCW__RESET_DESCRIPTION"}]</p>
					<button class="btn mt10" id="C__MODULE__QCW__RESET_CONFIG">
						<img src="[{$dir_images}]axialis/basic/button-remove.svg" />
						<span>[{isys type="lang" ident="LC__MODULE__QCW__BUTTON_RESET"}]</span>
					</button>
				</div>
			</div>

			<br class="cb" />
			<hr class="mt10 mb10" />

			<div class="container">
				<h3 class="bg-neutral-200 p5 border m5">[{isys type="lang" ident="LC__MODULE__QCW__ADD_PROFILES"}]</h3>

				<div class="p5">
					<p>[{isys type="lang" ident="LC__MODULE__QCW__IMPORT_DESCRIPTION"}]</p>

					<div class="mt10 mb10" id="qcw-profile-upload">
						<!-- Will be handled by JS -->
					</div>

					<table id="profile-table" class="mainTable mt15 border">
						<thead>
						<tr>
							<th>[{isys type="lang" ident="LC__MODULE__QCW__FILE"}]</th>
							<th>[{isys type="lang" ident="LC__MODULE__QCW__ACTIONS"}]</th>
						</tr>
						</thead>
						<tbody>
							<!-- Will be handled by JS -->
						</tbody>
					</table>

					<button id="C__MODULE__QCW__LOAD_CONFIG" class="btn mt15">
						<img src="[{$dir_images}]icons/silk/arrow_right.png" class="mr5" />
						<span>[{isys type="lang" ident="LC__MODULE__QCW__PROFILE_POPUP__LOAD_PROFILE"}]</span>
					</button>
				</div>
			</div>
		</div>

		<div class="popup-footer-ng">
			<button type="button" class="btn popup-closer">
				<span>[{isys type="lang" ident="LC__VISUALIZATION_PROFILES__CLOSE_POPUP"}]</span>
			</button>
		</div>
	</div>
	<script type="text/javascript">
		(function () {
			'use strict';

			var $popup       = $('popup-qcw'),
			    $saveButton  = $('C__MODULE__QCW__SAVE_CONFIG'),
			    $resetButton = $('C__MODULE__QCW__RESET_CONFIG'),
			    $loadButton  = $('C__MODULE__QCW__LOAD_CONFIG'),
				$uploadField = $('qcw-profile-upload'),
				$profileTable = $('profile-table').down('tbody'),
				profiles = JSON.parse('[{$profiles|escape:"javascript"}]');

			$popup.on('click', '.popup-closer', function () {
				popup_close();
			});

			// Only submit the form, by click on this buttons.
			$saveButton.on('click', function () {
				var $profileTitleField = $('C__MODULE__QCW__CONFIG_TITLE'),
				    profileTitle = $profileTitleField.getValue();

				if (profileTitle.blank()) {
					$profileTitleField.highlight({startcolor:'#ffdddd', endcolor:'#ffffff', restorecolor:'#ffffff'});
					return;
				}

				$saveButton.disable()
                   .down('img').addClassName('animation-rotate').writeAttribute('src', window.dir_images + 'axialis/user-interface/loading.svg')
		           .next('span').update('[{isys type="lang" ident="LC__UNIVERSAL__LOADING"}]');

				new Ajax.Request('[{$ajax_url}]', {
					parameters: {
						action:       'saveProfile',
						profileTitle: profileTitle
					},
					method:     'post',
					onSuccess:  function (xhr) {
						var json = xhr.responseJSON;

						if (json.success) {
							$profileTitleField.setValue('');
							idoit.Notify.success('[{isys type="lang" ident="LC__INFOBOX__DATA_WAS_SAVED"}]');

							profiles.push(json.data);

							renderTable();

							$profileTable.down('tr[data-filename="' + json.data + '"]').highlight();
						} else {
							idoit.Notify.error(json.message, {sticky:true});
						}
					},
					onComplete: function () {
						$saveButton.enable()
							.down('img').removeClassName('animation-rotate').writeAttribute('src', window.dir_images + 'axialis/basic/symbol-ok.svg')
							.next('span').update('[{isys type="lang" ident="LC__UNIVERSAL__BUTTON_SAVE"}]');
					}
				});
			});

			// Trigger an ajax call for the "reset" button.
			$resetButton.on('click', function () {
				if (confirm('[{isys type="lang" ident="LC__MODULE__QCW__RESET_CONFIRM" p_bHtmlEncode=0}]'))
				{
					$resetButton.disable()
                        .down('img').addClassName('animation-rotate').writeAttribute('src', window.dir_images + 'axialis/user-interface/loading.svg')
			            .next('span').update('[{isys type="lang" ident="LC__UNIVERSAL__LOADING"}]');

					new Ajax.Request('?ajax=1&call=quick_configuration_wizard', {
						parameters: {
							func: 'reset'
						},
						method:     'post',
						onSuccess:  function (xhr) {
							var json = xhr.responseJSON;
							$('loading-object-type').hide();

							if (json.success)
							{
								// If everything went fine, reload the page.
								idoit.Notify.success('[{isys type="lang" ident="LC__MODULE__QCW__RESET_SUCCESS"}]', {sticky: true});

								// This triggers a get request.
								window.location.reload(true);
							}
							else
							{
								// Do some error messaging.
								idoit.Notify.success(json.message, {sticky: true});
							}
						},
						onFailure:  function (xhr) {
							idoit.Notify.success(xhr.responseText, {sticky: true});
						},
						onComplete: function () {
							$resetButton
									.down('img').removeClassName('animation-rotate').writeAttribute('src', window.dir_images + 'axialis/basic/button-remove.svg')
									.next('span').update('[{isys type="lang" ident="LC__MODULE__QCW__BUTTON_RESET"}]');
						}
					});
				}
			});

			$popup.on('click', 'button[data-action="delete-profile"]', function (ev) {
				var $button  = ev.findElement('button'),
				    $tr      = $button.up('tr'),
					filename = $tr.readAttribute('data-filename');

				if (confirm('[{isys type="lang" ident="LC__MODULE__QCW__DELETE_FILE" p_bHtmlEncode=false}]'))
				{
					$button.disable().down('img')
                        .addClassName('animation-rotate')
                        .writeAttribute('src', window.dir_images + 'axialis/user-interface/loading.svg')

					new Ajax.Request('[{$ajax_url}]', {
						parameters: {
							action: 'deleteProfile',
							file:   filename
						},
						method:     'post',
						onSuccess:  function () {
							profiles = profiles.filter(function (profile) {
								return profile !== filename;
							});

							renderTable();
						},
						onComplete: function () {
							// In case of "failure" reset the button.
							$button.enable().down('img')
                                .removeClassName('animation-rotate')
                                .writeAttribute('src', window.dir_images + 'axialis/basic/symbol-cancel.svg');
						}
					});
				}
			});

			// Import profile to the database
            $loadButton.on('click', function () {
                var profiles = $profileTable.select(':checked').invoke('readAttribute', 'value');

                if (profiles.length > 0) {
                    $loadButton
                        .down('img').addClassName('animation-rotate').writeAttribute('src', window.dir_images + 'axialis/user-interface/loading.svg')
                        .next('span').update('[{isys type="lang" ident="LC__UNIVERSAL__LOADING"}]');

                    new Ajax.Request('?ajax=1&call=quick_configuration_wizard', {
                        parameters: {
                            func:          'load_profiles',
                            profile_files: Object.toJSON(profiles)
                        },
                        method:     'post',
                        onSuccess:  function () {
                            window.location.reload(true);
                        },
                        onComplete: function () {
                            $loadButton
                                .down('img').removeClassName('animation-rotate').writeAttribute('src', window.dir_images + 'icons/silk/arrow_right.png')
                                .next('span').update('[{isys type="lang" ident="LC__MODULE__QCW__PROFILE_POPUP__LOAD_PROFILE"}]');
                        }
                    });
                }
            });

			new qq.FileUploader({
				element: $uploadField,
				action: '[{$ajax_url}]',
				multiple: false,
				autoUpload: true,
				sizeLimit: 1048576, // About 1 MB.
				allowedExtensions: ['xml'],
				params:{
					action:'upload'
				},
				onUpload: function (id) {
					var $lastRow = $profileTable.down('tr:last'),
					    cssClass = 'line0';

					if ($lastRow && $lastRow.hasClassName('line0')) {
                        cssClass = 'line1'
					}

					$profileTable
						.insert(new Element('tr', {className: cssClass, 'data-qq-id':id})
							.update(new Element('td', {colspan: 3})
								.update(new Element('img', {src: window.dir_images + 'ajax-loading.gif', className:'animation-rotate'}))
								.insert(new Element('span').update('[{isys type="lang" ident="LC__UNIVERSAL__LOADING"}]'))));

				},
				onComplete: function (id, filename, xhr) {
					if (xhr.success && xhr.data) {
						profiles.push(filename);

						renderTable();

						$profileTable.down('[data-filename="' + filename + '"]').highlight();
					} else {
						idoit.Notify.error(xhr.message || '[{isys type="lang" ident="LC__MODULE__QCW__PROFILE_POPUP__UPLOAD_ERROR"}]', {sticky:true});
					}
				},
				onError: function (id, filename, xhr) {
					var $tr = $profileTable.down('[data-qq-id="' + id + '"]');

					// This does not get triggered reliably...
					idoit.Notify.error(xhr.message || '[{isys type="lang" ident="LC__MODULE__QCW__PROFILE_POPUP__UPLOAD_ERROR"}]', {sticky:true});

					$tr.removeClassName('line0').removeClassName('line1').addClassName('bg-yellow').addClassName('text-yellow').down('td')
					   .update(new Element('img', {src:window.dir_images + 'icons/silk/error.png', className:'vam mr5'}))
					   .insert(new Element('span', {className:'vam'}).update(xhr.message || '[{isys type="lang" ident="LC__MODULE__QCW__PROFILE_POPUP__UPLOAD_ERROR"}]'));
				},
				dragText: '[{isys type="lang" ident="LC_FILEBROWSER__DROP_FILE"}]',
				uploadButtonText: '<img src="' + window.dir_images + 'axialis/basic/zoom.svg" alt="" /><span>[{isys type="lang" ident="LC__UNIVERSAL__FILE_ADD"}]</span>',
				cancelButtonText: '&nbsp;',
				failUploadText: '[{isys type="lang" ident="LC__UNIVERSAL__ERROR"}]'
			});

			function renderTable ()
			{
				var $tr, i;

				$profileTable.update();

				if (!Object.isArray(profiles) || profiles.length === 0)
				{
					return;
				}

				profiles = profiles.uniq();

				for (i in profiles)
				{
					if (! profiles.hasOwnProperty(i))
					{
						continue;
					}

					$tr = new Element('tr', {className:(i%2 ? 'line0' : 'line1'), 'data-filename': profiles[i]})
							.update(new Element('td')
									.update(new Element('label')
											.update(new Element('input', {type:'checkbox', className:'qcw_profile_files', value:profiles[i]}))
											.insert(' ')
											.insert(profiles[i])))
							.insert(new Element('td')
									.update(new Element('a', {className:'btn btn-small', href:'[{$download_link}]' + profiles[i], type:'application/octet-stream', title:'[{isys type="lang" ident="LC__UNIVERSAL__DOWNLOAD_FILE" p_bHtmlEncode=false}]', 'data-tooltip': 1})
											.update(new Element('img', {src:window.dir_images + 'axialis/basic/symbol-download.svg'})))
									.insert(' ') // For an optical space between the two buttons.
									.insert(new Element('button', {className:'btn btn-small', type:'button', 'data-action':'delete-profile', title:'[{isys type="lang" ident="LC__UNIVERSAL__DELETE_FILE" p_bHtmlEncode=false}]', 'data-tooltip': 1})
											.update(new Element('img', {src:window.dir_images + 'axialis/basic/symbol-cancel.svg'}))));

					$profileTable.insert($tr);
				}
			}

			// Render the table.
			renderTable();
		})();
	</script>
[{/isys_group}]
