//
//  BaseWebViewController.m(まちプレ)
//  Machicomi
//
//  Created by admin on 4/2/15.
//  Copyright (c) 2015 Phan Quang Hoang. All rights reserved.
//

//#import <GoogleMobileAds/GoogleMobileAds.h>
#import <YJADSDK/YJADBannerView.h>

#import "BaseWebViewController.h"
#import "AppDelegate.h"
//#import "JSONKit.h"	DELETE 2016-01-14

#import "NJKWebViewProgressView.h"
#import "NJKWebViewProgress.h"

// DELETE 2015-06-17 No Use NJKWebViewProgressDelegate
@interface BaseWebViewController () <UIWebViewDelegate, YJADBannerViewDelegate /*,NJKWebViewProgressDelegate*/>
{
	NSTimer *timer;
	NSTimer *loadingTimer;
	
	BOOL isPushNews;
}

// バナー広告(Yahoo)	ADD 2015-11-24
@property (strong, nonatomic) YJADBannerView *adView;

@property (strong, nonatomic) NSArray    *oneLoadingItems;
@property (strong, nonatomic) NSArray    *oneFinishedItems;
@property (strong, nonatomic) NSArray    *buttonLoadingItems;
@property (strong, nonatomic) NSArray    *buttonFinshedItems;
@property (strong, nonatomic) UIBarButtonItem   *fixedSpace;
@property (copy, nonatomic) NSString *newsId;
@property (strong, nonatomic) IBOutlet UIButton *backFloatButton;
//@property (strong, nonatomic) IBOutlet GADBannerView *adMobView;

- (void)backView:(id)sender;
- (IBAction)onBackFloatButton:(id)sender;

@end

@implementation BaseWebViewController
{
	BOOL isLinkClicked;
	BOOL isFinishedLoading;
	BOOL isLoadingWebView_;
//	BOOL isFirtLoad;
	
	int  webViewLoads_;
	int countLink;
	
	NSString *_currentLink;
	ASIFormDataRequest *_request;
	
	NJKWebViewProgressView *_progressView;
//	NJKWebViewProgress *_progressProxy;
}

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view.
	
	self.oneLoadingItems    = @[self.closeButtonItem];
	self.oneFinishedItems   = @[self.reloadButtonItem];
	self.buttonLoadingItems = @[self.shareButtonItem, self.fixedSpace, self.closeButtonItem];
	self.buttonFinshedItems = @[self.shareButtonItem, self.fixedSpace, self.reloadButtonItem];
	
	// MODIFY 2015-06-12 systemVersion => NSFoundationVersionNumber
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
//	if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
		// Set title attribute
		NSDictionary *textAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
										[UIColor blackColor],
										NSForegroundColorAttributeName,
										[UIFont boldSystemFontOfSize:17.0f], NSFontAttributeName, nil];
		self.navigationController.navigationBar.titleTextAttributes = textAttributes;
//	} else {
//		NSDictionary *textTitleOptions = [NSDictionary dictionaryWithObjectsAndKeys:
//										  [UIColor blackColor], UITextAttributeTextColor,
//										  [UIFont boldSystemFontOfSize:17.0f], UITextAttributeFont, nil];
//
//		[self.navigationController.navigationBar setTitleTextAttributes:textTitleOptions];
	}

//    _progressProxy = [[NJKWebViewProgress alloc] init];
//    _webView.delegate = _progressProxy;
//    _progressProxy.webViewProxyDelegate = self;
//    _progressProxy.progressDelegate = self;
//    
//    CGFloat progressBarHeight = 2.f;
//    CGRect navigaitonBarBounds = self.navigationController.navigationBar.bounds;
//    CGRect barFrame = CGRectMake(0, navigaitonBarBounds.size.height - progressBarHeight, navigaitonBarBounds.size.width, progressBarHeight);
//    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
//    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
	
	//self.navigationItem.leftBarButtonItem = self.backButtonItem;
	self.navigationItem.rightBarButtonItems = self.oneFinishedItems;
	
	[self.navigationController.navigationBar setTranslucent:NO];
	
	UISwipeGestureRecognizer * swiperight=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swiperight:)];
	swiperight.direction=UISwipeGestureRecognizerDirectionRight;
	[self.view addGestureRecognizer:swiperight];
	
	[self.view addSubview:self.webView];
	
	countLink = 0;
	_currentLink = URL_WEB_NEWS;
	//[self loadWebViewWithURL:URL_WEB_NEWS];

	// バナー広告(Yahoo)	MODIFY 2015-11-24
	_adView = [[YJADBannerView alloc] initWithAdUnitID:YDN_UNITID_NEWS delegate:self];
	_adView.frame = CGRectMake((SCREEN_MIN_LENGTH-YDN_SIZE_W)/2.f, 0, YDN_SIZE_W, YDN_SIZE_H);
//	_adView.test = YES;
	[_adView loadAd:nil];
	[self.view addSubview:_adView];
