Example usage for com.google.gwt.user.client.ui CheckBox setValue

List of usage examples for com.google.gwt.user.client.ui CheckBox setValue

Introduction

In this page you can find the example usage for com.google.gwt.user.client.ui CheckBox setValue.

Prototype

@Override
public void setValue(Boolean value) 

Source Link

Document

Checks or unchecks the check box.

Usage

From source file:org.unitime.timetable.gwt.client.events.EventFilterBox.java

License:Apache License

public EventFilterBox(AcademicSessionProvider session) {
    super(session);

    addFilter(new FilterBox.StaticSimpleFilter("type", MESSAGES.tagEventType()) {
        @Override/*  w  w w  .ja va 2 s. c  om*/
        public void validate(String text, AsyncCallback<Chip> callback) {
            String translatedValue = null;
            if ("class".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventTypeShort()[0];
            else if ("final exam".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventTypeShort()[1];
            else if ("midterm exam".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventTypeShort()[2];
            else if ("course".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventTypeShort()[3];
            else if ("special".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventTypeShort()[4];
            else if ("not available".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventTypeShort()[5];
            callback.onSuccess(new Chip(getCommand(), text).withTranslatedCommand(getLabel())
                    .withTranslatedValue(translatedValue));
        }
    });

    iSponsors = new ListBox();
    iSponsors.setMultipleSelect(true);
    iSponsors.setWidth("100%");
    iSponsors.setVisibleItemCount(3);

    addFilter(new FilterBox.CustomFilter("sponsor", MESSAGES.tagSponsor(), iSponsors) {
        @Override
        public void getSuggestions(List<Chip> chips, String text,
                AsyncCallback<Collection<Suggestion>> callback) {
            if (text.isEmpty()) {
                callback.onSuccess(null);
            } else {
                List<Suggestion> suggestions = new ArrayList<Suggestion>();
                for (int i = 0; i < iSponsors.getItemCount(); i++) {
                    Chip chip = new Chip("sponsor", iSponsors.getValue(i))
                            .withTranslatedCommand(MESSAGES.tagSponsor());
                    String name = iSponsors.getItemText(i);
                    if (iSponsors.getValue(i).toLowerCase().startsWith(text.toLowerCase())) {
                        suggestions.add(new Suggestion(name, chip));
                    } else if (text.length() > 2 && name.toLowerCase().contains(" " + text.toLowerCase())) {
                        suggestions.add(new Suggestion(name, chip));
                    }
                }
                callback.onSuccess(suggestions);
            }
        }

        @Override
        public boolean isVisible() {
            return iSponsors.getItemCount() > 0;
        }
    });
    iSponsors.addChangeHandler(new ChangeHandler() {
        @Override
        public void onChange(ChangeEvent event) {
            boolean changed = false;
            for (int i = 0; i < iSponsors.getItemCount(); i++) {
                Chip chip = new Chip("sponsor", iSponsors.getValue(i))
                        .withTranslatedCommand(MESSAGES.tagSponsor());
                if (iSponsors.isItemSelected(i)) {
                    if (!hasChip(chip)) {
                        addChip(chip, false);
                        changed = true;
                    }
                } else {
                    if (hasChip(chip)) {
                        removeChip(chip, false);
                        changed = true;
                    }
                }
            }
            if (changed)
                fireValueChangeEvent();
        }
    });

    FilterBox.StaticSimpleFilter mode = new FilterBox.StaticSimpleFilter("mode", MESSAGES.tagEventMode()) {
        @Override
        public void validate(String text, AsyncCallback<Chip> callback) {
            String translatedValue = null;
            if ("all".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventModeAbbv()[0];
            else if ("my".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventModeAbbv()[1];
            else if ("approved".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventModeAbbv()[2];
            else if ("unapproved".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventModeAbbv()[3];
            else if ("awaiting".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventModeAbbv()[4];
            else if ("conflicting".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventModeAbbv()[5];
            else if ("my awaiting".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventModeAbbv()[6];
            else if ("cancelled".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventModeAbbv()[7];
            else if ("expiring".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventModeAbbv()[8];
            callback.onSuccess(new Chip(getCommand(), text).withTranslatedCommand(getLabel())
                    .withTranslatedValue(translatedValue));
        }
    };
    mode.setMultipleSelection(false);
    addFilter(mode);

    addFilter(new FilterBox.StaticSimpleFilter("role", MESSAGES.tagEventRole()) {
        @Override
        public void getPopupWidget(final FilterBox box, final AsyncCallback<Widget> callback) {
            callback.onSuccess(null);
        }

        @Override
        public void validate(String text, AsyncCallback<Chip> callback) {
            String translatedValue = null;
            if ("all".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventRole()[0];
            else if ("student".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventRole()[1];
            else if ("instructor".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventRole()[2];
            else if ("coordinator".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventRole()[3];
            else if ("contact".equalsIgnoreCase(text))
                translatedValue = CONSTANTS.eventRole()[4];
            callback.onSuccess(new Chip(getCommand(), text).withTranslatedCommand(getLabel())
                    .withTranslatedValue(translatedValue));
        }
    });

    Label reqLab = new Label(MESSAGES.propRequestedBy());

    iRequested = new AriaSuggestBox(new RequestedByOracle());
    iRequested.setStyleName("unitime-TextArea");
    iRequested.setWidth("200px");

    final CheckBox conflicts = new CheckBox(MESSAGES.checkDisplayConflicts());
    conflicts.getElement().getStyle().setMarginLeft(10, Unit.PX);

    final CheckBox sessions = new CheckBox(MESSAGES.checkSpanMultipleSessions());
    sessions.getElement().getStyle().setMarginLeft(10, Unit.PX);

    iOther = new FilterBox.CustomFilter("other", MESSAGES.tagOther(), reqLab, iRequested, conflicts, sessions) {
        @Override
        public void getSuggestions(final List<Chip> chips, final String text,
                AsyncCallback<Collection<FilterBox.Suggestion>> callback) {
            if (text.isEmpty()) {
                callback.onSuccess(null);
            } else {
                List<FilterBox.Suggestion> suggestions = new ArrayList<FilterBox.Suggestion>();
                if ("conflicts".startsWith(text.toLowerCase())
                        || MESSAGES.checkDisplayConflicts().toLowerCase().startsWith(text.toLowerCase())) {
                    suggestions.add(new Suggestion(MESSAGES.checkDisplayConflicts(),
                            new Chip("flag", "Conflicts").withTranslatedCommand(MESSAGES.tagEventFlag())
                                    .withTranslatedValue(MESSAGES.attrFlagShowConflicts())));
                }
                if ("sessinons".startsWith(text.toLowerCase())
                        || MESSAGES.checkSpanMultipleSessions().toLowerCase().startsWith(text.toLowerCase())) {
                    suggestions.add(new Suggestion(MESSAGES.checkSpanMultipleSessions(),
                            new Chip("flag", "All Sessions").withTranslatedCommand(MESSAGES.tagEventFlag())
                                    .withTranslatedValue(MESSAGES.attrFlagAllSessions())));
                }
                callback.onSuccess(suggestions);
            }
        }
    };
    addFilter(iOther);

    addFilter(new FilterBox.StaticSimpleFilter("requested", MESSAGES.tagRequested()));
    addFilter(new FilterBox.StaticSimpleFilter("flag", MESSAGES.tagEventFlag()) {
        @Override
        public void validate(String text, AsyncCallback<Chip> callback) {
            String translatedValue = null;
            if ("conflicts".equalsIgnoreCase(text))
                translatedValue = MESSAGES.attrFlagShowConflicts();
            else if ("all sessions".equalsIgnoreCase(text))
                translatedValue = MESSAGES.attrFlagAllSessions();
            callback.onSuccess(new Chip(getCommand(), text).withTranslatedCommand(getLabel())
                    .withTranslatedValue(translatedValue));
        }
    });

    iRequested.getValueBox().addChangeHandler(new ChangeHandler() {
        @Override
        public void onChange(ChangeEvent event) {
            requestedChanged(true);
        }
    });
    iRequested.getValueBox().addKeyPressHandler(new KeyPressHandler() {
        @Override
        public void onKeyPress(KeyPressEvent event) {
            Scheduler.get().scheduleDeferred(new ScheduledCommand() {
                @Override
                public void execute() {
                    requestedChanged(false);
                }
            });
        }
    });
    iRequested.getValueBox().addKeyUpHandler(new KeyUpHandler() {
        @Override
        public void onKeyUp(KeyUpEvent event) {
            if (event.getNativeKeyCode() == KeyCodes.KEY_BACKSPACE)
                Scheduler.get().scheduleDeferred(new ScheduledCommand() {
                    @Override
                    public void execute() {
                        requestedChanged(false);
                    }
                });
        }
    });
    iRequested.getValueBox().addBlurHandler(new BlurHandler() {
        @Override
        public void onBlur(BlurEvent event) {
            requestedChanged(true);
        }
    });
    iRequested.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {
        @Override
        public void onSelection(SelectionEvent<com.google.gwt.user.client.ui.SuggestOracle.Suggestion> event) {
            requestedChanged(true);
        }
    });
    conflicts.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
        @Override
        public void onValueChange(ValueChangeEvent<Boolean> event) {
            Chip chip = new Chip("flag", "Conflicts").withTranslatedCommand(MESSAGES.tagEventFlag())
                    .withTranslatedValue(MESSAGES.attrFlagShowConflicts());
            if (event.getValue()) {
                if (!hasChip(chip))
                    addChip(chip, true);
            } else {
                if (hasChip(chip))
                    removeChip(chip, true);
            }
        }
    });
    conflicts.addMouseDownHandler(new MouseDownHandler() {
        @Override
        public void onMouseDown(MouseDownEvent event) {
            event.getNativeEvent().stopPropagation();
            event.getNativeEvent().preventDefault();
        }
    });

    sessions.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
        @Override
        public void onValueChange(ValueChangeEvent<Boolean> event) {
            Chip chip = new Chip("flag", "All Sessions").withTranslatedCommand(MESSAGES.tagEventFlag())
                    .withTranslatedValue(MESSAGES.attrFlagAllSessions());
            if (event.getValue()) {
                if (!hasChip(chip))
                    addChip(chip, true);
            } else {
                if (hasChip(chip))
                    removeChip(chip, true);
            }
        }
    });
    sessions.addMouseDownHandler(new MouseDownHandler() {
        @Override
        public void onMouseDown(MouseDownEvent event) {
            event.getNativeEvent().stopPropagation();
            event.getNativeEvent().preventDefault();
        }
    });

    AbsolutePanel m = new AbsolutePanel();
    m.setStyleName("unitime-DateSelector");
    final SingleDateSelector.SingleMonth m1 = new SingleDateSelector.SingleMonth(MESSAGES.tagDateFrom());
    m1.setAllowDeselect(true);
    m.add(m1);
    final SingleDateSelector.SingleMonth m2 = new SingleDateSelector.SingleMonth(MESSAGES.tagDateTo());
    m2.setAllowDeselect(true);
    m.add(m2);
    addFilter(new FilterBox.CustomFilter("date", MESSAGES.tagDate(), m) {
        @Override
        public void getSuggestions(List<Chip> chips, String text,
                AsyncCallback<Collection<Suggestion>> callback) {
            List<FilterBox.Suggestion> suggestions = new ArrayList<FilterBox.Suggestion>();
            Chip chFrom = null, chTo = null;
            for (Chip c : chips) {
                if (c.getCommand().equals("from"))
                    chFrom = c;
                if (c.getCommand().equals("to"))
                    chTo = c;
            }
            try {
                Date date = DateTimeFormat.getFormat("MM/dd").parse(text);
                suggestions.add(new FilterBox.Suggestion(
                        new Chip("from", sDateFormat.format(date)).withTranslatedCommand(MESSAGES.tagDateFrom())
                                .withTranslatedValue(sLocalDateFormat.format(date)),
                        chFrom));
                suggestions.add(new FilterBox.Suggestion(
                        new Chip("to", sDateFormat.format(date)).withTranslatedCommand(MESSAGES.tagDateTo())
                                .withTranslatedValue(sLocalDateFormat.format(date)),
                        chTo));
            } catch (Exception e) {
            }
            try {
                Date date = DateTimeFormat.getFormat("dd.MM").parse(text);
                suggestions.add(new FilterBox.Suggestion(
                        new Chip("from", sDateFormat.format(date)).withTranslatedCommand(MESSAGES.tagDateFrom())
                                .withTranslatedValue(sLocalDateFormat.format(date)),
                        chFrom));
                suggestions.add(new FilterBox.Suggestion(
                        new Chip("to", sDateFormat.format(date)).withTranslatedCommand(MESSAGES.tagDateTo())
                                .withTranslatedValue(sLocalDateFormat.format(date)),
                        chTo));
            } catch (Exception e) {
            }
            try {
                Date date = DateTimeFormat.getFormat("MM/dd/yy").parse(text);
                suggestions.add(new FilterBox.Suggestion(
                        new Chip("from", sDateFormat.format(date)).withTranslatedCommand(MESSAGES.tagDateFrom())
                                .withTranslatedValue(sLocalDateFormat.format(date)),
                        chFrom));
                suggestions.add(new FilterBox.Suggestion(
                        new Chip("to", sDateFormat.format(date)).withTranslatedCommand(MESSAGES.tagDateTo())
                                .withTranslatedValue(sLocalDateFormat.format(date)),
                        chTo));
            } catch (Exception e) {
            }
            try {
                Date date = DateTimeFormat.getFormat("dd.MM.yy").parse(text);
                suggestions.add(new FilterBox.Suggestion(
                        new Chip("from", sDateFormat.format(date)).withTranslatedCommand(MESSAGES.tagDateFrom())
                                .withTranslatedValue(sLocalDateFormat.format(date)),
                        chFrom));
                suggestions.add(new FilterBox.Suggestion(
                        new Chip("to", sDateFormat.format(date)).withTranslatedCommand(MESSAGES.tagDateTo())
                                .withTranslatedValue(sLocalDateFormat.format(date)),
                        chTo));
            } catch (Exception e) {
            }
            try {
                Date date = DateTimeFormat.getFormat("MMM dd").parse(text);
                suggestions.add(new FilterBox.Suggestion(
                        new Chip("from", sDateFormat.format(date)).withTranslatedCommand(MESSAGES.tagDateFrom())
                                .withTranslatedValue(sLocalDateFormat.format(date)),
                        chFrom));
                suggestions.add(new FilterBox.Suggestion(
                        new Chip("to", sDateFormat.format(date)).withTranslatedCommand(MESSAGES.tagDateTo())
                                .withTranslatedValue(sLocalDateFormat.format(date)),
                        chTo));
            } catch (Exception e) {
            }
            try {
                Date date = DateTimeFormat.getFormat("MMM dd yy").parse(text);
                suggestions.add(new FilterBox.Suggestion(
                        new Chip("from", sDateFormat.format(date)).withTranslatedCommand(MESSAGES.tagDateFrom())
                                .withTranslatedValue(sLocalDateFormat.format(date)),
                        chFrom));
                suggestions.add(new FilterBox.Suggestion(
                        new Chip("to", sDateFormat.format(date)).withTranslatedCommand(MESSAGES.tagDateTo())
                                .withTranslatedValue(sLocalDateFormat.format(date)),
                        chTo));
            } catch (Exception e) {
            }
            callback.onSuccess(suggestions);
        }
    });
    addFilter(new FilterBox.StaticSimpleFilter("from", MESSAGES.tagDateFrom()) {
        @Override
        public void validate(String value, AsyncCallback<Chip> callback) {
            String translatedValue = null;
            try {
                translatedValue = sLocalDateFormat.format(sDateFormat.parse(value));
            } catch (IllegalArgumentException e) {
            }
            callback.onSuccess(new Chip(getCommand(), value).withTranslatedCommand(getLabel())
                    .withTranslatedValue(translatedValue));
        }
    });
    addFilter(new FilterBox.StaticSimpleFilter("to", MESSAGES.tagDateTo()) {
        @Override
        public void validate(String value, AsyncCallback<Chip> callback) {
            String translatedValue = null;
            try {
                translatedValue = sLocalDateFormat.format(sDateFormat.parse(value));
            } catch (IllegalArgumentException e) {
            }
            callback.onSuccess(new Chip(getCommand(), value).withTranslatedCommand(getLabel())
                    .withTranslatedValue(translatedValue));
        }
    });

    session.addAcademicSessionChangeHandler(new AcademicSessionChangeHandler() {
        @Override
        public void onAcademicSessionChange(AcademicSessionChangeEvent event) {
            if (event.isChanged() && event.getNewAcademicSessionId() != null) {
                RPC.execute(new RequestSessionDetails(event.getNewAcademicSessionId()),
                        new AsyncCallback<GwtRpcResponseList<SessionMonth>>() {

                            @Override
                            public void onFailure(Throwable caught) {
                            }

                            @Override
                            public void onSuccess(GwtRpcResponseList<SessionMonth> result) {
                                m1.setMonths(result);
                                m2.setMonths(result);
                            }
                        });
            }
        }
    });

    m1.addValueChangeHandler(new ValueChangeHandler<Date>() {
        @Override
        public void onValueChange(ValueChangeEvent<Date> event) {
            Chip ch = getChip("from");
            Date value = event.getValue();
            if (value == null) {
                if (ch != null)
                    removeChip(ch, true);
            } else {
                if (ch != null) {
                    if (ch.getValue().equals(sDateFormat.format(value)))
                        return;
                    removeChip(ch, false);
                }
                addChip(new Chip("from", sDateFormat.format(value))
                        .withTranslatedCommand(MESSAGES.tagDateFrom())
                        .withTranslatedValue(sLocalDateFormat.format(value)), true);
            }
        }
    });
    m2.addValueChangeHandler(new ValueChangeHandler<Date>() {
        @Override
        public void onValueChange(ValueChangeEvent<Date> event) {
            Chip ch = getChip("to");
            Date value = event.getValue();
            if (value == null) {
                if (ch != null)
                    removeChip(ch, true);
            } else {
                if (ch != null) {
                    if (ch.getValue().equals(sDateFormat.format(value)))
                        return;
                    removeChip(ch, false);
                }
                addChip(new Chip("to", sDateFormat.format(value)).withTranslatedCommand(MESSAGES.tagDateTo())
                        .withTranslatedValue(sLocalDateFormat.format(value)), true);
            }
        }
    });

    List<Chip> days = new ArrayList<Chip>();
    days.add(new Chip("day", "Monday").withTranslatedCommand(MESSAGES.tagDayOfWeek())
            .withTranslatedValue(CONSTANTS.longDays()[0]));
    days.add(new Chip("day", "Tuesday").withTranslatedCommand(MESSAGES.tagDayOfWeek())
            .withTranslatedValue(CONSTANTS.longDays()[1]));
    days.add(new Chip("day", "Wednesday").withTranslatedCommand(MESSAGES.tagDayOfWeek())
            .withTranslatedValue(CONSTANTS.longDays()[2]));
    days.add(new Chip("day", "Thursday").withTranslatedCommand(MESSAGES.tagDayOfWeek())
            .withTranslatedValue(CONSTANTS.longDays()[3]));
    days.add(new Chip("day", "Friday").withTranslatedCommand(MESSAGES.tagDayOfWeek())
            .withTranslatedValue(CONSTANTS.longDays()[4]));
    days.add(new Chip("day", "Saturday").withTranslatedCommand(MESSAGES.tagDayOfWeek())
            .withTranslatedValue(CONSTANTS.longDays()[5]));
    days.add(new Chip("day", "Sunday").withTranslatedCommand(MESSAGES.tagDayOfWeek())
            .withTranslatedValue(CONSTANTS.longDays()[6]));
    addFilter(new FilterBox.StaticSimpleFilter("day", MESSAGES.tagDayOfWeek(), days));

    final TimeSelector st = new TimeSelector(null);
    final TimeSelector et = new TimeSelector(st);
    st.setStyleName("unitime-TextArea");
    st.addStyleName("unitime-TimeSelector");
    et.setStyleName("unitime-TextArea");
    et.addStyleName("unitime-TimeSelector");
    addFilter(new FilterBox.CustomFilter("time", MESSAGES.tagTime(), new Label(MESSAGES.propAfter()), st,
            new Label(" " + MESSAGES.propBefore()), et) {
        @Override
        public void getSuggestions(List<Chip> chips, String text,
                AsyncCallback<Collection<Suggestion>> callback) {
            List<FilterBox.Suggestion> suggestions = new ArrayList<FilterBox.Suggestion>();
            Chip chStart = null, chStop = null;
            for (Chip c : chips) {
                if (c.getCommand().equals("after"))
                    chStart = c;
                if (c.getCommand().equals("before"))
                    chStop = c;
            }
            Integer start = TimeSelector.TimeUtils.parseTime(CONSTANTS, text, null);
            Integer stop = TimeSelector.TimeUtils.parseTime(CONSTANTS, text,
                    chStart == null ? null : TimeSelector.TimeUtils.parseMilitary(chStart.getValue()));
            if (chStart == null) {
                if (start != null) {
                    suggestions.add(new FilterBox.Suggestion(new Chip("after", TimeUtils.slot2military(start))
                            .withTranslatedCommand(MESSAGES.tagTimeAfter())
                            .withTranslatedValue(TimeUtils.slot2time(start)), chStart));
                    suggestions
                            .add(new FilterBox.Suggestion(new Chip("after", TimeUtils.slot2military(start + 3))
                                    .withTranslatedCommand(MESSAGES.tagTimeAfter())
                                    .withTranslatedValue(TimeUtils.slot2time(start + 3)), chStart));
                    suggestions
                            .add(new FilterBox.Suggestion(new Chip("after", TimeUtils.slot2military(start + 6))
                                    .withTranslatedCommand(MESSAGES.tagTimeAfter())
                                    .withTranslatedValue(TimeUtils.slot2time(start + 6)), chStart));
                    suggestions
                            .add(new FilterBox.Suggestion(new Chip("after", TimeUtils.slot2military(start + 9))
                                    .withTranslatedCommand(MESSAGES.tagTimeAfter())
                                    .withTranslatedValue(TimeUtils.slot2time(start + 9)), chStart));
                }
                if (stop != null) {
                    suggestions.add(new FilterBox.Suggestion(new Chip("before", TimeUtils.slot2military(stop))
                            .withTranslatedCommand(MESSAGES.tagTimeBefore())
                            .withTranslatedValue(TimeUtils.slot2time(stop)), chStop));
                    suggestions
                            .add(new FilterBox.Suggestion(new Chip("before", TimeUtils.slot2military(stop + 3))
                                    .withTranslatedCommand(MESSAGES.tagTimeBefore())
                                    .withTranslatedValue(TimeUtils.slot2time(stop + 3)), chStop));
                    suggestions
                            .add(new FilterBox.Suggestion(new Chip("before", TimeUtils.slot2military(stop + 6))
                                    .withTranslatedCommand(MESSAGES.tagTimeBefore())
                                    .withTranslatedValue(TimeUtils.slot2time(stop + 6)), chStop));
                    suggestions
                            .add(new FilterBox.Suggestion(new Chip("before", TimeUtils.slot2military(stop + 9))
                                    .withTranslatedCommand(MESSAGES.tagTimeBefore())
                                    .withTranslatedValue(TimeUtils.slot2time(stop + 9)), chStop));
                }
            } else {
                if (stop != null) {
                    suggestions.add(new FilterBox.Suggestion(new Chip("before", TimeUtils.slot2military(stop))
                            .withTranslatedCommand(MESSAGES.tagTimeBefore())
                            .withTranslatedValue(TimeUtils.slot2time(stop)), chStop));
                    suggestions
                            .add(new FilterBox.Suggestion(new Chip("before", TimeUtils.slot2military(stop + 3))
                                    .withTranslatedCommand(MESSAGES.tagTimeBefore())
                                    .withTranslatedValue(TimeUtils.slot2time(stop + 3)), chStop));
                    suggestions
                            .add(new FilterBox.Suggestion(new Chip("before", TimeUtils.slot2military(stop + 6))
                                    .withTranslatedCommand(MESSAGES.tagTimeBefore())
                                    .withTranslatedValue(TimeUtils.slot2time(stop + 6)), chStop));
                    suggestions
                            .add(new FilterBox.Suggestion(new Chip("before", TimeUtils.slot2military(stop + 9))
                                    .withTranslatedCommand(MESSAGES.tagTimeBefore())
                                    .withTranslatedValue(TimeUtils.slot2time(stop + 9)), chStop));
                }
                if (start != null) {
                    suggestions.add(new FilterBox.Suggestion(new Chip("after", TimeUtils.slot2military(start))
                            .withTranslatedCommand(MESSAGES.tagTimeAfter())
                            .withTranslatedValue(TimeUtils.slot2time(start)), chStart));
                    suggestions
                            .add(new FilterBox.Suggestion(new Chip("after", TimeUtils.slot2military(start + 3))
                                    .withTranslatedCommand(MESSAGES.tagTimeAfter())
                                    .withTranslatedValue(TimeUtils.slot2time(start + 3)), chStart));
                    suggestions
                            .add(new FilterBox.Suggestion(new Chip("after", TimeUtils.slot2military(start + 6))
                                    .withTranslatedCommand(MESSAGES.tagTimeAfter())
                                    .withTranslatedValue(TimeUtils.slot2time(start + 6)), chStart));
                    suggestions
                            .add(new FilterBox.Suggestion(new Chip("after", TimeUtils.slot2military(start + 9))
                                    .withTranslatedCommand(MESSAGES.tagTimeAfter())
                                    .withTranslatedValue(TimeUtils.slot2time(start + 9)), chStart));
                }
            }
            callback.onSuccess(suggestions);
        }
    });
    st.addValueChangeHandler(new ValueChangeHandler<Integer>() {
        @Override
        public void onValueChange(ValueChangeEvent<Integer> event) {
            Chip ch = getChip("after");
            Integer start = event.getValue();
            if (start == null) {
                if (ch != null)
                    removeChip(ch, true);
            } else {
                if (ch != null) {
                    if (ch.getCommand().equals(TimeUtils.slot2military(start)))
                        return;
                    removeChip(ch, false);
                }
                addChip(new Chip("after", TimeUtils.slot2military(start))
                        .withTranslatedCommand(MESSAGES.tagTimeAfter())
                        .withTranslatedValue(TimeUtils.slot2time(start)), true);
            }
            Chip ch2 = getChip("before");
            Integer stop = et.getValue();
            if (stop == null) {
                if (ch2 != null)
                    removeChip(ch2, true);
            } else {
                if (ch2 != null) {
                    if (ch2.getCommand().equals(TimeUtils.slot2military(stop)))
                        return;
                    removeChip(ch2, false);
                }
                addChip(new Chip("before", TimeUtils.slot2military(stop))
                        .withTranslatedCommand(MESSAGES.tagTimeBefore())
                        .withTranslatedValue(TimeUtils.slot2time(stop)), true);
            }
        }
    });
    et.addValueChangeHandler(new ValueChangeHandler<Integer>() {
        @Override
        public void onValueChange(ValueChangeEvent<Integer> event) {
            Chip ch = getChip("before");
            Integer stop = event.getValue();
            if (stop == null) {
                if (ch != null)
                    removeChip(ch, true);
            } else {
                if (ch != null) {
                    if (ch.getCommand().equals(TimeUtils.slot2military(stop)))
                        return;
                    removeChip(ch, false);
                }
                addChip(new Chip("before", TimeUtils.slot2military(stop))
                        .withTranslatedCommand(MESSAGES.tagTimeBefore())
                        .withTranslatedValue(TimeUtils.slot2time(stop)), true);
            }
        }
    });

    addFilter(new FilterBox.StaticSimpleFilter("after", MESSAGES.tagTimeAfter()) {
        @Override
        public void validate(String text, AsyncCallback<Chip> callback) {
            String translatedValue = null;
            Integer slot = TimeUtils.parseTime2(CONSTANTS, text, null);
            if (slot != null)
                translatedValue = TimeUtils.slot2time(slot);
            callback.onSuccess(new Chip(getCommand(), text).withTranslatedCommand(getLabel())
                    .withTranslatedValue(translatedValue));
        }
    });
    addFilter(new FilterBox.StaticSimpleFilter("before", MESSAGES.tagTimeBefore()) {
        @Override
        public void validate(String text, AsyncCallback<Chip> callback) {
            String translatedValue = null;
            Integer slot = TimeUtils.parseTime2(CONSTANTS, text, null);
            if (slot != null)
                translatedValue = TimeUtils.slot2time(slot);
            callback.onSuccess(new Chip(getCommand(), text).withTranslatedCommand(getLabel())
                    .withTranslatedValue(translatedValue));
        }
    });

    addValueChangeHandler(new ValueChangeHandler<String>() {
        @Override
        public void onValueChange(ValueChangeEvent<String> event) {
            iLastRequested = getChip("requested");
            if (!isFilterPopupShowing()) {
                conflicts.setValue(hasChip(new Chip("flag", "Conflicts")));
                sessions.setValue(hasChip(new Chip("flag", "All Sessions")));
                Chip req = getChip("requested");
                if (req == null)
                    iRequested.setText("");
                else
                    iRequested.setText(req.getValue());
                for (int i = 0; i < iSponsors.getItemCount(); i++) {
                    String value = iSponsors.getValue(i);
                    iSponsors.setItemSelected(i, hasChip(new Chip("sponsor", value)));
                }
                Chip chFrom = getChip("from");
                if (chFrom != null)
                    m1.setDate(sDateFormat.parse(chFrom.getValue()));
                else
                    m1.clearSelection();
                Chip chTo = getChip("to");
                if (chTo != null)
                    m2.setDate(sDateFormat.parse(chTo.getValue()));
                else
                    m2.clearSelection();
                Chip chStart = getChip("after");
                if (chStart != null)
                    st.setValue(TimeSelector.TimeUtils.parseMilitary(chStart.getValue()));
                else
                    st.setValue(null);
                Chip chStop = getChip("before");
                if (chStop != null)
                    et.setValue(TimeSelector.TimeUtils.parseMilitary(chStop.getValue()));
                else
                    et.setValue(null);
            }
            if (getAcademicSessionId() != null)
                init(false, getAcademicSessionId(), new Command() {
                    @Override
                    public void execute() {
                        if (isFilterPopupShowing())
                            showFilterPopup();
                    }
                });
            setAriaLabel(ARIA.eventFilter(toAriaString()));
        }
    });

    addFocusHandler(new FocusHandler() {
        @Override
        public void onFocus(FocusEvent event) {
            setAriaLabel(ARIA.eventFilter(toAriaString()));
        }
    });
}

From source file:org.unitime.timetable.gwt.client.events.EventMeetingTable.java

License:Apache License

public EventMeetingTable(Mode mode, boolean selectable, EventPropertiesProvider properties) {
    setStyleName("unitime-EventMeetings");

    iMode = mode;//from  ww w .  j a v a 2s.c  o m
    iSelectable = selectable;
    iPropertiesProvider = properties;

    if (getRowCount() > 0)
        clearTable();

    List<UniTimeTableHeader> header = new ArrayList<UniTimeTableHeader>();

    UniTimeTableHeader hTimes = new UniTimeTableHeader("&otimes;", HasHorizontalAlignment.ALIGN_CENTER);
    header.add(hTimes);
    hTimes.addOperation(new Operation() {
        @Override
        public void execute() {
            for (int row = 1; row < getRowCount(); row++) {
                Widget w = getWidget(row, 0);
                if (w != null && w instanceof CheckBox) {
                    CheckBox ch = (CheckBox) w;
                    ch.setValue(true);
                }
            }
        }

        @Override
        public boolean isApplicable() {
            for (int row = 1; row < getRowCount(); row++) {
                Widget w = getWidget(row, 0);
                if (w != null && w instanceof CheckBox) {
                    CheckBox ch = (CheckBox) w;
                    if (!ch.getValue())
                        return true;
                }
            }
            return false;
        }

        @Override
        public boolean hasSeparator() {
            return false;
        }

        @Override
        public String getName() {
            return MESSAGES.opSelectAll();
        }
    });
    hTimes.addOperation(new Operation() {
        @Override
        public void execute() {
            for (int row = 1; row < getRowCount(); row++) {
                Widget w = getWidget(row, 0);
                if (w != null && w instanceof CheckBox) {
                    CheckBox ch = (CheckBox) w;
                    ch.setValue(getData(row).inConflict());
                }
            }
        }

        @Override
        public boolean isApplicable() {
            for (int row = 1; row < getRowCount(); row++) {
                Widget w = getWidget(row, 0);
                if (w != null && w instanceof CheckBox)
                    if (getData(row).inConflict())
                        return true;
            }
            return false;
        }

        @Override
        public boolean hasSeparator() {
            return false;
        }

        @Override
        public String getName() {
            return MESSAGES.opSelectAllConflicting();
        }
    });
    hTimes.addOperation(new Operation() {
        @Override
        public void execute() {
            for (int row = 1; row < getRowCount(); row++) {
                Widget w = getWidget(row, 0);
                if (w != null && w instanceof CheckBox) {
                    CheckBox ch = (CheckBox) w;
                    ch.setValue(false);
                }
            }
        }

        @Override
        public boolean isApplicable() {
            for (int row = 1; row < getRowCount(); row++) {
                Widget w = getWidget(row, 0);
                if (w != null && w instanceof CheckBox) {
                    CheckBox ch = (CheckBox) w;
                    if (ch.getValue())
                        return true;
                }
            }
            return false;
        }

        @Override
        public boolean hasSeparator() {
            return false;
        }

        @Override
        public String getName() {
            return MESSAGES.opClearSelection();
        }
    });
    hTimes.addOperation(new Operation() {
        @Override
        public void execute() {
            getOperation(OperationType.AddMeetings).execute(EventMeetingTable.this, OperationType.AddMeetings,
                    null);
        }

        @Override
        public boolean isApplicable() {
            return hasOperation(OperationType.AddMeetings);
        }

        @Override
        public boolean hasSeparator() {
            return true;
        }

        @Override
        public String getName() {
            return MESSAGES.opAddMeetings();
        }
    });
    hTimes.addOperation(new EventMeetingOperation() {
        @Override
        public boolean hasSeparator() {
            return false;
        }

        @Override
        public String getName() {
            return (hasSelection() ? MESSAGES.opDeleteSelectedMeetings() : MESSAGES.opDeleteNewMeetings());
        }

        @Override
        public boolean isApplicable(EventMeetingRow row) {
            return isEditable() && row.isCanDelete();
        }

        @Override
        public void execute(int row, EventMeetingRow event) {
            while (row + 1 < getRowCount() && getData(row + 1).hasParent())
                removeRow(row + 1);
            if (getData(row).getMeeting().getId() == null)
                removeRow(row);
            else {
                MeetingInterface meeting = getData(row).getMeeting();
                meeting.setApprovalStatus(ApprovalStatus.Deleted);
                meeting.setCanApprove(false);
                meeting.setCanCancel(false);
                meeting.setCanInquire(false);
                meeting.setCanEdit(false);
                meeting.setCanDelete(false);
                getRowFormatter().addStyleName(row, "deleted-row");
                setWidget(row, 0, new HTML("&nbsp;"));
                HTML approval = (HTML) getWidget(row, getHeader(MESSAGES.colApproval()).getColumn());
                approval.setStyleName("deleted-meeting");
                approval.setText(MESSAGES.approvalDeleted());
                ValueChangeEvent.fire(EventMeetingTable.this, getValue());
            }
        }

        @Override
        public void execute() {
            super.execute();
            if (hasOperation(OperationType.Delete))
                getOperation(OperationType.Delete).execute(EventMeetingTable.this, OperationType.Delete, null);
        }
    });
    hTimes.addOperation(new EventMeetingOperation() {
        @Override
        public boolean hasSeparator() {
            return true;
        }

        @Override
        public boolean allMustMatch(boolean hasSelection) {
            return false;
        }

        @Override
        public String getName() {
            return (hasSelection() ? MESSAGES.opInquireSelectedMeetings() : MESSAGES.opInquireAllMeetings());
        }

        @Override
        public boolean isApplicable(EventMeetingRow row) {
            return hasOperation(OperationType.Inquire) && row.isCanInquire();
        }

        @Override
        public void execute(int row, EventMeetingRow event) {
        }

        @Override
        public void execute() {
            getOperation(OperationType.Inquire).execute(EventMeetingTable.this, OperationType.Inquire, data());
        }

        @Override
        public boolean allowNoSelection() {
            return getMode().hasFlag(ModeFlag.AllowApproveAll);
        }
    });
    hTimes.addOperation(new EventMeetingOperation() {
        @Override
        public boolean hasSeparator() {
            return false;
        }

        @Override
        public String getName() {
            return (hasSelection() ? MESSAGES.opApproveSelectedMeetings() : MESSAGES.opApproveAllMeetings());
        }

        @Override
        public boolean isApplicable(EventMeetingRow row) {
            return hasOperation(OperationType.Approve) && row.isCanApprove();
        }

        @Override
        public void execute(int row, EventMeetingRow event) {
        }

        @Override
        public void execute() {
            getOperation(OperationType.Approve).execute(EventMeetingTable.this, OperationType.Approve, data());
        }

        @Override
        public boolean allowNoSelection() {
            return getMode().hasFlag(ModeFlag.AllowApproveAll);
        }
    });
    hTimes.addOperation(new EventMeetingOperation() {
        @Override
        public boolean hasSeparator() {
            return false;
        }

        @Override
        public String getName() {
            if (hasOperation(OperationType.Delete))
                return (hasSelection() ? MESSAGES.opCancelSelectedMeetingsNoPopup()
                        : MESSAGES.opCancelAllMeetingsNoPopup());
            else
                return (hasSelection() ? MESSAGES.opCancelSelectedMeetings() : MESSAGES.opCancelAllMeetings());
        }

        @Override
        public boolean isApplicable(EventMeetingRow row) {
            return (hasOperation(OperationType.Cancel) && row.isCanCancel())
                    || (isEditable() && row.isCanCancel());
        }

        @Override
        public void execute(int row, EventMeetingRow event) {
            if (isEditable()) {
                while (row + 1 < getRowCount() && getData(row + 1).hasParent())
                    removeRow(row + 1);
                if (getData(row).getMeeting().getId() == null)
                    removeRow(row);
                else {
                    getData(row).getMeeting().setApprovalStatus(ApprovalStatus.Cancelled);
                    getRowFormatter().addStyleName(row, "cancelled-row");
                    setWidget(row, 0, new HTML("&nbsp;"));
                    HTML approval = (HTML) getWidget(row, getHeader(MESSAGES.colApproval()).getColumn());
                    approval.setStyleName("cancelled-meeting");
                    approval.setText(MESSAGES.approvalCancelled());
                    ValueChangeEvent.fire(EventMeetingTable.this, getValue());
                }
            }
        }

        @Override
        public void execute() {
            super.execute();
            if (hasOperation(OperationType.Cancel))
                getOperation(OperationType.Cancel).execute(EventMeetingTable.this, OperationType.Cancel,
                        data());
        }

        @Override
        public boolean allowNoSelection() {
            return getMode().hasFlag(ModeFlag.AllowApproveAll);
        }
    });
    hTimes.addOperation(new EventMeetingOperation() {
        @Override
        public boolean hasSeparator() {
            return false;
        }

        @Override
        public String getName() {
            return (hasSelection() ? MESSAGES.opRejectSelectedMeetings() : MESSAGES.opRejectAllMeetings());
        }

        @Override
        public boolean isApplicable(EventMeetingRow row) {
            return hasOperation(OperationType.Reject) && row.isCanApprove();
        }

        @Override
        public void execute(int row, EventMeetingRow event) {
        }

        @Override
        public void execute() {
            getOperation(OperationType.Reject).execute(EventMeetingTable.this, OperationType.Reject, data());
        }

        @Override
        public boolean allowNoSelection() {
            return getMode().hasFlag(ModeFlag.AllowApproveAll);
        }
    });
    hTimes.addOperation(new EventMeetingOperation() {
        @Override
        public void execute() {
            getOperation(OperationType.Modify).execute(EventMeetingTable.this, OperationType.Modify, data());
        }

        @Override
        public String getName() {
            return MESSAGES.opModifyMeetings();
        }

        @Override
        public boolean isApplicable() {
            Integer start = null, end = null;
            boolean hasSelection = hasSelection();
            if (hasSelection) {
                for (int row = 1; row < getRowCount(); row++) {
                    Widget w = getWidget(row, 0);
                    if (w != null && w instanceof CheckBox) {
                        CheckBox ch = (CheckBox) w;
                        if (ch.getValue()) {
                            EventMeetingRow e = getData(row);
                            if (!isApplicable(e))
                                return false;
                            if (start == null) {
                                start = e.getMeeting().getStartSlot();
                                end = e.getMeeting().getEndSlot();
                            } else if (start != e.getMeeting().getStartSlot()
                                    || end != e.getMeeting().getEndSlot())
                                return false;
                        }
                    }
                }
                return true;
            } else if (allowNoSelection()) {
                boolean canSelect = false;
                for (int row = 1; row < getRowCount(); row++) {
                    Widget w = getWidget(row, 0);
                    if (w != null && w instanceof CheckBox) {
                        EventMeetingRow e = getData(row);
                        if (!isApplicable(e))
                            return false;
                        if (start == null) {
                            start = e.getMeeting().getStartSlot();
                            end = e.getMeeting().getEndSlot();
                        } else if (start != e.getMeeting().getStartSlot() || end != e.getMeeting().getEndSlot())
                            return false;
                        canSelect = true;
                    }
                }
                return canSelect;
            } else {
                return false;
            }
        }

        @Override
        public boolean allMustMatch(boolean hasSelection) {
            return true;
        }

        @Override
        public boolean isApplicable(EventMeetingRow data) {
            return isEditable() && hasOperation(OperationType.Modify) && data.getMeeting() != null
                    && (data.getMeeting().getId() == null || data.getMeeting().isCanDelete()
                            || data.getMeeting().isCanCancel());
        }

        @Override
        public void execute(int row, EventMeetingRow data) {
        }
    });
    hTimes.addOperation(new EventMeetingOperation() {
        @Override
        public void execute() {
            Integer so = null, eo = null;
            boolean soSame = true, eoSame = true;
            for (EventMeetingRow r : data()) {
                MeetingInterface m = r.getMeeting();
                if (so == null)
                    so = m.getStartOffset();
                else if (m.getStartOffset() != so)
                    soSame = false;
                if (eo == null)
                    eo = -m.getEndOffset();
                else if (-m.getEndOffset() != eo)
                    eoSame = false;
            }
            final UniTimeDialogBox dialog = new UniTimeDialogBox(true, false);
            SimpleForm simple = new SimpleForm();
            simple.removeStyleName("unitime-NotPrintableBottomLine");
            final NumberBox setupTime = new NumberBox();
            if (soSame && so != null)
                setupTime.setValue(so);
            simple.addRow(MESSAGES.propSetupTime(), setupTime);
            final NumberBox teardownTime = new NumberBox();
            if (eoSame && eo != null)
                teardownTime.setValue(eo);
            simple.addRow(MESSAGES.propTeardownTime(), teardownTime);
            UniTimeHeaderPanel footer = new UniTimeHeaderPanel();
            footer.addButton("ok", MESSAGES.buttonOk(), 75, new ClickHandler() {
                @Override
                public void onClick(ClickEvent event) {
                    int colSetup = getHeader(MESSAGES.colSetupTimeShort()).getColumn();
                    int colTear = getHeader(MESSAGES.colTeardownTimeShort()).getColumn();
                    int colPubl = getHeader(MESSAGES.colPublishedTime()).getColumn();
                    for (Integer row : rows()) {
                        MeetingInterface meeting = getData(row).getMeeting();
                        if (setupTime.toInteger() != null)
                            meeting.setStartOffset(setupTime.toInteger());
                        if (teardownTime.toInteger() != null)
                            meeting.setEndOffset(-teardownTime.toInteger());
                        ((NumberCell) getWidget(row, colSetup))
                                .setText(String.valueOf(meeting.getStartOffset()));
                        ((NumberCell) getWidget(row, colTear)).setText(String.valueOf(-meeting.getEndOffset()));
                        ((Label) getWidget(row, colPubl)).setText(meeting.getMeetingTime(CONSTANTS));
                    }
                    dialog.hide();
                }
            });
            footer.addButton("cancel", MESSAGES.buttonCancel(), 75, new ClickHandler() {
                @Override
                public void onClick(ClickEvent event) {
                    dialog.hide();
                }
            });
            simple.addBottomRow(footer);
            dialog.setWidget(simple);
            dialog.setText(MESSAGES.dlgChangeOffsets());
            dialog.setEscapeToHide(true);
            dialog.center();
        }

        @Override
        public String getName() {
            return MESSAGES.opChangeOffsets();
        }

        @Override
        public boolean isApplicable(EventMeetingRow data) {
            return isEditable() && data.getMeeting() != null
                    && (data.getMeeting().getId() == null || data.getMeeting().isCanEdit());
        }

        @Override
        public void execute(int row, EventMeetingRow data) {
        }
    });

    UniTimeTableHeader hName = new UniTimeTableHeader(MESSAGES.colName());
    header.add(hName);

    UniTimeTableHeader hSection = new UniTimeTableHeader(MESSAGES.colSection(),
            HasHorizontalAlignment.ALIGN_RIGHT);
    header.add(hSection);

    UniTimeTableHeader hType = new UniTimeTableHeader(MESSAGES.colType());
    header.add(hType);

    UniTimeTableHeader hTitle = new UniTimeTableHeader(MESSAGES.colTitle());
    header.add(hTitle);

    UniTimeTableHeader hNote = new UniTimeTableHeader(MESSAGES.colNote());
    header.add(hNote);

    UniTimeTableHeader hDate = new UniTimeTableHeader(MESSAGES.colDate());
    header.add(hDate);

    UniTimeTableHeader hTimePub = new UniTimeTableHeader(MESSAGES.colPublishedTime());
    header.add(hTimePub);
    UniTimeTableHeader hTimeAll = new UniTimeTableHeader(MESSAGES.colAllocatedTime());
    header.add(hTimeAll);
    UniTimeTableHeader hTimeSetup = new UniTimeTableHeader(MESSAGES.colSetupTimeShort(),
            HasHorizontalAlignment.ALIGN_RIGHT);
    header.add(hTimeSetup);
    UniTimeTableHeader hTimeTeardown = new UniTimeTableHeader(MESSAGES.colTeardownTimeShort(),
            HasHorizontalAlignment.ALIGN_RIGHT);
    header.add(hTimeTeardown);

    UniTimeTableHeader hLocation = new UniTimeTableHeader(MESSAGES.colLocation());
    header.add(hLocation);

    UniTimeTableHeader hCapacity = new UniTimeTableHeader(MESSAGES.colCapacity(),
            HasHorizontalAlignment.ALIGN_RIGHT);
    header.add(hCapacity);

    UniTimeTableHeader hEnrollment = new UniTimeTableHeader(MESSAGES.colEnrollment(),
            HasHorizontalAlignment.ALIGN_RIGHT);
    header.add(hEnrollment);

    UniTimeTableHeader hLimit = new UniTimeTableHeader(MESSAGES.colLimit(), HasHorizontalAlignment.ALIGN_RIGHT);
    header.add(hLimit);

    UniTimeTableHeader hSponsor = new UniTimeTableHeader(MESSAGES.colSponsorOrInstructor());
    header.add(hSponsor);

    UniTimeTableHeader hContact = new UniTimeTableHeader(MESSAGES.colMainContact());
    header.add(hContact);

    UniTimeTableHeader hApproval = new UniTimeTableHeader(MESSAGES.colApproval());
    header.add(hApproval);

    UniTimeTableHeader hLastChange = new UniTimeTableHeader(MESSAGES.colLastChange());
    header.add(hLastChange);

    addRow(null, header);

    final Operation titleOp = addHideOperation(hTitle, EventFlag.SHOW_TITLE, new Check() {
        @Override
        public boolean isChecked() {
            return true;
        }
    });
    final Operation noteOp = addHideOperation(hNote, EventFlag.SHOW_NOTE, new Check() {
        @Override
        public boolean isChecked() {
            return !titleOp.isApplicable();
        }
    });
    addHideOperation(hTimePub, EventFlag.SHOW_PUBLISHED_TIME, new Check() {
        @Override
        public boolean isChecked() {
            return !titleOp.isApplicable() && !noteOp.isApplicable();
        }
    });
    addHideOperation(hTimeAll, EventFlag.SHOW_ALLOCATED_TIME);
    addHideOperation(hTimeSetup, EventFlag.SHOW_SETUP_TIME);
    addHideOperation(hTimeTeardown, EventFlag.SHOW_TEARDOWN_TIME);
    addHideOperation(hCapacity, EventFlag.SHOW_CAPACITY);
    addHideOperation(hEnrollment, EventFlag.SHOW_ENROLLMENT);
    addHideOperation(hLimit, EventFlag.SHOW_LIMIT);
    addHideOperation(hSponsor, EventFlag.SHOW_SPONSOR);
    addHideOperation(hContact, EventFlag.SHOW_MAIN_CONTACT);
    addHideOperation(hApproval, EventFlag.SHOW_APPROVAL);
    addHideOperation(hLastChange, EventFlag.SHOW_LAST_CHANGE);

    Operation hideDuplicitiesForMeetings = new AriaOperation() {
        @Override
        public boolean isApplicable() {
            return iMode.hasFlag(ModeFlag.CanHideDuplicitiesForMeetings);
        }

        @Override
        public boolean hasSeparator() {
            return true;
        }

        @Override
        public void execute() {
            EventCookie.getInstance()
                    .setHideDuplicitiesForMeetings(!EventCookie.getInstance().isHideDuplicitiesForMeetings());
            int colDate = getHeader(MESSAGES.colDate()).getColumn();
            int colApproval = getHeader(MESSAGES.colApproval()).getColumn();
            for (int row = 1; row < getRowCount(); row++) {
                EventMeetingRow data = getData(row);
                if (data == null)
                    continue;
                EventInterface event = data.getEvent();
                String[] mtgs = new String[] { "", "", "", "", "", "", "" };
                String prevApproval = null;
                String[] prev = null;
                String prevSpan = null;
                String approval = "";
                boolean globalUnavailability = event != null && event.getId() != null && event.getId() < 0
                        && event.getType() == EventType.Unavailabile;
                for (MultiMeetingInterface m : EventInterface.getMultiMeetings(
                        data.getMeetings(getMeetingFilter()), true,
                        globalUnavailability ? null : iPropertiesProvider,
                        event == null ? null : event.getType())) {
                    String[] mtg = new String[] {
                            m.isArrangeHours() ? event.hasMessage()
                                    ? event.getMessage()
                                    : CONSTANTS.arrangeHours()
                                    : (m.getDays(CONSTANTS) + " "
                                            + (m.getNrMeetings() == 1
                                                    ? sDateFormatLong.format(m.getFirstMeetingDate())
                                                    : sDateFormatShort.format(m.getFirstMeetingDate()) + " - "
                                                            + sDateFormatLong.format(m.getLastMeetingDate()))),
                            m.isArrangeHours() && event.hasMessage() ? CONSTANTS.arrangeHours()
                                    : m.getMeetings().first().getMeetingTime(CONSTANTS),
                            m.getMeetings().first().getAllocatedTime(CONSTANTS),
                            String.valueOf(m.getMeetings().first().getStartOffset()),
                            String.valueOf(-m.getMeetings().first().getEndOffset()),
                            m.getLocationNameWithHint(),
                            (m.getMeetings().first().getLocation() == null ? ""
                                    : m.getMeetings().first().getLocation().hasSize()
                                            ? m.getMeetings().first().getLocation().getSize().toString()
                                            : MESSAGES.notApplicable()) };
                    if (!m.isArrangeHours() && !m.isPast()) {
                        SessionMonth.Flag dateFlag = (globalUnavailability || iPropertiesProvider == null ? null
                                : iPropertiesProvider.getDateFlag(event == null ? null : event.getType(),
                                        m.getFirstMeetingDate()));
                        if (dateFlag != null) {
                            switch (dateFlag) {
                            case FINALS:
                                mtg[0] = "<span class='finals' title=\"" + MESSAGES.hintFinals() + "\">"
                                        + mtg[0] + "</span>";
                                break;
                            case MIDTERMS:
                                mtg[0] = "<span class='midterms' title=\"" + MESSAGES.hintMidterms() + "\">"
                                        + mtg[0] + "</span>";
                                break;
                            case BREAK:
                                mtg[0] = "<span class='break' title=\"" + MESSAGES.hintBreak() + "\">" + mtg[0]
                                        + "</span>";
                                break;
                            case HOLIDAY:
                                mtg[0] = "<span class='holiday' title=\"" + MESSAGES.hintHoliday() + "\">"
                                        + mtg[0] + "</span>";
                                break;
                            case WEEKEND:
                                mtg[0] = "<span class='weekend' title=\"" + MESSAGES.hintWeekend() + "\">"
                                        + mtg[0] + "</span>";
                                break;
                            }
                        }
                    }
                    if (!m.isArrangeHours() && iPropertiesProvider != null && iPropertiesProvider.isTooEarly(
                            m.getMeetings().first().getStartSlot(), m.getMeetings().first().getEndSlot())) {
                        for (int i = 1; i <= 2; i++)
                            mtg[i] = "<span class='early' title=\"" + MESSAGES.hintTooEarly() + "\">" + mtg[i]
                                    + "</span>";
                    }
                    String span = "";
                    if (m.getApprovalStatus() == ApprovalStatus.Cancelled)
                        span = "cancelled-meeting";
                    else if (m.getApprovalStatus() == ApprovalStatus.Rejected)
                        span = "rejected-meeting";
                    else if (m.isPast())
                        span = "past-meeting";
                    for (int i = 0; i < mtgs.length; i++) {
                        mtgs[i] += (mtgs[i].isEmpty() ? "" : "<br>") + (prev != null && span.equals(prevSpan)
                                && prev[i == 6 ? i - 1 : i].equals(mtg[i == 6 ? i - 1 : i])
                                        ? MESSAGES.repeatingSymbol()
                                        : (!span.isEmpty() ? "<span class='" + span + "'>" : "") + mtg[i]
                                                + (!span.isEmpty() ? "</span>" : ""));
                    }
                    String thisApproval = (m.getApprovalStatus() == ApprovalStatus.Approved
                            ? sDateFormatApproval.format(m.getApprovalDate())
                            : m.getApprovalStatus() == ApprovalStatus.Cancelled ? MESSAGES.approvalCancelled()
                                    : m.getApprovalStatus() == ApprovalStatus.Rejected
                                            ? MESSAGES.approvalRejected()
                                            : "");

                    approval += (approval.isEmpty() ? "" : "<br>")
                            + (prev != null && span.equals(prevSpan) && prevApproval.equals(thisApproval)
                                    ? MESSAGES.repeatingSymbol()
                                    : (m.getApprovalStatus() == ApprovalStatus.Approved
                                            ? m.isPast() ? "<span class='past-meeting'>"
                                                    + sDateFormatApproval.format(m.getApprovalDate())
                                                    + "</span>"
                                                    : sDateFormatApproval.format(m.getApprovalDate())
                                            : m.getApprovalStatus() == ApprovalStatus.Cancelled
                                                    ? "<span class='cancelled-meeting'>"
                                                            + MESSAGES.approvalCancelled() + "</span>"
                                                    : m.getApprovalStatus() == ApprovalStatus.Rejected
                                                            ? "<span class='rejected-meeting'>"
                                                                    + MESSAGES.approvalRejected() + "</span>"
                                                            : event != null
                                                                    && event.getType() == EventType.Unavailabile
                                                                            ? ""
                                                                            : m.getFirstMeetingDate() == null
                                                                                    ? ""
                                                                                    : m.isPast()
                                                                                            ? "<span class='not-approved-past'>"
                                                                                                    + MESSAGES
                                                                                                            .approvalNotApprovedPast()
                                                                                                    + "</span>"
                                                                                            : event != null
                                                                                                    && event.getExpirationDate() != null
                                                                                                            ? "<span class='not-approved'>"
                                                                                                                    + MESSAGES
                                                                                                                            .approvalExpire(
                                                                                                                                    sDateFormatExpiration
                                                                                                                                            .format(event
                                                                                                                                                    .getExpirationDate()))
                                                                                                                    + "</span>"
                                                                                                            : "<span class='not-approved'>"
                                                                                                                    + MESSAGES
                                                                                                                            .approvalNotApproved()
                                                                                                                    + "</span>"));
                    if (EventCookie.getInstance().isHideDuplicitiesForMeetings()) {
                        prev = mtg;
                        prevSpan = span;
                        prevApproval = thisApproval;
                    }
                }
                for (int i = 0; i < mtgs.length; i++) {
                    if (i == 3 || i == 4 || i == 6)
                        setWidget(row, colDate + i, new NumberCell(mtgs[i]));
                    else
                        setWidget(row, colDate + i, new HTML(mtgs[i], false));
                }
                setWidget(row, colApproval, new HTML(approval == null ? "" : approval, false));
            }
        }

        @Override
        public String getName() {
            return EventCookie.getInstance().isHideDuplicitiesForMeetings()
                    ? MESSAGES.opUncheck(MESSAGES.opHideRepeatingInformation())
                    : MESSAGES.opCheck(MESSAGES.opHideRepeatingInformation());
        }

        @Override
        public String getAriaLabel() {
            return EventCookie.getInstance().isHideDuplicitiesForMeetings()
                    ? ARIA.opUncheck(MESSAGES.opHideRepeatingInformation())
                    : ARIA.opCheck(MESSAGES.opHideRepeatingInformation());
        }
    };
    hDate.addOperation(hideDuplicitiesForMeetings);
    hTimePub.addOperation(hideDuplicitiesForMeetings);
    hTimeAll.addOperation(hideDuplicitiesForMeetings);
    hTimeSetup.addOperation(hideDuplicitiesForMeetings);
    hTimeTeardown.addOperation(hideDuplicitiesForMeetings);
    hLocation.addOperation(hideDuplicitiesForMeetings);
    hCapacity.addOperation(hideDuplicitiesForMeetings);
    hApproval.addOperation(hideDuplicitiesForMeetings);

    addSortByOperation(hName, EventMeetingSortBy.NAME);
    addSortByOperation(hSection, EventMeetingSortBy.SECTION);
    addSortByOperation(hType, EventMeetingSortBy.TYPE);
    addSortByOperation(hTitle, EventMeetingSortBy.TITLE);
    addSortByOperation(hNote, EventMeetingSortBy.NOTE);
    addSortByOperation(hDate, EventMeetingSortBy.DATE);
    addSortByOperation(hTimePub, EventMeetingSortBy.PUBLISHED_TIME);
    addSortByOperation(hTimeAll, EventMeetingSortBy.ALLOCATED_TIME);
    addSortByOperation(hTimeSetup, EventMeetingSortBy.SETUP_TIME);
    addSortByOperation(hTimeTeardown, EventMeetingSortBy.TEARDOWN_TIME);
    addSortByOperation(hLocation, EventMeetingSortBy.LOCATION);
    addSortByOperation(hCapacity, EventMeetingSortBy.CAPACITY);
    addSortByOperation(hEnrollment, EventMeetingSortBy.ENROLLMENT);
    addSortByOperation(hLimit, EventMeetingSortBy.LIMIT);
    addSortByOperation(hSponsor, EventMeetingSortBy.SPONSOR);
    addSortByOperation(hContact, EventMeetingSortBy.MAIN_CONTACT);
    addSortByOperation(hApproval, EventMeetingSortBy.APPROVAL);
    addSortByOperation(hLastChange, EventMeetingSortBy.LAST_CHANGE);

    hTimes.addOperation(new AriaOperation() {
        @Override
        public void execute() {
            EventCookie.getInstance().setAutomaticallyApproveNewMeetings(
                    !EventCookie.getInstance().isAutomaticallyApproveNewMeetings());
            for (int row = 1; row < getRowCount(); row++) {
                EventMeetingRow data = getData(row);
                if (data.hasMeeting() && data.getMeeting().getId() == null && data.getMeeting().isCanApprove()
                        && data.hasEvent() && (data.getEvent().getType() == EventType.Special
                                || data.getEvent().getType() == EventType.Course)) {
                    HTML approval = (HTML) getWidget(row, getHeader(MESSAGES.colApproval()).getColumn());
                    if (EventCookie.getInstance().isAutomaticallyApproveNewMeetings()) {
                        approval.setStyleName("new-approved-meeting");
                        approval.setText(MESSAGES.approvelNewApprovedMeeting());
                    } else {
                        approval.setStyleName("new-meeting");
                        approval.setText(MESSAGES.approvalNewMeeting());
                    }
                }
            }
            ValueChangeEvent.fire(EventMeetingTable.this, getValue());
        }

        @Override
        public boolean isApplicable() {
            for (int row = 1; row < getRowCount(); row++) {
                EventMeetingRow data = getData(row);
                if (data.hasMeeting() && data.getMeeting().getId() == null && data.getMeeting().isCanApprove()
                        && data.hasEvent() && (data.getEvent().getType() == EventType.Special
                                || data.getEvent().getType() == EventType.Course))
                    return true;
            }
            return false;
        }

        @Override
        public boolean hasSeparator() {
            return true;
        }

        @Override
        public String getName() {
            return EventCookie.getInstance().isAutomaticallyApproveNewMeetings()
                    ? MESSAGES.opUncheck(MESSAGES.opAutomaticApproval())
                    : MESSAGES.opCheck(MESSAGES.opAutomaticApproval());
        }

        @Override
        public String getAriaLabel() {
            return EventCookie.getInstance().isAutomaticallyApproveNewMeetings()
                    ? ARIA.opUncheck(MESSAGES.opAutomaticApproval())
                    : ARIA.opCheck(MESSAGES.opAutomaticApproval());
        }

    });

    for (int i = 0; i < getCellCount(0); i++)
        getCellFormatter().setStyleName(0, i, "unitime-ClickableTableHeaderNoBorderLine");

    resetColumnVisibility();
}

From source file:org.unitime.timetable.gwt.client.events.RoomFilterBox.java

License:Apache License

public RoomFilterBox(AcademicSessionProvider session) {
    super(session);

    iDepartments = new ListBox();
    iDepartments.setMultipleSelect(false);
    iDepartments.setWidth("100%");

    iDepartmentFilter = new FilterBox.CustomFilter("department", MESSAGES.tagDepartment(), iDepartments) {
        @Override/*from w  w  w .j av a2s.co  m*/
        public void getSuggestions(List<Chip> chips, String text,
                AsyncCallback<Collection<Suggestion>> callback) {
            if (text.isEmpty()) {
                callback.onSuccess(null);
            } else {
                Chip oldChip = getChip("department");
                List<Suggestion> suggestions = new ArrayList<Suggestion>();
                for (int i = 0; i < iDepartments.getItemCount(); i++) {
                    Chip chip = new Chip("department", iDepartments.getValue(i))
                            .withTranslatedCommand(MESSAGES.tagDepartment());
                    String name = iDepartments.getItemText(i);
                    if (iDepartments.getValue(i).toLowerCase().startsWith(text.toLowerCase())) {
                        suggestions.add(new Suggestion(name, chip, oldChip));
                    } else if (text.length() > 2 && (name.toLowerCase().contains(" " + text.toLowerCase())
                            || name.toLowerCase().contains(" (" + text.toLowerCase()))) {
                        suggestions.add(new Suggestion(name, chip, oldChip));
                    }
                }
                if ("department".startsWith(text.toLowerCase()) && text.toLowerCase().length() >= 5) {
                    for (int i = 0; i < iDepartments.getItemCount(); i++) {
                        Chip chip = new Chip("department", iDepartments.getValue(i))
                                .withTranslatedCommand(MESSAGES.tagDepartment());
                        String name = iDepartments.getItemText(i);
                        if (!chip.equals(oldChip))
                            suggestions.add(new Suggestion(name, chip, oldChip));
                    }
                }
                callback.onSuccess(suggestions);
            }
        }

        @Override
        public void validate(String value, AsyncCallback<Chip> callback) {
            String translatedValue = null;
            if ("managed".equalsIgnoreCase(value))
                translatedValue = MESSAGES.attrDepartmentManagedRooms();
            callback.onSuccess(new Chip(getCommand(), value).withTranslatedCommand(getLabel())
                    .withTranslatedValue(translatedValue));
        }
    };
    iDepartmentFilter.setVisible(false);
    addFilter(iDepartmentFilter);
    iDepartments.addChangeHandler(new ChangeHandler() {
        @Override
        public void onChange(ChangeEvent event) {
            Chip oldChip = getChip("department");
            Chip newChip = (iDepartments.getSelectedIndex() <= 0 ? null
                    : new Chip("department", iDepartments.getValue(iDepartments.getSelectedIndex()))
                            .withTranslatedCommand(MESSAGES.tagDepartment()));
            if (oldChip != null) {
                if (newChip == null) {
                    removeChip(oldChip, true);
                } else {
                    if (!oldChip.getValue().equals(newChip.getValue())) {
                        removeChip(oldChip, false);
                        addChip(newChip, true);
                    }
                }
            } else {
                if (newChip != null)
                    addChip(newChip, true);
            }
        }
    });

    addFilter(new FilterBox.StaticSimpleFilter("type", MESSAGES.tagRoomType()));
    addFilter(new FilterBox.StaticSimpleFilter("feature", MESSAGES.tagRoomFeature()));
    addFilter(new FilterBox.StaticSimpleFilter("group", MESSAGES.tagRoomGroup()));
    addFilter(new FilterBox.StaticSimpleFilter("size", MESSAGES.tagRoomSize()));
    addFilter(new FilterBox.StaticSimpleFilter("flag", MESSAGES.tagRoomFlag()) {
        @Override
        public void validate(String text, AsyncCallback<Chip> callback) {
            String translatedValue = null;
            if ("all".equalsIgnoreCase(text))
                translatedValue = MESSAGES.attrFlagAllRooms();
            else if ("event".equalsIgnoreCase(text))
                translatedValue = MESSAGES.attrFlagEventRooms();
            else if ("nearby".equalsIgnoreCase(text))
                translatedValue = MESSAGES.attrFlagNearbyRooms();
            callback.onSuccess(new Chip(getCommand(), text).withTranslatedCommand(getLabel())
                    .withTranslatedValue(translatedValue));
        }
    });

    iBuildings = new ListBox();
    iBuildings.setMultipleSelect(true);
    iBuildings.setWidth("100%");
    iBuildings.setVisibleItemCount(3);

    addFilter(new FilterBox.CustomFilter("building", MESSAGES.tagBuilding(), iBuildings) {
        @Override
        public void getSuggestions(List<Chip> chips, String text,
                AsyncCallback<Collection<Suggestion>> callback) {
            if (text.isEmpty()) {
                callback.onSuccess(null);
            } else {
                List<Suggestion> suggestions = new ArrayList<Suggestion>();
                for (int i = 0; i < iBuildings.getItemCount(); i++) {
                    Chip chip = new Chip("building", iBuildings.getValue(i))
                            .withTranslatedCommand(MESSAGES.tagBuilding());
                    String name = iBuildings.getItemText(i);
                    if (iBuildings.getValue(i).toLowerCase().startsWith(text.toLowerCase())) {
                        suggestions.add(new Suggestion(name, chip));
                    } else if (text.length() > 2 && name.toLowerCase().contains(" " + text.toLowerCase())) {
                        suggestions.add(new Suggestion(name, chip));
                    }
                }
                if ("building".startsWith(text.toLowerCase()) && text.toLowerCase().length() >= 5) {
                    for (int i = 0; i < iBuildings.getItemCount(); i++) {
                        Chip chip = new Chip("building", iBuildings.getValue(i))
                                .withTranslatedCommand(MESSAGES.tagBuilding());
                        String name = iBuildings.getItemText(i);
                        suggestions.add(new Suggestion(name, chip));
                    }
                }
                callback.onSuccess(suggestions);
            }
        }

        @Override
        public boolean isVisible() {
            return iBuildings.getItemCount() > 0;
        }
    });
    iBuildings.addChangeHandler(new ChangeHandler() {
        @Override
        public void onChange(ChangeEvent event) {
            boolean changed = false;
            for (int i = 0; i < iBuildings.getItemCount(); i++) {
                Chip chip = new Chip("building", iBuildings.getValue(i))
                        .withTranslatedCommand(MESSAGES.tagBuilding());
                if (iBuildings.isItemSelected(i)) {
                    if (!hasChip(chip)) {
                        addChip(chip, false);
                        changed = true;
                    }
                } else {
                    if (hasChip(chip)) {
                        removeChip(chip, false);
                        changed = true;
                    }
                }
            }
            if (changed)
                fireValueChangeEvent();
        }
    });

    Label l1 = new Label(MESSAGES.propMin());

    iMin = new TextBox();
    iMin.setStyleName("unitime-TextArea");
    iMin.setMaxLength(10);
    iMin.getElement().getStyle().setWidth(50, Unit.PX);

    Label l2 = new Label(MESSAGES.propMax());
    l2.getElement().getStyle().setMarginLeft(10, Unit.PX);

    iMax = new TextBox();
    iMax.setMaxLength(10);
    iMax.getElement().getStyle().setWidth(50, Unit.PX);
    iMax.setStyleName("unitime-TextArea");

    final CheckBox events = new CheckBox(MESSAGES.checkOnlyEventLocations());
    events.getElement().getStyle().setMarginLeft(10, Unit.PX);

    final CheckBox nearby = new CheckBox(MESSAGES.checkIncludeNearby());
    nearby.getElement().getStyle().setMarginLeft(10, Unit.PX);

    addFilter(new FilterBox.CustomFilter("other", MESSAGES.tagOther(), l1, iMin, l2, iMax, events, nearby) {
        @Override
        public void getSuggestions(final List<Chip> chips, final String text,
                AsyncCallback<Collection<FilterBox.Suggestion>> callback) {
            if (text.isEmpty()) {
                callback.onSuccess(null);
            } else {
                List<FilterBox.Suggestion> suggestions = new ArrayList<FilterBox.Suggestion>();
                if (MESSAGES.attrFlagNearbyRooms().toLowerCase().startsWith(text.toLowerCase())
                        || "nearby".startsWith(text.toLowerCase())
                        || MESSAGES.checkIncludeNearby().toLowerCase().startsWith(text.toLowerCase())) {
                    suggestions.add(new Suggestion(MESSAGES.checkIncludeNearby(),
                            new Chip("flag", "Nearby").withTranslatedCommand(MESSAGES.tagRoomFlag())
                                    .withTranslatedValue(MESSAGES.attrFlagNearbyRooms())));
                } else if (MESSAGES.attrFlagAllRooms().toLowerCase().startsWith(text.toLowerCase())
                        || "all".startsWith(text.toLowerCase())
                        || MESSAGES.checkAllLocations().toLowerCase().startsWith(text.toLowerCase())) {
                    suggestions.add(new Suggestion(MESSAGES.checkAllLocations(),
                            new Chip("flag", "All").withTranslatedCommand(MESSAGES.tagRoomFlag())
                                    .withTranslatedValue(MESSAGES.attrFlagAllRooms()),
                            new Chip("flag", "Event").withTranslatedCommand(MESSAGES.tagRoomFlag())
                                    .withTranslatedValue(MESSAGES.attrFlagEventRooms())));
                } else if (MESSAGES.attrFlagEventRooms().toLowerCase().startsWith(text.toLowerCase())
                        || "event".startsWith(text.toLowerCase())
                        || MESSAGES.checkOnlyEventLocations().toLowerCase().startsWith(text.toLowerCase())) {
                    suggestions.add(new Suggestion(MESSAGES.checkOnlyEventLocations(),
                            new Chip("flag", "Event").withTranslatedCommand(MESSAGES.tagRoomFlag())
                                    .withTranslatedValue(MESSAGES.attrFlagEventRooms()),
                            new Chip("flag", "All").withTranslatedCommand(MESSAGES.tagRoomFlag())
                                    .withTranslatedValue(MESSAGES.attrFlagAllRooms())));
                } else {
                    Chip old = null;
                    for (Chip c : chips) {
                        if (c.getCommand().equals("size")) {
                            old = c;
                            break;
                        }
                    }
                    try {
                        String number = text;
                        String prefix = "";
                        if (text.startsWith("<=") || text.startsWith(">=")) {
                            number = number.substring(2);
                            prefix = text.substring(0, 2);
                        } else if (text.startsWith("<") || text.startsWith(">")) {
                            number = number.substring(1);
                            prefix = text.substring(0, 1);
                        }
                        Integer.parseInt(number);
                        suggestions.add(new Suggestion(
                                new Chip("size", text).withTranslatedCommand(MESSAGES.tagRoomSize()), old));
                        if (prefix.isEmpty()) {
                            suggestions.add(new Suggestion(
                                    new Chip("size", "<=" + text).withTranslatedCommand(MESSAGES.tagRoomSize()),
                                    old));
                            suggestions.add(new Suggestion(
                                    new Chip("size", ">=" + text).withTranslatedCommand(MESSAGES.tagRoomSize()),
                                    old));
                        }
                    } catch (Exception e) {
                    }
                    if (text.contains("..")) {
                        try {
                            String first = text.substring(0, text.indexOf('.'));
                            String second = text.substring(text.indexOf("..") + 2);
                            Integer.parseInt(first);
                            Integer.parseInt(second);
                            suggestions.add(new Suggestion(
                                    new Chip("size", text).withTranslatedCommand(MESSAGES.tagRoomSize()), old));
                        } catch (Exception e) {
                        }
                    }
                }
                callback.onSuccess(suggestions);
            }
        }

    });

    iMin.addChangeHandler(new ChangeHandler() {
        @Override
        public void onChange(ChangeEvent event) {
            sizeChanged(true);
        }
    });
    iMax.addChangeHandler(new ChangeHandler() {
        @Override
        public void onChange(ChangeEvent event) {
            sizeChanged(true);
        }
    });

    iMin.addKeyPressHandler(new KeyPressHandler() {
        @Override
        public void onKeyPress(KeyPressEvent event) {
            Scheduler.get().scheduleDeferred(new ScheduledCommand() {
                @Override
                public void execute() {
                    sizeChanged(false);
                }
            });
        }
    });
    iMax.addKeyPressHandler(new KeyPressHandler() {
        @Override
        public void onKeyPress(KeyPressEvent event) {
            Scheduler.get().scheduleDeferred(new ScheduledCommand() {
                @Override
                public void execute() {
                    sizeChanged(false);
                }
            });
        }
    });

    iMin.addKeyUpHandler(new KeyUpHandler() {
        @Override
        public void onKeyUp(KeyUpEvent event) {
            if (event.getNativeKeyCode() == KeyCodes.KEY_BACKSPACE)
                Scheduler.get().scheduleDeferred(new ScheduledCommand() {
                    @Override
                    public void execute() {
                        sizeChanged(false);
                    }
                });
        }
    });
    iMax.addKeyUpHandler(new KeyUpHandler() {
        @Override
        public void onKeyUp(KeyUpEvent event) {
            if (event.getNativeKeyCode() == KeyCodes.KEY_BACKSPACE)
                Scheduler.get().scheduleDeferred(new ScheduledCommand() {
                    @Override
                    public void execute() {
                        sizeChanged(false);
                    }
                });
        }
    });
    iMin.addBlurHandler(new BlurHandler() {
        @Override
        public void onBlur(BlurEvent event) {
            sizeChanged(true);
        }
    });
    iMax.addBlurHandler(new BlurHandler() {
        @Override
        public void onBlur(BlurEvent event) {
            sizeChanged(true);
        }
    });

    nearby.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
        @Override
        public void onValueChange(ValueChangeEvent<Boolean> event) {
            Chip chip = new Chip("flag", "Nearby").withTranslatedCommand(MESSAGES.tagRoomFlag())
                    .withTranslatedValue(MESSAGES.attrFlagNearbyRooms());
            if (event.getValue()) {
                if (!hasChip(chip))
                    addChip(chip, true);
            } else {
                if (hasChip(chip))
                    removeChip(chip, true);
            }
        }
    });
    nearby.addMouseDownHandler(new MouseDownHandler() {
        @Override
        public void onMouseDown(MouseDownEvent event) {
            event.getNativeEvent().stopPropagation();
            event.getNativeEvent().preventDefault();
        }
    });

    events.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
        @Override
        public void onValueChange(ValueChangeEvent<Boolean> event) {
            Chip eventChip = new Chip("flag", "Event").withTranslatedCommand(MESSAGES.tagRoomFlag())
                    .withTranslatedValue(MESSAGES.attrFlagEventRooms());
            Chip allChip = new Chip("flag", "All").withTranslatedCommand(MESSAGES.tagRoomFlag())
                    .withTranslatedValue(MESSAGES.attrFlagAllRooms());
            if (event.getValue()) {
                if (!hasChip(eventChip))
                    addChip(eventChip, true);
                if (hasChip(allChip))
                    removeChip(allChip, true);
            } else {
                if (hasChip(eventChip))
                    removeChip(eventChip, true);
                if (!hasChip(allChip))
                    addChip(allChip, true);
            }
        }
    });
    events.addMouseDownHandler(new MouseDownHandler() {
        @Override
        public void onMouseDown(MouseDownEvent event) {
            event.getNativeEvent().stopPropagation();
            event.getNativeEvent().preventDefault();
        }
    });

    addValueChangeHandler(new ValueChangeHandler<String>() {
        @Override
        public void onValueChange(ValueChangeEvent<String> event) {
            iLastSize = getChip("size");
            if (!isFilterPopupShowing()) {
                nearby.setValue(hasChip(new Chip("flag", "Nearby").withTranslatedCommand(MESSAGES.tagRoomFlag())
                        .withTranslatedValue(MESSAGES.attrFlagNearbyRooms())));
                events.setValue(hasChip(new Chip("flag", "Event").withTranslatedCommand(MESSAGES.tagRoomFlag())
                        .withTranslatedValue(MESSAGES.attrFlagEventRooms())));
                Chip size = getChip("size");
                if (size != null) {
                    if (size.getValue().startsWith("<=")) {
                        iMin.setText("");
                        iMax.setText(size.getValue().substring(2));
                    } else if (size.getValue().startsWith("<")) {
                        try {
                            iMax.setText(String.valueOf(Integer.parseInt(size.getValue().substring(1)) - 1));
                            iMin.setText("");
                        } catch (Exception e) {
                        }
                    } else if (size.getValue().startsWith(">=")) {
                        iMin.setText(size.getValue().substring(2));
                        iMax.setText("");
                    } else if (size.getValue().startsWith(">")) {
                        try {
                            iMin.setText(String.valueOf(Integer.parseInt(size.getValue().substring(1)) + 1));
                            iMax.setText("");
                        } catch (Exception e) {
                        }
                    } else if (size.getValue().contains("..")) {
                        iMin.setText(size.getValue().substring(0, size.getValue().indexOf("..")));
                        iMax.setText(size.getValue().substring(size.getValue().indexOf("..") + 2));
                    } else {
                        iMin.setText(size.getValue());
                        iMax.setText(size.getValue());
                    }
                } else {
                    iMin.setText("");
                    iMax.setText("");
                }
                for (int i = 0; i < iBuildings.getItemCount(); i++) {
                    String value = iBuildings.getValue(i);
                    iBuildings.setItemSelected(i,
                            hasChip(new Chip("building", value).withTranslatedCommand(MESSAGES.tagBuilding())));
                }
                iDepartments.setSelectedIndex(0);
                for (int i = 1; i < iDepartments.getItemCount(); i++) {
                    String value = iDepartments.getValue(i);
                    if (hasChip(
                            new Chip("department", value).withTranslatedCommand(MESSAGES.tagDepartment()))) {
                        iDepartments.setSelectedIndex(i);
                        break;
                    }
                }
            }
            if (getAcademicSessionId() != null)
                init(false, getAcademicSessionId(), new Command() {
                    @Override
                    public void execute() {
                        if (isFilterPopupShowing())
                            showFilterPopup();
                    }
                });
            setAriaLabel(ARIA.roomFilter(toAriaString()));
        }
    });

    addFocusHandler(new FocusHandler() {
        @Override
        public void onFocus(FocusEvent event) {
            setAriaLabel(ARIA.roomFilter(toAriaString()));
        }
    });
}

From source file:org.unitime.timetable.gwt.client.hql.SavedHQLPage.java

License:Apache License

public void openDialog(SavedHQLInterface.Query q) {
    iDialogQuery = q;/*from w w w.  j av a2 s .c  o  m*/
    if (iDialog == null) {
        iDialog = new UniTimeDialogBox(true, false);
        iDialogForm = new SimpleForm();
        iDialogName = new UniTimeTextBox(100, 680);
        iDialogForm.addRow(MESSAGES.propName(), iDialogName);
        iDialogDescription = new TextArea();
        iDialogDescription.setStyleName("unitime-TextArea");
        iDialogDescription.setVisibleLines(5);
        iDialogDescription.setCharacterWidth(120);
        iDialogForm.addRow(MESSAGES.propDescription(), iDialogDescription);
        iDialogForm.getCellFormatter().setVerticalAlignment(1, 0, HasVerticalAlignment.ALIGN_TOP);
        iDialogQueryArea = new TextArea();
        iDialogQueryArea.setStyleName("unitime-TextArea");
        iDialogQueryArea.setVisibleLines(10);
        iDialogQueryArea.setCharacterWidth(120);
        iDialogForm.addRow(MESSAGES.propQuery(), iDialogQueryArea);
        iDialogForm.getCellFormatter().setVerticalAlignment(2, 0, HasVerticalAlignment.ALIGN_TOP);
        for (int i = 0; i < iFlags.size(); i++) {
            SavedHQLInterface.Flag f = iFlags.get(i);
            CheckBox ch = new CheckBox(f.getText());
            iDialogForm.addRow(i == 0 ? MESSAGES.propFlags() : "", ch);
        }
        iDialogHeader = new UniTimeHeaderPanel();
        iDialogForm.addBottomRow(iDialogHeader);
        iDialogHeader.addButton("save", MESSAGES.opQuerySave(), 75, new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                iDialogQuery.setName(iDialogName.getText());
                if (iDialogName.getText().isEmpty()) {
                    iDialogHeader.setErrorMessage(MESSAGES.errorNameIsRequired());
                    return;
                }
                iDialogQuery.setDescription(iDialogDescription.getText());
                iDialogQuery.setQuery(iDialogQueryArea.getText());
                if (iDialogQueryArea.getText().isEmpty()) {
                    iDialogHeader.setErrorMessage(MESSAGES.errorQueryIsRequired());
                    return;
                }
                int flags = 0;
                boolean hasAppearance = false;
                for (int i = 0; i < iFlags.size(); i++) {
                    SavedHQLInterface.Flag f = iFlags.get(i);
                    CheckBox ch = (CheckBox) iDialogForm.getWidget(3 + i, 1);
                    if (ch.getValue()) {
                        flags += f.getValue();
                        if (f.isAppearance())
                            hasAppearance = true;
                    }
                }
                if (!hasAppearance) {
                    iDialogHeader.setErrorMessage(MESSAGES.errorNoAppearanceSelected());
                    return;
                }
                iDialogQuery.setFlags(flags);
                RPC.execute(new HQLStoreRpcRequest(iDialogQuery), new AsyncCallback<GwtRpcResponseLong>() {
                    @Override
                    public void onFailure(Throwable caught) {
                        iDialogHeader.setErrorMessage(caught.getMessage());
                    }

                    @Override
                    public void onSuccess(GwtRpcResponseLong result) {
                        iDialog.hide();
                        loadQueries(result.getValue(), false);
                    }
                });
            }
        });
        iDialogHeader.addButton("test", MESSAGES.opQueryTest(), 75, new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                if (iDialogQueryArea.getText().isEmpty()) {
                    iDialogHeader.setErrorMessage(MESSAGES.errorQueryIsRequired());
                    return;
                }
                iDialogQuery.setQuery(iDialogQueryArea.getText());
                LoadingWidget.getInstance().show(MESSAGES.waitTestingQuery());
                HQLExecuteRpcRequest request = new HQLExecuteRpcRequest();
                request.setQuery(iDialogQuery);
                request.setFromRow(0);
                request.setMaxRows(101);
                RPC.execute(request, new AsyncCallback<Table>() {
                    @Override
                    public void onFailure(Throwable caught) {
                        iDialogHeader.setErrorMessage(MESSAGES.failedTestNoReason());
                        LoadingWidget.getInstance().hide();
                        UniTimeNotifications.error(MESSAGES.failedTest(caught.getMessage()), caught);
                    }

                    @Override
                    public void onSuccess(Table result) {
                        iDialogHeader.setMessage(result.size() <= 1 ? MESSAGES.infoTestSucceededNoResults()
                                : result.size() > 101 ? MESSAGES.infoTestSucceededWith100OrMoreRows()
                                        : MESSAGES.infoTestSucceededWithRows(result.size() - 1));
                        LoadingWidget.getInstance().hide();
                    }
                });
            }
        });
        iDialogHeader.addButton("export", MESSAGES.opScriptExport(), new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                RPC.execute(EncodeQueryRpcRequest.encode("output=hql.xml&id=" + iDialogQuery.getId()),
                        new AsyncCallback<EncodeQueryRpcResponse>() {
                            @Override
                            public void onFailure(Throwable caught) {
                            }

                            @Override
                            public void onSuccess(EncodeQueryRpcResponse result) {
                                ToolBox.open(GWT.getHostPageBaseURL() + "export?q=" + result.getQuery());
                            }
                        });
            }
        });
        iDialogHeader.addButton("delete", MESSAGES.opQueryDelete(), 75, new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                RPC.execute(new HQLDeleteRpcRequest(iDialogQuery.getId()),
                        new AsyncCallback<GwtRpcResponseBoolean>() {
                            @Override
                            public void onFailure(Throwable caught) {
                                iDialogHeader.setErrorMessage(caught.getMessage());
                            }

                            @Override
                            public void onSuccess(GwtRpcResponseBoolean result) {
                                iDialog.hide();
                                loadQueries(null, false);
                            }
                        });
            }
        });
        iDialogHeader.addButton("back", MESSAGES.opQueryBack(), 75, new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                iDialog.hide();
            }
        });
        iDialog.setWidget(iDialogForm);
    }
    iDialog.setText(q == null ? MESSAGES.dialogNewReport() : MESSAGES.dialogEditReport(q.getName()));
    iDialogHeader.setEnabled("export", q != null);
    iDialogHeader.setEnabled("delete", q != null);
    iDialogHeader.clearMessage();
    iDialogName.setText(q == null ? "" : q.getName());
    iDialogDescription.setText(q == null ? "" : q.getDescription());
    iDialogQueryArea.setText(q == null ? "" : q.getQuery());
    for (int i = 0; i < iFlags.size(); i++) {
        SavedHQLInterface.Flag f = iFlags.get(i);
        CheckBox ch = (CheckBox) iDialogForm.getWidget(3 + i, 1);
        ch.setValue(q == null ? iAppearance.equals(f.getAppearance()) : (q.getFlags() & f.getValue()) != 0);
    }
    if (iDialogQuery == null)
        iDialogQuery = new SavedHQLInterface.Query();
    iDialog.center();
}

