//
//  ProductDetailVC.m
//  GotoBus
//
//  Created by 包光清 on 2018/6/25.
//

#import "ProductDetailVC.h"
#import "Lang.h"
#import "SDK.h"
#import "BeanUtils.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "ImageUtils.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import "CalendarViewController.h"
#import "TextViewController.h"
#import "DTAttributedTextCell.h"
#import <libextobjc/EXTScope.h>
#import <BlocksKit/BlocksKit.h>
#import <BlocksKit/BlocksKit+UIKit.h>
#import <BlocksKit/A2DynamicDelegate.h>
#import <PureLayout/PureLayout.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "Utility.h"
#import "CustomIcons.h"
#import "Destination.h"
#import "BusAjaxDo.h"
#import "GetPricesResponseJsonMapper.h"
#import "GetDynamicPriceResponseJsonMapper.h"
#import "HeadTipView.h"
#import "AppTracker.h"
#import "BusSeachDetailCell.h"
#import "BusSearchDetailPriceCell.h"
#import "BookingReviewViewController.h"
#import "BusSearchDetailFeatureViewController.h"
#import "BusRescheduleViewController.h"
#import "BusVendorReviewListViewController.h"
#import "HotelSearchListViewController.h"
#import "ProductSearchListVC.h"
#import "SelectLocationViewController.h"
#import "Vars.h"

@interface ProductDetailVC ()
@property (nonatomic, strong) NSMutableDictionary *labelToInfo;
@property (nonatomic, strong) HeadTipView *headtipView;
@property (nonatomic, strong) NSArray *cellDataArrays;
@property (nonatomic, strong, readonly) NSString *serviceDate;
@property (nonatomic, strong, readonly) NSString *busFrom;
@property (nonatomic, strong, readonly) NSString *busTo;
@property (nonatomic, strong, readonly) NSString *fromName;
@property (nonatomic, strong, readonly) NSString *toName;
@property (nonatomic, strong, readonly) NSString *busRoute;
@property (nonatomic, assign, readonly) BOOL isFlexiTicket;
@end

@implementation ProductDetailVC

