public class ConfigManager {
		
	private SharedPreferences preferences;
	
	public ConfigManager(Activity activity) {
		
        // init config manager
        preferences = activity.getSharedPreferences("config", Context.MODE_PRIVATE);
	}

	public CommonConfig getCommonConfig() {
		return new CommonConfig();
	};
	
	public KanaTestConfig getKanaTestConfig() {
		return new KanaTestConfig();
	}
	
	public KanjiTestConfig getKanjiTestConfig() {
		return new KanjiTestConfig();
	}

	public SplashConfig getSplashConfig() {
		return new SplashConfig();
	}
	
	public WordDictionarySearchConfig getWordDictionarySearchConfig() {
		return new WordDictionarySearchConfig();
	}

	public KanjiSearchMeaningConfig getKanjiSearchMeaningConfig() {
		return new KanjiSearchMeaningConfig();
	}
	
	public DictionaryHearConfig getDictionaryHearConfig() {
		return new DictionaryHearConfig();
	}
	
	public WordTestConfig getWordTestConfig() {
		return new WordTestConfig();
	}

	public WordTestSM2Config getWordTestSM2Config() {
		return new WordTestSM2Config();
	}

	public class CommonConfig {

		private final String commonConfigPrefix = "commonConfig_";

		private final String userIdPostfix = "userId";

		private final String messageLastTimestampPostfix = "messageLastTimestamp";

		private final String themeTypePostfix = "themeType";

		public String getOrGenerateUniqueUserId() {

			String userId = preferences.getString(commonConfigPrefix + userIdPostfix, null);

			if (userId == null) { // generujemy losowy identyfikator

				userId = UUID.randomUUID().toString();

				// zapisujemy
				Editor editor = preferences.edit();

				editor.putString(commonConfigPrefix + userIdPostfix, userId);

				editor.commit();
			}

			return userId;
		}

		public String getMessageLastTimestamp() {
			return preferences.getString(commonConfigPrefix + messageLastTimestampPostfix, null);
		}

		public void setMessageLastTimestamp(String messageLastTimestamp) {

			Editor editor = preferences.edit();

			editor.putString(commonConfigPrefix + messageLastTimestampPostfix, messageLastTimestamp);

			editor.commit();
		}

		public JapaneseAndroidLearnHelperApplication.ThemeType getThemeType(JapaneseAndroidLearnHelperApplication.ThemeType defaultThemeType) {

			String themeTypeString = preferences.getString(commonConfigPrefix + themeTypePostfix, defaultThemeType.name());

			if (themeTypeString != null) {
				try {
					return JapaneseAndroidLearnHelperApplication.ThemeType.valueOf(themeTypeString);

				} catch (Exception e) {
					// noop, zostanie uzyta warotsc domyslna
				}
			}

			return defaultThemeType;
		}

		public void setThemeType(JapaneseAndroidLearnHelperApplication.ThemeType themeType) {

			Editor editor = preferences.edit();

			editor.putString(commonConfigPrefix + themeTypePostfix, themeType.name());

			editor.commit();
		}
	}
	
	public class KanaTestConfig {
		
		private final String kanaTestConfigPrefix = "kanaTestConfig_";
		
		private final String rangeTestPostfix = "rangeTest";
		
		private final String testMode1Postfix = "testMode1";
		private final String testMode2Postfix = "testMode2";
		
		private final String untilSuccessPostfix = "untilSuccess";
		private final String untilSuccessNewWordLimitPostfix = "untilSuccessNewWordLimit";
		
		private final String gojuuonPostfix = "gojuuon";
		private final String dakutenHandakutenPostfix = "dakutenHandakuten";
		private final String youonPostfix = "youon";
				
		public RangeTest getRangeTest() {
			
			String rangeTest = preferences.getString(kanaTestConfigPrefix + rangeTestPostfix, RangeTest.HIRAGANA_KATAKANA.toString());
			
			return RangeTest.valueOf(rangeTest);
		}

		public TestMode1 getTestMode1() {
			
			String testMode1 = preferences.getString(kanaTestConfigPrefix + testMode1Postfix, TestMode1.CHOOSE.toString());
			
			return TestMode1.valueOf(testMode1);
		}

		public TestMode2 getTestMode2() {
			
			String testMode2 = preferences.getString(kanaTestConfigPrefix + testMode2Postfix, TestMode2.KANA_TO_ROMAJI.toString());
			
			return TestMode2.valueOf(testMode2);
		}

		public void setRangeTest(RangeTest rangeTest) {
			
			Editor editor = preferences.edit();
			
			editor.putString(kanaTestConfigPrefix + rangeTestPostfix, rangeTest.toString());
			
			editor.commit();
		}

		public void setTestMode1(TestMode1 testMode1) {
			
			Editor editor = preferences.edit();
			
			editor.putString(kanaTestConfigPrefix + testMode1Postfix, testMode1.toString());
			
			editor.commit();
		}

		public void setTestMode2(TestMode2 testMode2) {
			
			Editor editor = preferences.edit();
			
			editor.putString(kanaTestConfigPrefix + testMode2Postfix, testMode2.toString());
			
			editor.commit();
		}

		public Boolean getUntilSuccess() {
			return preferences.getBoolean(kanaTestConfigPrefix + untilSuccessPostfix, true);
		}

		public void setUntilSuccess(boolean untilSuccess) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(kanaTestConfigPrefix + untilSuccessPostfix, untilSuccess);
			
			editor.commit();
		}

		public Boolean getUntilSuccessNewWordLimit() {
			return preferences.getBoolean(kanaTestConfigPrefix + untilSuccessNewWordLimitPostfix, false);
		}

		public void setUntilSuccessNewWordLimit(boolean untilSuccessNewWordLimit) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(kanaTestConfigPrefix + untilSuccessNewWordLimitPostfix, untilSuccessNewWordLimit);
			
			editor.commit();
		}
		
		public Boolean getGojuuon() {
			return preferences.getBoolean(kanaTestConfigPrefix + gojuuonPostfix, true);
		}

		public Boolean getDakutenHandakuten() {
			return preferences.getBoolean(kanaTestConfigPrefix + dakutenHandakutenPostfix, true);
		}

		public Boolean getYouon() {
			return preferences.getBoolean(kanaTestConfigPrefix + youonPostfix, true);
		}

		public void setGojuuon(Boolean gojuuon) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(kanaTestConfigPrefix + gojuuonPostfix, gojuuon);
			
			editor.commit();
		}

		public void setDakutenHandakuten(boolean dakutenHandakuten) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(kanaTestConfigPrefix + dakutenHandakutenPostfix, dakutenHandakuten);
			
			editor.commit();
		}

		public void setYouon(boolean youon) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(kanaTestConfigPrefix + youonPostfix, youon);
			
			editor.commit();
		}		
	}
	
	public class KanjiTestConfig {
		
		private final String kanjiTestConfigPrefix = "kanjiTestConfig_";
		
		private final String kanjiTestModePostfix = "kanjiTestMode";
		
		private final String kanjiTestChosenKanjiPostfix = "chosenKanji";
		
		private final String kanjiTestChosenKanjiGroupPostfix = "chosenKanjiGroup";

		private final String kanjiTestChosenUserGroupPostfix = "chosenUserGroup";
		
		private final String kanjiTestUntilSuccessPostfix = "untilSuccess";
		
		private final String kanjiTestUntilSuccessNewWordLimitPostfix = "untilSuccessNewWordLimit";
		
		private final String kanjiTestDedicateExamplePostfix = "dedicateExample";
		
		private final String kanjiTestMaxTestSizePostfix = "maxTestSize";
		
		private final String kanjiTestOwnGroupListPostfix = "ownGroupList";

		private final String kanjiTestOwnGroupPostfix = "ownGroup";
		
		private final String kanjiTestChosenOwnGroupPostfix = "chosenOwnGroup";
		
		public KanjiTestMode getKanjiTestMode() {
			
			String kanjiTestMode = preferences.getString(kanjiTestConfigPrefix + kanjiTestModePostfix, KanjiTestMode.DRAW_KANJI_FROM_MEANING.toString());
			
			if (kanjiTestMode.equals("DRAW_KANJI_IN_WORD_GROUP") == true) { // zabezpieczenie, przed wczesniejsza wartoscia
				return KanjiTestMode.DRAW_KANJI_IN_WORD;
			}
			
			return KanjiTestMode.valueOf(kanjiTestMode);
		}
		
		public void setKanjiTestMode(KanjiTestMode kanjiTestMode) {
			
			Editor editor = preferences.edit();
			
			editor.putString(kanjiTestConfigPrefix + kanjiTestModePostfix, kanjiTestMode.toString());
			
			editor.commit();
		}
		
		public List<String> getChosenKanjiAsList() {
			
			List<String> result = new ArrayList<String>();
			
			String chosenKanjiString = preferences.getString(kanjiTestConfigPrefix + kanjiTestChosenKanjiPostfix, null);

            if (chosenKanjiString == null || chosenKanjiString.trim().equals("") == true) {
                return result;
            }

            String[] chosenKanjiSplited = chosenKanjiString.split(",");
			
			for (String currentChosenKanji : chosenKanjiSplited) {
				result.add(currentChosenKanji);
			}
			
			return result;
		}
		
		public Set<String> getChosenKanjiGroup() {

			Set<String> result = new HashSet<String>();
			
			String chosenKanjiGroupString = preferences.getString(kanjiTestConfigPrefix + kanjiTestChosenKanjiGroupPostfix,  null);

            if (chosenKanjiGroupString == null || chosenKanjiGroupString.trim().equals("") == true) {
                return result;
            }

            String[] chosenKanjiGroupSplited = chosenKanjiGroupString.split(",");
			
			for (String currentChosenKanjiGroup : chosenKanjiGroupSplited) {
				result.add(currentChosenKanjiGroup);
			}
			
			return result;
		}
		
		public void setChosenKanji(List<String> chosenKanjiList) {
			
			StringBuffer chosenKanjiStringBuffer = new StringBuffer();
			
			for (int idx = 0; idx < chosenKanjiList.size(); ++idx) {
				
				if (idx != 0) {
					chosenKanjiStringBuffer.append(",");
				}
				
				chosenKanjiStringBuffer.append(chosenKanjiList.get(idx));
			}
			
			Editor editor = preferences.edit();
			
			editor.putString(kanjiTestConfigPrefix + kanjiTestChosenKanjiPostfix, chosenKanjiStringBuffer.toString());
			
			editor.commit();
		}

		public void setChosenKanjiGroup(List<String> chosenKanjiGroupList) {
			
			StringBuffer chosenKanjiGroupStringBuffer = new StringBuffer();
			
			for (int idx = 0; idx < chosenKanjiGroupList.size(); ++idx) {
				
				if (idx != 0) {
					chosenKanjiGroupStringBuffer.append(",");
				}
				
				chosenKanjiGroupStringBuffer.append(chosenKanjiGroupList.get(idx));
			}
			
			Editor editor = preferences.edit();
			
			editor.putString(kanjiTestConfigPrefix + kanjiTestChosenKanjiGroupPostfix, chosenKanjiGroupStringBuffer.toString());
			
			editor.commit();
		}

		public Set<Integer> getChosenUserGroups() {

			Set<Integer> result = new HashSet<Integer>();

			String chosenUserGroupString = preferences.getString(kanjiTestConfigPrefix + kanjiTestChosenUserGroupPostfix, null);

			if (chosenUserGroupString == null || chosenUserGroupString.trim().equals("") == true) {
				return result;
			}

			String[] chosenUserGroupSplited = chosenUserGroupString.split(",");

			for (String currentChosenUserGroupId : chosenUserGroupSplited) {
				result.add(new Integer(currentChosenUserGroupId));
			}

			return result;
		}


		public void setChosenUserGroups(List<Integer> chosenUserGroupsNumberList) {

			if (chosenUserGroupsNumberList == null) {
				return;
			}

			StringBuffer chosenUserGroupsNumberSb = new StringBuffer();

			for (int chosenUserGroupsNumberListIdx = 0; chosenUserGroupsNumberListIdx < chosenUserGroupsNumberList.size(); ++chosenUserGroupsNumberListIdx) {

				chosenUserGroupsNumberSb.append(chosenUserGroupsNumberList.get(chosenUserGroupsNumberListIdx));

				if (chosenUserGroupsNumberListIdx != chosenUserGroupsNumberList.size() - 1) {
					chosenUserGroupsNumberSb.append(",");
				}
			}

			Editor editor = preferences.edit();

			editor.putString(kanjiTestConfigPrefix + kanjiTestChosenUserGroupPostfix, chosenUserGroupsNumberSb.toString());

			editor.commit();
		}

		public Boolean getUntilSuccess() {
			return preferences.getBoolean(kanjiTestConfigPrefix + kanjiTestUntilSuccessPostfix, true);
		}

		public void setUntilSuccess(boolean untilSuccess) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(kanjiTestConfigPrefix + kanjiTestUntilSuccessPostfix, untilSuccess);
			
			editor.commit();
		}

		public Boolean getUntilSuccessNewWordLimitPostfix() {
			return preferences.getBoolean(kanjiTestConfigPrefix + kanjiTestUntilSuccessNewWordLimitPostfix, false);
		}

		public void setUntilSuccessNewWordLimitPostfix(boolean untilSuccessNewWordLimit) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(kanjiTestConfigPrefix + kanjiTestUntilSuccessNewWordLimitPostfix, untilSuccessNewWordLimit);
			
			editor.commit();
		}
		
		public Boolean getDedicateExample() {
			return preferences.getBoolean(kanjiTestConfigPrefix + kanjiTestDedicateExamplePostfix, false);
		}

		public void setDedicateExample(boolean untilSuccess) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(kanjiTestConfigPrefix + kanjiTestDedicateExamplePostfix, untilSuccess);
			
			editor.commit();
		}

		public Integer getMaxTestSize() {			
			return preferences.getInt(kanjiTestConfigPrefix + kanjiTestMaxTestSizePostfix, 1000);			
		}
		
		public void setMaxTestSize(int maxTestSize) {
			
			Editor editor = preferences.edit();
			
			editor.putInt(kanjiTestConfigPrefix + kanjiTestMaxTestSizePostfix, maxTestSize);
			
			editor.commit();			
		}
		
		public List<String> getOwnGroupList() {
			
			List<String> result = new ArrayList<String>();
			
			String ownGroupListString = preferences.getString(kanjiTestConfigPrefix + kanjiTestOwnGroupListPostfix, "");
			
			String[] ownGroupListStringSplited = ownGroupListString.split(",");
			
			for (String currentOwnGroupList : ownGroupListStringSplited) {
				
				if (currentOwnGroupList.trim().equals("") == false) {
					result.add(currentOwnGroupList);
				}				
			}
			
			return result;
		}
		
		public void setOwnGroupList(List<String> ownGroupList) {
			
			StringBuffer ownGroupListStringBuffer = new StringBuffer();
			
			for (int idx = 0; idx < ownGroupList.size(); ++idx) {
				
				if (idx != 0) {
					ownGroupListStringBuffer.append(",");
				}
				
				ownGroupListStringBuffer.append(ownGroupList.get(idx));
			}
			
			Editor editor = preferences.edit();
			
			editor.putString(kanjiTestConfigPrefix + kanjiTestOwnGroupListPostfix, ownGroupListStringBuffer.toString());
			
			editor.commit();
		}
		
		public void addOwnGroup(String groupName) {
			
			List<String> ownGroupList = getOwnGroupList();
			
			if (ownGroupList.contains(groupName) == true) {
				throw new RuntimeException("Try to add already exists group");
			}
			
			ownGroupList.add(groupName);
			
			Collections.sort(ownGroupList, new Comparator<String>() {

				@Override
				public int compare(String lhs, String rhs) {
					return lhs.compareToIgnoreCase(rhs);
				}
			});
			
			setOwnGroupList(ownGroupList);
		}

		public void deleteOwnGroup(String ownGroupName) {
			
			List<String> ownGroupList = getOwnGroupList();
			
			if (ownGroupList.contains(ownGroupName) == false) {
				throw new RuntimeException("Try to delete doesn't exist group");
			}
			
			ownGroupList.remove(ownGroupName);
			
			Collections.sort(ownGroupList, new Comparator<String>() {

				@Override
				public int compare(String lhs, String rhs) {
					return lhs.compareToIgnoreCase(rhs);
				}
			});
			
			setOwnGroupList(ownGroupList);
			
			Editor editor = preferences.edit();			
			editor.remove(kanjiTestConfigPrefix + kanjiTestOwnGroupPostfix + "_" + escapeOwnGroupName(ownGroupName));			
			editor.commit();
		}
		
		public boolean isOwnGroupExists(String groupName) {
			
			List<String> ownGroupList = getOwnGroupList();
			
			return ownGroupList.contains(groupName);
		}
		
		public void setOwnGroupKanjiList(String ownGroupName, Set<String> ownGroupKanjiList) {
			
			StringBuffer ownGroupKanjiListStringBuffer = new StringBuffer();
			
			Iterator<String> ownGroupKanjiListIterator = ownGroupKanjiList.iterator();
			
			int counter = 0;
			
			while (ownGroupKanjiListIterator.hasNext() == true) {
				
				if (counter != 0) {
					ownGroupKanjiListStringBuffer.append(",");
				}
											
				ownGroupKanjiListStringBuffer.append(ownGroupKanjiListIterator.next());
								
				counter++;
			}
			
			Editor editor = preferences.edit();
			
			editor.putString(kanjiTestConfigPrefix + kanjiTestOwnGroupPostfix + "_" + escapeOwnGroupName(ownGroupName), ownGroupKanjiListStringBuffer.toString());
			
			editor.commit();
		}
		
		public Set<String> getOwnGroupKanjiList(String ownGroupName) {
			
			Set<String> result = new TreeSet<String>();
			
			String ownGroupKanjiListString = preferences.getString(kanjiTestConfigPrefix + kanjiTestOwnGroupPostfix + "_" + escapeOwnGroupName(ownGroupName), "");
			
			String[] ownGroupKanjiListSplitted = ownGroupKanjiListString.split(",");
			
			for (String currentOwnGroupKanji : ownGroupKanjiListSplitted) {
				
				if (currentOwnGroupKanji.trim().equals("") == false) {
					result.add(currentOwnGroupKanji);
				}				
			}
			
			return result;			
		}

		private String escapeOwnGroupName(String ownGroupName) {
			return ownGroupName.replaceAll(" ", "_");			
		}
		
		public Set<String> getChosenOwnKanjiGroup() {
			
			Set<String> result = new HashSet<String>();
			
			String chosenOwnKanjiGroupString = preferences.getString(kanjiTestConfigPrefix + kanjiTestChosenOwnGroupPostfix, null);

            if (chosenOwnKanjiGroupString == null || chosenOwnKanjiGroupString.trim().equals("") == true) {
                return result;
            }

            String[] chosenOwnKanjiGroupSplited = chosenOwnKanjiGroupString.split(",");
			
			for (String currentChosenKanjiGroup : chosenOwnKanjiGroupSplited) {
				result.add(currentChosenKanjiGroup);
			}
			
			return result;
		}

		public void setChosenOwnKanjiGroup(List<String> chosenOwnKanjiGroupList) {
			
			StringBuffer chosenOwnKanjiGroupStringBuffer = new StringBuffer();
			
			for (int idx = 0; idx < chosenOwnKanjiGroupList.size(); ++idx) {
				
				if (idx != 0) {
					chosenOwnKanjiGroupStringBuffer.append(",");
				}
				
				chosenOwnKanjiGroupStringBuffer.append(chosenOwnKanjiGroupList.get(idx));
			}
			
			Editor editor = preferences.edit();
			
			editor.putString(kanjiTestConfigPrefix + kanjiTestChosenOwnGroupPostfix, chosenOwnKanjiGroupStringBuffer.toString());
			
			editor.commit();
		}
	}
	
	public class SplashConfig {
		
		private final String splashConfigPrefix = "splashConfig_";
		
		private final String dialogBoxSkipPostfix = "dialogBoxSkip";
		
		public Boolean getDialogBoxSkip() {
			return preferences.getBoolean(splashConfigPrefix + dialogBoxSkipPostfix, false);
		}

		public void setDialogBoxSkip(boolean dialogBoxSkip) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(splashConfigPrefix + dialogBoxSkipPostfix, dialogBoxSkip);
			
			editor.commit();
		}		
	}
	
	public class WordDictionarySearchConfig {
		
		private final String wordDictionarySearchConfigPrefix = "wordDictionarySearchConfig_";
		
		private final String eachChangeSearchPostfix = "eachChangeSearch";
		
		private final String automaticSendMissingWordPostfix = "automaticSendMissingWord";
		
		private final String useAutocompletePostfix = "useAutocomplete";
		
		private final String useSuggestionPostfix = "useSuggestion";
		
		public Boolean getEachChangeSearch() {
			return preferences.getBoolean(wordDictionarySearchConfigPrefix + eachChangeSearchPostfix, false);
		}
		
		public void setEachChangeSearch(boolean eachChangeSearch) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(wordDictionarySearchConfigPrefix + eachChangeSearchPostfix, eachChangeSearch);
			
			editor.commit();			
		}
		
		public Boolean getAutomaticSendMissingWord() {
			return preferences.getBoolean(wordDictionarySearchConfigPrefix + automaticSendMissingWordPostfix, true);
		}
		
		public void setAutomaticSendMissingWord(boolean automaticSendMissingWord) {

			Editor editor = preferences.edit();
			
			editor.putBoolean(wordDictionarySearchConfigPrefix + automaticSendMissingWordPostfix, automaticSendMissingWord);
			
			editor.commit();			
		}
		
		public Boolean getUseAutocomplete() {
			return preferences.getBoolean(wordDictionarySearchConfigPrefix + useAutocompletePostfix, true);
		}
		
		public void setUseAutocomplete(boolean useAutocomplete) {

			Editor editor = preferences.edit();
			
			editor.putBoolean(wordDictionarySearchConfigPrefix + useAutocompletePostfix, useAutocomplete);
			
			editor.commit();			
		}
		
		public Boolean getUseSuggestion() {
			return preferences.getBoolean(wordDictionarySearchConfigPrefix + useSuggestionPostfix, true);
		}
		
		public void setUseSuggestion(boolean useSuggestion) {

			Editor editor = preferences.edit();
			
			editor.putBoolean(wordDictionarySearchConfigPrefix + useSuggestionPostfix, useSuggestion);
			
			editor.commit();			
		}
	}

	public class KanjiSearchMeaningConfig {
		
		private final String kanjiSearchMeaningConfigPrefix = "kanjiSearchMeaningConfig_";
		
		private final String eachChangeSearchPostfix = "eachChangeSearch";
		
		private final String useAutocompletePostfix = "useAutocomplete";
		
		private final String useSuggestionPostfix = "useSuggestion";
		
		public Boolean getEachChangeSearch() {
			return preferences.getBoolean(kanjiSearchMeaningConfigPrefix + eachChangeSearchPostfix, false);
		}
		
		public void setEachChangeSearch(boolean eachChangeSearch) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(kanjiSearchMeaningConfigPrefix + eachChangeSearchPostfix, eachChangeSearch);
			
			editor.commit();			
		}
		
		public Boolean getUseAutocomplete() {
			return preferences.getBoolean(kanjiSearchMeaningConfigPrefix + useAutocompletePostfix, true);
		}
		
		public void setUseAutocomplete(boolean useAutocomplete) {

			Editor editor = preferences.edit();
			
			editor.putBoolean(kanjiSearchMeaningConfigPrefix + useAutocompletePostfix, useAutocomplete);
			
			editor.commit();			
		}
		
		public Boolean getUseSuggestion() {
			return preferences.getBoolean(kanjiSearchMeaningConfigPrefix + useSuggestionPostfix, true);
		}
		
		public void setUseSuggestion(boolean useSuggestion) {

			Editor editor = preferences.edit();
			
			editor.putBoolean(kanjiSearchMeaningConfigPrefix + useSuggestionPostfix, useSuggestion);
			
			editor.commit();			
		}
	}
	
	public class DictionaryHearConfig {
		
		private final String dictionaryHearConfigPrefix = "dictionaryHearConfig_";
		
		private final String repeatNumberPostfix = "repeatNumber";
		
		private final String delayNumberPostfix = "delayNumber";
		
		private final String wordGroupsPostfix = "wordGroups";

		private final String wordUserGroupsPostfix = "wordUserGroups";

		private final String randomPostfix = "random";
		
		public Integer getRepeatNumber() {
			return preferences.getInt(dictionaryHearConfigPrefix + repeatNumberPostfix, 1);
		}
		
		public void setRepeatNumber(int repeatNumber) {
			
			Editor editor = preferences.edit();
			
			editor.putInt(dictionaryHearConfigPrefix + repeatNumberPostfix, repeatNumber);
			
			editor.commit();			
		}	

		public Integer getDelayNumber() {
			return preferences.getInt(dictionaryHearConfigPrefix + delayNumberPostfix, 3);
		}
		
		public void setDelayNumber(int repeatNumber) {
			
			Editor editor = preferences.edit();
			
			editor.putInt(dictionaryHearConfigPrefix + delayNumberPostfix, repeatNumber);
			
			editor.commit();			
		}
		
		public Set<String> getChosenWordGroups() {
			
			Set<String> result = new HashSet<String>();
			
			String chosenWordGroupString = preferences.getString(dictionaryHearConfigPrefix + wordGroupsPostfix, null);
			
			if (chosenWordGroupString == null || chosenWordGroupString.trim().equals("") == true) {
				return result;
			}
			
			String[] chosenWordGroupSplited = chosenWordGroupString.split(",");
			
			for (String currentChosenWordGroup : chosenWordGroupSplited) {
				result.add(currentChosenWordGroup);
			}
			
			return result;
		}

		public Set<Integer> getChosenWordUserGroups() {

			Set<Integer> result = new HashSet<Integer>();

			String chosenWordUserGroupString = preferences.getString(dictionaryHearConfigPrefix + wordUserGroupsPostfix, null);

			if (chosenWordUserGroupString == null || chosenWordUserGroupString.trim().equals("") == true) {
				return result;
			}

			String[] chosenWordUserGroupSplited = chosenWordUserGroupString.split(",");

			for (String currentChosenWordUserGroupId : chosenWordUserGroupSplited) {
				result.add(new Integer(currentChosenWordUserGroupId));
			}

			return result;
		}

		public void setChosenWordGroups(List<String> chosenWordGroupsNumberList) {
			
			if (chosenWordGroupsNumberList == null) {
				return;
			}
			
			StringBuffer chosenWordGroupsNumberSb = new StringBuffer();
			
			for (int chosenWordGroupsNumberListIdx = 0; chosenWordGroupsNumberListIdx < chosenWordGroupsNumberList.size(); ++chosenWordGroupsNumberListIdx) {
				
				chosenWordGroupsNumberSb.append(chosenWordGroupsNumberList.get(chosenWordGroupsNumberListIdx));
				
				if (chosenWordGroupsNumberListIdx != chosenWordGroupsNumberList.size() - 1) {
					chosenWordGroupsNumberSb.append(",");	
				}
			}
			
			Editor editor = preferences.edit();
			
			editor.putString(dictionaryHearConfigPrefix + wordGroupsPostfix, chosenWordGroupsNumberSb.toString());
			
			editor.commit();
		}

		public void setChosenWordUserGroups(List<Integer> chosenWordUserGroupsNumberList) {

			if (chosenWordUserGroupsNumberList == null) {
				return;
			}

			StringBuffer chosenWordUserGroupsNumberSb = new StringBuffer();

			for (int chosenWordUserGroupsNumberListIdx = 0; chosenWordUserGroupsNumberListIdx < chosenWordUserGroupsNumberList.size(); ++chosenWordUserGroupsNumberListIdx) {

				chosenWordUserGroupsNumberSb.append(chosenWordUserGroupsNumberList.get(chosenWordUserGroupsNumberListIdx));

				if (chosenWordUserGroupsNumberListIdx != chosenWordUserGroupsNumberList.size() - 1) {
					chosenWordUserGroupsNumberSb.append(",");
				}
			}

			Editor editor = preferences.edit();

			editor.putString(dictionaryHearConfigPrefix + wordUserGroupsPostfix, chosenWordUserGroupsNumberSb.toString());

			editor.commit();
		}

		public Boolean getRandom() {
			return preferences.getBoolean(dictionaryHearConfigPrefix + randomPostfix, true);
		}

		public void setRandom(boolean random) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(dictionaryHearConfigPrefix + randomPostfix, random);
			
			editor.commit();
		}
	}

	public class WordTestConfig {
		
		private final String wordTestConfigPrefix = "wordTestConfig_";
		
		private final String repeatNumberPostfix = "repeatNumber";
				
		private final String wordGroupsPostfix = "wordGroups";

		private final String wordUserGroupsPostfix = "wordUserGroups";
		
		private final String randomPostfix = "random";
		
		private final String untilSuccessPostfix = "untilSuccess";
		
		private final String untilSuccessNewWordLimitPostfix = "untilSuccessNewWordLimit";
		
		private final String showKanjiPostfix = "showKanji";
		
		private final String showKanaPostfix = "showKana";
		
		private final String showTranslatePostfix = "showTranslate";
		
		private final String showAdditionalInfoPostfix = "showAdditionalInfo";
		
		private final String wordTestModePostfix = "wordTestMode";
		
		public Integer getRepeatNumber() {
			return preferences.getInt(wordTestConfigPrefix + repeatNumberPostfix, 1);
		}
		
		public void setRepeatNumber(int repeatNumber) {
			
			Editor editor = preferences.edit();
			
			editor.putInt(wordTestConfigPrefix + repeatNumberPostfix, repeatNumber);
			
			editor.commit();			
		}	
		
		public Set<String> getChosenWordGroups() {
			
			Set<String> result = new HashSet<String>();
			
			String chosenWordGroupString = preferences.getString(wordTestConfigPrefix + wordGroupsPostfix, null);
			
			if (chosenWordGroupString == null || chosenWordGroupString.trim().equals("") == true) {
				return result;
			}
			
			String[] chosenWordGroupSplited = chosenWordGroupString.split(",");
			
			for (String currentChosenWordGroup : chosenWordGroupSplited) {
				result.add(currentChosenWordGroup);
			}
			
			return result;
		}

		public Set<Integer> getChosenWordUserGroups() {

			Set<Integer> result = new HashSet<Integer>();

			String chosenWordUserGroupString = preferences.getString(wordTestConfigPrefix + wordUserGroupsPostfix, null);

			if (chosenWordUserGroupString == null || chosenWordUserGroupString.trim().equals("") == true) {
				return result;
			}

			String[] chosenWordUserGroupSplited = chosenWordUserGroupString.split(",");

			for (String currentChosenWordUserGroupId : chosenWordUserGroupSplited) {
				result.add(new Integer(currentChosenWordUserGroupId));
			}

			return result;
		}

		public void setChosenWordGroups(List<String> chosenWordGroupsNumberList) {
			
			if (chosenWordGroupsNumberList == null) {
				return;
			}
			
			StringBuffer chosenWordGroupsNumberSb = new StringBuffer();
			
			for (int chosenWordGroupsNumberListIdx = 0; chosenWordGroupsNumberListIdx < chosenWordGroupsNumberList.size(); ++chosenWordGroupsNumberListIdx) {
				
				chosenWordGroupsNumberSb.append(chosenWordGroupsNumberList.get(chosenWordGroupsNumberListIdx));
				
				if (chosenWordGroupsNumberListIdx != chosenWordGroupsNumberList.size() - 1) {
					chosenWordGroupsNumberSb.append(",");	
				}
			}
			
			Editor editor = preferences.edit();
			
			editor.putString(wordTestConfigPrefix + wordGroupsPostfix, chosenWordGroupsNumberSb.toString());
			
			editor.commit();
		}

		public void setChosenWordUserGroups(List<Integer> chosenWordUserGroupsNumberList) {

			if (chosenWordUserGroupsNumberList == null) {
				return;
			}

			StringBuffer chosenWordUserGroupsNumberSb = new StringBuffer();

			for (int chosenWordUserGroupsNumberListIdx = 0; chosenWordUserGroupsNumberListIdx < chosenWordUserGroupsNumberList.size(); ++chosenWordUserGroupsNumberListIdx) {

				chosenWordUserGroupsNumberSb.append(chosenWordUserGroupsNumberList.get(chosenWordUserGroupsNumberListIdx));

				if (chosenWordUserGroupsNumberListIdx != chosenWordUserGroupsNumberList.size() - 1) {
					chosenWordUserGroupsNumberSb.append(",");
				}
			}

			Editor editor = preferences.edit();

			editor.putString(wordTestConfigPrefix + wordUserGroupsPostfix, chosenWordUserGroupsNumberSb.toString());

			editor.commit();
		}

		public Boolean getRandom() {
			return preferences.getBoolean(wordTestConfigPrefix + randomPostfix, true);
		}

		public void setRandom(boolean random) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(wordTestConfigPrefix + randomPostfix, random);
			
			editor.commit();
		}

		public Boolean getUntilSuccess() {
			return preferences.getBoolean(wordTestConfigPrefix + untilSuccessPostfix, true);
		}

		public void setUntilSuccess(boolean untilSuccess) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(wordTestConfigPrefix + untilSuccessPostfix, untilSuccess);
			
			editor.commit();
		}

		public Boolean getUntilSuccessNewWordLimit() {
			return preferences.getBoolean(wordTestConfigPrefix + untilSuccessNewWordLimitPostfix, false);
		}

		public void setUntilSuccessNewWordLimit(boolean untilSuccessNewWordLimit) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(wordTestConfigPrefix + untilSuccessNewWordLimitPostfix, untilSuccessNewWordLimit);
			
			editor.commit();
		}
		
		public Boolean getShowKanji() {
			return preferences.getBoolean(wordTestConfigPrefix + showKanjiPostfix, true);
		}

		public void setShowKanji(boolean showKanji) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(wordTestConfigPrefix + showKanjiPostfix, showKanji);
			
			editor.commit();
		}

		public Boolean getShowKana() {
			return preferences.getBoolean(wordTestConfigPrefix + showKanaPostfix, true);
		}

		public void setShowKana(boolean showKanji) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(wordTestConfigPrefix + showKanaPostfix, showKanji);
			
			editor.commit();
		}
		
		public Boolean getShowTranslate() {
			return preferences.getBoolean(wordTestConfigPrefix + showTranslatePostfix, true);
		}

		public void setShowTranslate(boolean showTranslate) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(wordTestConfigPrefix + showTranslatePostfix, showTranslate);
			
			editor.commit();
		}

		public Boolean getShowAdditionalInfo() {
			return preferences.getBoolean(wordTestConfigPrefix + showAdditionalInfoPostfix, true);
		}

		public void setAdditionalInfoTranslate(boolean showAdditionalInfo) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(wordTestConfigPrefix + showAdditionalInfoPostfix, showAdditionalInfo);
			
			editor.commit();
		}
		
		public WordTestMode getWordTestMode() {
			
			String wordTestMode = preferences.getString(wordTestConfigPrefix + wordTestModePostfix, WordTestMode.INPUT.toString());
						
			return WordTestMode.valueOf(wordTestMode);
		}
		
		public void setWordTestMode(WordTestMode wordTestMode) {
			
			Editor editor = preferences.edit();
			
			editor.putString(wordTestConfigPrefix + wordTestModePostfix, wordTestMode.toString());
			
			editor.commit();
		}
	}
	
	public class WordTestSM2Config {
		
		private final String wordTestSM2ConfigPrefix = "wordTestSM2Config_";
		
		private final String maxNewWordsPostfix = "maxNewWords";
				
		private final String showKanjiPostfix = "showKanji";
		
		private final String showKanaPostfix = "showKana";
		
		private final String showTranslatePostfix = "showTranslate";
		
		private final String showAdditionalInfoPostfix = "showAdditionalInfo";
		
		private final String wordTestSM2ModePostfix = "wordTestSM2Mode";
		
		public Integer getMaxNewWords() {
			return preferences.getInt(wordTestSM2ConfigPrefix + maxNewWordsPostfix, 20);
		}
		
		public void setMaxNewWords(int maxNewWords) {
			
			Editor editor = preferences.edit();
			
			editor.putInt(wordTestSM2ConfigPrefix + maxNewWordsPostfix, maxNewWords);
			
			editor.commit();			
		}	
		
		public Boolean getShowKanji() {
			return preferences.getBoolean(wordTestSM2ConfigPrefix + showKanjiPostfix, true);
		}

		public void setShowKanji(boolean showKanji) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(wordTestSM2ConfigPrefix + showKanjiPostfix, showKanji);
			
			editor.commit();
		}

		public Boolean getShowKana() {
			return preferences.getBoolean(wordTestSM2ConfigPrefix + showKanaPostfix, true);
		}

		public void setShowKana(boolean showKanji) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(wordTestSM2ConfigPrefix + showKanaPostfix, showKanji);
			
			editor.commit();
		}
		
		public Boolean getShowTranslate() {
			return preferences.getBoolean(wordTestSM2ConfigPrefix + showTranslatePostfix, true);
		}

		public void setShowTranslate(boolean showTranslate) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(wordTestSM2ConfigPrefix + showTranslatePostfix, showTranslate);
			
			editor.commit();
		}

		public Boolean getShowAdditionalInfo() {
			return preferences.getBoolean(wordTestSM2ConfigPrefix + showAdditionalInfoPostfix, true);
		}

		public void setAdditionalInfoTranslate(boolean showAdditionalInfo) {
			
			Editor editor = preferences.edit();
			
			editor.putBoolean(wordTestSM2ConfigPrefix + showAdditionalInfoPostfix, showAdditionalInfo);
			
			editor.commit();
		}
		
		public WordTestSM2Mode getWordTestSM2Mode() {
			
			String wordTestSM2Mode = preferences.getString(wordTestSM2ConfigPrefix + wordTestSM2ModePostfix, WordTestSM2Mode.CHOOSE.toString());
						
			return WordTestSM2Mode.valueOf(wordTestSM2Mode);
		}
		
		public void setWordTestSM2Mode(WordTestSM2Mode wordTestSM2Mode) {
			
			Editor editor = preferences.edit();
			
			editor.putString(wordTestSM2ConfigPrefix + wordTestSM2ModePostfix, wordTestSM2Mode.toString());
			
			editor.commit();
		}
	}
} public class CountersActivity extends Activity {
	
	private Stack<Integer> backScreenPositionStack = new Stack<Integer>();
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		MenuShorterHelper.onCreateOptionsMenu(menu);
		
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		return MenuShorterHelper.onOptionsItemSelected(item, getApplicationContext(), this);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);

		JapaneseAndroidLearnHelperApplication.getInstance().setContentViewAndTheme(this, R.layout.counters);
		
		JapaneseAndroidLearnHelperApplication.getInstance().logScreen(this, getString(R.string.logs_counters));

		final ScrollView scrollMainLayout = (ScrollView)findViewById(R.id.counters_main_layout_scroll);
		final LinearLayout mainLayout = (LinearLayout)findViewById(R.id.counters_main_layout);
		
		final List<IScreenItem> report = new ArrayList<IScreenItem>();
		
		final List<TitleItem> titleList = new ArrayList<TitleItem>();
		
		// get all counters
		CountersHelper countersHelper = new CountersHelper();
		
		List<CounterEntry> allCounters = countersHelper.getAllCounters(getResources());
		
		report.add(new TitleItem(getString(R.string.counters_title), 0));
		
		for (CounterEntry currentCounter : allCounters) {
			
			String kanji = currentCounter.getKanji();
			String kana = currentCounter.getKana();
			String romaji = currentCounter.getRomaji();
			
			String description = currentCounter.getDescription();
						
			description = description.substring(0, 1).toUpperCase(Locale.getDefault()) + description.substring(1);
			
			StringBuffer title = new StringBuffer();
			
			title.append(description);
			title.append(":  ");
			
			if (kanji != null) {
				title.append(kanji);
				
				title.append(" - ");
			}
			
			title.append(kana);
			
			title.append(" (");
			title.append(romaji);
			title.append(")");
			
			TitleItem currentTitle = new TitleItem(title.toString(), 1);
			
			titleList.add(currentTitle);
			report.add(currentTitle);
			
			TableLayout tableLayout = new TableLayout(TableLayout.LayoutParam.WrapContent_WrapContent, true, true);
			
			List<Entry> currentCounterEntries = currentCounter.getEntries();
			
			for (Entry currentCounterEntriesCurrentEntry : currentCounterEntries) {
				
				TableRow tableRow = new TableRow();
				
				if (currentCounterEntriesCurrentEntry != null) {
					StringValue entryKey = new StringValue(currentCounterEntriesCurrentEntry.getKey(), 15.0f, 1);
					StringValue entryKanji = new StringValue(currentCounterEntriesCurrentEntry.getKanji(), 15.0f, 1);
					StringValue entryKana = new StringValue(currentCounterEntriesCurrentEntry.getKana(), 15.0f, 1);
					StringValue entryRomaji = new StringValue(currentCounterEntriesCurrentEntry.getRomaji(), 15.0f, 1);

					entryKey.setNullMargins(false);
					entryKanji.setNullMargins(true);
					entryKana.setNullMargins(true);
					entryRomaji.setNullMargins(true);				

					tableRow.addScreenItem(entryKey);
					tableRow.addScreenItem(entryKanji);
					tableRow.addScreenItem(entryKana);
					tableRow.addScreenItem(entryRomaji);
				} else {
					tableRow.addScreenItem(new StringValue("", 3.0f, 2));
				}
				
				tableLayout.addTableRow(tableRow);
			}			
			
			report.add(tableLayout);
			
			List<String> exampleUse = currentCounter.getExampleUse();
			
			if (exampleUse != null && exampleUse.size() > 0) {
				
				report.add(new StringValue("", 10.0f, 2));
				
				report.add(new TitleItem(getString(R.string.counters_examples), 2));
				
				for (String currentExample : exampleUse) {
					report.add(new StringValue(currentExample, 15.0f, 2));
				}
			}
			
			report.add(new StringValue("", 12.0f, 2));
		}
		
		// add index
		int indexPos = 0;
		
		report.add(indexPos, new TitleItem(getString(R.string.counters_index), 0));
		indexPos++;
		
		report.add(indexPos, new StringValue(getString(R.string.counters_index_go), 12.0f, 1));
		indexPos++;
		
		report.add(indexPos, new StringValue("", 6.0f, 2));
		indexPos++;
		
		for (final TitleItem currentTitle : titleList) {
			StringValue titleStringValue = new StringValue(currentTitle.getTitle(), 15.0f, 2);
			
			titleStringValue.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					
					backScreenPositionStack.push(scrollMainLayout.getScrollY());
					
					scrollMainLayout.scrollTo(0, currentTitle.getY() - 3);
				}
			});
			
			report.add(indexPos, titleStringValue);
			
			indexPos++;
		}
		
		report.add(indexPos, new StringValue("", 12.0f, 2));
		
		// fill mail layout
		fillMainLayout(report, mainLayout);

		/*
		// report problem
		Button reportProblemButton = (Button)findViewById(R.id.counters_report_problem_button);
		
		reportProblemButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View view) {
				
				StringBuffer reportSb = new StringBuffer();
				
				for (IScreenItem currentReportScreenItem : report) {
					reportSb.append(currentReportScreenItem.toString()).append("\n\n");
				}
				
				String chooseEmailClientTitle = getString(R.string.choose_email_client);
				
				String mailSubject = getString(R.string.counters_report_problem_email_subject);
				
				String mailBody = getString(R.string.counters_report_problem_email_body,
						reportSb.toString());				
				
		        String versionName = "";
		        int versionCode = 0;
		        
		        try {
		        	PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
		        	
		            versionName = packageInfo.versionName;
		            versionCode = packageInfo.versionCode;

		        } catch (NameNotFoundException e) {        	
		        }
				
				Intent reportProblemIntent = ReportProblem.createReportProblemIntent(mailSubject, mailBody.toString(), versionName, versionCode); 
				
				startActivity(Intent.createChooser(reportProblemIntent, chooseEmailClientTitle));
			}
		});
		*/
	}
	
	@Override
	public void onBackPressed() {
		
		if (backScreenPositionStack.isEmpty() == true) {
			super.onBackPressed();
			
			return;
		}
		
		Integer backPostion = backScreenPositionStack.pop();

		final ScrollView scrollMainLayout = (ScrollView)findViewById(R.id.counters_main_layout_scroll);
		
		scrollMainLayout.scrollTo(0, backPostion);
	}

	private void fillMainLayout(List<IScreenItem> generatedDetails, LinearLayout mainLayout) {

		for (IScreenItem currentDetailsReportItem : generatedDetails) {
			currentDetailsReportItem.generate(this, getResources(), mainLayout);
		}
	}
} public class DictionaryHearOptions extends Activity {
	
	private TtsConnector japanaeseTtsConnector;
	
	private TtsConnector polishTtsConnector;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		MenuShorterHelper.onCreateOptionsMenu(menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		return MenuShorterHelper.onOptionsItemSelected(item, getApplicationContext(), this);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		JapaneseAndroidLearnHelperApplication.getInstance().setContentViewAndTheme(this, R.layout.dictionary_hear_options);
		
		JapaneseAndroidLearnHelperApplication.getInstance().logScreen(this, getString(R.string.logs_dictionary_hear_options));

		final DictionaryHearConfig dictionaryHearConfig = JapaneseAndroidLearnHelperApplication.getInstance()
				.getConfigManager(this).getDictionaryHearConfig();

		final LinearLayout mainLayout = (LinearLayout) findViewById(R.id.dictionary_hear_options_main_layout);

		// get repeat number
		final EditText repeatNumberEditText = (EditText) findViewById(R.id.dictionary_hear_options_repeat_number_edit_text);

		repeatNumberEditText.setText(String.valueOf(dictionaryHearConfig.getRepeatNumber()));

		final EditText delayNumberEditText = (EditText) findViewById(R.id.dictionary_hear_options_delay_number_edit_text);

		delayNumberEditText.setText(String.valueOf(dictionaryHearConfig.getDelayNumber()));

		final CheckBox randomCheckBox = (CheckBox) findViewById(R.id.dictionary_hear_options_random);

		randomCheckBox.setChecked(dictionaryHearConfig.getRandom());

		final Button startButton = (Button) findViewById(R.id.dictionary_hear_start);

		// groups
		final List<CheckBox> wordGroupCheckBoxList = new ArrayList<CheckBox>();

		// loading word groups

		List<GroupEnum> groupsNames;

		try {
			groupsNames = JapaneseAndroidLearnHelperApplication.getInstance()
					.getDictionaryManager(this).getDictionaryEntryGroupTypes();

		} catch (DictionaryException e) {

			startButton.setEnabled(false);

			Toast.makeText(this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();

			groupsNames = new ArrayList<>();
		}

		Set<String> chosenWordGroups = dictionaryHearConfig.getChosenWordGroups();

		for (int groupsNamesIdx = 0; groupsNamesIdx < groupsNames.size(); ++groupsNamesIdx) {

			GroupEnum groupEnum = groupsNames.get(groupsNamesIdx);

			if (groupEnum == GroupEnum.OTHER) {
				continue;
			}

			CheckBox checkbox = createGroupCheckBox(groupEnum, null, groupEnum.getValue(),
					chosenWordGroups != null && chosenWordGroups.contains(groupsNames.get(groupsNamesIdx).getValue()));

			wordGroupCheckBoxList.add(checkbox);

			mainLayout.addView(checkbox, mainLayout.getChildCount() - 1);
		}

		// loading user word groups
		List<UserGroupEntity> allUserGroupList = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(this).getDataManager().getAllUserGroupList();

		Set<Integer> chosenWordUserGroups = dictionaryHearConfig.getChosenWordUserGroups();

		for (int allUserGroupListIdx = 0; allUserGroupListIdx < allUserGroupList.size(); ++allUserGroupListIdx) {

			UserGroupEntity userGroupEntity = allUserGroupList.get(allUserGroupListIdx);

			String checkboxText = userGroupEntity.getType() == UserGroupEntity.Type.USER_GROUP ? userGroupEntity.getName() :
					getString(R.string.user_group_star_group);

			CheckBox checkbox = createGroupCheckBox(null, userGroupEntity, checkboxText,
					chosenWordUserGroups != null && chosenWordUserGroups.contains(userGroupEntity.getId()));

			wordGroupCheckBoxList.add(checkbox);

			mainLayout.addView(checkbox);
		}

		// check TTS
		if (japanaeseTtsConnector != null) {
			japanaeseTtsConnector.stop();
		}
		
		japanaeseTtsConnector = new TtsConnector(DictionaryHearOptions.this, TtsLanguage.JAPANESE);

		if (polishTtsConnector != null) {
			polishTtsConnector.stop();
		}
		
		polishTtsConnector = new TtsConnector(DictionaryHearOptions.this, TtsLanguage.POLISH);
			
		// start action		
		startButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				
				final ProgressDialog progressDialog = ProgressDialog.show(DictionaryHearOptions.this,
						getString(R.string.dictionary_hear_options_check_tts1),
						getString(R.string.dictionary_hear_options_check_tts2));

				class PrepareAsyncTask extends AsyncTask<Void, Void, Void> {

					private boolean japaneseInitialized = false;
					private boolean polishInitialized = false;
					
					@Override
					protected Void doInBackground(Void... params) {
						
						japaneseInitialized = isTtsConnectorInitialized(japanaeseTtsConnector);
						polishInitialized = isTtsConnectorInitialized(polishTtsConnector);
						
						return null;
					}

					private boolean isTtsConnectorInitialized(TtsConnector ttsConnector) {

						for (int idx = 0; idx < 10; ++idx) {

							Boolean onInitResult = ttsConnector.getOnInitResult();

							if (onInitResult == null) {
								try {
									Thread.sleep(1000);
								} catch (InterruptedException e) {
								}

							} else {

								return onInitResult.booleanValue();
							}
						}

						return false;
					}

					@SuppressWarnings("deprecation")
					@Override
					protected void onPostExecute(Void voidNull) {
						
						super.onPostExecute(voidNull);

						if (progressDialog != null && progressDialog.isShowing()) {
							progressDialog.dismiss();
						}

						// INFO: Tylko do testow
						// FIXME
						// int warning = 0;
						// japaneseInitialized = true;
						// polishInitialized = true;
						
						if (japaneseInitialized == false || polishInitialized == false) { // wystapil blad
							
							AlertDialog alertDialog = new AlertDialog.Builder(DictionaryHearOptions.this).create();

							String message = null;

							if (japaneseInitialized == false && polishInitialized == false) {
								message = getString(R.string.tts_japanese_polish_error);
							} else if (japaneseInitialized == true && polishInitialized == false) {
								message = getString(R.string.tts_polish_error);
							} else if (japaneseInitialized == false && polishInitialized == true) {
								message = getString(R.string.tts_japanese_error);
							} else {
								throw new RuntimeException();
							}

							alertDialog.setMessage(message);
							alertDialog.setCancelable(false);

							alertDialog.setButton(getString(R.string.tts_error_ok), new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									// noop
								}
							});

							if (japaneseInitialized == false || polishInitialized == false) {
								alertDialog.setButton2(getString(R.string.tts_google_android_tts),
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(DialogInterface dialog, int which) {

												Uri marketUri = Uri.parse(getString(R.string.tts_google_android_tts_url));

												Intent marketIntent = new Intent(Intent.ACTION_VIEW, marketUri);

												startActivity(marketIntent);
											}
										});
							}
							
							/*
							if (polishInitialized == false) {
								alertDialog.setButton3(getString(R.string.tts_ivona_google_play_go),
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(DialogInterface dialog, int which) {

												Uri marketUri = Uri.parse(getString(R.string.tts_ivona_market_url));

												Intent marketIntent = new Intent(Intent.ACTION_VIEW, marketUri);

												startActivity(marketIntent);
											}
										});
							}
							*/

							alertDialog.show();							
							
						} else { // ok
							
							// przygotowanie danych
							
							String repeatNumberString = repeatNumberEditText.getText().toString();

							boolean repeatNumberError = false;

							int repeatNumber = -1;

							if (repeatNumberString == null) {
								repeatNumberError = true;
							} else {

								try {
									repeatNumber = Integer.parseInt(repeatNumberString);
								} catch (NumberFormatException e) {
									repeatNumberError = true;
								}
							}

							if (repeatNumberError == false && repeatNumber <= 0) {
								repeatNumberError = true;
							}

							if (repeatNumberError == true) {

								Toast toast = Toast.makeText(DictionaryHearOptions.this,
										getString(R.string.dictionary_hear_options_repeat_number_invalid), Toast.LENGTH_SHORT);

								toast.show();

								return;
							}

							dictionaryHearConfig.setRepeatNumber(repeatNumber);

							String delayNumberString = delayNumberEditText.getText().toString();

							boolean delayNumberError = false;

							int delayNumber = -1;

							if (delayNumberString == null) {
								delayNumberError = true;
							} else {

								try {
									delayNumber = Integer.parseInt(delayNumberString);
								} catch (NumberFormatException e) {
									delayNumberError = true;
								}
							}

							if (delayNumberError == false && delayNumber < 0) {
								delayNumberError = true;
							}

							if (delayNumberError == true) {

								Toast toast = Toast.makeText(DictionaryHearOptions.this,
										getString(R.string.dictionary_hear_options_delay_number_invalid), Toast.LENGTH_SHORT);

								toast.show();

								return;
							}

							dictionaryHearConfig.setDelayNumber(delayNumber);

							boolean random = randomCheckBox.isChecked();

							dictionaryHearConfig.setRandom(random);

							List<DictionaryEntry> chosenAllDictionaryEntryList = new ArrayList<DictionaryEntry>();

							List<GroupEnum> chosenWordGroupsNumberList = new ArrayList<GroupEnum>();
							List<Integer> chosenWordUserGroupsNumberList = new ArrayList<Integer>();

							DictionaryManagerCommon dictionaryManager = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(DictionaryHearOptions.this);

							for (int wordGroupCheckBoxListIdx = 0; wordGroupCheckBoxListIdx < wordGroupCheckBoxList.size(); ++wordGroupCheckBoxListIdx) {

								CheckBox currentWordGroupCheckBox = wordGroupCheckBoxList.get(wordGroupCheckBoxListIdx);

								if (currentWordGroupCheckBox.isChecked() == true) {

									CheckBoxTag currentWordGroupCheckBoxTag = (CheckBoxTag)currentWordGroupCheckBox.getTag();

									List<DictionaryEntry> currentWordsGroupDictionaryEntryList = null;

									if (currentWordGroupCheckBoxTag.groupType == CheckBoxGroupType.INTERNAL_GROUP) { // grupa wbudowana

										try {
											currentWordsGroupDictionaryEntryList = dictionaryManager.getGroupDictionaryEntries(currentWordGroupCheckBoxTag.groupEnum);

										} catch (DictionaryException e) {
											Toast.makeText(DictionaryHearOptions.this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();

											return;
										}

									} else if (currentWordGroupCheckBoxTag.groupType == CheckBoxGroupType.USER_GROUP) { // grupa uzytkownika

										List<UserGroupItemEntity> userGroupItemListForUserEntity = dictionaryManager.getDataManager().getUserGroupItemListForUserEntity(currentWordGroupCheckBoxTag.userGroupEntity);

										if (userGroupItemListForUserEntity == null) {
											userGroupItemListForUserEntity = new ArrayList<>();
										}

										currentWordsGroupDictionaryEntryList = new ArrayList<>();

										for (UserGroupItemEntity userGroupItemEntity : userGroupItemListForUserEntity) {

											if (userGroupItemEntity.getType() == UserGroupItemEntity.Type.DICTIONARY_ENTRY) {

												DictionaryEntry dictionaryEntry = null;

												try {
													dictionaryEntry = dictionaryManager.getDictionaryEntryById(userGroupItemEntity.getItemId());

												} catch (DictionaryException e) {
													Toast.makeText(DictionaryHearOptions.this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();

													return;
												}

												if (dictionaryEntry != null) {
													currentWordsGroupDictionaryEntryList.add(dictionaryEntry);
												}
											}
										}
									}

									for (int repeatIdx = 0; repeatIdx < repeatNumber; ++repeatIdx) {
										chosenAllDictionaryEntryList.addAll(currentWordsGroupDictionaryEntryList);
									}

									if (currentWordGroupCheckBoxTag.groupType == CheckBoxGroupType.INTERNAL_GROUP) { // grupa wbudowana

										chosenWordGroupsNumberList.add(currentWordGroupCheckBoxTag.groupEnum);

									} else if (currentWordGroupCheckBoxTag.groupType == CheckBoxGroupType.USER_GROUP) { // grupa uzytkownika

										chosenWordUserGroupsNumberList.add(currentWordGroupCheckBoxTag.userGroupEntity.getId());

									}
								}
							}

							if (chosenAllDictionaryEntryList.size() == 0) {

								Toast toast = null;

								if (chosenWordGroupsNumberList.size() == 0 && chosenWordUserGroupsNumberList.size() == 0) {
									toast = Toast.makeText(DictionaryHearOptions.this,
											getString(R.string.dictionary_hear_options_word_group_no_chosen), Toast.LENGTH_SHORT);

								} else {
									toast = Toast.makeText(DictionaryHearOptions.this,
											getString(R.string.dictionary_hear_options_word_group_zero_words), Toast.LENGTH_SHORT);
								}

								toast.show();

								return;
							}

							dictionaryHearConfig.setChosenWordGroups(GroupEnum.convertToValues(chosenWordGroupsNumberList));
							dictionaryHearConfig.setChosenWordUserGroups(chosenWordUserGroupsNumberList);

							if (random == true) {
								Collections.shuffle(chosenAllDictionaryEntryList);
							}

							JapaneseAndroidLearnHelperDictionaryHearContext dictionaryHearContext = JapaneseAndroidLearnHelperApplication
									.getInstance().getContext().getDictionaryHearContext();

							dictionaryHearContext.reset();

							dictionaryHearContext.setDictionaryEntryList(chosenAllDictionaryEntryList);

							finish();

							Intent intent = new Intent(getApplicationContext(), DictionaryHear.class);

							startActivity(intent);							
						}						
					}
				}

				new PrepareAsyncTask().execute();
			}
		});

		/*
		// report problem button
		Button reportProblemButton = (Button) findViewById(R.id.dictionary_hear_options_report_problem_button);

		reportProblemButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {

				StringBuffer detailsSb = new StringBuffer();

				TextView optionsRepeat = (TextView) findViewById(R.id.dictionary_hear_options_repeat);
				TextView optionsOther = (TextView) findViewById(R.id.dictionary_hear_options_other);
                TextView optionsGroupPleaseChoose = (TextView)findViewById(R.id.dictionary_hear_options_group_please_choose);
                TextView optionsGroupInternal = (TextView)findViewById(R.id.dictionary_hear_options_group_internal);
                TextView optionsGroupUser = (TextView)findViewById(R.id.dictionary_hear_options_group_user);

                detailsSb.append("***" + optionsRepeat.getText() + "***\n\n");
				detailsSb.append(repeatNumberEditText.getText().toString()).append("\n\n");

				detailsSb.append("***" + optionsOther.getText() + "***\n\n");
				detailsSb.append(randomCheckBox.isChecked() + " - " + randomCheckBox.getText()).append("\n\n");

                detailsSb.append("*** " + optionsGroupPleaseChoose.getText() + " ***\n\n");
                detailsSb.append("*** " + optionsGroupInternal.getText() + " ***\n\n");

                for (CheckBox currentWordGroupCheckBox : wordGroupCheckBoxList) {

                    CheckBoxTag currentWordGroupCheckBoxTag = (CheckBoxTag)currentWordGroupCheckBox.getTag();

                    if (currentWordGroupCheckBoxTag.groupType != CheckBoxGroupType.INTERNAL_GROUP) {
                        continue;
                    }

                    String currentWordGroupCheckBoxText = currentWordGroupCheckBox.getText().toString();

                    detailsSb.append(currentWordGroupCheckBox.isChecked() + " - " + currentWordGroupCheckBoxText).append("\n");
                }

                detailsSb.append("*** " + optionsGroupUser.getText() + " ***\n\n");

                for (CheckBox currentWordGroupCheckBox : wordGroupCheckBoxList) {

                    CheckBoxTag currentWordGroupCheckBoxTag = (CheckBoxTag)currentWordGroupCheckBox.getTag();

                    if (currentWordGroupCheckBoxTag.groupType != CheckBoxGroupType.USER_GROUP) {
                        continue;
                    }

                    String currentWordGroupCheckBoxText = currentWordGroupCheckBox.getText().toString();

                    detailsSb.append(currentWordGroupCheckBox.isChecked() + " - " + currentWordGroupCheckBoxText).append("\n");
                }

				String chooseEmailClientTitle = getString(R.string.choose_email_client);

				String mailSubject = getString(R.string.dictionary_hear_options_report_problem_email_subject);

				String mailBody = getString(R.string.dictionary_hear_options_report_problem_email_body,
						detailsSb.toString());

				String versionName = "";
				int versionCode = 0;

				try {
					PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);

					versionName = packageInfo.versionName;
					versionCode = packageInfo.versionCode;

				} catch (NameNotFoundException e) {
				}

				Intent reportProblemIntent = ReportProblem.createReportProblemIntent(mailSubject, mailBody.toString(),
						versionName, versionCode);

				startActivity(Intent.createChooser(reportProblemIntent, chooseEmailClientTitle));
			}
		});
		*/
	}
	
	@Override
	protected void onDestroy() {

		if (japanaeseTtsConnector != null) {
			japanaeseTtsConnector.stop();
		}

		if (polishTtsConnector != null) {
			polishTtsConnector.stop();
		}
		
		super.onDestroy();
	}

	private CheckBox createGroupCheckBox(GroupEnum groupEnum, UserGroupEntity userGroupEntity, String text, boolean checked) {

		CheckBox checkbox = new CheckBox(this);

		if ( 	(groupEnum == null && userGroupEntity == null) ||
				(groupEnum != null && userGroupEntity != null)) {
			throw new RuntimeException();
		}

		if (groupEnum != null) {
			checkbox.setTag(new CheckBoxTag(groupEnum));

		} else if (userGroupEntity != null) {
			checkbox.setTag(new CheckBoxTag(userGroupEntity));
		}

		checkbox.setLayoutParams(new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));

		checkbox.setTextSize(12);
		checkbox.setText(text);

		checkbox.setChecked(checked);

		return checkbox;
	}

	private static class CheckBoxTag {

		private CheckBoxGroupType groupType;

		private GroupEnum groupEnum;

		private UserGroupEntity userGroupEntity;

		public CheckBoxTag(GroupEnum groupEnum) {
			this.groupType = CheckBoxGroupType.INTERNAL_GROUP;
			this.groupEnum = groupEnum;
		}

		public CheckBoxTag(UserGroupEntity userGroupEntity) {
			this.groupType = CheckBoxGroupType.USER_GROUP;
			this.userGroupEntity = userGroupEntity;
		}
	}

	private static enum CheckBoxGroupType {

		INTERNAL_GROUP,

		USER_GROUP;
	}
} @SuppressWarnings("deprecation")
public class WordDictionaryTab extends TabActivity {