From source file:org.unitime.timetable.gwt.client.instructor.InstructorsTable.java

License:Apache License

public InstructorsTable(InstructorAttributePropertiesInterface properties, boolean selectable) {
    setStyleName("unitime-Instructorss");
    iSelectable = selectable;/*from  w  ww.ja  v a2s  . com*/
    iProperties = properties;

    List<UniTimeTableHeader> header = new ArrayList<UniTimeTableHeader>();
    for (InstructorsColumn column : InstructorsColumn.values()) {
        int nrCells = getNbrCells(column);
        for (int idx = 0; idx < nrCells; idx++) {
            UniTimeTableHeader h = new UniTimeTableHeader(getColumnName(column, idx),
                    getColumnAlignment(column, idx));
            header.add(h);
        }
    }

    for (final InstructorsColumn column : InstructorsColumn.values()) {
        if (InstructorComparator.isApplicable(column) && getNbrCells(column) > 0) {
            final UniTimeTableHeader h = header.get(getCellIndex(column));
            Operation op = new SortOperation() {
                @Override
                public void execute() {
                    doSort(column);
                }

                @Override
                public boolean isApplicable() {
                    return getRowCount() > 1 && h.isVisible();
                }

                @Override
                public boolean hasSeparator() {
                    return true;
                }

                @Override
                public String getName() {
                    return MESSAGES.opSortBy(getColumnName());
                }

                @Override
                public String getColumnName() {
                    return h.getHTML().replace("<br>", " ");
                }
            };
            h.addOperation(op);
        }
    }

    addRow(null, header);

    for (int i = 0; i < getCellCount(0); i++)
        getCellFormatter().setStyleName(0, i, "unitime-ClickableTableHeader");

    setSortBy(InstructorCookie.getInstance().getSortAttributesBy());

    if (iSelectable) {
        header.get(0).addOperation(new Operation() {
            @Override
            public void execute() {
                for (int row = 1; row < getRowCount(); row++) {
                    Widget w = getWidget(row, 0);
                    if (w != null && w instanceof CheckBox) {
                        CheckBox ch = (CheckBox) w;
                        ch.setValue(true);
                    }
                    setSelected(row, true);
                }
            }

            @Override
            public boolean isApplicable() {
                for (int row = 1; row < getRowCount(); row++) {
                    Widget w = getWidget(row, 0);
                    if (w != null && w instanceof CheckBox) {
                        CheckBox ch = (CheckBox) w;
                        if (!ch.getValue())
                            return true;
                    }
                }
                return false;
            }

            @Override
            public boolean hasSeparator() {
                return false;
            }

            @Override
            public String getName() {
                return MESSAGES.opSelectAll();
            }
        });
        header.get(0).addOperation(new Operation() {
            @Override
            public void execute() {
                for (int row = 1; row < getRowCount(); row++) {
                    Widget w = getWidget(row, 0);
                    if (w != null && w instanceof CheckBox) {
                        CheckBox ch = (CheckBox) w;
                        ch.setValue(false);
                    }
                    setSelected(row, false);
                }
            }

            @Override
            public boolean isApplicable() {
                for (int row = 1; row < getRowCount(); row++) {
                    Widget w = getWidget(row, 0);
                    if (w != null && w instanceof CheckBox) {
                        CheckBox ch = (CheckBox) w;
                        if (ch.getValue())
                            return true;
                    }
                }
                return false;
            }

            @Override
            public boolean hasSeparator() {
                return false;
            }

            @Override
            public String getName() {
                return MESSAGES.opClearSelection();
            }
        });

        setAllowSelection(true);
        addMouseClickListener(new MouseClickListener<InstructorInterface>() {
            @Override
            public void onMouseClick(TableEvent<InstructorInterface> event) {
                selectInstructor(event.getRow(), isSelected(event.getRow()));
            }
        });
    }
}