- (instancetype)init {
    if ((self = [super init])) {
        // Custom initialization
        self.title = @"Details";
        [[Vars appDelegate] applyDefaultConfigurationForViewController:self];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
	
	[[AppTracker sharedInstance] sendView:[self class]];
	
    [self prepareData];

    self.tableView.sectionHeaderHeight = [UIConstants defaultTableViewCellLayoutInsets].top;
    self.tableView.sectionFooterHeight = [UIConstants defaultTableViewCellLayoutInsets].bottom;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BusSeachDetailCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([BusSeachDetailCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BusSearchDetailPriceCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([BusSearchDetailPriceCell class])];

	[self setHeadView];
    if (YES) {
        UIView *footerView = [[UIView alloc] init];
        UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
        button1.frame = CGRectMake(15, 15, CGRectGetWidth([UIScreen mainScreen].bounds) - 15 * 2, [UIConstants defaultTableViewRowHeight]);
        button1.backgroundColor = [Vars defaultTintColor];
        button1.titleLabel.font = [UIFont boldSystemFontOfSize:[UIFont buttonFontSize]];
        [button1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        if (self.isReschedule) {
            [button1 setTitle:@"Select and Continue" forState:UIControlStateNormal];
        } else if (self.is_roundtrip && !self.is_return) {
            [button1 setTitle:@"Choose Returning Schedule" forState:UIControlStateNormal];
        } else if (!self.isBusHotelPackage) {
            [button1 setTitle:@"Add to Cart" forState:UIControlStateNormal];
        } else {
            [button1 setTitle:@"Select and Continue" forState:UIControlStateNormal];
        }
        [Utility addRoundedBorderToButton:button1];
        [footerView addSubview:button1];
        if (!self.isReschedule && !self.is_roundtrip && !self.is_return && !self.isBusHotelPackage) {
            [button1 addTarget:self action:@selector(changeToOneWayTrip) forControlEvents:UIControlEventTouchUpInside];
            
            UIButton *button2 = [UIButton buttonWithType:UIButtonTypeSystem];
            button2.frame = CGRectMake(15, [UIConstants defaultTableViewRowHeight] + 15 * 2, CGRectGetWidth([UIScreen mainScreen].bounds) - 15 * 2, [UIConstants defaultTableViewRowHeight]);
            button2.backgroundColor = [Vars defaultTintColor];
            button2.titleLabel.font = [UIFont boldSystemFontOfSize:[UIFont buttonFontSize]];
            [button2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [button2 setTitle:@"Choose Returning Schedule" forState:UIControlStateNormal];
            [Utility addRoundedBorderToView:button2];
            [button2 addTarget:self action:@selector(performSegueForReturnDateToRoundTrip) forControlEvents:UIControlEventTouchUpInside];
            [footerView addSubview:button2];
            
            footerView.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [UIConstants defaultTableViewRowHeight] * 2 + 15 * 3);
        } else {
            [button1 addTarget:self action:@selector(gotoNext) forControlEvents:UIControlEventTouchUpInside];
            footerView.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [UIConstants defaultTableViewRowHeight] + 15 * 2);
        }
        
        self.tableView.tableFooterView = footerView;
    }
    [self buildCellDataSource];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
	NSMutableArray *busEntries = [NSMutableArray array];
	NSMutableArray *otherEntries = [NSMutableArray array];
	for (CartEntry *entry in [Vars appDelegate].shopCarts.entries) {
		if (entry.product.is_bus) {
			[busEntries addObject:entry];
		} else {
			[otherEntries addObject:entry];
		}
	}
	if (self.is_roundtrip && self.is_return) {
		[CocoaUtils removeObjectsInArray:busEntries fromIndex:1];
	} else {
		[busEntries removeLastObject];
	}
	[[Vars appDelegate].shopCarts.entries removeAllObjects];
	[[Vars appDelegate].shopCarts.entries addObjectsFromArray:busEntries];
	[[Vars appDelegate].shopCarts.entries addObjectsFromArray:otherEntries];
	
    // ajax
    [self performRequestIsDynamic];
}

#pragma mark - Property

- (NSString *)serviceDate {
	return !self.is_return ? self.beforethisdate : self.return_date;
}

- (NSString *)busFrom {
	return !self.is_return ? self.depart : self.arrival;
}

- (NSString *)busTo {
	return !self.is_return ? self.arrival : self.depart;
}

- (NSString *)fromName {
	return [Destination cityName:self.busFrom];
}

- (NSString *)toName {
	return [Destination cityName:self.busTo];
}

- (NSString *)busRoute {
	return [NSString stringWithFormat:@"%@ to %@", self.fromName, self.toName];
}

- (BOOL)isFlexiTicket {
	return [self isFlexiTicketWithPriceType:self.labelToInfo[@"PriceType"]];
}

- (NSDictionary *)optionsForDisplayingHTMLString {
	UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
	return @{ DTUseiOS6Attributes : @YES, DTDefaultFontFamily : font.familyName, DTDefaultFontSize : @(font.pointSize), DTDefaultLinkDecoration : @NO };
}

#pragma mark - Action

- (void)performRequestIsDynamic {
    if (self.prData.dynamic) {
        [self performRequestForGetDynamicPrice];
    } else if (self.prData.ai) {
        [self performRequestForGetPrices];
    }
}

- (void)changeToOneWayTrip {
	[self changeToRoundTripIfReturnDate:nil];
}

- (void)detailPeopleType:(UIButton *)sender isFlexiTicket:(BOOL)isFlexiTicket{
	NSMutableAttributedString *priceInfo = [[NSMutableAttributedString alloc] init];
	for (GetProductOptionsResponsePeopleType *peopleType in self.prData.peopleType) {
		[priceInfo appendAttributedString:[[NSAttributedString alloc] im_initWithString:peopleType.name.capitalizedString]];
		[priceInfo appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
		[priceInfo appendAttributedString:[[NSAttributedString alloc] im_initWithString:peopleType.peoplePrice > 0 ? [self.prData.currencySymbol stringByAppendingFormat:@"%g", peopleType.peoplePrice + (isFlexiTicket ? self.prData.flexiReschedulePolicy.flexiPrice : 0)] : @"Free" attributes:@{ NSForegroundColorAttributeName : [Vars defaultTintColor] }]];
		if (peopleType.ageFrom >= 0 && peopleType.ageTo > 0) {
			[priceInfo appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
			[priceInfo appendAttributedString:[[NSAttributedString alloc] im_initWithString:[NSString stringWithFormat:@"(%d-%d)", peopleType.ageFrom, peopleType.ageTo] attributes:@{ NSForegroundColorAttributeName : [UIColor lightGrayColor] }]];
		} else if (peopleType.ageFrom < 0 && peopleType.ageTo > 0) {
			[priceInfo appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
			[priceInfo appendAttributedString:[[NSAttributedString alloc] im_initWithString:[NSString stringWithFormat:@"(Under %d)", peopleType.ageTo] attributes:@{ NSForegroundColorAttributeName : [UIColor lightGrayColor] }]];
		} else if (peopleType.ageFrom >= 0 && peopleType.ageTo < 0) {
			[priceInfo appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
			[priceInfo appendAttributedString:[[NSAttributedString alloc] im_initWithString:[NSString stringWithFormat:@"(Over %d)", peopleType.ageFrom] attributes:@{ NSForegroundColorAttributeName : [UIColor lightGrayColor] }]];
		}
		if (peopleType != self.prData.peopleType.lastObject) {
			[priceInfo appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"\n"]];
		}
	}
	[CocoaUtils showTooltipWithMessage:[[NSAttributedString alloc] initWithAttributedString:priceInfo] inView:self.view atFrame:[sender convertRect:sender.bounds toView:self.view]];
}

#pragma mark - Segue

- (void)gotoNext {
	if (![self validateForm]) {
		return;
	}
	if (self.isReschedule) {
		CartEntry *entry = [[CartEntry alloc] init];
		entry.product.p_type = 1;
		entry.product.product_id = self.prData.pid;
		entry.product.schedule_id = self.prData.scheduleId;
		entry.product.name = self.prData.productName;
		entry.product.busRouteName = self.busRoute;
		entry.options[@"date"] = self.labelToInfo[@"Date"];
		entry.options[@"departure"] = self.labelToInfo[@"Departure"];
		entry.options[@"arrival"] = self.labelToInfo[@"Arrival"];
		if (self.labelToInfo[@"PriceType"]) {
			entry.options[@"priceType"] = self.labelToInfo[@"PriceType"];
		}
		[[Vars appDelegate].shopCarts.entries addObject:entry];
		[self.navigationController popToViewController:[CocoaUtils lastViewControllerWithClass:[BusRescheduleViewController class] onNavigationController:self.navigationController] animated:YES];
	} else {
		CartEntry *entry = [[CartEntry alloc] init];
		entry.product.p_type = 1;
		entry.product.product_id = self.prData.pid;
		entry.product.schedule_id = self.prData.scheduleId;
		entry.product.name = self.prData.productName;
		entry.product.vendor = self.prData.vendorId;
		entry.product.vendor_obj.id = entry.product.vendor;
		entry.product.vendor_obj.short_name = self.prData.operator;
		entry.product.busRouteName = self.busRoute;
		entry.product.apiSchema = self.prData.apiSchema;
		entry.product.purchasedSeparately = self.prData.purchasedSeparately;
		entry.product.piwikCategory = [NSString stringWithFormat:@"%@ Bus", self.busRoute];
		NSMutableArray *array = [NSMutableArray array];
		if (YES) {
			Label *label = [[Label alloc] init];
			label.alias = @"date";
			label.name = IMLocalizedString(@"Departure Date");
			[array addObject:label];
		}
		if (YES) {
			Label *label = [[Label alloc] init];
			label.alias = @"departure";
			label.name = @"Departure";
			[array addObject:label];
		}
		if (YES) {
			Label *label = [[Label alloc] init];
			label.alias = @"arrival";
			label.name = @"Arrival";
			[array addObject:label];
		}
		entry.product.labels = [NSArray arrayWithArray:array];
		PPLBasedCountData *countData = [[PPLBasedCountData alloc] init];
		countData.adultCount = [Vars appDelegate].shopCarts.adultNum;
		entry.product.PPLBasedPrice = [[PPLBasedPrice alloc] init];
		for (GetProductOptionsResponsePeopleType *peopleType in self.prData.peopleType) {
			if ([peopleType.name isEqualToString:@"child"]) {
				entry.product.PPLBasedPrice.enable_child = YES;
				entry.product.PPLBasedPrice.child_age_from = peopleType.ageFrom;
				entry.product.PPLBasedPrice.child_age_to = peopleType.ageTo;
				countData.childCount = [Vars appDelegate].shopCarts.childNum;
			} else if ([peopleType.name isEqualToString:@"infant"]) {
				entry.product.PPLBasedPrice.enable_infant = YES;
			} else if ([peopleType.name isEqualToString:@"senior"]) {
				entry.product.PPLBasedPrice.enable_senior = YES;
			} else if ([peopleType.name isEqualToString:@"junior"]) {
				entry.product.PPLBasedPrice.enable_junior = YES;
			} else if ([peopleType.name isEqualToString:@"student"]) {
				entry.product.PPLBasedPrice.enable_student = YES;
			} else if ([peopleType.name isEqualToString:@"soldier"]) {
				entry.product.PPLBasedPrice.enable_soldier = YES;
			}
		}
		entry.PPLBasedCountData = countData;
		entry.options[@"date"] = self.labelToInfo[@"Date"];
		entry.options[@"departure"] = self.labelToInfo[@"Departure"];
		entry.options[@"arrival"] = self.labelToInfo[@"Arrival"];
		if (self.labelToInfo[@"PriceType"]) {
			entry.options[@"priceType"] = self.labelToInfo[@"PriceType"];
		}
		[[Vars appDelegate].shopCarts.entries addObject:entry];
		if (self.is_roundtrip && !self.is_return) {
			ProductSearchListVC *viewController = [[ProductSearchListVC alloc] init];
			viewController.currentDepartString = self.beforethisdate;
			viewController.currentReturnString = self.return_date;
			viewController.departCity = self.depart;
			viewController.returnCity = self.arrival;
			viewController.roundtrip = self.is_roundtrip;
			viewController.is_return = !self.is_return;
			viewController.isBusHotelPackage = self.isBusHotelPackage;
			ProductSearchListVC *prevViewController = [CocoaUtils lastViewControllerWithClass:[ProductSearchListVC class] onNavigationController:self.navigationController];
			viewController.productsDepart = prevViewController.productsDepart;
			viewController.productsReturn = prevViewController.productsReturn;
			[self.navigationController pushViewController:viewController animated:YES];
		} else if (!self.isBusHotelPackage) {
			BookingReviewViewController *viewController = [[BookingReviewViewController alloc] init];
			[self.navigationController pushViewController:viewController animated:YES];
		} else {
#ifdef POD_OF_MWPhotoBrowser
			HotelSearchListViewController *viewController = [[HotelSearchListViewController alloc] init];
			HotelSearchPaginationParam *hotelParam = [[HotelSearchPaginationParam alloc] init];
			NSDictionary *dict = [Vars appDelegate].coreData.hotelSearchDataSource[@"destinations"];
			hotelParam.destination = [dict allKeysForObject:self.arrival].firstObject;
			hotelParam.checkIn = self.beforethisdate;
			hotelParam.checkOut = self.return_date;
			hotelParam.roomInfo = [Vars appDelegate].shopCarts.roomBasedCountDatas;
			hotelParam.isBusHotelPackage = self.isBusHotelPackage;
			viewController.hotelSearchParam = hotelParam;
			viewController.isBusHotelPackage = self.isBusHotelPackage;
			[self.navigationController pushViewController:viewController animated:YES];
#endif
		}
	}
}

- (void)performSegueForReturnDateToRoundTrip {
	if (![self validateForm]) {
		return;
	}
    CalendarViewController *viewController = [[CalendarViewController alloc] init];
    viewController.title = @"Return date";
    [[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
    viewController.calendarManager.minimumDate = [StringUtils isEmpty:self.beforethisdate] ? [NSDate date] : [[DateFormatUtils ISO_DATE_FORMAT] parse:self.beforethisdate];
    viewController.calendarManager.maximumDate = [DateUtils addMonths:[NSDate date] amount:6];
    [viewController.calendarManager setDidSelectDateBlock:^(NSDate *date) {
        [self changeToRoundTripIfReturnDate:date];
        NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
        [viewControllers removeObjectAtIndex:viewControllers.count - 2];
        self.navigationController.viewControllers = viewControllers;
    }];
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForDepartureStopIsArrival:(BOOL)isArrival onTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
	SelectLocationViewController *viewController = [[SelectLocationViewController alloc] init];
	viewController.title = @"Select Stop";
	viewController.isArrival = isArrival;
	for (BusSearchLocationTuple *tuple in self.prData.departs) {
		[viewController addAnnotations:[BusStop toAnnotations:tuple.stationList] title:tuple.stationCityName isArrival:NO];
	}
	for (BusSearchLocationTuple *tuple in self.prData.arrivals) {
		[viewController addAnnotations:[BusStop toAnnotations:tuple.stationList] title:tuple.stationCityName isArrival:YES];
	}
	[viewController selectTitle:self.fromName isArrival:NO];
	[viewController selectTitle:self.toName isArrival:YES];
	[viewController selectAnnotation:[[viewController getAnnotationsIsArrival:NO] bk_match:^BOOL (MapViewAnnotation *annotation) {
		return [self.labelToInfo[@"Departure"] isEqualToString:annotation.value];
	}] isArrival:NO];
	[viewController selectAnnotation:[[viewController getAnnotationsIsArrival:YES] bk_match:^BOOL (MapViewAnnotation *annotation) {
		return [self.labelToInfo[@"Arrival"] isEqualToString:annotation.value];
	}] isArrival:YES];
	[viewController setDidCancelBlock:^{
		[self.navigationController popViewControllerAnimated:YES];
	}];
	[viewController setDidDoneDepartureAndArrivalBlock:^(MapViewAnnotation *departureAnnotation, MapViewAnnotation *arrivalAnnotation) {
		if (!departureAnnotation) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please select pick up stop"];
			return;
		}
		if (!arrivalAnnotation) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please select drop off stop"];
			return;
		}
		self.labelToInfo[@"Departure"] = departureAnnotation.value;
		self.labelToInfo[@"Arrival"] = arrivalAnnotation.value;
		[self updateTipView];
		[self.navigationController popViewControllerAnimated:YES];
		[tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
	}];
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForFeatures {
    BusSearchDetailFeatureViewController *viewController = [[BusSearchDetailFeatureViewController alloc] init];
    viewController.busSearchData = self.prData;
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForReviewList {
    BusVendorReviewListViewController *viewController = [[BusVendorReviewListViewController alloc] init];
    viewController.vendorId = self.prData.vendorId;
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForTermsAndConditions:(BOOL )isFlexi {
    TextViewController *viewController = [[TextViewController alloc] init];
    viewController.title = IMLocalizedString(@"Terms and Conditions");
    [[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
    viewController.textView.text = [self getReschedulePolicy:isFlexi];
    [self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Private

- (BOOL)isFlexiTicketWithPriceType:(NSString *)priceType {
	return [priceType isEqualToString:@"Flexi Ticket"];
}

- (void)changeToRoundTripIfReturnDate:(NSDate *)returnDate {
	if (returnDate) {
		self.return_date = [[DateFormatUtils ISO_DATE_FORMAT] format:returnDate];
		self.is_roundtrip = YES;
	} else {
		self.is_roundtrip = NO;
		self.return_date = nil;
	}
	[self gotoNext];
}

- (NSString *)getShortStringForSubTo:(NSString *)originString {
	NSRange range = [originString rangeOfString:@" "];
	return  [originString substringWithRange:NSMakeRange(0,range.location)];
}

- (NSString *)getReschedulePolicy:(BOOL )isFlexi {
	if (isFlexi) {
		return [NSString stringWithFormat:@"1. Unused and unchecked tickets can be self-reschedule online for free up to %g times before departure time.\n\n2. Unused and unchecked tickets can be self-reschedule online for free up to %g time(s) within %g hours after departure time.\n\n3. Refund of unused tickets may be claimed for the original amount paid minus a service fee of $%g\n\n4. Double Loyalty Points will be awarded upon completion of the trip.", self.prData.flexiReschedulePolicy.beforeTimes, self.prData.flexiReschedulePolicy.afterTimes, self.prData.flexiReschedulePolicy.afterHours, self.prData.flexiReschedulePolicy.flexiPrice];
	} else {
		return [NSString stringWithFormat:@"1. Tickets can be rescheduled up to %g times no less than %g hours before the scheduled departure time for an additional fee.\n\n2. Once a reservation is booked, it cannot be canceled by the customer.", self.prData.flexiReschedulePolicy.baseTimes, self.prData.flexiReschedulePolicy.baseHours];
	}
}

- (void)setHeadView {
	UIView *headView = [[UIView alloc] init];
	headView.backgroundColor = [UIColor clearColor];
	
	self.headtipView = [HeadTipView viewFromNib];
	self.headtipView.backgroundColor = [UIColor clearColor];
	self.headtipView.tipView.backgroundColor = [Vars defaultTintColor];
	[headView addSubview:self.headtipView];
    [self.headtipView autoPinEdge:ALEdgeTop toEdge:ALEdgeTop ofView:headView withOffset:10];
    [self.headtipView autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:headView withOffset:10];
	[self.headtipView autoCenterInSuperview];

    headView.frame = CGRectSetSize(headView.frame, [headView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]);
	
	self.tableView.tableHeaderView = headView;
	[self setHeadViewData];
}

- (void)setHeadViewData {
	[self.headtipView.operaImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://www.gotobus.com/images/logo/vendor/%d.jpg", self.prData.vendorId]] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
		if (error && !image) {
			self.headtipView.operatorlab.text = self.prData.operator;
			self.headtipView.operatorlab.hidden = NO;
			self.headtipView.operaImageView.hidden = YES;
		} else {
			self.headtipView.operatorlab.hidden = YES;
			self.headtipView.operaImageView.hidden = NO;
		}
	}];
	
	NSString *dateStr = self.serviceDate;
	
	NSDate *starDate = [[DateFormatUtils ISO_DATE_FORMAT] parse:dateStr];
	
	self.headtipView.airportDatelab.text = [CocoaUtils localizedStringFromDate:starDate template:@"EEEMMMd"];

	self.headtipView.wagonNumberlab.text =  self.prData.scheduleId;
	
	[self updateTipView];
}

- (void)updateTipView {
	NSString *dateStr = self.serviceDate;
	
	NSString *departDate1 = [StringUtils isEmpty:self.labelToInfo[@"Departure"]]? [self.prData displayTimeByCityName:self.fromName isArrival:NO] :[self getShortStringForSubTo:self.labelToInfo[@"Departure"]];
	
	NSString *arrviDate1 = [StringUtils isEmpty:self.labelToInfo[@"Arrival"]]? [self.prData displayTimeByCityName:self.toName isArrival:YES] : [self getShortStringForSubTo:self.labelToInfo[@"Arrival"]];
	
	if (YES) {
		if (YES) {
			self.headtipView.departDatelab.text = departDate1;
			self.headtipView.departDatelab.textColor = [UIColor blackColor];
			NSInteger nextDay = [self.prData nextArrivalDayByCityName:self.arrival];
			if (nextDay > 0) {
				if (nextDay == 1) {
					self.headtipView.isTomorrowLab.attributedText = [DrawUtils attributedStringWithFAKIcon:[CustomIcons nextDayIconWithSize:12] fillColor:[CocoaUtils colorWithRGBs:StandardColorBlue]];
				} else if (nextDay == 2) {
					self.headtipView.isTomorrowLab.attributedText = [DrawUtils attributedStringWithFAKIcon:[CustomIcons nextDayTwoIconWithSize:12] fillColor:[CocoaUtils colorWithRGBs:StandardColorBlue]];
				}
			}
			self.headtipView.deparsitelab.text = [StringUtils isEmpty:self.labelToInfo[@"Departure"]] ? [self.prData locationByCityName:self.fromName isArrival:NO] :[self.prData locationByOption:self.labelToInfo[@"Departure"] isArrival:NO];
			self.headtipView.deparsitelab.textColor = [UIColor blackColor];
		}
		
		if(YES) {
			NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
			
			[attributedString appendAttributedString: [DrawUtils attributedStringWithFAKIcon:[FAKFontAwesome clockOIconWithSize:self.headtipView.airportTimelab.font.pointSize] fillColor:[UIColor lightGrayColor]]];
            [attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
			NSLocale *locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
			NSDate *starDate = [DateUtils parseDate:[NSString stringWithFormat:@"%@ %@", dateStr, departDate1] locale:locale parsePatterns:@"yyyy-MM-dd h:mma", nil];
			NSInteger nextDay = [self.prData nextArrivalDayByCityName:self.toName];
			NSDate *endDate = [DateUtils addDays:[DateUtils parseDate:[NSString stringWithFormat:@"%@ %@", dateStr, arrviDate1] locale:locale parsePatterns:@"yyyy-MM-dd h:mma", nil] amount:nextDay];
			if (![StringUtils isEmpty:[Utility abbreviatedDurationStringFromDate:starDate toDate:endDate]]) {
				[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:[Utility abbreviatedDurationStringFromDate:starDate toDate:endDate]]];
			}
			self.headtipView.airportTimelab.attributedText = attributedString;
			self.headtipView.airportTimelab.textColor = [UIColor blackColor];
		}
		if (YES) {
			self.headtipView.ArrivalDatelab.text = arrviDate1;
			self.headtipView.ArrivalDatelab.textColor = [UIColor blackColor];
			
			self.headtipView.dArrivalsitelab.text = [StringUtils isEmpty:self.labelToInfo[@"Arrival"]] ? [self.prData locationByCityName:self.toName isArrival:YES] : [self.prData locationByOption:self.labelToInfo[@"Arrival"] isArrival:YES];
			self.headtipView.dArrivalsitelab.textColor = [UIColor blackColor];
		}
	}
}

- (void)prepareData {
	self.labelToInfo = [NSMutableDictionary dictionary];
	self.labelToInfo[@"Date"] = self.prData.dateOption;
	if (self.prData.departs.count == 1) {
		BusSearchLocationTuple *tuple = self.prData.departs.firstObject;
		if (tuple.stationList.count == 1) {
			BusStop *stop = tuple.stationList.firstObject;
			self.labelToInfo[@"Departure"] = stop.option_value;
		}
	}
	if (self.prData.arrivals.count == 1) {
		BusSearchLocationTuple *tuple = self.prData.arrivals.firstObject;
		if (tuple.stationList.count == 1) {
			BusStop *stop = tuple.stationList.firstObject;
			self.labelToInfo[@"Arrival"] = stop.option_value;
		}
		
	}
	if (self.prData.hasFlexiTicket) {
		self.labelToInfo[@"PriceType"] = self.isFlexiTicketOnly ? @"Flexi Ticket" : @"Value Ticket";
	}
}

- (BOOL)validateForm {
	if ([StringUtils isEmpty:self.labelToInfo[@"Departure"]]) {
        [CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please select pick up stop" dismissalHandler:^{
            NSIndexPath *indexPath = [CocoaUtils indexPathOfObjectIdenticalTo:[CocoaUtils objectPassingTest:^BOOL (TableViewCellData *obj, NSUInteger idx, BOOL *stop) {
                return [obj.identifier isEqualToString:@"Departure"];
            } fromArrays:self.cellDataArrays] fromArrays:self.cellDataArrays];
            if (indexPath) {
                [self performSegueForDepartureStopIsArrival: NO
                                                onTableView:self.tableView atIndexPath: indexPath];
            }
        }];
		return NO;
	}
	if ([StringUtils isEmpty:self.labelToInfo[@"Arrival"]]) {
        [CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please select drop off stop" dismissalHandler:^{
            NSIndexPath *indexPath = [CocoaUtils indexPathOfObjectIdenticalTo:[CocoaUtils objectPassingTest:^BOOL (TableViewCellData *obj, NSUInteger idx, BOOL *stop) {
                return [obj.identifier isEqualToString:@"Arrival"];
            } fromArrays:self.cellDataArrays] fromArrays:self.cellDataArrays];
            if (indexPath) {
                [self performSegueForDepartureStopIsArrival: YES
                                                onTableView:self.tableView atIndexPath: indexPath];
            }
            
        }];
		return NO;
	}
	return YES;
}

- (void)buildCellDataSource {
	NSMutableArray *arrays = [NSMutableArray array];
	@weakify(self)
	if (self.prData.hasFlexiTicket) {
		NSMutableArray *array = [NSMutableArray array];
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleValue1;
			data.text = IMLocalizedString(@"Ticket Type");
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.reuseIdentifier = NSStringFromClass([BusSearchDetailPriceCell class]);
			data.isCustomRegistered = YES;
			[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, BusSearchDetailPriceCell *cell) {
				@strongify(self)
				cell.titleLabel.text = IMLocalizedString(@"Value Ticket");
				cell.subtitleLabel.text = @"Non-Refundable, Rescheduling Fees Before Trip";
				cell.subtitleLabel.textColor = [UIColor lightGrayColor];
				if(!self.isFlexiTicket) {
					cell.imageView.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome checkCircleIconWithSize:24] fillColor:[Vars defaultTintColor]];
				} else {
					cell.imageView.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome circleThinIconWithSize:24] fillColor:[Vars defaultTintColor]];
				}
				if (YES) {
					[cell.salePriceButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
					if (self.prData.isDynamicPrice) {
						[cell.salePriceButton setAttributedTitle:[DrawUtils attributedStringWithFAKIcon:[CustomIcons dynamicPriceIconWithSize:24] fillColor:[CocoaUtils colorWithRGBs:StandardColorBlue]] forState:UIControlStateNormal];
						[cell.salePriceButton addTarget:self action:@selector(performRequestIsDynamic) forControlEvents:UIControlEventTouchUpInside];
					} else {
						UIFont *integerDigitsFont = cell.salePriceButton.titleLabel.font;
						UIFont *fractionDigitsFont = [integerDigitsFont fontWithSize:integerDigitsFont.pointSize * 0.5];
						NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:[Utility attributedPriceWithNumber:[NSNumber numberWithFloat:self.prData.displayPrice] currencySymbol:self.prData.currencySymbol integerDigitsFont:integerDigitsFont fractionDigitsFont:fractionDigitsFont textColor:[Vars defaultTintColor]]];
						if (self.prData.peopleType.count > 1){
							NSRange strRange = {0,[attributedString length]};
							[attributedString addAttribute:NSUnderlineStyleAttributeName value:
							 [NSNumber numberWithInteger:NSUnderlineStyleDouble | NSUnderlinePatternDot] range:strRange];
						}
						[cell.salePriceButton bk_addEventHandler:^(id  _Nonnull sender) {
							[self detailPeopleType:cell.salePriceButton isFlexiTicket:NO];
						} forControlEvents:UIControlEventTouchUpInside];
						[cell.salePriceButton setAttributedTitle:attributedString forState:UIControlStateNormal];
					}
				}
				cell.salePriceButton.hidden = NO;
				cell.detailDisclosureButton.hidden = NO;
				[cell.detailDisclosureButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
				[cell.detailDisclosureButton bk_addEventHandler:^(id  _Nonnull sender) {
					[self performSegueForTermsAndConditions:NO];
				} forControlEvents:UIControlEventTouchUpInside];
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				self.labelToInfo[@"PriceType"] = @"Value Ticket";
				[tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
			}];
			[array addObject:data];
		}
		if (!self.isFlexiTicketOnly) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.reuseIdentifier = NSStringFromClass([BusSearchDetailPriceCell class]);
			data.isCustomRegistered = YES;
			[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, BusSearchDetailPriceCell *cell) {
				@strongify(self)
				cell.titleLabel.text = IMLocalizedString(@"Flexi Ticket");
				cell.subtitleLabel.text = @"Partially Refundable, Free Rescheduling, Extra Loyalty Points";
				cell.subtitleLabel.textColor = [UIColor lightGrayColor];
				if(self.isFlexiTicket) {
					cell.imageView.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome checkCircleIconWithSize:24] fillColor:[Vars defaultTintColor]];
				} else {
					cell.imageView.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome circleThinIconWithSize:24] fillColor:[Vars defaultTintColor]];
				}
				if (YES) {
					[cell.salePriceButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
					if (self.prData.isDynamicPrice) {
						[cell.salePriceButton setAttributedTitle:[DrawUtils attributedStringWithFAKIcon:[CustomIcons dynamicPriceIconWithSize:24] fillColor:[CocoaUtils colorWithRGBs:StandardColorBlue]] forState:UIControlStateNormal];
						[cell.salePriceButton addTarget:self action:@selector(performRequestIsDynamic) forControlEvents:UIControlEventTouchUpInside];
					} else {
						UIFont *integerDigitsFont = cell.salePriceButton.titleLabel.font;
						UIFont *fractionDigitsFont = [integerDigitsFont fontWithSize:integerDigitsFont.pointSize * 0.5];
						NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:[Utility attributedPriceWithNumber:[NSNumber numberWithFloat:self.prData.displayPrice + self.prData.flexiReschedulePolicy.flexiPrice] currencySymbol:self.prData.currencySymbol integerDigitsFont:integerDigitsFont fractionDigitsFont:fractionDigitsFont textColor:[Vars defaultTintColor]]];
						if (self.prData.peopleType.count > 1) {
							NSRange strRange = {0,[attributedString length]};
							[attributedString addAttribute:NSUnderlineStyleAttributeName value:
							 [NSNumber numberWithInteger:NSUnderlineStyleDouble | NSUnderlinePatternDot] range:strRange];
						}
						[cell.salePriceButton bk_addEventHandler:^(id  _Nonnull sender) {
							[self detailPeopleType:cell.salePriceButton isFlexiTicket:YES];
						} forControlEvents:UIControlEventTouchUpInside];
						[cell.salePriceButton setAttributedTitle:attributedString forState:UIControlStateNormal];
					}
				}
				cell.salePriceButton.hidden = NO;
				cell.detailDisclosureButton.hidden = NO;
				[cell.detailDisclosureButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
				[cell.detailDisclosureButton bk_addEventHandler:^(id  _Nonnull sender) {
					[self performSegueForTermsAndConditions:YES];
				} forControlEvents:UIControlEventTouchUpInside];
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				self.labelToInfo[@"PriceType"] = @"Flexi Ticket";
				[tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
			}];
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	if (YES) {
		NSMutableArray *array = [NSMutableArray array];
		if (!self.prData.hasFlexiTicket) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.reuseIdentifier = NSStringFromClass([BusSeachDetailCell class]);
			data.isCustomRegistered = YES;
			[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, BusSeachDetailCell *cell) {
				@strongify(self)
				cell.titleLab.text = @"Price";
				cell.rightImageView.image = nil;
				if (YES) {
					[cell.salePriceBtn bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
					if (self.prData.isDynamicPrice) {
						[cell.salePriceBtn setAttributedTitle:[DrawUtils attributedStringWithFAKIcon:[CustomIcons dynamicPriceIconWithSize:24] fillColor:[CocoaUtils colorWithRGBs:StandardColorBlue]] forState:UIControlStateNormal];
						[cell.salePriceBtn addTarget:self action:@selector(performRequestIsDynamic) forControlEvents:UIControlEventTouchUpInside];
					} else {
						UIFont *integerDigitsFont = cell.salePriceBtn.titleLabel.font;
						UIFont *fractionDigitsFont = [integerDigitsFont fontWithSize:integerDigitsFont.pointSize * 0.5];
						NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:[Utility attributedPriceWithNumber:[NSNumber numberWithFloat:self.prData.displayPrice] currencySymbol:self.prData.currencySymbol integerDigitsFont:integerDigitsFont fractionDigitsFont:fractionDigitsFont textColor:[Vars defaultTintColor]]];
						if (self.prData.peopleType.count > 1){
							NSRange strRange = {0,[attributedString length]};
							[attributedString addAttribute:NSUnderlineStyleAttributeName value:
							 [NSNumber numberWithInteger:NSUnderlineStyleSingle | NSUnderlinePatternDot] range:strRange];
						}
						[cell.salePriceBtn setAttributedTitle:attributedString forState:UIControlStateNormal];
						[cell.salePriceBtn bk_addEventHandler:^(id  _Nonnull sender) {
							[self detailPeopleType:cell.salePriceBtn isFlexiTicket:NO];
						} forControlEvents:UIControlEventTouchUpInside];
					}
				}
				cell.contextLabel.hidden = YES;
				cell.salePriceBtn.hidden = NO;
			}];
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.reuseIdentifier = NSStringFromClass([BusSeachDetailCell class]);
			data.isCustomRegistered = YES;
            data.identifier = @"Departure";
			[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, BusSeachDetailCell *cell) {
				@strongify(self)
				cell.titleLab.text = @"Departure";
				cell.rightImageView.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome angleRightIconWithSize:24] fillColor:[UIColor blackColor]];
				if ([StringUtils isEmpty:self.labelToInfo[@"Departure"]]) {
                    cell.contextLabel.text = @"Select pick up stop";
					cell.contextLabel.textColor = [UIColor lightGrayColor];
				} else {
					cell.contextLabel.attributedText = [Utility attributedStringWithHtmlString:self.labelToInfo[@"Departure"] fixAttributes:@{ NSFontAttributeName : cell.contextLabel.font }];
					cell.contextLabel.textColor = [UIColor blackColor];
				}
				cell.contextLabel.hidden = NO;
				cell.salePriceBtn.hidden = YES;
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				[self performSegueForDepartureStopIsArrival: NO
												onTableView:tableView atIndexPath: indexPath];
			}];
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.reuseIdentifier = NSStringFromClass([BusSeachDetailCell class]);
			data.isCustomRegistered = YES;
            data.identifier = @"Arrival";
			[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, BusSeachDetailCell *cell) {
				@strongify(self)
				cell.titleLab.text = @"Arrival";
				cell.rightImageView.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome angleRightIconWithSize:24] fillColor:[UIColor blackColor]];
				if ([StringUtils isEmpty:self.labelToInfo[@"Arrival"]]) {
					cell.contextLabel.text = @"Select drop off stop";
					cell.contextLabel.textColor = [UIColor lightGrayColor];
				} else {
                    cell.contextLabel.attributedText = [CocoaUtils isHtmlString:self.labelToInfo[@"Arrival"]] ? [Utility attributedStringWithHtmlString:self.labelToInfo[@"Arrival"] fixAttributes:@{ NSFontAttributeName : cell.contextLabel.font }] : [[NSAttributedString alloc] im_initWithString:self.labelToInfo[@"Arrival"]];
					cell.contextLabel.textColor = [UIColor blackColor];
				}
				cell.contextLabel.hidden = NO;
				cell.salePriceBtn.hidden = YES;
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				[self performSegueForDepartureStopIsArrival: YES onTableView:tableView atIndexPath: indexPath];
			}];
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	if (YES) {
		NSMutableArray *array = [NSMutableArray array];
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.reuseIdentifier = NSStringFromClass([BusSeachDetailCell class]);
			data.isCustomRegistered = YES;
			[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, BusSeachDetailCell *cell) {
				@strongify(self)
				UIFont *font = [UIConstants defaultTableViewCellTextLabelFont:UITableViewCellStyleSubtitle];
				cell.titleLab.text = @"Features";
				cell.rightImageView.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome angleRightIconWithSize:24] fillColor:[UIColor blackColor]];
				cell.contextLabel.attributedText =  [CocoaUtils attributedStringForImage:[self.prData concatenateFeatureImageToSize:CGSizeMake(font.pointSize, font.pointSize) tintColor:[UIColor blackColor] borderWidth:font.pointSize / 5]];
				cell.contextLabel.hidden = NO;
				cell.salePriceBtn.hidden = YES;
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				[self performSegueForFeatures];
			}];
			[array addObject:data];
		}
		if (YES) {
			UIFont *font = [UIConstants defaultTableViewCellTextLabelFont:UITableViewCellStyleSubtitle];
			HCSStarRatingView *starRatingView = [[HCSStarRatingView alloc] initWithFrame:CGRectMake(0, 0, font.pointSize * 5.5, font.pointSize)];
			[CocoaUtils configureStarRatingView:starRatingView editing:NO];
			starRatingView.tintColor = [CocoaUtils colorWithRGBs:StandardColorOrange];
			starRatingView.value = self.prData.vendorStarRating;
			UIImage *snapshotImage = [ImageUtils snapshotImageWithView:starRatingView];
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.reuseIdentifier = NSStringFromClass([BusSeachDetailCell class]);
			data.isCustomRegistered = YES;
			[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, BusSeachDetailCell *cell) {
				@strongify(self)
				cell.titleLab.text = @"Rating";
				cell.rightImageView.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome angleRightIconWithSize:24] fillColor:[UIColor blackColor]];
				NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
				[attributedString appendAttributedString:[CocoaUtils attributedStringForImage:snapshotImage verticalAlignWithFont:cell.contextLabel.font]];
				[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:[NSString stringWithFormat:@" %d %@", self.prData.vendorThreeStarRatingCount, self.prData.vendorThreeStarRatingCount > 1 ? @"Reviews" : @"Review"] attributes:@{ NSForegroundColorAttributeName : [UIColor blackColor]}]];
				cell.contextLabel.attributedText = attributedString;
				cell.contextLabel.hidden = NO;
				cell.salePriceBtn.hidden = YES;
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				[self performSegueForReviewList];
			}];
			[array addObject:data];
		}
		if (![StringUtils isBlank:self.prData.specialRemark]) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.reuseIdentifier = NSStringFromClass([DTAttributedTextCell class]);
            data.isCustomRegistered = YES;
            data.className = NSStringFromClass([DTAttributedTextCell class]);
            [data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, DTAttributedTextCell *cell) {
				cell.backgroundColor = [UIColor clearColor];
				cell.contentView.backgroundColor = [UIColor clearColor];
				cell.attributedTextContextView.backgroundColor = [UIColor clearColor];
                cell.attributedTextContextView.edgeInsets = UIEdgeInsetsMake(5, 15 , 5, 15);
				UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
				NSData *dA = UIImagePNGRepresentation([DrawUtils imageWithFAKIcon:[FAKFontAwesome infoCircleIconWithSize:font.pointSize] fillColor:[UIColor lightGrayColor]]);
				NSString *imageSt = [NSString stringWithFormat:@"<img src=\"data:image/png;base64, %@\" style=\"width:%fpx;height:%fpx;vertical-align:middle;\"/> ", [dA base64EncodedStringWithOptions:0], font.pointSize, font.pointSize];
				[cell setHTMLString:[imageSt im_stringByAppendingString:self.prData.specialRemark] options:[self optionsForDisplayingHTMLString]];
                [CocoaUtils hideSeparatorOfCell:cell];
            }];
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	self.cellDataArrays = [NSArray arrayWithArray:arrays];
}