//	// AdMobバナー	ADD 2015-09-25
//	_adMobView = [_adMobView initWithAdSize:kGADAdSizeSmartBannerPortrait origin:CGPointMake(0, 0)];
//	_adMobView.adUnitID = ADMOB_UNITID_NEWS;
//	_adMobView.rootViewController = self;
//	[_adMobView loadRequest:[GADRequest request]];
}

// AdMobバナー表示	ADD 2015-09-25
- (void)showAdMob
{
	// AdMobバナー表示	ADD 2015-09-24
	int mobflg_p = [[[NSUserDefaults standardUserDefaults] objectForKey:NSUserDefaultMobflgNews] intValue];

	// バナー広告(Yahoo)	MODIFY 2015-11-24
	_adView.hidden = (mobflg_p==1)? NO: YES;
//	_adMobView.hidden = (mobflg_p==1)? NO: YES;
	
	[self showAdMobOnTop];
}

// AdMobバナー表示(まちプレトップ画面のみ)
- (void)showAdMobOnTop
{
	// まちプレトップ画面のみAdMob表示
	// まちプレTOP画面チェック	ADD 2015-10-05
	NSString *urlStr = [[_webView.request URL] absoluteString];
//	DBG_LOG(@"request:%@", urlStr);

	int mobflg_p = [[[NSUserDefaults standardUserDefaults] objectForKey:NSUserDefaultMobflgNews] intValue];
	// バナー広告(Yahoo)	MODIFY 2015-11-24
	if (urlStr.length > 0 && [urlStr rangeOfString:URL_WEB_NEWS_TOP].location != NSNotFound) {
		// トップ画面
//		_adView.hidden = NO;
		_adView.hidden = (mobflg_p==1)? NO: YES;
	} else {
		_adView.hidden = (_webView.canGoBack||mobflg_p!=1)? YES: NO;
	}
//	if (urlStr.length > 0 && [urlStr rangeOfString:URL_WEB_NEWS_TOP].location != NSNotFound) {
//		// トップ画面
//		_adMobView.hidden = NO;
//	} else {
//		_adMobView.hidden = (_webView.canGoBack)? YES: NO;
//	}
	[self resizeSubView];
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	[self appDelegate].isScreen = NEWS_CONTENT;
	[self.navigationController.navigationBar addSubview:_progressView];
}

- (void)viewDidAppear:(BOOL)animated
{
	[super viewDidAppear:animated];
	
	// AdMobバナー表示	ADD 2015-09-25
	[self showAdMob];

//	[self resizeSubView];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
	
	[SVProgressHUD dismiss];
	[timer invalidate];
	timer = nil;
	webViewLoads_ = 0;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
	// Get the new view controller using [segue destinationViewController].
	// Pass the selected object to the new view controller.
}
*/

- (AppDelegate*)appDelegate
{
	return (AppDelegate*)[UIApplication sharedApplication].delegate;
}

#pragma mark Getter
- (UIWebView*)webView
{
	if (!_webView) {
		_webView = [[UIWebView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) - 52.0f - 2.0f)];
		DBG_LOG(@"w %f h %f",CGRectGetWidth(self.view.frame),CGRectGetHeight(self.view.frame) - 52.0f - 2.0f);
		_webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

		// 既存BUG修正	ADD 2015-07-22 
		_webView.scalesPageToFit = YES;

		_webView.delegate = self;
	}
	return _webView;
}

- (UIBarButtonItem*)fixedSpace
{
	if (!_fixedSpace) {
		_fixedSpace = [[UIBarButtonItem alloc]
					  initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
					  target:nil
					  action:nil];
		[_fixedSpace setWidth:15];
	}
	return _fixedSpace;
}

- (UIBarButtonItem*)reloadButtonItem
{
	if (!_reloadButtonItem) {
		UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
		[button setFrame:CGRectMake(0.0f, 0.0f, 23.0f, 26.0f)];
		[button setImage:gImageReloadGroup forState:UIControlStateNormal];
		[button setImage:gImageReloadGroupHighlight forState:UIControlStateSelected];
		[button setImage:gImageReloadGroupHighlight forState:UIControlStateHighlighted];
		
		[button addTarget:self action:@selector(reloadPressed:) forControlEvents:UIControlEventTouchUpInside];
		_reloadButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
	}
	return _reloadButtonItem;
}

- (UIBarButtonItem*)backButtonItem
{
	if (!_backButtonItem) {
		UIButton *backButton = [[UIButton alloc] init];
		
		[backButton setImage:gImageHeaderBack forState:UIControlStateNormal];
		[backButton setImage:gImageHeaderBackHighlight forState:UIControlStateHighlighted];
		[backButton setImage:gImageHeaderBackHighlight forState:UIControlStateSelected];
		[backButton addTarget:self action:@selector(backView:) forControlEvents:UIControlEventTouchUpInside];
		[backButton setFrame:CGRectMake(0, 0, 50.0f, 20.0f)];
		
		// MODIFY 2015-06-12 systemVersion => NSFoundationVersionNumber
		if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
//		if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
			_backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
			UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
											   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
											   target:nil action:nil];
			negativeSpacer.width = -8;// it was -6 in iOS 6
			[self.navigationItem setLeftBarButtonItems:[NSArray arrayWithObjects:negativeSpacer, _backButtonItem, nil] animated:NO];
			
			
			// Set title attribute
			NSDictionary *textAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
											[UIColor blackColor],
											NSForegroundColorAttributeName,
											[UIFont boldSystemFontOfSize:17.0f], NSFontAttributeName, nil];
			self.navigationController.navigationBar.titleTextAttributes = textAttributes;