From source file:org.unitime.timetable.gwt.client.rooms.RoomEdit.java

License:Apache License

public void setProperties(RoomPropertiesInterface properties) {
    iProperties = properties;/*from  w  w w.ja  v a 2  s. co m*/

    iForm.setColSpan(iProperties.isGoogleMap() ? 3 : 2);

    iBuilding.getWidget().clear();
    iBuilding.getWidget().addItem(MESSAGES.itemSelect(), "-1");
    for (BuildingInterface building : iProperties.getBuildings())
        iBuilding.getWidget().addItem(building.getAbbreviation() + " - " + building.getName(),
                building.getId().toString());

    iCoordinatesFormat.setText(iProperties.getEllipsoid());

    iExaminationRooms.clear();
    iExaminationRoomsPanel.clear();
    for (final ExamTypeInterface type : iProperties.getExamTypes()) {
        final CheckBox ch = new CheckBox(type.getLabel());
        ch.addStyleName("exam");
        iExaminationRooms.put(type.getId(), ch);
        iExaminationRoomsPanel.add(ch);
        ch.setValue(false);
        ch.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
            @Override
            public void onValueChange(ValueChangeEvent<Boolean> event) {
                Integer row = iPeriodPreferencesRow.get(type.getId());
                if (row != null) {
                    PeriodPreferencesWidget pref = iPeriodPreferences.get(type.getId());
                    iForm.getRowFormatter().setVisible(row, event.getValue() && pref != null
                            && pref.getModel() != null && !pref.getModel().getPeriods().isEmpty());
                }
                boolean prefVisible = false;
                for (ExamTypeInterface t : iProperties.getExamTypes()) {
                    if (iExaminationRooms.get(t.getId()).getValue()) {
                        PeriodPreferencesWidget pref = iPeriodPreferences.get(t.getId());
                        if (pref != null && pref.getModel() != null
                                && !pref.getModel().getPeriods().isEmpty()) {
                            prefVisible = true;
                            break;
                        }
                    }
                }
                if (iPeriodPreferencesHeaderRow > 0)
                    iForm.getRowFormatter().setVisible(iPeriodPreferencesHeaderRow, prefVisible);
                if (!event.getValue()) {
                    iExamCapacity.clearHint();
                    iHeader.clearMessage();
                }
            }
        });
    }

    if (iProperties.isGoogleMap() && iGoogleMap == null) {
        iGoogleMap = new AbsolutePanel();
        iGoogleMap.setStyleName("map");

        iGoogleMapControl = new AbsolutePanel();
        iGoogleMapControl.setStyleName("control");
        final TextBox searchBox = new TextBox();
        searchBox.setStyleName("unitime-TextBox");
        searchBox.addStyleName("searchBox");
        searchBox.getElement().setId("mapSearchBox");
        searchBox.setTabIndex(-1);
        iGoogleMapControl.add(searchBox);
        Button button = new Button(MESSAGES.buttonGeocode(), new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                geocodeAddress();
            }
        });
        button.setTabIndex(-1);
        searchBox.addKeyPressHandler(new KeyPressHandler() {
            @Override
            public void onKeyPress(KeyPressEvent event) {
                switch (event.getNativeEvent().getKeyCode()) {
                case KeyCodes.KEY_ENTER:
                    event.preventDefault();
                    geocodeAddress();
                    return;
                }
            }
        });
        button.addStyleName("geocode");
        ToolBox.setWhiteSpace(button.getElement().getStyle(), "nowrap");
        Character accessKey = UniTimeHeaderPanel.guessAccessKey(MESSAGES.buttonGeocode());
        if (accessKey != null)
            button.setAccessKey(accessKey);
        iGoogleMapControl.add(button);

        iGoogleMap.add(iGoogleMapControl);

        addGoogleMap(iGoogleMap.getElement(), iGoogleMapControl.getElement());
    }

    iGroups.clear();
    iGroupPanel.clear();
    iGlobalGroupsPanel = null;
    if (!iProperties.getGroups().isEmpty()) {
        P groups = new P("groups");
        for (GroupInterface group : iProperties.getGroups()) {
            CheckBox ch = new CheckBox(group.getLabel());
            ch.addStyleName("group");
            iGroups.put(group.getId(), ch);
            if (group.getDepartment() != null) {
                P d = iGroupPanel.get(group.getDepartment().getId());
                if (d == null) {
                    d = new P("groups");
                    d.setWidth("100%");
                    iGroupPanel.put(group.getDepartment().getId(), d);
                }
                d.add(ch);
            } else {
                groups.add(ch);
            }
        }
        if (groups.getWidgetCount() > 0) {
            iGlobalGroupsPanel = groups;
        }
    }

    iFeatures.clear();
    if (!iProperties.getFeatures().isEmpty()) {
        for (FeatureInterface feature : iProperties.getFeatures()) {
            CheckBox ch = new CheckBox(feature.getTitle());
            ch.addStyleName("feature");
            iFeatures.put(feature.getId(), ch);
        }
    }

    iPeriodPreferences.clear();
    for (ExamTypeInterface type : iProperties.getExamTypes()) {
        PeriodPreferencesWidget pref = new PeriodPreferencesWidget(true);
        iPeriodPreferences.put(type.getId(), pref);
    }
}

