//
//  AppDelegate.m
//  Project
//
//  Created by Phan Quang Hoang on 8/26/13.
//  Copyright (c) 2013 Phan Quang Hoang. All rights reserved.
//
#define SavedHTTPCookiesKey @"SavedHTTPCookies"

#import "AppDelegate.h"
#import "ViewController.h"
#import "TopScreenView.h"
#import "ResearchListView.h"
#import "ListItemChange.h"
//#import "JSONKit.h"	DELETE 2016-01-14
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SSKeychain.h"
#import <Security/Security.h>
#import "ConnectionManager.h"
#import "SlashViewController.h"
#import "TestFlight.h"
#import "ContactListView.h"
#import "WebViewController.h"
#import "UIAlertView+Blocks.h"
#import "ContactSuperViewController.h"
#import "DeviceHardware.h"
#import "RegisterSchemaViewController.h"

#import "CommonPopupViewController.h"

#import "UINavigationControllerEx.h"

#define WIDTH_BUTTON_ITEM  (IS_IPHONE_6?64.0f:(SIZE_WIDTH/5))

//#define HEIGHT_BUTTON_ITEM  52.0f
#define HEIGHT_BUTTON_ITEM  49.0f

#define ORIGIN_Y_BUTTON_ITEM	0.f

@implementation AppDelegate
{
//	BOOL login;
	BOOL firstStartApp;
	NSInteger errorCode;
	NSString *errorText;
	NSString *retrieveuuid;
	NSString *newsId;
	TYPE_PUSH type;
	BOOL pushLocal;
	BOOL allHaveKey;
	BOOL isRecievePush;
	BOOL isFirstLoad;
	BOOL isLoadFooter;
	BOOL isClickedPushNews;
	BOOL isJustClickedPushNews;
	
	NSArray * _buttonArray;
	UINavigationController *_navListItem;
	
	BOOL bAlertTimeout;
}

@synthesize startApp;
@synthesize topButton;
@synthesize questionButton;
@synthesize listResearchButton;
@synthesize infoButton;
@synthesize footerView;
@synthesize token;

/*
 ⁃	App lifecycle
 ⁃	Data loading
 ⁃	Private methods
 ⁃	Button selectors
 ⁃	Notification selectors
 ⁃	Delegates
 */

#pragma mark - App lifecycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
	DBG_LOG(@"window %@", _window);
	self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

	_statusBarStyle = UIStatusBarStyleDefault;
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_8_4) {
		// iOS9 and later	ADD 2016-01-13
		[[UINavigationBar appearance] setBarTintColor:UIColorNavigation];
//		[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
		_statusBarStyle = UIStatusBarStyleDefault;
	} else
	// MODIFY 2015-06-12 systemVersion => NSFoundationVersionNumber
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
//	if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
		[[UINavigationBar appearance] setBarTintColor:UIColorNavigation];
		[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
		_statusBarStyle = UIStatusBarStyleDefault;
	} else {
		[[UINavigationBar appearance] setTintColor:UIColorNavigation];
		// Customize the title text for *all* UINavigationBars
	}
   
//    [SVProgressHUD setForegroundColor:[UIColor colorWithRed:73/255.0f green:73/255.0f blue:69/255.0f alpha:1.0f]];
//    [SVProgressHUD setBackgroundColor:[UIColor clearColor]];
	[SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
	
	//login = YES;
	[self loadCookie];
	
	_isReload = NO;
	pushLocal = NO;
	isFirstLoad = YES;
	_ignoreEmailPass = NO;	// ADD 2015-09-09
	_isShowOfflineBar = NO;	// ADD 2015-09-15
	bAlertTimeout = NO;		// ADD 2015-10-07
	_isLoginFailed = NO;	// ADD 2015-10-07
	_isShowAlert = NO;
	
	//[TestFlight takeOff:@"8677c8e8-987d-4fd5-a97a-a8915fafed27"];
	
	float systemVersion = [[UIDevice currentDevice].systemVersion floatValue];

	// バージョン情報変更 Build => Version	MODIFY 2015-12-11
//	NSString *versionString = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString*)kCFBundleVersionKey];
	NSString *versionString = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
	NSLog(@"version is %@", versionString);
	
	_userAgent = [NSString stringWithFormat:@"MachicomiIOS/%@(Apple; %@; %0.1f)",versionString, [DeviceHardware machine], systemVersion];
	//NSLog(@"IOS: === %@", _userAgent);
	
	
	// Override point for customization after application launch.
	// Let the device know we want to receive push notifications
	
	//original code

	// MODIFY 2015-06-12 systemVersion => respondsToSelector:@selector(registerUserNotificationSettings)
	if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
//	//fixed code by Vu 19/01/2015
//	if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
//	{
		UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
		[application registerUserNotificationSettings:notificationSettings];
//	}
//	else
//	{
//		[application registerForRemoteNotificationTypes:
//		 (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
	}
	// NSUserDefaults初期設定		ADD 2015-10-08
	NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
	NSDictionary *defaults = @{
							   NSUserDefaultMailTutorial: @"ON"	// メール詳細チュートリアルON
							   };
	[ud registerDefaults:defaults];
	
	// Check app is launchedone
	if ([[NSUserDefaults standardUserDefaults] objectForKey:NSUserDefaultHasLaunchedOnce]){
		// app already launched
	} else {
		[[NSUserDefaults standardUserDefaults] setBool:YES forKey:NSUserDefaultHasLaunchedOnce];
		[[NSUserDefaults standardUserDefaults] synchronize];
		// This is the first launch ever
		[UIApplication sharedApplication].applicationIconBadgeNumber = -1;
	}
	
	// MODIFY 2015-06-17 iOS7 depreated UIStatusBarStyleBlackOpaque
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_8_4) {
		// iOS9 and later	ADD 2016-01-13
//		[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
		_statusBarStyle = UIStatusBarStyleLightContent;
	} else
	if([[UIDevice currentDevice].systemVersion floatValue] >= 7.0) {
		[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
		_statusBarStyle = UIStatusBarStyleLightContent;
		//[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleBlackOpaque];
	}

	// init something value
	_keyId = @"1001";
	_hostId = @"";
	_hostId = [[NSUserDefaults standardUserDefaults] stringForKey:NSUserDefaultHostid];
	   
	// init Tabbar
	self.tabBarController = [[UITabBarController alloc] init];
	
	int positionY = 0;
	// MODIFY 2015-06-12 systemVersion => NSFoundationVersionNumber
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
//	if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
		positionY = SIZE_HEIGHT - 52;
	}else {
		positionY = SIZE_HEIGHT - 20 - 52;
	}
	
//	footerView = [[UIToolbar alloc] initWithFrame:CGRectMake(0.0f, positionY, SIZE_WIDTH, 52.0f)];
	footerView = [[UIToolbar alloc] initWithFrame:CGRectMake(0.0f, positionY + 3.f, SIZE_WIDTH, 49.f)];
	[footerView setBackgroundImage:gImageBackgroundFooter forToolbarPosition:UIToolbarPositionBottom barMetrics:UIBarMetricsDefault];
	footerView.clipsToBounds = YES;
	
	self.viewController = [[StartViewController alloc] initWithNibName:@"StartViewController" bundle:nil];
	
	startApp = [UIButton buttonWithType:UIButtonTypeCustom];
	startApp.showsTouchWhenHighlighted = YES;
	startApp.frame = CGRectMake(0.0f, 0.0f, WIDTH_BUTTON_ITEM, HEIGHT_BUTTON_ITEM);
	// MODIFY 2015-07-31
//	[startApp setImage:gImageBackgroundFooterTop forState:UIControlStateNormal];
	[startApp setImage:gImageBackgroundFooterTopOn forState:UIControlStateNormal];
	[startApp addTarget:self action:@selector(clickOnMyPage:) forControlEvents:UIControlEventTouchUpInside];
	[footerView addSubview:startApp];
	
	// Reset click time
	[[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"LastTopClicked"];
	[[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"LastResearchClicked"];
	
	// Add view to tabbar
	topScreenView = [[TopScreenView alloc] init];
	researchListView = [[ResearchListView alloc] initWithNibName:@"ResearchListView" bundle:nil];
	contentViewController = [[BaseWebViewController alloc] init];
	listItemChangeView = [[ListItemChange alloc] initWithNibName:@"ListItemChange" bundle:nil];
	
	// トップ
	UINavigationController *navTopScreen = [[UINavigationController alloc] initWithRootViewController:topScreenView];
	
	// クエスチョン
	UINavigationController *navResearch = [[UINavigationController alloc] initWithRootViewController:researchListView];
	
	// まちプレ Question view controller
	UINavigationController *navQuestionVC = [[UINavigationController alloc] initWithRootViewController:contentViewController];
	
	// その他
//	UINavigationController *navListItem = [[UINavigationController alloc] initWithRootViewController:listItemChangeView];
	_navListItem = [[UINavigationController alloc] initWithRootViewController:listItemChangeView];
	
	UINavigationController *navViewCtr = [[UINavigationController alloc] initWithRootViewController:self.viewController];
  
	
	if([[UIDevice currentDevice].systemVersion floatValue] < 6.0f) {
		
	} else {
		NSDictionary *textAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
										[UIColor whiteColor],NSForegroundColorAttributeName,
										[UIFont boldSystemFontOfSize:20.0f], NSFontAttributeName, nil];
		navViewCtr.navigationBar.titleTextAttributes = textAttributes;
		navTopScreen.navigationBar.titleTextAttributes = textAttributes;
		navResearch.navigationBar.titleTextAttributes = textAttributes;
//		navListItem.navigationBar.titleTextAttributes = textAttributes;
		_navListItem.navigationBar.titleTextAttributes = textAttributes;
	}

//	self.tabBarController.viewControllers = @[navViewCtr, navTopScreen, navQuestionVC, navResearch, navListItem];
	self.tabBarController.viewControllers = @[navViewCtr, navTopScreen, navQuestionVC, navResearch, _navListItem];

	// Top button bar item
	[self setUpTopButtonBarItem];
	
	// Question
	[self setUpQuestionButtonBarItem];
	
	// Research screen
	[self setUpResearchButtonBarItem];
	
	// User setting
	[self setUpSettingButtonBarItem];
	
	// タブバー上部区切り線		ADD 2015-07-29
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
		_footerTopLine = [[UIImageView alloc] initWithFrame:
						 CGRectMake(0, 0, SIZE_WIDTH, (1.f / [UIScreen mainScreen].scale))];
	} else {
		_footerTopLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SIZE_WIDTH, 1)];
	}
	_footerTopLine.backgroundColor = [UIColor colorWithRed:(178.f/255.f) green:(178.f/255.f) blue:(178.f/255.f) alpha:1.f];
//	_footerTopLine.backgroundColor = [UIColor redColor];
	[footerView addSubview:_footerTopLine];
	
	// Store button item into array
	_buttonArray = @[topButton,questionButton, listResearchButton, infoButton];
 
	slashView = [[SlashViewController alloc] initWithNibName:@"SlashViewController" bundle:nil];
	[slashView.view setFrame:CGRectMake(0.0f, 0.0f, SIZE_WIDTH, SIZE_HEIGHT)];
	
	
	[self.tabBarController.view addSubview:slashView.view];
//	self.tabBarController.selectedIndex = 0;
	self.window.rootViewController = self.tabBarController;
	[self.tabBarController.view addSubview:footerView];
	_backTabbar = [[NSMutableArray alloc] init];
	
	startApp.hidden = YES;
	topButton.hidden = YES;
	questionButton.hidden = YES;
	listResearchButton.hidden = YES;
	infoButton.hidden = YES;
	
	// Set pressed buton top

	[self settingLaunchApp:launchOptions];
	DBG_LOG(@"%@", self.window.rootViewController);
	DBG_LOG(@"%@", self.tabBarController.viewControllers);
	DBG_LOG(@"%@", self.tabBarController.customizableViewControllers);
	DBG_LOG(@"select %zd", self.tabBarController.selectedIndex);

	// iOS9対応	ADD 2016-01-13
	// 全てのwindow.RootViewControllerは必ず設定されていなければならない
	// SVProgressHUDで仕様されているwindow.RootViewControllerを設定
	NSArray *windows = [[UIApplication sharedApplication] windows];
	for(UIWindow *window in windows) {
		DBG_LOG(@"window: %@",window.description);
		if(window.rootViewController == nil){
			UIViewController* vc = [[UIViewController alloc]initWithNibName:nil bundle:nil];
			window.rootViewController = vc;
		}
	}
	[self.window makeKeyAndVisible];
	
	DBG_LOG(@"%f:%f", SCREEN_MIN_LENGTH, SCREEN_MAX_LENGTH);
	return YES;
}

// _userAgent GETTER	ADD 2016-01-25
- (NSString*)getUserAgentWithHostID
{
	NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
	NSMutableString *agent = [_userAgent mutableCopy];
	NSUInteger insIdx = agent.length - 2;
	if ([ud stringForKey:NSUserDefaultMailAddress].length > 0) {
		// login
		[agent insertString:[NSString stringWithFormat:@"; 1; %@", _hostId] atIndex:insIdx];
	} else {
		// not login
		[agent insertString:[NSString stringWithFormat:@"; 0; %@", _hostId] atIndex:insIdx];
	}
	return [agent copy];
}