//		} else {
//			_backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
//			self.navigationItem.leftBarButtonItem = _backButtonItem;
//			
//			NSDictionary *textTitleOptions = [NSDictionary dictionaryWithObjectsAndKeys:
//											  [UIColor blackColor], UITextAttributeTextColor,
//											  [UIFont boldSystemFontOfSize:17.0f], UITextAttributeFont, nil];
//
//			[self.navigationController.navigationBar setTitleTextAttributes:textTitleOptions];
		}
	}
	return _backButtonItem;
}

- (UIBarButtonItem*)closeButtonItem
{
	if (!_closeButtonItem) {
		UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
		[button setFrame:CGRectMake(0.0f, 0.0f, 16.0f, 26.0f)];
		[button setImage:gImageCloseNormal forState:UIControlStateNormal];
		[button setImage:gImageCloseHighlight forState:UIControlStateSelected];
		[button setImage:gImageCloseHighlight forState:UIControlStateHighlighted];
		
		[button addTarget:self action:@selector(closePressed:) forControlEvents:UIControlEventTouchUpInside];
		_closeButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
	}
	return _closeButtonItem;
}

- (UIBarButtonItem*)shareButtonItem
{
	if (!_shareButtonItem) {
		UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
		[button setFrame:CGRectMake(0.0f, 0.0f, 19.0f, 26.0f)];
		[button setImage:gImageShareNormal forState:UIControlStateNormal];
		[button setImage:gImageShareHighlight forState:UIControlStateSelected];
		[button setImage:gImageShareHighlight forState:UIControlStateHighlighted];
		
		[button addTarget:self action:@selector(sharePressed:) forControlEvents:UIControlEventTouchUpInside];

		_shareButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
	}
	return _shareButtonItem;
}

- (void)loadWebViewWithURL:(NSString*)url
{
	// Remove cache
	NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
	for (NSHTTPCookie *cookie in [storage cookies]) {
		[storage deleteCookie:cookie];
	}
	[[NSUserDefaults standardUserDefaults] synchronize];
	
	
	// Clear cache
	[self.webView removeFromSuperview];
	self.webView = nil;
	isPushNews = NO;
	webViewLoads_ = 0;
	self.navigationItem.leftBarButtonItem = nil;
	
	NSURL *urlRequest = [NSURL URLWithString:url];
	NSMutableURLRequest *requestObj = [NSMutableURLRequest requestWithURL:urlRequest cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
	[requestObj setHTTPMethod:@"POST"];
	NSString *body = [NSString stringWithFormat:@"hostid=%@", [self appDelegate].hostId];
	[requestObj setHTTPBody:[body dataUsingEncoding: NSUTF8StringEncoding]];
 
	[self.webView loadRequest:requestObj];
	[[NSURLCache sharedURLCache] removeCachedResponseForRequest:requestObj];
	
	[self.view addSubview:self.webView];

	// ADD 2015-11-27
	if (!_webView.canGoBack) {
		[self getInfoFooterAPI];
	}
//	// AdMobバナー表示	ADD 2015-09-25
//	[self showAdMob];
}

// フローティング・バックボタン位置計算	ADD 2015-07-22
- (CGRect)makeBackFloatButtonPoint:(CGRect)webFrame button:(CGRect)btnFrame
{
	CGRect frame = btnFrame;
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
		// iOS8 and later
		frame.origin = CGPointMake(16.f, webFrame.size.height - btnFrame.size.height - 16.f - 44.f);
	} else {
		frame.origin = CGPointMake(16.f, webFrame.size.height - btnFrame.size.height - 16.f - 44.f);
	}
	
	return frame;
}