From source file:org.unitime.timetable.gwt.client.rooms.RoomEdit.java

License:Apache License

public void setRoom(RoomDetailInterface room) {
    iRoom = room;//from   w w  w. j a v a  2s  .  c om
    if (iRoom == null) {
        iRoom = new RoomDetailInterface();
        iRoom.setSessionId(iProperties.getAcademicSessionId());
        iRoom.setSessionName(iProperties.getAcademicSessionName());
        iHeader.setEnabled("create", true);
        iHeader.setEnabled("update", false);
        iHeader.setEnabled("delete", false);
    } else {
        iHeader.setEnabled("create", false);
        iHeader.setEnabled("update", true);
        iHeader.setEnabled("delete", iRoom.isCanDelete());
    }
    iLastControllingDept = iRoom.getControlDepartment();
    iLastEventDept = iRoom.getEventDepartment();

    iForm.clear();

    iHeader.clearMessage();
    iForm.addHeaderRow(iHeader);

    int firstRow = iForm.getRowCount();

    if (iMode.hasSessionSelection()) {
        iForm.addRow(MESSAGES.propAcademicSession(),
                new Label(
                        iRoom.hasSessionName() ? iRoom.getSessionName() : iProperties.getAcademicSessionName()),
                1);
    }

    if (iRoom.getRoomType() == null || iRoom.isCanChangeType()) {
        iType.clearHint();
        iType.getWidget().clear();
        if (iRoom.getRoomType() == null) {
            iType.getWidget().addItem(MESSAGES.itemSelect(), "-1");
            for (RoomTypeInterface type : iProperties.getRoomTypes()) {
                if (type.isRoom() && iProperties.isCanAddRoom())
                    iType.getWidget().addItem(type.getLabel(), type.getId().toString());
                else if (!type.isRoom() && iProperties.isCanAddNonUniversity())
                    iType.getWidget().addItem(type.getLabel(), type.getId().toString());
            }
            iType.getWidget().setSelectedIndex(0);
        } else {
            for (RoomTypeInterface type : iProperties.getRoomTypes()) {
                if (type.isRoom() && iRoom.getBuilding() != null)
                    iType.getWidget().addItem(type.getLabel(), type.getId().toString());
                else if (!type.isRoom() && iRoom.getBuilding() == null)
                    iType.getWidget().addItem(type.getLabel(), type.getId().toString());
            }
            for (int i = 0; i < iType.getWidget().getItemCount(); i++) {
                if (iType.getWidget().getValue(i).equals(iRoom.getRoomType().getId().toString())) {
                    iType.getWidget().setSelectedIndex(i);
                    break;
                }
            }
        }
        iForm.addRow(MESSAGES.propRoomType(), iType, 1);
    } else {
        iForm.addRow(MESSAGES.propRoomType(), new Label(iRoom.getRoomType().getLabel(), false), 1);
    }

    if (iRoom.getUniqueId() != null && iRoom.getBuilding() == null) {
        iBuildingRow = -1;
    } else if (iRoom.getUniqueId() == null || iRoom.isCanChangeRoomProperties()) {
        iBuilding.clearHint();
        if (iRoom.getBuilding() == null) {
            iBuilding.getWidget().setSelectedIndex(0);
        } else {
            iBuilding.getWidget().setSelectedIndex(1 + iProperties.getBuildings().indexOf(iRoom.getBuilding()));
        }
        iBuildingRow = iForm.addRow(MESSAGES.propBuilding(), iBuilding, 1);
    } else {
        iBuildingRow = iForm.addRow(MESSAGES.propBuilding(),
                new Label(iRoom.getBuilding().getAbbreviation() + " - " + iRoom.getBuilding().getName()), 1);
    }

    if (iRoom.getUniqueId() == null || iRoom.isCanChangeRoomProperties()) {
        iName.clearHint();
        iName.getWidget().setText(iRoom.getName() == null ? "" : iRoom.getName());
        iForm.addRow(iNameLabel, iName, 1);
    } else {
        iForm.addRow(iNameLabel, new Label(iRoom.getName()), 1);
    }

    if (iRoom.getRoomType() == null || iRoom.isCanChangeType()) {
        typeChanged();
    } else {
        if (iBuildingRow >= 0)
            iForm.getRowFormatter().setVisible(iBuildingRow,
                    iRoom.getRoomType() != null && iRoom.getRoomType().isRoom());
        iNameLabel
                .setText(iRoom.getRoomType() != null && iRoom.getRoomType().isRoom() ? MESSAGES.propRoomNumber()
                        : MESSAGES.propRoomName());
    }

    if (iRoom.getUniqueId() == null || iRoom.isCanChangeRoomProperties()) {
        iDisplayName.setText(iRoom.getDisplayName() == null ? "" : iRoom.getDisplayName());
        iForm.addRow(MESSAGES.propDisplayName(), iDisplayName, 1);
    } else if (iRoom.hasDisplayName()) {
        iForm.addRow(MESSAGES.propDisplayName(), new Label(iRoom.getDisplayName()), 1);
    }

    if ((iRoom.getUniqueId() == null && iProperties.isCanChangeExternalId()) || iRoom.isCanChangeExternalId()) {
        iExternalId.setText(iRoom.getExternalId() == null ? "" : iRoom.getExternalId());
        iForm.addRow(MESSAGES.propExternalId(), iExternalId, 1);
    } else if (iRoom.hasExternalId()) {
        iForm.addRow(MESSAGES.propExternalId(), new Label(iRoom.getExternalId()), 1);
    }

    if (iRoom.getUniqueId() == null || iRoom.isCanChangeCapacity()) {
        iCapacity.clearHint();
        iCapacity.getWidget().setValue(iRoom.getCapacity());
        iForm.addRow(MESSAGES.propCapacity(), iCapacity, 1);
    } else if (iRoom.getCapacity() != null) {
        iForm.addRow(MESSAGES.propCapacity(), new Label(iRoom.getCapacity().toString()), 1);
    }

    if ((iRoom.getUniqueId() == null && iProperties.isCanChangeControll()) || iRoom.isCanChangeControll()) {
        iControllingDepartment.clearHint();
        iControllingDepartment.getWidget().clear();
        iControllingDepartment.getWidget().addItem(MESSAGES.itemNoControlDepartment(), "-1");
        for (DepartmentInterface department : iProperties.getDepartments())
            iControllingDepartment.getWidget().addItem(
                    department.getExtAbbreviationOrCode() + " - " + department.getExtLabelWhenExist(),
                    department.getId().toString());
        if (iRoom.getControlDepartment() == null) {
            iControllingDepartment.getWidget().setSelectedIndex(0);
        } else {
            int index = iProperties.getDepartments().indexOf(iRoom.getControlDepartment());
            if (index >= 0) {
                iControllingDepartment.getWidget().setSelectedIndex(1 + index);
            } else {
                iControllingDepartment.getWidget().addItem(
                        iRoom.getControlDepartment().getExtAbbreviationOrCode() + " - "
                                + iRoom.getControlDepartment().getExtLabelWhenExist(),
                        iRoom.getControlDepartment().getId().toString());
                iControllingDepartment.getWidget()
                        .setSelectedIndex(iControllingDepartment.getWidget().getItemCount() - 1);
            }
        }
        if (iRoom.getUniqueId() == null && iControllingDepartment.getWidget().getItemCount() == 2)
            iControllingDepartment.getWidget().setSelectedIndex(1);
        iForm.addRow(MESSAGES.propControllingDepartment(), iControllingDepartment, 1);
        /*      } else if (iRoom.getUniqueId() == null) {
                 iControllingDepartment.getWidget().clear();
                 for (DepartmentInterface department: iProperties.getDepartments())
                    iControllingDepartment.getWidget().addItem(department.getExtAbbreviationOrCode() + " - " + department.getExtLabelWhenExist(), department.getId().toString());
                 //TODO: guess selected department from filter
                 iForm.addRow(MESSAGES.propDepartment(), iControllingDepartment, 1);*/
    } else if (iRoom.getControlDepartment() != null && iProperties.isCanSeeCourses()) {
        iForm.addRow(MESSAGES.propControllingDepartment(),
                new Label(RoomDetail.toString(iRoom.getControlDepartment())), 1);
    }

    if (iRoom.getUniqueId() == null || iRoom.isCanChangeRoomProperties()) {
        iX.setValue(iRoom.getX());
        iY.setValue(iRoom.getY());
        iForm.addRow(MESSAGES.propCoordinates(), iCoordinates, 1);
        iArea.setValue(iRoom.getArea());
        iAreaFormat.setText(iProperties != null && iProperties.isRoomAreaInMetricUnits()
                ? CONSTANTS.roomAreaMetricUnitsLong()
                : CONSTANTS.roomAreaUnitsLong());
        iForm.addRow(MESSAGES.propRoomArea(), iAreaPanel, 1);
        if (iProperties.isCanSeeCourses()) {
            iDistanceCheck.setValue(!iRoom.isIgnoreTooFar());
            distanceCheckChanged();
            iForm.addRow(MESSAGES.propDistanceCheck(), iDistanceCheck, 1);
        }
        iRoomCheck.setValue(!iRoom.isIgnoreRoomCheck());
        roomCheckChanged();
        iForm.addRow(MESSAGES.propRoomCheck(), iRoomCheck, 1);
        if (iGoogleMapControl != null)
            iGoogleMapControl.setVisible(true);
    } else {
        if (iRoom.hasCoordinates())
            if (iProperties != null && iProperties.hasEllipsoid())
                iForm.addRow(MESSAGES.propCoordinates(), new HTML(MESSAGES
                        .coordinatesWithEllipsoid(iRoom.getX(), iRoom.getY(), iProperties.getEllipsoid())), 1);
            else
                iForm.addRow(MESSAGES.propCoordinates(),
                        new HTML(MESSAGES.coordinates(iRoom.getX(), iRoom.getY())), 1);
        if (iRoom.getArea() != null)
            iForm.addRow(MESSAGES.propRoomArea(),
                    new HTML(MESSAGES.roomArea(iRoom.getArea()) + " "
                            + (iProperties != null && iProperties.isRoomAreaInMetricUnits()
                                    ? CONSTANTS.roomAreaMetricUnitsShort()
                                    : CONSTANTS.roomAreaUnitsShort())),
                    1);
        if (iProperties.isCanSeeCourses()) {
            iForm.addRow(MESSAGES.propDistanceCheck(), new Check(!room.isIgnoreTooFar(),
                    MESSAGES.infoDistanceCheckOn(), MESSAGES.infoDistanceCheckOff()), 1);
            iForm.addRow(MESSAGES.propRoomCheck(), new Check(!room.isIgnoreRoomCheck(),
                    MESSAGES.infoRoomCheckOn(), MESSAGES.infoRoomCheckOff()), 1);
        } else if (iProperties.isCanSeeEvents()) {
            iForm.addRow(MESSAGES.propRoomCheck(), new Check(!room.isIgnoreRoomCheck(),
                    MESSAGES.infoRoomCheckOn(), MESSAGES.infoRoomCheckOff()), 1);
        }
        if (iGoogleMapControl != null)
            iGoogleMapControl.setVisible(false);
    }

    if ((iRoom.getUniqueId() == null && iProperties.isCanChangeExamStatus()) || iRoom.isCanChangeExamStatus()) {
        for (Map.Entry<Long, CheckBox> e : iExaminationRooms.entrySet())
            e.getValue().setValue(false);
        if (iRoom.hasExamTypes()) {
            for (ExamTypeInterface type : iRoom.getExamTypes())
                iExaminationRooms.get(type.getId()).setValue(true);
        }
        iForm.addRow(MESSAGES.propExamRooms(), iExaminationRoomsPanel, 1);
        iExamCapacity.getWidget().setValue(iRoom.getExamCapacity());
        iForm.addRow(MESSAGES.propExamCapacity(), iExamCapacity, 1);
    } else if (iProperties.isCanSeeExams() && (iRoom.getExamCapacity() != null || iRoom.hasExamTypes())) {
        iForm.addRow(MESSAGES.propExamCapacity(), new RoomDetail.ExamSeatingCapacityLabel(iRoom), 1);
    }

    if ((iRoom.getUniqueId() == null && iProperties.isCanChangeEventProperties())
            || iRoom.isCanChangeEventProperties()) {
        iEventDepartment.clear();
        if ((iRoom.getUniqueId() == null && iProperties.isCanChangeControll()) || (iRoom.getUniqueId() != null
                && (iRoom.getEventDepartment() == null || iRoom.isCanChangeControll()))) {
            iEventDepartment.addItem(MESSAGES.itemNoEventDepartment(), "-1");
        }
        for (DepartmentInterface department : iProperties.getDepartments())
            if (department.isEvent())
                iEventDepartment.addItem(department.getDeptCode() + " - " + department.getLabel(),
                        department.getId().toString());
        if (iRoom.getEventDepartment() == null) {
            iEventDepartment.setSelectedIndex(0);
        } else {
            iEventDepartment.setSelectedIndex(0);
            for (int i = 1; i < iEventDepartment.getItemCount(); i++) {
                if (iEventDepartment.getValue(i).equals(iRoom.getEventDepartment().getId().toString())) {
                    iEventDepartment.setSelectedIndex(i);
                    break;
                }
            }
            if (iRoom.getEventDepartment() != null
                    && "-1".equals(iEventDepartment.getValue(iEventDepartment.getSelectedIndex()))) {
                iEventDepartment.addItem(
                        iRoom.getEventDepartment().getDeptCode() + " - "
                                + iRoom.getEventDepartment().getLabel(),
                        iRoom.getEventDepartment().getId().toString());
                iEventDepartment.setSelectedIndex(iEventDepartment.getItemCount() + -1);
            }
        }
        iForm.addRow(MESSAGES.propEventDepartment(), iEventDepartment, 1);
        iEventStatus.getWidget()
                .setSelectedIndex(iRoom.getEventStatus() == null ? 0 : iRoom.getEventStatus() + 1);
        iEventStatus.clearHint();
        iForm.addRow(MESSAGES.propEventStatus(), iEventStatus, 1);
        iNote.getWidget().setText(iRoom.getEventNote() == null ? "" : iRoom.getEventNote());
        iForm.addRow(MESSAGES.propEventNote(), iNote, 1);
        iBreakTime.setValue(iRoom.getBreakTime());
        iForm.addRow(MESSAGES.propBreakTime(), iBreakTimePanel, 1);
    } else if (iProperties.isCanSeeEvents()) {
        if (iRoom.getEventDepartment() != null)
            iForm.addRow(MESSAGES.propEventDepartment(),
                    new Label(RoomDetail.toString(iRoom.getEventDepartment(), true)), 1);
        if (iRoom.getEventStatus() != null || iRoom.getDefaultEventStatus() != null) {
            Label status = new Label(
                    CONSTANTS.eventStatusName()[iRoom.getEventStatus() == null ? iRoom.getDefaultEventStatus()
                            : iRoom.getEventStatus()]);
            if (iRoom.getEventStatus() == null)
                status.addStyleName("default");
            iForm.addRow(MESSAGES.propEventStatus(), status, 1);
        }
        if (iRoom.hasEventNote() || iRoom.hasDefaultEventNote()) {
            HTML note = new HTML(iRoom.hasEventNote() ? iRoom.getEventNote() : iRoom.getDefaultEventNote());
            if (!iRoom.hasEventNote())
                note.addStyleName("default");
            iForm.addRow(MESSAGES.propEventNote(), note, 1);
        }
        if (iRoom.getBreakTime() != null || iRoom.getDefaultBreakTime() != null) {
            Label bt = new Label(
                    (iRoom.getBreakTime() == null ? iRoom.getDefaultBreakTime() : iRoom.getBreakTime())
                            .toString());
            if (iRoom.getBreakTime() == null)
                bt.addStyleName("default");
            iForm.addRow(MESSAGES.propBreakTime(), bt, 1);
        }
    }

    if (iProperties.isGoogleMap()) {
        iForm.setWidget(firstRow, 2, iGoogleMap);
        iForm.getFlexCellFormatter().setRowSpan(firstRow, 2, iForm.getRowCount() - firstRow - 1);
    }

    if (((iRoom.getUniqueId() == null && iProperties.isCanChangeGroups()) || iRoom.isCanChangeGroups())
            && !iProperties.getGroups().isEmpty()) {
        iForm.addHeaderRow(MESSAGES.headerRoomGroups());
        for (Map.Entry<Long, CheckBox> e : iGroups.entrySet())
            e.getValue().setValue(iRoom.hasGroup(e.getKey()));
        if (iGlobalGroupsPanel != null) {
            iForm.addRow(MESSAGES.propGlobalGroups(), iGlobalGroupsPanel);
        } else {
            List<GroupInterface> globalGroups = iRoom.getGlobalGroups();
            if (!globalGroups.isEmpty())
                iForm.addRow(MESSAGES.propGlobalGroups(), new RoomDetail.GroupsCell(globalGroups), 1);
        }
        for (DepartmentInterface dept : iProperties.getDepartments()) {
            P d = iGroupPanel.get(dept.getId());
            if (d != null)
                iForm.addRow(dept.getExtLabelWhenExist() + ":", d);
        }
    } else if (iRoom.hasGroups()) {
        iForm.addHeaderRow(MESSAGES.headerRoomGroups());
        List<GroupInterface> globalGroups = iRoom.getGlobalGroups();
        if (!globalGroups.isEmpty())
            iForm.addRow(MESSAGES.propGlobalGroups(), new RoomDetail.GroupsCell(globalGroups));
        List<GroupInterface> departmentalGroups = iRoom.getDepartmentalGroups(null);
        if (!departmentalGroups.isEmpty())
            iForm.addRow(MESSAGES.propDepartmenalGroups(), new RoomDetail.GroupsCell(departmentalGroups));
    }

    if (((iRoom.getUniqueId() == null && iProperties.isCanChangeFeatures()) || iRoom.isCanChangeFeatures())
            && !iProperties.getFeatures().isEmpty()) {
        iForm.addHeaderRow(MESSAGES.headerRoomFeatures());
        for (Map.Entry<Long, CheckBox> e : iFeatures.entrySet())
            e.getValue().setValue(iRoom.hasFeature(e.getKey()));
        P features = new P("features");
        Map<Long, P> fp = new HashMap<Long, P>();
        for (FeatureInterface feature : iProperties.getFeatures()) {
            CheckBox ch = iFeatures.get(feature.getId());
            if (feature.getType() != null) {
                P d = fp.get(feature.getType().getId());
                if (d == null) {
                    d = new P("features");
                    d.setWidth("100%");
                    fp.put(feature.getType().getId(), d);
                }
                d.add(ch);
            } else {
                features.add(ch);
            }
        }
        for (FeatureInterface feature : iRoom.getFeatures()) {
            if (!iFeatures.containsKey(feature.getId()) && feature.getDepartment() == null) {
                P f = new P("feature");
                f.setText(feature.getTitle());
                if (feature.getType() != null) {
                    P d = fp.get(feature.getType().getId());
                    if (d == null) {
                        d = new P("features");
                        d.setWidth("100%");
                        fp.put(feature.getType().getId(), d);
                    }
                    d.add(f);
                } else {
                    features.add(f);
                }
            }
        }
        if (features.getWidgetCount() > 0)
            iForm.addRow(MESSAGES.propFeatures(), features);
        for (FeatureTypeInterface type : iProperties.getFeatureTypes()) {
            P d = fp.get(type.getId());
            if (d != null)
                iForm.addRow(type.getLabel() + ":", d);
        }
    } else if (iRoom.hasFeatures()) {
        iForm.addHeaderRow(MESSAGES.headerRoomFeatures());
        List<FeatureInterface> features = iRoom.getFeatures((Long) null);
        if (!features.isEmpty())
            iForm.addRow(MESSAGES.propFeatures(), new RoomDetail.FeaturesCell(features));
        for (FeatureTypeInterface type : iProperties.getFeatureTypes()) {
            List<FeatureInterface> featuresOfType = iRoom.getFeatures(type);
            if (!featuresOfType.isEmpty())
                iForm.addRow(type.getLabel() + ":", new RoomDetail.FeaturesCell(featuresOfType));
        }
    }

    if (iRoom.hasRoomSharingModel()) {
        iRoomSharingHeader.clearMessage();
        iRoomSharing.setEditable(iProperties.isCanEditDepartments()
                || (iRoom.getUniqueId() == null && iProperties.isCanChangeAvailability())
                || iRoom.isCanChangeAvailability());
        iRoomSharing.setModel(iRoom.getRoomSharingModel());
        iRoomSharing.setVisible(true);
        if (iRoom.getUniqueId() == null) {
            iLastSelectedDepartmentId = Long.valueOf(iControllingDepartment.getWidget()
                    .getValue(iControllingDepartment.getWidget().getSelectedIndex()));
            if (iLastSelectedDepartmentId > 0)
                iRoomSharing.addOption(iLastSelectedDepartmentId);
        }
        iForm.addHeaderRow(iRoomSharingHeader);
        iForm.addRow(iRoomSharing);
    } else if (iProperties.isCanEditDepartments()
            || (iRoom.getUniqueId() == null && iProperties.isCanChangeAvailability())
            || iRoom.isCanChangeAvailability()) {
        iForm.addHeaderRow(iRoomSharingHeader);
        iForm.addRow(iRoomSharing);
        iRoomSharingHeader.showLoading();
        iRoomSharing.setVisible(false);
        RPC.execute(
                RoomInterface.RoomSharingRequest.load(iRoom.getSessionId(), iRoom.getUniqueId(), false, true),
                new AsyncCallback<RoomSharingModel>() {
                    @Override
                    public void onFailure(Throwable caught) {
                        iRoomSharingHeader
                                .setErrorMessage(MESSAGES.failedToLoadRoomAvailability(caught.getMessage()));
                    }

                    @Override
                    public void onSuccess(RoomSharingModel result) {
                        iRoomSharingHeader.clearMessage();
                        iRoomSharing.setEditable(iProperties.isCanEditDepartments()
                                || (iRoom.getUniqueId() == null && iProperties.isCanChangeAvailability())
                                || iRoom.isCanChangeAvailability());
                        iRoomSharing.setModel(result);
                        iRoomSharing.setVisible(true);
                        if (iRoom.getUniqueId() == null) {
                            iLastSelectedDepartmentId = Long.valueOf(iControllingDepartment.getWidget()
                                    .getValue(iControllingDepartment.getWidget().getSelectedIndex()));
                            if (iLastSelectedDepartmentId > 0)
                                iRoomSharing.addOption(iLastSelectedDepartmentId);
                        }
                    }
                });
    }

    if (iProperties.isCanEditRoomExams()
            || (iProperties.isCanSeeExams() && iRoom.isCanSeePeriodPreferences() && iRoom.hasExamTypes())) {
        iPeriodPreferencesHeaderRow = iForm.addHeaderRow(iPeriodPreferencesHeader);
        iForm.getRowFormatter().setVisible(iPeriodPreferencesHeaderRow, false);
        for (ExamTypeInterface type : iProperties.getExamTypes()) {
            PeriodPreferencesWidget pref = iPeriodPreferences.get(type.getId());
            int row = iForm.addRow(MESSAGES.propExaminationPreferences(type.getLabel()), pref);
            iPeriodPreferencesRow.put(type.getId(), row);
            iForm.getRowFormatter().setVisible(iPeriodPreferencesRow.get(type.getId()), false);
        }
        iPeriodPreferencesHeader.clearMessage();
        for (final ExamTypeInterface type : iProperties.getExamTypes()) {
            final PeriodPreferencesWidget pref = iPeriodPreferences.get(type.getId());
            if (iRoom.hasPeriodPreferenceModel(type.getId())) {
                pref.setEditable(iProperties.isCanEditRoomExams());
                pref.setModel(iRoom.getPeriodPreferenceModel(type.getId()));
                boolean visible = iExaminationRooms.get(type.getId()).getValue()
                        && !pref.getModel().getPeriods().isEmpty();
                iForm.getRowFormatter().setVisible(iPeriodPreferencesRow.get(type.getId()), visible);
                if (visible)
                    iForm.getRowFormatter().setVisible(iPeriodPreferencesHeaderRow, true);
            } else if ((iRoom.getUniqueId() == null && iProperties.isCanChangeExamStatus())
                    || iRoom.isCanChangeExamStatus()) {
                iPeriodPreferencesHeader.showLoading();
                iForm.getRowFormatter().setVisible(iPeriodPreferencesRow.get(type.getId()), false);
                RPC.execute(RoomInterface.PeriodPreferenceRequest.load(iRoom.getSessionId(),
                        iRoom.getUniqueId(), type.getId()), new AsyncCallback<PeriodPreferenceModel>() {
                            @Override
                            public void onFailure(Throwable caught) {
                                iPeriodPreferencesHeader.setErrorMessage(
                                        MESSAGES.failedToLoadPeriodPreferences(caught.getMessage()));
                            }

                            @Override
                            public void onSuccess(PeriodPreferenceModel result) {
                                iPeriodPreferencesHeader.clearMessage();
                                pref.setEditable(iProperties.isCanEditRoomExams());
                                pref.setModel(result);
                                boolean visible = iExaminationRooms.get(type.getId()).getValue()
                                        && !pref.getModel().getPeriods().isEmpty();
                                iForm.getRowFormatter().setVisible(iPeriodPreferencesRow.get(type.getId()),
                                        visible);
                                if (visible)
                                    iForm.getRowFormatter().setVisible(iPeriodPreferencesHeaderRow, true);
                            }
                        });
            } else {
                iForm.getRowFormatter().setVisible(iPeriodPreferencesRow.get(type.getId()), false);
            }
        }
    } else {
        iPeriodPreferencesHeaderRow = -1;
        iPeriodPreferencesRow.clear();
    }

    if (((iRoom.getUniqueId() == null && iProperties.isCanChangeEventAvailability())
            || iRoom.isCanChangeEventAvailability())
            || (iProperties.isCanSeeEvents() && iRoom.isCanSeeEventAvailability())) {
        iForm.addHeaderRow(iEventAvailabilityHeader);
        iForm.addRow(iEventAvailability);
        iEventAvailabilityHeader
                .setVisible(!"-1".equals(iEventDepartment.getValue(iEventDepartment.getSelectedIndex())));
        if (iRoom.hasEventAvailabilityModel()) {
            iEventAvailabilityHeader.clearMessage();
            iEventAvailability
                    .setEditable((iRoom.getUniqueId() == null && iProperties.isCanChangeEventAvailability())
                            || iRoom.isCanChangeEventAvailability());
            iEventAvailability.setModel(iRoom.getEventAvailabilityModel());
            iEventAvailability
                    .setVisible(!"-1".equals(iEventDepartment.getValue(iEventDepartment.getSelectedIndex())));
        } else {
            iEventAvailabilityHeader.showLoading();
            iEventAvailability.setVisible(false);
            RPC.execute(RoomInterface.RoomSharingRequest.load(iRoom.getSessionId(), iRoom.getUniqueId(), true),
                    new AsyncCallback<RoomSharingModel>() {
                        @Override
                        public void onFailure(Throwable caught) {
                            iEventAvailabilityHeader.setErrorMessage(
                                    MESSAGES.failedToLoadRoomAvailability(caught.getMessage()));
                        }

                        @Override
                        public void onSuccess(RoomSharingModel result) {
                            iEventAvailabilityHeader.clearMessage();
                            iEventAvailability.setEditable(
                                    (iRoom.getUniqueId() == null && iProperties.isCanChangeEventAvailability())
                                            || iRoom.isCanChangeEventAvailability());
                            iEventAvailability.setModel(result);
                            iEventAvailability.setVisible(!"-1"
                                    .equals(iEventDepartment.getValue(iEventDepartment.getSelectedIndex())));
                        }
                    });
        }
    }

    if (iRoom.hasPictures() || (iRoom.getUniqueId() == null && iProperties.isCanChangePicture())
            || iRoom.isCanChangePicture()) {
        iForm.addHeaderRow(iPicturesHeader);
        if ((iRoom.getUniqueId() == null && iProperties.isCanChangePicture()) || iRoom.isCanChangePicture())
            iForm.addRow(MESSAGES.propNewPicture(), iFileUpload);
        iForm.addRow(iPictures);
        iPictures.clearTable(1);

        if (iRoom.hasPictures()) {
            for (final RoomPictureInterface picture : iRoom.getPictures())
                iPictures.addRow(picture, line(picture));
        }
    }

    iForm.addBottomRow(iFooter);

    if (iRoom.getUniqueId() == null && iProperties.hasFutureSessions()) {
        int row = iForm.addHeaderRow(iApplyToHeader);
        iForm.getRowFormatter().addStyleName(row, "space-above");
        iApplyTo.clearTable(1);
        long id = 0;
        for (AcademicSessionInterface session : iProperties.getFutureSessions()) {
            List<Widget> line = new ArrayList<Widget>();
            CheckBox select = new CheckBox();
            line.add(select);
            select.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
                @Override
                public void onValueChange(ValueChangeEvent<Boolean> event) {
                    futureChanged();
                }
            });
            line.add(new Label());
            line.add(new Label());
            line.add(new Label());
            line.add(new Label());
            line.add(new Label(session.getLabel()));
            Integer flags = RoomCookie.getInstance().getFutureFlags(session.getId());
            select.setValue(flags != null);
            for (FutureOperation op : FutureOperation.values()) {
                CheckBox ch = new CheckBox();
                ch.setValue(canFutureOperation(iRoom, op) && ((flags == null && op.getDefaultSelectionNewRoom())
                        || (flags != null && op.in(flags))));
                if (op == FutureOperation.ROOM_PROPERTIES) {
                    ch.setValue(true);
                    ch.setEnabled(false);
                }
                line.add(ch);
            }
            FutureRoomInterface fr = new FutureRoomInterface();
            fr.setSession(session);
            fr.setId(--id);
            iApplyTo.addRow(fr, line);
        }
        for (FutureOperation op : FutureOperation.values()) {
            iApplyTo.setColumnVisible(6 + op.ordinal(), canFutureOperation(iRoom, op));
        }
        iApplyTo.setColumnVisible(1, false);
        iApplyTo.setColumnVisible(2, false);
        iApplyTo.setColumnVisible(3, false);
        iApplyTo.setColumnVisible(4, false);
        iForm.addRow(iApplyTo);
        futureChanged();
    } else if (iRoom.hasFutureRooms()) {
        int row = iForm.addHeaderRow(iApplyToHeader);
        iForm.getRowFormatter().addStyleName(row, "space-above");
        iApplyTo.clearTable(1);
        boolean hasExtId = false, hasType = false, hasCapacity = false;
        for (FutureRoomInterface fr : iRoom.getFutureRooms()) {
            List<Widget> line = new ArrayList<Widget>();
            CheckBox select = new CheckBox();
            line.add(select);
            select.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
                @Override
                public void onValueChange(ValueChangeEvent<Boolean> event) {
                    futureChanged();
                }
            });
            line.add(new FutureRoomNameCell(fr));
            if (fr.hasExternalId())
                hasExtId = true;
            line.add(new Label(fr.hasExternalId() ? fr.getExternalId() : ""));
            if (fr.hasType())
                hasType = true;
            line.add(new Label(fr.hasType() ? fr.getType() : ""));
            if (fr.hasCapacity())
                hasCapacity = true;
            line.add(new Label(fr.hasCapacity() ? fr.getCapacity().toString() : ""));
            line.add(new Label(fr.getSession().getLabel()));
            Integer flags = RoomCookie.getInstance().getFutureFlags(fr.getSession().getId());
            select.setValue(flags != null);
            for (FutureOperation op : FutureOperation.values()) {
                CheckBox ch = new CheckBox();
                ch.setValue(canFutureOperation(iRoom, op)
                        && ((flags == null && op.getDefaultSelection()) || (flags != null && op.in(flags))));
                line.add(ch);
            }
            iApplyTo.addRow(fr, line);
        }
        for (FutureOperation op : FutureOperation.values()) {
            iApplyTo.setColumnVisible(6 + op.ordinal(), canFutureOperation(iRoom, op));
        }
        iApplyTo.setColumnVisible(1, true);
        iApplyTo.setColumnVisible(2, hasExtId);
        iApplyTo.setColumnVisible(3, hasType);
        iApplyTo.setColumnVisible(4, hasCapacity);
        iForm.addRow(iApplyTo);
        futureChanged();
    }
}