- (void)settingLaunchApp:(NSDictionary *)launchOptions
{
	NSDictionary *notification = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
	_isLaunchedByNoti = NO;
	
	if (notification) {
		// PUSH通知からアプリ起動
		NSString *mailAdress = [[NSUserDefaults standardUserDefaults] objectForKey:NSUserDefaultMailAddress];
		if(mailAdress.length == 0) {
			[self clickOnMyPage:startApp];
		} else {
			_isLaunchedByNoti = YES;	// YES:通知からの起動
			type = [[notification objectForKey:@"type"] intValue];
			
			if (type == TYPE_PUSH_NEWS) {
				isClickedPushNews = YES;
				newsId = notification[@"newsid"];
			}
			
			
			NSDictionary *contentPush = [notification objectForKey:@"aps"];

			if (type == TYPE_PUSH_TOP) {
				// 連絡メール
				// 連絡メールバッジのカウントアップ&表示	MODIFY 2015-09-03
				[self setReadBadge:contentPush];
//				// 連絡メールのバッジカウント追加
//				NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//				NSInteger read = [[defaults objectForKey:NSUserDefaultReadCount] integerValue];
//				read += [[contentPush objectForKey:@"badge"] integerValue];
//				[defaults setInteger:read forKey:NSUserDefaultReadCount];
//				[defaults synchronize];
//				// 連絡メールのバッジ表示
//				self.readcountButon.hidden = NO;
//				[self.readcountButon setTitle:[NSString stringWithFormat:@"%ld", (long)read] forState:UIControlStateNormal];
				
			} else if(type == TYPE_PUSH_RESEARCH) {
				[self setResearchBadge:contentPush];
//				NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//				NSInteger answer = [[defaults objectForKey:NSUserDefaultAnswerCount] integerValue];
//				answer += [[contentPush objectForKey:@"badge"] integerValue];
//				[defaults setInteger:answer forKey:NSUserDefaultAnswerCount];
//				[defaults synchronize];
//				
//				self.answercountButon.hidden = NO;
//				[self.answercountButon setTitle:[NSString stringWithFormat:@"%ld", (long)answer] forState:UIControlStateNormal];
			} else if (type == TYPE_PUSH_TIMELINE) {
				// Time line
				siteId = [notification objectForKey:@"siteid"];
				topScreenView.delegate = self;
			}
			
			NSArray *allKey = [notification allKeys];
			BOOL isHaveKey = NO;
			BOOL isHaveSite = NO;
			
			for (NSString* theKey in allKey) {
				if ([theKey isEqualToString:@"rseq"] && ![[notification objectForKey:theKey] isEqualToString:@""]) {
					isHaveKey = YES;
				}
				if ([theKey isEqualToString:@"siteid"] && ![[notification objectForKey:theKey] isEqualToString:@""]) {
					isHaveSite = YES;
				}
			}
			if (isHaveKey && isHaveSite){
				if (type == TYPE_PUSH_REMIND) {
					// リマインダー	ADD 2015-11-17
					// トップ画面表示通知 TopScreenView::showMailWithScheme
					[[NSNotificationCenter defaultCenter] postNotificationName:NSNotificationSchemeToContactDetail object:notification];
				} else
				if (type == TYPE_PUSH_TOP) {
					// トップ画面表示通知 TopScreenView::recievePushTop
					[[NSNotificationCenter defaultCenter] postNotificationName:NSNotificationPushToScreen object:notification];
				}
				isHaveKey = NO;
				isHaveSite = NO;
			}
		}
	}
	
	
	BOOL iPad = [(NSString*)[UIDevice currentDevice].model hasPrefix:@"iPad"] && [[UIDevice currentDevice].systemVersion floatValue] >= 7.0;
	
	BOOL iPhone = [(NSString*)[UIDevice currentDevice].model hasPrefix:@"iPhone"] && [[UIDevice currentDevice].systemVersion floatValue] >= 7.0;
	
	if (iPad || iPhone) {
		userDisablePush = YES;
		retrieveuuid = [SSKeychain passwordForService:@"com.vcc.machicomi" account:@"user"];
		self.client_id = retrieveuuid;
		if (retrieveuuid == nil) { // if this is the first time app lunching , create key for device
			NSString *uuid  = [self createNewUUID];
			// save newly created key to Keychain
			[SSKeychain setPassword:uuid forService:@"com.vcc.machicomi" account:@"user"];
			// this is the one time process
			self.client_id = uuid;
		}
		
		NSLog(@"User disable remote notification");
		NSString *oldToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"device_token"];
		self.token = oldToken;
		
#ifdef putApliLog
		// PutApiLogin failed
		NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
		[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
		[dateFormatter setDateFormat:@"yyyy/MM/dd HH/mm/ss"];
		NSString *currentDate = [dateFormatter stringFromDate:[NSDate date]];
		NSString *successNULL;
		if(oldToken == nil) {
			successNULL = [NSString stringWithFormat:@"%@ User disable remote notification [iOS]", currentDate];
		}else {
			successNULL = [NSString stringWithFormat:@"%@ Get token SUCCESS %@ [iOS]", currentDate, oldToken];
		}
		[self putApiLog:successNULL];
#endif

		ConnectionManager *connectManager = [[ConnectionManager alloc] init];
		if ([connectManager isConnectNetwork]) {
			[self applyAPI:oldToken];
		} else {
			// OFFLINE対応	MODIFY 2015-09-04
			[slashView.view removeFromSuperview];
//			// OFFLINE MESSAGE
//			[self showAlert888];
		}
		
	} else {
		
		NSLog(@"User enable remote notification");
		userDisablePush = NO;
	}
	
	[[UIApplication sharedApplication] setApplicationIconBadgeNumber: -1];
	[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
	[[UIApplication sharedApplication] cancelAllLocalNotifications];
	
	_isFirstTimeAfterRegister = 0;
	_isFirstTimeStartAppAndCantGoBack = NO;
	_isStartSchemaRegisterAndFirstTimeApp = NO;
}

- (void)changeLayoutAfterPresentModel
{
	CGRect rect = footerView.frame;
	rect.origin.y = rect.origin.y + 20;
	footerView.frame = rect;
}

- (void)defaultOriginalWindows
{
	if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
		if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_8_4) {
			// iOS9 and later	ADD 2016-01-13
//			[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
			_statusBarStyle = UIStatusBarStyleLightContent;
		} else {
			// iOS8 and earlier
			[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
			_statusBarStyle = UIStatusBarStyleLightContent;
		}
		self.window.clipsToBounds = YES;
		self.window.frame =  CGRectMake(0, 0, self.window.frame.size.width, SIZE_HEIGHT);
		self.window.bounds = CGRectMake(0, 0, self.window.frame.size.width, SIZE_HEIGHT);
	}
}

- (void)changeOriginalWindows
{
	if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
		if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_8_4) {
			// iOS9 and later	ADD 2016-01-13
//			[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
			_statusBarStyle = UIStatusBarStyleLightContent;
		} else {
			// iOS8 and earlier
			[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
			_statusBarStyle = UIStatusBarStyleLightContent;
		}
		self.window.clipsToBounds = YES;
		self.window.frame =  CGRectMake(0, 20, self.window.frame.size.width, SIZE_HEIGHT);
		self.window.bounds = CGRectMake(0, 20, self.window.frame.size.width, SIZE_HEIGHT);
	}
}

- (void)forwardLoginView
{
	if(type == TYPE_PUSH_RESEARCH) {
		
		[self clickOnListResearchPage:listResearchButton];
		[self showMainComponent];
		[self.tabBarController setSelectedIndex:3];
		
	} else if (type == TYPE_PUSH_NEWS){
		[self clickOnQuestion:questionButton];
		[self showMainComponent];
		
		[self.tabBarController setSelectedIndex:2];
	}
	else {
		[self.tabBarController setSelectedIndex:1];
	}
}

- (void)showMainComponent
{
	self.topAppView.hidden = NO;
	self.topButton.hidden = NO;
	self.questionAppView.hidden = NO;
	self.questionButton.hidden = NO;
	self.researchAppView.hidden = NO;
	self.settingAppView.hidden = NO;
	self.listResearchButton.hidden = NO;
	self.infoButton.hidden = NO;
	[footerView setHidden:NO];
	self.tabBarController.tabBar.hidden = NO;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
	// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
	// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
	[self saveCookie];
	// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
	// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
	self.isTopInBackground = YES;
	self.viewInBackground = YES;
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
	// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
	// タイムアウトでログインに失敗していた場合は再度ログイン	ADD 2015-10-08
	if (_isLoginFailed) {
		[self clearTimeout];
		// 再度ログイン認証を行う
		[startApp sendActionsForControlEvents:UIControlEventTouchUpInside];
	}
	if([_isScreen isEqualToString:TOP_SCREEN]) {
		//reload TOP
		UINavigationController *navTopScreen = [[self.tabBarController viewControllers] objectAtIndex:1];
		TopScreenView *topViewController = (TopScreenView *)[navTopScreen.viewControllers objectAtIndex:0];
		if ([topViewController isKindOfClass:[TopScreenView class]]) {
			[topViewController reloadTopData];
		}
		
	} else if([_isScreen isEqualToString:RESEARCH_SCREEN]) {
		//reload Research
		NSLog(@"reload Research");
		UINavigationController *navResearchScreen = [[self.tabBarController viewControllers] objectAtIndex:3];
		ResearchListView *researchScreenView = (ResearchListView *)[navResearchScreen.viewControllers objectAtIndex:0];
		if ([researchScreenView isKindOfClass:[ResearchListView class]]) {
			[researchScreenView reloadTableViewDataSource];
		}
	} else if([_isScreen isEqualToString:CONTACT_LIST]){
		UINavigationController *navTopScreen = [[self.tabBarController viewControllers] objectAtIndex:1];
		NSArray *viewControllers = navTopScreen.viewControllers;
		for (UIViewController *viewController in viewControllers) {
			if([viewController isKindOfClass:[ContactListView class]]) {
				ContactListView *contactListView = (ContactListView*)viewController;
				[contactListView reloadTableViewDataSource];
				break;
			}
		}
	} else if([_isScreen isEqualToString:CONTACT_DETAIL]) {
		UINavigationController *navTopScreen = (UINavigationController *)[self.tabBarController selectedViewController];
		ContactSuperViewController *contactSuper = (ContactSuperViewController*)[navTopScreen visibleViewController];
		if ([contactSuper isKindOfClass:[ContactSuperViewController class]]) {
			[contactSuper showCurrentContactDetail];
		}
	}
	else
	{
		// WebView Type
		UINavigationController *navTopScreen = (UINavigationController *)[self.tabBarController selectedViewController];
		WebViewController *webView = (WebViewController*)[navTopScreen visibleViewController];
		if ([webView isKindOfClass:[WebViewController class]]) {
			if([webView respondsToSelector:@selector(loadWebView)]) {
				[webView reloadWebView];
			}
		}
		isLoadFooter = YES;
	}
	
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	if([defaults objectForKey:@"device_token"] == nil) {
		[[UIApplication sharedApplication] unregisterForRemoteNotifications];
		
		//original code
		
//#ifdef __IPHONE_8_0
//    UIUserNotificationSettings* notificationSettings =[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
//            [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
//#else
//    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
//             (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
//        
//#endif
		
		// MODIFY 2015-06-12 systemVersion => respondsToSelector:@selector(registerUserNotificationSettings)
		if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
//		//fixed code by Vu 19/01/2015
//		if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
//		{
			// iOS8 and later
			UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
			[[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
		} else {
			// iOS7 and earlier
			[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
			 (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
		}
	}
}


- (void)applicationDidBecomeActive:(UIApplication *)application
{
	// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
	//application.applicationIconBadgeNumber = 0;
	[[UIApplication sharedApplication] setApplicationIconBadgeNumber: -1];
	[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
	[[UIApplication sharedApplication] cancelAllLocalNotifications];
	
	// ADD 2015-12-07
	dispatch_async(dispatch_get_main_queue(), ^{
		NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
		NSInteger read = [ud integerForKey:NSUserDefaultReadCount];
		[UIApplication sharedApplication].applicationIconBadgeNumber = read;
	});

	[self loadFooter:isRecievePush];
	isRecievePush = NO;
}

- (void)applicationWillTerminate:(UIApplication *)application
{
	[self saveCookie];
	// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
	NSLog(@"Kill app");
}

#pragma mark - Data loading
/* Push token */
- (void)applyAPI:(NSString *)tokenString
{
	// Apply PushTokenAPI
	NSString *urlAsString = PushTokenAPI;
	NSLog(@"WebAPI:%@", urlAsString);
	NSURL *url = [NSURL URLWithString:urlAsString];
	ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
	[request setTimeOutSeconds:10];
	[request addRequestHeader:@"User-Agent" value:_userAgent];
	[request addPostValue:_keyId forKey:@"keyid"];
	[request addPostValue:self.client_id forKey:@"client_id"];
	[request addPostValue:tokenString forKey:@"device_token"];
	[request setValidatesSecureCertificate:YES];
	[request setDelegate:self];
	[request startAsynchronous];
}

// WebAPIログ出力(DEBUG用)
- (void)putApiLog:(NSString *)text;
{
#ifdef putApliLog
	// Apply PushTokenAPI
	NSString *urlAsString = putApliLog;
	NSLog(@"WebAPI:%@", urlAsString);
	NSURL *url = [NSURL URLWithString:urlAsString];
//    NSLog(@"client id %@", retrieveuuid);
	ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
	[request addPostValue:_hostId forKey:@"hostid"];
	[request addPostValue:text forKey:@"text"];
	[request setValidatesSecureCertificate:YES];
	[request startAsynchronous];
	[request setCompletionBlock:^{
		NSLog(@"Completed log");
	}];
	[request setFailedBlock:^{
		NSLog(@"Failed log");
	}];
#endif
}

- (void)pushChecking
{
	// Apply PushTokenAPI
	NSString *tokenStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"device_token"];
	NSString *urlAsString = putDeviceId;
	NSLog(@"WebAPI:%@", urlAsString);
	NSURL *url = [NSURL URLWithString:urlAsString];;
	ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
	[request addPostValue:_hostId forKey:@"hostid"];
	[request addPostValue:self.client_id forKey:@"client_id"];
	[request addPostValue:tokenStr forKey:@"device_token"];
	[request setValidatesSecureCertificate:YES];
	[request startAsynchronous];
	[request setCompletionBlock:^{
		NSLog(@"Completed log");
	}];
	[request setFailedBlock:^{
		NSLog(@"Failed log");
	}];

}

//- (void)dismissSplash
//{
//    [slashView dismissModalViewControllerAnimated:NO];
//}

#pragma mark Config
- (void)setUpTopButtonBarItem
{
	// TOP screen
	self.topAppView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, WIDTH_BUTTON_ITEM, HEIGHT_BUTTON_ITEM)];
	// button badge
	self.readcountButon = [self cornerBadgeButton];

//	UIEdgeInsets inset = self.readcountButon.titleEdgeInsets;
//	inset.left = -5;
//	self.readcountButon.titleEdgeInsets = inset;
	
	topButton = [UIButton buttonWithType:UIButtonTypeCustom];
	topButton.showsTouchWhenHighlighted = YES;
	// 位置調整	MODIFY 2015-07-23
//	topButton.frame = CGRectMake(0.0f, 0.0f, WIDTH_BUTTON_ITEM, HEIGHT_BUTTON_ITEM);
	topButton.frame = CGRectMake(0.0f, ORIGIN_Y_BUTTON_ITEM, WIDTH_BUTTON_ITEM, HEIGHT_BUTTON_ITEM);
	[topButton setImage:gImageButtonEmailSelected forState:UIControlStateNormal];
	[topButton addTarget:self action:@selector(clickOnTopPage:) forControlEvents:UIControlEventTouchUpInside];
	topButton.hidden = YES;
	topButton.tag = 1;
	[self.topAppView addSubview:topButton];
	[self.topAppView addSubview:self.readcountButon];
	[footerView addSubview:self.topAppView];
}

- (void)setUpResearchButtonBarItem
{
	self.researchAppView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.questionAppView.frame), 0.0f, WIDTH_BUTTON_ITEM, HEIGHT_BUTTON_ITEM)];
	self.answercountButon = [self cornerBadgeButton];
	
	listResearchButton = [UIButton buttonWithType:UIButtonTypeCustom];
	listResearchButton.showsTouchWhenHighlighted = YES;
	// 位置調整	MODIFY 2015-07-23