- (void)loadWebViewWithURL:(NSString*)url newsId:(NSString*)newsId
{
	_newsId = [newsId copy];
	
	if (gIsPushNews) {
		isPushNews = YES;  
	}
	
	webViewLoads_ = 0;
	
	NSString *stringURL = [NSString stringWithFormat:@"%@?newsid=%@",url, _newsId];
	NSURL *urlRequest = [NSURL URLWithString:stringURL];
	
	NSMutableURLRequest *requestObj = [NSMutableURLRequest requestWithURL:urlRequest cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
	
	[requestObj setHTTPMethod:@"POST"];
	NSString *body = [NSString stringWithFormat:@"hostid=%@", [self appDelegate].hostId];
	[requestObj setHTTPBody:[body dataUsingEncoding: NSUTF8StringEncoding]];
	
	[self.webView loadRequest:requestObj];
	
	// Remove cache
	[[NSURLCache sharedURLCache] removeCachedResponseForRequest:requestObj];
	for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
		[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
	}
	// ADD 2015-11-27
	if (!_webView.canGoBack) {
		[self getInfoFooterAPI];
	}
}

- (void)loadingWeb:(BOOL)isLoading
{
	if ( ! _webView.canGoBack) {
		// まちプレトップ画面
	}
	if (isLoading) {
		
		if ( ! _webView.canGoBack) {
			// まちプレトップ画面
			self.navigationItem.rightBarButtonItems = self.oneLoadingItems;
		} else
		if (isLinkClicked || isPushNews) {
			self.navigationItem.rightBarButtonItems = self.buttonLoadingItems;
		} else {
			self.navigationItem.rightBarButtonItems = self.oneLoadingItems;
		}
		
	} else {
		if ( ! _webView.canGoBack) {
			// まちプレトップ画面
			self.navigationItem.rightBarButtonItems = self.oneFinishedItems;
		} else
		if (isLinkClicked || isPushNews) {
			self.navigationItem.rightBarButtonItems = self.buttonFinshedItems;
		} else {
			self.navigationItem.rightBarButtonItems = self.oneFinishedItems;
			//[self removeWebHistory];
		}
	}
}

-(void)swiperight:(UISwipeGestureRecognizer*)gestureRecognizer
{
	if ([self.webView canGoBack]) {
		[self.webView goBack];
	}
}

- (void)showWarningMessage
{
	[[self appDelegate] alertWithViewController:self title:ERROR_TITLE message:ERROR_MESSAGE completion:^{
		if ( ! [[self appDelegate] isOffline]) {
			[SVProgressHUD dismiss];
		}
	}];
//	// iOS8対応	MODIFY 2015-06-24
//	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
//		// iOS8 and later
//		UIAlertController *alertController = [UIAlertController alertControllerWithTitle:ERROR_TITLE message:ERROR_MESSAGE preferredStyle:UIAlertControllerStyleAlert];
//		// addActionした順に左から右にボタンが配置されます
//		[alertController addAction:[UIAlertAction actionWithTitle:OK_MESSAGE style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//			ConnectionManager *connectManager = [[ConnectionManager alloc] init];
//			if ([connectManager isConnectNetwork]) {
//				[SVProgressHUD dismiss];
//			}
//		}]];
//		[self presentViewController:alertController animated:YES completion:nil];
//	} else {
//		// iOS7 and earlier
//		[UIAlertView showWithTitle:ERROR_TITLE message:ERROR_MESSAGE cancelButtonTitle:OK_MESSAGE otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
//			ConnectionManager *connectManager = [[ConnectionManager alloc] init];
//			if (buttonIndex == 0) {
//				if ([connectManager isConnectNetwork]) {
//					[SVProgressHUD dismiss];
//				}
//			}
//		}];
//	}
}

#pragma mark Action button
- (void)backView:(id)sender
{
	DBG_METHOD;
	if (!isFinishedLoading) {
		NSLog(@"isFinishedLoading");
		//return;
	}
	
	// タイムアウト解除	ADD 2015-10-09
	[[self appDelegate] clearTimeout];

	if ([self.webView canGoBack]) {
		NSLog(@"canGoBack");
		
		webViewLoads_ = 0;
		countLink = 0;
		
		isFinishedLoading = NO;
		[self.webView goBack];
	} else if (isPushNews) {
		isPushNews = NO;
		[self loadWebViewWithURL:URL_WEB_NEWS];
	}
	// ADD 2015-11-27
	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 500 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{
		if (!_webView.canGoBack) {
			[self getInfoFooterAPI];
		}
	});
}

- (IBAction)onBackFloatButton:(id)sender {
	DBG_METHOD;
	[self backView:sender];
}

- (void)removeWebHistory
{
	[self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"if( window.history.length > 1 ) { window.history.go( -( window.history.length - 1 ) ) };"]];
}

- (void)reloadPressed:(id)sender
{
	// タイムアウト解除	ADD 2015-10-09
	[[self appDelegate] clearTimeout];

	webViewLoads_ = 0;

	// MODIFY 2015-09-29
	if (_newsId.length==0) {
		[self.webView reload];
	} else {
		if (!isLinkClicked) {
			//[self removeWebHistory];
			[self.webView reload];
		} else {
			[self loadWebViewWithURL:_currentLink newsId:_newsId];
		}
	}
//	if (!isLinkClicked) {
//		//[self removeWebHistory];
//		[self.webView reload];
//	} else {
//		[self loadWebViewWithURL:_currentLink newsId:_newsId];
//	}
	// ADD 2015-11-27
	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 500 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{
		if (!_webView.canGoBack) {
			[self getInfoFooterAPI];
		}
	});
}

