MainViewController::MainViewController()
: m_msg(FDataManager::getInstance()->getSessionMsgs())
, m_timeNoticeImageView(NULL)
, m_sessionNoticeImageView(NULL)
//, m_totalView(NULL)
//, m_totalViewList(NULL)
, m_msgTableView(NULL)
, m_pageView(NULL)
, m_pageControl(NULL)
, m_pageControlBG(NULL)
//, m_pageViewTitle(NULL)
, p_alertView(NULL)
, p_pLoading(NULL)
//, m_pastSection(0)
//, m_nextSection(1)
, m_timeForPageView(getTimeSecond())
, m_sustainabilitySurvey(NULL)
, m_monent(NULL)
, m_vote(NULL)
, m_map(NULL)
, m_session(NULL)
, m_my(NULL)
, m_pageStatus(MAP_ALL_MAP)
{
    m_filterMsg.clear();
    m_page.clear();
    m_pageAllMapVec.clear();
//    m_msg(FDataManager::getInstance()->getSessionMsgs())
    
    FNoticeManager::sharedFNoticeManager()->setTarget(this, FNotice_selector(MainViewController::onNotice));
    CAScheduler::schedule(schedule_selector(MainViewController::refreshNoticeRedPoint), this, 1);
}
bool MainViewController::checkPageStatusIsChanged()
{
    time_t nowTime = getTimeSecond();
    struct tm * timeinfo;
    timeinfo = localtime(&nowTime);
    string timeStr = "";
    int statusShouldbe = MAP_ALL_MAP;
    if (timeinfo->tm_hour >= 6 && timeinfo->tm_hour < 9) {
        statusShouldbe = MAP_PRE_EVENT;
    }
    else if (timeinfo->tm_hour >= 9 && timeinfo->tm_hour < 13) {
        statusShouldbe = MAP_MORNING;
    }
    else if (timeinfo->tm_hour >= 13 && timeinfo->tm_hour < 18) {
        statusShouldbe = MAP_AFTERNOON;
    }
    else if (timeinfo->tm_hour >= 18 && timeinfo->tm_hour < 22) {
        statusShouldbe = MAP_EVENING;
    }
    if (m_pageStatus != statusShouldbe) {
        m_pageStatus = statusShouldbe;
        return true;
    }
    return false;
}
void SessionsViewController::refreshTableByTime(int index)
{
    
    m_msgFilter.clear();
    if (index == 0)
    {
        for (std::vector<sessionMsg>::iterator it = m_msg->begin(); it != m_msg->end(); it++)
        {
            m_msgFilter.push_back(&(*it));
        }
    }
    else
    {
        time_t nowTimeCount = getTimeSecond();
//        struct tm* nowTime = localtime(&nowTimeCount);
//        int nowYear = nowTime->tm_year;
//        int nowDay = nowTime->tm_yday;
//        int nowHour = nowTime->tm_hour;
//        int nowMin = nowTime->tm_min;
//        CCLog("now : %d %d %d %d", nowYear, nowDay, nowHour, nowMin);
        
        for (std::vector<sessionMsg>::iterator it = m_msg->begin(); it != m_msg->end(); it++)
        {
            struct tm* startTime = localtime(&(it->m_startTime));
//            int startYear = startTime->tm_year;
//            int startDay = startTime->tm_yday;
            int startHour = startTime->tm_hour;
//            int startMin = startTime->tm_min;

            struct tm* endTime = localtime(&(it->m_endTime));
//            int endYear = endTime->tm_year;
//            int endDay = endTime->tm_yday;
            int endHour = endTime->tm_hour;
            int endMin = endTime->tm_min;
            
//            CCLog("start index %d: %d %d %d %d", index, startYear, startDay, startHour, startMin);
//            CCLog("end   index %d: %d %d %d %d", index, endYear, endDay, endHour, endMin);

            if ((startHour == index + 8) || ((endHour > index + 8 || (endHour == index + 8 && endMin != 0)) && startHour < index + 8))
                m_msgFilter.push_back(&(*it));
        }
    }
    if (m_msgTableView)
    {
		m_msgTableView->setFrame(DRect(0, (180), m_winSize.width, m_winSize.height - (180)));
        m_msgTableView->reloadData();
    }
}
//advance to next menu screen with current selection
void incrementMenuID(){
	clearLCD();
	previousMenuID = currentMenuID;
	//Coming From...
	//[Sleep]
	if (currentMenuID == 0 || currentMenuID == 1)
		currentMenuID = 10;
	
	//[Main Menu]
	else if (currentMenuID == 10){
		if(researchPeriod == 0){
			if (selectionInMenu == 0)
				currentMenuID = 20;
			else if (selectionInMenu == 1)
				currentMenuID = 30;
			else if (selectionInMenu == 2){
				currentMenuID = 40;
			}			
			else if (selectionInMenu == 3)
				currentMenuID = 70;
			else if (selectionInMenu == 4)
				currentMenuID = 0;
			else if (selectionInMenu == 5)
				currentMenuID = 80;
		}	
		else{
			if(selectionInMenu == 3 || selectionInMenu == 4 || selectionInMenu == 5){
				if (selectionInMenu == 3)
					currentMenuID = 70;
				else if(selectionInMenu == 4)
					currentMenuID = 0;
				else if(selectionInMenu == 5)
					currentMenuID = 80;
			}					
			else
				currentMenuID = 11;	
		}						
	}
	//[Log - Choose Activity]
	else if (currentMenuID == 20){
		selectedActivity = selectionInMenu;
		selectedYear = getTimeYear();
		selectedMonth = getTimeMonth();
		selectedDate = getTimeDate();
		selectedDay = getTimeDay();
		selectedHour = getTimeHour();
		selectedMinute = getTimeMinute();
		selectedSecond = getTimeSecond();
		currentMenuID++;
	}	
	//[Log - Choose Mood]	
	else if (currentMenuID == 21){
		selectedMood = selectionInMenu;
		currentMenuID++;		
	}
	//[Log - Confirm]
	else if (currentMenuID == 22){	

		insertRecord(selectedYear,selectedMonth,selectedDate, selectedDay, selectedHour,selectedMinute,selectedSecond,selectedActivity,selectedMood);
		currentMenuID = 10;	
	}
	//[View Timeline]
	else if (currentMenuID == 30){
		currentMenuID = 10;
	}
	
	//[Edit,Add,Remove]
	else if (currentMenuID == 40){
		uint8_t numberOfRecords = getUnencrpytedRecordCount();
		if (selectionInMenu == 0){
			if(numberOfRecords == 0){
				selectedYear = getTimeYear();
				selectedMonth = getTimeMonth();
				selectedDate = getTimeDate();
				selectedDay = getTimeDay();
				currentMenuID = 42;
			}	
			else{
				currentMenuID = 41;
			}							
		}
		else{				
			if(numberOfRecords == 0)
				currentMenuID = 43;
			else{
				if (selectionInMenu == 1)
				currentMenuID = 50;
				else if (selectionInMenu == 2)
				currentMenuID = 60;
			}				
		}				
	}
	
	//[Add]
	else if (currentMenuID == 41){
		uint8_t numberOfRecords = getUnencrpytedRecordCount();
		if(numberOfRecords != 0){
			iter = getMemMapStartIndex();
			selectedRecord = (selectionInMenu + iter) % maxRecNum;
			address = getMemMapElement(selectedRecord);
		}
		else{		
			selectedMinute = getTimeMinute();
			selectedSecond = getTimeSecond();
		}		
		selectedYear = getTimeYear();
		selectedMonth = getTimeMonth();
		selectedDate = getTimeDate();
		selectedDay = getTimeDay();
		selectedHour = getTimeHour();
		firstPass = 0;
		currentMenuID = 42;
	}
	
	//[Add - choose time]
	else if (currentMenuID == 42){
		if(timeSelection == HOUR)
			timeSelection = MINUTE;
		else
			currentMenuID = 44;	
	}
	
	//[Edit - NO RECORDS]
	else if (currentMenuID == 43){
		currentMenuID = 10;
	}

	//[Add - choose Activity]
	else if (currentMenuID == 44){
		selectedActivity = selectionInMenu;
		currentMenuID = 45;
	}
	
	//[Add - choose Mood]
	else if (currentMenuID == 45){
		selectedMood = selectionInMenu;
		currentMenuID = 46;
	}
	
	//[Add - Confirm]
	else if (currentMenuID == 46){
		
		insertRecord(selectedYear,selectedMonth,selectedDate, selectedDay, selectedHour,selectedMinute,0,selectedActivity,selectedMood);
		
		currentMenuID = 10;
	}
	
	//[Edit - choose time]
	else if (currentMenuID == 50){
		start = getMemMapStartIndex();
		selectedIndex = (selectionInMenu + start) % maxRecNum;
		address = getMemMapElement(selectedIndex);
		activityInRecord = getActivity(address);
		moodInRecord = getMood(address);
		selectedHour = getHour(address);
		selectedMinute = getMinute(address);
		currentMenuID = 51;
	}
	
	//[Edit - Mood or Act]
	else if (currentMenuID == 51){
		if (selectionInMenu == 0){
			firstPass = 0;
			currentMenuID = 52;
		}			
		else if (selectionInMenu == 1)
			currentMenuID = 56;
	}

	//[Edit - Act - Choose Time]
	else if (currentMenuID == 52){
		if(timeSelection == HOUR)
			timeSelection = MINUTE;
		else
		currentMenuID = 54;
	}

	//[Edit - Act - Choose Act]
	else if (currentMenuID == 54){
		selectedActivity = selectionInMenu;
		selectedMood = moodInRecord;
		currentMenuID = 55;
	}

	//[Edit - Act - Confirm]
	else if (currentMenuID == 55){
		setHourByAddress(address,selectedHour);
		setMinuteByAddress(address,selectedMinute);
		setActivityByAddress(address,selectedActivity);		
		currentMenuID = 10;
	}

	//[Edit - Mood - Choose Mood]
	else if (currentMenuID == 56){
		selectedMood = selectionInMenu;
		selectedActivity = activityInRecord;
		currentMenuID = 57;
	}

	//[Edit - Mood - Confirm]
	else if (currentMenuID == 57){
		setMoodByAddress(address,selectedMood);
		currentMenuID = 10;
	}
	
	//[Remove - choose record]
	else if (currentMenuID == 60){
		iter = getMemMapStartIndex();
		selectedRecord = (selectionInMenu + iter) % maxRecNum;
		address = getMemMapElement(selectedRecord);
		selectedActivity = getActivity(address);
		selectedMood = getMood(address);
		selectedHour = getHour(address);
		selectedMinute = getMinute(address);
		currentMenuID = 61;
	}

	//[Remove - confirm]
	else if (currentMenuID == 61){
		deleteRecord(selectedRecord);
		currentMenuID = 10;
	}

	//[Settings]
	else if (currentMenuID == 70){
		if(selectionInMenu == 0){
			firstPass = 0;
			currentMenuID = 71;	
		}			
		else if(selectionInMenu == 1)
			currentMenuID = 72;
		else if(selectionInMenu == 2)
			currentMenuID = 73;
	}
	
	//[Settings - modify Time]
	else if (currentMenuID == 71){
		if(timeSelection == HOUR)
			timeSelection = MINUTE;
		else if (timeSelection == MINUTE)
			timeSelection = DAY;
		else if (timeSelection == DAY)
			timeSelection = MONTH;
		else if (timeSelection == MONTH)
			timeSelection = YEAR;
		else{
			currentMenuID = 70;
			modifiedTimeFlag = 1;
		}			
	}

	//[Settings - Invert Screen]
	else if (currentMenuID == 72){
		invertColours = getInvertColourSetting();
		setInvertColourSetting(!invertColours);
		invertColours = !invertColours;
	}
	
	//[Settings - Reset]
	else if (currentMenuID == 73){
		currentMenuID = 74;
	}
	
	//[Settings - Reset]
	else if (currentMenuID == 74){
		resetRecords();
		currentMenuID = 70;
	}	
			
	//[Upload]
	else if (currentMenuID == 80){
		//currentMenuID = 10;
	}
	
	selectionInFrame = 0;
	selectionInMenu = 0;
}	
//Allows user to configure the time
void drawChangeTime(void){
	selectedYear = getTimeYear();
	selectedMonth = getTimeMonth();
	selectedDay = getTimeDate();
	selectedDOW = getTimeDay();	
	selectedHour = getTimeHour();
	selectedMinute = getTimeMinute();
	selectedSecond = getTimeSecond();
	
	if(firstPass == 0){
		timeSelection = 0;
		firstPass = 1;
	}		
	
	if (timeSelection == HOUR){
		if (manipulateTime == INCREMENT){
			if ((selectedHour + 1) >= 24)
				selectedHour = 0;			
			else
				selectedHour += 1;
			setTimeHour(selectedHour);			
			manipulateTime = NEUTRAL;
		}
		else if (manipulateTime == DECREMENT){
			if ((selectedHour - 1) < 0)
				selectedHour = 23;
			else
				selectedHour -= 1;
			setTimeHour(selectedHour);
			manipulateTime = NEUTRAL;
		}
	}
	else if (timeSelection == MINUTE){
		if (manipulateTime == INCREMENT){
			if ((selectedMinute + 1) >= 60)
				selectedMinute = 0;
			else
				selectedMinute += 1;
			setTimeMinute(selectedMinute);
			manipulateTime = NEUTRAL;
		}
		else if (manipulateTime == DECREMENT){
			if ((selectedMinute - 1) < 0)
				selectedMinute = 59;
			else
				selectedMinute -= 1;
			setTimeMinute(selectedMinute);
			manipulateTime = NEUTRAL;
		}
	}		
	else if (timeSelection == DAY){
		if (manipulateTime == INCREMENT){
			if ((selectedDay + 1) >= monthDays[selectedMonth-1]+1)
				selectedDay = 1;
			else
				selectedDay += 1;
			setTimeDay(selectedDay);
			manipulateTime = NEUTRAL;
		}
		else if (manipulateTime == DECREMENT){
			if ((selectedDay - 1) < 1)
				selectedDay = monthDays[selectedMonth-1];
			else
				selectedDay -= 1;
			setTimeDay(selectedDay);
			manipulateTime = NEUTRAL;
		}
	}		
	else if (timeSelection == MONTH){
		if (manipulateTime == INCREMENT){
			if ((selectedMonth + 1) >= 13)
				selectedMonth = 1;
			else
				selectedMonth += 1;
			setTimeMonth(selectedMonth);
			manipulateTime = NEUTRAL;
		}
		else if (manipulateTime == DECREMENT){
			if ((selectedMonth - 1) < 1)
				selectedMonth = 12;
			else
				selectedMonth -= 1;
			setTimeMonth(selectedMonth);
			manipulateTime = NEUTRAL;
		}
		//selectedDay = getTimeDate();
		if(monthDays[selectedMonth-1] < selectedDay){
			selectedDay = monthDays[selectedMonth-1];
			setTimeDay(selectedDay);
		}			
	}		
	else if (timeSelection == YEAR){
		if (manipulateTime == INCREMENT){
			if ((selectedYear + 1) >= 100)
				selectedYear = 0;
			else
				selectedYear += 1;
			setTimeYear(selectedYear);
			manipulateTime = NEUTRAL;
		}
		else if (manipulateTime == DECREMENT){
			if ((selectedYear - 1) < 0)
				selectedYear = 99;
			else
				selectedYear -= 1;
			manipulateTime = NEUTRAL;
			setTimeYear(selectedYear);
		}
	}
	
	setTimeDOW(calculateDOW(selectedDay,selectedMonth,selectedYear));
	
	printTime();
	printStringOnLine(1,"  Time Settings   ", 1,NOBOXMENU);
	printStringOnLine(2,"                  ", 0,NOBOXMENU);		
	printTimeSelectionOnLine(3,selectedHour,selectedMinute,0,timeSelection);
	printDateSelectionOnLine(4,selectedDay,selectedMonth,selectedYear,0,timeSelection);
	printStringOnLine(5,"                  ", 1,NOBOXMENU);
	printStringOnLine(6,"  Set the Time    ", 1,NOBOXMENU);
	printStringOnLine(7,"                  ", 1,NOBOXMENU);		
}
void startClock(void){
	DS1307Write(0x00,dec2bcd(getTimeSecond()) | 0x7F);	//set seconds
}
void SessionsViewController::onRequestFinished(const HttpResponseStatus& status, const CSJson::Value& json)
{
    if (status == HttpResponseSucceed && !json.empty())
    {
        CSJson::FastWriter writer;
        string tempjson = writer.write(json);
        //CCLog("receive json == %s",tempjson.c_str());
        
        const CSJson::Value& value = json["result"];
		FDataManager::getInstance()->setDiffServerTime(value["stime"].asInt64());

        m_msg->clear();
        m_msgFilter.clear();

		const CSJson::Value& v1 = json["result"]["sel"];
		int length = v1.size();
		for (int index = 0; index < length; index++)
		{
			sessionMsg temp_msg;
			temp_msg.m_sessionId = v1[index]["SessionId"].asInt();
			temp_msg.m_title = v1[index]["Title"].asString();
			temp_msg.m_location = v1[index]["Location"].asString();
			temp_msg.m_track = v1[index]["Track"].asString();
			temp_msg.m_format = v1[index]["Format"].asString();
			temp_msg.m_startTime = v1[index]["StartTime"].asInt64();
			temp_msg.m_endTime = v1[index]["EndTime"].asInt();
			temp_msg.m_likeNum = v1[index]["LikeCnt"].asInt();
			temp_msg.m_imageUrl = crossapp_format_string("%s%s", imgPreUrl.c_str(), v1[index]["Logo"].asCString());
			temp_msg.m_stored = v1[index]["CollectionFlag"].asBool();
			temp_msg.m_liked = v1[index]["LikeFlag"].asBool();
			temp_msg.m_done = v1[index]["Done"].asBool();
			temp_msg.m_point = v1[index]["Point"].asBool();
			m_msg->push_back(temp_msg);
		}
		const CSJson::Value& v2 = json["result"]["usr"];
        userInfo* uInfo = FDataManager::getInstance()->getUserInfo();
        uInfo->m_loginName = v2["LoginName"].asString();
        uInfo->m_userId = FDataManager::getInstance()->getUserId();
        uInfo->m_userName = crossapp_format_string("%s %s", v2["FirstName"].asString().c_str(), v2["LastName"].asString().c_str());
        uInfo->m_point = v2["Score"].asInt();
        uInfo->m_imageUrl = crossapp_format_string("%s%s", imgPreUrl.c_str(), v2["Icon"].asCString());
        uInfo->m_eggVoted = v2["EggVoted"].asBool();
        uInfo->m_greenAmb = v2["GreenAmb"].asBool();
        uInfo->m_demoVoteIdVec.clear();
        uInfo->m_voiceVoteIdVec.clear();
        int voteId = v2["DemoJamId1"].asInt();
        if (voteId != -1)
        {
            uInfo->m_demoVoteIdVec.push_back(voteId);
        }
        voteId = v2["DemoJamId2"].asInt();
        if (voteId != -1)
        {
            uInfo->m_demoVoteIdVec.push_back(voteId);
        }
        voteId = v2["VoiceVoteId1"].asInt();
        if (voteId != -1)
        {
            uInfo->m_voiceVoteIdVec.push_back(voteId);
        }
        voteId = v2["VoiceVoteId2"].asInt();
        if (voteId != -1)
        {
            uInfo->m_voiceVoteIdVec.push_back(voteId);
        }

        quickSort(m_msg, 0, (int)m_msg->size() - 1);
    }
	else
	{
		//showAlert();
	}
#ifdef LOCALTEST
    {
		m_msg->clear();

		for (int i = 0; i < 17; i++)
		{
			sessionMsg temp_msg;
			temp_msg.m_sessionId = 200 + i;
			temp_msg.m_title = "Customer Success";

			temp_msg.m_location = "Lisa Chen";
			temp_msg.m_track = "Customer";
			temp_msg.m_format = "Dev Faire";
			temp_msg.m_startTime = getTimeSecond();
			temp_msg.m_endTime = temp_msg.m_startTime + 3900;
			temp_msg.m_likeNum = 20;
			temp_msg.m_stored = (bool)(rand() % 2);
			temp_msg.m_imageUrl =
				"http://imgsrc.baidu.com/forum/pic/item/53834466d0160924a41f433bd50735fae6cd3452.jpg";
			//"http://img1.gtimg.com/14/1468/146894/14689486_980x1200_0.png";
			temp_msg.m_liked = (bool)(rand() % 2);
			temp_msg.m_done = (bool)(rand() % 2);
			temp_msg.m_point = 22;
			m_msg->push_back(temp_msg);

			userInfo uInfo;
			uInfo.m_userId = 101;
			uInfo.m_userName = "******";
			uInfo.m_point = 100;
			uInfo.m_pointRank = 20;
			uInfo.m_imageUrl = "http://imgsrc.baidu.com/forum/pic/item/53834466d0160924a41f433bd50735fae6cd3452.jpg";
			FDataManager::getInstance()->setUserInfo(uInfo);
		}
		quickSort(m_msg, 0, (int)m_msg->size() - 1);
    }
#endif

	refreshTableData();

    if (p_pLoading)
    {
        p_pLoading->stopAnimating();
    }
    
}