//	listResearchButton.frame = CGRectMake(00.0f, 0.0f, WIDTH_BUTTON_ITEM, HEIGHT_BUTTON_ITEM);
	listResearchButton.frame = CGRectMake(00.0f, ORIGIN_Y_BUTTON_ITEM, WIDTH_BUTTON_ITEM, HEIGHT_BUTTON_ITEM);
	[listResearchButton setImage:gImageButtonResearchNormal forState:UIControlStateNormal];
	[listResearchButton addTarget:self action:@selector(clickOnListResearchPage:) forControlEvents:UIControlEventTouchUpInside];
	listResearchButton.tag = 3;
	[self.researchAppView addSubview:listResearchButton];
	[self.researchAppView addSubview:self.answercountButon];
	[footerView addSubview:self.researchAppView];
}

- (void)setUpQuestionButtonBarItem
{
	self.questionAppView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.topAppView.frame), 0, WIDTH_BUTTON_ITEM, HEIGHT_BUTTON_ITEM)];
	questionButton = [UIButton buttonWithType:UIButtonTypeCustom];
	questionButton.showsTouchWhenHighlighted = YES;
	// 位置調整	MODIFY 2015-07-23
//	questionButton.frame = CGRectMake(0.0f, 0.0f, WIDTH_BUTTON_ITEM, HEIGHT_BUTTON_ITEM);
	questionButton.frame = CGRectMake(0.0f, ORIGIN_Y_BUTTON_ITEM, WIDTH_BUTTON_ITEM, HEIGHT_BUTTON_ITEM);
	[questionButton setImage:gImageButtonQuestionNormal forState:UIControlStateNormal];
	[questionButton addTarget:self action:@selector(clickOnQuestion:) forControlEvents:UIControlEventTouchUpInside];
	questionButton.tag = 2;
	
	// Badge number
	self.questionCountButon = [self cornerBadgeButton];
	
	self.questionCountButon.hidden = NO;
	
	[self.questionAppView addSubview:questionButton];
	[self.questionAppView addSubview:self.questionCountButon];
	[footerView addSubview:self.questionAppView];
}

- (void)setUpSettingButtonBarItem
{
	self.settingAppView = [[UIView alloc] initWithFrame:CGRectMake(SIZE_WIDTH - WIDTH_BUTTON_ITEM, 0.0f, WIDTH_BUTTON_ITEM, HEIGHT_BUTTON_ITEM)];
	self.infocountButton = [self cornerBadgeButton];
	
	infoButton = [UIButton buttonWithType:UIButtonTypeCustom];
	// 位置調整	MODIFY 2015-07-23
//	infoButton.frame = CGRectMake(0.0f, 0.0f, WIDTH_BUTTON_ITEM, HEIGHT_BUTTON_ITEM);
	infoButton.frame = CGRectMake(0.0f, ORIGIN_Y_BUTTON_ITEM, WIDTH_BUTTON_ITEM, HEIGHT_BUTTON_ITEM);
	infoButton.showsTouchWhenHighlighted = YES;
	[infoButton setImage:gImageButtonSettingNormal forState:UIControlStateNormal];
	[infoButton addTarget:self action:@selector(clickOnSettingUserPage:) forControlEvents:UIControlEventTouchUpInside];
	infoButton.tag = 3;
	[self.settingAppView addSubview:infoButton];
	[self.settingAppView addSubview:self.infocountButton];
	
	[footerView addSubview:self.settingAppView];
}

// Corner border button
- (UIButton*)cornerBadgeButton
{
	UIButton *button = nil;
	if (IS_IPHONE_6P) {
		// ADD 2015-07-28
		button = [[UIButton alloc] initWithFrame:CGRectMake(WIDTH_BUTTON_ITEM - 17.0f - 7.0f - 10.f, 4.0f, 17.0f, 17.0f)];
	} else {
		button = [[UIButton alloc] initWithFrame:CGRectMake(WIDTH_BUTTON_ITEM - 17.0f - 7.0f, 4.0f, 17.0f, 17.0f)];
	}
	
	[button setBackgroundColor:[UIColor colorWithRed:255/255.0f green:54/255.0f blue:0.0f alpha:1.0f]];
	[button setTitle:@"" forState:UIControlStateNormal];
	button.titleLabel.font = [UIFont systemFontOfSize:10];
	button.hidden = YES;
	
	button.layer.cornerRadius = CGRectGetHeight(button.frame)/2;
	button.layer.masksToBounds = YES;
	button.layer.borderColor = [UIColor colorWithRed:255/255.0f green:54/255.0f blue:0.0f alpha:1.0f].CGColor
	;
	button.layer.borderWidth = 1;
	
	return button;
}

#pragma mark - Private methods

/* get UUID */
- (NSString *)getUUID
{
	NSString *UUID = [[NSUserDefaults standardUserDefaults] objectForKey:@"uniqueID"];
	if (!UUID){
		CFUUIDRef theUUID = CFUUIDCreate(NULL);
		CFStringRef string = CFUUIDCreateString(NULL, theUUID);
		CFRelease(theUUID);
		UUID = [(__bridge NSString*)string stringByReplacingOccurrencesOfString:@"-"withString:@""];
		CFRelease(string);	// ADD BUG 2015-06-12 (Memory leak)
		[[NSUserDefaults standardUserDefaults] setValue:UUID forKey:@"uniqueID"];
	}
	return UUID;
}
/* Create UUID */
- (NSString *)createNewUUID
{
	CFUUIDRef theUUID = CFUUIDCreate(NULL);
	CFStringRef string = CFUUIDCreateString(NULL, theUUID);
	CFRelease(theUUID);
	
	// MODIFY BUG 2015-06-12 (Memory leak)
//	return [(__bridge NSString *)string stringByReplacingOccurrencesOfString:@"-"withString:@""];
	NSString *NewUUID = [(__bridge NSString *)string stringByReplacingOccurrencesOfString:@"-"withString:@""];
	CFRelease(string);
	return NewUUID;
}

#pragma mark - Public methods
/* Created by hamxn 1/23/15
 * Description: set top button highlight
 */
 
- (void)setTopButtonHighlight
{
	[topButton setHighlighted:NO];
	[topButton setBackgroundImage:gImageBackgroundFooterTopOn forState:UIControlStateNormal];
	[listResearchButton setBackgroundImage:gImageResearchFooter forState:UIControlStateNormal];
	[infoButton setBackgroundImage:gImageSettingFooter forState:UIControlStateNormal];
}

- (NSMutableDictionary *)getMutableDictionaryFromURL:(NSArray *)arrayParams
{
	NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
	for (int i = 0; i < arrayParams.count; i++) {
		NSString *stringParams = [arrayParams objectAtIndex:i];
		NSArray *arrayKeyAndValue = [stringParams componentsSeparatedByString:@"="];
		if (arrayKeyAndValue.count > 1) {
			[dictionary setObject:[arrayKeyAndValue objectAtIndex:1] forKey:[arrayKeyAndValue objectAtIndex:0]];
		} else if (arrayKeyAndValue.count == 1){
			[dictionary setObject:@"" forKey:[arrayKeyAndValue objectAtIndex:0]];
		}
	}
	return dictionary;
}

#pragma mark - プッシュ通知確認
// PUSH通知内容の表示確認
- (void)alertNotification:(NSString *)message
{
//	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NOTIFICATION_TITLE message:message delegate:self cancelButtonTitle:CANCEL_BUTTON otherButtonTitles:OTHER_BUTTON, nil];
//	[alert show];
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
		// iOS8 and later
		UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NOTIFICATION_TITLE message:message preferredStyle:UIAlertControllerStyleAlert];
		// addActionした順に左から右にボタンが配置されます
		[alertController addAction:[UIAlertAction actionWithTitle:CANCEL_BUTTON style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
			// ADD 2015-09-18
			UINavigationController *navigationController = [self.tabBarController.viewControllers objectAtIndex:1];
			BOOL isFindMode = NO;
			if ([navigationController.topViewController isKindOfClass:[ContactListView class]]) {
				ContactListView* vc = (ContactListView*)navigationController.topViewController;
				isFindMode = [vc isFindOrStar];
			}
			if (isFindMode==NO) {
				for (UIViewController *viewController in navigationController.viewControllers) {
					if ([viewController isKindOfClass:[TopScreenView class]]) {
						// トップ画面情報取得 - PUSH通知(連絡メール)
						TopScreenView *topViewController = (TopScreenView*)viewController;
						if ([_isScreen isEqualToString:CONTACT_LIST]
							/*||[_isScreen isEqualToString:CONTACT_DETAIL]*/) {
							// リスト更新処理
							[topViewController reloadContactListView:siteId];
						}
					}
				}
			}
		}]];
		[alertController addAction:[UIAlertAction actionWithTitle:OTHER_BUTTON style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
			[self alertEtc];
		}]];
		UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:1];
		[navigationConttoller.topViewController presentViewController:alertController animated:YES completion:nil];
	} else {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NOTIFICATION_TITLE message:message delegate:self cancelButtonTitle:CANCEL_BUTTON otherButtonTitles:OTHER_BUTTON, nil];
		[alert show];
	}
}

// 「一覧に戻る」アラート画面
- (void)popToContactList
{
//	alertStatus = 999;
//	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ALERT_TITLE message:CONTENT_MESSAGE delegate:self cancelButtonTitle:nil otherButtonTitles:CANCEL_BUTTON, nil];
//	[alert show];
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
		// iOS8 and later
		UIAlertController *alertController = [UIAlertController alertControllerWithTitle:ALERT_TITLE message:CONTENT_MESSAGE preferredStyle:UIAlertControllerStyleAlert];
		// addActionした順に左から右にボタンが配置されます
		[alertController addAction:[UIAlertAction actionWithTitle:CANCEL_BUTTON style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
			[self alert999];
		}]];
		UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:1];
		[navigationConttoller.topViewController presentViewController:alertController animated:YES completion:nil];
	} else {
		alertStatus = 999;
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ALERT_TITLE message:CONTENT_MESSAGE delegate:self cancelButtonTitle:nil otherButtonTitles:CANCEL_BUTTON, nil];
		[alert show];
	}
}

#pragma mark -
/* load cookie */
- (void)loadCookie
{
	NSData *cookiesData = [[NSUserDefaults standardUserDefaults]
						   objectForKey:SavedHTTPCookiesKey];
	if (cookiesData) {
		NSLog(@"load cookies");
		NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesData];
		for (NSHTTPCookie *cookie in cookies)
			[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
	}
	
}
/* save cookie */
- (void)saveCookie
{
	// Save the cookies to the user defaults
	NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject:
						   [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
	[[NSUserDefaults standardUserDefaults] setObject:cookiesData
											  forKey:SavedHTTPCookiesKey];
}

#pragma mark -
/* load footer */
- (void)loadFooter:(BOOL)isPush
{
	if (isPush) {
		if (allHaveKey) {
			NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
			int read_count = [[userDefault objectForKey:NSUserDefaultReadCount] intValue];
			int answer_count = [[userDefault objectForKey:NSUserDefaultAnswerCount] intValue];
			if (read_count > 0) {
				self.readcountButon.hidden = NO;
				[self.readcountButon setTitle:[NSString stringWithFormat:@"%d", read_count] forState:UIControlStateNormal];
			}
			if (answer_count > 0) {
				self.answercountButon.hidden = NO;
				[self.answercountButon setTitle:[NSString stringWithFormat:@"%d", answer_count] forState:UIControlStateNormal];
			}
			allHaveKey = NO;
		}
	} else {
		if (isFirstLoad == NO) {
			if (isLoadFooter) {
				UINavigationController *navTopScreen = [[self.tabBarController viewControllers] objectAtIndex:1];
				TopScreenView *topVC = (TopScreenView *)[navTopScreen.viewControllers objectAtIndex:0];
				[topVC getInfoFooterAPI];
				isLoadFooter = NO;
			}
		}
		isFirstLoad = NO;
	}
}

#pragma mark - Button selectors
// ログイントップ画面へ	ADD 2015-09-09
- (void)clickMyPage
{
	// ボタン押下
	_ignoreEmailPass = YES;
	[startApp sendActionsForControlEvents:UIControlEventTouchUpInside];
}
/* Login page */
- (void)clickOnMyPage:(id)sender
{
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	if ([defaults objectForKey:FLAG_REGISTER] != nil) {
		[defaults removeObjectForKey:FLAG_REGISTER];
		[defaults removeObjectForKey:FLAG_LOGIN_HOST_ID];
		
	}
	[defaults removeObjectForKey:NSUserDefaultForget];
	[defaults synchronize];
	
	[[NSNotificationCenter defaultCenter] postNotificationName:NSNotificationPostBack object:nil];
	[self.tabBarController setSelectedIndex:0];
	UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:0];
	[navigationConttoller popToRootViewControllerAnimated:NO];
}