#pragma mark 共有ボタン
- (void)sharePressed:(id)sender
{
	// 仕様変更 DELETE 2015-09-29
//	if (!isFinishedLoading) {
//		return;
//	}
	
	NSString *copyStringverse= _currentLink;
	
	NSMutableArray *shareItems = [NSMutableArray new];
	[shareItems addObject: copyStringverse];
	NSMutableArray *active = [NSMutableArray array];
	[active addObject:UIActivityTypePostToFacebook];
	[active addObject:UIActivityTypePostToTwitter];
	UIActivityViewController *shareController =
	[[UIActivityViewController alloc] initWithActivityItems: shareItems applicationActivities:nil];
	
	[self presentViewController:shareController animated:YES completion:^{
		
	}];
}

#pragma mark まちプレトップ画面の読み込み停止✖️ボタン
- (void)closePressed:(id)sender
{
	[self.webView stopLoading];
	[self loadingWeb:NO];
	[SVProgressHUD dismiss];

	// BACKボタン表示 ADD 2015-09-29
	[self showBackButton:_webView.canGoBack];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	countLink = 0;
	isFinishedLoading = YES;
	
	// ADD 2015-09-29
	[self loadingWeb:NO];
}

#pragma mark Webview delegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
	// Remove cache
//	[[NSURLCache sharedURLCache] removeCachedResponseForRequest:request];
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
		// iOS8系
		/*
		 こっちでもキャッシュクリアができた
		 [[NSURLCache sharedURLCache] removeCachedResponseForRequest:request];
		 */
		[[NSURLCache sharedURLCache] removeAllCachedResponses];
	}
	else if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
		// iOS7系
		[NSURLCache sharedURLCache].memoryCapacity = 0;
		[NSURLCache sharedURLCache].diskCapacity = 0;
		[[NSURLCache sharedURLCache] removeAllCachedResponses];
		[[NSURLCache sharedURLCache] removeCachedResponseForRequest:request];
	} else {
		// iOS6系
		[[NSURLCache sharedURLCache] removeAllCachedResponses];
	}

	if (navigationType == UIWebViewNavigationTypeLinkClicked
		|| navigationType==UIWebViewNavigationTypeFormSubmitted /*ADD 2015-09-14*/) {

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

		// ADD 2015-09-09
		if ( ! [[self appDelegate] isOnlineAndAlert:self]) {
			// OFFLINE
			return NO;
		}
		
		webViewLoads_ = 0;
		countLink = 0;
		isLinkClicked = YES;
		
		_currentLink = [request.URL absoluteString];
		DBG_METHOD_LINE;
		DBG_LOG(@"isLinkClicked = YES:%@", _currentLink);
	}
	
	if ([[[request URL] absoluteString] rangeOfString:URL_WEB_NEWS].location != NSNotFound) {
		isLinkClicked = NO;
		DBG_METHOD_LINE;
	}
	
	// 開始時の制御する必要なし DELETE 2015-10-01
//	// BACKボタン表示 MODIFY 2015-09-29
//	if ((isLinkClicked && [webView canGoBack]) || isPushNews) {
//		[self showBackButton:YES];
////		self.navigationItem.leftBarButtonItem = self.backButtonItem;
//	} else {
//		[self showBackButton:NO];
////		self.navigationItem.leftBarButtonItem = nil;
//	}

	// 仕様追加：外部ブラウザを開く	ADD 2015-11-17
	if (isLinkClicked) {
		NSString *stringBody = [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding];
		if([stringBody rangeOfString:@"dbrowser"].location != NSNotFound) {
			[[UIApplication sharedApplication] openURL:[NSURL URLWithString:_currentLink]];
			return NO;
		}
		
		@try {
			NSString *urlString = [[_currentLink componentsSeparatedByString:@"?"] objectAtIndex:1];
			
			if(urlString == nil)
				urlString = @"";
			
			if([urlString rangeOfString:@"dbrowser"].location != NSNotFound) {
				urlString = [[request URL] absoluteString];
				urlString = [urlString stringByReplacingOccurrencesOfString:@"dbrowser&" withString:@""];
				urlString = [urlString stringByReplacingOccurrencesOfString:@"&dbrowser" withString:@""];
				urlString = [urlString stringByReplacingOccurrencesOfString:@"?dbrowser" withString:@""];
				[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
				return NO;
			}
		}
		@catch (NSException *exception) {
			//
		}
	}
	
	return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
	isFinishedLoading = NO;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (!_webView.canGoBack) {
		isLinkClicked = NO;
		DBG_METHOD_LINE;
	}
	
	// BACKボタン表示 MODIFY 2015-09-29
//	[self showBackButton:_webView.canGoBack];	// test
	if (isLinkClicked || isPushNews) {
		[self showBackButton:YES];
//		self.navigationItem.leftBarButtonItem = self.backButtonItem;
//		// フローティング・バックボタン	ADD 2015-07-22
//		_backFloatButton.hidden = NO;
//		[_backFloatButton removeFromSuperview];
//		_backFloatButton.frame = [self makeBackFloatButtonPoint:self.webView.frame button:_backFloatButton.frame];
//		[self.view addSubview:_backFloatButton];
	} else {
		[self showBackButton:NO];
//		self.navigationItem.leftBarButtonItem = nil;
//		// フローティング・バックボタン	ADD 2015-07-22
//		_backFloatButton.hidden = YES;
	}
	
	[self loadingWeb:YES];
	
//    NSLog(@"isFinishedLoading = NO");
//    NSLog(@"Request %@",[webView.request.URL absoluteString]);
	
	isLoadingWebView_ = YES;
	
	if (webViewLoads_ == 0) {
		[SVProgressHUD show];
		[self loadingWeb:YES];
		
		[timer invalidate];
		timer = nil;
		timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(webViewActuallyFinished) userInfo:nil repeats:NO];
	}
	
	webViewLoads_++;
	countLink++;
}