From source file:org.unitime.timetable.gwt.client.rooms.RoomFeatureEdit.java

License:Apache License

public void setProperties(RoomPropertiesInterface properties) {
    iProperties = properties;/*from   w w  w .  j  av  a 2  s  .c o m*/
    iRooms.setProperties(properties);

    iForm.getRowFormatter().setVisible(iTypeRow, !iProperties.getFeatureTypes().isEmpty());
    iType.clear();
    if (!iProperties.getFeatureTypes().isEmpty()) {
        iType.addItem(MESSAGES.itemNoFeatureType(), "-1");
        for (FeatureTypeInterface type : iProperties.getFeatureTypes())
            iType.addItem(type.getLabel(), type.getId().toString());
    }

    iFutureSessions.clear();
    iForm.getRowFormatter().setVisible(iFutureSessionsRow, iProperties.hasFutureSessions());
    if (iProperties.hasFutureSessions()) {
        CheckBox current = new CheckBox(iProperties.getAcademicSessionName());
        current.setValue(true);
        current.setEnabled(false);
        current.addStyleName("future-session");
        iFutureSessions.add(current);
        for (AcademicSessionInterface session : iProperties.getFutureSessions()) {
            if (session.isCanAddGlobalRoomGroup() || session.isCanAddDepartmentalRoomGroup()) {
                CheckBox ch = new CheckBox(session.getLabel());
                iFutureSessionsToggles.put(session.getId(), ch);
                ch.addStyleName("future-session");
                iFutureSessions.add(ch);
            }
        }
    }
}