#pragma mark メールボタン押下
/* Top page */
- (void)clickOnTopPage:(id)sender
{
	[self resetAllItems];

	// メールボタン押下以外のときも対応	DELETE 2015-11-05
//	if ([_isScreen isEqualToString:CONTACT_LIST]
//		||[_isScreen isEqualToString:CONTACT_DETAIL]) {
		UINavigationController *navigationController = [self.tabBarController.viewControllers objectAtIndex:1];	// for TopScreenView
		TopScreenView *topViewController;
		for (UIViewController *viewController in navigationController.viewControllers) {
			if ([viewController isKindOfClass:[TopScreenView class]]){
				topViewController = (TopScreenView*)viewController;
				break;
			}
		}
		for (UIViewController *viewController in navigationController.viewControllers) {
			if ([viewController isKindOfClass:[ContactListView class]]){
				// 施設メールリロード
				ContactListView *contactListView = (ContactListView*)viewController;
				if (contactListView.starMode || contactListView.findMode) {
					if (topViewController) {
						[topViewController reloadWhenNoTopData:contactListView.siteid];
					} else {
						_reloadMailSiteid = [contactListView.siteid copy];
					}
				}
				break;
			}
		}
//	}

//		contactListView.siteid = topListObject.siteid;
//		contactListView.sitename = topListObject.sitename;
//		contactListView.groupid = (int)topListObject.groupid;
//		
//		if (topListObject.isLoadMore) {
//			contactListView.dictionaryMailList = topListObject.loadMoreDictionary;
//			contactListView.topListObject = topListObject;
//			contactListView.isPostLoadMore = YES;
//		} else {
//			contactListView.dictionaryMailList = topListObject.mailList;// topListObject.mailList
//			contactListView.topListObject = topListObject;
//		}
//		
//		[self.navigationController pushViewController:contactListView animated:YES];

	UIButton *button = (UIButton*)sender;
	[button setHighlighted:NO];
	[button setImage:gImageButtonEmailSelected forState:UIControlStateNormal];

	_isTabbarClick = YES;
	[self.tabBarController setSelectedIndex:1];

	UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:1];
	/*NSArray *ary =*/ [navigationConttoller popToRootViewControllerAnimated:YES];

//	ContactListView *contactListView = (ContactListView*)ary[0];
//	if (contactListView && ary.count==1) {
//		// 連絡メール一覧からの戻り
//		DBG_LOG(@"ContactListView");
//		// トップ画面リロード
//		[topScreenView reloadTOP:YES];
////		contactListView.mailList
////		[topScreenView handleContactNotification];
//	}

	// DELETE 2015-09-14
//	// MODIFY 2015-09-07
//	DBG_METHOD_LINE;
//	[self isOnlineAndAlert:navigationConttoller.topViewController];
//	
////	// ADD 2015-07-24
////	ConnectionManager *connectManager = [[ConnectionManager alloc] init];
////	if (! [connectManager isConnectNetwork]) {
////		if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
////			// iOS8 and later
////			UIAlertController *alertController = [UIAlertController alertControllerWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE preferredStyle:UIAlertControllerStyleAlert];
////			// addActionした順に左から右にボタンが配置されます
////			[alertController addAction:[UIAlertAction actionWithTitle:OK_MESSAGE style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
////			}]];
////			[navigationConttoller.topViewController presentViewController:alertController animated:YES completion:nil];
////		} else {
////			// iOS7 and earlier
////			[UIAlertView showWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE cancelButtonTitle:OK_MESSAGE otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
////				
////			}];
////		}
////	}
}

#pragma mark クエスチョン
/* Research page */
- (void)clickOnListResearchPage:(id)sender
{
	// OFFLINE CHECK	ADD 2015-07-27,MODIFY 2015-09-07
	DBG_METHOD_LINE;

	// タイムアウト解除	ADD 2015-10-09
	[self clearTimeout];
	
	BOOL isTop = YES;
	if (self.tabBarController.selectedIndex != 1) {
		isTop = NO;
	}
	if ([topScreenView isOnlineAndAlert:isTop]) {
//	if ([self isOnlineAndAlert:navigationConttoller.topViewController]) {
		[self resetAllItems];
		
		UIButton *button = (UIButton*)sender;
		[button setHighlighted:NO];
		[button setImage:gImageButtonResearchSelected forState:UIControlStateNormal];
		
		_isTabbarClick = YES;
		[self.tabBarController setSelectedIndex:3];
		UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:3];
		[navigationConttoller popToRootViewControllerAnimated:YES];
	}
//	ConnectionManager *connectManager = [[ConnectionManager alloc] init];
//	if ([connectManager isConnectNetwork]) {
//		[self resetAllItems];
//		
//		UIButton *button = (UIButton*)sender;
//		[button setHighlighted:NO];
//		[button setImage:gImageButtonResearchSelected forState:UIControlStateNormal];
//
//		_isTabbarClick = YES;
//		[self.tabBarController setSelectedIndex:3];
//		UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:3];
//		[navigationConttoller popToRootViewControllerAnimated:YES];
//	} else {
//		if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
//			// iOS8 and later
//			UIAlertController *alertController = [UIAlertController alertControllerWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE preferredStyle:UIAlertControllerStyleAlert];
//			// addActionした順に左から右にボタンが配置されます
//			[alertController addAction:[UIAlertAction actionWithTitle:OK_MESSAGE style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//			}]];
//			UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:4];
//			[navigationConttoller.topViewController presentViewController:alertController animated:YES completion:nil];
//		} else {
//			// iOS7 and earlier
//			[UIAlertView showWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE cancelButtonTitle:OK_MESSAGE otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
//				
//			}];
//		}
//	}
}

- (void)clickOnListResearchPage
{
	// OFFLINE CHECK	ADD 2015-07-27,MODIFY 2015-09-07
	DBG_METHOD_LINE;
	UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:4];
	if ([self isOnlineAndAlert:navigationConttoller.topViewController]) {
		[self resetAllItems];
		
		[listResearchButton setHighlighted:NO];
		[listResearchButton setImage:gImageButtonResearchSelected forState:UIControlStateNormal];
		
		_isTabbarClick = YES;
		[self.tabBarController setSelectedIndex:3];
		UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:3];
		[navigationConttoller popToRootViewControllerAnimated:YES];
	}
//	ConnectionManager *connectManager = [[ConnectionManager alloc] init];
//	if ([connectManager isConnectNetwork]) {
//		[self resetAllItems];
//		
//		[listResearchButton setHighlighted:NO];
//		[listResearchButton setImage:gImageButtonResearchSelected forState:UIControlStateNormal];
//
//		_isTabbarClick = YES;
//		[self.tabBarController setSelectedIndex:3];
//		UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:3];
//		[navigationConttoller popToRootViewControllerAnimated:YES];
//	} else {
//		if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
//			// iOS8 and later
//			UIAlertController *alertController = [UIAlertController alertControllerWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE preferredStyle:UIAlertControllerStyleAlert];
//			// addActionした順に左から右にボタンが配置されます
//			[alertController addAction:[UIAlertAction actionWithTitle:OK_MESSAGE style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//			}]];
//			UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:4];
//			[navigationConttoller.topViewController presentViewController:alertController animated:YES completion:nil];
//		} else {
//			// iOS7 and earlier
//			[UIAlertView showWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE cancelButtonTitle:OK_MESSAGE otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
//				
//			}];
//		}
//	}
}

#pragma mark まちプレボタン押下
- (void)clickOnQuestion:(id)sender
{
	// OFFLINE CHECK	ADD 2015-07-27,MODIFY 2015-09-07
	DBG_METHOD_LINE;

	// タイムアウト解除	ADD 2015-10-09
	[self clearTimeout];

	BOOL isTop = YES;
	if (self.tabBarController.selectedIndex != 1) {
		isTop = NO;
	}
	if ([topScreenView isOnlineAndAlert:isTop]) {
//	if ([self isOnlineAndAlert:navigationConttoller.topViewController]) {
		[self resetAllItems];
		
		UIButton *button = (UIButton*)sender;
		[button setHighlighted:NO];
		[button setImage:gImageButtonQuestionSelected forState:UIControlStateNormal];
		
		_isTabbarClick = YES;
		[self.tabBarController setSelectedIndex:2];
		UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:2];
		BaseWebViewController *vc = navigationConttoller.viewControllers[0];
		[vc viewDidLoad];
		//[vc removeWebHistory];
		
		if (isClickedPushNews) {
			gIsPushNews = YES;
			[vc loadWebViewWithURL:URL_WEB_NEWS newsId:newsId];
		} else {
			gIsPushNews = NO;
			[vc loadWebViewWithURL:URL_WEB_NEWS];
		}
		
		isClickedPushNews = NO;
		newsId = NULL;
		
		[navigationConttoller popToRootViewControllerAnimated:YES];
	}

//	ConnectionManager *connectManager = [[ConnectionManager alloc] init];
//	if ([connectManager isConnectNetwork]) {
//		[self resetAllItems];
//		
//		UIButton *button = (UIButton*)sender;
//		[button setHighlighted:NO];
//		[button setImage:gImageButtonQuestionSelected forState:UIControlStateNormal];
//
//		_isTabbarClick = YES;
//		[self.tabBarController setSelectedIndex:2];
//		UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:2];
//		BaseWebViewController *vc = navigationConttoller.viewControllers[0];
//		[vc viewDidLoad];
//		//[vc removeWebHistory];
//		
//		if (isClickedPushNews) {
//			gIsPushNews = YES;
//			[vc loadWebViewWithURL:URL_WEB_NEWS newsId:newsId];
//		} else {
//			gIsPushNews = NO;
//			[vc loadWebViewWithURL:URL_WEB_NEWS];
//		}
//		
//		isClickedPushNews = NO;
//		newsId = NULL;
//		
//		[navigationConttoller popToRootViewControllerAnimated:YES];
//	} else {
//		if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
//			// iOS8 and later
//			UIAlertController *alertController = [UIAlertController alertControllerWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE preferredStyle:UIAlertControllerStyleAlert];
//			// addActionした順に左から右にボタンが配置されます
//			[alertController addAction:[UIAlertAction actionWithTitle:OK_MESSAGE style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//			}]];
//			UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:4];
//			[navigationConttoller.topViewController presentViewController:alertController animated:YES completion:nil];
//		} else {
//			// iOS7 and earlier
//			[UIAlertView showWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE cancelButtonTitle:OK_MESSAGE otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
//				
//			}];
//		}
//	}
}

#pragma mark その他ボタン
/* Setting page */
- (void)clickOnSettingUserPage:(id)sender
{
	// OFFLINE CHECK	ADD 2015-07-27,MODIFY 2015-09-07
	DBG_METHOD_LINE;

	// タイムアウト解除	ADD 2015-10-09
	[self clearTimeout];

	BOOL isTop = YES;
	if (self.tabBarController.selectedIndex != 1) {
		isTop = NO;
	}
	if ([topScreenView isOnlineAndAlert:isTop]) {
//	if ([self isOnlineAndAlert:navigationConttoller.topViewController]) {
		[self resetAllItems];
		
		UIButton *button = (UIButton*)sender;
		[button setHighlighted:NO];
		[button setImage:gImageButtonSettingSelected forState:UIControlStateNormal];
		
		_isTabbarClick = YES;
		[self.tabBarController setSelectedIndex:4];
		UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:4];
		[navigationConttoller popToRootViewControllerAnimated:NO completion:^{
			if (_isReload) {
				dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 500 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{
					[[NSNotificationCenter defaultCenter] postNotificationName:NSNotificationReloadWeb object:nil];
				});
			}
		}];
	}

//	ConnectionManager *connectManager = [[ConnectionManager alloc] init];
//	if ([connectManager isConnectNetwork]) {
//	
//		[self resetAllItems];
//		
//		UIButton *button = (UIButton*)sender;
//		[button setHighlighted:NO];
//		[button setImage:gImageButtonSettingSelected forState:UIControlStateNormal];
//
//		if (_isReload) {
//			[[NSNotificationCenter defaultCenter] postNotificationName:NSNotificationReloadWeb object:nil];
//		}
//		_isTabbarClick = YES;
//		[self.tabBarController setSelectedIndex:4];
//		UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:4];
//		
//		[navigationConttoller popToRootViewControllerAnimated:YES];
//
//	}else {
//		// MODIFY 2015-07-24
////		[UIAlertView showWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE cancelButtonTitle:OK_MESSAGE otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
////			
////		}];
//		if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
//			// iOS8 and later
//			UIAlertController *alertController = [UIAlertController alertControllerWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE preferredStyle:UIAlertControllerStyleAlert];
//			// addActionした順に左から右にボタンが配置されます
//			[alertController addAction:[UIAlertAction actionWithTitle:OK_MESSAGE style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//			}]];
//			UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:4];
//			[navigationConttoller.topViewController presentViewController:alertController animated:YES completion:nil];
//		} else {
//			// iOS7 and earlier
//			[UIAlertView showWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE cancelButtonTitle:OK_MESSAGE otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
//				
//			}];
//		}
//	}
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
	// Do something with the url here
	NSLog(@"url: %@", [url absoluteString]);
	NSString *stringUrl = url.absoluteString;
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSArray *arraySplit = [stringUrl componentsSeparatedByString:@"?"];
	if (arraySplit.count > 1) {
//        NSString *stringParams = [arraySplit objectAtIndex:1];
//        NSDictionary *dictionaryParams = [self getMutableDictionaryFromURL:[stringParams componentsSeparatedByString:@"&"]];
	}
	return YES;
}

- (BOOL)isUIAlertControllerOnTop
{
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
		UIViewController *topController = self.window.rootViewController;
		while (topController.presentedViewController) {
			topController = topController.presentedViewController;
		}
		if ([topController isKindOfClass:[UIAlertController class]]) {
			//
			DBG_LOG(@"UIAlertController");
			return YES;
		}
	} else if (_isShowAlert) {
		DBG_LOG(@"isShowAlert");
		return YES;
	}
	return NO;
}

#pragma mark - URL Scheme
// URL スキームで起動した場合
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
	NSString *stringUrl = url.absoluteString;
	
	NSArray *arraySplit = [stringUrl componentsSeparatedByString:@"?"];
	if (arraySplit.count > 1) {
		NSString *stringParams = [arraySplit objectAtIndex:1];
		NSDictionary *dictionaryParams = [self getMutableDictionaryFromURL:[stringParams componentsSeparatedByString:@"&"]];
		
		if ([[arraySplit objectAtIndex:0] rangeOfString:@"login"].location != NSNotFound) {
			
			// MODIFY 2015-09-07
			DBG_METHOD_LINE;
			UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:4];
			if ([self isOnlineAndAlert:navigationConttoller.topViewController]) {
				NSString *valueDses = [dictionaryParams objectForKey:@"Dses"];
				
				ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:URL_API_LOGIN_REGISTER]];
				[request addPostValue:valueDses forKey:@"Dses"];
				[request setTag:TAG_API_LOGIN];
				[request setTimeOutSeconds:10.0];
				[request setDelegate:self];
				[request setDidFinishSelector:@selector(loginWebViewFinished:)];
				[request setDidFailSelector:@selector(loginWebViewFailed:)];
				[request startAsynchronous];
			}
			