// BACKボタン表示 ADD 2015-09-29
- (void)showBackButton:(BOOL)bShow
{
	if (bShow) {
		self.navigationItem.leftBarButtonItem = self.backButtonItem;
		// フローティング・バックボタン	ADD 2015-07-22
		_backFloatButton.hidden = NO;
		[_backFloatButton removeFromSuperview];
		_backFloatButton.frame = [self makeBackFloatButtonPoint:self.webView.frame button:_backFloatButton.frame];
		[self.view addSubview:_backFloatButton];
	} else {
		self.navigationItem.leftBarButtonItem = nil;
		// フローティング・バックボタン	ADD 2015-07-22
		_backFloatButton.hidden = YES;
	}
	// AdMov表示
	[self showAdMobOnTop];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//    webViewLoads_--;
	
	NSLog(@"LINK %@",[[_webView.request URL] absoluteString]);
	// BACKボタン表示 MODIFY 2015-09-29
	if (isLinkClicked || isPushNews) {
		[self showBackButton:YES];
	} else {
		[self showBackButton:NO];
	}
//	[self showBackButton:_webView.canGoBack];
//	if (_webView.canGoBack) {
//		self.navigationItem.leftBarButtonItem = self.backButtonItem;
//		// フローティング・バックボタン	ADD 2015-07-22
//		_backFloatButton.hidden = NO;
//		[_backFloatButton removeFromSuperview];
//		_backFloatButton.frame = [self makeBackFloatButtonPoint:self.webView.frame button:_backFloatButton.frame];
//		[self.view addSubview:_backFloatButton];
//	} else {
//		self.navigationItem.leftBarButtonItem = nil;
//		// フローティング・バックボタン	ADD 2015-07-22
//		_backFloatButton.hidden = YES;
//	}

	[timer invalidate];
	timer = nil;
	
	loadingTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerLoadingFinish) userInfo:nil repeats:NO];

	[self webViewActuallyFinished];
}

- (void)timerLoadingFinish
{
	// ADD 2015-09-29
	if (countLink <= 0) {
		return;
	}

	countLink--;
	DBG_LOG(@"countLink %zd",countLink);
	
	if (!_webView.canGoBack) {
		isLinkClicked = NO;
		DBG_METHOD_LINE;
	}
	
	if ([[[_webView.request URL] absoluteString] rangeOfString:URL_WEB_NEWS].location != NSNotFound) {
		isLinkClicked = NO;
		isPushNews = NO;
		DBG_METHOD_LINE;
		DBG_LOG(@"-> %@", [[_webView.request URL] absoluteString]);
	}
	
	if (countLink > 0) {
		return;
	}
	
	countLink = 0;
	
	[loadingTimer invalidate];
	loadingTimer = nil;
	
	// UIWebView object has fully loaded.
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	NSLog(@"LINK %@",[[_webView.request URL] absoluteString]);
	
	NSString *theTitle = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
	self.navigationItem.title = theTitle;
	_currentLink = [self.webView stringByEvaluatingJavaScriptFromString:@"window.location.href"];
	
	isFinishedLoading = YES;
	isLoadingWebView_ = YES;
	
	// BACKボタン表示 MODIFY 2015-09-29
//	[self showBackButton:_webView.canGoBack];	// test
	if (isLinkClicked || isPushNews) {
		[self showBackButton:YES];
//		self.navigationItem.leftBarButtonItem = self.backButtonItem;
	} else {
		[self showBackButton:NO];
//		self.navigationItem.leftBarButtonItem = nil;
	}
	
	[self loadingWeb:NO];
}

- (void)webViewActuallyFinished
{
//    NSLog(@"Did finished %d", webViewLoads_);
//    if (webViewLoads_ > 0) {
//        return;
//    }
	
//    webViewLoads_ = 0;

	NSString *theTitle = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
	self.navigationItem.title = theTitle;
	
	[SVProgressHUD dismiss];
}

