define(['mootools', 'jquery'], function ($$, jQuery) {

	var ClnPopups = new Class({
		initialize: function(){
			this.windows_ids = ['seq_popup_action', 'loading_screen', 'error_screen', 'popup_main_screen'];
			if (!document.can_create_events) $('save_link').setStyle('display', 'none');
			if (!document.can_create_events) $('save_view_link').setStyle('display', 'none');
			$('quick_add_event_name').addEvent('keypress', function(event){
				    var event = new Event(event);
				    //event is now the Event class.
				    if (event.key == 'enter') $('save_link').onclick();
				});
			$('quick_add_event_description').addEvent('keypress', function(event){
			    var event = new Event(event);
			    //event is now the Event class.
			    if (event.key == 'enter' && (event.shift || event.control))
			    {
			        event.stop();
			        $('save_link').onclick();
			    }
			});

	        jQuery('#quick_add_event_name').attr("placeholder",lmsg('calendar.defaults.new_name'));

		},
		openQuickPopup: function(cln_event, win_position){
			if (document.event_controller.edit_event_flag) return;
			this.common_event = cln_event;
			$('save_link').onclick = function(e){
	            var event_name = jQuery('#quick_add_event_name').val();

	            if (!event_name) {
	                cla.showMessage(lmsg('calendar.text.name_cannot_be_empty'), "", true);
	                return;
	            }

				document.event_controller.quickAddEnd();
			};
			$('save_view_link').onclick = function(e){
				document.event_controller.quickAddEnd();
			};
			$('delete_link').setStyle('display', 'none');
			this.fillPopupFields(cln_event);
			this.getQuickAddDiv().removeClass('d-none');
			this.getQuickAddDiv().setStyles({ visibility: 'hidden' });
			this.getQuickAddDiv().setStyles({
				left: win_position.x - Math.floor(this.getQuickAddDiv().getCoordinates().width/2),
				top: Math.max(win_position.y-this.getQuickAddDiv().getCoordinates().height + window.getScrollTop(), jQuery('.navbar-fixed-top').height() + 75),
				visibility: ''
			});
			this.showWindow('popup_main_screen');
		},
		fillPopupFields: function(cln_event){
			if (cln_event.seq_id == 0){
				$('ext_link').setProperty('href', "calendar_edit_event.php?id="+cln_event.getId()+'&type=event&start_date='+cln_event.start.serialize()+'&end_date='+cln_event.end.serialize()+'&full_day='+cln_event.full_day);
				$('ext_link').onclick = function() {$('ext_link').href += "&event_name="+encodeURIComponent($('quick_add_event_name').value)+"&calendar_id="+parseInt($('calendars_array').value)+"&event_description="+encodeURIComponent($('quick_add_event_description').value);};
			}else{
				$('ext_link').setProperty('href', "#");
				$('ext_link').onclick = function(){document.event_controller.popups.showSequenceDialog('adv_edit', document.lc['calendar.what_to_edit'] + '?'); return false;};
			}

			$$('.cln_popup_view_details').each(function(el){el.setStyle('display', (cln_event.getId() > 0 || cln_event.type == 'system') ? 'inline-block' : 'none');});
			if (cln_event.seq_id == 0){
				$$('.cln_popup_view_details').each(function(el){el.setProperty('href',
					$defined(cln_event.details_url) ? cln_event.details_url : "calendar_view_event.php?id="+cln_event.getId()+'&type=event');
					el.onclick = null;
				});
			}else{
				$$('.cln_popup_view_details').each(function(el){
					el.setProperty('href', "#");
					el.onclick = function(){document.event_controller.popups.showSequenceDialog('adv_view', document.lc['calendar.what_details'] + '?'); return false;};
				});
			}

			$('quick_add_event_name').setProperty('value', cln_event.getName());
			$('quick_add_event_description').setProperty('value', cln_event.getDescription());

			jQuery(document).ready(function(){
				jQuery('#quick_add_event_name').focus(function(){
					if(jQuery(this).val() === lmsg('calendar.defaults.new_name'))
						jQuery(this).val('');
				});
			});

			var icons = (cln_event.seq_id > 0 ) ? '<img class="mr-1" src="images/chain_part_icon.gif" alt="'+document.lc['calendar.text.chain_part']+'" title="'+document.lc['calendar.text.chain_part']+'"  align="absmiddle">' : '';
			if ( cln_event.is_personal == 0 && cln_event.participant == 1){
				if (cln_event.confirm == 0) var pat_alt = document.lc['calendar.text.invitation_unknown'];
				if (cln_event.confirm == 1) var pat_alt = document.lc['calendar.text.invitation_accepted'];
				if (cln_event.confirm == 2) var pat_alt = document.lc['calendar.text.invitation_rejected'];
				icons = icons + '<img class="mr-1" src="images/confirm_'+cln_event.confirm+'.gif" alt="'+pat_alt+'" title="'+pat_alt+'"  align="absmiddle">';
			}

			$('quick_add_event_time').setHTML(icons + document.lc['calendar.common.time'] + ': '+cln_event.getRange());
			/////////////////////////// REMINDER
			var reminder = cln_event.reminder;
			$('cln_reminder').setStyle('display', 'block');
			$('reminder_setter').setStyle('display', 'none');

			if (cln_event.reminder == '' ){
				$('cln_reminder').setStyle('display', 'none');
				$('reminder_setter').setStyle('display', 'block');
				reminder = cln_event.reminder_default;
				if ($('reminder_default').selectedIndex)
				  reminder = $('reminder_default').value;
			}
			var option = $('cln_reminder').getElement('option[value='+reminder+']');
			$('cln_reminder').selectedIndex = option.index;
			/////////////////////////// REMINDER END

			$('cln_a_bility_'+cln_event.a_bility).checked = true;
			if ($defined(cln_event.confirm)) $('cln_confirm_'+cln_event.confirm).checked = true;

			// select current calendar
			var option = $('calendars_array').getElement('option[value='+cln_event.cln_id+']');
			if (!$defined(option)){
				if ($('default_calendar').selectedIndex){
					option = $('calendars_array').options[$('default_calendar').selectedIndex];
				}else{
					var flag = true;
					for (var index = 0; index <$('calendars_array').options.length; index++)
					{
						el = $('calendars_array').options[index];
						if (flag && el.value > 0){
							option = el;
							flag = false;
						}
					}
				}
			}
			if ($defined(option)) $('calendars_array').selectedIndex = option.index;
			$('calendars_array').onchange();
			/* if ($defined(option) && $defined(option.onclick)) option.onclick(); */

			var is_creator = (cln_event.creator_id == document.session_uid);
			if ( !$defined(cln_event.cln_id) || (document.calendar_perms[129][cln_event.cln_id] == 1) || (is_creator && document.calendar_perms[3][cln_event.cln_id] == 1 ) ) {
				$('quick_add_event_name').removeProperty('disabled');
				$('quick_add_event_description').removeProperty('disabled');
				$("cln_popup_edit_controls_td").setStyle('display', 'block');
				$("cln_popup_view_controls_td").setStyle('display', 'none');

				$('cln_not_edit').setStyle('display', 'none');
				$('calendars_array').setStyle('display', 'block');
				if ( !is_creator && cln_event.id > 0){
					$('calendars_array').addClass('admin_only');
				}else{
					$('calendars_array').removeClass('admin_only');
				}
			}else{
				$('quick_add_event_name').setProperty('disabled', 'true');
				$('quick_add_event_description').setProperty('disabled', 'true');
				$("cln_popup_edit_controls_td").setStyle('display', 'none');
				$("cln_popup_view_controls_td").setStyle('display', 'block');

				$('calendars_array').setStyle('display', 'none');
				$('cln_not_edit').setHTML(document.calendar_info[cln_event.cln_id].name);
				$('cln_not_edit').setStyle('background-color', document.calendar_info[cln_event.cln_id].color);
				$('cln_not_edit').setStyle('color', document.calendar_info[cln_event.cln_id].text_color);
				$('cln_not_edit').setStyle('display', 'block');
			}

			if ($('quick_add_event_description').value.length == 0 && $('quick_add_event_description').getProperty('disabled')) {
				$('quick_add_event_description_row').addClass('d-none');
			}
			else {
				$('quick_add_event_description_row').removeClass('d-none');
			}

			if (cln_event.type == 'system'){
				$('cln_avail_row').addClass('d-none');
				$('cln_confirm_row').addClass('d-none');
				$('cln_overview_row').removeClass('d-none');
				$('cln_overview_body').setHTML(cln_event.overview);
			}else{
				$('cln_overview_row').addClass('d-none');
				if (cln_event.is_personal == 1 || cln_event.participant != 1){
					$('cln_avail_row').removeClass('d-none');
					$('cln_confirm_row').addClass('d-none');
				}else{
					$('cln_avail_row').addClass('d-none');
					$('cln_confirm_row').removeClass('d-none');
				}
			}
			if (!$('quick_add_event_name').disabled){
				try{
					$('quick_add_event_name').focus();
				}
				catch(e){
					return false;
				}
				$('quick_add_event_name').select();
			}
		},
		getQuickAddDiv: function(){
			return $('quick_add_popup');
		},
		closeQuickAddPopup: function(){
			this.getQuickAddDiv().addClass('d-none');
			this.common_event = null;
		},
		getEditedEvent: function(){
			if (!$defined(this.common_event)){
				alert("Error: havn't requested event!");
				return;
			}
			cln_event = this.common_event;
			cln_event.reminder = ($('cln_reminder').getStyle('display') == 'none') ? '' : $($('cln_reminder').options[$('cln_reminder').selectedIndex]).getProperty('value');
			if(cln_event.type == 'system') return cln_event;
			cln_event.setName($('quick_add_event_name').getProperty('value'));
			cln_event.setDescription($('quick_add_event_description').value);
			if ($('calendars_array').selectedIndex < 0){
				var cln_id = false;
			}else{
				var cln_id = $($('calendars_array').options[$('calendars_array').selectedIndex]).getProperty('value');
			}
			var is_creator = (cln_event.creator_id == document.session_uid);
			if (!$defined(cln_event.cln_id) || cln_event.cln_id == 0 || (document.calendar_perms[129][cln_event.cln_id] == 1) || (is_creator && document.calendar_perms[3][cln_event.cln_id] == 1 )) cln_event.cln_id = cln_id;
			cln_event.a_bility = $('cln_a_bility_1').checked ? 1 : 0;
			cln_event.confirm = $('cln_confirm_1').checked ? 1 : ($('cln_confirm_2').checked ? 2 : 0);
			return cln_event;
		},
		showDeleteLink: function(){
			$('delete_link').setHTML(document.lc['common.delete']).removeClass('deleteConfirm').setStyles({'display': 'inline-block'});
			$('delete_link').onclick = function(e){
				var e = new Event(e);
				document.event_controller.popups.confirmDelete(e.target);
			};
		},
		confirmDelete: function(target){
			var cln_event = this.getEditedEvent();
			if (cln_event.seq_id > 0) return this.showSequenceDialog('delete', document.lc['calendar.what_to_delete'] + '?');

			target.setHTML(document.lc['calendar.delete_confirm']).addClass('deleteConfirm').setStyles({'display': 'inline-block'});
			target.onclick = function(e){
				document.event_controller.quickDelete('event');return false;
			};
		},
		showSequenceDialog: function(action, header){
			this.seq_action = action;
			$('seq_popup_header').setHTML(header);
			this.showWindow("seq_popup_action");
			return;
		},
		doSeqAction: function(event_type){
			var cln_event = this.getEditedEvent();
			switch(this.seq_action)
			{
				case 'delete':
					document.event_controller.quickDelete(event_type);
					return this.showWindow('popup_main_screen');
				break;
				case 'edit':
					document.event_controller.quickEditEnd(cln_event, event_type);
					return this.showWindow('popup_main_screen');
				break;
				case 'adv_edit':
					var href = (event_type == 'event' ) ?
						"calendar_edit_event.php?id="+cln_event.getId()+'&type=event&start_date='+cln_event.start.serialize()+'&end_date='+cln_event.end.serialize()+'&full_day='+cln_event.full_day+'&event_name='+encodeURIComponent($('quick_add_event_name').value)+'&event_descsription='+encodeURIComponent($('quick_add_event_description').value) :
						"calendar_edit_event.php?id="+cln_event.seq_id+'&type=chain&event_name='+encodeURIComponent($('quick_add_event_name').value)+'&event_descsription='+encodeURIComponent($('quick_add_event_description').value);
					document.location.href = href;
					return;
				break;
				case 'adv_view':
					var href = (event_type == 'event' ) ?
						"calendar_view_event.php?id="+cln_event.getId()+'&type=event' :
						"calendar_view_event.php?id="+cln_event.seq_id+'&type=chain';
					document.location.href = href;
					return;
				break;
				default:
					alert('ERROR: actions is not set!');
					return this.showWindow('popup_main_screen');
			}
		},
		showWindow: function(win_name){
			this.windows_ids.each(function(id){
				if (id == win_name){
					$(win_name).removeClass('d-none');
				}else{
					$(id).addClass('d-none');
				}
			});
			var header = '';
			if (win_name == 'popup_main_screen')
				header = jQuery('#quick_add_event_time').html();
			else if (win_name == 'seq_popup_action')
				header = jQuery('#seq_popup_header').html();

			popup_set_header(jQuery('#quick_add_popup'), header);
		},
		saveLink2UpdateLink: function(){
			$('save_link').onclick = function(e){
				document.event_controller.popups.quickEdit();
			};
			$('save_view_link').onclick = function(e){
				document.event_controller.popups.quickEdit();
			};
		},
		quickEdit: function(){
			var cln_event = this.getEditedEvent();
			if (cln_event.seq_id > 0) return this.showSequenceDialog('edit', document.lc['calendar.what_to_edit'] + '?');
			return document.event_controller.quickEditEnd(cln_event, 'event');
		},
		setError: function(str){
			this.showWindow('error_screen');
			$('error_text').setHTML(strEscapeHTML(str));
		},
		// {'x': xxx, 'y': xxx, 'width': xxx, 'height': xxx}
		openHiddenEvents: function(options){
			var div = $('hidden_events');
			div.removeClass('d-none');
			div.setStyles({
				position: 'absolute',
				width: options.width
			});
			div.getElement('#e_body').setStyle('height', options.height);
			pos = document.cln_viewer.getHiddenEventsPosition(div.getCoordinates());
			div.setStyles({
				top: pos.y,
				left: pos.x
			});
			jQuery('#hidden_events .header img').unbind('click').click(function () { document.cln_viewer.closeHiddenEvents(); });
			return div;
		},
		getQuickWindowSize: function(){
			// 330, 150 - size of popup, we can calculate it later, but first time we will only fix it
			if (this.getQuickAddDiv().getStyle('height') == 'auto') return {'width': 370, 'height' : 150};
			return {'width': this.getQuickAddDiv().getStyle('width').toInt() - -20, 'height' : this.getQuickAddDiv().getStyle('height').toInt()};
		}
	});

	return ClnPopups;
});