//			ConnectionManager *connectManager = [[ConnectionManager alloc] init];
//			if ([connectManager isConnectNetwork]) {
//				
//				NSString *valueDses = [dictionaryParams objectForKey:@"Dses"];
//				
//				ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:URL_API_LOGIN_REGISTER]];
//				[request addPostValue:valueDses forKey:@"Dses"];
//				[request setTag:TAG_API_LOGIN];
//				[request setTimeOutSeconds:10.0];
//				[request setDelegate:self];
//				[request setDidFinishSelector:@selector(loginWebViewFinished:)];
//				[request setDidFailSelector:@selector(loginWebViewFailed:)];
//				[request startAsynchronous];
//				
//			} else {
////				[UIAlertView showWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE cancelButtonTitle:OK_MESSAGE otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
////				}];
//				if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
//					// iOS8 and later
//					UIAlertController *alertController = [UIAlertController alertControllerWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE preferredStyle:UIAlertControllerStyleAlert];
//					// addActionした順に左から右にボタンが配置されます
//					[alertController addAction:[UIAlertAction actionWithTitle:OK_MESSAGE style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//					}]];
//					UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:4];
//					[navigationConttoller.topViewController presentViewController:alertController animated:YES completion:nil];
//				} else {
//					[UIAlertView showWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE cancelButtonTitle:OK_MESSAGE otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
//					}];
//				}
//			}
		} else if ([[arraySplit objectAtIndex:0] rangeOfString:@"Register"].location != NSNotFound) {
			NSString *valueHref = [dictionaryParams objectForKey:@"href"];
			NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
			if (![valueHref isEqualToString:@""]) {

				// MODIFY 2015-09-07
				DBG_METHOD_LINE;
				UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:4];
				if ([self isOnlineAndAlert:navigationConttoller.topViewController]) {
					if ([valueHref respondsToSelector:@selector(stringByRemovingPercentEncoding)]) {
						// iOS7 and later	MODIFY 2016-01-12
						valueHref = [valueHref stringByRemovingPercentEncoding];
					} else {
						// iOS6 and earlier
						valueHref = [valueHref stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
					}
					if(_isStartSchemaRegisterAndFirstTimeApp) {
						RegisterSchemaViewController *reg = [[RegisterSchemaViewController alloc] initWithNibName:@"RegisterSchemaViewController" bundle:nil];
						UINavigationController *controller = [[UINavigationController alloc] initWithRootViewController:reg];
						
						reg._url = valueHref;
						
						[self.tabBarController presentViewController:controller animated:YES completion:^{
							
						}];
					} else {
						[defaults setObject:valueHref forKey:FLAG_REGISTER_URL];
						[defaults synchronize];
					}
				}

//				ConnectionManager *connectManager = [[ConnectionManager alloc] init];
//				if ([connectManager isConnectNetwork]) {
//					valueHref = [valueHref stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//					if(_isStartSchemaRegisterAndFirstTimeApp) {
//						RegisterSchemaViewController *reg = [[RegisterSchemaViewController alloc] initWithNibName:@"RegisterSchemaViewController" bundle:nil];
//						UINavigationController *controller = [[UINavigationController alloc] initWithRootViewController:reg];
//						
//						reg._url = valueHref;
//						
//						[self.tabBarController presentViewController:controller animated:YES completion:^{
//							
//						}];
//					} else {
//						[defaults setObject:valueHref forKey:FLAG_REGISTER_URL];
//					}
//
//				}else {
////					[UIAlertView showWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE cancelButtonTitle:OK_MESSAGE otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
////						
////					}];
//					if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
//						// iOS8 and later
//						UIAlertController *alertController = [UIAlertController alertControllerWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE preferredStyle:UIAlertControllerStyleAlert];
//						// addActionした順に左から右にボタンが配置されます
//						[alertController addAction:[UIAlertAction actionWithTitle:OK_MESSAGE style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//						}]];
//						UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:4];
//						[navigationConttoller.topViewController presentViewController:alertController animated:YES completion:nil];
//					} else {
//						[UIAlertView showWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE cancelButtonTitle:OK_MESSAGE otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
//							
//						}];
//					}
//				}
			}
		} else if ([[arraySplit objectAtIndex:0] rangeOfString:@"Mail"].location != NSNotFound) {
			// ログインチェック	ADD 2015-10-14
			NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
			if (((NSString *)[defaults objectForKey:NSUserDefaultMailAddress]).length == 0) {
				// ログインしていない
				return YES;
			}
//			if ([self isUIAlertControllerOnTop]) {
//				// 警告ダイアログ表示中
//				DBG_LOG(@"Scheme:Mail");
//				return YES;
//			}
			// メール詳細 ADD 2015-10-07
			siteId = [dictionaryParams objectForKey:@"siteid"];
			NSString *rseq = [dictionaryParams objectForKey:@"rseq"];
			DBG_LOG(@"Scheme:Mail siteid:%@ rseq:%@", siteId, rseq);
			
			// 連絡メール詳細画面表示	(遷移なし)
			if (rseq.length && siteId.length) {
				// メールID & 施設ID あり
				// Select TOP
				[self topPageSelected];
				if ([_isScreen isEqualToString: TOP_SCREEN]
				   ||[_isScreen isEqualToString:CONTACT_LIST]
				   ||[_isScreen isEqualToString:CONTACT_DETAIL]
				   ||[_isScreen isEqualToString:RESEARCH_SCREEN]
				   ||[_isScreen isEqualToString:WEB_VIEW]
				   || _isScreen.length==0/*アプリ起動*/) {
					// トップ画面表示通知 TopScreenView::showMailWithScheme
					[[NSNotificationCenter defaultCenter] postNotificationName:NSNotificationSchemeToContactDetail object:dictionaryParams];
				}
			}
		}
	} else {
		
	}

	return YES;
}