- (void)webView:(UIWebView*)webView didFailLoadWithError:(NSError*)error {
//    webViewLoads_--;
	countLink--;
	
	[SVProgressHUD dismiss];

//	if ([timer isValid]) {
//		[timer invalidate];
//	}
//	timer = nil;
	if ([loadingTimer isValid]) {
		[loadingTimer invalidate];
	}
	loadingTimer = nil;
	
	isFinishedLoading = YES;
	
	if (countLink == 0) {
		// BACKボタン表示 ADD 2015-09-29
		[self showBackButton:_webView.canGoBack];
		[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
		[self loadingWeb:NO];
	}

	DBG_LOG(@"error:%zd",error.code);
	// ADD 2015-07-27
	if (error.code == NSURLErrorTimedOut) {
		dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
			// タイムアウトメッセージ	MODIFY 2015-09-14
			[[self appDelegate] alertTimeout:self completion:^{
				AppDelegate *delegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
				[delegate.topButton sendActionsForControlEvents:UIControlEventTouchUpInside];
			}];
//			[self showTimeOutMessage];
		});
	}
}
//// ADD 2015-07-27
//- (void)showTimeOutMessage
//{
//	// iOS8対応	MODIFY 2015-06-24
//	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
//		// iOS8 and later
//		UIAlertController *alertController = [UIAlertController alertControllerWithTitle:ALERT_TITLE message:TIMEOUT_MESSAGE preferredStyle:UIAlertControllerStyleAlert];
//		// addActionした順に左から右にボタンが配置されます
//		[alertController addAction:[UIAlertAction actionWithTitle:OK_MESSAGE style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//			AppDelegate *delegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
//			[delegate.topButton sendActionsForControlEvents:UIControlEventTouchUpInside];
//		}]];
//		[self presentViewController:alertController animated:YES completion:nil];
//	} else {
//		// iOS7 and earlier
//		[UIAlertView showWithTitle:ALERT_TITLE message:TIMEOUT_MESSAGE cancelButtonTitle:OK_MESSAGE otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
//			AppDelegate *delegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
//			[delegate.topButton sendActionsForControlEvents:UIControlEventTouchUpInside];
//		}];
//	}
//}

/* Update layout */
- (void)resizeSubView
{
	CGFloat navHeight = [self.navigationController.navigationBar frame].size.height;
	CGFloat tabHeight = (self.tabBarController.tabBar.frame.size.height + 0);
	CGFloat stsHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
	CGRect rect = _webView.frame;
	// MODIFY 2015-06-12 systemVersion => NSFoundationVersionNumber
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
//	if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")){
//		rect.size.height = SIZE_HEIGHT - 52.0f - 15.0f;
		rect.size.height = SIZE_HEIGHT - navHeight - tabHeight - stsHeight;
//	} else {
//		rect.size.height = SIZE_HEIGHT - 20 - 52 - 44;
	}
	// バナー広告(Yahoo)	MODIFY 2015-11-24
	if ( ! _adView.hidden) {
		rect.size.height -= CGRectGetHeight(_adView.frame);
		CGRect frame = _adView.frame;
		frame.origin.y = rect.origin.y + rect.size.height;
		_adView.frame = frame;
	}
//	// バナー広告表示(AdMob)	ADD 2015-09-24
//	if ( ! _adMobView.hidden) {
//		rect.size.height -= _adMobView.frame.size.height;
//		CGRect frame = _adMobView.frame;
//		frame.origin.y = rect.origin.y + rect.size.height;
//		_adMobView.frame = frame;
//	}
	_webView.frame = rect;
}

// ステータスバースタイル iOS9対応	ADD 2016-01-13
- (UIStatusBarStyle)preferredStatusBarStyle
{
	return [self appDelegate].statusBarStyle;
}

#pragma mark - Data loading
/* Footer */
- (void)getInfoFooterAPI // api 3-9
{
	ConnectionManager *connectManager = [[ConnectionManager alloc] init];
	if ([connectManager isConnectNetwork]) {
		// Apply GetFooterAPI
		NSString *urlAsString = GetFooterAPI;
		NSLog(@"WebAPI:%@", urlAsString);		
		NSURL *url = [NSURL URLWithString:urlAsString];
		
		_request = [ASIFormDataRequest requestWithURL:url];
		[_request addRequestHeader:@"User-Agent" value:[self appDelegate].userAgent];
		[_request setTimeOutSeconds:10.0];
		[_request addPostValue:[self appDelegate].keyId forKey:@"keyid"];
		[_request addPostValue:[self appDelegate].hostId forKey:@"hostid"];
		[_request setDelegate:self];
		[_request startAsynchronous];
		
	}else {
		// MODIFY 2015-09-14
		[[self appDelegate] alertOffline:self completion:^{
			[SVProgressHUD dismiss];
		}];
//		// iOS8対応	MODIFY 2015-06-24
//		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) {
//				[SVProgressHUD dismiss];
//			}]];
//			[self 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) {
//				[SVProgressHUD dismiss];
//			}];
//		}
	}
}