	private final List<TabHost.TabSpec> tagHostSpecList = new ArrayList<TabHost.TabSpec>();

	private int counter = 1;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		menu.add(Menu.NONE, R.id.main_menu_word_dictionary_tab_add_tab, Menu.NONE, R.string.word_dictionary_tab_add_tab);
		menu.add(Menu.NONE, R.id.main_menu_word_dictionary_tab_del_tab, Menu.NONE, R.string.word_dictionary_tab_del_tab);

		MenuShorterHelper.onCreateOptionsMenu(menu);
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		int itemId = item.getItemId();

		if (itemId == R.id.main_menu_word_dictionary_tab_add_tab) { // add tab

			addTab(getTabHost(), false);

			return true;
		} else if (itemId == R.id.main_menu_word_dictionary_tab_del_tab) { // del tab

			delCurrentTab(getTabHost());

			return true;
			
		} else {
			return MenuShorterHelper.onOptionsItemSelected(item, getApplicationContext(), this);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		JapaneseAndroidLearnHelperApplication.getInstance().setContentViewAndTheme(this, R.layout.word_dictionary_tab);

		TabHost tabHost = getTabHost();

		addTab(tabHost, true);

		tabHost.setCurrentTab(0);
	}

	private void addTab(TabHost tabHost, boolean addFindExtra) {

		// word dictionary
		Intent wordDictionary = new Intent(getApplicationContext(), WordDictionary.class);

		if (addFindExtra == true) {
			wordDictionary.putExtra("findWordRequest", getIntent().getSerializableExtra("findWordRequest"));
		}

		TabSpec wordDictionaryTabSpec = tabHost.newTabSpec("WordDictionaryTabSpec." + counter)
				.setIndicator(getString(R.string.word_dictionary_tab_tab, counter)).setContent(wordDictionary);

		tabHost.addTab(wordDictionaryTabSpec);
		tagHostSpecList.add(wordDictionaryTabSpec);

		tabHost.setCurrentTab(tagHostSpecList.size() - 1);

		counter++;
	}