#pragma mark - Notification selectors
#pragma mark - PushNotification
//#ifdef __IPHONE_8_0
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
	//register to receive notifications
	[application registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler
{
	//handle the actions
	if ([identifier isEqualToString:@"declineAction"]){
	}
	else if ([identifier isEqualToString:@"answerAction"]){
	}
}
//#endif

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
	retrieveuuid = [SSKeychain passwordForService:@"com.vcc.machicomi" account:@"user"];
	self.client_id = retrieveuuid;
	if (retrieveuuid == nil) { // if this is the first time app lunching , create key for device
		NSString *uuid  = [self createNewUUID];
		// save newly created key to Keychain
		[SSKeychain setPassword:uuid forService:@"com.vcc.machicomi" account:@"user"];
		// this is the one time process
		self.client_id = uuid;
	}

	token = [NSString stringWithFormat:@"%@", deviceToken];
	token = [token stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
	token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
	NSLog(@"トークン取得:%@", token);

	[[NSUserDefaults standardUserDefaults] setObject:token forKey:@"device_token"];
	[[NSUserDefaults standardUserDefaults] synchronize];
	
	if (!userDisablePush) {
		NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
		[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
		[dateFormatter setDateFormat:@"yyyy/MM/dd HH/mm/ss"];
		NSString *currentDate = [dateFormatter stringFromDate:[NSDate date]];
		
		if(token != nil) {
			[self pushChecking];
#ifdef putApliLog
			// PutApiLogin success but null
			NSString *successNULL = [NSString stringWithFormat:@"%@ Get token SUCCESS but Token_value is NULL [iOS]", currentDate];
			[self putApiLog:successNULL];
#endif
			NSLog(@"%@ Get token SUCCESS but Token_value is NULL [iOS]", currentDate);
			
		}else {
#ifdef putApliLog
			// PutApiLogin success
			NSString *successNULL = [NSString stringWithFormat:@"%@ Get token SUCCESS %@ [iOS]", currentDate, token];
			[self putApiLog:successNULL];
#endif
			NSLog(@"%@ Get token SUCCESS %@ [iOS]", currentDate, token);
		}
		
		ConnectionManager *connectManager = [[ConnectionManager alloc] init];
		if ([connectManager isConnectNetwork]) {
			[self applyAPI:token];
		} else {
			// OFFLINE MESSAGE	OFFLINE対応	DELETE 2015-09-10
//			[self showAlert888];
		}
	}else {
		userDisablePush = NO;
	}
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
	NSLog(@"error:%@",error);
	NSLog(@"トークン取得失敗");
	if(!userDisablePush) {
		retrieveuuid = [SSKeychain passwordForService:@"com.vcc.machicomi" account:@"user"];
		self.client_id = retrieveuuid;
		if (retrieveuuid == nil) { // if this is the first time app lunching , create key for device
			NSString *uuid  = [self createNewUUID];
			// save newly created key to Keychain
			[SSKeychain setPassword:uuid forService:@"com.vcc.machicomi" account:@"user"];
			// this is the one time process
			self.client_id = uuid;
		}
		
		NSString *oldToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"device_token"];
		NSLog(@"Failed to get token, error: %@", error);
		
#ifdef putApliLog
		// PutApiLogin failed
		NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
		[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
		[dateFormatter setDateFormat:@"yyyy/MM/dd HH/mm/ss"];
		NSString *currentDate = [dateFormatter stringFromDate:[NSDate date]];
		NSString *successNULL = [NSString stringWithFormat:@"%@ Get token FAILED [iOS]", currentDate];
		[self putApiLog:successNULL];
#endif
		
		ConnectionManager *connectManager = [[ConnectionManager alloc] init];
		if ([connectManager isConnectNetwork]) {
			[self applyAPI:oldToken];
		}else {
			// OFFLINE MESSAGE	OFFLINE対応	DELETE 2015-09-10
//			[self showAlert888];
		}

	} else {
		userDisablePush = NO;
	}
}

// アプリ起動中にプッシュ通知受信
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
	UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:1];
	if (![self isOnlineAndAlert:navigationConttoller.topViewController]) {
		NSDictionary *contentPush = [userInfo objectForKey:@"aps"];
		NSString *message = [contentPush objectForKey:@"alert"];
		if (message.length) {
			[self notificationRepeat:message];	// ローカル通知でaps/alertメッセージ表示
		}
		return;
	}
	_isLaunchedByNoti = NO;
	isRecievePush = YES;
	UIApplicationState state = [application applicationState];
	//save notification dictionary for alertview
	notificationDic = userInfo;
	NSString *mailAdress = [[NSUserDefaults standardUserDefaults] objectForKey:NSUserDefaultMailAddress];
	if(mailAdress.length == 0)
	{
		return;
	}
	
	// == userInfo ==
	// title タイトル
	// message 本文
	// type 1:連絡 / 2:リサーチ / 3:タイムライン / 6:まちpress
	// siteid サイトID
	// rseq メールID
	// newsid まちPRESS記事ID
	// aps Apple通知ペイロード辞書
	
	type = [[userInfo objectForKey:@"type"] intValue];
	newsId = userInfo[@"newsid"];
	
	NSLog(@"application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo");
	
	NSDictionary *contentPush = [userInfo objectForKey:@"aps"];

	NSString *message = [contentPush objectForKey:@"alert"];
	if (state == UIApplicationStateActive) {
		
		 NSLog(@"TYPE NOT BACKGROUND");
		
		if (type == TYPE_PUSH_REMIND) {
			// リマインダー	ADD 2015-10-16 仕様追加
			if ([self isUIAlertControllerOnTop]) {
				// 警告ダイアログ表示中
				[self notificationRepeat:message];	// ローカル通知でaps/alertメッセージ表示
				return;
			}
			UINavigationController *navigationController = [self.tabBarController.viewControllers objectAtIndex:1];	// for TopScreenView
			if (([navigationController.topViewController isKindOfClass:[TopScreenView class]]
				 ||[navigationController.topViewController isKindOfClass:[ContactListView class]]
				 ||[navigationController.topViewController isKindOfClass:[ContactSuperViewController class]])
				&& _isMFMailComposeViewController==NO) {
				// 通常
			} else {
				// 警告ダイアログ表示中
				[self notificationRepeat:message];	// ローカル通知でaps/alertメッセージ表示
				return;
			}
			siteId = [userInfo objectForKey:@"siteid"];
			for (UIViewController *viewController in navigationController.viewControllers) {
				if ([viewController isKindOfClass:[TopScreenView class]]){
					// DELETE 2015-09-19
//					if ([_isScreen isEqualToString:CONTACT_DETAIL]) {
//						_isEnterForeGround = YES;
//					}
					// トップ画面情報取得 - PUSH通知(連絡メール)
					TopScreenView *topViewController = (TopScreenView*)viewController;
					// トップ画面情報があるときは読み込まない	MODIFY 2015-09-03
					//					[topViewController reloadTopData];
					DBG_LOG(@"reloadWhenNoTopData siteid:%zd", siteId);
					[topViewController reloadWhenNoTopData:siteId];
				}
			}
			// 連絡メール一覧表示時のローディングアニメーション
			if([_isScreen isEqualToString:CONTACT_LIST]) {
				for(UIViewController *viewController in navigationController.viewControllers) {
					if ([viewController isKindOfClass:[ContactListView class]]){
						// ローディングアニメーション
						ContactListView *contactListView = (ContactListView*)viewController;
						[contactListView loadAnimation];
						break;
					}
				}
			}
			[self alertNotification:message];	// PUSH通知内容の表示確認
			[self notificationRepeat:message];	// ローカル通知でaps/alertメッセージ表示
		} else
		if (type == TYPE_PUSH_TOP) {
			// TOP reload
			
			// 連絡メールバッジのカウントアップ&表示	MODIFY 2015-09-03
			[self setReadBadge:contentPush];
//			// 連絡メールのバッジカウント追加
//			NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//			NSInteger read = [[defaults objectForKey:NSUserDefaultReadCount] integerValue];
//			read += [[contentPush objectForKey:@"badge"] integerValue];
//			[defaults setInteger:read forKey:NSUserDefaultReadCount];
//			[defaults synchronize];
//			
//			// 連絡メールバッジ表示
//			self.readcountButon.hidden = NO;
//			[self.readcountButon setTitle:[NSString stringWithFormat:@"%ld", (long)read] forState:UIControlStateNormal];
			
			if ([self isUIAlertControllerOnTop]) {
				// 警告ダイアログ表示中
				[self notificationRepeat:message];	// ローカル通知でaps/alertメッセージ表示
				return;
			}
			// Reload TOP
			UINavigationController *navigationController = [self.tabBarController.viewControllers objectAtIndex:1];	// for TopScreenView

			if (([navigationController.topViewController isKindOfClass:[TopScreenView class]]
				||[navigationController.topViewController isKindOfClass:[ContactListView class]]
				||[navigationController.topViewController isKindOfClass:[ContactSuperViewController class]])
				&& _isMFMailComposeViewController==NO) {
				// 通常
			} else {
				// 警告ダイアログ表示中
				[self notificationRepeat:message];	// ローカル通知でaps/alertメッセージ表示
				return;
			}

			siteId = [userInfo objectForKey:@"siteid"];
			for (UIViewController *viewController in navigationController.viewControllers) {
				if ([viewController isKindOfClass:[TopScreenView class]]){
					// DELETE 2015-09-19
//					if ([_isScreen isEqualToString:CONTACT_DETAIL]) {
//						_isEnterForeGround = YES;
//					}
					// トップ画面情報取得 - PUSH通知(連絡メール)
					TopScreenView *topViewController = (TopScreenView*)viewController;
					// トップ画面情報があるときは読み込まない	MODIFY 2015-09-03
//					[topViewController reloadTopData];
					DBG_LOG(@"reloadWhenNoTopData siteid:%zd", siteId);
					[topViewController reloadWhenNoTopData:siteId];
				}
			}
			
			// 連絡メール一覧表示時のローディングアニメーション
			if([_isScreen isEqualToString:CONTACT_LIST]) {
				for(UIViewController *viewController in navigationController.viewControllers) {
					if ([viewController isKindOfClass:[ContactListView class]]){
						// ローディングアニメーション
						ContactListView *contactListView = (ContactListView*)viewController;
						[contactListView loadAnimation];
						break;
					}
				}
			}
			
			// 連絡メール詳細画面のときも表示確認を行って画面遷移する
			if([_isScreen isEqualToString:CONTACT_DETAIL]) {
//				alertStatus = 999;
				[self alertNotification:message];	// PUSH通知内容の表示確認 ADD 2015-09-18
				[self notificationRepeat:message];	// ローカル通知でaps/alertメッセージ表示
			} else {
				[self alertNotification:message];	// PUSH通知内容の表示確認
				[self notificationRepeat:message];	// ローカル通知でaps/alertメッセージ表示
			}
			
		} else if (type == TYPE_PUSH_RESEARCH) {
			
			// Research reload
			[self alertNotification:message];
			[self notificationRepeat:message];
			
			[self setResearchBadge:contentPush];
//			NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//			NSInteger answer = [[defaults objectForKey:NSUserDefaultAnswerCount] integerValue];
//			answer += [[contentPush objectForKey:@"badge"] integerValue];
//			[defaults setInteger:answer forKey:NSUserDefaultAnswerCount];
//			[defaults synchronize];
//
//			self.answercountButon.hidden = NO;
//			[self.answercountButon setTitle:[NSString stringWithFormat:@"%ld", (long)answer] forState:UIControlStateNormal];
			
			// Reload Research
			UINavigationController *navigationController = [self.tabBarController.viewControllers objectAtIndex:3];
			for(UIViewController *viewController in navigationController.viewControllers) {
				if ([viewController isKindOfClass:[ResearchListView class]])
				{
					ResearchListView *researchList = (ResearchListView*)viewController;
					[researchList reloadData];
				}
			}
			
		} else if(type == TYPE_PUSH_TIMELINE){
			// Timeline
			siteId = [userInfo objectForKey:@"siteid"];
			[self alertNotification:message];
			[self notificationRepeat:message];
			
		} else if(type == TYPE_PUSH_NEWS){ // News Content
			// reload
			[self alertNotification:message];
			[self notificationRepeat:message];
			
			NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
			NSInteger answer = [[defaults objectForKey:NSUserDefaultNewsCount] integerValue];
			answer += [[contentPush objectForKey:@"badge"] integerValue];
			[defaults setInteger:answer forKey:NSUserDefaultNewsCount];
			[defaults synchronize];
			
			self.questionCountButon.hidden = NO;
			[self.questionCountButon setTitle:[NSString stringWithFormat:@"%ld",(long)answer] forState:UIControlStateNormal];

			//[self clickOnQuestion:self.questionButton];
		} else {
			[self alertNotification:message];
			[self notificationRepeat:message];
		}
	} else {
		// Enter background
		NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
		if(((NSString *)[defaults objectForKey:NSUserDefaultMailAddress]).length > 0){
			NSArray *allKey = [userInfo allKeys];
			BOOL isHaveKey = NO;
			BOOL isHaveSite= NO;
			for (NSString* theKey in allKey) {
				
				if ([theKey isEqualToString:@"rseq"] && ![[userInfo objectForKey:theKey] isEqualToString:@""]) {
					isHaveKey = YES;
				}
				if ([theKey isEqualToString:@"siteid"] && ![[userInfo objectForKey:theKey] isEqualToString:@""]) {
					isHaveSite = YES;
				}
			}
			
			NSString *noLoad = @"";
			NSLog(@"TIMELINE2");
			
			if (type == TYPE_PUSH_REMIND) {
				if ( ! (isHaveKey && isHaveSite)) {
					return;
				}
				// Reload TOP
				UINavigationController *navigationController = [self.tabBarController.viewControllers objectAtIndex:1];	// for TopScreenView
				
				// メール詳細の削除確認画面を閉じる
				if ([navigationController.topViewController isKindOfClass:[ContactSuperViewController class]]) {
					ContactSuperViewController* vc = (ContactSuperViewController*)navigationController.topViewController;
					// 削除確認を閉じる
					[vc closeTrashAlert];
				}
				// メール一覧の削除・既読の確認画面を閉じる
				BOOL isFindMode = NO;
				if ([navigationController.topViewController isKindOfClass:[ContactListView class]]) {
					ContactListView* vc = (ContactListView*)navigationController.topViewController;
					[vc closeAlertDelOrRead];
					isFindMode = [vc isFindOrStar];
				}
				if (([navigationController.topViewController isKindOfClass:[TopScreenView class]]
					 ||[navigationController.topViewController isKindOfClass:[ContactListView class]]
					 ||[navigationController.topViewController isKindOfClass:[ContactSuperViewController class]])
					&& _isMFMailComposeViewController==NO) {
					// 通常
				} else {
					// 警告ダイアログ表示中
					NSDate* fireDate = [NSDate date];
					dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 500 * NSEC_PER_MSEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
						// ローカル通知でaps/alertメッセージ表示
						[self notificationRepeat:message fireDate:fireDate];
					});
					return;
				}
				
				if (isFindMode==NO) {
					[self topPageSelected];
				}
				
				if (![_isScreen isEqualToString: TOP_SCREEN]) {
					for (UIViewController *viewController in navigationController.viewControllers) {
						if ([viewController isKindOfClass:[TopScreenView class]])
						{
							// トップ画面情報はスリープ復帰時に読み込むため読み込まない	MODIFY 2015-09-19
							// トップ画面情報取得 - PUSH通知(連絡メール)
							TopScreenView *topViewController = (TopScreenView*)viewController;
							//						[topViewController reloadTopData];
							[topViewController.navigationController popToRootViewControllerAnimated:NO completion:^{
								if (isFindMode==NO) {
									dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1000 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{
										_isScreen = TOP_SCREEN;
										siteId = [userInfo objectForKey:@"siteid"];
										[topViewController reloadWhenNoTopData:siteId];
									});
								}
								_isLaunchedByNoti = NO;	// YES:通知からのforegroundへ復帰
							}];
						}
					}
				}
				// Select TOP
				[self topPageSelected];
				if ([_isScreen isEqualToString: TOP_SCREEN]
					||[_isScreen isEqualToString:CONTACT_LIST]
					||[_isScreen isEqualToString:CONTACT_DETAIL]
					||[_isScreen isEqualToString:RESEARCH_SCREEN]
					||[_isScreen isEqualToString:WEB_VIEW]
					|| _isScreen.length==0/*アプリ起動*/) {
					// トップ画面表示通知 TopScreenView::showMailWithScheme
					[[NSNotificationCenter defaultCenter] postNotificationName:NSNotificationSchemeToContactDetail object:notificationDic];
				}
			} else
			if (type == TYPE_PUSH_TOP) {
				if ( ! (isHaveKey && isHaveSite)) {
					return;
				}
				
				// 連絡メールバッジのカウントアップ&表示	MODIFY 2015-09-03
				[self setReadBadge:contentPush];
//				// Select TOP
//				NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//				NSInteger read = [[defaults objectForKey:NSUserDefaultReadCount] integerValue];
//				read += [[contentPush objectForKey:@"badge"] integerValue];
//				[defaults setInteger:read forKey:NSUserDefaultReadCount];
//				[defaults synchronize];
//					
//				self.readcountButon.hidden = NO;
//				[self.readcountButon setTitle:[NSString stringWithFormat:@"%ld", (long)read] forState:UIControlStateNormal];
					
				noLoad = @"tab1";
				
				// Reload TOP
				UINavigationController *navigationController = [self.tabBarController.viewControllers objectAtIndex:1];	// for TopScreenView

				// メール詳細の削除確認画面を閉じる
				if ([navigationController.topViewController isKindOfClass:[ContactSuperViewController class]]) {
					ContactSuperViewController* vc = (ContactSuperViewController*)navigationController.topViewController;
					// 削除確認を閉じる
					[vc closeTrashAlert];
				}
				// メール一覧の削除・既読の確認画面を閉じる
				BOOL isFindMode = NO;
				if ([navigationController.topViewController isKindOfClass:[ContactListView class]]) {
					ContactListView* vc = (ContactListView*)navigationController.topViewController;
					[vc closeAlertDelOrRead];
					isFindMode = [vc isFindOrStar];
				}
				if (([navigationController.topViewController isKindOfClass:[TopScreenView class]]
					 ||[navigationController.topViewController isKindOfClass:[ContactListView class]]
					 ||[navigationController.topViewController isKindOfClass:[ContactSuperViewController class]])
					&& _isMFMailComposeViewController==NO) {
					// 通常
				} else {
					// 警告ダイアログ表示中
					NSDate* fireDate = [NSDate date];
					dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 500 * NSEC_PER_MSEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
						// ローカル通知でaps/alertメッセージ表示
						[self notificationRepeat:message fireDate:fireDate];
					});
					return;
				}

				if (isFindMode==NO) {
					[self topPageSelected];
				}
				if([_isScreen isEqualToString:TOP_SCREEN]) {
					NSLog(@"Push to Detail2");
					// TODO:スリープ復帰
					// DELETE 2015-09-19
					// トップ画面表示通知 TopScreenView::recievePushTop
					dispatch_queue_t q_global = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
					dispatch_async(q_global, ^{
						for (ASIHTTPRequest *request in ASIHTTPRequest.sharedQueue.operations) {
							if (![request isCancelled]) {
								[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
//								[NSThread sleepForTimeInterval:1];
							}
						}
						dispatch_async(dispatch_get_main_queue(), ^{
							_isLaunchedByNoti = NO;	// YES:通知からのforegroundへ復帰
							[[NSNotificationCenter defaultCenter] postNotificationName:NSNotificationPushToScreen object:userInfo];
						});
					});
				} else {
					
					for (UIViewController *viewController in navigationController.viewControllers) {
						if ([viewController isKindOfClass:[TopScreenView class]])
						{
//							for (ASIHTTPRequest *request in ASIHTTPRequest.sharedQueue.operations) {
//								if(![request isCancelled]) {
//									[request cancel];
//									[request setDelegate:nil];
//								}
//							}
							// トップ画面情報はスリープ復帰時に読み込むため読み込まない	MODIFY 2015-09-19
							// トップ画面情報取得 - PUSH通知(連絡メール)
							TopScreenView *topViewController = (TopScreenView*)viewController;
//							[topViewController reloadTopData];
							[topViewController.navigationController popToRootViewControllerAnimated:NO completion:^{
								if (isFindMode==NO) {
									_isScreen = TOP_SCREEN;
									siteId = [userInfo objectForKey:@"siteid"];
									[topViewController reloadWhenNoTopData:siteId];
								}

								NSLog(@"Push to Detail2");
								_isLaunchedByNoti = YES;	// YES:通知からのforegroundへ復帰
								// TODO:スリープ復帰
								// DELETE 2015-09-19
								// トップ画面表示通知 TopScreenView::recievePushTop
								[[NSNotificationCenter defaultCenter] postNotificationName:NSNotificationPushToScreen object:userInfo];
							}];
						
							// DELETE 2015-09-19
//							NSLog(@"Push to Detail2");
//							_isLaunchedByNoti = YES;	// YES:通知からのforegroundへ復帰
//							if ([_isScreen isEqualToString:CONTACT_DETAIL]) {
//								_isEnterForeGround = YES;
//							}
//							[self topPageSelected];
//							// トップ画面表示通知 TopScreenView::recievePushTop
//							[[NSNotificationCenter defaultCenter] postNotificationName:NSNotificationPushToScreen object:userInfo];
						}
					}
				}

			} else if (type == TYPE_PUSH_RESEARCH) {
				if (isHaveKey && isHaveSite) {
					[self setResearchBadge:contentPush];
//					NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//					int answer = [[defaults objectForKey:NSUserDefaultAnswerCount] intValue];
//					answer += [[contentPush objectForKey:@"badge"] integerValue];
//					[defaults setInteger:answer forKey:NSUserDefaultAnswerCount];
//					[defaults synchronize];
//					
//					self.answercountButon.hidden = NO;
//					[self.answercountButon setTitle:[NSString stringWithFormat:@"%d", answer] forState:UIControlStateNormal];
					noLoad = @"tab2";
					NSLog(@"TYPE 2 BACKGROUND");
					
					// Change to research view
					[self clickOnListResearchPage:listResearchButton];
					
				}

			} else if(type == TYPE_PUSH_NEWS){
				NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
				int answer = [[defaults objectForKey:NSUserDefaultNewsCount] intValue];
				answer += [[contentPush objectForKey:@"badge"] integerValue];
				[defaults setInteger:answer forKey:NSUserDefaultNewsCount];
				[defaults synchronize];
				
				self.questionCountButon.hidden = NO;
				[self.questionCountButon setTitle:[NSString stringWithFormat:@"%d", answer] forState:UIControlStateNormal];
				
				//UINavigationController *navigationController = [self.tabBarController.viewControllers objectAtIndex:2];
				//BaseWebViewController *vc = navigationController.viewControllers[0];
				//[vc reloadPressed:nil];
				
				isClickedPushNews = YES;
				isJustClickedPushNews = YES;
				
				[self clickOnQuestion:self.questionButton];
				
				
			} else if(type == TYPE_PUSH_TIMELINE) {
				// Time line
				// Reload top
				NSLog(@"TIMELINE BACKGROUND");
				[self topPageSelected];
				siteId = [userInfo objectForKey:@"siteid"];
				UINavigationController *navigationController = [self.tabBarController.viewControllers objectAtIndex:1];
				for(UIViewController *viewController in navigationController.viewControllers) {
					if ([viewController isKindOfClass:[TopScreenView class]]){
						// トップ画面情報取得
						_pushType = type;	// ADD 2015-10-05
						TopScreenView *topViewController = (TopScreenView*)viewController;
						topViewController.delegate = self;
						[topViewController reloadTopData];
					}
				}
				
			} else {
				[self clickOnTopPage:topButton];
			}
			
			isHaveKey = NO;
			isHaveSite = NO;
			allHaveKey = YES;
			
		} else {
			[self clickOnMyPage:startApp];
		}
	
	}
}