#pragma mark - Network

- (void)performRequestForGetDynamicPrice {
	NSDictionary *requestDict = @{@"type" : @"dynamic_prices",@"version" : @1,@"pids" : [NSString stringWithFormat:@"%d", self.prData.pid],@"service_date" : self.serviceDate};
	
	[Utility getJSONFromRequestWithMethod:@"GET" url:[Utility perlCgiBin:@"ajax"] parameters:requestDict success:^(id jsonObject) {
		GetPricesResponseJsonMapper *mapper = [[GetPricesResponseJsonMapper alloc] init];
		if (![mapper parseWithJSONObject:jsonObject]) {
			GetPricesResponse *response = mapper.response;
			for (ProductAiPriceBean *bean in response.prices) {
				if (bean.pid == self.prData.pid) {
					if (self.prData.peopleType.count > bean.price.count) {
						self.prData.peopleType = [self.prData.peopleType subarrayWithRange:NSMakeRange(0, bean.price.count)];
					}
					if (self.prData.peopleType.count == bean.price.count) {
						[self.prData.peopleType enumerateObjectsUsingBlock:^(GetProductOptionsResponsePeopleType *obj, NSUInteger idx, BOOL *stop) {
							GetProductOptionsResponsePeopleType *peopleType = bean.price[idx];
							obj.peoplePrice = peopleType.peoplePrice;
						}];
						self.prData.dynamic = NO;
					}
					break;
				}
			}
			[self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
		}
	}];
}

- (void)performRequestForGetPrices {
	GetPrices *getPrices = [[GetPrices alloc] init];
	getPrices.pids = [NSString stringWithFormat:@"%d", self.prData.pid];
	getPrices.service_date = self.serviceDate;
	
	NSDictionary *requestDict = [BeanUtils describeAccessibleSimple:getPrices];
	
	[Utility performRESTRequestWithMethod:@"GET" url:getPrices.address parameters:requestDict success:^(id jsonObject) {
		GetPricesResponseJsonMapper *mapper = [[GetPricesResponseJsonMapper alloc] init];
		if (![mapper parseWithJSONObject:jsonObject]) {
			GetPricesResponse *response = mapper.response;
			for (ProductAiPriceBean *bean in response.prices) {
				if (bean.pid == self.prData.pid) {
					if (self.prData.peopleType.count == bean.price.count) {
						[self.prData.peopleType enumerateObjectsUsingBlock:^(GetProductOptionsResponsePeopleType *obj, NSUInteger idx, BOOL *stop) {
							GetProductOptionsResponsePeopleType *peopleType = bean.price[idx];
							obj.peoplePrice = peopleType.peoplePrice;
						}];
						self.prData.ai = NO;
					}
					break;
				}
			}
			[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
		}
	}];
}

#pragma mark - Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.cellDataArrays.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.cellDataArrays[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
    return [UIToolkit tableView:tableView atIndexPath:indexPath cellWithData:data];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
    [UIToolkit tableView:tableView atIndexPath:indexPath didSelectWithData:data];
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
    if ([data.reuseIdentifier isEqualToString:NSStringFromClass([BusSearchDetailPriceCell class])]) {
        return [UIToolkit instantiateRowHeightForTableViewCellWithNibName:NSStringFromClass([BusSearchDetailPriceCell class])];
    } else if ([data.reuseIdentifier isEqualToString:NSStringFromClass([DTAttributedTextCell class])]) {
        return 100;
    }
    return [UIConstants defaultTableViewRowHeight];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
    if ([data.reuseIdentifier isEqualToString:NSStringFromClass([DTAttributedTextCell class])]) {
        DTAttributedTextCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
        return [cell requiredRowHeightInTableView:tableView];
    }
    return [UIToolkit tableView:tableView atIndexPath:indexPath rowHeightWithData:data];
}

@end