From source file:org.unitime.timetable.gwt.client.rooms.RoomFeatureEdit.java

License:Apache License

public void setFeature(FeatureInterface feature, String dept) {
    iHeader.clearMessage();// w  w w . java2  s  .c om
    iName.clearHint();
    iAbbreviation.clearHint();
    iDepartment.clearHint();
    if (feature == null) {
        iFeature = new FeatureInterface();
        iFeature.setSessionId(iProperties.getAcademicSessionId());
        iFeature.setSessionName(iProperties.getAcademicSessionName());
        if (iSessionLabel != null)
            iSessionLabel.setText(iProperties.getAcademicSessionName());
        iHeader.setEnabled("create", true);
        iHeader.setEnabled("update", false);
        iHeader.setEnabled("delete", false);
        iName.getWidget().setText("");
        iAbbreviation.getWidget().setText("");
        iDepartment.getWidget().clear();
        iGlobal.setValue(true, true);
        iGlobal.setEnabled(true);
        if (iType != null && iType.getItemCount() > 0)
            iType.setSelectedIndex(0);
        if (iProperties.isCanAddDepartmentalRoomFeature()) {
            iDepartment.getWidget().addItem(MESSAGES.itemSelect(), "-1");
            iDepartment.getWidget().setSelectedIndex(0);
            for (DepartmentInterface department : iProperties.getDepartments()) {
                iDepartment.getWidget().addItem(
                        department.getExtAbbreviationOrCode() + " - " + department.getExtLabelWhenExist(),
                        department.getId().toString());
                if (dept != null && dept.equals(department.getDeptCode())) {
                    iDepartment.getWidget().setSelectedIndex(iDepartment.getWidget().getItemCount() - 1);
                    iGlobal.setValue(false, true);
                }
            }
        }
        if (!iProperties.isCanAddGlobalRoomFeature()) {
            iGlobal.setValue(false, true);
            iGlobal.setEnabled(false);
        } else if (!iProperties.isCanAddDepartmentalRoomGroup()) {
            iGlobal.setValue(true, true);
            iGlobal.setEnabled(false);
        }
    } else {
        iFeature = new FeatureInterface(feature);
        if (iSessionLabel != null)
            iSessionLabel.setText(feature.getSessionName());
        iHeader.setEnabled("create", false);
        iHeader.setEnabled("update", feature.canEdit());
        iHeader.setEnabled("delete", feature.canDelete());
        iName.getWidget().setText(feature.getLabel() == null ? "" : feature.getLabel());
        iAbbreviation.getWidget().setText(feature.getAbbreviation() == null ? "" : feature.getAbbreviation());
        if (iType != null && iType.getItemCount() > 0) {
            if (feature.getType() == null) {
                iType.setSelectedIndex(0);
            } else {
                iType.setSelectedIndex(1 + iProperties.getFeatureTypes().indexOf(feature.getType()));
            }
        }
        iGlobal.setValue(!feature.isDepartmental(), true);
        iGlobal.setEnabled(false);
        iDepartment.getWidget().clear();
        if (feature.isDepartmental()) {
            for (DepartmentInterface department : iProperties.getDepartments())
                iDepartment.getWidget().addItem(
                        department.getExtAbbreviationOrCode() + " - " + department.getExtLabelWhenExist(),
                        department.getId().toString());
            int index = iProperties.getDepartments().indexOf(feature.getDepartment());
            if (index >= 0) {
                iDepartment.getWidget().setSelectedIndex(index);
            } else {
                iDepartment.getWidget().addItem(
                        feature.getDepartment().getExtAbbreviationOrCode() + " - "
                                + feature.getDepartment().getExtLabelWhenExist(),
                        feature.getDepartment().getId().toString());
                iDepartment.getWidget().setSelectedIndex(iDepartment.getWidget().getItemCount() - 1);
            }
        }
    }

    if (iProperties.hasFutureSessions()) {
        for (AcademicSessionInterface session : iProperties.getFutureSessions()) {
            CheckBox ch = iFutureSessionsToggles.get(session.getId());
            if (ch != null) {
                ch.setValue(RoomCookie.getInstance().getFutureFlags(session.getId()) != null);
            }
        }
    }
}

From source file:org.unitime.timetable.gwt.client.rooms.RoomGroupEdit.java

License:Apache License

public void setProperties(RoomPropertiesInterface properties) {
    iProperties = properties;/*from w ww. j  a va2  s  . c  o  m*/
    iRooms.setProperties(properties);

    iFutureSessions.clear();
    iForm.getRowFormatter().setVisible(iFutureSessionsRow, iProperties.hasFutureSessions());
    if (iProperties.hasFutureSessions()) {
        CheckBox current = new CheckBox(iProperties.getAcademicSessionName());
        current.setValue(true);
        current.setEnabled(false);
        current.addStyleName("future-session");
        iFutureSessions.add(current);
        for (AcademicSessionInterface session : iProperties.getFutureSessions()) {
            if (session.isCanAddGlobalRoomGroup() || session.isCanAddDepartmentalRoomGroup()) {
                CheckBox ch = new CheckBox(session.getLabel());
                iFutureSessionsToggles.put(session.getId(), ch);
                ch.addStyleName("future-session");
                iFutureSessions.add(ch);
            }
        }
    }
}