// 連絡メールバッジ表示	ADD 2015-09-03
// aps	userInfo/aps
- (void)setReadBadge:(NSDictionary*)aps {
	// 連絡メールのバッジカウント追加
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSInteger read = [[defaults objectForKey:NSUserDefaultReadCount] integerValue];
//	read += [[aps objectForKey:@"badge"] integerValue];
	read = [[aps objectForKey:@"badge"] integerValue];
	[defaults setInteger:read forKey:NSUserDefaultReadCount];
	[defaults synchronize];
	
	// 連絡メールバッジ表示
	if (read > 0) {
		self.readcountButon.hidden = NO;
		[self.readcountButon setTitle:[NSString stringWithFormat:@"%ld", (long)read] forState:UIControlStateNormal];
	} else {
		self.readcountButon.hidden = YES;
	}
}
// リサーチバッジ表示		ADD 2015-09-07
// aps	userInfo/aps
- (void)setResearchBadge:(NSDictionary*)aps
{
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSInteger answer = [[aps objectForKey:@"badge"] integerValue];
//	NSInteger answer = [[defaults objectForKey:NSUserDefaultAnswerCount] integerValue];
//	answer += [[aps objectForKey:@"badge"] integerValue];
	[defaults setInteger:answer forKey:NSUserDefaultAnswerCount];
	[defaults synchronize];
	
	if (answer > 0) {
		self.answercountButon.hidden = NO;
		[self.answercountButon setTitle:[NSString stringWithFormat:@"%ld", (long)answer] forState:UIControlStateNormal];
	} else {
		self.answercountButon.hidden = YES;
	}
}

#pragma mark - UILocalNotification
// ローカツ通知受信処理なし
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
	NSLog(@"LocalNotification:%@", notification);

}

// 即時にローカル通知でメッセージを表示
- (void)notificationRepeat:(NSString *)message
{
	[self notificationRepeat:message fireDate:[NSDate date]];
}
- (void)notificationRepeat:(NSString *)message fireDate:(NSDate*)fireDate
{
	UILocalNotification *localNotification = [[UILocalNotification alloc] init];
	localNotification.fireDate = fireDate;
	localNotification.alertBody = message;
	[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

#pragma mark - ASIHTTPRequestDelegate

- (void)loginWebViewFinished:(ASIHTTPRequest *)request
{
	NSData *responseData = [request responseData];

	// JSONKit => NSJSONSerialization	iOS9対応	MODIFY 2016-01-14
//	NSDictionary *resultsArray = [responseData objectFromJSONData];
	NSError *error = nil;
	id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&error];
	NSDictionary *resultsArray = (NSDictionary*)jsonObject;
	DBG_LOG(@"JSON %@", resultsArray);

	NSArray *keyResult = [resultsArray allKeys];
	
	if ([[keyResult objectAtIndex:0] isEqualToString:@"error"]) {
		NSDictionary *error = [resultsArray objectForKey:[keyResult objectAtIndex:0]];
		NSLog(@"error diction %@", error);
		
		errorCode = [[error objectForKey:@"code"] integerValue];
		
		errorText = [error objectForKey:@"text"];
		if (errorCode == 1102) {
			//
		} else if (errorCode == 902) {
			
		} else if (errorCode == 903) {
			
		} else if (errorCode == 904) {
			
		} else if (errorCode == 905) {
			
		} else if (errorCode == 906) {
			
		} else if (errorCode == 907) {
			
		} else if (errorCode == 908) {
			
		} else if (errorCode == 402) {
			
		}
	} else {
		
		NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
		_hostId = [resultsArray objectForKey:@"hostid"];
		[defaults setObject:_hostId forKey:NSUserDefaultHostid];
		[defaults synchronize];
		
		if (request.tag == TAG_API_LOGIN) {
			
			NSString *mail = [resultsArray objectForKey:@"mailadr"];
			NSString *pass = [resultsArray objectForKey:@"passwd"];
			if ((mail != nil && ![mail isEqualToString:@""]) && (pass != nil && ![pass isEqualToString:@""])) {
				[defaults setObject:mail forKey:NSUserDefaultMailAddress];
				[defaults setObject:pass forKey:NSUserDefaultPassWord];
				[defaults synchronize];
			}
			
			[[NSNotificationCenter defaultCenter] postNotificationName:@"LoginWebFinished" object:nil];
			self.startApp.hidden = YES;
			[self topPageSelected];
			
			if ([defaults objectForKey:FLAG_REGISTER] != nil) {
				[defaults removeObjectForKey:FLAG_REGISTER];
				[defaults removeObjectForKey:FLAG_LOGIN_HOST_ID];
				[defaults synchronize];
			}
		}
	}
	[slashView.view removeFromSuperview];
}

- (void)loginWebViewFailed:(ASIHTTPRequest *)request
{
	NSLog(@"End: %@", [NSDate date]);
	NSError *error = [request error];
	NSLog(@"ASIHttpRequest Error: %@", [error localizedDescription]);
//	[UIAlertView showWithTitle:ALERT_TITLE message:TIMEOUT_MESSAGE cancelButtonTitle:OK_MESSAGE otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
//		if(_hostId == nil) {
//			[self alert888];
//		}else {
//			[slashView.view removeFromSuperview];
//		}
//	}];
	UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:1];

	// hostid存在チェック	ADD 2015-10-09
	[self checkHostid:navigationConttoller.topViewController];
	
//	// タイムアウトメッセージ	MODIFY 2015-09-14
//	[self alertTimeout:navigationConttoller.topViewController completion:^{
////		[slashView.view removeFromSuperview];
//		if(_hostId == nil) {
//			NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
//			_hostId = [ud stringForKey:NSUserDefaultHostid];
//			if (_hostId == nil) {
//				[self alert888];
//			}
//		} else {
//			[slashView.view removeFromSuperview];
//		}
//	}];
}


/* putPushTokun API */
- (void)requestFinished:(ASIHTTPRequest *)request
{
	NSData *responseData = [request responseData];

	// JSONKit => NSJSONSerialization	iOS9対応	MODIFY 2016-01-14
//	NSDictionary *resultsArray = [responseData objectFromJSONData];
	NSError *error = nil;
	id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&error];
	NSDictionary *resultsArray = (NSDictionary*)jsonObject;
//	DBG_LOG(@"PUSH_TOKEN %@", resultsArray);

	if (resultsArray==nil) {
		[self requestFailed:request];
		return;
	}
	NSArray *keyResult = [resultsArray allKeys];
	
	if ([[keyResult objectAtIndex:0] isEqualToString:@"error"]) {
		NSDictionary *error = [resultsArray objectForKey:[keyResult objectAtIndex:0]];
		NSLog(@"error diction %@", error);
		
		errorCode = [[error objectForKey:@"code"] integerValue];
		
		errorText = [error objectForKey:@"text"];
		if (errorCode == 1102) {
			// 
		} else if (errorCode == 902) {
			
		} else if (errorCode == 903) {
			
		} else if (errorCode == 904) {
			
		} else if (errorCode == 905) {
			
		} else if (errorCode == 906) {
			
		} else if (errorCode == 907) {
			
		} else if (errorCode == 908) {
			
		} else if (errorCode == 402) {
			
		}
	}

	[slashView.view removeFromSuperview];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
	NSLog(@"End: %@", [NSDate date]);
	NSError *error = [request error];
	NSLog(@"ASIHttpRequest Error: %@", [error localizedDescription]);
//	[UIAlertView showWithTitle:ALERT_TITLE message:TIMEOUT_MESSAGE cancelButtonTitle:OK_MESSAGE otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
//		if(_hostId == nil) {
//			[self alert888];
//		}else {
//			[slashView.view removeFromSuperview];
//		}
//	}];

	UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:1];

	// hostid存在チェック&タイムアウトメッセージ	ADD 2015-10-13
	[self checkHostid:navigationConttoller.topViewController];

//	// タイムアウトメッセージ	MODIFY 2015-09-14
//	BOOL bShow = [self alertTimeout:navigationConttoller.topViewController completion:^{
//		if (_hostId == nil) {
//			NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
//			_hostId = [ud stringForKey:NSUserDefaultHostid];
//			if (_hostId == nil) {
//				[self alert888];
//			}
//		} else {
//			[slashView.view removeFromSuperview];
//		}
//	}];
//	if (!bShow) {
//		if (_hostId == nil) {
//			NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
//			_hostId = [ud stringForKey:NSUserDefaultHostid];
//			if (_hostId == nil) {
//				[self alert888];
//			}
//		} else {
//			[slashView.view removeFromSuperview];
//		}
//	}
}

// OFFLINE対応	DELETE 2015-09-10
//#pragma mark -
//// OFFLINE MESSAGE & EXIT()	ADD 2015-07-27
//- (void)showAlert888
//{
//	NSString* title = OFFLINE_TITLE;
//	NSString* message = OFFLINE_MESSAGE;
//	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
//		// iOS8 and later
//		UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
//		// addActionした順に左から右にボタンが配置されます
//		[alertController addAction:[UIAlertAction actionWithTitle:OK_MESSAGE style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//			[self alert888];
//		}]];
//		UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:1];
//		[navigationConttoller.topViewController presentViewController:alertController animated:YES completion:nil];
//	} else {
//		UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:OK_MESSAGE otherButtonTitles: nil];
////		NSArray* subviews = alertView.subviews;
////		id obj = nil;
////		// タイトル文字列が存在しない場合はsubviewsの1番目の要素
////		if (title.length > 0) {
////			if ([subviews count] > 0) {
////				obj = [[alertView subviews] objectAtIndex:0];
////			}
////		}
////		// タイトル文字列が存在する場合はsubviewsの2番目の要素
////		else if (title.length > 0 && [subviews count] > 1) {
////			obj = [subviews objectAtIndex:1];
////		}
////		// UILabel型であればtextAlignmentを左寄せにセット
////		if (obj && [obj isKindOfClass:[UILabel class]]) {
////			((UILabel *)obj).textAlignment = NSTextAlignmentLeft;
////		}
//		alertStatus = 888;
//		[alertView show];
//	}
//}

#pragma mark - OFFLINE関連
// OFFLINE MESSAGE	ADD 2015-09-03
- (BOOL)isOnlineAndAlert:(UIViewController*)topViewController
{
	BOOL isOnline = YES;
	if ([self isOffline]) {
		isOnline = NO;
		[self alertOffline:topViewController];
	}
	return isOnline;
}
- (void)alertOffline:(UIViewController*)viewController
{
//	[self alertWithViewController:viewController title:OFFLINE_TITLE message:OFFLINE_MESSAGE completion:nil];
	[self alertOffline:viewController completion:nil];
}
- (void)alertOffline:(UIViewController*)viewController completion:(void (^)(void))completion
{
	[self alertWithViewController:viewController title:OFFLINE_TITLE message:OFFLINE_MESSAGE completion:completion];
}
- (BOOL)isOffline
{
	if (_isLoginFailed) {
		return _isLoginFailed;
	}
	ConnectionManager *connectManager = [[ConnectionManager alloc] init];
	return (! [connectManager isConnectNetwork]);
}
- (void)alertWithViewController:(UIViewController*)controller title:(NSString*)title message:(NSString*)message completion:(void (^)(void))completion
{
	[self alertWithViewController:controller title:title message:message cancelButtonTitle:OK_MESSAGE completion:completion];
	
//	_isShowAlert = YES;
//	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
//		// iOS8 and later
//		UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
//
//		// 左寄せ
////		NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
////		style.alignment = NSTextAlignmentLeft;
////		NSAttributedString *str = [[NSAttributedString alloc] initWithString:message
////																  attributes:
////								   @{ NSParagraphStyleAttributeName: style,
////									  NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleBody],
////									  NSForegroundColorAttributeName : [UIColor blackColor]}];
////		[alertController setValue:str forKey:@"attributedMessage"];
//
//		// addActionした順に左から右にボタンが配置されます
//		[alertController addAction:[UIAlertAction actionWithTitle:OK_MESSAGE style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//			_isShowAlert = NO;
//			if (completion) {
//				completion();
//			}
//		}]];
//		[controller presentViewController:alertController animated:YES completion:nil];
//	} else {
//		// iOS7 and earlier
//		[UIAlertView showWithTitle:title message:message cancelButtonTitle:OK_MESSAGE otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
//			_isShowAlert = NO;
//			if (completion) {
//				completion();
//			}
//		}];
//	}
}
- (void)alertWithViewController:(UIViewController*)controller title:(NSString*)title message:(NSString*)message cancelButtonTitle:cancelButtonTitle completion:(void (^)(void))completion
{
	_isShowAlert = YES;
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
		// iOS8 and later
		UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
		
		// 左寄せ
//		NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
//		style.alignment = NSTextAlignmentLeft;
//		NSAttributedString *str = [[NSAttributedString alloc] initWithString:message
//																  attributes:
//								   @{ NSParagraphStyleAttributeName: style,
//									  NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleBody],
//									  NSForegroundColorAttributeName : [UIColor blackColor]}];
//		[alertController setValue:str forKey:@"attributedMessage"];
		
		// addActionした順に左から右にボタンが配置されます
		[alertController addAction:[UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
			_isShowAlert = NO;
			if (completion) {
				completion();
			}
		}]];
		[controller presentViewController:alertController animated:YES completion:nil];
	} else {
		// iOS7 and earlier
		[UIAlertView showWithTitle:title message:message cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
			_isShowAlert = NO;
			if (completion) {
				completion();
			}
		}];
	}
}