#pragma mark- ASIHTTPRequestDelegate
/* request finish */
- (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(@"FOOTER %@", resultsArray);
	
	NSArray *keyResult = [resultsArray allKeys];
	if ([[keyResult objectAtIndex:0] isEqualToString:@"error"]) {
		for (int i = 0; i < [keyResult count]; i++) {
			NSDictionary *error = [resultsArray objectForKey:[keyResult objectAtIndex:i]];
			int resultError = [[error objectForKey:@"code"] intValue];
			if (resultError == 902) {
				// todo something
			}
			if (resultError == 903) {
				// todo something
			}
			[self showWarningMessage];
		}
	} else {
		
		int answerCount = [[resultsArray objectForKey:@"answercount"] intValue];
		int readCount = [[resultsArray objectForKey:@"readcount"] intValue];
		int newsCount = [[resultsArray objectForKey:@"newscount"] intValue];
		int infoCount = [[resultsArray objectForKey:@"infocount"] intValue];
		// AdMobバナー表示フラグ	ADD 2015-09-24
		int mobflg_p = [[resultsArray objectForKey:@"mobflg_p"] intValue];//まちプレTOP(1:表示)
		int mobflg_s = [[resultsArray objectForKey:@"mobflg_s"] intValue];//設定TOP(1:表示)
		
		[self displayBagdeNumber:readCount researchBadge:answerCount
					   newsBadge:newsCount settingBadge:infoCount
		 				mobflgNews:mobflg_p mobflgSettings:mobflg_s];
	}
}

// Display badge number
- (void)displayBagdeNumber:(int)topBadge
			 researchBadge:(int)researchBadge
				 newsBadge:(int)newsBadge
			  settingBadge:(int)settingBadge
				mobflgNews:(int)mobflg_p
			mobflgSettings:(int)mobflg_s
{
	if (topBadge >= 0) {
		if (topBadge == 0) {
			[self appDelegate].readcountButon.hidden = YES;
		}else {
			[self appDelegate].readcountButon.hidden = NO;
			[[self appDelegate].readcountButon setTitle:[NSString stringWithFormat:@"%d", topBadge] forState:UIControlStateNormal];
		}
	} else {
		topBadge = 0;
		[self appDelegate].readcountButon.hidden = YES;
	}
	if (researchBadge >= 0) {
		if (researchBadge == 0) {
			[self appDelegate].answercountButon.hidden = YES;
		} else {
			[self appDelegate].answercountButon.hidden = NO;
			[[self appDelegate].answercountButon setTitle:[NSString stringWithFormat:@"%d", researchBadge] forState:UIControlStateNormal];
		}
	} else {
		researchBadge = 0;
		[self appDelegate].answercountButon.hidden = YES;
	}
	
	// [>] -> [>=] BUG MODIFY 2015-12-11
	if (newsBadge >= 0) {
		if (newsBadge == 0) {
			[self appDelegate].questionCountButon.hidden = YES;
		}
		else {
			
			[[self appDelegate].questionCountButon setTitle:[NSString stringWithFormat:@"%d", newsBadge] forState:UIControlStateNormal];
			[self appDelegate].questionCountButon.hidden = NO;
		}
	} else {
		newsBadge = 0;
		[self appDelegate].questionCountButon.hidden = YES;
	}
	
	if(settingBadge >=0) {
		if (settingBadge == 0) {
			[self appDelegate].infocountButton.hidden = YES;
		}
		else {
			
			[[self appDelegate].infocountButton setTitle:[NSString stringWithFormat:@"%d", settingBadge] forState:UIControlStateNormal];
			[self appDelegate].infocountButton.hidden = NO;
		}
	} else {
		settingBadge = 0;
		[self appDelegate].infocountButton.hidden = YES;
	}
	
	[UIApplication sharedApplication].applicationIconBadgeNumber = topBadge;
	NSUserDefaults *userInfo = [NSUserDefaults standardUserDefaults];
	[userInfo setInteger:topBadge forKey:NSUserDefaultReadCount];
	[userInfo setInteger:researchBadge forKey:NSUserDefaultAnswerCount];
	[userInfo setInteger:newsBadge forKey:NSUserDefaultNewsCount];
	[userInfo setInteger:settingBadge forKey:NSUserDefaultInfoCount];

	// AdMobバナー表示フラグ	ADD 2015-09-24
	[userInfo setInteger:mobflg_p forKey:NSUserDefaultMobflgNews];
	[userInfo setInteger:mobflg_s forKey:NSUserDefaultMobflgSettings];

	[userInfo synchronize];
	// バナー広告表示	ADD 2015-11-27
	[self showAdMob];
}

#pragma mark -
// call from AppDelegate tabbutton	OFFLINE MESSAGE	ADD 2015-09-10
- (BOOL)isOnlineAndAlert
{
	BOOL online = [[self appDelegate] isOnlineAndAlert:self];
	return online;
}

#pragma mark - YJADBannerViewDelegate
- (void)bannerViewDidLoad:(YJADBannerView *)adView
{
	DBG_LOG(@"bannerViewDidLoad");
}
- (void)bannerView:(YJADBannerView *)adView didFailLoadWithError:(NSError *)error
{
	DBG_LOG(@"didFailLoadWithError:%@", error);
}
- (void)bannerViewDidClickToAd:(YJADBannerView *)adView
{
	DBG_LOG(@"bannerViewDidClickToAd");
}

@end