	private void delCurrentTab(TabHost tabHost) {

		int currentTab = tabHost.getCurrentTab();

		tagHostSpecList.remove(currentTab);

		if (tagHostSpecList.size() == 0) {
			finish();

			return;
		}

		tabHost.clearAllTabs();

		for (TabHost.TabSpec spec : tagHostSpecList) {
			tabHost.addTab(spec);
		}

		if (currentTab >= tagHostSpecList.size()) {
			currentTab = tagHostSpecList.size();
		}

		currentTab = currentTab - 1;

		if (currentTab < 0) {
			currentTab = 0;
		}

		tabHost.setCurrentTab(currentTab);
	}
} public class InfoActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);

        JapaneseAndroidLearnHelperApplication.getInstance().setContentViewAndTheme(this, R.layout.info);
        
        JapaneseAndroidLearnHelperApplication.getInstance().logScreen(this, getString(R.string.logs_info));

        TextView titleVersion = (TextView)findViewById(R.id.info_title_version);
        
        String versionName = "";
        int versionCode = 0;
        
        try {
        	PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        	
            versionName = packageInfo.versionName;
            versionCode = packageInfo.versionCode;

        } catch (NameNotFoundException e) {        	
        }
        
        titleVersion.setText(getString(R.string.info_version, versionCode, versionName));
        
        TextView infoBody = (TextView)findViewById(R.id.info_body);
        
        infoBody.setMovementMethod(LinkMovementMethod.getInstance());
    }
} public class Kana extends Activity {

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		super.onCreateOptionsMenu(menu);

		JapaneseAndroidLearnHelperApplication.getInstance().logScreen(this, getString(R.string.logs_kana));
		
		MenuShorterHelper.onCreateOptionsMenu(menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		return MenuShorterHelper.onOptionsItemSelected(item, getApplicationContext(), this);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		JapaneseAndroidLearnHelperApplication.getInstance().setContentViewAndTheme(this, R.layout.word_kana);

		TableLayout mainTableLayout = (TableLayout) findViewById(R.id.word_kana_main_layout);

		final List<IScreenItem> screenItems = new ArrayList<IScreenItem>();

		Map<String, KanaEntry> kanaCache = JapaneseAndroidLearnHelperApplication.getInstance()
				.getDictionaryManager(Kana.this).getKanaHelper().getKanaCache(true);

		Typeface radicalTypeface = JapaneseAndroidLearnHelperApplication.getInstance().getBabelStoneHanSubset(getAssets());
		
		generateHiraganaTable(screenItems, kanaCache, radicalTypeface);
		generateKatakanaTable(screenItems, kanaCache, radicalTypeface);
		generateKatakanaAdditionalTable(screenItems, kanaCache, radicalTypeface);

		fillMainLayout(screenItems, mainTableLayout);

		/*
		Button reportProblemButton = (Button) findViewById(R.id.word_kana_report_problem_button);

		reportProblemButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {

				StringBuffer detailsSb = new StringBuffer();

				for (IScreenItem currentscreenItem : screenItems) {
					detailsSb.append(currentscreenItem.toString()).append("\n\n");
				}

				String chooseEmailClientTitle = getString(R.string.choose_email_client);

				String mailSubject = getString(R.string.kana_report_problem_email_subject);

				String mailBody = getString(R.string.kana_report_problem_email_body, detailsSb.toString());

				String versionName = "";
				int versionCode = 0;

				try {
					PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);

					versionName = packageInfo.versionName;
					versionCode = packageInfo.versionCode;

				} catch (NameNotFoundException e) {
				}

				Intent reportProblemIntent = ReportProblem.createReportProblemIntent(mailSubject, mailBody.toString(),
						versionName, versionCode);

				startActivity(Intent.createChooser(reportProblemIntent, chooseEmailClientTitle));
			}
		});
		*/
	}

	private void generateHiraganaTable(List<IScreenItem> screenItems, Map<String, KanaEntry> kanaCache, Typeface babelStoneHanTypeface) {

		screenItems.add(new TitleItem(getString(R.string.kana_hiragana_label), 0));
		screenItems.add(new StringValue(getString(R.string.kana_info), 12.0f, 0));
		screenItems.add(new StringValue(getString(R.string.kana_info2), 12.0f, 0));

		pl.idedyk.android.japaneselearnhelper.screen.TableRow a_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(a_tableRow, kanaCache, "あ", babelStoneHanTypeface);
		addKanaItem(a_tableRow, kanaCache, "い", babelStoneHanTypeface);
		addKanaItem(a_tableRow, kanaCache, "う", babelStoneHanTypeface);
		addKanaItem(a_tableRow, kanaCache, "え", babelStoneHanTypeface);
		addKanaItem(a_tableRow, kanaCache, "お", babelStoneHanTypeface);

		screenItems.add(a_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow k_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(k_tableRow, kanaCache, "か", babelStoneHanTypeface);
		addKanaItem(k_tableRow, kanaCache, "き", babelStoneHanTypeface);
		addKanaItem(k_tableRow, kanaCache, "く", babelStoneHanTypeface);
		addKanaItem(k_tableRow, kanaCache, "け", babelStoneHanTypeface);
		addKanaItem(k_tableRow, kanaCache, "こ", babelStoneHanTypeface);

		screenItems.add(k_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow s_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(s_tableRow, kanaCache, "さ", babelStoneHanTypeface);
		addKanaItem(s_tableRow, kanaCache, "し", babelStoneHanTypeface);
		addKanaItem(s_tableRow, kanaCache, "す", babelStoneHanTypeface);
		addKanaItem(s_tableRow, kanaCache, "せ", babelStoneHanTypeface);
		addKanaItem(s_tableRow, kanaCache, "そ", babelStoneHanTypeface);

		screenItems.add(s_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow t_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(t_tableRow, kanaCache, "た", babelStoneHanTypeface);
		addKanaItem(t_tableRow, kanaCache, "ち", babelStoneHanTypeface);
		addKanaItem(t_tableRow, kanaCache, "つ", babelStoneHanTypeface);
		addKanaItem(t_tableRow, kanaCache, "て", babelStoneHanTypeface);
		addKanaItem(t_tableRow, kanaCache, "と", babelStoneHanTypeface);

		screenItems.add(t_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow n_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(n_tableRow, kanaCache, "な", babelStoneHanTypeface);
		addKanaItem(n_tableRow, kanaCache, "に", babelStoneHanTypeface);
		addKanaItem(n_tableRow, kanaCache, "ぬ", babelStoneHanTypeface);
		addKanaItem(n_tableRow, kanaCache, "ね", babelStoneHanTypeface);
		addKanaItem(n_tableRow, kanaCache, "の", babelStoneHanTypeface);

		screenItems.add(n_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow h_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(h_tableRow, kanaCache, "は", babelStoneHanTypeface);
		addKanaItem(h_tableRow, kanaCache, "ひ", babelStoneHanTypeface);
		addKanaItem(h_tableRow, kanaCache, "ふ", babelStoneHanTypeface);
		addKanaItem(h_tableRow, kanaCache, "へ", babelStoneHanTypeface);
		addKanaItem(h_tableRow, kanaCache, "ほ", babelStoneHanTypeface);

		screenItems.add(h_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow m_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(m_tableRow, kanaCache, "ま", babelStoneHanTypeface);
		addKanaItem(m_tableRow, kanaCache, "み", babelStoneHanTypeface);
		addKanaItem(m_tableRow, kanaCache, "む", babelStoneHanTypeface);
		addKanaItem(m_tableRow, kanaCache, "め", babelStoneHanTypeface);
		addKanaItem(m_tableRow, kanaCache, "も", babelStoneHanTypeface);

		screenItems.add(m_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow y_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(y_tableRow, kanaCache, "や", babelStoneHanTypeface);
		addKanaItem(y_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(y_tableRow, kanaCache, "ゆ", babelStoneHanTypeface);
		addKanaItem(y_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(y_tableRow, kanaCache, "よ", babelStoneHanTypeface);

		screenItems.add(y_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow r_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(r_tableRow, kanaCache, "ら", babelStoneHanTypeface);
		addKanaItem(r_tableRow, kanaCache, "り", babelStoneHanTypeface);
		addKanaItem(r_tableRow, kanaCache, "る", babelStoneHanTypeface);
		addKanaItem(r_tableRow, kanaCache, "れ", babelStoneHanTypeface);
		addKanaItem(r_tableRow, kanaCache, "ろ", babelStoneHanTypeface);

		screenItems.add(r_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow w_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(w_tableRow, kanaCache, "わ", babelStoneHanTypeface);
		addKanaItem(w_tableRow, kanaCache, "ゐ", babelStoneHanTypeface);
		addKanaItem(w_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(w_tableRow, kanaCache, "ゑ", babelStoneHanTypeface);
		addKanaItem(w_tableRow, kanaCache, "を", babelStoneHanTypeface);

		screenItems.add(w_tableRow);
		
		pl.idedyk.android.japaneselearnhelper.screen.TableRow v_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(v_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(v_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(v_tableRow, kanaCache, "ゔ", babelStoneHanTypeface);
		addKanaItem(v_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(v_tableRow, kanaCache, null, babelStoneHanTypeface);
		
		screenItems.add(v_tableRow);
		
		pl.idedyk.android.japaneselearnhelper.screen.TableRow n2_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(n2_tableRow, kanaCache, "ん", babelStoneHanTypeface);
		addKanaItem(n2_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(n2_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(n2_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(n2_tableRow, kanaCache, null, babelStoneHanTypeface);

		screenItems.add(n2_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow g_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(g_tableRow, kanaCache, "が", babelStoneHanTypeface);
		addKanaItem(g_tableRow, kanaCache, "ぎ", babelStoneHanTypeface);
		addKanaItem(g_tableRow, kanaCache, "ぐ", babelStoneHanTypeface);
		addKanaItem(g_tableRow, kanaCache, "げ", babelStoneHanTypeface);
		addKanaItem(g_tableRow, kanaCache, "ご", babelStoneHanTypeface);

		screenItems.add(g_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow z_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(z_tableRow, kanaCache, "ざ", babelStoneHanTypeface);
		addKanaItem(z_tableRow, kanaCache, "じ", babelStoneHanTypeface);
		addKanaItem(z_tableRow, kanaCache, "ず", babelStoneHanTypeface);
		addKanaItem(z_tableRow, kanaCache, "ぜ", babelStoneHanTypeface);
		addKanaItem(z_tableRow, kanaCache, "ぞ", babelStoneHanTypeface);

		screenItems.add(z_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow d_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(d_tableRow, kanaCache, "だ", babelStoneHanTypeface);
		addKanaItem(d_tableRow, kanaCache, "ぢ", babelStoneHanTypeface);
		addKanaItem(d_tableRow, kanaCache, "づ", babelStoneHanTypeface);
		addKanaItem(d_tableRow, kanaCache, "で", babelStoneHanTypeface);
		addKanaItem(d_tableRow, kanaCache, "ど", babelStoneHanTypeface);

		screenItems.add(d_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow b_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(b_tableRow, kanaCache, "ば", babelStoneHanTypeface);
		addKanaItem(b_tableRow, kanaCache, "び", babelStoneHanTypeface);
		addKanaItem(b_tableRow, kanaCache, "ぶ", babelStoneHanTypeface);
		addKanaItem(b_tableRow, kanaCache, "べ", babelStoneHanTypeface);
		addKanaItem(b_tableRow, kanaCache, "ぼ", babelStoneHanTypeface);

		screenItems.add(b_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow p_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(p_tableRow, kanaCache, "ぱ", babelStoneHanTypeface);
		addKanaItem(p_tableRow, kanaCache, "ぴ", babelStoneHanTypeface);
		addKanaItem(p_tableRow, kanaCache, "ぷ", babelStoneHanTypeface);
		addKanaItem(p_tableRow, kanaCache, "ぺ", babelStoneHanTypeface);
		addKanaItem(p_tableRow, kanaCache, "ぽ", babelStoneHanTypeface);

		screenItems.add(p_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow ky_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(ky_tableRow, kanaCache, "きゃ", babelStoneHanTypeface);
		addKanaItem(ky_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(ky_tableRow, kanaCache, "きゅ", babelStoneHanTypeface);
		addKanaItem(ky_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(ky_tableRow, kanaCache, "きょ", babelStoneHanTypeface);

		screenItems.add(ky_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow shy_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(shy_tableRow, kanaCache, "しゃ", babelStoneHanTypeface);
		addKanaItem(shy_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(shy_tableRow, kanaCache, "しゅ", babelStoneHanTypeface);
		addKanaItem(shy_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(shy_tableRow, kanaCache, "しょ", babelStoneHanTypeface);

		screenItems.add(shy_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow chy_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(chy_tableRow, kanaCache, "ちゃ", babelStoneHanTypeface);
		addKanaItem(chy_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(chy_tableRow, kanaCache, "ちゅ", babelStoneHanTypeface);
		addKanaItem(chy_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(chy_tableRow, kanaCache, "ちょ", babelStoneHanTypeface);

		screenItems.add(chy_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow ny_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(ny_tableRow, kanaCache, "にゃ", babelStoneHanTypeface);
		addKanaItem(ny_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(ny_tableRow, kanaCache, "にゅ", babelStoneHanTypeface);
		addKanaItem(ny_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(ny_tableRow, kanaCache, "にょ", babelStoneHanTypeface);

		screenItems.add(ny_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow hy_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(hy_tableRow, kanaCache, "ひゃ", babelStoneHanTypeface);
		addKanaItem(hy_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(hy_tableRow, kanaCache, "ひゅ", babelStoneHanTypeface);
		addKanaItem(hy_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(hy_tableRow, kanaCache, "ひょ", babelStoneHanTypeface);

		screenItems.add(hy_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow my_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(my_tableRow, kanaCache, "みゃ", babelStoneHanTypeface);
		addKanaItem(my_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(my_tableRow, kanaCache, "みゅ", babelStoneHanTypeface);
		addKanaItem(my_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(my_tableRow, kanaCache, "みょ", babelStoneHanTypeface);

		screenItems.add(my_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow ry_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(ry_tableRow, kanaCache, "りゃ", babelStoneHanTypeface);
		addKanaItem(ry_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(ry_tableRow, kanaCache, "りゅ", babelStoneHanTypeface);
		addKanaItem(ry_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(ry_tableRow, kanaCache, "りょ", babelStoneHanTypeface);

		screenItems.add(ry_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow gy_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(gy_tableRow, kanaCache, "ぎゃ", babelStoneHanTypeface);
		addKanaItem(gy_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(gy_tableRow, kanaCache, "ぎゅ", babelStoneHanTypeface);
		addKanaItem(gy_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(gy_tableRow, kanaCache, "ぎょ", babelStoneHanTypeface);

		screenItems.add(gy_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow jy_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(jy_tableRow, kanaCache, "じゃ", babelStoneHanTypeface);
		addKanaItem(jy_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(jy_tableRow, kanaCache, "じゅ", babelStoneHanTypeface);
		addKanaItem(jy_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(jy_tableRow, kanaCache, "じょ", babelStoneHanTypeface);

		screenItems.add(jy_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow by_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(by_tableRow, kanaCache, "びゃ", babelStoneHanTypeface);
		addKanaItem(by_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(by_tableRow, kanaCache, "びゅ", babelStoneHanTypeface);
		addKanaItem(by_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(by_tableRow, kanaCache, "びょ", babelStoneHanTypeface);

		screenItems.add(by_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow py_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(py_tableRow, kanaCache, "ぴゃ", babelStoneHanTypeface);
		addKanaItem(py_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(py_tableRow, kanaCache, "ぴゅ", babelStoneHanTypeface);
		addKanaItem(py_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(py_tableRow, kanaCache, "ぴょ", babelStoneHanTypeface);

		screenItems.add(py_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow dy_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(dy_tableRow, kanaCache, "ぢゃ", babelStoneHanTypeface);
		addKanaItem(dy_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(dy_tableRow, kanaCache, "ぢゅ", babelStoneHanTypeface);
		addKanaItem(dy_tableRow, kanaCache, null, babelStoneHanTypeface);
		addKanaItem(dy_tableRow, kanaCache, "ぢょ", babelStoneHanTypeface);

		screenItems.add(dy_tableRow);
	}

	private void generateKatakanaTable(List<IScreenItem> screenItems, Map<String, KanaEntry> kanaCache, Typeface radicalTypeface) {

		screenItems.add(new TitleItem(getString(R.string.kana_katakana_label), 0));
		screenItems.add(new StringValue(getString(R.string.kana_info), 12.0f, 0));
		screenItems.add(new StringValue(getString(R.string.kana_info2), 12.0f, 0));

		pl.idedyk.android.japaneselearnhelper.screen.TableRow a_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(a_tableRow, kanaCache, "ア", radicalTypeface);
		addKanaItem(a_tableRow, kanaCache, "イ", radicalTypeface);
		addKanaItem(a_tableRow, kanaCache, "ウ", radicalTypeface);
		addKanaItem(a_tableRow, kanaCache, "エ", radicalTypeface);
		addKanaItem(a_tableRow, kanaCache, "オ", radicalTypeface);

		screenItems.add(a_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow k_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(k_tableRow, kanaCache, "カ", radicalTypeface);
		addKanaItem(k_tableRow, kanaCache, "キ", radicalTypeface);
		addKanaItem(k_tableRow, kanaCache, "ク", radicalTypeface);
		addKanaItem(k_tableRow, kanaCache, "ケ", radicalTypeface);
		addKanaItem(k_tableRow, kanaCache, "コ", radicalTypeface);

		screenItems.add(k_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow s_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(s_tableRow, kanaCache, "サ", radicalTypeface);
		addKanaItem(s_tableRow, kanaCache, "シ", radicalTypeface);
		addKanaItem(s_tableRow, kanaCache, "ス", radicalTypeface);
		addKanaItem(s_tableRow, kanaCache, "セ", radicalTypeface);
		addKanaItem(s_tableRow, kanaCache, "ソ", radicalTypeface);

		screenItems.add(s_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow t_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(t_tableRow, kanaCache, "タ", radicalTypeface);
		addKanaItem(t_tableRow, kanaCache, "チ", radicalTypeface);
		addKanaItem(t_tableRow, kanaCache, "ツ", radicalTypeface);
		addKanaItem(t_tableRow, kanaCache, "テ", radicalTypeface);
		addKanaItem(t_tableRow, kanaCache, "ト", radicalTypeface);

		screenItems.add(t_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow n_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(n_tableRow, kanaCache, "ナ", radicalTypeface);
		addKanaItem(n_tableRow, kanaCache, "ニ", radicalTypeface);
		addKanaItem(n_tableRow, kanaCache, "ヌ", radicalTypeface);
		addKanaItem(n_tableRow, kanaCache, "ネ", radicalTypeface);
		addKanaItem(n_tableRow, kanaCache, "ノ", radicalTypeface);

		screenItems.add(n_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow h_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(h_tableRow, kanaCache, "ハ", radicalTypeface);
		addKanaItem(h_tableRow, kanaCache, "ヒ", radicalTypeface);
		addKanaItem(h_tableRow, kanaCache, "フ", radicalTypeface);
		addKanaItem(h_tableRow, kanaCache, "ヘ", radicalTypeface);
		addKanaItem(h_tableRow, kanaCache, "ホ", radicalTypeface);

		screenItems.add(h_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow m_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(m_tableRow, kanaCache, "マ", radicalTypeface);
		addKanaItem(m_tableRow, kanaCache, "ミ", radicalTypeface);
		addKanaItem(m_tableRow, kanaCache, "ム", radicalTypeface);
		addKanaItem(m_tableRow, kanaCache, "メ", radicalTypeface);
		addKanaItem(m_tableRow, kanaCache, "モ", radicalTypeface);

		screenItems.add(m_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow y_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(y_tableRow, kanaCache, "ヤ", radicalTypeface);
		addKanaItem(y_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(y_tableRow, kanaCache, "ユ", radicalTypeface);
		addKanaItem(y_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(y_tableRow, kanaCache, "ヨ", radicalTypeface);

		screenItems.add(y_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow r_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(r_tableRow, kanaCache, "ラ", radicalTypeface);
		addKanaItem(r_tableRow, kanaCache, "リ", radicalTypeface);
		addKanaItem(r_tableRow, kanaCache, "ル", radicalTypeface);
		addKanaItem(r_tableRow, kanaCache, "レ", radicalTypeface);
		addKanaItem(r_tableRow, kanaCache, "ロ", radicalTypeface);

		screenItems.add(r_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow w_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(w_tableRow, kanaCache, "ワ", radicalTypeface);
		addKanaItem(w_tableRow, kanaCache, "ヰ", radicalTypeface);
		addKanaItem(w_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(w_tableRow, kanaCache, "ヱ", radicalTypeface);
		addKanaItem(w_tableRow, kanaCache, "ヲ", radicalTypeface);

		screenItems.add(w_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow n2_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(n2_tableRow, kanaCache, "ン", radicalTypeface);
		addKanaItem(n2_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(n2_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(n2_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(n2_tableRow, kanaCache, null, radicalTypeface);

		screenItems.add(n2_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow g_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(g_tableRow, kanaCache, "ガ", radicalTypeface);
		addKanaItem(g_tableRow, kanaCache, "ギ", radicalTypeface);
		addKanaItem(g_tableRow, kanaCache, "グ", radicalTypeface);
		addKanaItem(g_tableRow, kanaCache, "ゲ", radicalTypeface);
		addKanaItem(g_tableRow, kanaCache, "ゴ", radicalTypeface);

		screenItems.add(g_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow z_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(z_tableRow, kanaCache, "ザ", radicalTypeface);
		addKanaItem(z_tableRow, kanaCache, "ジ", radicalTypeface);
		addKanaItem(z_tableRow, kanaCache, "ズ", radicalTypeface);
		addKanaItem(z_tableRow, kanaCache, "ゼ", radicalTypeface);
		addKanaItem(z_tableRow, kanaCache, "ゾ", radicalTypeface);

		screenItems.add(z_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow d_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(d_tableRow, kanaCache, "ダ", radicalTypeface);
		addKanaItem(d_tableRow, kanaCache, "ヂ", radicalTypeface);
		addKanaItem(d_tableRow, kanaCache, "ヅ", radicalTypeface);
		addKanaItem(d_tableRow, kanaCache, "デ", radicalTypeface);
		addKanaItem(d_tableRow, kanaCache, "ド", radicalTypeface);

		screenItems.add(d_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow b_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(b_tableRow, kanaCache, "バ", radicalTypeface);
		addKanaItem(b_tableRow, kanaCache, "ビ", radicalTypeface);
		addKanaItem(b_tableRow, kanaCache, "ブ", radicalTypeface);
		addKanaItem(b_tableRow, kanaCache, "ベ", radicalTypeface);
		addKanaItem(b_tableRow, kanaCache, "ボ", radicalTypeface);

		screenItems.add(b_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow p_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(p_tableRow, kanaCache, "パ", radicalTypeface);
		addKanaItem(p_tableRow, kanaCache, "ピ", radicalTypeface);
		addKanaItem(p_tableRow, kanaCache, "プ", radicalTypeface);
		addKanaItem(p_tableRow, kanaCache, "ペ", radicalTypeface);
		addKanaItem(p_tableRow, kanaCache, "ポ", radicalTypeface);

		screenItems.add(p_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow ky_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(ky_tableRow, kanaCache, "キャ", radicalTypeface);
		addKanaItem(ky_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(ky_tableRow, kanaCache, "キュ", radicalTypeface);
		addKanaItem(ky_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(ky_tableRow, kanaCache, "キョ", radicalTypeface);

		screenItems.add(ky_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow shy_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(shy_tableRow, kanaCache, "シャ", radicalTypeface);
		addKanaItem(shy_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(shy_tableRow, kanaCache, "シュ", radicalTypeface);
		addKanaItem(shy_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(shy_tableRow, kanaCache, "ショ", radicalTypeface);

		screenItems.add(shy_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow chy_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(chy_tableRow, kanaCache, "チャ", radicalTypeface);
		addKanaItem(chy_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(chy_tableRow, kanaCache, "チュ", radicalTypeface);
		addKanaItem(chy_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(chy_tableRow, kanaCache, "チョ", radicalTypeface);

		screenItems.add(chy_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow ny_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(ny_tableRow, kanaCache, "ニャ", radicalTypeface);
		addKanaItem(ny_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(ny_tableRow, kanaCache, "ニュ", radicalTypeface);
		addKanaItem(ny_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(ny_tableRow, kanaCache, "ニョ", radicalTypeface);

		screenItems.add(ny_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow hy_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(hy_tableRow, kanaCache, "ヒャ", radicalTypeface);
		addKanaItem(hy_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(hy_tableRow, kanaCache, "ヒュ", radicalTypeface);
		addKanaItem(hy_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(hy_tableRow, kanaCache, "ヒョ", radicalTypeface);

		screenItems.add(hy_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow my_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(my_tableRow, kanaCache, "ミャ", radicalTypeface);
		addKanaItem(my_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(my_tableRow, kanaCache, "ミュ", radicalTypeface);
		addKanaItem(my_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(my_tableRow, kanaCache, "ミョ", radicalTypeface);

		screenItems.add(my_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow ry_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(ry_tableRow, kanaCache, "リャ", radicalTypeface);
		addKanaItem(ry_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(ry_tableRow, kanaCache, "リュ", radicalTypeface);
		addKanaItem(ry_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(ry_tableRow, kanaCache, "リョ", radicalTypeface);

		screenItems.add(ry_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow gy_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(gy_tableRow, kanaCache, "ギャ", radicalTypeface);
		addKanaItem(gy_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(gy_tableRow, kanaCache, "ギュ", radicalTypeface);
		addKanaItem(gy_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(gy_tableRow, kanaCache, "ギョ", radicalTypeface);

		screenItems.add(gy_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow jy_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(jy_tableRow, kanaCache, "ジャ", radicalTypeface);
		addKanaItem(jy_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(jy_tableRow, kanaCache, "ジュ", radicalTypeface);
		addKanaItem(jy_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(jy_tableRow, kanaCache, "ジョ", radicalTypeface);

		screenItems.add(jy_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow by_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(by_tableRow, kanaCache, "ビャ", radicalTypeface);
		addKanaItem(by_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(by_tableRow, kanaCache, "ビュ", radicalTypeface);
		addKanaItem(by_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(by_tableRow, kanaCache, "ビョ", radicalTypeface);

		screenItems.add(by_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow py_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(py_tableRow, kanaCache, "ピャ", radicalTypeface);
		addKanaItem(py_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(py_tableRow, kanaCache, "ピュ", radicalTypeface);
		addKanaItem(py_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(py_tableRow, kanaCache, "ピョ", radicalTypeface);

		screenItems.add(py_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow dy_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(dy_tableRow, kanaCache, "ヂャ", radicalTypeface);
		addKanaItem(dy_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(dy_tableRow, kanaCache, "ヂュ", radicalTypeface);
		addKanaItem(dy_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(dy_tableRow, kanaCache, "ヂョ", radicalTypeface);

		screenItems.add(dy_tableRow);
	}

	private void generateKatakanaAdditionalTable(List<IScreenItem> screenItems, Map<String, KanaEntry> kanaCache, Typeface radicalTypeface) {

		screenItems.add(new TitleItem(getString(R.string.kana_katakana_additional_label), 0));
		screenItems.add(new StringValue(getString(R.string.kana_info), 12.0f, 0));
		screenItems.add(new StringValue(getString(R.string.kana_info2), 12.0f, 0));
		//screenItems.add(new StringValue(getString(R.string.kana_info3), 12.0f, 0));
		
		pl.idedyk.android.japaneselearnhelper.screen.TableRow ye_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(ye_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(ye_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(ye_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(ye_tableRow, kanaCache, "イェ", radicalTypeface);
		addKanaItem(ye_tableRow, kanaCache, null, radicalTypeface);

		screenItems.add(ye_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow u_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(u_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(u_tableRow, kanaCache, "ウィ", radicalTypeface);
		addKanaItem(u_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(u_tableRow, kanaCache, "ウェ", radicalTypeface);
		addKanaItem(u_tableRow, kanaCache, "ウォ", radicalTypeface);

		screenItems.add(u_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow v1_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(v1_tableRow, kanaCache, "ヷ", radicalTypeface);
		addKanaItem(v1_tableRow, kanaCache, "ヸ", radicalTypeface);
		addKanaItem(v1_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(v1_tableRow, kanaCache, "ヹ", radicalTypeface);
		addKanaItem(v1_tableRow, kanaCache, "ヺ", radicalTypeface);

		screenItems.add(v1_tableRow);
		
		pl.idedyk.android.japaneselearnhelper.screen.TableRow v2_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(v2_tableRow, kanaCache, "ヴァ", radicalTypeface);
		addKanaItem(v2_tableRow, kanaCache, "ヴィ", radicalTypeface);
		addKanaItem(v2_tableRow, kanaCache, "ヴ", radicalTypeface);
		addKanaItem(v2_tableRow, kanaCache, "ヴェ", radicalTypeface);
		addKanaItem(v2_tableRow, kanaCache, "ヴォ", radicalTypeface);

		screenItems.add(v2_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow s_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(s_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(s_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(s_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(s_tableRow, kanaCache, "シェ", radicalTypeface);
		addKanaItem(s_tableRow, kanaCache, null, radicalTypeface);

		screenItems.add(s_tableRow);
		
		pl.idedyk.android.japaneselearnhelper.screen.TableRow j_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(j_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(j_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(j_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(j_tableRow, kanaCache, "ジェ", radicalTypeface);
		addKanaItem(j_tableRow, kanaCache, null, radicalTypeface);

		screenItems.add(j_tableRow);
		
		pl.idedyk.android.japaneselearnhelper.screen.TableRow c_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(c_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(c_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(c_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(c_tableRow, kanaCache, "チェ", radicalTypeface);
		addKanaItem(c_tableRow, kanaCache, null, radicalTypeface);

		screenItems.add(c_tableRow);
		
		pl.idedyk.android.japaneselearnhelper.screen.TableRow t_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(t_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(t_tableRow, kanaCache, "ティ", radicalTypeface);
		addKanaItem(t_tableRow, kanaCache, "トゥ", radicalTypeface);
		addKanaItem(t_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(t_tableRow, kanaCache, null, radicalTypeface);

		screenItems.add(t_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow tyu_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(tyu_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(tyu_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(tyu_tableRow, kanaCache, "テュ", radicalTypeface);
		addKanaItem(tyu_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(tyu_tableRow, kanaCache, null, radicalTypeface);

		screenItems.add(tyu_tableRow);
		
		pl.idedyk.android.japaneselearnhelper.screen.TableRow d_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(d_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(d_tableRow, kanaCache, "ディ", radicalTypeface);
		addKanaItem(d_tableRow, kanaCache, "ドゥ", radicalTypeface);
		addKanaItem(d_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(d_tableRow, kanaCache, null, radicalTypeface);

		screenItems.add(d_tableRow);

		pl.idedyk.android.japaneselearnhelper.screen.TableRow dyu_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(dyu_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(dyu_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(dyu_tableRow, kanaCache, "デュ", radicalTypeface);
		addKanaItem(dyu_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(dyu_tableRow, kanaCache, null, radicalTypeface);

		screenItems.add(dyu_tableRow);
		
		pl.idedyk.android.japaneselearnhelper.screen.TableRow ts_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(ts_tableRow, kanaCache, "ツァ", radicalTypeface);
		addKanaItem(ts_tableRow, kanaCache, "ツィ", radicalTypeface);
		addKanaItem(ts_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(ts_tableRow, kanaCache, "ツェ", radicalTypeface);
		addKanaItem(ts_tableRow, kanaCache, "ツォ", radicalTypeface);

		screenItems.add(ts_tableRow);
		
		pl.idedyk.android.japaneselearnhelper.screen.TableRow f_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(f_tableRow, kanaCache, "ファ", radicalTypeface);
		addKanaItem(f_tableRow, kanaCache, "フィ", radicalTypeface);
		addKanaItem(f_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(f_tableRow, kanaCache, "フェ", radicalTypeface);
		addKanaItem(f_tableRow, kanaCache, "フォ", radicalTypeface);

		screenItems.add(f_tableRow);		

		pl.idedyk.android.japaneselearnhelper.screen.TableRow fyu_tableRow = new pl.idedyk.android.japaneselearnhelper.screen.TableRow();

		addKanaItem(fyu_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(fyu_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(fyu_tableRow, kanaCache, "フュ", radicalTypeface);
		addKanaItem(fyu_tableRow, kanaCache, null, radicalTypeface);
		addKanaItem(fyu_tableRow, kanaCache, null, radicalTypeface);

		screenItems.add(fyu_tableRow);
	}

	private void addKanaItem(pl.idedyk.android.japaneselearnhelper.screen.TableRow tableRow,
			Map<String, KanaEntry> kanaCache, String kana, Typeface radicalTypeface) {

		addKanaItem(tableRow, kanaCache, kana, null, radicalTypeface);
	}
	
	private void addKanaItem(pl.idedyk.android.japaneselearnhelper.screen.TableRow tableRow,
			Map<String, KanaEntry> kanaCache, String kana, String forceKanaDisplay, Typeface radicalTypeface) {

		StringValue stringValue = null;

		if (kana != null) {
			final KanaEntry kanaEntry = kanaCache.get(kana);

			if (kanaEntry == null) {
				throw new RuntimeException(kana);
			}
			
			boolean use = kanaEntry.isUse();

			Spanned spanned = Html.fromHtml("<b>" + kanaEntry.getKanaDisplay() + 
					(use == true ? "" : " *") +
					"</b><br/>"
					+ (forceKanaDisplay == null ? kanaEntry.getKanaJapanese() : forceKanaDisplay) + "<br/>");

			stringValue = new StringValue(spanned, 20, 0);

			stringValue.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					List<KanjivgEntry> allStrokePaths = kanaEntry.getStrokePaths();

					StrokePathInfo strokePathInfo = new StrokePathInfo();
					strokePathInfo.setStrokePaths(allStrokePaths);

					Intent intent = new Intent(getApplicationContext(), SodActivity.class);

					intent.putExtra("strokePathsInfo", strokePathInfo);

					startActivity(intent);
				}
			});

		} else {
			stringValue = new StringValue("", 20, 0);
		}

		stringValue.setTypeface(radicalTypeface);
		stringValue.setGravity(Gravity.CENTER);
		stringValue.setNullMargins(true);

		tableRow.addScreenItem(stringValue);
	}

	private void fillMainLayout(List<IScreenItem> generatedDetails, TableLayout mainTableLayout) {

		for (IScreenItem currentDetailsReportItem : generatedDetails) {
			currentDetailsReportItem.generate(this, getResources(), mainTableLayout);
		}
	}
} public class KanaTestOptions extends Activity {
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);

		JapaneseAndroidLearnHelperApplication.getInstance().setContentViewAndTheme(this, R.layout.kana_test_options);
		
		JapaneseAndroidLearnHelperApplication.getInstance().logScreen(this, getString(R.string.logs_kana_test_options));

		LinearLayout mainLayout = (LinearLayout)findViewById(R.id.kana_test_options_main_layout);
		
		final List<IScreenItem> screenItems = generateOptionsScreen();
		
		fillMainLayout(screenItems, mainLayout);
	}

	private void fillMainLayout(List<IScreenItem> screenItems, LinearLayout mainLayout) {
		
		for (IScreenItem currentScreenItem : screenItems) {
			currentScreenItem.generate(this, getResources(), mainLayout);			
		}
	}
	
	private List<IScreenItem> generateOptionsScreen() {
		
		final JapaneseAndroidLearnHelperKanaTestContext kanaTestContext = JapaneseAndroidLearnHelperApplication.getInstance().getContext().getKanaTestContext();
		
		final KanaTestConfig kanaTestConfig = JapaneseAndroidLearnHelperApplication.getInstance().getConfigManager(this).getKanaTestConfig();
		
		final List<IScreenItem> result = new ArrayList<IScreenItem>();
		
		result.add(new TitleItem(getString(R.string.kana_test_mode2), 0));
		
		final RadioGroup testMode2RadioGroup = new RadioGroup(this);
		
		TestMode2 testMode2 = kanaTestConfig.getTestMode2();
		
		testMode2RadioGroup.addRadioButton(this, getString(R.string.kana_test_mode2_kana_to_romaji), R.id.kana_test_mode2_kana_to_romaji_id, (testMode2 == null ? true : (testMode2 == TestMode2.KANA_TO_ROMAJI ? true : false)));
		
		testMode2RadioGroup.addRadioButton(this, getString(R.string.kana_test_mode2_romaji_to_kana), R.id.kana_test_mode2_romaji_to_kana_id, (testMode2 == TestMode2.ROMAJI_TO_KANA ? true : false));
		
		result.add(testMode2RadioGroup);
		//result.add(new StringValue(getString(R.string.kana_test_mode2_romaji_to_kana_info), 12.0f, 2));
		
		result.add(new TitleItem(getString(R.string.kana_test_range), 0));
		
		final RadioGroup rangeTestRadioGroup = new RadioGroup(this);
		
		RangeTest rangeTest = kanaTestConfig.getRangeTest();
		
		rangeTestRadioGroup.addRadioButton(this, getString(R.string.kana_test_range_hiragana), R.id.kana_test_range_hiragana_id, (rangeTest == RangeTest.HIRAGANA ? true : false));
		rangeTestRadioGroup.addRadioButton(this, getString(R.string.kana_test_range_katakana), R.id.kana_test_range_katakana_id, (rangeTest == RangeTest.KATAKANA ? true : false));
		rangeTestRadioGroup.addRadioButton(this, getString(R.string.kana_test_range_hiragana_katakana), R.id.kana_test_range_hiragana_katakana_id, (rangeTest == null ? true : (rangeTest == RangeTest.HIRAGANA_KATAKANA ? true : false)));
		
		result.add(rangeTestRadioGroup);
		
		/*
		result.add(new TitleItem(getString(R.string.kana_test_mode1), 0));
		
		final RadioGroup testMode1RadioGroup = new RadioGroup(this);
		
		TestMode1 testMode1 = kanaTestContext.getTestMode1();
		
		testMode1RadioGroup.addRadioButton(this, getString(R.string.kana_test_mode1_choose), R.id.kana_test_mode1_choose_id, (testMode1 == null ? true : (testMode1 == TestMode1.CHOOSE ? true : false)));
		testMode1RadioGroup.addRadioButton(this, getString(R.string.kana_test_mode1_input), R.id.kana_test_mode1_input_id, (testMode1 == TestMode1.INPUT ? true : false));
		
		result.add(testMode1RadioGroup);
		*/
		
		result.add(new TitleItem(getString(R.string.kana_test_char_range), 0));
		
		Boolean gojuuon = kanaTestConfig.getGojuuon();
		
		final CheckBox gojuuonCheckBox = new CheckBox(this, getString(R.string.kana_test_char_range_gojuuon), (gojuuon == null ? true : gojuuon.booleanValue()), R.id.kana_test_char_range_gojuuon);
		result.add(gojuuonCheckBox);
		
		Boolean dakutenHandakuten = kanaTestConfig.getDakutenHandakuten();
		
		final CheckBox dakutenHandakutenCheckBox = new CheckBox(this, getString(R.string.kana_test_char_range_dakuten_handakuten), (dakutenHandakuten == null ? true : dakutenHandakuten.booleanValue()), R.id.kana_test_char_range_dakuten_handakuten);
		result.add(dakutenHandakutenCheckBox);
		
		Boolean youon = kanaTestConfig.getYouon();
		
		final CheckBox youonCheckBox = new CheckBox(this, getString(R.string.kana_test_char_range_youon), (youon == null ? true : youon.booleanValue()), R.id.kana_test_char_range_youon);
		result.add(youonCheckBox);
				
		result.add(new TitleItem(getString(R.string.kana_test_other), 0));
		
		Boolean untilSuccess = kanaTestConfig.getUntilSuccess();
		
		final CheckBox untilSuccessCheckBox = new CheckBox(this, getString(R.string.kana_test_until_success), (untilSuccess == null ? true : untilSuccess.booleanValue()), R.id.kana_test_until_success_id);
		
		result.add(untilSuccessCheckBox);
		
		Boolean untilSuccessNewWordLimit = kanaTestConfig.getUntilSuccessNewWordLimit();

		final CheckBox untilSuccessNewWordLimitCheckBox = new CheckBox(this, getString(R.string.kana_test_until_success_new_word_limit), (untilSuccessNewWordLimit == null ? true : untilSuccessNewWordLimit.booleanValue()), R.id.kana_test_until_success_new_word_limit_id);
		
		result.add(untilSuccessNewWordLimitCheckBox);
		
		setUntilSuccessNewWordLimitCheckBoxEnabled(untilSuccessCheckBox, untilSuccessNewWordLimitCheckBox);
		
		// actions
		untilSuccessCheckBox. setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				setUntilSuccessNewWordLimitCheckBoxEnabled(untilSuccessCheckBox, untilSuccessNewWordLimitCheckBox);				
			}
		});
		
		pl.idedyk.android.japaneselearnhelper.screen.Button startButton = new pl.idedyk.android.japaneselearnhelper.screen.Button(
				getString(R.string.kana_test_options_startTest));
		
		startButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View view) {
				
				kanaTestContext.resetTest();
				
				int rangeTestRadioGroupCheckedRadioButtonId = rangeTestRadioGroup.getCheckedRadioButtonId();
				
				if (rangeTestRadioGroupCheckedRadioButtonId == R.id.kana_test_range_hiragana_id) {
					kanaTestConfig.setRangeTest(JapaneseAndroidLearnHelperKanaTestContext.RangeTest.HIRAGANA);
				} else if (rangeTestRadioGroupCheckedRadioButtonId == R.id.kana_test_range_katakana_id) {
					kanaTestConfig.setRangeTest(JapaneseAndroidLearnHelperKanaTestContext.RangeTest.KATAKANA);
				} else if (rangeTestRadioGroupCheckedRadioButtonId == R.id.kana_test_range_hiragana_katakana_id) {
					kanaTestConfig.setRangeTest(JapaneseAndroidLearnHelperKanaTestContext.RangeTest.HIRAGANA_KATAKANA);
				} else {
					throw new RuntimeException("rangeTestRadioGroupCheckedRadioButtonId: " + rangeTestRadioGroupCheckedRadioButtonId);
				}
				
				/*
				int testMode1RadioGroupCheckedRadioButtonId = testMode1RadioGroup.getCheckedRadioButtonId();
				
				if (testMode1RadioGroupCheckedRadioButtonId == R.id.kana_test_mode1_choose_id) {
					kanaTestContext.setTestMode1(JapaneseAndroidLearnHelperKanaTestContext.TestMode1.CHOOSE);
				} else if (testMode1RadioGroupCheckedRadioButtonId == R.id.kana_test_mode1_input_id) {
					kanaTestContext.setTestMode1(JapaneseAndroidLearnHelperKanaTestContext.TestMode1.INPUT);
				} else {
					throw new RuntimeException("testMode1RadioGroupCheckedRadioButtonId: " + testMode1RadioGroupCheckedRadioButtonId);
				}
				*/
				
				kanaTestConfig.setTestMode1(JapaneseAndroidLearnHelperKanaTestContext.TestMode1.CHOOSE);
				
				int testMode2RadioGroupCheckedRadioButtonId = testMode2RadioGroup.getCheckedRadioButtonId();
				
				if (testMode2RadioGroupCheckedRadioButtonId == R.id.kana_test_mode2_kana_to_romaji_id) {
					kanaTestConfig.setTestMode2(JapaneseAndroidLearnHelperKanaTestContext.TestMode2.KANA_TO_ROMAJI);
				} else if (testMode2RadioGroupCheckedRadioButtonId == R.id.kana_test_mode2_romaji_to_kana_id) {
					kanaTestConfig.setTestMode2(JapaneseAndroidLearnHelperKanaTestContext.TestMode2.ROMAJI_TO_KANA);
				} else {
					throw new RuntimeException("testMode2RadioGroupCheckedRadioButtonId: " + testMode2RadioGroupCheckedRadioButtonId);
				}
				
				kanaTestConfig.setUntilSuccess(untilSuccessCheckBox.isChecked());
				
				kanaTestConfig.setUntilSuccessNewWordLimit(untilSuccessNewWordLimitCheckBox.isChecked());
				
				if (gojuuonCheckBox.isChecked() == false && dakutenHandakutenCheckBox.isChecked() == false && 
						youonCheckBox.isChecked() == false) {
					
					Toast toast = Toast.makeText(KanaTestOptions.this, getString(R.string.kana_test_char_no_range), Toast.LENGTH_SHORT);
					
					toast.show();
					
					return;
				}
				
				kanaTestConfig.setGojuuon(gojuuonCheckBox.isChecked());
				kanaTestConfig.setDakutenHandakuten(dakutenHandakutenCheckBox.isChecked());
				kanaTestConfig.setYouon(youonCheckBox.isChecked());
				
				kanaTestContext.setInitialized(false);
				
				Intent intent = new Intent(getApplicationContext(), KanaTest.class);
				
				startActivity(intent);
				
				finish();
			}
		});
		
		result.add(new StringValue("", 12.0f, 0));
		
		result.add(startButton);

		/*
		Button reportProblemButton = (Button)findViewById(R.id.kana_test_options_report_problem_button);
		
		reportProblemButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View view) {
				
				StringBuffer detailsSb = new StringBuffer();
				
				for (IScreenItem currentScreenItem : result) {
					detailsSb.append(currentScreenItem.toString()).append("\n\n");
				}
				
				String chooseEmailClientTitle = getString(R.string.choose_email_client);
				
				String mailSubject = getString(R.string.kana_test_options_report_problem_email_subject);
				
				String mailBody = getString(R.string.kana_test_options_report_problem_email_body,
						detailsSb.toString());
				
		        String versionName = "";
		        int versionCode = 0;
		        
		        try {
		        	PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
		        	
		            versionName = packageInfo.versionName;
		            versionCode = packageInfo.versionCode;

		        } catch (NameNotFoundException e) {        	
		        }
								
				Intent reportProblemIntent = ReportProblem.createReportProblemIntent(mailSubject, mailBody.toString(), versionName, versionCode); 
				
				startActivity(Intent.createChooser(reportProblemIntent, chooseEmailClientTitle));
			}
		});
		*/
		
		return result;
	}
	
	private void setUntilSuccessNewWordLimitCheckBoxEnabled(CheckBox untilSuccessCheckBox, CheckBox untilSuccessNewWordLimitCheckBox) {
		
		if (untilSuccessCheckBox.isChecked() == true) {
			untilSuccessNewWordLimitCheckBox.setEnabled(true);
		} else {
			untilSuccessNewWordLimitCheckBox.setEnabled(false);
		}
	}
} @SuppressWarnings("deprecation")
public class KanjiSearch extends TabActivity {

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		MenuShorterHelper.onCreateOptionsMenu(menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		return MenuShorterHelper.onOptionsItemSelected(item, getApplicationContext(), this);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		JapaneseAndroidLearnHelperApplication.getInstance().setContentViewAndTheme(this, R.layout.kanji_search);

		TabHost tabHost = getTabHost();

		// radical search
		Intent kanjiSearchRadicalIntent = new Intent().setClass(this, KanjiSearchRadical.class);

		TabSpec kanjiSearchRadicalTabSpec = tabHost.newTabSpec("KanjiSearchRadical")
				.setIndicator(getString(R.string.kanji_search_type_radical)).setContent(kanjiSearchRadicalIntent);

		tabHost.addTab(kanjiSearchRadicalTabSpec);

		// kanji recognizer
		Intent kanjiRecognizeIntent = new Intent().setClass(this, KanjiRecognizeActivity.class);

		TabSpec kanjiRecognizeTabSpec = tabHost.newTabSpec("kanjiRecognizeTab")
				.setIndicator(getString(R.string.kanji_search_type_kanji_recognizer)).setContent(kanjiRecognizeIntent);

		tabHost.addTab(kanjiRecognizeTabSpec);

		// kanji search meaning
		Intent kanjiSearchMeaningIntent = new Intent().setClass(this, KanjiSearchMeaning.class);

		TabSpec kanjiSearchMeaningTabSpec = tabHost.newTabSpec("KanjiSearchMeaning")
				.setIndicator(getString(R.string.kanji_search_meaning)).setContent(kanjiSearchMeaningIntent);

		tabHost.addTab(kanjiSearchMeaningTabSpec);

		// kanji search stroke count
		Intent kanjiSearchStrokeCountIntent = new Intent().setClass(this, KanjiSearchStrokeCount.class);

		TabSpec kanjiSearchStrokeCountTabSpec = tabHost.newTabSpec("KanjiSearchStrokeCount")
				.setIndicator(getString(R.string.kanji_search_stroke_count)).setContent(kanjiSearchStrokeCountIntent);

		tabHost.addTab(kanjiSearchStrokeCountTabSpec);

		tabHost.setCurrentTab(0);

		//

		Toast.makeText(this, getString(R.string.kanji_search_info), Toast.LENGTH_SHORT).show();
	}
} public class KanjiRecognizeActivity extends Activity {

	private KanjiDrawView drawView;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		MenuShorterHelper.onCreateOptionsMenu(menu);
		
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		return MenuShorterHelper.onOptionsItemSelected(item, getApplicationContext(), this);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);

		JapaneseAndroidLearnHelperApplication.getInstance().setContentViewAndTheme(this, R.layout.kanji_recognizer);
		
		JapaneseAndroidLearnHelperApplication.getInstance().logScreen(this, getString(R.string.logs_kanji_recognize));

		init();
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);

		init();
	}

	private void init() {

		drawView = (KanjiDrawView) findViewById(R.id.kanji_recognizer_draw_view);

		Button undoButton = (Button) findViewById(R.id.kanji_recognizer_undo_button);

		undoButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				drawView.removeLastStroke();

			}
		});

		Button clearButton = (Button) findViewById(R.id.kanji_recognizer_clear_button);

		clearButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				drawView.clear();

			}
		});

		Button recognizeButton = (Button) findViewById(R.id.kanji_recognizer_recognize_button);

		recognizeButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {				
				
				final List<Stroke> strokes = drawView.getStrokes();
				
				if (strokes.size() == 0) {
					
					Toast toast = Toast.makeText(KanjiRecognizeActivity.this, getString(R.string.kanji_recognizer_please_draw), Toast.LENGTH_SHORT);
					
					toast.show();
					
					return;
				}
				
				final ProgressDialog progressDialog = ProgressDialog.show(KanjiRecognizeActivity.this, 
						getString(R.string.kanji_recognizer_recoginize1),
						getString(R.string.kanji_recognizer_recoginize2));
				
				final StringBuffer strokesStringBuffer = new StringBuffer();

				class RecognizeAsyncTaskResult {

					private DictionaryException dictionaryException;

					private List<KanjiEntry> kanjiEntryList;

					public RecognizeAsyncTaskResult(DictionaryException dictionaryException) {
						this.dictionaryException = dictionaryException;
					}

					public RecognizeAsyncTaskResult(List<KanjiEntry> kanjiEntryList) {
						this.kanjiEntryList = kanjiEntryList;
					}
				}

				class RecognizeAsyncTask extends AsyncTask<Void, Void, RecognizeAsyncTaskResult> {

					@Override
					protected RecognizeAsyncTaskResult doInBackground(Void... arg0) {

						DictionaryManagerCommon dictionaryManager = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(KanjiRecognizeActivity.this);
						
						ZinniaManagerCommon zinniaManager = dictionaryManager.getZinniaManager();
						
						// zinniaManager.open();

                        ZinniaManagerCommon.IZinnaManagerCharacter zinniaCharacter = zinniaManager.createNewCharacter();
						
						strokesStringBuffer.append("Width: " + drawView.getWidth()).append("\n\n");
						strokesStringBuffer.append("Height: " + drawView.getHeight()).append("\n");
						
						zinniaCharacter.clear();
						zinniaCharacter.setWidth(drawView.getWidth());
						zinniaCharacter.setHeight(drawView.getHeight());
						
						for (int idx = 0; idx < strokes.size(); ++idx) {
							
							strokesStringBuffer.append(String.valueOf((idx + 1))).append(":");
							
							Stroke currentStroke = strokes.get(idx);
							
							List<PointF> currentStrokePoints = currentStroke.getPoints();
							
							for (PointF currentStrokeCurrentPoint : currentStrokePoints) {
								zinniaCharacter.add(idx, (int)currentStrokeCurrentPoint.x, (int)currentStrokeCurrentPoint.y);
								
								strokesStringBuffer.append(currentStrokeCurrentPoint.x).append(" ").append(currentStrokeCurrentPoint.y).append(";");
							}
							
							strokesStringBuffer.append("\n\n");
						}

						List<KanjiRecognizerResultItem> recognizeResult = null;

						try {
							recognizeResult = zinniaCharacter.recognize(100);

						} catch (DictionaryException e) {
							return new RecognizeAsyncTaskResult(e);

						} finally {
							zinniaCharacter.destroy();
						}

						List<String> findKanjiListRequest = new ArrayList<>();

						for (KanjiRecognizerResultItem currentRecognizeResult : recognizeResult) {
							findKanjiListRequest.add(currentRecognizeResult.getKanji());
						}

						List<KanjiEntry> kanjiEntries = null;

						try {
							kanjiEntries = dictionaryManager.findKanjiList(findKanjiListRequest);
						} catch (DictionaryException e) {
							return new RecognizeAsyncTaskResult(e);
						}

						return new RecognizeAsyncTaskResult(kanjiEntries);
					}
					
				    @Override
				    protected void onPostExecute(RecognizeAsyncTaskResult result) {

				        super.onPostExecute(result);

				        if (progressDialog != null && progressDialog.isShowing()) {
				        	progressDialog.dismiss();
				        }

						if (result.dictionaryException != null) {

							Toast.makeText(KanjiRecognizeActivity.this, getString(R.string.dictionary_exception_common_error_message, result.dictionaryException.getMessage()), Toast.LENGTH_LONG).show();

							return;
						}

						Intent intent = new Intent(getApplicationContext(), KanjiRecognizerResult.class);
						
						KanjiEntry[] kanjiEntriesAsArray = new KanjiEntry[result.kanjiEntryList.size()];

						result.kanjiEntryList.toArray(kanjiEntriesAsArray);
						
						intent.putExtra("kanjiRecognizeResult", kanjiEntriesAsArray);
						intent.putExtra("kanjiRecognizeResultStrokes", strokesStringBuffer.toString());
						
						startActivity(intent);
				    }
				}
				
				new RecognizeAsyncTask().execute();
			}
		});
	}
} public class KanjiTestOptionsActivity extends Activity {
	
	private KanjiList kanjiList;

	private List<CheckBox> kanjiGroupList;
	//private List<CheckBox> kanjiOwnGroupList;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		menu.add(Menu.NONE, R.id.kanji_test_options_input_kanji_to_test, Menu.NONE,
				R.string.kanji_test_options_input_kanji_to_test);
		
		menu.add(Menu.NONE, R.id.kanji_test_options_clear_selected_kanji, Menu.NONE,
				R.string.kanji_test_options_clear_selected_kanji);

		/*
		menu.add(Menu.NONE, R.id.kanji_test_options_save_current_kanji_list_as_own_group, Menu.NONE,
				R.string.kanji_test_options_save_current_kanji_list_as_own_group);
		*/

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		if (item.getItemId() == R.id.kanji_test_options_input_kanji_to_test) {

			AlertDialog.Builder alert = new AlertDialog.Builder(this);

			alert.setTitle(getString(R.string.kanji_test_options_input_kanji_to_test));
			alert.setMessage(getString(R.string.kanji_test_options_input_kanji_to_test2));

			// Set an EditText view to get user input 
			final EditText input = new EditText(this);
			alert.setView(input);

			alert.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int whichButton) {

					String kanjiValue = input.getText().toString();

					List<KanjiEntry> knownKanjiList = null;

					try {
						knownKanjiList = JapaneseAndroidLearnHelperApplication.getInstance()
								.getDictionaryManager(KanjiTestOptionsActivity.this).findKnownKanji(kanjiValue);

					} catch (DictionaryException e) {

						Toast.makeText(KanjiTestOptionsActivity.this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();

						return;
					}

					List<String> allKanjisInGroup = new ArrayList<String>();

					StringBuffer allKanjiTest = new StringBuffer();

					for (KanjiEntry currentKanjiEntry : knownKanjiList) {

						if (currentKanjiEntry.isUsed() == true
								&& allKanjisInGroup.contains(currentKanjiEntry.getKanji()) == false) {
							allKanjisInGroup.add(currentKanjiEntry.getKanji());

							allKanjiTest.append(currentKanjiEntry.getKanji());
						}
					}

					if (allKanjisInGroup.size() == 0) {
						Toast.makeText(KanjiTestOptionsActivity.this,
								getString(R.string.kanji_test_options_input_no_kanji), Toast.LENGTH_SHORT).show();

						return;
					}

					for (CheckBox currentCheckBox : kanjiGroupList) {
						currentCheckBox.setChecked(false);
					}

					for (String currentInputedKanji : allKanjisInGroup) {
						kanjiList.setKanjiChecked(currentInputedKanji, true);
					}

					Toast.makeText(KanjiTestOptionsActivity.this,
							getString(R.string.kanji_test_options_input_detected_kanji, allKanjiTest.toString()),
							Toast.LENGTH_SHORT).show();

					showSelectedKanji();
				}
			});

			alert.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int whichButton) {
					// noop
				}
			});

			alert.show();

			return true;

		} else if (item.getItemId() == R.id.kanji_test_options_clear_selected_kanji) {

			for (CheckBox currentCheckBox : kanjiGroupList) {
				currentCheckBox.setChecked(false);
			}

			kanjiList.clearUserSelectedKanjiList();

			showSelectedKanji();

			Toast.makeText(KanjiTestOptionsActivity.this,
					getString(R.string.kanji_test_options_clear_selected_kanji_all), Toast.LENGTH_SHORT).show();

			return true;
			
		} /* else if (item.getItemId() == R.id.kanji_test_options_save_current_kanji_list_as_own_group) {
			
			final List<KanjiEntry> userSelectedKanjiList = kanjiList.getUserSelectedKanjiList();
						
			if (userSelectedKanjiList.size() == 0) {
				
				Toast.makeText(KanjiTestOptionsActivity.this,
						getString(R.string.kanji_test_options_save_current_kanji_list_as_own_group_please_choose_kanji),
						Toast.LENGTH_SHORT).show();
								
				return true;
			}
			
			AlertDialog.Builder alert = new AlertDialog.Builder(this);

			alert.setTitle(getString(R.string.kanji_test_options_save_current_kanji_list_as_own_group_dialog_title));

			// Set an EditText view to get user input 
			final EditText input = new EditText(this);
			
			input.setSingleLine(true);
			
			alert.setView(input);

			alert.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int whichButton) {
					
					String groupName = input.getText().toString();
					
					boolean isCorrectGroupName = true;
										
					if (groupName == null || groupName.trim().equals("") == true) {						
						isCorrectGroupName = false;						
					}
					
					if (isCorrectGroupName == true) {
						
						if (groupName.matches("([A-Z]|[a-z]| |[0-9])*") == false) {
							isCorrectGroupName = false;	
						}						
					}
					
					if (isCorrectGroupName == false) {
						
						Toast.makeText(KanjiTestOptionsActivity.this,
								getString(R.string.kanji_test_options_save_current_kanji_list_as_own_group_incorrect_group_name),
								Toast.LENGTH_SHORT).show();
						
						return;
					}					
					
					final KanjiTestConfig kanjiTestConfig = JapaneseAndroidLearnHelperApplication.getInstance()
							.getConfigManager(KanjiTestOptionsActivity.this).getKanjiTestConfig();

					// jesli grupa nieistnieje, dodaj ja
					if (kanjiTestConfig.isOwnGroupExists(groupName) == false) {
						
						// dodanie grupy
						kanjiTestConfig.addOwnGroup(groupName);
					}					
					
					// zapisanie znakow do grupy
					Set<String> userSelectedKanjiStringList = new TreeSet<String>();
					
					for (KanjiEntry kanjiEntry : userSelectedKanjiList) {
						userSelectedKanjiStringList.add(kanjiEntry.getKanji());
					}
					
					kanjiTestConfig.setOwnGroupKanjiList(groupName, userSelectedKanjiStringList);
					
					// wyswietlenie listy grup
					showOwnGroupList();					
				}
			});

			alert.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int whichButton) {
					// noop
				}
			});

			alert.show();

			return true;			
		}
		*/
		
		return false;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		JapaneseAndroidLearnHelperApplication.getInstance().setContentViewAndTheme(this, R.layout.kanji_test_options);
		
		JapaneseAndroidLearnHelperApplication.getInstance().logScreen(this, getString(R.string.logs_kanji_test_options));

		final KanjiTestConfig kanjiTestConfig = JapaneseAndroidLearnHelperApplication.getInstance()
				.getConfigManager(this).getKanjiTestConfig();

		final TextView testModeTextView = (TextView) findViewById(R.id.kanji_test_options_test_mode);

		final RadioButton testModeDrawKanjiFromMeaningRadioButton = (RadioButton) findViewById(R.id.kanji_test_options_test_mode_draw_kanji_from_meaning);
		final RadioButton testModeChooseKanjiFromMeaningRadioButton = (RadioButton) findViewById(R.id.kanji_test_options_test_mode_choose_kanji_from_meaning);
		final RadioButton testModeDrawKanjiFromInWord = (RadioButton) findViewById(R.id.kanji_test_options_test_mode_draw_kanji_in_word);
		final RadioButton testModeChooseKanjiFromInWord = (RadioButton) findViewById(R.id.kanji_test_options_test_mode_choose_kanji_in_word);

		KanjiTestMode kanjiTestMode = kanjiTestConfig.getKanjiTestMode();

		if (kanjiTestMode == KanjiTestMode.DRAW_KANJI_FROM_MEANING) {
			testModeDrawKanjiFromMeaningRadioButton.setChecked(true);
		} else if (kanjiTestMode == KanjiTestMode.CHOOSE_KANJI_FROM_MEANING) {
			testModeChooseKanjiFromMeaningRadioButton.setChecked(true);
		} else if (kanjiTestMode == KanjiTestMode.DRAW_KANJI_IN_WORD) {
			testModeDrawKanjiFromInWord.setChecked(true);
		} else if (kanjiTestMode == KanjiTestMode.CHOOSE_KANJI_IN_WORD) {
			testModeChooseKanjiFromInWord.setChecked(true);
		} else {
			throw new RuntimeException("KanjiTestMode kanjiTestMode: " + kanjiTestMode);
		}

		final TextView otherOptionsTextView = (TextView) findViewById(R.id.kanji_test_options_other_options);

		// until success
		final CheckBox untilSuccessCheckBox = (CheckBox) findViewById(R.id.kanji_test_options_until_success);

		untilSuccessCheckBox.setChecked(kanjiTestConfig.getUntilSuccess());

		// until success new word limit
		final CheckBox untilSuccessNewWordLimitCheckBox = (CheckBox) findViewById(R.id.kanji_test_options_until_success_new_word_limit);

		untilSuccessNewWordLimitCheckBox.setChecked(kanjiTestConfig.getUntilSuccessNewWordLimitPostfix());

		setUntilSuccessNewWordLimitCheckBoxEnabled(untilSuccessCheckBox, untilSuccessNewWordLimitCheckBox);
		
		// max test size
		final EditText maxTestSizeEditText = (EditText)findViewById(R.id.kanji_test_options_max_test_size_edit_text);
		
		maxTestSizeEditText.setText(String.valueOf(kanjiTestConfig.getMaxTestSize()));

		// actions
		untilSuccessCheckBox.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setUntilSuccessNewWordLimitCheckBoxEnabled(untilSuccessCheckBox, untilSuccessNewWordLimitCheckBox);
			}
		});

		// dedicate example
		final CheckBox dedicateExampleCheckBox = (CheckBox) findViewById(R.id.kanji_test_options_dedicate_example);

		dedicateExampleCheckBox.setChecked(kanjiTestConfig.getDedicateExample());

		final TextView chooseKanjiGroupTextView = (TextView) findViewById(R.id.kanji_test_options_choose_kanji_group);

		final TextView chosenKanjiTextView = (TextView) findViewById(R.id.kanji_test_options_chosen_kanji);

		final LinearLayout mainLayout = (LinearLayout) findViewById(R.id.kanji_test_options_main_layout);

		kanjiList = new KanjiList();
		kanjiGroupList = new ArrayList<CheckBox>();
		// kanjiOwnGroupList = new ArrayList<CheckBox>(); // stary mechanizm!!!

		final Button startTestButton = (Button) findViewById(R.id.kanji_test_options_start_test);

		startTestButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				if (testModeDrawKanjiFromMeaningRadioButton.isChecked() == true) {
					kanjiTestConfig.setKanjiTestMode(KanjiTestMode.DRAW_KANJI_FROM_MEANING);
				} else if (testModeChooseKanjiFromMeaningRadioButton.isChecked() == true) {
					kanjiTestConfig.setKanjiTestMode(KanjiTestMode.CHOOSE_KANJI_FROM_MEANING);
				} else if (testModeDrawKanjiFromInWord.isChecked() == true) {
					kanjiTestConfig.setKanjiTestMode(KanjiTestMode.DRAW_KANJI_IN_WORD);
				} else if (testModeChooseKanjiFromInWord.isChecked() == true) {
					kanjiTestConfig.setKanjiTestMode(KanjiTestMode.CHOOSE_KANJI_IN_WORD);
				} else {
					throw new RuntimeException("KanjiTestMode kanjiTestMode");
				}

				kanjiTestConfig.setUntilSuccess(untilSuccessCheckBox.isChecked());

				kanjiTestConfig.setUntilSuccessNewWordLimitPostfix(untilSuccessNewWordLimitCheckBox.isChecked());

				kanjiTestConfig.setDedicateExample(dedicateExampleCheckBox.isChecked());

				List<String> chosenKanjiList = new ArrayList<String>();

				for (KanjiEntry currentCheckBoxKanjiEntry : kanjiList.getUserSelectedKanjiList()) {
					chosenKanjiList.add(currentCheckBoxKanjiEntry.getKanji());
				}

				// find kanji entry list / get kanji with details
				final List<KanjiEntry> kanjiEntryList;

				try {
					kanjiEntryList = JapaneseAndroidLearnHelperApplication.getInstance()
							.getDictionaryManager(KanjiTestOptionsActivity.this)
							.findKanjiList(chosenKanjiList);
				} catch (DictionaryException e) {

					Toast.makeText(KanjiTestOptionsActivity.this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();

					return;
				}

				kanjiTestConfig.setChosenKanji(chosenKanjiList);

				// zapis grup wbudowanych i uzytkownika
				final List<String> chosenKanjiGroupList = new ArrayList<String>();

				List<Integer> chosenUserGroupsNumberList = new ArrayList<Integer>();
				final List<UserGroupEntity> chosenUserGroupEntityList = new ArrayList<UserGroupEntity>();

				for (CheckBox currentKanjiGroupListCheckBox : kanjiGroupList) {

					if (currentKanjiGroupListCheckBox.isChecked() == true) {

						CheckBoxTag currentKanjiGroupCheckBoxTag = (CheckBoxTag)currentKanjiGroupListCheckBox.getTag();

						if (currentKanjiGroupCheckBoxTag.groupType == CheckBoxGroupType.INTERNAL_GROUP) { // grupa wbudowana
							chosenKanjiGroupList.add(currentKanjiGroupListCheckBox.getText().toString());

						} else if (currentKanjiGroupCheckBoxTag.groupType == CheckBoxGroupType.USER_GROUP) { // grupa uzytkownika
							chosenUserGroupsNumberList.add(currentKanjiGroupCheckBoxTag.userGroupEntity.getId());
							chosenUserGroupEntityList.add(currentKanjiGroupCheckBoxTag.userGroupEntity);
						}
					}
				}

				kanjiTestConfig.setChosenKanjiGroup(chosenKanjiGroupList);
				kanjiTestConfig.setChosenUserGroups(chosenUserGroupsNumberList);

				/*
				// zapis wybranych wlasnych grup - stary mechanizm!!!
				final List<String> chosenOwnKanjiGroupList = new ArrayList<String>();

				for (CheckBox currentKanjiOwnGroupListCheckBox : kanjiOwnGroupList) {

					if (currentKanjiOwnGroupListCheckBox.isChecked() == true) {
						chosenOwnKanjiGroupList.add(currentKanjiOwnGroupListCheckBox.getText().toString());
					}
				}

				kanjiTestConfig.setChosenOwnKanjiGroup(chosenOwnKanjiGroupList);				
				*/

				if (chosenKanjiList.size() == 0) {

					Toast toast = Toast.makeText(KanjiTestOptionsActivity.this,
							getString(R.string.kanji_test_options_choose_kanji_info), Toast.LENGTH_SHORT);

					toast.show();

					return;
				}

				if ((kanjiTestConfig.getKanjiTestMode() == KanjiTestMode.CHOOSE_KANJI_IN_WORD || kanjiTestConfig.getKanjiTestMode() == KanjiTestMode.DRAW_KANJI_IN_WORD)
						&& dedicateExampleCheckBox.isChecked() == true) {

					if (chosenKanjiGroupList.size() == 0 && chosenUserGroupEntityList.size() == 0) {

						Toast toast = Toast.makeText(KanjiTestOptionsActivity.this,
								getString(R.string.kanji_test_options_choose_kanji_group_info), Toast.LENGTH_SHORT);

						toast.show();

						return;
					}

					int dictionaryEntrySize = 0;

					// przeglad i wczytywanie slow dla wybranych wbudowanych slow
					for (String currentKanjiGroup : chosenKanjiGroupList) {

						List<DictionaryEntry> currentWordsGroupDictionaryEntryList = null;

						try {
							currentWordsGroupDictionaryEntryList = JapaneseAndroidLearnHelperApplication
									.getInstance().getDictionaryManager(KanjiTestOptionsActivity.this)
									.getGroupDictionaryEntries(GroupEnum.getGroupEnum(currentKanjiGroup));

						} catch (DictionaryException e) {
							Toast.makeText(KanjiTestOptionsActivity.this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();

							return;
						}

						dictionaryEntrySize += currentWordsGroupDictionaryEntryList.size();
					}

					// przeglad i wczytywanie slow dla wybranych grup uzytkownika
					for (UserGroupEntity userGroupEntity : chosenUserGroupEntityList) {

						// wczytujemy liste slow z tej grupy
						List<UserGroupItemEntity> userGroupItemListForUserEntity = JapaneseAndroidLearnHelperApplication.getInstance()
								.getDictionaryManager(KanjiTestOptionsActivity.this).getDataManager().getUserGroupItemListForUserEntity(userGroupEntity);

						if (userGroupItemListForUserEntity == null) {
							userGroupItemListForUserEntity = new ArrayList<>();
						}

						// sprawdzamy, czy wystepuje tu slowa, ktore maja w sobie wybrane znaki kanji
						for (UserGroupItemEntity userGroupItemEntity : userGroupItemListForUserEntity) {

							if (userGroupItemEntity.getType() == UserGroupItemEntity.Type.DICTIONARY_ENTRY) {

								DictionaryEntry dictionaryEntry = null;

								try {
									dictionaryEntry = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(KanjiTestOptionsActivity.this).
											getDictionaryEntryById(userGroupItemEntity.getItemId());

								} catch (DictionaryException e) {
									Toast.makeText(KanjiTestOptionsActivity.this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();

									return;
								}

								if (dictionaryEntry != null) {

									for (KanjiEntry currentKanjiEntry : kanjiEntryList) {

										String currentDictionaryEntryKanji = dictionaryEntry.getKanji();

										if (currentDictionaryEntryKanji != null && currentDictionaryEntryKanji.contains(currentKanjiEntry.getKanji()) == true) {
											dictionaryEntrySize++;
										}
									}
								}
							}
						}
					}

					if (dictionaryEntrySize == 0) {
						Toast toast = Toast.makeText(KanjiTestOptionsActivity.this,
								getString(R.string.kanji_test_options_choose_kanji_group_no_words), Toast.LENGTH_LONG);

						toast.show();

						return;
					}
				}
				
				// max test size
				boolean maxTestSizeError = false;
				
				int maxTestSize = -1;
				
				String maxTestSizeString = maxTestSizeEditText.getText().toString();
				
				if (maxTestSizeString == null) {
					maxTestSizeError = true;
					
				} else {
					
					try {
						maxTestSize = Integer.parseInt(maxTestSizeString);
						
					} catch (NumberFormatException e) {
						maxTestSizeError = true;
					}					
				}
				
				if (maxTestSizeError == true || maxTestSize <= 0) {
					Toast toast = Toast.makeText(KanjiTestOptionsActivity.this,
							getString(R.string.kanji_test_options_max_test_size_error), Toast.LENGTH_SHORT);

					toast.show();

					return;					
				}
				
				kanjiTestConfig.setMaxTestSize(maxTestSize);				

				// prepare test
				final ProgressDialog progressDialog = ProgressDialog.show(KanjiTestOptionsActivity.this,
						getString(R.string.kanji_test_options_prepare1),
						getString(R.string.kanji_test_options_prepare2));

				class PrepareAsyncTaskResult {

					private DictionaryException dictionaryException;

					public PrepareAsyncTaskResult() {
					}

					public PrepareAsyncTaskResult(DictionaryException dictionaryException) {
						this.dictionaryException = dictionaryException;
					}
				}

				class PrepareAsyncTask extends AsyncTask<Void, Void, PrepareAsyncTaskResult> {

					@Override
					protected PrepareAsyncTaskResult doInBackground(Void... arg) {

						// get kanji test context
						JapaneseAndroidLearnHelperKanjiTestContext kanjiTestContext = JapaneseAndroidLearnHelperApplication
								.getInstance().getContext().getKanjiTestContext();

						// reset test
						kanjiTestContext.resetTest();
						
						List<KanjiEntry> kanjiEntryList2 = kanjiEntryList;

						Collections.shuffle(kanjiEntryList2);
						
						// max test size filter
						int maxTestSize = kanjiTestConfig.getMaxTestSize();
						
						if (kanjiEntryList2.size() > maxTestSize) {
							
							List<KanjiEntry> newKanjiEntryList = new ArrayList<KanjiEntry>();
							
							for (int kanjiEntryListIdx = 0; kanjiEntryListIdx < maxTestSize; ++kanjiEntryListIdx) {
								newKanjiEntryList.add(kanjiEntryList2.get(kanjiEntryListIdx));
							}
							
							kanjiEntryList2 = newKanjiEntryList;
						}						

						EntryOrderList<KanjiEntry> kanjiEntryListEntryOrderList = null;

						if (untilSuccessCheckBox.isChecked() == true && untilSuccessNewWordLimitCheckBox.isChecked() == true) {
							kanjiEntryListEntryOrderList = new EntryOrderList<KanjiEntry>(kanjiEntryList2, 10);

						} else {
							kanjiEntryListEntryOrderList = new EntryOrderList<KanjiEntry>(kanjiEntryList2, kanjiEntryList2.size());
						}

						// set kanji entry list in context
						kanjiTestContext.setKanjiEntryList(kanjiEntryListEntryOrderList);

						if (kanjiTestConfig.getKanjiTestMode() == KanjiTestMode.DRAW_KANJI_IN_WORD
								|| kanjiTestConfig.getKanjiTestMode() == KanjiTestMode.CHOOSE_KANJI_IN_WORD) {

							List<JapaneseAndroidLearnHelperKanjiTestContext.DictionaryEntryWithRemovedKanji> dictionaryEntryWithRemovedKanjiList = new ArrayList<JapaneseAndroidLearnHelperKanjiTestContext.DictionaryEntryWithRemovedKanji>();

							if (dedicateExampleCheckBox.isChecked() == false) {

								FindWordRequest findWordRequest = new FindWordRequest();

								findWordRequest.searchKanji = true;
								findWordRequest.searchKana = false;
								findWordRequest.searchRomaji = false;
								findWordRequest.searchTranslate = false;
								findWordRequest.searchInfo = false;
								findWordRequest.searchGrammaFormAndExamples = false;
								findWordRequest.wordPlaceSearch = WordPlaceSearch.START_WITH;
								findWordRequest.dictionaryEntryTypeList = null;

								for (KanjiEntry currentKanjiEntry : kanjiEntryList2) {

									findWordRequest.word = currentKanjiEntry.getKanji();

									// find word with this kanji
									FindWordResult findWordResult = null;

									try {
										findWordResult = JapaneseAndroidLearnHelperApplication.getInstance()
												.getDictionaryManager(KanjiTestOptionsActivity.this)
												.findWord(findWordRequest);

									} catch (DictionaryException e) {
										return new PrepareAsyncTaskResult(e);
									}

									List<ResultItem> findWordResultResult = findWordResult.result;

									for (ResultItem currentFindWordResultResult : findWordResultResult) {

										JapaneseAndroidLearnHelperKanjiTestContext.DictionaryEntryWithRemovedKanji currentDictionaryEntryWithRemovedKanji = new JapaneseAndroidLearnHelperKanjiTestContext.DictionaryEntryWithRemovedKanji(
												currentFindWordResultResult.getDictionaryEntry(), currentKanjiEntry.getKanji());

										dictionaryEntryWithRemovedKanjiList.add(currentDictionaryEntryWithRemovedKanji);

										if (dictionaryEntryWithRemovedKanjiList.size() >= maxTestSize) {
											break;
										}
									}

									if (dictionaryEntryWithRemovedKanjiList.size() >= maxTestSize) {
										break;
									}
								}

								for (KanjiEntry currentKanjiEntry : kanjiEntryList2) {

									if (dictionaryEntryWithRemovedKanjiList.size() >= maxTestSize) {
										break;
									}

									// find word with this kanji
									FindWordResult findWordResult = null;

									try {
										findWordResult = JapaneseAndroidLearnHelperApplication.getInstance()
												.getDictionaryManager(KanjiTestOptionsActivity.this)
												.findWord(findWordRequest);

									} catch (DictionaryException e) {
										return new PrepareAsyncTaskResult(e);
									}

									List<ResultItem> findWordResultResult = findWordResult.result;

									for (ResultItem currentFindWordResultResult : findWordResultResult) {

										DictionaryEntry currentDictionaryEntry = currentFindWordResultResult
												.getDictionaryEntry();

										String currentDictionaryEntryKanji = currentDictionaryEntry.getKanji();

										if (currentDictionaryEntryKanji == null || currentDictionaryEntryKanji.contains(currentKanjiEntry.getKanji()) == false) {
											continue;
										}

										JapaneseAndroidLearnHelperKanjiTestContext.DictionaryEntryWithRemovedKanji currentDictionaryEntryWithRemovedKanji = new JapaneseAndroidLearnHelperKanjiTestContext.DictionaryEntryWithRemovedKanji(
												currentFindWordResultResult.getDictionaryEntry(), currentKanjiEntry.getKanji());

										dictionaryEntryWithRemovedKanjiList.add(currentDictionaryEntryWithRemovedKanji);

										if (dictionaryEntryWithRemovedKanjiList.size() >= maxTestSize) {
											break;
										}
									}

									if (dictionaryEntryWithRemovedKanjiList.size() >= maxTestSize) {
										break;
									}
								}

							} else {

								// wczytywanie dedykowanych slow dla wybranych wbudowanych grup
								for (String currentKanjiGroup : chosenKanjiGroupList) {

									List<DictionaryEntry> currentWordsGroupDictionaryEntryList = null;

									try {
										currentWordsGroupDictionaryEntryList = JapaneseAndroidLearnHelperApplication
												.getInstance().getDictionaryManager(KanjiTestOptionsActivity.this)
												.getGroupDictionaryEntries(GroupEnum.getGroupEnum(currentKanjiGroup));

									} catch (DictionaryException e) {
										return new PrepareAsyncTaskResult(e);
									}

									for (KanjiEntry currentKanjiEntry : kanjiEntryList2) {

										for (DictionaryEntry currentDictionaryEntry : currentWordsGroupDictionaryEntryList) {

											String currentDictionaryEntryKanji = currentDictionaryEntry.getKanji();

											if (currentDictionaryEntryKanji.contains(currentKanjiEntry.getKanji()) == false) {
												continue;
											}

											JapaneseAndroidLearnHelperKanjiTestContext.DictionaryEntryWithRemovedKanji currentDictionaryEntryWithRemovedKanji = new JapaneseAndroidLearnHelperKanjiTestContext.DictionaryEntryWithRemovedKanji(
													currentDictionaryEntry, currentKanjiEntry.getKanji());

											dictionaryEntryWithRemovedKanjiList.add(currentDictionaryEntryWithRemovedKanji);

											if (dictionaryEntryWithRemovedKanjiList.size() >= maxTestSize) {
												break;
											}
										}

										if (dictionaryEntryWithRemovedKanjiList.size() >= maxTestSize) {
											break;
										}
									}

									if (dictionaryEntryWithRemovedKanjiList.size() >= maxTestSize) {
										break;
									}
								}

								// wczytywanie dedykowanych slow dla wybranych grup uzytkownika
								for (UserGroupEntity userGroupEntity : chosenUserGroupEntityList) {

									// wczytujemy liste slow z tej grupy
									List<UserGroupItemEntity> userGroupItemListForUserEntity = JapaneseAndroidLearnHelperApplication.getInstance()
											.getDictionaryManager(KanjiTestOptionsActivity.this).getDataManager().getUserGroupItemListForUserEntity(userGroupEntity);

									if (userGroupItemListForUserEntity == null) {
										userGroupItemListForUserEntity = new ArrayList<>();
									}

									// sprawdzamy, czy wystepuje tu slowa, ktore maja w sobie wybrane znaki kanji
									for (UserGroupItemEntity userGroupItemEntity : userGroupItemListForUserEntity) {

										if (userGroupItemEntity.getType() == UserGroupItemEntity.Type.DICTIONARY_ENTRY) {

											DictionaryEntry dictionaryEntry = null;

											try {
												dictionaryEntry = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(KanjiTestOptionsActivity.this).
														getDictionaryEntryById(userGroupItemEntity.getItemId());

											} catch (DictionaryException e) {
												return new PrepareAsyncTaskResult(e);
											}

											if (dictionaryEntry != null) {

												for (KanjiEntry currentKanjiEntry : kanjiEntryList2) {

													String currentDictionaryEntryKanji = dictionaryEntry.getKanji();

													if (currentDictionaryEntryKanji != null && currentDictionaryEntryKanji.contains(currentKanjiEntry.getKanji()) == true) {

														JapaneseAndroidLearnHelperKanjiTestContext.DictionaryEntryWithRemovedKanji currentDictionaryEntryWithRemovedKanji =
																new JapaneseAndroidLearnHelperKanjiTestContext.DictionaryEntryWithRemovedKanji(dictionaryEntry, currentKanjiEntry.getKanji());

														dictionaryEntryWithRemovedKanjiList.add(currentDictionaryEntryWithRemovedKanji);

														if (dictionaryEntryWithRemovedKanjiList.size() >= maxTestSize) {
															break;
														}
													}
												}
											}
										}

										if (dictionaryEntryWithRemovedKanjiList.size() >= maxTestSize) {
											break;
										}
									}

									if (dictionaryEntryWithRemovedKanjiList.size() >= maxTestSize) {
										break;
									}
								}
							}

							Collections.shuffle(dictionaryEntryWithRemovedKanjiList);

							EntryOrderList<JapaneseAndroidLearnHelperKanjiTestContext.DictionaryEntryWithRemovedKanji> entryOrderList = null;

							if (untilSuccessCheckBox.isChecked() == true && untilSuccessNewWordLimitCheckBox.isChecked() == true) {

								entryOrderList = new EntryOrderList<JapaneseAndroidLearnHelperKanjiTestContext.DictionaryEntryWithRemovedKanji>(
										dictionaryEntryWithRemovedKanjiList, 10);

							} else {

								entryOrderList = new EntryOrderList<JapaneseAndroidLearnHelperKanjiTestContext.DictionaryEntryWithRemovedKanji>(
										dictionaryEntryWithRemovedKanjiList, dictionaryEntryWithRemovedKanjiList.size());
							}

							kanjiTestContext.setDictionaryEntryWithRemovedKanji(entryOrderList);
						}

						return new PrepareAsyncTaskResult();
					}

					@SuppressWarnings("deprecation")
					@Override
					protected void onPostExecute(PrepareAsyncTaskResult result) {
						super.onPostExecute(result);

						if (progressDialog != null && progressDialog.isShowing()) {
							progressDialog.dismiss();
						}

						if (result.dictionaryException != null) {

							Toast.makeText(KanjiTestOptionsActivity.this, getString(R.string.dictionary_exception_common_error_message, result.dictionaryException.getMessage()), Toast.LENGTH_LONG).show();

							return;
						}

						AlertDialog alertDialog = new AlertDialog.Builder(KanjiTestOptionsActivity.this).create();

						alertDialog.setCancelable(false);

						alertDialog.setTitle(getString(R.string.kanji_test_options_info_title));
						alertDialog.setMessage(getString(R.string.kanji_test_options_info_message));

						alertDialog.setButton(getString(R.string.kanji_test_options_info_ok),
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog, int which) {

										Intent intent = new Intent(getApplicationContext(), KanjiTest.class);

										startActivity(intent);

										finish();
									}
								});

						alertDialog.show();
					}
				}

				new PrepareAsyncTask().execute();
			}
		});

		/*
		Button reportProblemButton = (Button) findViewById(R.id.kanji_test_options_report_problem_button);

		reportProblemButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {

				TextView optionsGroupInternal = (TextView)findViewById(R.id.kanji_test_options_chosen_kanji_group_internal);
				TextView optionsGroupUser = (TextView)findViewById(R.id.kanji_test_options_chosen_kanji_group_user);

				//

				StringBuffer detailsSb = new StringBuffer();

				detailsSb.append("***" + testModeTextView.getText() + "***\n\n");

				detailsSb.append(
						testModeDrawKanjiFromMeaningRadioButton.isChecked() + " - "
								+ testModeDrawKanjiFromMeaningRadioButton.getText()).append("\n\n");
				detailsSb.append(
						testModeChooseKanjiFromMeaningRadioButton.isChecked() + " - "
								+ testModeChooseKanjiFromMeaningRadioButton.getText()).append("\n\n");
				detailsSb.append(
						testModeDrawKanjiFromInWord.isChecked() + " - " + testModeDrawKanjiFromInWord.getText())
						.append("\n\n");
				detailsSb.append(
						testModeChooseKanjiFromInWord.isChecked() + " - " + testModeChooseKanjiFromInWord.getText())
						.append("\n\n");

				detailsSb.append("***" + otherOptionsTextView.getText() + "***\n\n");

				detailsSb.append(untilSuccessCheckBox.isChecked() + " - " + untilSuccessCheckBox.getText()).append(
						"\n\n");

				detailsSb.append(
						untilSuccessNewWordLimitCheckBox.isChecked() + " - "
								+ untilSuccessNewWordLimitCheckBox.getText()).append("\n\n");

				detailsSb.append(dedicateExampleCheckBox.isChecked() + " - " + dedicateExampleCheckBox.getText())
						.append("\n\n");

				detailsSb.append("***" + chooseKanjiGroupTextView.getText() + "***\n\n");

				detailsSb.append("*** " + optionsGroupInternal.getText() + " ***\n\n");

				for (CheckBox currentKanjiGroupList : kanjiGroupList) {

					CheckBoxTag currentKanjiGroupCheckBoxTag = (CheckBoxTag)currentKanjiGroupList.getTag();

					if (currentKanjiGroupCheckBoxTag.groupType != CheckBoxGroupType.INTERNAL_GROUP) {
						continue;
					}

					String currentKanjiGroupListText = currentKanjiGroupList.getText().toString();

					detailsSb.append(currentKanjiGroupList.isChecked() + " - " + currentKanjiGroupListText)
							.append("\n");
				}

				detailsSb.append("\n*** " + optionsGroupUser.getText() + " ***\n\n");

				for (CheckBox currentKanjiGroupList : kanjiGroupList) {

					CheckBoxTag currentKanjiGroupCheckBoxTag = (CheckBoxTag) currentKanjiGroupList.getTag();

					if (currentKanjiGroupCheckBoxTag.groupType != CheckBoxGroupType.USER_GROUP) {
						continue;
					}

					String currentKanjiGroupListText = currentKanjiGroupList.getText().toString();

					detailsSb.append(currentKanjiGroupList.isChecked() + " - " + currentKanjiGroupListText)
							.append("\n");
				}

				/ *
				// stary mechanizm wlasnych grup
				final TextView chooseOwnKanjiGroup = (TextView)findViewById(R.id.kanji_test_options_choose_own_kanji_group);
				
				if (chooseOwnKanjiGroup.getVisibility() == View.VISIBLE) {
					
					detailsSb.append("***" + chooseOwnKanjiGroup.getText() + "***\n\n");

					for (CheckBox currentOwnKanjiGroupList : kanjiOwnGroupList) {

						String currentKanjiOwnGroupListText = currentOwnKanjiGroupList.getText().toString();

						detailsSb.append(currentOwnKanjiGroupList.isChecked() + " - " + currentKanjiOwnGroupListText)
								.append("\n");
					}					
				}
				* /
				
				detailsSb.append("\n***" + chosenKanjiTextView.getText() + "***\n\n");

				for (KanjiEntry currentCheckBoxKanjiEntry : kanjiList.getAllKanjiList()) {

					if (kanjiList.isChecked(currentCheckBoxKanjiEntry) == true) {
						detailsSb.append(
								"true - " + currentCheckBoxKanjiEntry.getKanji() + " - "
										+ currentCheckBoxKanjiEntry.getPolishTranslates()).append("\n");
					}
				}

				String chooseEmailClientTitle = getString(R.string.choose_email_client);

				String mailSubject = getString(R.string.kanji_test_options_report_problem_email_subject);

				String mailBody = getString(R.string.kanji_test_options_report_problem_email_body, detailsSb.toString());

				String versionName = "";
				int versionCode = 0;

				try {
					PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);

					versionName = packageInfo.versionName;
					versionCode = packageInfo.versionCode;

				} catch (NameNotFoundException e) {
				}

				Intent reportProblemIntent = ReportProblem.createReportProblemIntent(mailSubject, mailBody.toString(),
						versionName, versionCode);

				startActivity(Intent.createChooser(reportProblemIntent, chooseEmailClientTitle));
			}
		});
		*/

		// loading kanji

		final ProgressDialog progressDialog = ProgressDialog.show(this, getString(R.string.kanji_test_options_loading),
				getString(R.string.kanji_test_options_loading2));

		class PrepareAsyncTaskResult {

			private List<KanjiEntry> kanjiEntryList;

			private DictionaryException dictionaryException;

			public PrepareAsyncTaskResult(List<KanjiEntry> kanjiEntryList) {
				this.kanjiEntryList = kanjiEntryList;
			}

			public PrepareAsyncTaskResult(DictionaryException dictionaryException) {
				this.dictionaryException = dictionaryException;
			}
		}

		class PrepareAsyncTask extends AsyncTask<Void, Void, PrepareAsyncTaskResult> {

			@Override
			protected PrepareAsyncTaskResult doInBackground(Void... arg) {

				// INFO: Gdy bedziesz to zmienial, sprawdz obsluge DictionaryException przy findWord !!!!

				try {
					return new PrepareAsyncTaskResult(JapaneseAndroidLearnHelperApplication.getInstance()
							.getDictionaryManager(KanjiTestOptionsActivity.this).getAllKanjis(false, true));

				} catch (DictionaryException e) {
					return new PrepareAsyncTaskResult(e);
				}
			}

			@Override
			protected void onPostExecute(PrepareAsyncTaskResult result) {

				if (progressDialog != null && progressDialog.isShowing()) {
					progressDialog.dismiss();
				}

				if (result.dictionaryException != null) {

					startTestButton.setEnabled(false);

					Toast.makeText(KanjiTestOptionsActivity.this, getString(R.string.dictionary_exception_common_error_message, result.dictionaryException.getMessage()), Toast.LENGTH_LONG).show();

					return;
				}

				List<KanjiEntry> allKanjis = result.kanjiEntryList;

				Map<GroupEnum, Set<String>> kanjiGroups = new TreeMap<GroupEnum, Set<String>>();

				for (int allKanjisIdx = 0; allKanjisIdx < allKanjis.size(); ++allKanjisIdx) {

					KanjiEntry currentKanjiEntry = allKanjis.get(allKanjisIdx);

					kanjiList.addKanjiEntry(currentKanjiEntry);

					List<GroupEnum> currentKanjiEntryGroups = currentKanjiEntry.getGroups();

					if (currentKanjiEntryGroups != null && currentKanjiEntryGroups.size() > 0) {

						for (GroupEnum currentCurrentKanjiEntryGroup : currentKanjiEntryGroups) {

							Set<String> groupSet = kanjiGroups.get(currentCurrentKanjiEntryGroup);

							if (groupSet == null) {
								groupSet = new HashSet<String>();
							}

							groupSet.add(currentKanjiEntry.getKanji());

							kanjiGroups.put(currentCurrentKanjiEntryGroup, groupSet);
						}
					}
				}

				List<String> chosenKanji = kanjiTestConfig.getChosenKanjiAsList();

				for (String currentChoosenKanji : chosenKanji) {
					kanjiList.setKanjiChecked(currentChoosenKanji, true);
				}

				GroupEnum[] kanjiGroupsKeysArray = new GroupEnum[kanjiGroups.size()];

				kanjiGroups.keySet().toArray(kanjiGroupsKeysArray);

				GroupEnum.sortGroups(kanjiGroupsKeysArray);

				// add to main layout

				// internal groups

				Set<String> chosenKanjiGroup = kanjiTestConfig.getChosenKanjiGroup();

				for (GroupEnum currentKanjiGroup : kanjiGroupsKeysArray) {

					CheckBox currentKanjiGroupCheckBox = createGroupCheckBox(kanjiGroups.get(currentKanjiGroup), null, currentKanjiGroup.getValue(),
							chosenKanjiGroup != null && chosenKanjiGroup.contains(currentKanjiGroup.getValue()));

					kanjiGroupList.add(currentKanjiGroupCheckBox);

					mainLayout.addView(currentKanjiGroupCheckBox, mainLayout.getChildCount() - 3);

					currentKanjiGroupCheckBox.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							fillKanjiGroupKanjis();
						}
					});
				}

				// loading user word groups
				List<UserGroupEntity> allUserGroupList = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(KanjiTestOptionsActivity.this).getDataManager().getAllUserGroupList();

				Set<Integer> chosenUserGroups = kanjiTestConfig.getChosenUserGroups();

				for (int allUserGroupListIdx = 0; allUserGroupListIdx < allUserGroupList.size(); ++allUserGroupListIdx) {

					UserGroupEntity userGroupEntity = allUserGroupList.get(allUserGroupListIdx);

					String checkboxText = userGroupEntity.getType() == UserGroupEntity.Type.USER_GROUP ? userGroupEntity.getName() :
							getString(R.string.user_group_star_group);

					CheckBox currentKanjiGroupCheckBox = createGroupCheckBox(null, userGroupEntity, checkboxText,
							chosenUserGroups != null && chosenUserGroups.contains(userGroupEntity.getId()));

					kanjiGroupList.add(currentKanjiGroupCheckBox);

					mainLayout.addView(currentKanjiGroupCheckBox, mainLayout.getChildCount() - 2);

					currentKanjiGroupCheckBox.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							fillKanjiGroupKanjis();
						}
					});
				}

				// showOwnGroupList();
				if (chosenKanjiGroup.size() > 0 || chosenUserGroups.size() > 0) {
					fillKanjiGroupKanjis();
				}

				showSelectedKanji();
			}
		}

		new PrepareAsyncTask().execute();
	}
	
	private void fillKanjiGroupKanjis() {
		
		Set<String> allKanjisInGroup = new HashSet<String>();

		// pobierz znaki z grup
		for (CheckBox currentKanjiGroupListCheckBox : kanjiGroupList) {

			if (currentKanjiGroupListCheckBox.isChecked() == false) {
				continue;
			}

			CheckBoxTag currentKanjiGroupCheckBoxTag = (CheckBoxTag)currentKanjiGroupListCheckBox.getTag();

			Set<String> kanjiSet = null;

			if (currentKanjiGroupCheckBoxTag.groupType == CheckBoxGroupType.INTERNAL_GROUP) { // grupa wbudowana
				kanjiSet = currentKanjiGroupCheckBoxTag.groupEnumKanjiSet;

			} else if (currentKanjiGroupCheckBoxTag.groupType == CheckBoxGroupType.USER_GROUP) { // grupa uzytkownika

				List<UserGroupItemEntity> userGroupItemListForUserEntity = JapaneseAndroidLearnHelperApplication.getInstance()
						.getDictionaryManager(KanjiTestOptionsActivity.this).getDataManager().getUserGroupItemListForUserEntity(currentKanjiGroupCheckBoxTag.userGroupEntity);

				if (userGroupItemListForUserEntity == null) {
					userGroupItemListForUserEntity = new ArrayList<>();
				}

				kanjiSet = new HashSet<>();

				for (UserGroupItemEntity userGroupItemEntity : userGroupItemListForUserEntity) {

					if (userGroupItemEntity.getType() == UserGroupItemEntity.Type.KANJI_ENTRY) {

						KanjiEntry kanjiEntry = null;

						try {
							kanjiEntry = JapaneseAndroidLearnHelperApplication.getInstance()
									.getDictionaryManager(KanjiTestOptionsActivity.this).getKanjiEntryById(userGroupItemEntity.getItemId());

						} catch (DictionaryException e) {

							Toast.makeText(KanjiTestOptionsActivity.this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();

							break;
						}

						if (kanjiEntry != null) {
							kanjiSet.add(kanjiEntry.getKanji());
						}
					}
				}
			}

			allKanjisInGroup.addAll(kanjiSet);
		}

		/*
		// pobierz znaki z grup uzytkownika - stary mechanizm !!!
		for (CheckBox currentOwnGroupListCheckBox : kanjiOwnGroupList) {

			if (currentOwnGroupListCheckBox.isChecked() == false) {
				continue;
			}

			@SuppressWarnings("unchecked")
			Set<String> currentOwnGroupKanjiListCheckBoxTag = (Set<String>) currentOwnGroupListCheckBox
					.getTag();

			allKanjisInGroup.addAll(currentOwnGroupKanjiListCheckBoxTag);
		}
		*/

		// ustawienie znakow
		for (KanjiEntry currentCheckBoxKanjiEntry : kanjiList.getAllKanjiList()) {

			String currentCheckBoxKanjiEntryKanji = currentCheckBoxKanjiEntry.getKanji();

			kanjiList.setKanjiChecked(currentCheckBoxKanjiEntry,
					allKanjisInGroup.contains(currentCheckBoxKanjiEntryKanji));
		}

		showSelectedKanji();		
	}
	
	/*
	private void showOwnGroupList() {
		
		final LinearLayout mainLayout = (LinearLayout) findViewById(R.id.kanji_test_options_main_layout);
		
		final View startView = findViewById(R.id.kanji_test_options_choose_own_kanji_group);
		final View stopView = (TextView) findViewById(R.id.kanji_test_options_chosen_kanji);
		
		boolean startDelete = false;

		for (int idx = 0; idx < mainLayout.getChildCount(); ++idx) {

			View currentMainLayoutChildView = mainLayout.getChildAt(idx);

			if (currentMainLayoutChildView == startView) {
				startDelete = true;

				continue;
			}
			
			if (currentMainLayoutChildView == stopView) {
				break;
			}

			if (startDelete == true) {
				mainLayout.removeView(currentMainLayoutChildView);

				idx--;
			}
		}
		
		final KanjiTestConfig kanjiTestConfig = JapaneseAndroidLearnHelperApplication.getInstance()
				.getConfigManager(KanjiTestOptionsActivity.this).getKanjiTestConfig();

		List<String> ownGroupList = kanjiTestConfig.getOwnGroupList();

		if (ownGroupList.size() == 0) {
			startView.setVisibility(View.GONE);
			
		} else {
			startView.setVisibility(View.VISIBLE);
		}
		
		kanjiOwnGroupList.clear();		
		
		boolean startAdd = false;

		for (int idx = 0; idx < mainLayout.getChildCount(); ++idx) {

			View currentMainLayoutChildView = mainLayout.getChildAt(idx);

			if (currentMainLayoutChildView == startView) {
				startAdd = true;

				continue;
			}
			
			if (startAdd == true) {
				
				int counter = 0;
				
				Set<String> chosenOwnKanjiGroup = kanjiTestConfig.getChosenOwnKanjiGroup();
				
				for (final String currentOwnGroupName : ownGroupList) {
										
					CheckBox currentKanjiGroupCheckBox = new CheckBox(KanjiTestOptionsActivity.this);

					currentKanjiGroupCheckBox.setLayoutParams(new LinearLayout.LayoutParams(
							LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));

					currentKanjiGroupCheckBox.setTextSize(12);
					currentKanjiGroupCheckBox.setText(currentOwnGroupName);

					currentKanjiGroupCheckBox.setChecked(chosenOwnKanjiGroup.contains(currentOwnGroupName));
					currentKanjiGroupCheckBox.setTag(kanjiTestConfig.getOwnGroupKanjiList(currentOwnGroupName));

					kanjiOwnGroupList.add(currentKanjiGroupCheckBox);
					
					currentKanjiGroupCheckBox.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							fillKanjiGroupKanjis();
						}
					});
					
					LinearLayout linearLayout = new LinearLayout(this);

					LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
							LayoutParams.WRAP_CONTENT);
					linearLayout.setLayoutParams(layoutParams);

					// delete icon
					ImageView deleteImageView = new ImageView(this);

					LinearLayout.LayoutParams imageLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT);
					
					imageLayoutParams.gravity = Gravity.CENTER;
					imageLayoutParams.leftMargin = 10;


					deleteImageView.setLayoutParams(imageLayoutParams);
					deleteImageView.setImageDrawable(getResources().getDrawable(R.drawable.delete));

					linearLayout.addView(currentKanjiGroupCheckBox);
					linearLayout.addView(deleteImageView);

					// actions: delete
					View.OnClickListener deleteOnClickListener = new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							
							DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									switch (which) {
										case DialogInterface.BUTTON_POSITIVE:

											kanjiTestConfig.deleteOwnGroup(currentOwnGroupName);
											
											showOwnGroupList();

											break;

										case DialogInterface.BUTTON_NEGATIVE:

											// noop

											break;
									}
								}
							};

							AlertDialog.Builder builder = new AlertDialog.Builder(KanjiTestOptionsActivity.this);

							builder.setMessage(getString(R.string.kanji_test_delete_own_group_question, currentOwnGroupName))
									.setPositiveButton(getString(R.string.kanji_test_delete_own_group_question_yes), dialogClickListener)
									.setNegativeButton(getString(R.string.kanji_test_delete_own_group_question_no), dialogClickListener).show();							
						}
					};

					deleteImageView.setOnClickListener(deleteOnClickListener);
					
					mainLayout.addView(linearLayout, idx + counter);
					
					counter++;
				}
				
				break;
			}			
		}		
	}
	*/

	private void showSelectedKanji() {

		final LinearLayout mainLayout = (LinearLayout) findViewById(R.id.kanji_test_options_main_layout);
		final TextView chosenKanjiInfoTextView = (TextView) findViewById(R.id.kanji_test_options_chosen_kanji_info);

		boolean startDelete = false;

		// clear end of main layout
		for (int idx = 0; idx < mainLayout.getChildCount(); ++idx) {

			View currentMainLayoutChildView = mainLayout.getChildAt(idx);

			if (currentMainLayoutChildView == chosenKanjiInfoTextView) {
				startDelete = true;

				continue;
			}

			if (startDelete == true) {
				mainLayout.removeView(currentMainLayoutChildView);

				idx--;
			}
		}

		for (final KanjiEntry currentCheckBoxKanjiEntry : kanjiList.getUserSelectedKanjiList()) {

			LinearLayout linearLayout = new LinearLayout(this);

			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
					LayoutParams.WRAP_CONTENT);
			linearLayout.setLayoutParams(layoutParams);

			// kanji
			TextView kanjiTextView = new TextView(this);

			LinearLayout.LayoutParams kanjiLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);

			kanjiLayoutParams.leftMargin = 10;

			kanjiTextView.setLayoutParams(kanjiLayoutParams);

			StringBuffer currentKanjiEntryText = new StringBuffer();

			currentKanjiEntryText.append("<big>").append(currentCheckBoxKanjiEntry.getKanji()).append("</big> - ")
					.append(currentCheckBoxKanjiEntry.getPolishTranslates().toString()).append("\n\n");

			kanjiTextView.setTextSize(15.0f);
			kanjiTextView.setText(Html.fromHtml(currentKanjiEntryText.toString()), BufferType.SPANNABLE);

			// delete icon
			ImageView deleteImageView = new ImageView(this);

			LinearLayout.LayoutParams imageLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);
			imageLayoutParams.gravity = Gravity.CENTER;

			imageLayoutParams.leftMargin = 10;

			deleteImageView.setLayoutParams(imageLayoutParams);

			deleteImageView.setImageDrawable(getResources().getDrawable(JapaneseAndroidLearnHelperApplication.getInstance().getThemeType().getDeleteIconId()));

			linearLayout.addView(kanjiTextView);
			linearLayout.addView(deleteImageView);

			// actions: delete
			View.OnClickListener deleteOnClickListener = new View.OnClickListener() {

				@Override
				public void onClick(View v) {

					for (CheckBox currentKanjiGroupListCheckBox : kanjiGroupList) {
						currentKanjiGroupListCheckBox.setChecked(false);
					}

					/*
					// stary mechanizm wlasnych grup !!!
					for (CheckBox currentKanjiOwnGroupListCheckBox : kanjiOwnGroupList) {
						currentKanjiOwnGroupListCheckBox.setChecked(false);
					}
					*/
					
					kanjiList.setKanjiChecked(currentCheckBoxKanjiEntry, false);

					showSelectedKanji();
				}
			};

			kanjiTextView.setOnClickListener(deleteOnClickListener);
			deleteImageView.setOnClickListener(deleteOnClickListener);

			mainLayout.addView(linearLayout);
		}
	}

	private void setUntilSuccessNewWordLimitCheckBoxEnabled(CheckBox untilSuccessCheckBox,
			CheckBox untilSuccessNewWordLimitCheckBox) {

		if (untilSuccessCheckBox.isChecked() == true) {
			untilSuccessNewWordLimitCheckBox.setEnabled(true);
		} else {
			untilSuccessNewWordLimitCheckBox.setEnabled(false);
		}
	}

	private static class KanjiList {

		private final List<KanjiEntry> allKanjiList = new ArrayList<KanjiEntry>();

		private final List<KanjiEntry> userSelectedKanjiList = new ArrayList<KanjiEntry>();

		public List<KanjiEntry> getAllKanjiList() {
			return allKanjiList;
		}

		public List<KanjiEntry> getUserSelectedKanjiList() {
			
			Collections.sort(userSelectedKanjiList, new Comparator<KanjiEntry>() {

				@Override
				public int compare(KanjiEntry lhs, KanjiEntry rhs) {
					return Integer.valueOf(lhs.getId()).compareTo(Integer.valueOf(rhs.getId()));
				}
			});
			
			return userSelectedKanjiList;
		}

		public void clearUserSelectedKanjiList() {
			userSelectedKanjiList.clear();
		}

		public void addKanjiEntry(KanjiEntry kanjiEntry) {
			allKanjiList.add(kanjiEntry);
		}

		public void setKanjiChecked(String kanji, boolean checked) {

			KanjiEntry foundKanjiEntry = null;

			for (KanjiEntry currentKanjiEntry : allKanjiList) {

				if (currentKanjiEntry.getKanji().equals(kanji) == true) {

					foundKanjiEntry = currentKanjiEntry;

					break;
				}
			}

			if (foundKanjiEntry != null) {
				setKanjiChecked(foundKanjiEntry, checked);
			}
		}

		public void setKanjiChecked(KanjiEntry kanjiEntry, boolean checked) {

			if (checked == false) {
				userSelectedKanjiList.remove(kanjiEntry);

			} else if (userSelectedKanjiList.contains(kanjiEntry) == false) {
				userSelectedKanjiList.add(kanjiEntry);
			}
		}

		public boolean isChecked(KanjiEntry kanjiEntry) {
			return userSelectedKanjiList.contains(kanjiEntry);
		}
	}

	private CheckBox createGroupCheckBox(Set<String> groupEnumKanjiSet, UserGroupEntity userGroupEntity, String text, boolean checked) {

		CheckBox checkbox = new CheckBox(this);

		if ( 	(groupEnumKanjiSet == null && userGroupEntity == null) ||
				(groupEnumKanjiSet != null && userGroupEntity != null)) {
			throw new RuntimeException();
		}

		if (groupEnumKanjiSet != null) {
			checkbox.setTag(new CheckBoxTag(groupEnumKanjiSet));

		} else if (userGroupEntity != null) {
			checkbox.setTag(new CheckBoxTag(userGroupEntity));
		}

		checkbox.setLayoutParams(new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));

		checkbox.setTextSize(12);
		checkbox.setText(text);
		checkbox.setChecked(checked);

		return checkbox;
	}

	private static class CheckBoxTag {

		private CheckBoxGroupType groupType;

		private Set<String> groupEnumKanjiSet;

		private UserGroupEntity userGroupEntity;

		public CheckBoxTag(Set<String> groupEnumKanjiSet) {
			this.groupType = CheckBoxGroupType.INTERNAL_GROUP;
			this.groupEnumKanjiSet = groupEnumKanjiSet;
		}

		public CheckBoxTag(UserGroupEntity userGroupEntity) {
			this.groupType = CheckBoxGroupType.USER_GROUP;
			this.userGroupEntity = userGroupEntity;
		}
	}

	private static enum CheckBoxGroupType {

		INTERNAL_GROUP,

		USER_GROUP;
	}
} public class KeigoTable extends Activity {

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		MenuShorterHelper.onCreateOptionsMenu(menu);
		
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		return MenuShorterHelper.onOptionsItemSelected(item, getApplicationContext(), this);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);

		JapaneseAndroidLearnHelperApplication.getInstance().setContentViewAndTheme(this, R.layout.keigo_table);
		
		JapaneseAndroidLearnHelperApplication.getInstance().logScreen(this, getString(R.string.logs_keigo_table));

		final LinearLayout mainLayout = (LinearLayout)findViewById(R.id.keigo_table_main_layout);
		
		final List<IScreenItem> report = new ArrayList<IScreenItem>();
		
		// get keigo helper
		KeigoHelper keigoHelper = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(this).getKeigoHelper();
		
		report.add(new TitleItem(getString(R.string.keigo_title), 0));
				
		addKeigoHighEntryList(report, keigoHelper);
		
		report.add(new StringValue("", 10.0f, 1));
		
		addKeigoLowEntryList(report, keigoHelper);
		
		// fill mail layout
		fillMainLayout(report, mainLayout);

		/*
		// report problem
		Button reportProblemButton = (Button)findViewById(R.id.keigo_table_report_problem_button);
		
		reportProblemButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View view) {
				
				StringBuffer reportSb = new StringBuffer();
				
				for (IScreenItem currentReportScreenItem : report) {
					reportSb.append(currentReportScreenItem.toString()).append("\n\n");
				}
				
				String chooseEmailClientTitle = getString(R.string.choose_email_client);
				
				String mailSubject = getString(R.string.keigo_table_report_problem_email_subject);
				
				String mailBody = getString(R.string.keigo_table_report_problem_email_body,
						reportSb.toString());				
				
		        String versionName = "";
		        int versionCode = 0;
		        
		        try {
		        	PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
		        	
		            versionName = packageInfo.versionName;
		            versionCode = packageInfo.versionCode;

		        } catch (NameNotFoundException e) {        	
		        }
				
				Intent reportProblemIntent = ReportProblem.createReportProblemIntent(mailSubject, mailBody.toString(), versionName, versionCode); 
				
				startActivity(Intent.createChooser(reportProblemIntent, chooseEmailClientTitle));
			}
		});
		*/
	}
	
	private void addKeigoHighEntryList(List<IScreenItem> report, KeigoHelper keigoHelper) {
		
		// get keigo high entry list
		List<KeigoEntry> keigoHighEntryList = keigoHelper.getKeigoHighEntryList();
		
		report.add(new TitleItem(getString(R.string.keigo_high_entry_list_title), 1));
		
		report.add(new StringValue("", 5.0f, 1));
				
		TableLayout tableLayout = new TableLayout(TableLayout.LayoutParam.WrapContent_WrapContent, true, true);
		
		for (KeigoEntry currentKeigoEntry : keigoHighEntryList) {
			
			String keigoEntryKanji = currentKeigoEntry.getKanji();
			String keigoEntryKana = currentKeigoEntry.getKana();

			// verb value
			String verb = null;
			
			if (keigoEntryKanji != null) {
				verb = keigoEntryKanji + " (" + keigoEntryKana + ")";
				
			} else {
				verb = keigoEntryKana;
			}
			
			boolean addTilde = false;
			
			if (verb.equals("ている") == true) {				
				addTilde = true;
			}

			addRowValue(tableLayout, getString(R.string.keigo_high_entry_list_verb), addTilde == false ? verb : "~" + verb);
			
			// keigo verb
			String keigoEntryKeigoKanji = currentKeigoEntry.getKeigoKanji(true);
			String keigoEntryKeigoKana = currentKeigoEntry.getKeigoKana(true);
			
			String keigoVerb = null;
			
			if (keigoEntryKeigoKanji != null) {
				keigoVerb = keigoEntryKeigoKanji + " (" + keigoEntryKeigoKana + ")";
				
			} else {
				keigoVerb = keigoEntryKeigoKana;
			}
			
			addRowValue(tableLayout, getString(R.string.keigo_high_entry_list_keigo_verb), addTilde == false ? keigoVerb : "~" + keigoVerb);
			
			// keigo verb masu
			String keigoEntryKeigoKanjiMasu = currentKeigoEntry.getKeigoLongFormWithoutMasuKanji();
			String keigoEntryKeigoKanaMasu = currentKeigoEntry.getKeigoLongFormWithoutMasuKana();
			
			String keigoVerbMasu = null;
			
			if (keigoEntryKeigoKanjiMasu != null) {
				keigoVerbMasu = keigoEntryKeigoKanjiMasu + "ます";
				
			} else if (keigoEntryKeigoKanaMasu != null) {
				keigoVerbMasu = keigoEntryKeigoKanaMasu + "ます";
				
			} else {
				keigoVerbMasu = "-";
			}

			addRowValue(tableLayout, getString(R.string.keigo_high_entry_list_keigo_verb_masu), addTilde == false ? keigoVerbMasu : "~" + keigoVerbMasu);
			
			// spacer
			TableRow spacerTableRow = new TableRow();      
			spacerTableRow.addScreenItem(new StringValue("", 8.0f, 1));
			tableLayout.addTableRow(spacerTableRow); 
		}
		
		// regular
		addRowValue(tableLayout, getString(R.string.keigo_high_entry_list_verb_regular), "お + [czasownik bez masu] + になる");		
		
		report.add(tableLayout);
	}

	private void addKeigoLowEntryList(List<IScreenItem> report, KeigoHelper keigoHelper) {
		
		// get keigo low entry list
		List<KeigoEntry> keigoLowEntryList = keigoHelper.getKeigoLowEntryList();
		
		report.add(new TitleItem(getString(R.string.keigo_low_entry_list_title), 1));
		
		report.add(new StringValue("", 5.0f, 1));
				
		TableLayout tableLayout = new TableLayout(TableLayout.LayoutParam.WrapContent_WrapContent, true, true);
		
		for (KeigoEntry currentKeigoEntry : keigoLowEntryList) {
			
			String keigoEntryKanji = currentKeigoEntry.getKanji();
			String keigoEntryKana = currentKeigoEntry.getKana();

			// verb value
			String verb = null;
			
			if (keigoEntryKanji != null) {
				verb = keigoEntryKanji + " (" + keigoEntryKana + ")";
				
			} else {
				verb = keigoEntryKana;
			}
			
			boolean addTilde = false;
			
			if (verb.equals("ている") == true || verb.equals("です") == true) {
				addTilde = true;
			}

			addRowValue(tableLayout, getString(R.string.keigo_low_entry_list_verb), addTilde == false ? verb : "~" + verb);
			
			// keigo verb
			String keigoEntryKeigoKanji = currentKeigoEntry.getKeigoKanji(true);
			String keigoEntryKeigoKana = currentKeigoEntry.getKeigoKana(true);
			
			String keigoVerb = null;
			
			if (keigoEntryKeigoKanji != null) {
				keigoVerb = keigoEntryKeigoKanji + " (" + keigoEntryKeigoKana + ")";
				
			} else {
				keigoVerb = keigoEntryKeigoKana;
			}
			
			addRowValue(tableLayout, getString(R.string.keigo_low_entry_list_keigo_verb), addTilde == false ? keigoVerb : "~" + keigoVerb);
			
			// keigo verb masu
			String keigoEntryKeigoKanjiMasu = currentKeigoEntry.getKeigoLongFormWithoutMasuKanji();
			String keigoEntryKeigoKanaMasu = currentKeigoEntry.getKeigoLongFormWithoutMasuKana();
			
			String keigoVerbMasu = null;
			
			if (keigoEntryKeigoKanjiMasu != null) {
				keigoVerbMasu = keigoEntryKeigoKanjiMasu + "ます";
				
			} else if (keigoEntryKeigoKanaMasu != null) {
				keigoVerbMasu = keigoEntryKeigoKanaMasu + "ます";
				
			} else {
				keigoVerbMasu = "-";
			}

			addRowValue(tableLayout, getString(R.string.keigo_low_entry_list_keigo_verb_masu), addTilde == false ? keigoVerbMasu : 
				(keigoVerbMasu.equals("-") == false ? "~" + keigoVerbMasu : keigoVerbMasu));
			
			// spacer
			TableRow spacerTableRow = new TableRow();      
			spacerTableRow.addScreenItem(new StringValue("", 8.0f, 1));
			tableLayout.addTableRow(spacerTableRow); 
		}
		
		// regular
		addRowValue(tableLayout, getString(R.string.keigo_low_entry_list_verb_regular), "お + [czasownik bez masu] + する");	
		
		report.add(tableLayout);
	}
	
	private void addRowValue(TableLayout tableLayout, String title, String value) {
		
		TableRow tableRow = new TableRow();
		
		StringValue titleStringValue = new StringValue(title, 14.0f, 0);
		
		titleStringValue.setMarginTop(0);
		titleStringValue.setMarginLeft(5);
		titleStringValue.setMarginRight(5);
		titleStringValue.setMarginBottom(0);

		titleStringValue.setBackgroundColor(JapaneseAndroidLearnHelperApplication.getInstance().getThemeType().getTitleItemBackgroundColorAsColor());
		
		StringValue valueStringValue = new StringValue(value, 14.0f, 0);
		
		tableRow.addScreenItem(titleStringValue);
		tableRow.addScreenItem(valueStringValue);
		
		tableLayout.addTableRow(tableRow);
	}

	private void fillMainLayout(List<IScreenItem> generatedDetails, LinearLayout mainLayout) {

		for (IScreenItem currentDetailsReportItem : generatedDetails) {
			currentDetailsReportItem.generate(this, getResources(), mainLayout);
		}
	}
} public class ReportProblem {
	
	public static Intent createReportProblemIntent(String mailSubject, String mailBody, String versionName, int versionCode) {
		
		Intent email = new Intent(Intent.ACTION_SEND);
		
		mailBody += "---\nVersion code: " + versionCode + "\nVersion name: " + versionName + "\n";
		
		email.putExtra(Intent.EXTRA_EMAIL, new String[] { "fryderyk.mazurek@gmail.com" } );
		
		email.putExtra(Intent.EXTRA_SUBJECT, mailSubject);
		email.putExtra(Intent.EXTRA_TEXT, mailBody);
		
		email.setType("message/rfc822");
		
		return email;
	}
} public class ServerClient {
	
	//private static final String PREFIX_URL = "http://10.0.2.2:8080"; // dev
	private static final String PREFIX_URL = "https://www.japonski-pomocnik.pl"; // prod

	private static final String SEND_MISSING_WORD_URL = PREFIX_URL + "/android/sendMissingWord";
	private static final String SEARCH_URL = PREFIX_URL + "/android/search";
	private static final String GET_MESSAGE_URL = PREFIX_URL + "/android/getMessage";

	private static final String AUTOCOMPLETE_URL = PREFIX_URL + "/android/autocomplete";
	
	private static final String SPELL_CHECKER_SUGGESTION_URL = PREFIX_URL + "/android/spellCheckerSuggestion";

	private static final String SEND_QUEUE_EVENT_URL = PREFIX_URL + "/android/receiveQueueEvent";

	private static final String REMOTE_DATABASE_CONNECTOR_BASE_URL = PREFIX_URL + "/android/remoteDatabaseConnector/";

	private static final int TIMEOUT = 10000;
	
	public ServerClient() {
				
	}
	
	public boolean sendMissingWord(PackageInfo packageInfo, String word, WordPlaceSearch wordPlaceSearch) {
		
		boolean connected = isConnected();
		
		if (connected == false) {			
			return false;
		}

		HttpURLConnection httpURLConnection = null;
		
		try {
			// przygotuj dane wejsciowe
			Map<String, Object> requestDataMap = new HashMap<String, Object>();

			requestDataMap.put("word", word);
			requestDataMap.put("wordPlaceSearch", wordPlaceSearch.toString());

			httpURLConnection = callRemoteService(packageInfo, SEND_MISSING_WORD_URL, convertMapToJSONObject(requestDataMap).toString());

			// sprawdz odpowiedz
			int statusCode = httpURLConnection.getResponseCode();

			if (statusCode < 200 || statusCode >= 300) {

				Log.e("ServerClient", "Error send missing word: " + httpURLConnection.getResponseCode() + " - " + httpURLConnection.getResponseMessage());

				return false;
			}

			return true;

		} catch (Exception e) {
			Log.e("ServerClient", "Error send missing word: ", e);
			
			return false;

		} finally {

			if (httpURLConnection != null) {
				httpURLConnection.disconnect();
			}
		}
	}
	
	private String createUserAgent(PackageInfo packageInfo) {
		
		StringBuffer sb = new StringBuffer("JapaneseAndroidLearnHelper");
		
		if (packageInfo != null) {			
			sb.append("/" + packageInfo.versionCode + "/" + packageInfo.versionName);
		}
				
		return sb.toString();
	}

	public FindWordResult search(PackageInfo packageInfo, FindWordRequest findWordRequest) {
		
		boolean connected = isConnected();
		
		if (connected == false) {			
			return null;
		}

		HttpURLConnection httpURLConnection = null;

		BufferedReader contentInputStreamReader = null;

		try {
			// przygotuj dane wejsciowe
			Map<String, Object> requestDataMap = createMapFromFindWordRequest(findWordRequest);

			httpURLConnection = callRemoteService(packageInfo, SEARCH_URL, convertMapToJSONObject(requestDataMap).toString());

			// sprawdz odpowiedz
			int statusCode = httpURLConnection.getResponseCode();

			if (statusCode < 200 || statusCode >= 300) {

				Log.e("ServerClient", "Error search: " + httpURLConnection.getResponseCode() + " - " + httpURLConnection.getResponseMessage());
				
				return null;
			}

			// pobierz odpowiedz
			contentInputStreamReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

			StringBuffer jsonResponseSb = new StringBuffer();
			
			while (true) {		
				String readLine = contentInputStreamReader.readLine();
				
				if (readLine == null) {
					break;
				}
				
				jsonResponseSb.append(readLine);			
			}

			if (jsonResponseSb.length() == 0) {
				return null;
			}

			JSONObject responseJSON = new JSONObject(jsonResponseSb.toString());
			
			return createFindWordResultFromJSON(responseJSON);
			
		} catch (Exception e) {
			Log.e("ServerClient", "Error search: ", e);
			
			return null;

		} finally {

			if (contentInputStreamReader != null) {

				try {
					contentInputStreamReader.close();

				} catch (IOException e) {
					// noop
				}
			}

			if (httpURLConnection != null) {
				httpURLConnection.disconnect();
			}
		}
	}

	private boolean isConnected() {
		
		ConnectivityManager cm = (ConnectivityManager)JapaneseAndroidLearnHelperApplication.getInstance().
				getSystemService(Context.CONNECTIVITY_SERVICE);
		
		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
		
		if (activeNetwork == null) {
			return false;
		}
		
		return activeNetwork.isConnected();		
	}
	
	private static JSONObject convertMapToJSONObject(Map<String, Object> params) throws JSONException {

	    Iterator<Map.Entry<String, Object>> paramsEntrySetIterator = params.entrySet().iterator();

	    JSONObject result = new JSONObject();
	    
	    while (paramsEntrySetIterator.hasNext() == true) { 
	    	
	    	Map.Entry<String, Object> currentPair = (Map.Entry<String, Object>)paramsEntrySetIterator.next();

	        String key = (String)currentPair.getKey();	        
	        Object value = currentPair.getValue();
	        
	        if (value instanceof List<?>) {
	        	
	        	JSONArray jsonArray = new JSONArray();
	        	
	        	List<?> valueList =  (List<?>)value;
	        	
	        	for (Object currentValue : valueList) {					
	        		jsonArray.put(currentValue.toString());	        		
	        	}
	        	
	        	result.put(key, jsonArray);
	        	
	        } else {
	        	result.put(key, value);
	        }	        
	    }
	    
	    return result;
	}
	
	private Map<String, Object> createMapFromFindWordRequest(FindWordRequest findWordRequest) {
				
		Map<String, Object> requestDataMap =  new HashMap<String, Object>();
		
		requestDataMap.put("searchMainDictionary", findWordRequest.searchMainDictionary);
		requestDataMap.put("searchGrammaFormAndExamples", findWordRequest.searchGrammaFormAndExamples);
		requestDataMap.put("searchName", findWordRequest.searchName);
		
		requestDataMap.put("word", findWordRequest.word);
		
		requestDataMap.put("searchKanji", findWordRequest.searchKanji);
		requestDataMap.put("searchKana", findWordRequest.searchKana);
		requestDataMap.put("searchRomaji", findWordRequest.searchRomaji);
		requestDataMap.put("searchTranslate", findWordRequest.searchTranslate);
		requestDataMap.put("searchInfo", findWordRequest.searchInfo);
		requestDataMap.put("searchOnlyCommonWord", findWordRequest.searchOnlyCommonWord);
		
		requestDataMap.put("wordPlaceSearch", findWordRequest.wordPlaceSearch);
		
		requestDataMap.put("dictionaryEntryTypeList", findWordRequest.dictionaryEntryTypeList);
				
		return requestDataMap;
	}
	
	private FindWordResult createFindWordResultFromJSON(JSONObject responseJSON) throws JSONException {
		
		FindWordResult findWordResult = new FindWordResult();
		
		findWordResult.moreElemetsExists = responseJSON.getBoolean("moreElemetsExists");
		findWordResult.foundGrammaAndExamples = responseJSON.getBoolean("foundGrammaAndExamples");
		findWordResult.foundNames = responseJSON.getBoolean("foundNames");
		
		findWordResult.result = new ArrayList<FindWordResult.ResultItem>();
		
		JSONArray resultJsonArray = responseJSON.getJSONArray("result");
		
		for (int resultIdx = 0; resultIdx < resultJsonArray.length(); ++resultIdx) {
			
			JSONObject currentJsonObjectResult = resultJsonArray.getJSONObject(resultIdx);
						
			DictionaryEntry dictionaryEntry = new DictionaryEntry();
			
			// id
			int id = currentJsonObjectResult.getInt("id");
			
			dictionaryEntry.setId(id);
			
			// dictionaryEntryTypeList
			JSONArray dictionaryEntryTypeListJsonArray = currentJsonObjectResult.getJSONArray("dictionaryEntryTypeList");
			
			List<DictionaryEntryType> dictionaryEntryTypeList = new ArrayList<DictionaryEntryType>();
			
			for (int dictionaryEntryTypeListJsonArrayIdx = 0; 
					dictionaryEntryTypeListJsonArrayIdx < dictionaryEntryTypeListJsonArray.length(); ++dictionaryEntryTypeListJsonArrayIdx) {
				
				dictionaryEntryTypeList.add(DictionaryEntryType.getDictionaryEntryType(
						dictionaryEntryTypeListJsonArray.getString(dictionaryEntryTypeListJsonArrayIdx)));
			}
			
			dictionaryEntry.setDictionaryEntryTypeList(dictionaryEntryTypeList);
			
			// attributeList
			AttributeList attributeList = new AttributeList();
			
			if (currentJsonObjectResult.has("attributeList") == true) {
				
				JSONArray attributeListJsonArray = currentJsonObjectResult.getJSONArray("attributeList");
				
				for (int attributeListJsonArrayIdx = 0; attributeListJsonArrayIdx < attributeListJsonArray.length();
						attributeListJsonArrayIdx++) {
					
					JSONObject currentAttributeJsonObject = attributeListJsonArray.getJSONObject(attributeListJsonArrayIdx);
					
					AttributeType attributeType = AttributeType.valueOf(currentAttributeJsonObject.getString("attributeType"));					
					List<String> attributeValueList = convertJSONArrayToListString(currentAttributeJsonObject.getJSONArray("attributeValue"));
					
					attributeList.addAttributeValue(attributeType, attributeValueList);
				}				
			}
			
			dictionaryEntry.setAttributeList(attributeList);
			
			// groups
			JSONArray groupsEnumListJsonArray = currentJsonObjectResult.getJSONArray("groups");
			
			List<GroupEnum> groupsEnumList = new ArrayList<GroupEnum>();
			
			for (int groupsEnumListJsonArrayIdx = 0; 
					groupsEnumListJsonArrayIdx < groupsEnumListJsonArray.length(); ++groupsEnumListJsonArrayIdx) {
				
				groupsEnumList.add(GroupEnum.valueOf(groupsEnumListJsonArray.getString(groupsEnumListJsonArrayIdx)));
			}
			
			dictionaryEntry.setGroups(groupsEnumList);

			// prefixKana
			if (currentJsonObjectResult.has("prefixKana") == true) {
				dictionaryEntry.setPrefixKana(currentJsonObjectResult.getString("prefixKana"));
			}
			
			// kanji
			if (currentJsonObjectResult.has("kanji") == true) {
				dictionaryEntry.setKanji(currentJsonObjectResult.getString("kanji"));
			}
			
			// kanaList
			dictionaryEntry.setKana(currentJsonObjectResult.getString("kana"));
			
			// prefixRomaji
			if (currentJsonObjectResult.has("prefixRomaji") == true) {
				dictionaryEntry.setPrefixRomaji(currentJsonObjectResult.getString("prefixRomaji"));
			}
			
			// romajiList
			dictionaryEntry.setRomaji(currentJsonObjectResult.getString("romaji"));
			
			// translates
			dictionaryEntry.setTranslates(convertJSONArrayToListString(currentJsonObjectResult.getJSONArray("translates")));
			
			// info
			if (currentJsonObjectResult.has("info") == true) {
				dictionaryEntry.setInfo(currentJsonObjectResult.getString("info"));
			}
			
			// name
			dictionaryEntry.setName(currentJsonObjectResult.getBoolean("name"));
						
			findWordResult.result.add(new FindWordResult.ResultItem(dictionaryEntry));
		}
		
		return findWordResult;
	}
	
	private List<String> convertJSONArrayToListString(JSONArray jsonArray) throws JSONException {
		
		List<String> result = new ArrayList<String>();
		
		for (int idx = 0; idx < jsonArray.length(); ++idx) {			
			result.add(jsonArray.getString(idx));			
		}
		
		return result;
	}
	
	public List<String> getAutoComplete(PackageInfo packageInfo, String word, AutoCompleteSuggestionType autoCompleteSuggestionType) {
		
		boolean connected = isConnected();
		
		if (connected == false) {			
			return new ArrayList<>();
		}
		
		if (word == null || word.length() < 2) {
			return new ArrayList<>();
		}

		HttpURLConnection httpURLConnection = null;

		BufferedReader contentInputStreamReader = null;
		
		try {
			// przygotuj dane wejsciowe
			Map<String, Object> requestDataMap = new HashMap<String, Object>();

			requestDataMap.put("word", word);
			requestDataMap.put("type", autoCompleteSuggestionType.getType());

			httpURLConnection = callRemoteService(packageInfo, AUTOCOMPLETE_URL, convertMapToJSONObject(requestDataMap).toString());

			// sprawdz odpowiedz
			int statusCode = httpURLConnection.getResponseCode();

			if (statusCode < 200 || statusCode >= 300) {

				Log.e("ServerClient", "Error send missing word: " + httpURLConnection.getResponseCode() + " - " + httpURLConnection.getResponseMessage());

				return new ArrayList<>();
			}
			
			// pobranie odpowiedzi
			contentInputStreamReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

			StringBuffer jsonResponseSb = new StringBuffer();
			
			while (true) {		
				String readLine = contentInputStreamReader.readLine();
				
				if (readLine == null) {
					break;
				}
				
				jsonResponseSb.append(readLine);			
			}

			if (jsonResponseSb.length() == 0) {
				return null;
			}

			JSONArray responseJSON = new JSONArray(jsonResponseSb.toString());

			List<String> result = new ArrayList<String>();
			
			for (int idx = 0; idx < responseJSON.length(); ++idx) {
				
				JSONObject jsonObject = responseJSON.getJSONObject(idx);
				
				result.add(jsonObject.getString("value"));
			}			
			
			return result;
			
		} catch (Exception e) {
			Log.e("ServerClient", "Error send missing word: ", e);
			
			return null;

		} finally {

			if (contentInputStreamReader != null) {

				try {
					contentInputStreamReader.close();

				} catch (IOException e) {
					// noop
				}
			}

			if (httpURLConnection != null) {
				httpURLConnection.disconnect();
			}
		}
	}
	
	public List<String> getSuggestionList(PackageInfo packageInfo, String word, AutoCompleteSuggestionType autoCompleteSuggestionType) {
		
		boolean connected = isConnected();
		
		if (connected == false) {			
			return null;
		}
		
		if (word == null || word.length() < 2) {
			return null;
		}

		HttpURLConnection httpURLConnection = null;

		BufferedReader contentInputStreamReader = null;
		
		try {
			// przygotuj dane wejsciowe
			Map<String, Object> requestDataMap = new HashMap<String, Object>();

			requestDataMap.put("word", word);
			requestDataMap.put("type", autoCompleteSuggestionType.getType());

			httpURLConnection = callRemoteService(packageInfo, SPELL_CHECKER_SUGGESTION_URL, convertMapToJSONObject(requestDataMap).toString());

			// sprawdz odpowiedz
			int statusCode = httpURLConnection.getResponseCode();

			if (statusCode < 200 || statusCode >= 300) {
				Log.e("ServerClient", "Error send missing word: " + httpURLConnection.getResponseCode() + " - " + httpURLConnection.getResponseMessage());
				
				return null;
			}
			
			// pobranie odpowiedzi
			contentInputStreamReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

			StringBuffer jsonResponseSb = new StringBuffer();
			
			while (true) {		
				String readLine = contentInputStreamReader.readLine();
				
				if (readLine == null) {
					break;
				}
				
				jsonResponseSb.append(readLine);			
			}

			if (jsonResponseSb.length() == 0) {
				return null;
			}

			JSONArray responseJSON = new JSONArray(jsonResponseSb.toString());

			List<String> result = new ArrayList<String>();
			
			for (int idx = 0; idx < responseJSON.length(); ++idx) {
				
				JSONObject jsonObject = responseJSON.getJSONObject(idx);
				
				result.add(jsonObject.getString("value"));
			}			
			
			return result;
			
		} catch (Exception e) {
			Log.e("ServerClient", "Error send missing word: ", e);
			
			return null;

		} finally {

			if (contentInputStreamReader != null) {

				try {
					contentInputStreamReader.close();

				} catch (IOException e) {
					// noop
				}
			}

			if (httpURLConnection != null) {
				httpURLConnection.disconnect();
			}
		}
	}

    public String callRemoteDictionaryConnectorMethod(PackageInfo packageInfo, String methodName, String jsonRequest) throws Exception {

        boolean connected = isConnected();

        if (connected == false) {
            throw new IOException("Not connected");
        }

		HttpURLConnection httpURLConnection = null;

		BufferedReader contentInputStreamReader = null;

        try {
			httpURLConnection = callRemoteService(packageInfo, REMOTE_DATABASE_CONNECTOR_BASE_URL + methodName, jsonRequest);

			// sprawdz odpowiedz
			int statusCode = httpURLConnection.getResponseCode();

			if (statusCode < 200 || statusCode >= 300) {
                Log.e("ServerClient", "Error callRemoteDictionaryConnectorMethod: " + httpURLConnection.getResponseCode() + " - " + httpURLConnection.getResponseMessage());

                throw new IOException(httpURLConnection.getResponseCode() + " - " + httpURLConnection.getResponseMessage());
            }

			// pobranie odpowiedzi
            contentInputStreamReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

            StringBuffer jsonResponseSb = new StringBuffer();

            while (true) {
                String readLine = contentInputStreamReader.readLine();

                if (readLine == null) {
                    break;
                }

                jsonResponseSb.append(readLine);
            }

			if (jsonResponseSb.length() == 0) {
				throw new IOException();
			}

			return jsonResponseSb.toString();

        } catch (Exception e) {
            Log.e("ServerClient", "Error callRemoteDictionaryConnectorMethod: ", e);

            throw e;

		} finally {

			if (contentInputStreamReader != null) {

				try {
					contentInputStreamReader.close();

				} catch (IOException e) {
					// noop
				}
			}

			if (httpURLConnection != null) {
				httpURLConnection.disconnect();
			}
		}
    }

	public static <T> T callInServerThread(Callable<Object> callable, Class<T> resultClass) throws DictionaryException {

		ExecutorService executorService = null;

		try {
			executorService = Executors.newFixedThreadPool(1);

			Future<Object> resultFuture = executorService.submit(callable);

			Object resultObject = null;

			try {
				resultObject = resultFuture.get();

			} catch (Exception e) {
				throw new DictionaryException(e);
			}

			if (resultObject == null) {
				return null;

			} else if (resultObject instanceof DictionaryException) {
				throw (DictionaryException) resultObject;

			} else if (resultObject instanceof Exception) {
				throw new DictionaryException((Exception) resultObject);

			} else if (resultClass.isInstance(resultObject) == true) {
				return (T) resultObject;

			} else {
				throw new RuntimeException("Unknown object: " + resultObject);
			}

		} finally {

			if (executorService != null) {
				executorService.shutdown();
			}
		}
	}

	private HttpURLConnection callRemoteService(PackageInfo packageInfo, String urlString, String requestPostString) throws Exception {

		// url
		URL url = new URL(urlString);

		// tworzymy polaczenie
		HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();

		httpURLConnection.setRequestMethod("POST");

		// parametry do polaczenia
		httpURLConnection.setUseCaches(false);
		httpURLConnection.setAllowUserInteraction(false);
		httpURLConnection.setConnectTimeout(TIMEOUT);
		httpURLConnection.setReadTimeout(TIMEOUT);

		httpURLConnection.setDoInput(true);
		httpURLConnection.setDoOutput(true);

		// ustaw naglowki
		httpURLConnection.setRequestProperty("Accept", "application/json");
		httpURLConnection.setRequestProperty("Content-type", "application/json");
		httpURLConnection.setRequestProperty("User-Agent", createUserAgent(packageInfo));

		httpURLConnection.setRequestProperty("Content-Type", "application/json; utf-8");

		//

		// wywolaj serwer
		httpURLConnection.connect();

		// dane wejsciowe
		BufferedOutputStream bufferedOutputStream = null;

		try {
			bufferedOutputStream = new BufferedOutputStream(httpURLConnection.getOutputStream());

			bufferedOutputStream.write(requestPostString.getBytes("UTF-8"));

			bufferedOutputStream.flush();

		} catch(IOException exception) {
			throw exception;

		} finally {

			if (bufferedOutputStream != null) {

				try {
					bufferedOutputStream.close();

				} catch (IOException e) {
					// noop
				}
			}
		}

		return httpURLConnection;
	}

	public boolean sendQueueEvent(PackageInfo packageInfo, IQueueEvent queueEvent) {

		boolean connected = isConnected();

		if (connected == false) {
			return false;
		}

		HttpURLConnection httpURLConnection = null;

		BufferedReader contentInputStreamReader = null;

		try {
			String jsonRequest = new Gson().toJson(new QueueEventWrapper(queueEvent.getId(), queueEvent.getUserId(), queueEvent.getQueryEventOperation(), queueEvent.getCreateDateAsString(), queueEvent.getParams()));

			httpURLConnection = callRemoteService(packageInfo, SEND_QUEUE_EVENT_URL, jsonRequest);

			// sprawdz odpowiedz
			int statusCode = httpURLConnection.getResponseCode();

			if (statusCode < 200 || statusCode >= 300) {
				Log.e("ServerClient", "Error sendQueueEvent: " + httpURLConnection.getResponseCode() + " - " + httpURLConnection.getResponseMessage());

				return false;
			}

			return true;

		} catch (Exception e) {
			Log.e("ServerClient", "Error sendQueueEvent: ", e);

			return false;

		} finally {

			if (contentInputStreamReader != null) {

				try {
					contentInputStreamReader.close();

				} catch (IOException e) {
					// noop
				}
			}

			if (httpURLConnection != null) {
				httpURLConnection.disconnect();
			}
		}
	}

	public static class GetMessageResult {

		public String message;

		public String timestamp;
	}

	public GetMessageResult getMessage(PackageInfo packageInfo) {

		boolean connected = isConnected();

		if (connected == false) {
			return null;
		}

		HttpURLConnection httpURLConnection = null;

		BufferedReader contentInputStreamReader = null;

		try {
			httpURLConnection = callRemoteService(packageInfo, GET_MESSAGE_URL, new JSONObject().toString());

			// sprawdz odpowiedz
			int statusCode = httpURLConnection.getResponseCode();

			if (statusCode < 200 || statusCode >= 300) {

				Log.e("ServerClient", "Error search: " + httpURLConnection.getResponseCode() + " - " + httpURLConnection.getResponseMessage());

				return null;
			}

			// pobierz odpowiedz
			contentInputStreamReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

			StringBuffer jsonResponseSb = new StringBuffer();

			while (true) {
				String readLine = contentInputStreamReader.readLine();

				if (readLine == null) {
					break;
				}

				jsonResponseSb.append(readLine);
			}

			if (jsonResponseSb.length() == 0) {
				return null;
			}

			JSONObject responseJSON = new JSONObject(jsonResponseSb.toString());

			String message = responseJSON.optString("message");
			String timestamp = responseJSON.optString("timestamp");

			// mamy jakis komunikat
			if (message != null && message.trim().equals("") == false && timestamp != null && timestamp.trim().equals("") == false) {

				GetMessageResult getMessageResult = new GetMessageResult();

				getMessageResult.message = message.trim();
				getMessageResult.timestamp = timestamp.trim();

				return getMessageResult;

			} else {
				return null;
			}

		} catch (Exception e) {
			Log.e("ServerClient", "Error search: ", e);

			return null;

		} finally {

			if (contentInputStreamReader != null) {

				try {
					contentInputStreamReader.close();

				} catch (IOException e) {
					// noop
				}
			}

			if (httpURLConnection != null) {
				httpURLConnection.disconnect();
			}
		}
	}

	public static enum AutoCompleteSuggestionType {
		
		WORD_DICTIONARY("wordDictionaryEntry"),
		
		KANJI_DICTIONARY("kanjiDictionaryEntry");
		
		private String type;
		
		AutoCompleteSuggestionType(String type) {
			this.type = type;
		}

		public String getType() {
			return type;
		}
	}
} public class Splash extends Activity implements ActivityCompat.OnRequestPermissionsResultCallback {

	private static final int REQUEST_CODE_ASK_PERMISSIONS = 666;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		// init google analytics
		// JapaneseAndroidLearnHelperApplication.getInstance().getTracker();

		requestWindowFeature(Window.FEATURE_NO_TITLE);

		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

		JapaneseAndroidLearnHelperApplication.getInstance().setContentViewAndTheme(this, R.layout.splash);

		final TextView progressDesc = (TextView) findViewById(R.id.splash_desc_label);

		progressDesc.setText("");

		ConfigManager configManager = new ConfigManager(this);

		JapaneseAndroidLearnHelperApplication.getInstance().setConfigManager(configManager);

		// poproszenie o uprawnienie

		progressDesc.setText(getString(R.string.splash_check_permission));

		// sprawdzamy, czy mam nadane juz uprawnienie dostepu do pamieci urzadzenia
		int hasStoragePermission = ContextCompat.checkSelfPermission(this,
				Manifest.permission.WRITE_EXTERNAL_STORAGE);

		if (hasStoragePermission != PackageManager.PERMISSION_GRANTED) {

			// metoda shouldShowRequestPermissionRationale zwraca false, gdy uruchamiamy aplikacje pierwszy raz lub uzytkownik zablokowal pokazywanie prosb o uprawnienie
			//if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == false) {

			AlertDialog alertDialog = new AlertDialog.Builder(Splash.this).create();

			alertDialog.setCancelable(false);

			alertDialog.setTitle(getString(R.string.splash_permission_request_message_box_title));
			alertDialog.setMessage(getString(R.string.splash_permission_request_message_box_message));

			alertDialog.setButton(getString(R.string.splash_ok),
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

							ActivityCompat.requestPermissions(Splash.this,
									new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},
									REQUEST_CODE_ASK_PERMISSIONS);
						}
					});

			if (isFinishing() == false) {
				alertDialog.show();
			}

			return;

		} else { // mamy juz uprawnienie
			doInit();
		}
	}

	private void doInit() {

		final ProgressBar progressBar = (ProgressBar) findViewById(R.id.splash_progressbar);

		final TextView progressDesc = (TextView) findViewById(R.id.splash_desc_label);

		int versionCode = 0;

		try {
			PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);

			versionCode = packageInfo.versionCode;

		} catch (NameNotFoundException e) {
		}

		final int finalVersionCode = versionCode;

		final Resources resources = getResources();
		final AssetManager assets = getAssets();

		// create dictionary manager
		final DictionaryManagerCommon dictionaryManager = DictionaryManagerCommon.getDictionaryManager();

		class ProgressInfo {
			Integer progressBarMaxValue;

			Integer progressBarValue;

			String description;

			String errorMessage;
		}

		class InitJapaneseAndroidLearnHelperContextAsyncTask extends AsyncTask<Void, ProgressInfo, Void> {

			class LoadWithProgress implements ILoadWithProgress {

				@Override
				public void setMaxValue(int maxValue) {
					ProgressInfo progressInfo = new ProgressInfo();

					progressInfo.progressBarMaxValue = maxValue;

					publishProgress(progressInfo);
				}

				@Override
				public void setCurrentPos(int currentPos) {
					ProgressInfo progressInfo = new ProgressInfo();

					progressInfo.progressBarValue = currentPos;

					publishProgress(progressInfo);
				}

				@Override
				public void setDescription(String desc) {
					ProgressInfo progressInfo = new ProgressInfo();

					progressInfo.description = desc;

					publishProgress(progressInfo);
				}

				@Override
				public void setError(String errorMessage) {

					ProgressInfo progressInfo = new ProgressInfo();

					progressInfo.errorMessage = errorMessage;

					publishProgress(progressInfo);
				}
			}

			private String errorMessage;

			@Override
			protected Void doInBackground(Void... params) {

				LoadWithProgress loadWithProgress = new LoadWithProgress();

				dictionaryManager.init(Splash.this, loadWithProgress, resources, assets, getPackageName(), finalVersionCode);

				JapaneseAndroidLearnHelperApplication.getInstance().setDictionaryManager(dictionaryManager);

				return null;
			}

			@Override
			protected void onProgressUpdate(ProgressInfo... values) {
				super.onProgressUpdate(values);

				ProgressInfo progressInfo = values[0];

				if (progressInfo.description != null) {
					progressDesc.setText(progressInfo.description);
				}

				if (progressInfo.progressBarMaxValue != null) {
					progressBar.setMax(progressInfo.progressBarMaxValue);
				}

				if (progressInfo.progressBarValue != null) {
					progressBar.setProgress(progressInfo.progressBarValue);
				}

				if (progressInfo.errorMessage != null) {
					this.errorMessage = progressInfo.errorMessage;
				}
			}

			@SuppressWarnings("deprecation")
			@Override
			protected void onPostExecute(Void result) {

				if (errorMessage != null) {

					AlertDialog alertDialog = new AlertDialog.Builder(Splash.this).create();

					alertDialog.setMessage(getString(R.string.init_dictionary_error, errorMessage));
					alertDialog.setCancelable(false);

					alertDialog.setButton(getString(R.string.ok), new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					});

					if (isFinishing() == false) {
						alertDialog.show();
					}

					return;
				}

				final SplashConfig splashConfig = JapaneseAndroidLearnHelperApplication.getInstance()
						.getConfigManager(Splash.this).getSplashConfig();

				Boolean dialogBoxSkipResult = splashConfig.getDialogBoxSkip();

				if (dialogBoxSkipResult == null || dialogBoxSkipResult.booleanValue() == false) {

					AlertDialog alertDialog = new AlertDialog.Builder(Splash.this).create();

					LayoutInflater layoutInflater = LayoutInflater.from(Splash.this);

					View alertDialogView = layoutInflater.inflate(R.layout.splash_dialogbox, null);

					final TextView messageTextView = (TextView) alertDialogView
							.findViewById(R.id.splash_dialogbox_message);
					final CheckBox skipCheckBox = (CheckBox) alertDialogView
							.findViewById(R.id.splash_dialogbox_skipCheckBox);

					alertDialog.setView(alertDialogView);

					alertDialog.setCancelable(false);

					alertDialog.setTitle(getString(R.string.splash_message_box_title));
					messageTextView.setText(getString(R.string.splash_message_box_info));

					alertDialog.setButton(getString(R.string.splash_ok),
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {

									splashConfig.setDialogBoxSkip(skipCheckBox.isChecked());

									Intent intent = new Intent(getApplicationContext(),
											JapaneseAndroidLearnHelperMainActivity.class);

									startActivity(intent);

									finish();

									// start queue thread
									JapaneseAndroidLearnHelperApplication.getInstance().startQueueThread(Splash.this);

									// send start event
									JapaneseAndroidLearnHelperApplication.getInstance().addQueueEvent(Splash.this, new StatStartAppEvent(
                                            JapaneseAndroidLearnHelperApplication.getInstance().getConfigManager(Splash.this).getCommonConfig().getOrGenerateUniqueUserId()));
								}
							});

					if (isFinishing() == false) {
						alertDialog.show();
					}

				} else {

					Intent intent = new Intent(getApplicationContext(), JapaneseAndroidLearnHelperMainActivity.class);

					startActivity(intent);

					finish();

					// start queue thread
					JapaneseAndroidLearnHelperApplication.getInstance().startQueueThread(Splash.this);

					// send start event
					JapaneseAndroidLearnHelperApplication.getInstance().addQueueEvent(Splash.this, new StatStartAppEvent(
                            JapaneseAndroidLearnHelperApplication.getInstance().getConfigManager(Splash.this).getCommonConfig().getOrGenerateUniqueUserId()));
				}
			}
		}

		InitJapaneseAndroidLearnHelperContextAsyncTask initJapaneseAndroidLearnHelperContextAsyncTask = new InitJapaneseAndroidLearnHelperContextAsyncTask();

		initJapaneseAndroidLearnHelperContextAsyncTask.execute();
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

		switch (requestCode) {
			case REQUEST_CODE_ASK_PERMISSIONS:

				if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // dostalismy uprawnienie, inicjalizacja

					doInit();

				} else {
					// nie dostalismy uprawnienia

                    AlertDialog alertDialog = new AlertDialog.Builder(Splash.this).create();

                    alertDialog.setCancelable(false);

                    alertDialog.setMessage(getString(R.string.splash_permission_request_denied_message_box_message));

                    alertDialog.setButton(getString(R.string.splash_ok),
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                }
                            });

                    if (isFinishing() == false) {
                        alertDialog.show();
                    }
				}
				break;
			default:
				super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		}
	}
} public class WordTestOptions extends Activity {
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		MenuShorterHelper.onCreateOptionsMenu(menu);
		
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		
		return MenuShorterHelper.onOptionsItemSelected(item, getApplicationContext(), this);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		JapaneseAndroidLearnHelperApplication.getInstance().setContentViewAndTheme(this, R.layout.word_test_options);

		JapaneseAndroidLearnHelperApplication.getInstance().logScreen(this, getString(R.string.logs_word_test_options));

		final WordTestConfig wordTestConfig = JapaneseAndroidLearnHelperApplication.getInstance().getConfigManager(this).getWordTestConfig();
		
		final LinearLayout mainLayout = (LinearLayout)findViewById(R.id.word_test_options_main_layout);
		
		// get repeat number
		final EditText repeatNumberEditText = (EditText)findViewById(R.id.word_test_options_repeat_number_edit_text);
		
		repeatNumberEditText.setText(String.valueOf(wordTestConfig.getRepeatNumber()));
						
		// show kanji check box
		final CheckBox showKanjiCheckBox = (CheckBox)findViewById(R.id.word_test_options_show_kanji);
		
		showKanjiCheckBox.setChecked(wordTestConfig.getShowKanji());

		// show kana check box
		final CheckBox showKanaCheckBox = (CheckBox)findViewById(R.id.word_test_options_show_kana);
		
		showKanaCheckBox.setChecked(wordTestConfig.getShowKana());
		
		// show translate check box
		final CheckBox showTranslateCheckBox = (CheckBox)findViewById(R.id.word_test_options_show_translate);
		
		showTranslateCheckBox.setChecked(wordTestConfig.getShowTranslate());
		
		// show additional info check box
		final CheckBox showAdditionalInfoCheckBox = (CheckBox)findViewById(R.id.word_test_options_show_additional_info);
		
		showAdditionalInfoCheckBox.setChecked(wordTestConfig.getShowAdditionalInfo());
		
		// test mode
		final RadioButton testModeInputRadioButton = (RadioButton)findViewById(R.id.word_test_options_test_mode_radiogroup_input);
		final RadioButton testModeOverviewRadioButton = (RadioButton)findViewById(R.id.word_test_options_test_mode_radiogroup_overview);
		
		WordTestMode wordTestMode = wordTestConfig.getWordTestMode();
		
		if (wordTestMode == WordTestMode.INPUT) {
			testModeInputRadioButton.setChecked(true);
			showKanaCheckBox.setEnabled(false);
			showKanaCheckBox.setChecked(false);
		} else if (wordTestMode == WordTestMode.OVERVIEW) {
			testModeOverviewRadioButton.setChecked(true);
			showKanaCheckBox.setEnabled(true);
		} else {
			throw new RuntimeException("WordTestMode wordTestMode: " + wordTestMode);
		}
		
		// random check box
		final CheckBox randomCheckBox = (CheckBox)findViewById(R.id.word_test_options_random);
		
		randomCheckBox.setChecked(wordTestConfig.getRandom());

		// until sucess check box
		final CheckBox untilSuccessCheckBox = (CheckBox)findViewById(R.id.word_test_options_until_success);
		
		final CheckBox untilSuccessNewWordLimitCheckBox = (CheckBox)findViewById(R.id.word_test_options_new_word_limit);
		
		untilSuccessCheckBox.setChecked(wordTestConfig.getUntilSuccess());
		untilSuccessNewWordLimitCheckBox.setChecked(wordTestConfig.getUntilSuccessNewWordLimit());
		
		setUntilSuccessNewWordLimitCheckBoxEnabled(untilSuccessCheckBox, untilSuccessNewWordLimitCheckBox);
		
		// actions
		untilSuccessCheckBox.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				setUntilSuccessNewWordLimitCheckBoxEnabled(untilSuccessCheckBox, untilSuccessNewWordLimitCheckBox);				
			}
		});
		
		testModeInputRadioButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				showKanaCheckBox.setEnabled(false);
				showKanaCheckBox.setChecked(false);
			}
		});

		testModeOverviewRadioButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				showKanaCheckBox.setEnabled(true);	
			}
		});

		// start button
		final Button startButton = (Button)findViewById(R.id.word_test_options_start);

		// groups
		final List<CheckBox> wordGroupCheckBoxList = new ArrayList<CheckBox>();

		// loading word groups
		List<GroupEnum> groupsNames;

		try {
			groupsNames = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(this).getDictionaryEntryGroupTypes();

		} catch (DictionaryException e) {
			Toast.makeText(this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();

			startButton.setEnabled(false);

			groupsNames = new ArrayList<>();
		}
		
		Set<String> chosenWordGroups = wordTestConfig.getChosenWordGroups();

		for (int groupsNamesIdx = 0; groupsNamesIdx < groupsNames.size(); ++groupsNamesIdx) {

			GroupEnum groupEnum = groupsNames.get(groupsNamesIdx);

			if (groupEnum == GroupEnum.OTHER) {
				continue;
			}

			CheckBox checkbox = createGroupCheckBox(groupEnum, null, groupEnum.getValue(),
					chosenWordGroups != null && chosenWordGroups.contains(groupsNames.get(groupsNamesIdx).getValue()));

			wordGroupCheckBoxList.add(checkbox);
			
			mainLayout.addView(checkbox, mainLayout.getChildCount() - 1);
		}

		// loading user word groups
		List<UserGroupEntity> allUserGroupList = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(this).getDataManager().getAllUserGroupList();

		Set<Integer> chosenWordUserGroups = wordTestConfig.getChosenWordUserGroups();

		for (int allUserGroupListIdx = 0; allUserGroupListIdx < allUserGroupList.size(); ++allUserGroupListIdx) {

			UserGroupEntity userGroupEntity = allUserGroupList.get(allUserGroupListIdx);

			String checkboxText = userGroupEntity.getType() == UserGroupEntity.Type.USER_GROUP ? userGroupEntity.getName() :
					getString(R.string.user_group_star_group);

			CheckBox checkbox = createGroupCheckBox(null, userGroupEntity, checkboxText,
					chosenWordUserGroups != null && chosenWordUserGroups.contains(userGroupEntity.getId()));

			wordGroupCheckBoxList.add(checkbox);

			mainLayout.addView(checkbox);
		}

		// start action		
		startButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				
				// repeat
				String repeatNumberString = repeatNumberEditText.getText().toString();
				
				boolean repeatNumberError = false;
				
				int repeatNumber = -1;
				
				if (repeatNumberString == null) {
					repeatNumberError = true;
				} else {
					
					try {
						repeatNumber = Integer.parseInt(repeatNumberString);
					} catch (NumberFormatException e) {
						repeatNumberError = true;
					}
				}
				
				if (repeatNumberError == false && repeatNumber <= 0) {
					repeatNumberError = true;
				}
				
				if (repeatNumberError == true) {
					
					Toast toast = Toast.makeText(WordTestOptions.this, getString(R.string.word_test_options_repeat_number_invalid), Toast.LENGTH_SHORT);

					toast.show();

					return;					
				}
				
				wordTestConfig.setRepeatNumber(repeatNumber);
				
				// test mode
				WordTestMode chosenWordTestMode = null;
				
				if (testModeInputRadioButton.isChecked() == true) {
					chosenWordTestMode = WordTestMode.INPUT;
				} else if (testModeOverviewRadioButton.isChecked() == true) {
					chosenWordTestMode = WordTestMode.OVERVIEW;
				} else {
					throw new RuntimeException("WordTestConfig wordTestConfig");
				}
				
				wordTestConfig.setWordTestMode(chosenWordTestMode);
								
				// random
				boolean random = randomCheckBox.isChecked();
				
				wordTestConfig.setRandom(random);
				
				// until success
				boolean untilSuccess = untilSuccessCheckBox.isChecked();
				
				wordTestConfig.setUntilSuccess(untilSuccess);
				
				// until success new word limit
				boolean untilSuccessNewWordLimit = untilSuccessNewWordLimitCheckBox.isChecked();
				
				wordTestConfig.setUntilSuccessNewWordLimit(untilSuccessNewWordLimit);
				
				// show kanji
				boolean showKanji = showKanjiCheckBox.isChecked();
								
				wordTestConfig.setShowKanji(showKanji);
				
				// show kana
				boolean showKana = showKanaCheckBox.isChecked();
				
				wordTestConfig.setShowKana(showKana);
				
				// show translate
				boolean showTranslate = showTranslateCheckBox.isChecked();
				
				wordTestConfig.setShowTranslate(showTranslate);
				
				// show additional info
				boolean showAdditionalInfo = showAdditionalInfoCheckBox.isChecked();
				
				wordTestConfig.setAdditionalInfoTranslate(showAdditionalInfo);
				
				if (chosenWordTestMode == WordTestMode.INPUT && showKanji == false && showTranslate == false) {
					
					Toast toast = Toast.makeText(WordTestOptions.this, getString(R.string.word_test_options_no_kanji_translate), Toast.LENGTH_SHORT);

					toast.show();
					
					return;
				}

				if (chosenWordTestMode == WordTestMode.OVERVIEW && showKanji == false && showKana == false && showTranslate == false) {
					
					Toast toast = Toast.makeText(WordTestOptions.this, getString(R.string.word_test_options_no_kanji_kana_translate), Toast.LENGTH_SHORT);

					toast.show();
					
					return;
				}
				
				// groups
				List<DictionaryEntry> chosenAllDictionaryEntryList = new ArrayList<DictionaryEntry>();
				
				List<String> chosenWordGroupsNumberList = new ArrayList<String>();
				List<Integer> chosenWordUserGroupsNumberList = new ArrayList<Integer>();
				
				boolean wasFilteredWords = false;

				DictionaryManagerCommon dictionaryManager = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(WordTestOptions.this);

				for (int wordGroupCheckBoxListIdx = 0; wordGroupCheckBoxListIdx < wordGroupCheckBoxList.size(); ++wordGroupCheckBoxListIdx) {
					
					CheckBox currentWordGroupCheckBox = wordGroupCheckBoxList.get(wordGroupCheckBoxListIdx);
					
					if (currentWordGroupCheckBox.isChecked() == true) {

						CheckBoxTag currentWordGroupCheckBoxTag = (CheckBoxTag)currentWordGroupCheckBox.getTag();

						List<DictionaryEntry> currentWordsGroupDictionaryEntryList = null;

						if (currentWordGroupCheckBoxTag.groupType == CheckBoxGroupType.INTERNAL_GROUP) { // grupa wbudowana

							try {
								currentWordsGroupDictionaryEntryList = dictionaryManager.getGroupDictionaryEntries(currentWordGroupCheckBoxTag.groupEnum);

							} catch (DictionaryException e) {
								Toast.makeText(WordTestOptions.this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();

								return;
							}

						} else if (currentWordGroupCheckBoxTag.groupType == CheckBoxGroupType.USER_GROUP) { // grupa uzytkownika

							List<UserGroupItemEntity> userGroupItemListForUserEntity = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(WordTestOptions.this).getDataManager().getUserGroupItemListForUserEntity(currentWordGroupCheckBoxTag.userGroupEntity);

							if (userGroupItemListForUserEntity == null) {
								userGroupItemListForUserEntity = new ArrayList<>();
							}

							currentWordsGroupDictionaryEntryList = new ArrayList<>();

							for (UserGroupItemEntity userGroupItemEntity : userGroupItemListForUserEntity) {

								if (userGroupItemEntity.getType() == UserGroupItemEntity.Type.DICTIONARY_ENTRY) {

									DictionaryEntry dictionaryEntry = null;

									try {
										dictionaryEntry = dictionaryManager.getDictionaryEntryById(userGroupItemEntity.getItemId());

									} catch (DictionaryException e) {
										Toast.makeText(WordTestOptions.this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();

										return;
									}

									if (dictionaryEntry != null) {
										currentWordsGroupDictionaryEntryList.add(dictionaryEntry);
									}
								}
							}
						}

						for (int repeatIdx = 0; repeatIdx < repeatNumber; ++repeatIdx) {

							for (DictionaryEntry currentDictionaryEntry : currentWordsGroupDictionaryEntryList) {

								if (chosenWordTestMode == WordTestMode.INPUT) {

									if (showKanji == false && showKana == true && currentDictionaryEntry.isKanjiExists() == false) { // gdy bedziemy wpisywac kanji na podstawie kana, ale kanji nie ma
										wasFilteredWords = true;
									} else if (showTranslate == true || currentDictionaryEntry.isKanjiExists() == true) {
										chosenAllDictionaryEntryList.add(currentDictionaryEntry);
									} else {
										wasFilteredWords = true;
									}

								} else if (chosenWordTestMode == WordTestMode.OVERVIEW) {

									if (showKanji == true && showKana == false && showTranslate == false && currentDictionaryEntry.isKanjiExists() == false) {
										wasFilteredWords = true;
									} else if (showKanji == false && showKana == true && showTranslate == true && currentDictionaryEntry.isKanjiExists() == false) {
										wasFilteredWords = true;
									} else {
										chosenAllDictionaryEntryList.add(currentDictionaryEntry);
									}

								} else {
									throw new RuntimeException("WordTestConfig wordTestConfig: " + chosenWordTestMode);
								}
							}
						}

						if (currentWordGroupCheckBoxTag.groupType == CheckBoxGroupType.INTERNAL_GROUP) { // grupa wbudowana

							chosenWordGroupsNumberList.add(currentWordGroupCheckBoxTag.groupEnum.getValue());

						} else if (currentWordGroupCheckBoxTag.groupType == CheckBoxGroupType.USER_GROUP) { // grupa uzytkownika

							chosenWordUserGroupsNumberList.add(currentWordGroupCheckBoxTag.userGroupEntity.getId());

						}
					}
				}
								
				if (chosenAllDictionaryEntryList.size() == 0) {
					
					Toast toast = null;
					
					if (wasFilteredWords == false && chosenWordGroupsNumberList.size() == 0 && chosenWordUserGroupsNumberList.size() == 0) {
						toast = Toast.makeText(WordTestOptions.this, getString(R.string.word_test_options_word_group_no_chosen), Toast.LENGTH_SHORT);	
					} else {
						toast = Toast.makeText(WordTestOptions.this, getString(R.string.word_test_options_word_filtered), Toast.LENGTH_SHORT);
					}

					toast.show();

					return;
				}
				
				wordTestConfig.setChosenWordGroups(chosenWordGroupsNumberList);
				wordTestConfig.setChosenWordUserGroups(chosenWordUserGroupsNumberList);
				
				if (random == true) {
					Collections.shuffle(chosenAllDictionaryEntryList);
				}
				
				JapaneseAndroidLearnHelperWordTestContext wordTestContext = JapaneseAndroidLearnHelperApplication.getInstance().getContext().getWordTestContext();
				
				EntryOrderList<DictionaryEntry> entryOrderList = null;
				
				if (untilSuccess == true && untilSuccessNewWordLimit == true) {
					entryOrderList = new EntryOrderList<DictionaryEntry>(chosenAllDictionaryEntryList, 10);
				} else {
					entryOrderList = new EntryOrderList<DictionaryEntry>(chosenAllDictionaryEntryList, chosenAllDictionaryEntryList.size());
				}				
				
				wordTestContext.setWordsTest(entryOrderList);
				
				finish();
				
				Intent intent = new Intent(getApplicationContext(), WordTest.class);

				startActivity(intent);
			}
		});

		/*
		// report problem button
		Button reportProblemButton = (Button)findViewById(R.id.word_test_options_report_problem_button);

		reportProblemButton.setOnClickListener(new OnClickListener() {

			public void onClick(View view) {

				StringBuffer detailsSb = new StringBuffer();
				
				TextView optionsRepeat = (TextView)findViewById(R.id.word_test_options_repeat);
				TextView optionsTestMode = (TextView)findViewById(R.id.word_test_options_test_mode);
				TextView optionsShow = (TextView)findViewById(R.id.word_test_options_show);
				TextView optionsOther = (TextView)findViewById(R.id.word_test_options_other);
				TextView optionsGroupPleaseChoose = (TextView)findViewById(R.id.word_test_options_group_please_choose);
				TextView optionsGroupInternal = (TextView)findViewById(R.id.word_test_options_group_internal);
				TextView optionsGroupUser = (TextView)findViewById(R.id.word_test_options_group_user);

				detailsSb.append("*** " + optionsRepeat.getText() + " ***\n\n");
				detailsSb.append(repeatNumberEditText.getText().toString()).append("\n\n");

				detailsSb.append("*** " + optionsTestMode.getText() + " ***\n\n");
				detailsSb.append(testModeInputRadioButton.isChecked() + " - " + testModeInputRadioButton.getText()).append("\n\n");
				detailsSb.append(testModeOverviewRadioButton.isChecked() + " - " + testModeOverviewRadioButton.getText()).append("\n\n");
				
				detailsSb.append("*** " + optionsShow.getText() + " ***\n\n");
				detailsSb.append(showKanjiCheckBox.isChecked() + " - " + showKanjiCheckBox.getText()).append("\n\n");
				detailsSb.append(showKanaCheckBox.isChecked() + " - " + showKanaCheckBox.getText()).append("\n\n");
				detailsSb.append(showTranslateCheckBox.isChecked() + " - " + showTranslateCheckBox.getText()).append("\n\n");
				detailsSb.append(showAdditionalInfoCheckBox.isChecked() + " - " + showAdditionalInfoCheckBox.getText()).append("\n\n");
				
				detailsSb.append("*** " + optionsOther.getText() + " ***\n\n");
				detailsSb.append(randomCheckBox.isChecked() + " - " + randomCheckBox.getText()).append("\n\n");
				detailsSb.append(untilSuccessCheckBox.isChecked() + " - " + untilSuccessCheckBox.getText()).append("\n\n");
				detailsSb.append(untilSuccessNewWordLimitCheckBox.isChecked() + " - " + untilSuccessNewWordLimitCheckBox.getText()).append("\n\n");

				detailsSb.append("*** " + optionsGroupPleaseChoose.getText() + " ***\n\n");
				detailsSb.append("*** " + optionsGroupInternal.getText() + " ***\n\n");

				for (CheckBox currentWordGroupCheckBox : wordGroupCheckBoxList) {

					CheckBoxTag currentWordGroupCheckBoxTag = (CheckBoxTag)currentWordGroupCheckBox.getTag();

					if (currentWordGroupCheckBoxTag.groupType != CheckBoxGroupType.INTERNAL_GROUP) {
						continue;
					}

					String currentWordGroupCheckBoxText = currentWordGroupCheckBox.getText().toString();

					detailsSb.append(currentWordGroupCheckBox.isChecked() + " - " + currentWordGroupCheckBoxText).append("\n");
				}

				detailsSb.append("*** " + optionsGroupUser.getText() + " ***\n\n");

				for (CheckBox currentWordGroupCheckBox : wordGroupCheckBoxList) {

					CheckBoxTag currentWordGroupCheckBoxTag = (CheckBoxTag)currentWordGroupCheckBox.getTag();

					if (currentWordGroupCheckBoxTag.groupType != CheckBoxGroupType.USER_GROUP) {
						continue;
					}

					String currentWordGroupCheckBoxText = currentWordGroupCheckBox.getText().toString();

					detailsSb.append(currentWordGroupCheckBox.isChecked() + " - " + currentWordGroupCheckBoxText).append("\n");
				}

				//

				String chooseEmailClientTitle = getString(R.string.choose_email_client);

				String mailSubject = getString(R.string.word_test_options_report_problem_email_subject);

				String mailBody = getString(R.string.word_test_options_report_problem_email_body,
						detailsSb.toString());

				String versionName = "";
				int versionCode = 0;

				try {
					PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);

					versionName = packageInfo.versionName;
					versionCode = packageInfo.versionCode;

				} catch (NameNotFoundException e) {        	
				}

				Intent reportProblemIntent = ReportProblem.createReportProblemIntent(mailSubject, mailBody.toString(), versionName, versionCode); 

				startActivity(Intent.createChooser(reportProblemIntent, chooseEmailClientTitle));
			}
		});
		*/
	}
	
	private void setUntilSuccessNewWordLimitCheckBoxEnabled(CheckBox untilSuccessCheckBox, CheckBox untilSuccessNewWordLimitCheckBox) {
		
		if (untilSuccessCheckBox.isChecked() == true) {
			untilSuccessNewWordLimitCheckBox.setEnabled(true);
		} else {
			untilSuccessNewWordLimitCheckBox.setEnabled(false);
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	private CheckBox createGroupCheckBox(GroupEnum groupEnum, UserGroupEntity userGroupEntity, String text, boolean checked) {

		CheckBox checkbox = new CheckBox(this);

		if ( 	(groupEnum == null && userGroupEntity == null) ||
				(groupEnum != null && userGroupEntity != null)) {
			throw new RuntimeException();
		}

		if (groupEnum != null) {
			checkbox.setTag(new CheckBoxTag(groupEnum));

		} else if (userGroupEntity != null) {
			checkbox.setTag(new CheckBoxTag(userGroupEntity));
		}

		checkbox.setLayoutParams(new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));

		checkbox.setTextSize(12);
		checkbox.setText(text);

		checkbox.setChecked(checked);

		return checkbox;
	}

	private static class CheckBoxTag {

		private CheckBoxGroupType groupType;

		private GroupEnum groupEnum;

		private UserGroupEntity userGroupEntity;

		public CheckBoxTag(GroupEnum groupEnum) {
			this.groupType = CheckBoxGroupType.INTERNAL_GROUP;
			this.groupEnum = groupEnum;
		}

		public CheckBoxTag(UserGroupEntity userGroupEntity) {
			this.groupType = CheckBoxGroupType.USER_GROUP;
			this.userGroupEntity = userGroupEntity;
		}
	}

	private static enum CheckBoxGroupType {

		INTERNAL_GROUP,

		USER_GROUP;
	}
} public class WordTestSM2Options extends Activity {

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		menu.add(Menu.NONE, R.id.word_test_sm2_options_set_next_day, Menu.NONE, getString(R.string.word_test_sm2_options_set_next_day));
		
		MenuShorterHelper.onCreateOptionsMenu(menu);
		
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		
		if (item.getItemId() == R.id.word_test_sm2_options_set_next_day) { 
			
			DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
				
			    @Override
			    public void onClick(DialogInterface dialog, int which) {
			        switch (which){
			        case DialogInterface.BUTTON_POSITIVE:
			        	
						final DictionaryManagerCommon dictionaryManager = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(WordTestSM2Options.this);
						
						final WordTestSM2Manager wordTestSM2Manager = dictionaryManager.getWordTestSM2Manager();
					
						wordTestSM2Manager.setNextDay();			        	
			        	
			            break;

			        case DialogInterface.BUTTON_NEGATIVE:
			        	
			        	// noop
			        	
			            break;
			        }
			    }
			};

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			
			builder.setMessage(getString(R.string.word_test_sm2_options_set_next_day_alert_info)).setPositiveButton(getString(R.string.word_test_sm2_options_set_next_day_question_yes), dialogClickListener)
			    .setNegativeButton(getString(R.string.word_test_sm2_options_set_next_day_question_no), dialogClickListener).show();		
			
			return true;
		
		} else {
			return MenuShorterHelper.onOptionsItemSelected(item, getApplicationContext(), this);
		}
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		JapaneseAndroidLearnHelperApplication.getInstance().setContentViewAndTheme(this, R.layout.word_test_sm2_options);
		
		JapaneseAndroidLearnHelperApplication.getInstance().logScreen(this, getString(R.string.logs_word_test_sm2_options));

		final WordTestSM2Config wordTestSM2Config = JapaneseAndroidLearnHelperApplication.getInstance().getConfigManager(this).getWordTestSM2Config();
		
		// get max new number
		final EditText maxNewWordsNumberEditText = (EditText)findViewById(R.id.word_test_sm2_options_max_new_words_edit_text);
		
		maxNewWordsNumberEditText.setText(String.valueOf(wordTestSM2Config.getMaxNewWords()));
		
		// show kanji check box
		final CheckBox showKanjiCheckBox = (CheckBox)findViewById(R.id.word_test_sm2_options_show_kanji);
		
		showKanjiCheckBox.setChecked(wordTestSM2Config.getShowKanji());

		// show kana check box
		final CheckBox showKanaCheckBox = (CheckBox)findViewById(R.id.word_test_sm2_options_show_kana);
		
		showKanaCheckBox.setChecked(wordTestSM2Config.getShowKana());
		
		// show translate check box
		final CheckBox showTranslateCheckBox = (CheckBox)findViewById(R.id.word_test_sm2_options_show_translate);
		
		showTranslateCheckBox.setChecked(wordTestSM2Config.getShowTranslate());
		
		// show additional info check box
		final CheckBox showAdditionalInfoCheckBox = (CheckBox)findViewById(R.id.word_test_sm2_options_show_additional_info);
		
		showAdditionalInfoCheckBox.setChecked(wordTestSM2Config.getShowAdditionalInfo());
		
		// test mode
		final RadioButton testModeInputRadioButton = (RadioButton)findViewById(R.id.word_test_sm2_options_test_mode_radiogroup_input);
		final RadioButton testModeChooseRadioButton = (RadioButton)findViewById(R.id.word_test_sm2_options_test_mode_radiogroup_choose);
		
		WordTestSM2Mode wordTestSM2Mode = wordTestSM2Config.getWordTestSM2Mode();
		
		if (wordTestSM2Mode == WordTestSM2Mode.INPUT) {
			testModeInputRadioButton.setChecked(true);
			
			showKanaCheckBox.setEnabled(false);
			showKanaCheckBox.setChecked(false);
			
		} else if (wordTestSM2Mode == WordTestSM2Mode.CHOOSE) {
			testModeChooseRadioButton.setChecked(true);
						
		} else {
			throw new RuntimeException("WordTestSM2Mode wordTestSM2Mode: " + wordTestSM2Mode);
		}	
		
		// actions
		
		testModeInputRadioButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				showKanaCheckBox.setEnabled(false);
				showKanaCheckBox.setChecked(false);
			}
		});

		testModeChooseRadioButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				showKanaCheckBox.setEnabled(true);
			}
		});
		
		// start button
		final Button startButton = (Button)findViewById(R.id.word_test_sm2_options_start);
		
		// start action		
		startButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				
				// max new words number
				String maxNewWordsNumberString = maxNewWordsNumberEditText.getText().toString();
				
				boolean maxNewWordsNumberError = false;
				
				int maxNewWordsNumber = -1;
				
				if (maxNewWordsNumberString == null) {
					maxNewWordsNumberError = true;
				} else {
					
					try {
						maxNewWordsNumber = Integer.parseInt(maxNewWordsNumberString);
					} catch (NumberFormatException e) {
						maxNewWordsNumberError = true;
					}
				}
				
				if (maxNewWordsNumberError == false && maxNewWordsNumber < 0) {
					maxNewWordsNumberError = true;
				}
				
				if (maxNewWordsNumberError == true) {
					
					Toast toast = Toast.makeText(WordTestSM2Options.this, getString(R.string.word_test_sm2_options_max_new_words_number_invalid), Toast.LENGTH_SHORT);

					toast.show();

					return;					
				}
				
				wordTestSM2Config.setMaxNewWords(maxNewWordsNumber);
				
				// test mode
				WordTestSM2Mode chosenWordTestSM2Mode = null;
				
				if (testModeInputRadioButton.isChecked() == true) {
					chosenWordTestSM2Mode = WordTestSM2Mode.INPUT;
				} else if (testModeChooseRadioButton.isChecked() == true) {
					chosenWordTestSM2Mode = WordTestSM2Mode.CHOOSE;
				} else {
					throw new RuntimeException("WordTestSM2Mode wordTestSM2Mode");
				}
				
				wordTestSM2Config.setWordTestSM2Mode(chosenWordTestSM2Mode);
								
				// show kanji
				boolean showKanji = showKanjiCheckBox.isChecked();
								
				wordTestSM2Config.setShowKanji(showKanji);
				
				// show kana
				boolean showKana = showKanaCheckBox.isChecked();
				
				wordTestSM2Config.setShowKana(showKana);
				
				// show translate
				boolean showTranslate = showTranslateCheckBox.isChecked();
				
				wordTestSM2Config.setShowTranslate(showTranslate);
				
				// show additional info
				boolean showAdditionalInfo = showAdditionalInfoCheckBox.isChecked();
				
				wordTestSM2Config.setAdditionalInfoTranslate(showAdditionalInfo);
				
				if (chosenWordTestSM2Mode == WordTestSM2Mode.INPUT && showKanji == false && showTranslate == false) {
					
					Toast toast = Toast.makeText(WordTestSM2Options.this, getString(R.string.word_test_sm2_options_no_kanji_translate), Toast.LENGTH_SHORT);

					toast.show();
					
					return;
				}

				if (chosenWordTestSM2Mode == WordTestSM2Mode.CHOOSE && showKanji == false && showKana == false && showTranslate == false) {
					
					Toast toast = Toast.makeText(WordTestSM2Options.this, getString(R.string.word_test_sm2_options_no_kanji_kana_translate), Toast.LENGTH_SHORT);

					toast.show();
					
					return;
				}
				
				if (chosenWordTestSM2Mode == WordTestSM2Mode.CHOOSE && showKanji == true && showKana == true && showTranslate == true) {
					
					Toast toast = Toast.makeText(WordTestSM2Options.this, getString(R.string.word_test_sm2_options_all_kanji_kana_translate), Toast.LENGTH_SHORT);

					toast.show();
					
					return;
				}
				
				// prepare test
				final ProgressDialog progressDialog = new ProgressDialog(WordTestSM2Options.this);
				
				progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				
				progressDialog.setTitle(getString(R.string.word_test_sm2_options_prepare1));
				progressDialog.setMessage(getString(R.string.word_test_sm2_options_prepare2));
								
				progressDialog.setProgress(0);
				progressDialog.setMax(1);

				progressDialog.show();

				class PrepareAsyncTaskResult {

					private DictionaryException dictionaryException;

					public PrepareAsyncTaskResult() {
					}

					public PrepareAsyncTaskResult(DictionaryException dictionaryException) {
						this.dictionaryException = dictionaryException;
					}
				}

				class PrepareAsyncTask extends AsyncTask<Void, Void, PrepareAsyncTaskResult> {

					@Override
					protected PrepareAsyncTaskResult doInBackground(Void... arg) {
						
						int versionCode = 0;

						try {
							PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);

							versionCode = packageInfo.versionCode;

						} catch (NameNotFoundException e) {        	
						}

						DictionaryManagerCommon dictionaryManager = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(WordTestSM2Options.this);
						
						WordTestSM2Manager wordTestSM2Manager = dictionaryManager.getWordTestSM2Manager();
						
						Integer dbVersion = wordTestSM2Manager.getVersion();

						if (dbVersion == null || dbVersion.intValue() != versionCode) { // update db
							
							CsvReader wordPowerInputStreamCsvReader = null;
							
							int currentProgressNo = 0;
							
							try {
								
								int transactionCounter = 0;
																
								wordTestSM2Manager.beginTransaction();
								
								int dictionaryEntriesSize = dictionaryManager.getDictionaryEntriesSize();
								
								progressDialog.setMax(dictionaryEntriesSize);
								
								// pobierz plik z mocami
								WordPowerList wordPowerList = dictionaryManager.getWordPowerList();

								Iterator<Map.Entry<Integer, List<Integer>>> wordPowerListEntryIterator = wordPowerList.getWordPowerMap().entrySet().iterator();

								while (wordPowerListEntryIterator.hasNext() == true) {

									Map.Entry<Integer, List<Integer>> entrySet = wordPowerListEntryIterator.next();

									int power = entrySet.getKey();

									List<Integer> dictionaryEntryListForPower = entrySet.getValue();

									for (Integer currentDictionaryEntryIdx : dictionaryEntryListForPower) {

										// sprawdzanie, czy taki rekord istnieje
										boolean dictionaryEntryExistsInWordStat = wordTestSM2Manager.isDictionaryEntryExistsInWordStat(currentDictionaryEntryIdx);
										
										if (dictionaryEntryExistsInWordStat == false) { // dodawanie nowego
																					
											wordTestSM2Manager.insertDictionaryEntry(currentDictionaryEntryIdx, power);
											
										} else { // uaktualnienie mocy
																					
											wordTestSM2Manager.updateDictionaryEntry(currentDictionaryEntryIdx, power);
										}
										
										progressDialog.setProgress(currentProgressNo);

										currentProgressNo++;
										transactionCounter++;
										
										if (transactionCounter > 2000) {
											
											transactionCounter = 0;
											
											wordTestSM2Manager.commitTransaction();
											
											wordTestSM2Manager.endTransaction();
											wordTestSM2Manager.beginTransaction();
										}										
									}									
								}
								
								wordTestSM2Manager.setVersion(versionCode);
																
								wordTestSM2Manager.commitTransaction();
								
							} catch (DictionaryException e) {
								return new PrepareAsyncTaskResult(new DictionaryException(e));
								
							} finally {
								wordTestSM2Manager.endTransaction();
								
								if (wordPowerInputStreamCsvReader != null) {
									wordPowerInputStreamCsvReader.close();
								}
							}							
						}

						return new PrepareAsyncTaskResult();
					}

					@Override
					protected void onPostExecute(PrepareAsyncTaskResult result) {

						super.onPostExecute(result);

						if (progressDialog != null && progressDialog.isShowing()) {
							progressDialog.dismiss();
						}

						if (result.dictionaryException != null) {

							Toast.makeText(WordTestSM2Options.this, getString(R.string.dictionary_exception_common_error_message, result.dictionaryException.getMessage()), Toast.LENGTH_LONG).show();

							return;
						}
						
						finish();
						
						Intent intent = new Intent(getApplicationContext(), WordTestSM2.class);

						startActivity(intent);						
					}
				};
				
				new PrepareAsyncTask().execute();				
			}
		});

		/*
		// report problem button
		Button reportProblemButton = (Button)findViewById(R.id.word_test_sm2_options_report_problem_button);

		reportProblemButton.setOnClickListener(new OnClickListener() {

			public void onClick(View view) {

				StringBuffer detailsSb = new StringBuffer();
				
				TextView optionsMaxNewWords = (TextView)findViewById(R.id.word_test_sm2_options_max_new_words);
				
				TextView optionsTestMode = (TextView)findViewById(R.id.word_test_sm2_options_test_mode);
				
				TextView optionsShow = (TextView)findViewById(R.id.word_test_sm2_options_show);

				detailsSb.append("*** " + optionsMaxNewWords.getText() + " ***\n\n");
				detailsSb.append(maxNewWordsNumberEditText.getText().toString()).append("\n\n");
				
				detailsSb.append("*** " + optionsTestMode.getText() + " ***\n\n");
				detailsSb.append(testModeInputRadioButton.isChecked() + " - " + testModeInputRadioButton.getText()).append("\n\n");
				detailsSb.append(testModeChooseRadioButton.isChecked() + " - " + testModeChooseRadioButton.getText()).append("\n\n");
				
				detailsSb.append("*** " + optionsShow.getText() + " ***\n\n");
				detailsSb.append(showKanjiCheckBox.isChecked() + " - " + showKanjiCheckBox.getText()).append("\n\n");
				detailsSb.append(showKanaCheckBox.isChecked() + " - " + showKanaCheckBox.getText()).append("\n\n");
				detailsSb.append(showTranslateCheckBox.isChecked() + " - " + showTranslateCheckBox.getText()).append("\n\n");
				detailsSb.append(showAdditionalInfoCheckBox.isChecked() + " - " + showAdditionalInfoCheckBox.getText()).append("\n\n");
				
				String chooseEmailClientTitle = getString(R.string.choose_email_client);

				String mailSubject = getString(R.string.word_test_sm2_options_report_problem_email_subject);

				String mailBody = getString(R.string.word_test_sm2_options_report_problem_email_body,
						detailsSb.toString());

				String versionName = "";
				int versionCode = 0;

				try {
					PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);

					versionName = packageInfo.versionName;
					versionCode = packageInfo.versionCode;

				} catch (NameNotFoundException e) {        	
				}

				Intent reportProblemIntent = ReportProblem.createReportProblemIntent(mailSubject, mailBody.toString(), versionName, versionCode); 

				startActivity(Intent.createChooser(reportProblemIntent, chooseEmailClientTitle));
			}
		});
		*/
		
		/*
		// show alert
		AlertDialog alertDialog = new AlertDialog.Builder(WordTestSM2Options.this).create();
		
		alertDialog.setMessage(getString(R.string.word_test_sm2_options_alert_into));
		
		alertDialog.setCancelable(false);
		alertDialog.setButton(getString(R.string.ok), new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				// noop
			}
		});
		
		alertDialog.show();
		*/
	}	
} public class TransitiveIntransitivePairsTable extends Activity {
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		MenuShorterHelper.onCreateOptionsMenu(menu);
		
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		return MenuShorterHelper.onOptionsItemSelected(item, getApplicationContext(), this);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);

		JapaneseAndroidLearnHelperApplication.getInstance().setContentViewAndTheme(this, R.layout.transitive_intransitive_pairs_table);
		
		JapaneseAndroidLearnHelperApplication.getInstance().logScreen(this, getString(R.string.logs_transitive_intransitive_pairs_table));
		
		DictionaryEntry transitiveVerb = (DictionaryEntry)getIntent().getSerializableExtra("transitive_verb");
		DictionaryEntry intransitiveVerb = (DictionaryEntry)getIntent().getSerializableExtra("intransitive_verb");

		final LinearLayout mainLayout = (LinearLayout)findViewById(R.id.transitive_intransitive_pairs_table_main_layout);
		
		final List<IScreenItem> report = new ArrayList<IScreenItem>();
		
		if (transitiveVerb == null || intransitiveVerb == null) {
			
			// generate index
			try {
				generateIndex(report);

			} catch (DictionaryException e) {

				Toast.makeText(this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();
			}
			
		} else {
			// generate pairs report body
			generatePairsReportBody(report, transitiveVerb, intransitiveVerb);
		}
		
		// fill mail layout
		fillMainLayout(report, mainLayout);

		/*
		// report problem
		Button reportProblemButton = (Button)findViewById(R.id.transitive_intransitive_pairs_table_report_problem_button);
		
		reportProblemButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View view) {
				
				StringBuffer reportSb = new StringBuffer();
				
				for (IScreenItem currentReportScreenItem : report) {
					reportSb.append(currentReportScreenItem.toString()).append("\n\n");
				}
				
				String chooseEmailClientTitle = getString(R.string.choose_email_client);
				
				String mailSubject = getString(R.string.transitive_intransitive_pairs_table_report_problem_email_subject);
				
				String mailBody = getString(R.string.transitive_intransitive_pairs_table_report_problem_email_body,
						reportSb.toString());				
				
		        String versionName = "";
		        int versionCode = 0;
		        
		        try {
		        	PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
		        	
		            versionName = packageInfo.versionName;
		            versionCode = packageInfo.versionCode;

		        } catch (NameNotFoundException e) {        	
		        }
				
				Intent reportProblemIntent = ReportProblem.createReportProblemIntent(mailSubject, mailBody.toString(), versionName, versionCode); 
				
				startActivity(Intent.createChooser(reportProblemIntent, chooseEmailClientTitle));
			}
		});
		*/
	}
	
	private void generateIndex(List<IScreenItem> report) throws DictionaryException {
		
		// add index
		int indexPos = 0;
		
		report.add(indexPos, new TitleItem(getString(R.string.transitive_intransitive_pairs_table_index), 0));
		indexPos++;
		
		report.add(indexPos, new StringValue(getString(R.string.transitive_intransitive_pairs_table_index_go), 12.0f, 1));
		indexPos++;
		
		report.add(indexPos, new StringValue("", 6.0f, 2));
		indexPos++;
		
		// dictionary manager
		DictionaryManagerCommon dictionaryManager = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(this);
		
		List<TransitiveIntransitivePairWithDictionaryEntry> transitiveIntransitivePairsList = dictionaryManager.getTransitiveIntransitivePairsList();

		for (TransitiveIntransitivePairWithDictionaryEntry transitiveIntransitivePair : transitiveIntransitivePairsList) {

			final DictionaryEntry transitivityDictionaryEntry = transitiveIntransitivePair.getTransitiveDictionaryEntry();
			final DictionaryEntry intransitivityDictionaryEntry = transitiveIntransitivePair.getIntransitiveDictionaryEntry();

			// title			
			StringValue titleStringValue = new StringValue(transitivityDictionaryEntry.getKanji() + " [" + transitivityDictionaryEntry.getRomaji() + "] - " 
					+ intransitivityDictionaryEntry.getKanji() + " [" + intransitivityDictionaryEntry.getRomaji() + "]", 15.0f, 2);
			
			titleStringValue.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					
					Intent intent = new Intent(getApplicationContext(), TransitiveIntransitivePairsTable.class);
					
					intent.putExtra("transitive_verb", transitivityDictionaryEntry);
					intent.putExtra("intransitive_verb", intransitivityDictionaryEntry);
					
					startActivity(intent);
				}
			});
			
			report.add(indexPos, titleStringValue);
			
			indexPos++;
		}
		
		report.add(indexPos, new StringValue("", 12.0f, 2));		
	}

	private void generatePairsReportBody(List<IScreenItem> report, DictionaryEntry transitivityDictionaryEntry, DictionaryEntry intransitivityDictionaryEntry) {
				
		// dictionary manager
		DictionaryManagerCommon dictionaryManager = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(this);
		
		// title
		report.add(new TitleItem(getString(R.string.transitive_intransitive_pairs_table_title), 0));

		// title 2
		TitleItem titleItem = new TitleItem(transitivityDictionaryEntry.getKanji() + " [" + transitivityDictionaryEntry.getRomaji() + "] - " 
				+ intransitivityDictionaryEntry.getKanji() + " [" + intransitivityDictionaryEntry.getRomaji() + "]", 1);
					
		report.add(titleItem);
		
		// transitive verb
		generateVerbBody(report, transitivityDictionaryEntry, getString(R.string.transitive_intransitive_pairs_table_transitive_verb));
		
		// intransitve verb
		generateVerbBody(report, intransitivityDictionaryEntry, getString(R.string.transitive_intransitive_pairs_table_intransitive_verb));
					
		// spacer
		report.add(new StringValue("", 8.0f, 1));
		
	}
	
	private void generateVerbBody(List<IScreenItem> report, final DictionaryEntry dictionaryEntry, String title) {
				
		OnClickListener goToVerbDictionaryEntryDetails = 
				new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						Intent intent = new Intent(getApplicationContext(), WordDictionaryDetails.class);
						
						intent.putExtra("item", dictionaryEntry);
						
						startActivity(intent);
					}
				};
		
		// spacer
		report.add(new StringValue("", 1.5f, 1));
				
		TitleItem verbTitle = new TitleItem(title, 2);
		verbTitle.setOnClickListener(goToVerbDictionaryEntryDetails);
		
		report.add(verbTitle);
		
		// spacer
		report.add(new StringValue("", 0.5f, 1));
		
		TableLayout tableLayout = new TableLayout(TableLayout.LayoutParam.WrapContent_WrapContent, true, true);
		
		if (dictionaryEntry.isKanjiExists() == true) {
			
			// kanji
			addRowValue(tableLayout, getString(R.string.transitive_intransitive_pairs_table_kanji), dictionaryEntry.getKanji(), goToVerbDictionaryEntryDetails);
		}
		
		// kana
		addRowValue(tableLayout, getString(R.string.transitive_intransitive_pairs_table_kana), dictionaryEntry.getKana(), goToVerbDictionaryEntryDetails);
		
		// romaji
		addRowValue(tableLayout, getString(R.string.transitive_intransitive_pairs_table_romaji), dictionaryEntry.getRomaji(), goToVerbDictionaryEntryDetails);
		
		// translate
		addRowValue(tableLayout, getString(R.string.transitive_intransitive_pairs_table_translate), listStringToString(dictionaryEntry.getTranslates()), goToVerbDictionaryEntryDetails);
		
		report.add(tableLayout);
	}
	
	private void addRowValue(TableLayout tableLayout, String title, String value, OnClickListener goToVerbDictionaryEntryDetails) {
		
		TableRow tableRow = new TableRow();
		
		StringValue titleStringValue = new StringValue(title, 14.0f, 0);
		
		titleStringValue.setMarginTop(0);
		titleStringValue.setMarginLeft(5);
		titleStringValue.setMarginRight(5);
		titleStringValue.setMarginBottom(0);

		titleStringValue.setBackgroundColor(JapaneseAndroidLearnHelperApplication.getInstance().getThemeType().getTitleItemBackgroundColorAsColor());
		
		titleStringValue.setOnClickListener(goToVerbDictionaryEntryDetails);
		
		StringValue valueStringValue = new StringValue(value, 14.0f, 0);
		
		valueStringValue.setOnClickListener(goToVerbDictionaryEntryDetails);
		
		tableRow.addScreenItem(titleStringValue);
		tableRow.addScreenItem(valueStringValue);
		
		tableLayout.addTableRow(tableRow);
	}
	
	private String listStringToString(List<String> listString) {
		
		StringBuffer sb = new StringBuffer();
		
		for (int idx = 0; idx < listString.size(); ++idx) {
			
			sb.append(listString.get(idx));
			
			if (idx != listString.size() - 1) {
				
				sb.append("\n");				
			}
		}
		
		return sb.toString();
	}

	private void fillMainLayout(List<IScreenItem> generatedDetails, LinearLayout mainLayout) {

		for (IScreenItem currentDetailsReportItem : generatedDetails) {
			currentDetailsReportItem.generate(this, getResources(), mainLayout);
		}
	}
} public class UserGroupActivity extends Activity {

    private ListView userGroupListView;

    private UserGroupListItemAdapter userGroupListAdapter;

    private List<UserGroupListItem> userGroupList;

    //

    private DictionaryEntry dictionaryEntryToAdd = null;

    private KanjiEntry kanjiEntryToAdd = null;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        MenuShorterHelper.onCreateOptionsMenu(menu);

        menu.add(Menu.NONE, R.id.user_group_menu_create_new_group, Menu.NONE, R.string.user_group_menu_create_new_group);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);

        int itemId = item.getItemId();

        if (itemId == R.id.user_group_menu_create_new_group) { // tworzenie nowej grupy

            createOrUpdateUserGroup(null);

            return true;

        } else {
            return MenuShorterHelper.onOptionsItemSelected(item, getApplicationContext(), this);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle bundle) {

        super.onSaveInstanceState(bundle);
    }

    @Override
    protected void onRestoreInstanceState(Bundle bundle) {

        super.onRestoreInstanceState(bundle);
    }

    @Override
    public void onCreate(Bundle bundle) {

        super.onCreate(bundle);

        JapaneseAndroidLearnHelperApplication.getInstance().setContentViewAndTheme(this, R.layout.user_group);

        JapaneseAndroidLearnHelperApplication.getInstance().logScreen(this, getString(R.string.logs_user_group));

        //

        createUserGroupListView();

        //

        loadUserGroups();

        //

        checkItemToAdd();

        //

        // createReportProblemButton();
    }

    @Override
    public void onBackPressed() {

        final Intent mIntent = new Intent();

        setResult(RESULT_OK, mIntent);

        finish();
    }

    private void createUserGroupListView() {

        userGroupListView = (ListView)findViewById(R.id.user_group_list);

        userGroupList = new ArrayList<>();
        userGroupListAdapter = new UserGroupListItemAdapter(this, userGroupList);

        userGroupListView.setAdapter(userGroupListAdapter);

        userGroupListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                final UserGroupListItem userGroupListItem = (UserGroupListItem)userGroupListAdapter.getItem(position);

                UserGroupListItem.ItemType itemType = userGroupListItem.getItemType();

                // tworzenie menu podrecznego
                PopupMenu popupMenu = new PopupMenu(UserGroupActivity.this, view);

                if (dictionaryEntryToAdd != null || kanjiEntryToAdd != null) {
                    popupMenu.getMenu().add(Menu.NONE, R.id.user_group_popup_add_to_this_group, Menu.NONE, R.string.user_group_popup_add_to_this_group);
                }

                popupMenu.getMenu().add(Menu.NONE, R.id.user_group_popup_open_group, Menu.NONE, R.string.user_group_popup_open_group);

                if (itemType == UserGroupListItem.ItemType.USER_GROUP) {
                    popupMenu.getMenu().add(Menu.NONE, R.id.user_group_popup_change_group_name, Menu.NONE, R.string.user_group_popup_change_group_name);
                    popupMenu.getMenu().add(Menu.NONE, R.id.user_group_popup_delete_group, Menu.NONE, R.string.user_group_popup_delete_group);
                }

                //

                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

                    @Override
                    public boolean onMenuItemClick(MenuItem item) {

                        int itemId = item.getItemId();

                        if (itemId == R.id.user_group_popup_add_to_this_group) { // dodanie elementu do grupy

                            UserGroupEntity userGroupEntity = userGroupListItem.getUserGroupEntity();

                            addItemIdToUserGroupEntity(userGroupEntity);

                            return true;

                        } else if (itemId == R.id.user_group_popup_open_group) { // otwarcie grupy

                            UserGroupEntity userGroupEntity = userGroupListItem.getUserGroupEntity();

                            Intent intent = new Intent(getApplicationContext(), UserGroupContentsActivity.class);

                            intent.putExtra("userGroupEntity", userGroupEntity);

                            startActivity(intent);

                            return true;

                        } else if (itemId == R.id.user_group_popup_change_group_name) { // zmiana nazwy grupy

                            UserGroupEntity userGroupEntityToUpdate = userGroupListItem.getUserGroupEntity();

                            createOrUpdateUserGroup(userGroupEntityToUpdate);

                            return true;

                        } else if (itemId == R.id.user_group_popup_delete_group) { // usuniecie nazwy grupy

                            UserGroupEntity userGroupEntityToDelete = userGroupListItem.getUserGroupEntity();

                            deleteUserGroup(userGroupEntityToDelete);

                            return true;

                        } else {
                            return false;
                        }
                    }
                });

                //

                popupMenu.show();
            }
        });
    }

    private void loadUserGroups() {

        DictionaryManagerCommon dictionaryManager = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(this);

        DataManager dataManager = dictionaryManager.getDataManager();

        userGroupList.clear();

        List<UserGroupEntity> allUserGroupsList = dataManager.getAllUserGroupList();

        for (UserGroupEntity currentUserGroupEntity : allUserGroupsList) {
            userGroupList.add(new UserGroupListItem(currentUserGroupEntity, getResources()));
        }

        userGroupListAdapter.notifyDataSetChanged();
    }

    private void createOrUpdateUserGroup(final UserGroupEntity userGroupEntityToUpdate) {

        final EditText groupNameEditText = new EditText(this);

        groupNameEditText.setInputType(InputType.TYPE_CLASS_TEXT);

        if (userGroupEntityToUpdate != null) {
            groupNameEditText.setText(userGroupEntityToUpdate.getName());
        }

        //

        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();

        alertDialog.setTitle(getString(userGroupEntityToUpdate == null ? R.string.user_group_new_group_dialog_title : R.string.user_group_update_group_dialog_title));
        alertDialog.setMessage(getString(userGroupEntityToUpdate == null ? R.string.user_group_new_group_dialog_message : R.string.user_group_update_group_dialog_message));

        alertDialog.setView(groupNameEditText);

        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.user_group_ok_button), (DialogInterface.OnClickListener)null);
        alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.user_group_cancel_button), (DialogInterface.OnClickListener)null);

        alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {

                Button okButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);

                okButton.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {

                        DictionaryManagerCommon dictionaryManager = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(UserGroupActivity.this);

                        DataManager dataManager = dictionaryManager.getDataManager();

                        //

                        String newGroupName = groupNameEditText.getText().toString();

                        if (newGroupName == null || newGroupName.length() < 1) {

                            Toast.makeText(UserGroupActivity.this,
                                    getString(R.string.user_group_new_group_name_too_short_error), Toast.LENGTH_SHORT).show();

                            return;
                        }

                        if (newGroupName.length() > 90) {
                            Toast.makeText(UserGroupActivity.this,
                                    getString(R.string.user_group_new_group_name_too_long_error), Toast.LENGTH_SHORT).show();

                            return;
                        }

                        // sprawdzamy, czy grupa o takiej nazwie juz istnieje
                        List<UserGroupEntity> findUserGroupEntityResultList = dataManager.findUserGroupEntity(null, newGroupName);

                        if (findUserGroupEntityResultList != null && findUserGroupEntityResultList.size() > 0) { // grupa o podanej nazwie juz istnieje

                            Toast.makeText(UserGroupActivity.this,
                                    getString(R.string.user_group_new_group_already_exists_error), Toast.LENGTH_SHORT).show();

                            return;
                        }

                        if (userGroupEntityToUpdate == null) { // jesli to nowa grupa, tworzymy ja

                            // nie znaleziono, tworzymy nowa grupe
                            UserGroupEntity newUserGroupEntity = new UserGroupEntity(null, UserGroupEntity.Type.USER_GROUP, newGroupName);

                            dataManager.addUserGroup(newUserGroupEntity);

                        } else { // uaktualnienie nazwy grupy

                            userGroupEntityToUpdate.setName(newGroupName);

                            dataManager.updateUserGroup(userGroupEntityToUpdate);
                        }

                        alertDialog.dismiss();

                        Toast.makeText(UserGroupActivity.this,
                                getString(userGroupEntityToUpdate == null ? R.string.user_group_new_group_created : R.string.user_group_update_group_done), Toast.LENGTH_SHORT).show();

                        // zaladowanie nowe listy grup
                        loadUserGroups();
                    }
                });

                Button cancelButton = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);

                cancelButton.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        alertDialog.dismiss();
                    }
                });
            }
        });

        if (isFinishing() == false) {
            alertDialog.show();
        }
    }

    private void checkItemToAdd() {

        Serializable itemToAdd = getIntent().getSerializableExtra("itemToAdd");

        if (itemToAdd != null) {

            TextView itemToAddValueTextView = (TextView)findViewById(R.id.user_group_item_to_add_value);
            TextView itemToAddValueLabelTextView = (TextView)findViewById(R.id.user_group_item_to_add_value_label);
            //View itemToAddTextViewLine1 = (View)findViewById(R.id.user_group_item_to_add_line1);
            View itemToAddTextViewLine2 = (View)findViewById(R.id.user_group_item_to_add_line2);

            //

            CharSequence itemToAddToCharSequence = null;

            if (itemToAdd instanceof DictionaryEntry) {
                dictionaryEntryToAdd = (DictionaryEntry)itemToAdd;

                itemToAddToCharSequence = WordKanjiDictionaryUtils.getWordFullTextWithMark(dictionaryEntryToAdd);

            } else if (itemToAdd instanceof KanjiEntry) {
                kanjiEntryToAdd = (KanjiEntry)itemToAdd;

                String itemToAddToString = WordKanjiDictionaryUtils.getKanjiFullTextWithMark(kanjiEntryToAdd);

                itemToAddToCharSequence = Html.fromHtml(itemToAddToString.replaceAll("\n", "<br/>"));

            } else {
                throw new RuntimeException("Unknown itemToAdd: " + itemToAdd);
            }

            itemToAddValueTextView.setText(itemToAddToCharSequence);

            itemToAddValueTextView.setVisibility(View.VISIBLE);
            itemToAddValueLabelTextView.setVisibility(View.VISIBLE);
            //itemToAddTextViewLine1.setVisibility(View.VISIBLE);
            itemToAddTextViewLine2.setVisibility(View.VISIBLE);
        }
    }

    public void addItemIdToUserGroupEntity(final UserGroupEntity userGroupEntity) {

        DictionaryManagerCommon dictionaryManager = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(this);

        final DataManager dataManager = dictionaryManager.getDataManager();

        //

        final Integer itemId;
        final UserGroupItemEntity.Type itemIdUserGroupItemEntityType;

        if (dictionaryEntryToAdd != null) {
            itemId = dictionaryEntryToAdd.getId();
            itemIdUserGroupItemEntityType = UserGroupItemEntity.Type.DICTIONARY_ENTRY;

        } else if (kanjiEntryToAdd != null) {
            itemId = kanjiEntryToAdd.getId();
            itemIdUserGroupItemEntityType = UserGroupItemEntity.Type.KANJI_ENTRY;

        } else {
            throw new RuntimeException("dictionaryEntryToAdd and kanjiEntryToAdd is null");
        }

        boolean itemIdAlreadyExists = dataManager.isItemIdExistsInUserGroup(userGroupEntity, itemIdUserGroupItemEntityType, itemId);

        if (itemIdAlreadyExists == true) {

            Toast.makeText(UserGroupActivity.this,
                    getString(R.string.user_group_item_to_add_user_group_entity_already_exists), Toast.LENGTH_SHORT).show();

            return;
        }

        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();

        alertDialog.setTitle(getString(R.string.user_group_item_to_add_user_group_entity_title));
        alertDialog.setMessage(getString(R.string.user_group_item_to_add_user_group_entity_message,
                userGroupEntity.getType() == UserGroupEntity.Type.USER_GROUP ? userGroupEntity.getName() :
                getString(R.string.user_group_star_group)));

        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.user_group_ok_button), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                // dodanie do grupy
                dataManager.addItemIdToUserGroup(userGroupEntity, itemIdUserGroupItemEntityType, itemId);

                // komunikat
                Toast.makeText(UserGroupActivity.this,
                        getString(R.string.user_group_item_to_add_user_group_entity_toast, userGroupEntity.getType() == UserGroupEntity.Type.USER_GROUP ? userGroupEntity.getName() :
                                getString(R.string.user_group_star_group)), Toast.LENGTH_SHORT).show();

                //

                /*
                dictionaryEntryToAdd = null;
                kanjiEntryToAdd = null;

                //

                TextView itemToAddValueTextView = (TextView) findViewById(R.id.user_group_item_to_add_value);
                TextView itemToAddValueLabelTextView = (TextView) findViewById(R.id.user_group_item_to_add_value_label);
                View itemToAddTextViewLine1 = (View) findViewById(R.id.user_group_item_to_add_line1);
                View itemToAddTextViewLine2 = (View) findViewById(R.id.user_group_item_to_add_line2);

                itemToAddValueTextView.setVisibility(View.GONE);
                itemToAddValueLabelTextView.setVisibility(View.GONE);
                itemToAddTextViewLine1.setVisibility(View.GONE);
                itemToAddTextViewLine2.setVisibility(View.GONE);
                */
            }
        });

        alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.user_group_cancel_button), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();

            }
        });

        if (isFinishing() == false) {
            alertDialog.show();
        }
    }

    private void deleteUserGroup(final UserGroupEntity userGroupEntity) {

        DictionaryManagerCommon dictionaryManager = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(this);

        final DataManager dataManager = dictionaryManager.getDataManager();

        //

        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();

        alertDialog.setTitle(getString(R.string.user_group_delete_user_group_entity_title));
        alertDialog.setMessage(getString(R.string.user_group_delete_user_group_entity_message, userGroupEntity.getName()));

        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.user_group_ok_button), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                // usuniecie grupy
                dataManager.deleteUserGroup(userGroupEntity);

                // komunikat
                Toast.makeText(UserGroupActivity.this,
                        getString(R.string.user_group_delete_user_group_entity_toast, userGroupEntity.getName()), Toast.LENGTH_SHORT).show();

                // zaladowanie nowe listy grup
                loadUserGroups();
            }
        });

        alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.user_group_cancel_button), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();

            }
        });

        if (isFinishing() == false) {
            alertDialog.show();
        }
    }

    /*
    private void createReportProblemButton() {

        Button reportProblemButton = (Button)findViewById(R.id.user_group_report_problem_button);

        reportProblemButton.setOnClickListener(new OnClickListener() {

            public void onClick(View view) {

                StringBuffer userGroupListText = new StringBuffer();

                for (int userGroupListAdapterIdx = 0; userGroupListAdapterIdx < userGroupListAdapter.size(); ++userGroupListAdapterIdx) {
                    userGroupListText.append(((UserGroupListItem)userGroupListAdapter.getItem(userGroupListAdapterIdx)).getText().toString()).append("\n--\n");
                }

                String chooseEmailClientTitle = getString(R.string.choose_email_client);

                String mailSubject = getString(R.string.user_group_report_problem_email_subject);

                String mailBody = getString(R.string.user_group_report_problem_email_body, userGroupListText.toString());

                String versionName = "";
                int versionCode = 0;

                try {
                    PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);

                    versionName = packageInfo.versionName;
                    versionCode = packageInfo.versionCode;

                } catch (PackageManager.NameNotFoundException e) {
                }

                Intent reportProblemIntent = ReportProblem.createReportProblemIntent(mailSubject, mailBody.toString(), versionName, versionCode);

                startActivity(Intent.createChooser(reportProblemIntent, chooseEmailClientTitle));
            }
        });
    }
    */
}
import java.util.ArrayList;
import java.util.List;
import pl.idedyk.android.japaneselearnhelper.config.ConfigManager;
import pl.idedyk.android.japaneselearnhelper.counters.CountersActivity;
import pl.idedyk.android.japaneselearnhelper.dictionaryhear.DictionaryHearOptions;
import pl.idedyk.android.japaneselearnhelper.dictionaryscreen.WordDictionaryTab;
import pl.idedyk.android.japaneselearnhelper.info.InfoActivity;
import pl.idedyk.android.japaneselearnhelper.kana.Kana;
import pl.idedyk.android.japaneselearnhelper.kana.KanaTestOptions;
import pl.idedyk.android.japaneselearnhelper.kanji.KanjiSearch;
import pl.idedyk.android.japaneselearnhelper.kanji.hkr.KanjiRecognizeActivity;
import pl.idedyk.android.japaneselearnhelper.kanji.hkr.KanjiTestOptionsActivity;
import pl.idedyk.android.japaneselearnhelper.keigo.KeigoTable;
import pl.idedyk.android.japaneselearnhelper.problem.ReportProblem;
import pl.idedyk.android.japaneselearnhelper.serverclient.ServerClient;
import pl.idedyk.android.japaneselearnhelper.splash.Splash;
import pl.idedyk.android.japaneselearnhelper.test.WordTestOptions;
import pl.idedyk.android.japaneselearnhelper.testsm2.WordTestSM2Options;
import pl.idedyk.android.japaneselearnhelper.transitiveintransitive.TransitiveIntransitivePairsTable;
import pl.idedyk.android.japaneselearnhelper.usergroup.UserGroupActivity;
import pl.idedyk.japanese.dictionary.api.android.queue.event.StatEndAppEvent;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
package pl.idedyk.android.japaneselearnhelper;




public class JapaneseAndroidLearnHelperMainActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);

		JapaneseAndroidLearnHelperApplication.getInstance().setContentViewAndTheme(this, R.layout.main);
		
		JapaneseAndroidLearnHelperApplication.getInstance().logScreen(this, getString(R.string.logs_main_menu));

		// create menu
		createMenuList();

		// init menu actions
		initMenuActions();

		// check and show message for user
		checkAndShowMessageForUser();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {

		super.onBackPressed();

		JapaneseAndroidLearnHelperApplication.getInstance().addQueueEvent(this, new StatEndAppEvent(
				JapaneseAndroidLearnHelperApplication.getInstance().getConfigManager(this).getCommonConfig().getOrGenerateUniqueUserId()
		));
	}

	private void createMenuList() {
		ListView mainMenuListView = (ListView)findViewById(R.id.mainMenuList);

		List<MainMenuItem> mainMenuListItems = new ArrayList<MainMenuItem>();

		mainMenuListItems.add(new MainMenuItem(
				getString(R.string.main_menu_kana_kanji),
				getString(R.string.main_menu_kana_text)));

		mainMenuListItems.add(new MainMenuItem(
				getString(R.string.main_menu_kana_test_kanji),
				getString(R.string.main_menu_kana_test_text)));    	

		mainMenuListItems.add(new MainMenuItem(
				getString(R.string.main_menu_counters_kanji),
				getString(R.string.main_menu_counters_text)));    	

		mainMenuListItems.add(new MainMenuItem(
				getString(R.string.main_menu_keigo_table_kanji),
				getString(R.string.main_menu_keigo_table_text)));

		mainMenuListItems.add(new MainMenuItem(
				getString(R.string.main_menu_transitive_intransitive_pairs_table_kanji),
				getString(R.string.main_menu_transitive_intransitive_pairs_table_text)));
		
		mainMenuListItems.add(new MainMenuItem(
				getString(R.string.main_menu_dictionary_kanji),
				getString(R.string.main_menu_dictionary_text)));

		if (android.os.Build.VERSION.SDK_INT >= 14) { // if Android 4+
			mainMenuListItems.add(new MainMenuItem(
					getString(R.string.main_menu_dictionary_hear_kanji),
					getString(R.string.main_menu_dictionary_hear_text)));
		}
		
    	mainMenuListItems.add(new MainMenuItem(
    			getString(R.string.main_menu_word_test_kanji),
    			getString(R.string.main_menu_word_test_text)));
    	
    	mainMenuListItems.add(new MainMenuItem(
    			getString(R.string.main_menu_word_test_sm2_kanji),
    			getString(R.string.main_menu_word_test_sm2_text)));

		mainMenuListItems.add(new MainMenuItem(
				getString(R.string.main_menu_kanji_kanji),
				getString(R.string.main_menu_kanji_text)));

		/*
		mainMenuListItems.add(new MainMenuItem(
				getString(R.string.main_menu_kanji_recognizer_kanji),
				getString(R.string.main_menu_kanji_recognizer_text)));
		*/

		mainMenuListItems.add(new MainMenuItem(
				getString(R.string.main_menu_kanji_test_kanji),
				getString(R.string.main_menu_kanji_test_text)));

		mainMenuListItems.add(new MainMenuItem(
				getString(R.string.main_menu_show_user_group_kana),  15.0f,
				getString(R.string.main_menu_show_user_group_text)));

		mainMenuListItems.add(new MainMenuItem(
				getString(R.string.main_menu_black_white_switcher_kanji),
				getString(R.string.main_menu_black_white_switcher_text)));

		mainMenuListItems.add(new MainMenuItem(
				getString(R.string.main_menu_suggestion_kanji),
				getString(R.string.main_menu_suggestion_text)));

		mainMenuListItems.add(new MainMenuItem(
				getString(R.string.main_menu_information_kanji),
				getString(R.string.main_menu_information_text)));

		MainMenuListItemAdapter mainMenuListItemsAdapter = new MainMenuListItemAdapter(this, R.layout.main_menu_simplerow, mainMenuListItems);

		mainMenuListView.setAdapter(mainMenuListItemsAdapter);
	}

	private void initMenuActions() {

		final ListView mainMenuListView = (ListView)findViewById(R.id.mainMenuList);

		mainMenuListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				
				MainMenuItem mainMenuChosenItem = (MainMenuItem)mainMenuListView.getAdapter().getItem(position);
				
				String mainMenuChosenItemText = mainMenuChosenItem.getText();
				
				if (mainMenuChosenItemText.equals(getString(R.string.main_menu_kana_text)) == true) { // kana selected
					
					Intent intent = new Intent(getApplicationContext(), Kana.class);

					startActivity(intent);
				} else if (mainMenuChosenItemText.equals(getString(R.string.main_menu_kana_test_text)) == true) { // kana test selected
					
					Intent intent = new Intent(getApplicationContext(), KanaTestOptions.class);

					startActivity(intent);
					
				} else if (mainMenuChosenItemText.equals(getString(R.string.main_menu_counters_text)) == true) { // counter
					
					Intent intent = new Intent(getApplicationContext(), CountersActivity.class);

					startActivity(intent);
					
				} else if (mainMenuChosenItemText.equals(getString(R.string.main_menu_keigo_table_text)) == true) { // keigo table
					
					Intent intent = new Intent(getApplicationContext(), KeigoTable.class);

					startActivity(intent);
					
				} else if (mainMenuChosenItemText.equals(getString(R.string.main_menu_transitive_intransitive_pairs_table_text)) == true) { // transitive intransitive pairs table
					
					Intent intent = new Intent(getApplicationContext(), TransitiveIntransitivePairsTable.class);

					startActivity(intent);
					
				} else if (mainMenuChosenItemText.equals(getString(R.string.main_menu_dictionary_text)) == true) { // dictionary selected
					
					Intent intent = new Intent(getApplicationContext(), WordDictionaryTab.class);

					startActivity(intent);
					
				} else if (mainMenuChosenItemText.equals(getString(R.string.main_menu_dictionary_hear_text)) == true) { // dictionary hear

					Intent intent = new Intent(getApplicationContext(), DictionaryHearOptions.class);

					startActivity(intent);					
					
				} else if (mainMenuChosenItemText.equals(getString(R.string.main_menu_word_test_text)) == true) { // word test selected
					
					Intent intent = new Intent(getApplicationContext(), WordTestOptions.class);

					startActivity(intent);
					
				} else if (mainMenuChosenItemText.equals(getString(R.string.main_menu_word_test_sm2_text)) == true) { // word sm2 test selected

					Intent intent = new Intent(getApplicationContext(), WordTestSM2Options.class);

					startActivity(intent);					
					
				} else if (mainMenuChosenItemText.equals(getString(R.string.main_menu_kanji_text)) == true) { // kanji search
					
					Intent intent = new Intent(getApplicationContext(), KanjiSearch.class);

					startActivity(intent);
					
				/*} else if (mainMenuChosenItemText.equals(getString(R.string.main_menu_kanji_recognizer_text)) == true) { // kanji recognizer

					Intent intent = new Intent(getApplicationContext(), KanjiRecognizeActivity.class);

					startActivity(intent);					
				*/
				} else if (mainMenuChosenItemText.equals(getString(R.string.main_menu_kanji_test_text)) == true) { // kanji test

					Intent intent = new Intent(getApplicationContext(), KanjiTestOptionsActivity.class);