#pragma mark - TIMEOUT関連
// YES:画面表示 / NO:画面表示中
- (BOOL)alertTimeout:(UIViewController*)viewController completion:(void (^)(void))completion
{
	if (bAlertTimeout) {
		return NO;
	}
	_isLoginFailed = YES;	// ADD 2015-10-07
	NSString *urlAsString = URL_TIMEOUT_MESSAGE_API;
	NSURL *url = [NSURL URLWithString:urlAsString];
	ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
	[request addRequestHeader:@"User-Agent" value:_userAgent];
	[request setTimeOutSeconds:2.f];	// メッセージ取得タイムアウト2秒
	[request startSynchronous];
	
	NSString *requestString = request.responseString;

	// JSONKit => NSJSONSerialization	iOS9対応	MODIFY 2016-01-14
//	NSDictionary *resultArray = [requestString objectFromJSONString];
	NSError *error = nil;
	NSData *responseData = [requestString dataUsingEncoding:NSUTF8StringEncoding];
	id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&error];
	NSDictionary *resultArray = (NSDictionary*)jsonObject;
	DBG_LOG(@"JSON %@", resultArray);

	NSString* msg = nil;
	if (resultArray==nil) {
		// メッセージなし
	} else {
		msg = [resultArray objectForKey:@"message"];
	}

	if (msg.length==0){
		// 指定メッセージなし:固定メッセージ
		msg = TIMEOUT_MESSAGE;
	}
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
		// iOS8 and later
		UIAlertController *alertController = [UIAlertController alertControllerWithTitle:ALERT_TITLE message:msg preferredStyle:UIAlertControllerStyleAlert];
		// addActionした順に左から右にボタンが配置されます
		[alertController addAction:[UIAlertAction actionWithTitle:OK_MESSAGE style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
			bAlertTimeout = NO;
			if (completion) {
				completion();
			}
		}]];
		[viewController presentViewController:alertController animated:YES completion:nil];
	} else {
		// iOS7 and earlier
		[UIAlertView showWithTitle:ALERT_TITLE message:msg cancelButtonTitle:OK_MESSAGE otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
			bAlertTimeout = NO;
			if (completion) {
				completion();
			}
		}];
	}
	bAlertTimeout = YES;
	return bAlertTimeout;
}

// タイムアウト状態解除	ADD 2015-10-09
- (void)clearTimeout
{
	_isLoginFailed = NO;
}

- (void)checkHostid:(UIViewController*)viewController
{
	// hostidが存在しない場合の警告メッセージ	ADD 2015-10-09
	if (_hostId.length == 0) {
		NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
		_hostId = [ud stringForKey:NSUserDefaultHostid];
		if (_hostId.length == 0) {
			// TODO:hostidが存在しない確認メッセージ
			[self alertWithViewController:viewController title:ALERT_TITLE message:NO_HOSTID_MESSAGE completion:^{
				[self alert888];
			}];
		}
	}
	if (_hostId.length) {
		// タイムアウトメッセージ	MODIFY 2015-09-14
		BOOL bShow = [self alertTimeout:viewController completion:^{
			[slashView.view removeFromSuperview];
		}];
		if (!bShow) {
			[slashView.view removeFromSuperview];
		}
	}
}


#pragma mark - UIAlertDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	// OFFLINE対応	DELETE 2015-09-10
//	if(alertStatus == 888) {
//		[self alert888];
//		return;
//	}

	if(alertStatus == 999) {
		[self alert999];
		return;
	}
	
	if (buttonIndex == 1) {
		[self alertEtc];
	} else {
		NSLog(@"Close button");
		// ADD 2015-09-18
		UINavigationController *navigationController = [self.tabBarController.viewControllers objectAtIndex:1];
		for (UIViewController *viewController in navigationController.viewControllers) {
			if ([viewController isKindOfClass:[TopScreenView class]]) {
				// トップ画面情報取得 - PUSH通知(連絡メール)
				TopScreenView *topViewController = (TopScreenView*)viewController;
				if ([_isScreen isEqualToString:CONTACT_LIST]
					|| [_isScreen isEqualToString:CONTACT_DETAIL]) {
					// リスト更新処理
					[topViewController reloadContactListView:siteId];
				}
			}
		}
	}
}

// ADD 2015-07-27
- (void)alert888
{
	exit(0);
}

- (void)alert999
{
	// Contact detail receive notification
	UINavigationController *navigationController = [self.tabBarController.viewControllers objectAtIndex:1];
	BOOL isContactList = NO;
	for (UIViewController *view in navigationController.viewControllers) {
		if([view isKindOfClass:[ContactListView class]]) {
			isContactList = YES;
			[navigationController popToViewController:view animated:NO];
			break;
		}
	}
	if(isContactList == NO) {
		[navigationController popToRootViewControllerAnimated:NO];
	}
	alertStatus = 0;
}

#pragma mark PUSH通知からのアラート表示
- (void)alertEtc
{
	// PUSH通知のuserInfo
	NSArray *allKey = [notificationDic allKeys];
	BOOL isHaveKey = NO;	// メールID有無(YES:あり / NO:なし)
	BOOL isHaveSite = NO;	// 施設ID有無(YES:あり / NO:なし)
	for (NSString* theKey in allKey) {
		if ([theKey isEqualToString:@"rseq"] && ![[notificationDic objectForKey:theKey] isEqualToString:@""]) {
			isHaveKey = YES;	// メールIDあり
		}
		if ([theKey isEqualToString:@"siteid"] && ![[notificationDic objectForKey:theKey] isEqualToString:@""]) {
			isHaveSite = YES;	// 施設IDあり
		}
	}
	NSLog(@"Display button");
	if (type == TYPE_PUSH_REMIND) {
		
		// メール詳細 ADD 2015-10-07
//		siteId = [notificationDic objectForKey:@"siteid"];
//		NSString *rseq = [notificationDic objectForKey:@"rseq"];
//		DBG_LOG(@"Reminder:Mail siteid:%@ rseq:%@", siteId, rseq);
		
		// 連絡メール詳細画面表示	(遷移なし)
		if (isHaveKey && isHaveSite) {
			// メールID & 施設ID あり
			// Select TOP
			[self topPageSelected];
			if ([_isScreen isEqualToString: TOP_SCREEN]
				||[_isScreen isEqualToString:CONTACT_LIST]
				||[_isScreen isEqualToString:CONTACT_DETAIL]
				||[_isScreen isEqualToString:RESEARCH_SCREEN]
				||[_isScreen isEqualToString:WEB_VIEW]
				|| _isScreen.length==0/*アプリ起動*/) {
				// トップ画面表示通知 TopScreenView::showMailWithScheme
				[[NSNotificationCenter defaultCenter] postNotificationName:NSNotificationSchemeToContactDetail object:notificationDic];
			}
		}
	} else
	if (type == TYPE_PUSH_TOP) {
		// PUSH通知からの連絡メール詳細
		// Select TOP
		[self topPageSelected];
		
		// 連絡メール一覧リロード
		// 連絡メール詳細読み込み
		// 画面遷移 トップ画面 => 連絡メール一覧 => 連絡メール詳細
		if (isHaveKey && isHaveSite) {
			// メールID & 施設ID あり
			
			if([_isScreen isEqualToString: TOP_SCREEN]) {
				// トップ画面表示通知 TopScreenView::recievePushTop
				[[NSNotificationCenter defaultCenter] postNotificationName:NSNotificationPushToScreen object:notificationDic];
			}
			else if ([_isScreen isEqualToString:CONTACT_LIST]) {
				// トップ画面表示通知 TopScreenView::recievePushTop
				[[NSNotificationCenter defaultCenter] postNotificationName:NSNotificationPushToScreen object:notificationDic];
			}
			else if([_isScreen isEqualToString:CONTACT_DETAIL]) {
				// トップ画面表示通知 TopScreenView::recievePushTop
				[[NSNotificationCenter defaultCenter] postNotificationName:NSNotificationPushToScreen object:notificationDic];
			}
			else if ([_isScreen isEqualToString:RESEARCH_SCREEN]) {
				// トップ画面表示通知 TopScreenView::recievePushTop
				[[NSNotificationCenter defaultCenter] postNotificationName:NSNotificationPushToScreen object:notificationDic];
				
//				siteId = [notificationDic objectForKey:@"siteid"];
				UINavigationController *navigationController = [self.tabBarController.viewControllers objectAtIndex:1];
				for(UIViewController *viewController in navigationController.viewControllers) {
					if ([viewController isKindOfClass:[TopScreenView class]]) {
						// トップ画面情報があるときは読み込まない
						// トップ画面情報取得 - PUSH通知(連絡メール)
						TopScreenView *topViewController = (TopScreenView*)viewController;
						if ([topViewController isKindOfClass:[TopScreenView class]]) {
//							[topViewController reloadTopData];
							[topViewController reloadWhenNoTopData:siteId];
						}
					}
				}
			}
			else if([_isScreen isEqualToString:WEB_VIEW]) {
				// トップ画面表示通知 TopScreenView::recievePushTop
				[[NSNotificationCenter defaultCenter] postNotificationName:NSNotificationPushToScreen object:notificationDic];
				
//				siteId = [notificationDic objectForKey:@"siteid"];
				UINavigationController *navigationController = [self.tabBarController.viewControllers objectAtIndex:1];
				for(UIViewController *viewController in navigationController.viewControllers) {
					if ([viewController isKindOfClass:[TopScreenView class]])
					{
						// トップ画面情報があるときは読み込まない
						// トップ画面情報取得 - PUSH通知(連絡メール)
						TopScreenView *topViewController = (TopScreenView*)viewController;
						if ([topViewController isKindOfClass:[TopScreenView class]]) {
//							[topViewController reloadTopData];
							[topViewController reloadWhenNoTopData:siteId];
						}
					}
				}
			}
			
			isHaveKey = NO;
			isHaveSite = NO;
		}
	} else if (type == TYPE_PUSH_RESEARCH) {
		if (isHaveKey && isHaveSite) {
			if ([_isScreen isEqualToString:TOP_SCREEN] || self.isTopAppear) {
				[self clickOnListResearchPage:listResearchButton];
			}
			else if ([_isScreen isEqualToString: CONTACT_LIST]) {
				[self clickOnListResearchPage:listResearchButton];
			}
			else if ([_isScreen isEqualToString: RESEARCH_SCREEN]) {
				//[self clickOnListResearchPage:listResearchButton];
			}
			else if([_isScreen isEqualToString:CONTACT_DETAIL])
			{
				[self clickOnListResearchPage:listResearchButton];
			}
			else if([_isScreen isEqualToString: WEB_VIEW])
			{
				[self clickOnListResearchPage:listResearchButton];
			} else if([_isScreen isEqualToString:NEWS_CONTENT]){
				[self clickOnListResearchPage:listResearchButton];
			}
			
			isHaveKey = NO;
			isHaveSite = NO;
		}
		
	} else if (type == TYPE_PUSH_TIMELINE) {
		// Time line
		[self topPageSelected];
		UINavigationController *navigationController = [self.tabBarController.viewControllers objectAtIndex:1];
		for(UIViewController *viewController in navigationController.viewControllers) {
			if ([viewController isKindOfClass:[TopScreenView class]]){
				// トップ画面情報取得
				_pushType = type;	// ADD 2015-10-05
				TopScreenView *topViewController = (TopScreenView*)viewController;
				topViewController.delegate = self;
				[topViewController reloadTopData];
			}
		}
	} else if (type == TYPE_PUSH_NEWS){
		
		UINavigationController *navigationController = [self.tabBarController.viewControllers objectAtIndex:2];
		BaseWebViewController *vc = navigationController.viewControllers[0];
		
		isClickedPushNews = YES;
		
		if (self.tabBarController.selectedIndex == 2) {
			// Dont refresh
			
		} else {
			// Refresh to TOP
			[vc reloadPressed:nil];
		}
		
		[vc getInfoFooterAPI];
		
		[self clickOnQuestion:self.questionButton];
	}
	else {
		[self clickOnTopPage:topButton];
	}
}

#pragma mark - TopScreenViewDelegate
- (void)didReloadFinished
{
	NSLog(@"TOP reload finished");
	if(type == TYPE_PUSH_TIMELINE) {
		// Timeline
		UINavigationController *navigationController = [self.tabBarController.viewControllers objectAtIndex:1];
		for(UIViewController *viewController in navigationController.viewControllers) {
			if ([viewController isKindOfClass:[TopScreenView class]]){
				TopScreenView *topViewController = (TopScreenView*)viewController;
				[topViewController openTimeLineWithSiteId:siteId];
				// release delegate
				topViewController.delegate = nil;
			}
		}
	}
}

- (void)topPageSelected
{
	// Push to TOP
	[topButton setHighlighted:NO];
	[topButton setImage:gImageButtonEmailSelected forState:UIControlStateNormal];
	[listResearchButton setImage:gImageButtonResearchNormal forState:UIControlStateNormal];
	[questionButton setImage:gImageButtonQuestionNormal forState:UIControlStateNormal];
	[infoButton setImage:gImageButtonSettingNormal forState:UIControlStateNormal];
	[self.tabBarController setSelectedIndex:1];
	UINavigationController *navigationConttoller = [self.tabBarController.viewControllers objectAtIndex:1];
	[navigationConttoller popToRootViewControllerAnimated:NO];
}

// Reset status button
- (void)resetAllItems
{
	for (int i = 0; i < _buttonArray.count; i++) {
		UIButton *btn = [_buttonArray objectAtIndex:i];
		
		switch (i) {
			case 0:
				[btn setImage:gImageButtonEmailNormal forState:UIControlStateNormal];
				break;
				
			case 1://
				[btn setImage:gImageButtonQuestionNormal forState:UIControlStateNormal];
				break;
				
			case 2:
				[btn setImage:gImageButtonResearchNormal forState:UIControlStateNormal];
				break;
				
			case 3:
				[btn setImage:gImageButtonSettingNormal forState:UIControlStateNormal];
				break;
				
			default:
				break;
		}
	}
}
#pragma mark - ポップアップ画面
// 共通ポップアップ(まちプレ/クエスチョン)	ADD 2015-10-06
- (void)showCommonPopup:(NSString*)url delegate:(id)delegate
{
	CommonPopupViewController *popup = [[CommonPopupViewController alloc] init];
	popup.delegate = delegate;
	popup.url = [url copy];
//	popup.link = [link copy];
	UITabBarController* tabCon = self.tabBarController;
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
		// iOS8 and later
		popup.modalPresentationStyle = UIModalPresentationOverCurrentContext;
		tabCon.modalPresentationStyle = UIModalPresentationOverCurrentContext;
	} else {
		// iOS7
		popup.modalPresentationStyle = UIModalPresentationCurrentContext;
		tabCon.modalPresentationStyle = UIModalPresentationCurrentContext;
	}
	[tabCon presentViewController:popup animated:YES completion:nil];
}

@end
