<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

// +----------------------------------------------------------------------+
// | This page is for user section management. Login checking , new user registration, user listing etc.                                      |
// | File name : index.php                                                  |
// | PHP version >= 5.2                                                   |
// | Created On	: 	Nov 17 2011                                               |
// +----------------------------------------------------------------------+
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems ? 2010                                      |
// | All rights reserved                                                  |
// +------------------------------------------------------


class ControllerUser extends BaseController
{
    /*
      construction function. we can initialize the models here
     */

    public function init()
    {       
        parent::init();
        PageContext::$response = new stdClass();
        PageContext::$response->flagDisplay = 0;
        PageContext::$response->ImagePath = IMAGE_MAIN_URL;
        PageContext::$response->userImagePath = USER_IMAGE_URL;
        PageContext::$response->baseUrl = BASE_URL;
        PageContext::$response->sitelogo = SITE_LOGO;
        PageContext::$response->innerlogo = INNER_LOGO;
        PageContext::$response->curYear = date('Y');
        PageContext::$response->defaultImage = USER_IMAGE_URL_DEFAULT;
        PageContext::$response->bbfCharges = BBF_CHARGES;
        PageContext::$response->bbfTransactionCharges = BBF_TRANSACTION_CHARGE;
        PageContext::$response->activeSubMenu = '';
        PageContext::$response->isFBEnabled = FB_ENABLED;
        PageContext::$response->sess_user_last_login = Utils::getAuth('user_last_login');
//        echo PageContext::$response->sess_user_last_login;
        PageContext::$response->sess_user_id = Utils::getAuth('user_id');
        $user = User::getUserDetailId(PageContext::$response->sess_user_id);
       // echopre1($user);
        PageContext::$response->sess_user_status = $user->data->user_status;
        PageContext::$response->sess_user_name = $user->data->user_firstname . ' ' . $user->data->user_lastname;
        PageContext::$response->sess_user_alias = $user->data->user_alias;
        PageContext::$response->sess_user_email = $user->data->user_email;
        PageContext::$response->sess_user_fname = $user->data->user_firstname;
        PageContext::$response->sess_user_lname = $user->data->user_lastname;
        PageContext::$response->sess_user_image = '';
        PageContext::$response->sess_user_image = $user->data->Image;
        PageContext::$response->username = User::getUserNameFromAlias(PageContext::$response->sess_user_alias);
        PageContext::addJsVar('user_chat', PageContext::$response->username);
        $page = PageContext::$request['page'];
        $itemperpage = PAGE_LIST_COUNT;

        $announcementCount = Communities::getAnnouncementCountByUser();
        PageContext::$response->announcementCount = $announcementCount[0]->cmember_announcement_count;
        if (PageContext::$response->announcementCount == '') {
            PageContext::$response->announcementCount = 0;
        }
        $messageCount = Messages::getMessageCountByUser();
        PageContext::$response->messageCount = $messageCount[0]->user_message_count;
        $frndcount = Feed::getNumPendingFriendRequestByUser();
        PageContext::$response->NumFriendRequest = $frndcount[0]->user_friend_request_count;
        $users = Feed::getNumPendingPrivateRequestByUser();
        PageContext::$response->NumPrivateRequest = $users[0]->user_private_request_count;
        PageContext::$response->chat_display = CHAT_DISPLAY;
        if (PageContext::$response->sess_user_id > 0) {
            PageContext::registerPostAction("header", "header_inner", "user", "default");
            PageContext::$response->leftMenuUsersList = User::getUserFriends1(PageContext::$response->sess_user_alias, 'N.A', 'N.A');
        } else {
            PageContext::registerPostAction("header", "header_login", "index", "default");
        }
        
        PageContext::registerPostAction("footer", "home_footer", "index", "default");
        PageContext::registerPostAction("searchbox", "searchbox", "index", "default");
        PageContext::registerPostAction("messagebox", "messagebox", "index", "default");
        PageContext::addScript("common.js");
        PageContext::addScript("jssor.slider.mini.js");
        PageContext::addScript('jquery.colorbox.js');
        PageContext::addScript("script.js");
        PageContext::addScript("menu.js");
        PageContext::addJsVar('FB_APP_ID', FB_APP_ID);
    }

    public function newsfeed($alias, $ajaxmode)
    {
       // echo "here";exit;
        Utils::checkUserLoginStatus();
        //echo PageContext::$response->sess_user_status;exit;
        if (PageContext::$response->sess_user_status == 'I') {
            session_start(); 
        session_unset(); 
        session_destroy();
            $this->redirect("inactiveuser");
        }
        PageContext::addStyle("style1.css");
        PageContext::addScript("jquery.form.min.js");
        PageContext::addScript("jquery.autogrow.js");
        $userDetails = User::getUserDetails($alias);
        if($userDetails->data->Id == ''){
            PageContext::$response->sess_user_image = '';
            PageContext::$response->sess_user_name = '';
        }
        if (PageContext::$response->sess_user_status == 'I' && PageContext::$response->sess_user_alias == $alias) {
            $this->redirect("inactiveuser");
        }

        PageContext::addStyle('jquery.share.css');
        PageContext::addScript('tether.min.js');
        PageContext::addScript('config.js');
        PageContext::addScript('util.js');
        PageContext::addJsVar('ALIAS', $alias);

        PageContext::$response->activeSubMenu = 'profile';
        PageContext::$response->organization_display = ORG_DISPLAY;
        if(ORG_DISPLAY == 1){
            $leads = Business::getAllBusinessForUser();
            PageContext::$response->organization_display_list = $leads->records;
        }
        PageContext::$response->group_display = GRP_DISPLAY;
        if(GRP_DISPLAY == 1){
            $leads = Communities::getAllCommunities('',5);
            PageContext::$response->group_display_list = $leads->records;
        }
        PageContext::$response->organization_display = ORG_DISPLAY;
        if(FRND_DISPLAY == 1){
            $leads = User::getUserFriends($alias,'users.*',3);
            PageContext::$response->friend_display_list = $leads->data;
        }
        PageContext::$response->friend_display = FRND_DISPLAY;
        if(GALLERY_DISPLAY == 1){
            //$gallery = User::getUserFriends($alias,'users.*',3);
            PageContext::$response->gallery_display_list = Feed::getMyLatestNewsfeedImage($userDetails->data->Id);
           
             
        }
        PageContext::$response->gallery_display = GALLERY_DISPLAY;
//        if(ORG_DISPLAY == 1){
//            $leads = Business::getAllBusinessForUser();
//            PageContext::$response->organization_display_list = $leads->records;
//        }
        //=====================News Feed====================================
        if (PageContext::$response->sess_user_id > 0) {
            $share_array = array();
            $feed_array = array();
            $search = $_GET['search'];
            $business_type = $_GET['business_type'];
            PageContext::$response->search = $search;
            PageContext::$response->business_type = $business_type;
        }
        //=======================================================

        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "newsfeed", "user", "default");

        PageContext::addJsVar("LOGGED_USER_ALIAS", PageContext::$response->sess_user_alias);
        PageContext::addJsVar("CURRENT_USER_ALIAS", $alias);
        PageContext::addScript('profile.js');
        PageContext::addScript('search.js');
        PageContext::addScript("jquery.colorbox.js");
        PageContext::addScript('comment_popup.js');
        PageContext::addScript('timeago.js');
        PageContext::addScript('profile_business.js');
        PageContext::addScript('community.js');
        PageContext::addScript('jquery.share.js');
        PageContext::addScript('organisation.js');

        PageContext::$response->tojoin = " to join " . SITE_NAME;
        PageContext::$response->invitation_type = 'user';
        PageContext::$response->invitation_typeid = $userDetails->data->Id;
        PageContext::$body_class = 'member_area';
        PageContext::$response->username = User::getUserNameFromAlias($alias);
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$metaTitle = META_TITLE;// = META_TITLE;//SITE_NAME . " : Your personalised social network";
        PageContext::$metaDes = META_DES;// = META_DES;//SITE_NAME . " - Member Profile";
        PageContext::$metaKey = META_KEYWORDS;//= META_KEYWORDS;//SITE_NAME . " - Member Profile";

        PageContext::$response->message = Messages::getPageMessage();
        PageContext::$response->alias = $alias;

        //=========Fetch user details===============
        $userDetails = User::getUserDetails($alias);
        //echopre1($userDetails);
        PageContext::$response->userDetails = Utils::objectToArray($userDetails->data);
        PageContext::$response->userLastLogin = explode(' ', $userDetails->data->user_last_login);
        if (PageContext::$response->userDetails['Image'] == '') {
            PageContext::$response->image = "member_noimg.jpg";
        } else {
            PageContext::$response->image = PageContext::$response->userDetails['Image'];
        }
        
        
        
        
        
        PageContext::$response->communityAnnouncements = Communities::getAnnouncementsNewsfeed(1,5,$userDetails->data->Id);
        //$result = Communities::getCommunityAlias($communityData->data->community_id);
        // echopre(PageContext::$response->communityAnnouncements);
        PageContext::$response->communityId = $communityData->data->community_id;
        $comments = Comments::getAllComments($orderfield, $orderby, $page, $itemperpage, $search, $searchtypeArray, 'C', 5);
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->slno = 1;
        PageContext::$response->leads = $comments->records;
        PageContext::$response->totalrecords = $comments->totalrecords;
        PageContext::$response->pagination = Pagination::paginate($page, $itemperpage, $comments->totalrecords, $targetpage);
        PageContext::$response->comments = $comments->records;

            $share_array = array();
            $feed_array = array();
            $search = $_GET['search'];
            PageContext::$response->search = $search;
            //-------------Share------------------------
            if ($search == '' OR $search == 'S') {
                $shares = Feed::getFriendShares();
                foreach ($shares->records AS $share_item) {
                    $share_array[strtotime($share_item->share_date)][] = (array)$share_item;
                }
            }
            //----------------------Announcemnet -----------
            if ($search == '' OR $search == 'A' OR $search == 'S') {
                if ($search != 'S') {
                    $feeds = Feed::listUserFeedsNewsFeed('', $searchfeed = '', 1, 5);
                }
               // echopre($feeds);
                PageContext::addJsVar('TOTAL_FEED_PAGES', $feeds->totpages/5);
                foreach ($feeds->records AS $feed_item) {
                    $feed_array[][] = (array)$feed_item;
                }
                //----------News feed (Share+announcement)-------------
                $news_array = $share_array + $feed_array;
                krsort($news_array);
                PageContext::$response->feeds = $news_array;
                 foreach ($news_array AS $newsItems) {
                    // echopre($newsItems);
                     $news1[] = $newsItems[0];
                 }
                //--------------------Feed Comments----------------
               
            }
            
        $news_feed_count = User::getNewsFeed('','',$userDetails->data->Id);
        PageContext::addJsVar("TOTAL_FEED_PAGES", count($news_feed_count->data)/5);  
        $news_feed = User::getNewsFeed(1,5,$userDetails->data->Id);
        $orgfeeds = Business::getAnnouncementsNewsfeed(1,'',5,$userDetails->data->Id);
        //echopre($orgfeeds);exit;
        if($orgfeeds->data){
            //echopre($orgfeeds->data);
            $news_feed->data=!is_array($news_feed->data)?array():$news_feed->data;
            $merge = array_merge($news_feed->data, $orgfeeds->data); 
//            echopre($merge);exit;
        }
        else{
            $merge = $news_feed->data;
             //echopre($merge);exit;
        }
        
        if(is_array($news1)){
            $merge1 = array_merge($merge,$news1);
        }else{
            $merge1 = $merge;
        }
        
        $list = self::array_sort($merge1, 'days', 'SORT_DESC');
//        print_r($list);exit;
        //echopre($list);
        PageContext::$response->news_feed = $list;
        foreach ($list as $data) {
          // echopre($data);
            if($data['news_feed_id']!=''){
                $news_feed = Feed::getFeedComments($data['news_feed_id']);
//               echopre1($news_feed);
                $news_feed_like_users = Feed::getFeedLikesUsers($data['news_feed_id']);
                
                
                foreach ($news_feed->records as $value) { 
                   $replies = Feed::showFeedCommentReply($value->news_feed_comments_id); 
                   $like_user_comment_comments = Feed::showFeedCommentOfCommentsLikeUser($value->news_feed_comments_id); 
                foreach($like_user_comment_comments as $data1){
                   // echo $data->user_name;
                    $name .=  $data1->user_name.",";
                }
                $name = rtrim($name, ",");
                $news_feed->records['users']= $name;
                $value->user_image=User::getUserDetail($value->user_id)->data->Image;

//                echo $value['user_id'];
                
                   if($replies->totalrecords > 0){
                   $news_feed->records[$value->news_feed_comments_id] = $replies->totalrecords;
                   }
                   
                    
                }
//                echopre1($news_feed->records);
                PageContext::$response->newsFeedLikeUsers[$data['news_feed_id']] = $news_feed_like_users;
                PageContext::$response->newsFeed[$data['news_feed_id']] = $news_feed->records;
//                print_r(PageContext::$response->newsFeed[$data['news_feed_id']]);
                PageContext::$response->Page[$data['news_feed_id']]['totpages'] = $news_feed->totpages;
                PageContext::$response->Page[$data['news_feed_id']]['currentpage'] = $news_feed->currentpage;
            }
          
            elseif ($data['organization_announcement_id'] !='')
                  {
                $comments = Business::getAnnouncementComments($data['organization_announcement_id']);
              //  echopre1($comments);
                  foreach($comments->records as $value) {
                    //  echopre1($value);
                  // $replies = Feed::showFeedCommentReply($value->news_feed_comments_id); 
                   $like_user_comment_comments1 = Business::showOrgCommentOfCommentsLikeUser($value->organization_announcement_comment_id); 
                  // echopre($like_user_comment_comments1);
                foreach($like_user_comment_comments1 as $data2){
                 //   echo $data2->user_name;
                    $name1 .=  $data2->user_name.",";
                }
                $name1 = rtrim($name1, ",");
                $comments->records['users']= $name1; 
                $value->user_image=User::getUserDetail($value->user_id)->data->Image;
//                $comments->records['user_image']=User::getUserDetail($comments->records['user_id'])['Image'];

                }
                $news_feed_like_users = Business::getOrganizationCommentsLikesUsers($data['organization_announcement_id']);
               // echopre1($news_feed_like_users);
            PageContext::$response->newsFeedLikeUsers[$data['organization_announcement_id']] = $news_feed_like_users;
            PageContext::$response->newsFeed[$data['organization_announcement_id']] = $comments->records;
            PageContext::$response->Page[$data['organization_announcement_id']]['totpages'] = $comments->totpages;
            PageContext::$response->Page[$data['organization_announcement_id']]['currentpage'] = $comments->currentpage;
                  }
          elseif($data['community_announcement_id'] !=''){
               $comments = Feed::getAnnouncementComments($data['community_announcement_id']);
                foreach($comments->records as $value) {
                   //   echopre1($value);
                  // $replies = Feed::showFeedCommentReply($value->news_feed_comments_id); 
                   $like_user_comment_comments2 = Business::showGrpCommentOfCommentsLikeUser($value->announcement_comment_id); 
                  // echopre($like_user_comment_comments1);
                foreach($like_user_comment_comments2 as $data3){
                 //   echo $data2->user_name;
                    $name2 .=  $data3->user_name.",";
                }
                $name2 = rtrim($name2, ",");
                $comments->records['users']= $name2; 
                $value->user_image=User::getUserDetail($value->user_id)->data->Image;

                }
               $news_feed_like_users = Feed::getGroupCommentsLikesUsers($data['community_announcement_id']);
               // echopre1($news_feed_like_users);
                PageContext::$response->newsFeedLikeUsers[$data['community_announcement_id']] = $news_feed_like_users;
                PageContext::$response->newsFeed[$data['community_announcement_id']] = $comments->records;
                PageContext::$response->Page[$data['community_announcement_id']]['totpages'] = $comments->totpages;
                PageContext::$response->Page[$data['community_announcement_id']]['currentpage'] = $comments->currentpage;
          }
         //   echopre1(PageContext::$response->newsFeedLikeUsers);
        }
        $userDetails = User::getUserDetails($alias);
        if($userDetails->data->Id == ''){
            PageContext::$response->sess_user_image = '';
            PageContext::$response->sess_user_name = '';
        }
       // echopre(PageContext::$response->newsFeed);
        PageContext::addScript('friends_lazyload.js');
        PageContext::addScript('newsfeed_lazyload.js');

    }
    
    public function array_sort($array, $on, $order=SORT_ASC){

    $new_array = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
                break;
            case SORT_DESC:
                arsort($sortable_array);
                break;
        }

        foreach ($sortable_array as $k => $v) {
            $new_array[$k] = $array[$k];
        }
    }

    return $new_array;
}
    public function newsfeedajax($pagenum)
    {
        //echo "fgfgjfkg";exit;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $alias = $_POST['alias'];
        PageContext::addStyle("style1.css");
        PageContext::addScript("jquery.form.min.js");
        PageContext::addScript("jquery.autogrow.js");

        if (PageContext::$response->sess_user_status == 'I' && PageContext::$response->sess_user_alias == $alias) {
            $this->redirect("inactiveuser");
        }

        PageContext::addStyle('emoji.css');
        PageContext::addStyle('nanoscroller.css');
        PageContext::addStyle('jquery.share.css');
        //PageContext::addScript('nanoscroller.min.js');
        PageContext::addScript('tether.min.js');
        PageContext::addScript('config.js');
        PageContext::addScript('util.js');
        PageContext::addScript('common.js');
        PageContext::addJsVar('ALIAS', $alias);

        PageContext::$response->activeSubMenu = 'profile';
        PageContext::$response->organization_display = ORG_DISPLAY;
        if(ORG_DISPLAY == 1){
            $leads = Business::getAllBusinessForUser();
            PageContext::$response->organization_display_list = $leads->records;
        }
        PageContext::$response->group_display = GRP_DISPLAY;
       if(GRP_DISPLAY == 1){
            $leads = Communities::getAllCommunities();
            PageContext::$response->group_display_list = $leads->records;
        }
        PageContext::$response->organization_display = ORG_DISPLAY;
        if(FRND_DISPLAY == 1){
            $leads = User::getUserFriends($alias,'users.*',5);
           PageContext::$response->friend_display_list = $leads->data;
        }
        PageContext::$response->friend_display = FRND_DISPLAY;

        //=====================News Feed====================================
        if (PageContext::$response->sess_user_id > 0) {
            $share_array = array();
            $feed_array = array();
            $search = $_GET['search'];
            $business_type = $_GET['business_type'];
            PageContext::$response->search = $search;
            PageContext::$response->business_type = $business_type;
        }
        //=======================================================

        
        PageContext::addJsVar("LOGGED_USER_ALIAS", PageContext::$response->sess_user_alias);
        PageContext::addJsVar("CURRENT_USER_ALIAS", $alias);
        PageContext::addScript('profile.js');
        PageContext::addScript('search.js');
        PageContext::addScript("jquery.colorbox.js");
        PageContext::addScript('comment_popup.js');
        PageContext::addScript('timeago.js');
        PageContext::addScript('profile_business.js');
        PageContext::addScript('community.js');
        PageContext::addScript('jquery.share.js');

        PageContext::$response->tojoin = " to join " . SITE_NAME;
        PageContext::$response->invitation_type = 'user';
        PageContext::$response->invitation_typeid = PageContext::$response->sess_user_id;
        PageContext::$body_class = 'member_area';
        PageContext::$response->username = User::getUserNameFromAlias($alias);
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$metaTitle = META_TITLE;// = SITE_NAME . " : Your personalised social network";
        PageContext::$metaDes = META_DES;// = SITE_NAME . " - Member Profile";
        PageContext::$metaKey = META_KEYWORDS;//= SITE_NAME . " - Member Profile";

        PageContext::$response->message = Messages::getPageMessage();
        PageContext::$response->alias = $alias;

        //=========Fetch user details===============
        $userDetails = User::getUserDetails($alias);
        PageContext::$response->userDetails = Utils::objectToArray($userDetails->data);
        PageContext::$response->userLastLogin = explode(' ', $userDetails->data->user_last_login);
        if (PageContext::$response->userDetails['user_image_name'] == '') {
            PageContext::$response->image = "member_noimg.jpg";
        } else {
            PageContext::$response->image = PageContext::$response->userDetails['user_image_name'];
        }

//        $news_feed_count = User::getNewsFeed();
//        PageContext::addJsVar("TOTAL_FEED_PAGES", count($news_feed_count->data)/PAGE_LIST_COUNT);
//        $news_feed = User::getNewsFeed($pagenum,5);
//        
//        PageContext::$response->news_feed = $news_feed->data;
//        PageContext::addJsVar('TOTAL_FEED_PAGES', count($news_feed->data)/5);
//        foreach ($news_feed->data as $data) {
//
//            $news_feed = Feed::getFeedComments($data['news_feed_id']);
//            PageContext::$response->newsFeed[$data['news_feed_id']] = $news_feed->records;
//            PageContext::$response->Page[$data['news_feed_id']]['totpages'] = $news_feed->totpages;
//            PageContext::$response->Page[$data['news_feed_id']]['currentpage'] = $news_feed->currentpage;
//        }
        
          PageContext::$response->communityAnnouncements = Communities::getAnnouncementsNewsfeed($pagenum,5,PageContext::$response->sess_user_id);
        //$result = Communities::getCommunityAlias($communityData->data->community_id);
        // echopre1(PageContext::$response->communityAnnouncements);
       // PageContext::$response->communityId = $communityData->data->community_id;
//        $comments = Comments::getAllComments($orderfield, $orderby, $page, $itemperpage, $search, $searchtypeArray, 'C', 5);
//        if ($page > 1)
//            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
//        else
//            PageContext::$response->slno = 1;
//        PageContext::$response->leads = $comments->records;
//        PageContext::$response->totalrecords = $comments->totalrecords;
//        PageContext::$response->pagination = Pagination::paginate($page, $itemperpage, $comments->totalrecords, $targetpage);
//        PageContext::$response->comments = $comments->records;

            $share_array = array();
            $feed_array = array();
            $search = $_GET['search'];
            PageContext::$response->search = $search;
            //-------------Share------------------------
            if ($search == '' OR $search == 'S') {
                $shares = Feed::getFriendShares();
                foreach ($shares->records AS $share_item) {
                    $share_array[strtotime($share_item->share_date)][] = (array)$share_item;
                }
            }
            //----------------------Announcemnet -----------
            if ($search == '' OR $search == 'A' OR $search == 'S') {
                if ($search != 'S') {
                    $feeds = Feed::listUserFeedsNewsFeed('', $searchfeed = '', $pagenum, 5);
                }
               // PageContext::addJsVar('TOTAL_FEED_PAGES', $feeds->totpages/5);
                foreach ($feeds->records AS $feed_item) {
                    $feed_array[][] = (array)$feed_item;
                }
                //----------News feed (Share+announcement)-------------
                $news_array = $share_array + $feed_array;
                krsort($news_array);
                PageContext::$response->feeds = $news_array;
                 foreach ($news_array AS $newsItems) {
                    // echopre($newsItems);
                     $news1[] = $newsItems[0];
                 }
                //--------------------Feed Comments----------------
               
            }
            
//        $news_feed_count = User::getNewsFeed();
//        PageContext::addJsVar("TOTAL_FEED_PAGES", count($news_feed_count->data)/5);
        
        $news_feed = User::getNewsFeed($pagenum,5,PageContext::$response->sess_user_id);
        $orgfeeds = Business::getAnnouncementsNewsfeed($pagenum,'',5,PageContext::$response->sess_user_id);
        if($orgfeeds->data){
           $news_feed->data=!is_array($news_feed->data)?array():$news_feed->data;
            $merge = array_merge($news_feed->data, $orgfeeds->data); 
        }
        else{
            $merge = $news_feed->data;
        }
        
        if(is_array($news1)){
            $merge1 = array_merge($merge,$news1);
        }else{
            $merge1 = $merge;
        }
        
        $list = self::array_sort($merge1, 'days', 'SORT_DESC');
        PageContext::$response->news_feed = $list;
        foreach ($list as $data) {
          //  echopre($data);
            if($data['news_feed_id']!=''){
                $news_feed = Feed::getFeedComments($data['news_feed_id']);
                 $news_feed_like_users = Feed::getFeedLikesUsers($data['news_feed_id']);
                 
                 foreach ($news_feed->records as $value) {
                   $replies = Feed::showFeedCommentReply($value->news_feed_comments_id); 
                       $like_user_comment_comments = Feed::showFeedCommentOfCommentsLikeUser($value->news_feed_comments_id); 
                foreach($like_user_comment_comments as $data1){
                   // echo $data->user_name;
                    $name .=  $data1->user_name.",";
                }
                $name = rtrim($name, ",");
                $news_feed->records['users']= $name;
                $value->user_image=User::getUserDetail($value->user_id)->data->Image;
                   if($replies->totalrecords > 0)
                   $news_feed->records[$value->news_feed_comments_id] = $replies->totalrecords;
                }
                
                PageContext::$response->newsFeedLikeUsers[$data['news_feed_id']] = $news_feed_like_users;
                PageContext::$response->newsFeed[$data['news_feed_id']] = $news_feed->records;
                PageContext::$response->Page[$data['news_feed_id']]['totpages'] = $news_feed->totpages;
                PageContext::$response->Page[$data['news_feed_id']]['currentpage'] = $news_feed->currentpage;
            }
            elseif ($data['organization_announcement_id'] !='')
                  {
                $comments = Business::getAnnouncementComments($data['organization_announcement_id']);
                foreach($comments->records as $value) {
                    //  echopre1($value);
                  // $replies = Feed::showFeedCommentReply($value->news_feed_comments_id); 
                   $like_user_comment_comments1 = Business::showOrgCommentOfCommentsLikeUser($value->organization_announcement_comment_id); 
                  // echopre($like_user_comment_comments1);
                foreach($like_user_comment_comments1 as $data2){
                 //   echo $data2->user_name;
                    $name1 .=  $data2->user_name.",";
                }
                $name1 = rtrim($name1, ",");
                $comments->records['users']= $name1; 
                $value->user_image=User::getUserDetail($value->user_id)->data->Image;
                }
                $news_feed_like_users = Business::getOrganizationCommentsLikesUsers($data['organization_announcement_id']);
               // echopre1($news_feed_like_users);
            PageContext::$response->newsFeedLikeUsers[$data['organization_announcement_id']] = $news_feed_like_users;
           

            PageContext::$response->newsFeed[$data['organization_announcement_id']] = $comments->records;
            PageContext::$response->Page[$data['organization_announcement_id']]['totpages'] = $comments->totpages;
            PageContext::$response->Page[$data['organization_announcement_id']]['currentpage'] = $comments->currentpage;
                  }
          elseif($data['community_announcement_id'] !=''){
               $comments = Feed::getAnnouncementComments($data['community_announcement_id']);
                  foreach($comments->records as $value) {
                   //   echopre1($value);
                  // $replies = Feed::showFeedCommentReply($value->news_feed_comments_id); 
                   $like_user_comment_comments2 = Business::showGrpCommentOfCommentsLikeUser($value->announcement_comment_id); 
                  // echopre($like_user_comment_comments1);
                foreach($like_user_comment_comments2 as $data3){
                 //   echo $data2->user_name;
                    $name2 .=  $data3->user_name.",";
                }
                $name2 = rtrim($name2, ",");
                $comments->records['users']= $name2; 
                $value->user_image=User::getUserDetail($value->user_id)->data->Image;
                }
                $news_feed_like_users = Feed::getGroupCommentsLikesUsers($data['community_announcement_id']);
               // echopre1($news_feed_like_users);
                PageContext::$response->newsFeedLikeUsers[$data['community_announcement_id']] = $news_feed_like_users;

                PageContext::$response->newsFeed[$data['community_announcement_id']] = $comments->records;
                PageContext::$response->Page[$data['community_announcement_id']]['totpages'] = $comments->totpages;
                PageContext::$response->Page[$data['community_announcement_id']]['currentpage'] = $comments->currentpage;
          }
        }
        PageContext::addScript('friends_lazyload.js');
        PageContext::addScript('newsfeed_lazyload.js');

    }

    public function timeline($alias, $ajaxmode)
    {
        PageContext::addScript("jquery.form.min.js");
        PageContext::addScript("jquery.autogrow.js");
         $userDetails = User::getUserDetails($alias);
        if (PageContext::$response->sess_user_status == 'I' && PageContext::$response->sess_user_alias == $alias) {
            $this->redirect("inactiveuser");
        }
        if($userDetails->data->Id){
            PageContext::$response->sess_user_image = '';
        }
        PageContext::addJsVar('FB_APP_ID', FB_APP_ID);
        PageContext::addStyle('jquery.share.css');
        PageContext::addJsVar('ALIAS', $alias);
        PageContext::$response->activeSubMenu = 'profile';
        
        //=====================News Feed====================================
        if (PageContext::$response->sess_user_id > 0) {
            $share_array = array();
            $feed_array = array();
            $search = $_GET['search'];
            $business_type = $_GET['business_type'];
            PageContext::$response->search = $search;
            PageContext::$response->business_type = $business_type;
            PageContext::$response->timelineimage = User::getUserTimelineImage($alias);
            //-------------Share------------------------
            if ($search == '' OR $search == 'S') {
                $shares = Feed::getFriendShares();
                foreach ($shares->records AS $share_item) {
                    $share_array[strtotime($share_item->share_date)][] = (array)$share_item;
                }
            }

            //----------------------Announcemnet -----------
            if ($search == '' OR $search == 'A' OR $search == 'S') {
                if ($search != 'S') {
                    $feeds = Feed::listUserFeeds($business_type, $searchfeed = '', 1, 10);
                }
                PageContext::addJsVar('TOTAL_FEED_PAGES', $feeds->totpages);
                foreach ($feeds->records AS $feed_item) {
                    $feed_array[strtotime($feed_item->community_announcement_date)][] = (array)$feed_item;
                }

                //----------News feed (Share+announcement)-------------
                $news_array = $share_array + $feed_array;
                krsort($news_array);
                PageContext::$response->feeds = $news_array;

                //--------------------Feed Comments----------------
                foreach ($news_array AS $newsItems) {
                    foreach ($newsItems AS $news) {
//                        echopre1($news);
                        
                        if ($news['community_announcement_id']) {
                            $comments = Feed::getAnnouncementComments($news['community_announcement_id']);
                        }
                        PageContext::$response->Comments[$news['community_announcement_id']] = $comments->records;
                        PageContext::$response->Page[$news['community_announcement_id']]['totpages'] = $comments->totpages;
                        PageContext::$response->Page[$news['community_announcement_id']]['currentpage'] = $comments->currentpage;
                    }
                }

                PageContext::$response->count = $feeds->totalrecords;
            }
            //----------------Community dropdown--------------
            $communities = Feed::getAllCommunityNames();
            PageContext::$response->communities = $communities->data;
            $frndcount = Feed::getNumPendingFriendRequestByUser();
            PageContext::$response->NumFriendRequest = $frndcount[0]->user_friend_request_count;
            $users = Feed::getNumPendingPrivateRequestByUser();
            PageContext::$response->NumPrivateRequest = $users[0]->user_private_request_count;
            PageContext::$response->NumPendingBizcomMembers = Feed::getNumPendingBizcomMembers();
            pagecontext::$response->adminannouncement = pagecontext::$response->adminannouncements->data;
           

        }
        if(FRND_DISPLAY == 1){
            $leads = User::getUserFriends($alias,'users.*',3);
            PageContext::$response->friend_display_list = $leads->data;
        }
       // echopre1($leads->data);
        PageContext::$response->friend_display = FRND_DISPLAY;
        if(GALLERY_DISPLAY == 1){
            //$gallery = User::getUserFriends($alias,'users.*',3);
            PageContext::$response->gallery_display_list = Feed::getMyLatestNewsfeedImage(PageContext::$response->sess_user_id);
           
             
        }
        PageContext::$response->gallery_display = GALLERY_DISPLAY;
        //=======================================================
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "mytimeline", "user", "default");
        PageContext::addJsVar("LOGGED_USER_ALIAS", PageContext::$response->sess_user_alias);
        PageContext::addJsVar("CURRENT_USER_ALIAS", $alias);
        PageContext::addScript('profile.js');
        PageContext::addScript('search.js');    
        PageContext::addScript('comment_popup.js');
        PageContext::addScript('timeago.js');
        PageContext::addScript('profile_business.js');
        PageContext::addScript('community.js');
        PageContext::addScript('jquery.share.js');
        PageContext::$response->tojoin = " to join " . SITE_NAME;
        PageContext::$response->invitation_type = 'user';
        PageContext::$response->invitation_typeid = PageContext::$response->sess_user_id;
        PageContext::$body_class = 'member_area';
        PageContext::$response->username = User::getUserNameFromAlias($alias);
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$metaTitle = META_TITLE;// = SITE_NAME . " : Your personalised social network";
        PageContext::$metaDes = META_DES;// = SITE_NAME . " - Member Profile";
        PageContext::$metaKey = META_KEYWORDS;//= SITE_NAME . " - Member Profile";
        //=================Pending request==========================
        $pendingRequest = Connections::getUserPendingRequest($alias);
        PageContext::$response->pendingRequest = $pendingRequest->data;
        PageContext::$response->pendingRequestCount = sizeof($pendingRequest->data);

        //=============getCountires===========
        $country = Cmshelper::getAllCountries();
        $country_dropdown = array();
        if ($country) {
            $country_dropdown['--Country--'] = '';
            foreach ($country as $key => $val) {
                $country_dropdown[$val->text] = $val->value;
            }
        }
        PageContext::$response->countrydropdown = $country_dropdown;
        PageContext::$response->message = Messages::getPageMessage();
        PageContext::$response->alias = $alias;

        //=========Fetch user details===============
        //echo $alias;
       
       // echopre1($userDetails);
        $communityCount = Communities::getCommunityCount();
        PageContext::$response->community_count = $communityCount;
        $mutualFriendsCount = User::getUserMutualFriendCount(PageContext::$response->sess_user_id, $userDetails->data->Id);
        PageContext::$response->mutual_friend_count = $mutualFriendsCount;
        PageContext::$response->id = $userDetails->data->Id;
        PageContext::$response->user_name = $userDetails->data->Name;
        PageContext::$response->user_image = $userDetails->data->Image;
//        echo  PageContext::$response->user_image;exit;
       
        PageContext::addJsVar('TOTAL_PAGES', $userDetails->data->user_friends_count / LAZYLOAD_COUNT);
        PageContext::$response->userDetails = Utils::objectToArray($userDetails->data);
        PageContext::$response->business_friend = User::getFriendsCount(PageContext::$response->sess_user_id, 'B');
        PageContext::$response->personal_friend = User::getFriendsCount(PageContext::$response->sess_user_id, 'P');

        PageContext::$response->userLastLogin = explode(' ', $userDetails->data->user_last_login);
        if (PageContext::$response->userDetails['Image'] == '') {
            PageContext::$response->image = "member_noimg.jpg";
        } else {
            PageContext::$response->image = PageContext::$response->userDetails['Image'];
        }
        $tagDetails = User::getAssociatedBusiness($userDetails->data->Id);
        $total_pages = (sizeof($tagDetails->data) / LAZYLOAD_COUNT);
        PageContext::addJsVar('TOT_PAGESS', $total_pages);
        PageContext::$response->tagDetails = $tagDetails->data;

        //==============Ajax edit===============
        if ($ajaxmode == 'ajaxTrue') {
            PageContext::$response->sess_user_name = $_POST['user_firstname']." ".$_POST['user_lastname'];
            $objUserVo = new stdClass();
            $objUserVo->user_firstname = $_POST['user_firstname'];
            $objUserVo->user_lastname = $_POST['user_lastname'];
            $objUserVo->user_email = $_POST['user_email'];
            if ($_POST['user_date_of_birth'] != '') {
                $objUserVo->user_date_of_birth = date('Y-m-d', strtotime($_POST['user_date_of_birth']));
            } else {
                $objUserVo->user_date_of_birth = '';
            }
            $objUserVo->user_gender = $_POST['user_gender'];
            $objUserVo->user_address = $_POST['user_address'];
            $objUserVo->user_city = $_POST['user_city'];
            $objUserVo->user_state = $_POST['user_state'];
            $objUserVo->user_country = $_POST['user_country'];
            $objUserVo->user_phone = $_POST['user_phone'];
            $objUserVo->user_zipcode = $_POST['user_zipcode'];
            $objUserVo->user_privacy = $_POST['user_privacy'];
            $objUserVo->user_id = PageContext::$response->sess_user_id;
            $objUserRes = User::editUser(PageContext::$response->sess_user_id, $objUserVo);
            
            if ($objUserRes->status == SUCCESS) {//====================
                $data['msg'] = "User details updated successfully";
                $data['cls'] = "success_div";
                echo json_encode($data);
                exit;
            } else {

                $data['msg'] = $objUserRes->message;
                $data['cls'] = "error_div";
                echo json_encode($data);
                exit;
            }

        }
        if (PageContext::$response->sess_user_id != '') {
            $friends = User::getUserFriends(PageContext::$response->sess_user_alias, 'users.user_id');
            $user_id = User::getUserIdFromAlias($alias);
            PageContext::$response->friend_to = $user_id;
            foreach ($friends->data AS $friends) {
                $myfriends[] = $friends->user_id;
            }
            PageContext::$response->myfriends = $myfriends;
            $friends = User::getUserFriends(PageContext::$response->sess_user_alias, 'users.user_id');

            foreach ($friends->data AS $friends) {
                $myfriendsstatus[$friends->user_id] = $friends->friends_list_view_status;
            }
            PageContext::$response->myfriendsstatus = $myfriendsstatus;

            $invitations = Connections::getAllUserInvitationsSent(PageContext::$response->sess_user_alias, 'P', 'invitation_receiver_id');
            foreach ($invitations->data AS $invitations) {
                $myinvitations[] = $invitations->invitation_receiver_id;
            }
            PageContext::$response->myinvitedfriends = $myinvitations;
            $pendingFriendRequests = Connections::getUserPendingRequest(PageContext::$response->sess_user_alias);
            foreach ($pendingFriendRequests->data AS $pendingFriendRequest) {
                $myPendingRequests[] = $pendingFriendRequest->user_id;
                $myPendingRequestsInviteId[] = $pendingFriendRequest->invitation_id;
            }
            $key = array_search(PageContext::$response->id, $myPendingRequests);
            if ($key >= 0) { //echo"aaa";
                $inviteId = $myPendingRequestsInviteId[$key];
                PageContext::$response->inviteId = $inviteId;
            }
            PageContext::$response->myPendingRequests = $myPendingRequests;
        }

        if (Utils::getAuth('user_id')) {
            $bizcomInvite = Connections::getPendingBizComrequest(Utils::getAuth('user_id'));
            PageContext::$response->pendingBizcomrequests = $bizcomInvite->data;
        }
        PageContext::$response->message = Messages::getPageMessage();
        $leads = Communities::getSubscribedCommunityCount(Utils::getAuth('user_id'));
        PageContext::$response->Subscribed_community_count = $leads;
        $page = PageContext::$request['page'];
        $itemperpage = PAGE_LIST_COUNT;

        $announcementCount = Communities::getAnnouncementCountByUser();
        PageContext::$response->announcementCount = $announcementCount[0]->cmember_announcement_count;
        if (PageContext::$response->announcementCount == '') {
            PageContext::$response->announcementCount = 0;
        }
        $messageCount = Messages::getMessageCountByUser();
        $user_id = User::getUserIdFromAlias($alias);
        $news_feed1 = User::getTimeLine($user_id,'','');
        $count = count($news_feed1->data);
        PageContext::addJsVar('TOT_TIMELINE_PAGES', $count/5);
        
        $news_feed = User::getTimeLine($user_id,1,5);
        PageContext::$response->news_feed1 = $news_feed->data;
//        echopre($news_feed);
        foreach ($news_feed->data as $data) {
            $news_feed = Feed::getFeedComments($data['news_feed_id']);
            $news_feed_like_users = Feed::getFeedLikesUsers($data['news_feed_id']);
            
            foreach ($news_feed->records as $value) {
                   $replies = Feed::showFeedCommentReply($value->news_feed_comments_id); 
                       $like_user_comment_comments = Feed::showFeedCommentOfCommentsLikeUser($value->news_feed_comments_id); 
                foreach($like_user_comment_comments as $data1){
                   // echo $data->user_name;
                    $name .=  $data1->user_name.",";
                }
                $name = rtrim($name, ",");
                $news_feed->records['users']= $name;
                   if($replies->totalrecords > 0)
                   $news_feed->records[$value->news_feed_comments_id] = $replies->totalrecords;
                   $value->user_image=User::getUserDetail($value->user_id)->data->Image;
                }
            PageContext::$response->newsFeedLikeUsers[$data['news_feed_id']] = $news_feed_like_users;
            PageContext::$response->newsFeed[$data['news_feed_id']] = $news_feed->records;
//            echopre1(PageContext::$response->newsFeed[$data['news_feed_id']]);
        }
        $userDetail = User::getUserDetail(PageContext::$response->sess_user_id); 
        PageContext::$response->sess_user_image = $userDetail->data->Image;
        
        PageContext::$response->sess_user_alias = Utils::getAuth('user_alias');
        PageContext::$response->messageCount = $messageCount[0]->user_message_count;
        PageContext::addScript('friends_lazyload.js');
    }

    
    public function timelineajax($pagenum)
    {
        $alias = $_POST['alias'];
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        PageContext::addScript("jquery.form.min.js");
        PageContext::addScript("jquery.autogrow.js");

        if (PageContext::$response->sess_user_status == 'I' && PageContext::$response->sess_user_alias == $alias) {
            $this->redirect("inactiveuser");
        }
        PageContext::addStyle('nanoscroller.css');
        PageContext::addStyle('jquery.share.css');
        //PageContext::addScript('nanoscroller.min.js');
        PageContext::addScript('tether.min.js');
        PageContext::addScript('config.js');
        PageContext::addScript('util.js');
        PageContext::addScript('common.js');
        PageContext::addJsVar('ALIAS', $alias);
        PageContext::$response->activeSubMenu = 'profile';
        //=====================News Feed====================================
        if (PageContext::$response->sess_user_id > 0) {
            $share_array = array();
            $feed_array = array();
            $search = $_GET['search'];
            $business_type = $_GET['business_type'];
            PageContext::$response->search = $search;
            PageContext::$response->business_type = $business_type;
            PageContext::$response->timelineimage = User::getUserTimelineImage($alias);
            //-------------Share------------------------
            if ($search == '' OR $search == 'S') {
                $shares = Feed::getFriendShares();
                foreach ($shares->records AS $share_item) {
                    $share_array[strtotime($share_item->share_date)][] = (array)$share_item;
                }
            }

            //----------------------Announcemnet -----------
            if ($search == '' OR $search == 'A' OR $search == 'S') {
                if ($search != 'S') {
                    $feeds = Feed::listUserFeeds($business_type, $searchfeed = '',1,10);
                }
                PageContext::addJsVar('TOTAL_FEED_PAGES', $feeds->totpages);
                foreach ($feeds->records AS $feed_item) {
                    $feed_array[strtotime($feed_item->community_announcement_date)][] = (array)$feed_item;
                }

                //----------News feed (Share+announcement)-------------
                $news_array = $share_array + $feed_array;
                krsort($news_array);
                PageContext::$response->feeds = $news_array;
                //--------------------Feed Comments----------------
                foreach ($news_array AS $newsItems) {
                    foreach ($newsItems AS $news) {
                        if ($news['community_announcement_id']) {
                            $comments = Feed::getAnnouncementComments($news['community_announcement_id']);
                        }
                        PageContext::$response->Comments[$news['community_announcement_id']] = $comments->records;
                        PageContext::$response->Page[$news['community_announcement_id']]['totpages'] = $comments->totpages;
                        PageContext::$response->Page[$news['community_announcement_id']]['currentpage'] = $comments->currentpage;
                    }
                }

                PageContext::$response->count = $feeds->totalrecords;
            }
            //----------------Community dropdown--------------
            $communities = Feed::getAllCommunityNames();
            PageContext::$response->communities = $communities->data;
            $frndcount = Feed::getNumPendingFriendRequestByUser();
            PageContext::$response->NumFriendRequest = $frndcount[0]->user_friend_request_count;
            $users = Communities::getMyCommunitiesPendingMembersjoin($page, $itemperpage, '');
            PageContext::$response->NumPrivateRequest = $users->totalrecords;
            PageContext::$response->NumPendingBizcomMembers = Feed::getNumPendingBizcomMembers();
            pagecontext::$response->adminannouncement = pagecontext::$response->adminannouncements->data;


        }

        //=======================================================
      
        PageContext::addJsVar("LOGGED_USER_ALIAS", PageContext::$response->sess_user_alias);
        PageContext::addJsVar("CURRENT_USER_ALIAS", $alias);
        PageContext::addScript('profile.js');
        PageContext::addScript('search.js');
        PageContext::addScript("jquery.colorbox.js");
        PageContext::addScript('comment_popup.js');
        PageContext::addScript('timeago.js');
        PageContext::addScript('profile_business.js');
        PageContext::addScript('community.js');
        PageContext::addScript('jquery.share.js');
        PageContext::$response->tojoin = " to join " . SITE_NAME;
        PageContext::$response->invitation_type = 'user';
        PageContext::$response->invitation_typeid = PageContext::$response->sess_user_id;
        PageContext::$body_class = 'member_area';
        PageContext::$response->username = User::getUserNameFromAlias($alias);
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$metaTitle = META_TITLE;// = SITE_NAME . " : Your personalised social network";
        PageContext::$metaDes = META_DES;// = SITE_NAME . " - Member Profile";
        PageContext::$metaKey = META_KEYWORDS;//= SITE_NAME . " - Member Profile";
        //=================Pending request==========================
        $pendingRequest = Connections::getUserPendingRequest($alias);
        PageContext::$response->pendingRequest = $pendingRequest->data;
        PageContext::$response->pendingRequestCount = sizeof($pendingRequest->data);

        //=============getCountires===========
        $country = Cmshelper::getAllCountries();
        $country_dropdown = array();
        if ($country) {
            $country_dropdown['--Country--'] = '';
            foreach ($country as $key => $val) {
                $country_dropdown[$val->text] = $val->value;
            }
        }
        PageContext::$response->countrydropdown = $country_dropdown;
        PageContext::$response->message = Messages::getPageMessage();
        PageContext::$response->alias = $alias;

        //=========Fetch user details===============
        $userDetails = User::getUserDetails($alias);
        $communityCount = Communities::getCommunityCount();
        PageContext::$response->community_count = $communityCount;
        $mutualFriendsCount = User::getUserMutualFriendCount(PageContext::$response->sess_user_id, $userDetails->data->Id);
        PageContext::$response->mutual_friend_count = $mutualFriendsCount;
        PageContext::$response->id = $userDetails->data->Id;
        PageContext::$response->user_name = $userDetails->data->Name;
        PageContext::$response->user_image = $userDetails->data->user_image_name;
        PageContext::addJsVar('TOTAL_PAGES', $userDetails->data->user_friends_count / LAZYLOAD_COUNT);
        PageContext::$response->userDetails = Utils::objectToArray($userDetails->data);
        PageContext::$response->business_friend = User::getFriendsCount(PageContext::$response->sess_user_id, 'B');
        PageContext::$response->personal_friend = User::getFriendsCount(PageContext::$response->sess_user_id, 'P');

        PageContext::$response->userLastLogin = explode(' ', $userDetails->data->user_last_login);
        if (PageContext::$response->userDetails['user_image_name'] == '') {
            PageContext::$response->image = "member_noimg.jpg";
        } else {
            PageContext::$response->image = PageContext::$response->userDetails['user_image_name'];
        }
        $tagDetails = User::getAssociatedBusiness($userDetails->data->Id);
        $total_pages = (sizeof($tagDetails->data) / LAZYLOAD_COUNT);
        PageContext::addJsVar('TOT_PAGESS', $total_pages);
        PageContext::$response->tagDetails = $tagDetails->data;

        //==============Ajax edit===============
        if ($ajaxmode == 'ajaxTrue') {

            $objUserVo = new stdClass();
            $objUserVo->user_firstname = $_POST['user_firstname'];
            $objUserVo->user_lastname = $_POST['user_lastname'];
            $objUserVo->user_email = $_POST['user_email'];
            if ($_POST['user_date_of_birth'] != '') {
                $objUserVo->user_date_of_birth = date('Y-m-d', strtotime($_POST['user_date_of_birth']));
            } else {
                $objUserVo->user_date_of_birth = '';
            }
            $objUserVo->user_gender = $_POST['user_gender'];
            $objUserVo->user_address = $_POST['user_address'];
            $objUserVo->user_city = $_POST['user_city'];
            $objUserVo->user_state = $_POST['user_state'];
            $objUserVo->user_country = $_POST['user_country'];
            $objUserVo->user_phone = $_POST['user_phone'];
            $objUserVo->user_zipcode = $_POST['user_zipcode'];
            $objUserVo->user_privacy = $_POST['user_privacy'];
            $objUserVo->user_id = PageContext::$response->sess_user_id;
            $objUserRes = User::editUser(PageContext::$response->sess_user_id, $objUserVo);
            if ($objUserRes->status == SUCCESS) {//====================
                $data['msg'] = "User details updated successfully";
                $data['cls'] = "success_div";
                echo json_encode($data);
                exit;
            } else {

                $data['msg'] = $objUserRes->message;
                $data['cls'] = "error_div";
                echo json_encode($data);
                exit;
            }
            PageContext::$response->sess_user_name = PageContext::$response->user_name;
        }
        if (PageContext::$response->sess_user_id != '') {
            $friends = User::getUserFriends(PageContext::$response->sess_user_alias, 'users.user_id');
            $user_id = User::getUserIdFromAlias($alias);
            PageContext::$response->friend_to = $user_id;
            foreach ($friends->data AS $friends) {
                $myfriends[] = $friends->user_id;
            }
            PageContext::$response->myfriends = $myfriends;
            $friends = User::getUserFriends(PageContext::$response->sess_user_alias, 'users.user_id');

            foreach ($friends->data AS $friends) {
                $myfriendsstatus[$friends->user_id] = $friends->friends_list_view_status;
            }
            PageContext::$response->myfriendsstatus = $myfriendsstatus;

            $invitations = Connections::getAllUserInvitationsSent(PageContext::$response->sess_user_alias, 'P', 'invitation_receiver_id');
            foreach ($invitations->data AS $invitations) {
                $myinvitations[] = $invitations->invitation_receiver_id;
            }
            PageContext::$response->myinvitedfriends = $myinvitations;
            $pendingFriendRequests = Connections::getUserPendingRequest(PageContext::$response->sess_user_alias);
            foreach ($pendingFriendRequests->data AS $pendingFriendRequest) {
                $myPendingRequests[] = $pendingFriendRequest->user_id;
                $myPendingRequestsInviteId[] = $pendingFriendRequest->invitation_id;
            }
            $key = array_search(PageContext::$response->id, $myPendingRequests);
            if ($key >= 0) { //echo"aaa";
                $inviteId = $myPendingRequestsInviteId[$key];
                PageContext::$response->inviteId = $inviteId;
            }
            PageContext::$response->myPendingRequests = $myPendingRequests;
        }

        if (Utils::getAuth('user_id')) {
            $bizcomInvite = Connections::getPendingBizComrequest(Utils::getAuth('user_id'));
            PageContext::$response->pendingBizcomrequests = $bizcomInvite->data;
        }
        PageContext::$response->message = Messages::getPageMessage();
        $leads = Communities::getSubscribedCommunityCount(Utils::getAuth('user_id'));
        PageContext::$response->Subscribed_community_count = $leads;
        $page = PageContext::$request['page'];
        $itemperpage = PAGE_LIST_COUNT;

        $announcementCount = Communities::getAnnouncementCountByUser();
        PageContext::$response->announcementCount = $announcementCount[0]->cmember_announcement_count;
        if (PageContext::$response->announcementCount == '') {
            PageContext::$response->announcementCount = 0;
        }
        $messageCount = Messages::getMessageCountByUser();
        $user_id = User::getUserIdFromAlias($alias);
        $news_feed = User::getTimeLine($user_id,$pagenum,5);
        PageContext::$response->news_feed1 = $news_feed->data;
        foreach ($news_feed->data as $data) {
            $news_feed = Feed::getFeedComments($data['news_feed_id']);
            $news_feed_like_users = Feed::getFeedLikesUsers($data['news_feed_id']);
             
            foreach ($news_feed->records as $value) {
                   $replies = Feed::showFeedCommentReply($value->news_feed_comments_id); 
                       $like_user_comment_comments = Feed::showFeedCommentOfCommentsLikeUser($value->news_feed_comments_id); 
                foreach($like_user_comment_comments as $data1){
                   // echo $data->user_name;
                    $name .=  $data1->user_name.",";
                }
                $name = rtrim($name, ",");
                $news_feed->records['users']= $name;
                   if($replies->totalrecords > 0)
                   $news_feed->records[$value->news_feed_comments_id] = $replies->totalrecords;
                   $value->user_image=User::getUserDetail($value->user_id)->data->Image;
                }
                
            PageContext::$response->newsFeedLikeUsers[$data['news_feed_id']] = $news_feed_like_users;    
            PageContext::$response->newsFeed[$data['news_feed_id']] = $news_feed->records;
//            echopre1(PageContext::$response->newsFeed);
        }
        PageContext::$response->sess_user_alias = Utils::getAuth('user_alias');
        PageContext::$response->messageCount = $messageCount[0]->user_message_count;
        PageContext::addScript('friends_lazyload.js');
      

    }
    
    public function timelineimageupload()
    {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $objUserRes = new stdClass();
        $objUserImageData = new stdClass();
        $objUserRes->status = SUCCESS;
        $div = 'success_div';
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message['msg'] = "Please Upload File";
            $div = 'error_div';
        }
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
            $type = $_FILES['file']['type'];
            $type1 = @explode('/', $type);
            list($originalWidth, $originalHeight) = getimagesize($_FILES['file']['name']);
            if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "File format not supported.";
                $div = 'error_div';
            }
        }
        if ($objUserRes->status == SUCCESS) {
            $objUserImageData->user_id = PageContext::$response->sess_user_id;
            $objUserImageData->file = $_FILES['file'];
            $objUserImageData->timeline_date = date('m/d/Y');
            list($width, $height, $type, $attr) = getimagesize($_FILES["file"]['tmp_name']);
            $objUserRes->message = Images::addTimelineImage($objUserImageData,$width, $height);
            $div = $objUserRes->message['msgcls'];
            PageContext::$response->image_id = $objUserRes->message['image_id'];
            echo PageContext::$response->file = $objUserRes->message['file'];
            exit;
        }

    }

//    public function reposition_image() {
//        if (isset($_POST['pos'])) {
//
//            $from_top = abs($_POST['pos']);
//            $default_cover_width = 918;
//            $default_cover_height = 276;
//            $tb = new Images();
//            // apro l'immagine
//
//            $tb->openImg(FILE_UPLOAD_DIR."original.jpg"); //original cover image
//
//            $newHeight = $tb->getRightHeight($default_cover_width);
//
//	    $tb->creaThumb($default_cover_width, $newHeight);
//
//            $tb->setThumbAsOriginal();
//
//            $tb->cropThumb($default_cover_width, 276, 0, $from_top);
//
//
//            $tb->saveThumb(FILE_UPLOAD_DIR."cover1.jpg"); //save cropped cover image
//
//            $tb->resetOriginal();
//	    $tb->closeImg();
//            $data['status'] = 200;
//            $data['url'] = PageContext::$response->userImagePath.'cover1.jpg';
//            echo json_encode($data);
//            exit;
//
//        }
//    }


    public function home($alias, $ajaxmode)
    {
        if (PageContext::$response->sess_user_status == 'I' && PageContext::$response->sess_user_alias == $alias) {
            $this->redirect("inactiveuser");
        }
        PageContext::$response->tojoin = " to join " . SITE_NAME;
        PageContext::addJsVar('ALIAS', $alias);
        PageContext::registerPostAction("importcontacts", "importcontacts", "index", "default");
        PageContext::$response->invitation_type = 'user';
        PageContext::$response->invitation_typeid = PageContext::$response->sess_user_id;
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("leftcontent", "home", "user", "default");
        PageContext::addJsVar("LOGGED_USER_ALIAS", PageContext::$response->sess_user_alias);
        PageContext::addJsVar("CURRENT_USER_ALIAS", $alias);
        PageContext::addScript('profile.js');
        PageContext::addScript('search.js');
        PageContext::addScript("jquery.colorbox.js");
        PageContext::addScript('comment_popup.js');
        PageContext::addScript('timeago.js');
        PageContext::$body_class = 'member_area';
        PageContext::$response->activeSubMenu = 'profile';
        PageContext::$response->username = User::getUserNameFromAlias($alias);
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$metaTitle = META_TITLE;// = SITE_NAME . " : Your personalised social network";
        PageContext::$metaDes = META_DES;// = SITE_NAME . " - Member Profile";
        PageContext::$metaKey = META_KEYWORDS;//= SITE_NAME . " - Member Profile";
        //=================Pending request==========================
        $pendingRequest = Connections::getUserPendingRequest($alias);
        PageContext::$response->pendingRequest = $pendingRequest->data;
        PageContext::$response->pendingRequestCount = sizeof($pendingRequest->data);
        //=================Friend suggestion=============================


        //=============getCountires===========
        $country = Cmshelper::getAllCountries();
        $country_dropdown = array();
        if ($country) {
            $country_dropdown['--Country--'] = '';
            foreach ($country as $key => $val) {
                $country_dropdown[$val->text] = $val->value;
            }
        }
        PageContext::$response->message = Messages::getPageMessage();
        PageContext::$response->alias = $alias;
        //=========Fetch user details===============
        $userDetails = User::getUserDetails($alias);
        PageContext::$response->id = $userDetails->data->Id;
        PageContext::addJsVar('TOTAL_PAGES', $userDetails->data->user_friends_count / LAZYLOAD_COUNT);
        PageContext::$response->userDetails = Utils::objectToArray($userDetails->data);
        PageContext::$response->userLastLogin = explode(' ', $userDetails->data->user_last_login);
        if (PageContext::$response->userDetails['user_image_name'] == '') {
            PageContext::$response->image = "member_noimg.jpg";
        } else {
            PageContext::$response->image = PageContext::$response->userDetails['user_image_name'];
        }
        $tagDetails = User::getAssociatedBusiness($userDetails->data->Id);
        PageContext::$response->tagDetails = $tagDetails->data;
        //=======================About form====================
        $arrFormParams = array('name' => 'frmUserEdit', 'id' => 'frmUserEdit', 'method' => 'post', 'action' => '', 'class' => '');
        $objFormManager = new Formmanager($arrFormParams);
        $arrFormElements = array('user_firstname' => array('type' => 'text', 'name' => 'user_firstname', 'id' => 'user_firstname', 'value' => PageContext::$response->userDetails['user_firstname'], 'size' => 10, 'placeholder' => 'First Name',
            'label' => array('message' => 'First Name  ', 'class' => 'labelcol'),
        ),
            'user_lastname' => array('type' => 'text', 'name' => 'user_lastname', 'id' => 'user_lastname', 'value' => PageContext::$response->userDetails['user_lastname'], 'size' => 10, 'class' => '', 'placeholder' => 'Last Name',
                'label' => array('message' => 'Last Name  ', 'class' => 'labelcol'),
            ),
            'user_email' => array('type' => 'text', 'name' => 'user_email', 'id' => 'user_email', 'value' => PageContext::$response->userDetails['Email'], 'size' => 10, 'class' => '', 'placeholder' => 'Your Email',
                'label' => array('message' => 'Email  ', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter email'), 'email' => array('true', 'Please enter a valid email')))),
            'user_date_of_birth' => array('type' => 'text', 'id' => 'user_date_of_birth', 'name' => 'user_date_of_birth', 'value' => PageContext::$response->userDetails['Date_of_Birth'], 'size' => 10, 'class' => '', 'placeholder' => 'Date of birth', 'readonly' => 'readonly',
                'label' => array('message' => 'Date of Birth', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter date of birth'), 'date' => array('true', 'Please enter a valid date')))),
            'user_gender' => array('type' => 'select', 'name' => 'user_gender', 'id' => 'user_gender', 'selected' => array(PageContext::$response->userDetails['Gender']), 'class' => 'user_gender', 'placeholder' => 'Gender', 'options' => array('Select' => '', 'Male' => 'M', 'Female' => 'F'),
                'label' => array('message' => 'Gender', 'class' => ''),
            ),
            'user_address' => array('type' => 'textarea', 'name' => 'user_address', 'id' => 'user_address', 'value' => PageContext::$response->userDetails['Address'], 'class' => '', 'placeholder' => 'Address',
                'label' => array('message' => 'Address  ', 'class' => ''),
            ),
            'user_city' => array('type' => 'text', 'name' => 'user_city', 'id' => 'user_city', 'value' => PageContext::$response->userDetails['City'], 'size' => 10, 'class' => '', 'placeholder' => ' City',
                'label' => array('message' => 'City  ', 'class' => ''),
            ),
            'user_country' => array('type' => 'select', 'name' => 'user_country', 'id' => 'user_country', 'selected' => array(PageContext::$response->userDetails['user_country']), 'class' => 'user_country', 'placeholder' => 'Business Country', 'options' => $country_dropdown,
                'label' => array('message' => 'Country  ', 'class' => ''),
            ),
            'user_state' => array('type' => 'select', 'name' => 'user_state', 'id' => 'user_state', 'selected' => array(PageContext::$response->userDetails['user_state']), 'class' => 'user_state', 'placeholder' => '', 'options' => array('--State--' => '', 'ALABAMA' => 'AL'),
                'label' => array('message' => 'State  ', 'class' => ''),
            ),
            'user_phone' => array('type' => 'text', 'name' => 'user_phone', 'id' => 'user_phone', 'value' => PageContext::$response->userDetails['Phone'], 'size' => 10, 'class' => '', 'placeholder' => 'Telephone',
                'label' => array('message' => 'Phone  ', 'class' => ''),
            ),
            'user_zipcode' => array('type' => 'text', 'name' => 'user_zipcode', 'id' => 'user_zipcode', 'value' => PageContext::$response->userDetails['Zip_Code'], 'size' => 10, 'class' => '', 'placeholder' => 'Zip Code',
                'label' => array('message' => 'Zipcode  ', 'class' => ''),
            ),
            'user_privacy' => array('type' => 'select', 'name' => 'user_privacy', 'id' => 'user_privacy', 'selected' => array(PageContext::$response->userDetails['user_privacy']), 'class' => 'user_privacy', 'placeholder' => 'Privacy', 'options' => array('Select' => '', 'Show to All' => 'SA', 'Only to Me' => 'H', 'Only to BBF Memebers' => 'SM'),
                'label' => array('message' => 'Profile View', 'class' => ''),
            ),
            'user_id' => array('type' => 'hidden', 'name' => 'user_id', 'id' => 'user_id', 'value' => PageContext::$response->userDetails['Id'], 'size' => 10, 'class' => '', 'placeholder' => '',
                'label' => array('message' => '', 'class' => ''),
            ),
            'user_alias' => array('type' => 'hidden', 'name' => 'user_alias', 'id' => 'user_alias', 'value' => $alias, 'size' => 10, 'class' => '', 'placeholder' => '',
                'label' => array('message' => '', 'class' => ''),
            ),
            'btnSubmit' => array('type' => 'button', 'name' => 'btnSubmit', 'id' => 'jUpdate', 'class' => 'signup_btn', 'value' => 'Update'),
            'btnCancel' => array('type' => 'button', 'name' => 'btnCancel', 'id' => '', 'uid' => PageContext::$response->userDetails['Id'], 'alias' => $alias, 'class' => 'cancel_btn jShowProfile', 'value' => 'Cancel'),
        );
        $objFormManager->addFields($arrFormElements);
        //==============Ajax edit===============
        if ($ajaxmode == 'ajaxTrue') {
            $objValidator = new formValidator();
            $validation = $objValidator->validate($arrFormElements);

            if ($validation['error'] == 1) {
                $objFormManager->addValidationMessages($validation);
                $objFormManager->formErrorMessages;
                foreach ($objFormManager->formErrorMessages As $errMessage) {
                    $data['msg'][] = $errMessage . "<br>";
                    $data['cls'] = "error_div";
                }
                echo json_encode($data);
                exit;
            } else {
                $objUserVo = new stdClass();
                $objUserVo->user_firstname = $_POST['user_firstname'];
                $objUserVo->user_lastname = $_POST['user_lastname'];
                $objUserVo->user_email = $_POST['user_email'];
                $objUserVo->user_date_of_birth = date('Y-m-d', strtotime($_POST['user_date_of_birth']));
                $objUserVo->user_gender = $_POST['user_gender'];
                $objUserVo->user_address = $_POST['user_address'];
                $objUserVo->user_city = $_POST['user_city'];
                $objUserVo->user_state = $_POST['user_state'];
                $objUserVo->user_country = $_POST['user_country'];
                $objUserVo->user_phone = $_POST['user_phone'];
                $objUserVo->user_zipcode = $_POST['user_zipcode'];
                $objUserVo->user_privacy = $_POST['user_privacy'];
                $objUserVo->user_id = $_POST['user_id'];
                $objUserRes = User::editUser($_POST['user_id'], $objUserVo);
                if ($objUserRes->status == SUCCESS) {//====================
                    $data['msg'] = "User details updated successfully";
                    $data['cls'] = "success_div";
                    echo json_encode($data);
                    exit;
                } else {

                    $data['msg'] = $objUserRes->message;
                    $data['cls'] = "error_div";
                    echo json_encode($data);
                    exit;
                }
            }
        }
        if (PageContext::$response->sess_user_id != '') {
            $friends = User::getUserFriends(PageContext::$response->sess_user_alias, 'users.user_id');
            foreach ($friends->data AS $friends) {
                $myfriends[] = $friends->user_id;
            }
            PageContext::$response->myfriends = $myfriends;
            $invitations = Connections::getAllUserInvitationsSent(PageContext::$response->sess_user_alias, 'P', 'invitation_receiver_id');
            foreach ($invitations->data AS $invitations) {
                $myinvitations[] = $invitations->invitation_receiver_id;
            }
            PageContext::$response->myinvitedfriends = $myinvitations;
            $pendingFriendRequests = Connections::getUserPendingRequest(PageContext::$response->sess_user_alias);
            foreach ($pendingFriendRequests->data AS $pendingFriendRequest) {
                $myPendingRequests[] = $pendingFriendRequest->user_id;
                $myPendingRequestsInviteId[] = $pendingFriendRequest->invitation_id;
            }
            $key = array_search(PageContext::$response->id, $myPendingRequests);
            if ($key >= 0) {
                $inviteId = $myPendingRequestsInviteId[$key];
                PageContext::$response->inviteId = $inviteId;
            }

            PageContext::$response->myPendingRequests = $myPendingRequests;
        }
        if (Utils::getAuth('user_id')) {
            $bizcomInvite = Connections::getPendingBizComrequest(Utils::getAuth('user_id'));
            PageContext::$response->pendingBizcomrequests = $bizcomInvite->data;
        }
        PageContext::$response->message = Messages::getPageMessage();
        PageContext::$response->objForm = $objFormManager->renderForm();
        PageContext::addScript('friends_lazyload.js');
    }

    public function organization($alias = '')
    {
        PageContext::addStyle("rateit.css");
        PageContext::$response->rate_entity = 'B';
        PageContext::$response->rate_entity_alias = $alias;
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "business1", "user", "default");
        PageContext::addScript('timeago.js');
        PageContext::addScript("organisation.js");
        PageContext::$body_class = 'business_profile';
        PageContext::$response->activeSubMenu = 'business';
        PageContext::$response->org_grp = ORG_GRP;
        PageContext::$response->messagebox = Messages::getPageMessage();
        
        // rating part
        $type = 'B';
        $type_alias = $alias;
        $result = Business::getBusinessId($type_alias);
        $type_id = $result->data->business_id;
        $user_id = PageContext::$response->sess_user_id;
        $value = 0;
        $flag = 0;
        $rate = Ratings::getRatings($type_id, $type);
        $reuslt = Business::getBusiness($alias);
        //echopre1($reuslt);
        if ($rate->data->count != 0) {
            $value = $rate->data->total / $rate->data->count;
        }
        if ($user_id <= 0) {
            $flag = 1;
        } else {
            if ($user_id == $reuslt->data->business_created_by) {
                $flag = 2;
            } else {
                $rate1 = Ratings::checkIfRated($type_id, $type, $user_id);
                if ($rate1->data->rating_id > 0 || $rate1->data->rating_id != '') {
                    $flag = 1;
                }
            }
        }
        PageContext::addJsVar('RATEVALUE', $value);
        PageContext::addJsVar('RATEFLAG', $flag);
        PageContext::addJsVar('RATETYPE_ID', $type_id);
        PageContext::addJsVar('RATETYPE', $type);
        PageContext::addJsVar('RATE_USERID', $user_id);
        // end rating part

        PageContext::addScript("jquery.rateit.js");
        PageContext::addScript("rating.js");
        PageContext::registerPostAction("rating", "rate", "index", "default");
        PageContext::$response->business_id = $reuslt->data->business_id;
        //----Associates---
        $page = PageContext::$request['page'];
       $associates = User::getAllAssociatesByBusiness($reuslt->data->business_id);
       //echopre1($associates);
        $itemperpage = PAGE_LIST_COUNT;
        $targetpage = BASE_URL . "directory/$alias?searchusertext=" . $searchusertext . '&searchusertype=' . $searchusertype . '&sortuser=' . $orderuserfield . '&sortuserby=' . $ordersortby;
        PageContext::$response->associates = $associates->records;
        $tagged = array();
        foreach(PageContext::$response->associates as $data){
            $tagged[]= $data->user_id;
         }
        PageContext::$response->tagged = $tagged;
        PageContext::$response->totalrecords = $associates->totalrecords;
        PageContext::$response->paginationAffilate = Pagination::paginate($page, $itemperpage, $associates->totalrecords, $targetpage);
        //-------Affilated users-----------
        PageContext::$response->affliatesUsersList = Business::getAllAffiliatesIdForBusiness($reuslt->data->business_id);

        //----Affiliates---
        $page = PageContext::$request['page'];
        //$affiliateRequest = User::getAllAffilateRequestByBusiness($reuslt->data->business_id);
        $itemperpage = PAGE_LIST_COUNT;
        $targetpage = BASE_URL . "directory/$alias?searchusertext=" . $searchusertext . '&searchusertype=' . $searchusertype . '&sortuser=' . $orderuserfield . '&sortuserby=' . $ordersortby;
        //PageContext::$response->associatesRequest = $affiliateRequest->records;
       // PageContext::$response->totalrecords = $affiliateRequest->totalrecords;
        PageContext::$response->paginationAffilateReq = Pagination::paginate($page, $itemperpage, $associates->totalrecords, $targetpage);
        $address = $reuslt->data->business_address . ',' . $reuslt->data->business_city . ',' . $reuslt->data->business_state . ',' . $reuslt->data->business_country . ',' . $reuslt->data->business_zipcode;
        PageContext::addJsVar("gmaddress", Utils::escapeString($address));
        PageContext::$metaTitle = META_TITLE;// = SITE_NAME . " : Your personalised social network";
        PageContext::$metaDes = META_DES;// = SITE_NAME;
        PageContext::$metaKey = META_KEYWORDS;//= SITE_NAME;
        $orderfield = PageContext::$request['sort'];
        $orderby = PageContext::$request['sortby'];
        $page = PageContext::$request['page'];
        $search = addslashes(PageContext::$request['searchtext']);
        $searchtype = 'all';

        if ($orderby == '')
            $orderby = ' DESC';
        if ($orderfield == '')
            $orderfield = '	testimonial_id';
        // code to get the arrow for the sort order
        PageContext::$response->business_name_sortorder = Utils::sortarrow();
        PageContext::$response->{$orderfield . '_sortorder'} = Utils::getsortorder($orderby);
        PageContext::$response->searchtext = $search;
        PageContext::$response->searchtype = $searchtype;
        PageContext::$response->page = $page;
        // search field section
        switch ($searchtype) {
            case 'all':
                $searchtypeArray = array('comment_id', 'comment_content', 'business_type');
                break;
            case 'name':
                $searchtypeArray = array('business_name', 'user_email');
                break;
            case 'email':
                $searchtypeArray = array('user_email', 'business_email');
                break;
            case 'phone':
                $searchtypeArray = array('business_phone');
                break;
        }
        PageContext::$response->order = ($orderby == 'ASC') ? 'DESC' : 'ASC';
        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
       // $organizationObj = Business::getTaggedId($reuslt->data->business_id);
        PageContext::$response->tagg_id = $organizationObj->tagg_id;
        
        $itemperpage = PAGE_LIST_COUNT;
        $targetpage = BASE_URL . "directory/$alias?searchtext=" . $search . '&searchtype=' . $searchtype . '&sort=' . $orderfield . '&sortby=' . $orderby;
        if($reuslt->data->business_id){
        $testimonials = Comments::getAllTestimonials($orderfield, $orderby, $page, $itemperpage, $search, $searchtypeArray, $reuslt->data->business_id);
        }
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->slno = 1;
        PageContext::$response->leads = $testimonials->records;
        PageContext::$response->totalrecords = $testimonials->totalrecords;
       // PageContext::$response->pagination = Pagination::paginate($page, $itemperpage, $testimonials->totalrecords, $targetpage);
        PageContext::$response->testimonials = $testimonials->records;
        if ($reuslt->status == SUCCESS) {
            PageContext::$response->resultSet = $reuslt->data;
        } else {
            Messages::setPageMessage($reuslt->message, ERROR_CLASS);
            PageContext::$response->messagebox = Messages::getPageMessage();
        }
       // PageContext::$response->gallery_display_list = Business::getMyLatestDiscussionImage($reuslt->data->business_id);
       // echopre(PageContext::$response->gallery_display_list);
      //  $associates = User::getAllAssociatesByBusiness($reuslt->data->business_id, 1, 3);
        PageContext::$response->friend_display_list = $associates->records;
     //   $associatedBizcom = Business::getAllBizcomByBusiness($business_id);
        PageContext::addJsVar('TOTAL_PAGES', $associatedBizcom->totpages / LAZYLOAD_COUNT);
    }

    public function add_organization()
    {
        Utils::checkUserLoginStatus();
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "add_business", "user", "default");
        PageContext::addScript('cms_select_state_business.js');
        PageContext::addScript('validations_form.js');
        PageContext::$body_class = 'register';
        PageContext::$response->activeSubMenu = 'business';
        $dropdown = array();
        
        PageContext::$request['business_state'] = '';
        $country = Cmshelper::getAllCountries();
        $country_dropdown = array();
        if ($country) {
            $country_dropdown['--Country--'] = '';
            foreach ($country as $key => $val) {
                $country_dropdown[$val->text] = $val->value;
            }
        }
        PageContext::$response->countries = $country_dropdown;
        $category = Cmshelper::getAllCategoryName();
        if ($category) {
            $category_dropdown['--Category--'] = '';
            foreach ($category as $key => $val) {
                $category_dropdown[$val->text] = $val->value;
            }
        }
        PageContext::$response->categories = $category_dropdown;
        if (PageContext::$request['btnSubmit']) {
            $unsetArray = array('btnSubmit');
            if ($_FILES['business_image_id']['name']) {
                $fileHandler = new Filehandler();   //  print_r($_FILES); exit;
                $bannerFileDetails = $fileHandler->handleUpload($_FILES['business_image_id'], FILE_UPLOAD_DIR);

            }
            if ($_FILES['business_logo_id']['name']) {
                $fileHandler = new Filehandler();   //  print_r($_FILES); exit;
                $logoFileDetails = $fileHandler->handleUpload($_FILES['business_logo_id'], FILE_UPLOAD_DIR);
            }
            if (ADMIN_APPROVE_ORG_AUTO == 1) { 
                $status = 'A';
                $msg = BUSINESS_SUCCESS;
            } else {  
                $status = 'I';
                $msg = BUSINESS_SUCCESS . COMMUNITY_SUCCESS_APPROVAL;
            }
            $additionalParameters = array(
                'business_created_by' => Utils::getAuth('user_id'),
                'business_created_on' => date('Y-m-d'),
                'business_status' => $status
            );

            if ($bannerFileDetails->file_id > 0) {
                $additionalParameters['business_image_id'] = $bannerFileDetails->file_id;
                Utils::allResize($bannerFileDetails->file_path, 'small', '', '');
                Utils::allResize($bannerFileDetails->file_path, 'medium', '', '');
                Utils::allResize($bannerFileDetails->file_path, 'thumb', '', '');
            }
            if ($logoFileDetails->file_id > 0) {
                $additionalParameters['business_logo_id'] = $logoFileDetails->file_id;
                Utils::allResize($logoFileDetails->file_path, 'small', 190, 134);
                Utils::allResize($logoFileDetails->file_path, 'medium', 178, 164);
                Utils::allResize($logoFileDetails->file_path, 'thumb', 50, 30);
            }
            
            $objUserVo = new stdClass();
            $objUserVo->business_name = Utils::escapeString(PageContext::$request['business_name']);
            $objUserVo->business_email = Utils::escapeString(PageContext::$request['business_email']);
            $objUserVo->business_url = Utils::escapeString(PageContext::$request['business_url']);
            $objUserVo->business_type = Utils::escapeString(PageContext::$request['business_type']);
            $objUserVo->business_industry_id = Utils::escapeString(PageContext::$request['business_industry_id']);
            $objUserVo->business_description = Utils::escapeString(PageContext::$request['business_description']);
            $objUserVo->business_category_id = Utils::escapeString(PageContext::$request['business_category_id_add']);
            $objUserVo->business_address = Utils::escapeString(PageContext::$request['business_address']);
            $objUserVo->business_city = Utils::escapeString(PageContext::$request['business_city']);
            $objUserVo->business_country = Utils::escapeString(PageContext::$request['business_country']);
            $objUserVo->business_state = Utils::escapeString(PageContext::$request['business_state'])? Utils::escapeString(PageContext::$request['business_state']):Utils::escapeString($_POST['business_state']);
            $objUserVo->business_phone = Utils::escapeString(PageContext::$request['business_phone']);
            $objUserVo->business_zipcode = Utils::escapeString(PageContext::$request['business_zipcode']);
            $objUserVo->business_created_by = Utils::getAuth('user_id');
            $objUserVo->business_created_on = date('Y-m-d');
            $objUserVo->business_status = $status;//'A';
            $objUserVo->business_image_id = $bannerFileDetails->file_id;
            $objUserVo->business_logo_id = $logoFileDetails->file_id;
            $objUserVo->business_logo_name = $logoFileDetails->file_path;
            
            $objUserRes = Business::createBusiness($objUserVo);
            $business_id = $objUserRes->data->business_id;
            $objTag = array('user_id' => Utils::getAuth('user_id'), 'business_id' => $business_id, 'role' => 'Owner', 'tag_buisness_email' => Utils::getAuth('user_email'), 'status' => 'A', 'affiliation_status' => 'N');
            $result = Business::addTaggs($objTag);
            if ($objUserRes->status == SUCCESS) {//-----User Registration mail------
                if (ADMIN_APPROVE_ORG_AUTO == 0) {
                    $mailIds = array();
                    $replaceparams = array();
                    $mailIds[ADMIN_EMAILS] = '';
                    $replaceparams['NAME'] = PageContext::$response->sess_user_name;
                    $replaceparams['TITLE'] = $objUserVo->business_name;
                    $replaceparams['ENTITY'] = 'Page';
                    $objMailer = new Mailer();
                    $objMailer->sendMail($mailIds, 'admin_approval', $replaceparams);
                }
                Messages::setPageMessage($msg, 'success_div');
                Business::updatebusinessCount();
                $this->redirect('pages');
            } else { //----- User insertion failed--------
                PageContext::$request['business_email'] = $objUserVo->business_email;
                PageContext::$request['business_url'] = $objUserVo->business_url;
                PageContext::$request['business_type'] = $objUserVo->business_type;
                PageContext::$request['business_industry_id'] = $objUserVo->business_industry_id;
                PageContext::$request['business_description'] = $objUserVo->business_description;
                PageContext::$request['business_address'] = $objUserVo->business_address;
                PageContext::$request['business_city'] = $objUserVo->business_city;
                PageContext::$request['business_country'] = $objUserVo->business_country;
                PageContext::$request['business_state'] = $objUserVo->business_state;
                PageContext::$request['business_phone'] = $objUserVo->business_phone;
                PageContext::$request['business_zipcode'] = $objUserVo->business_zipcode;
                Messages::setPageMessage($objUserRes->message, 'error_div');
            }

        }
        Business::updatebusinessCount();
        PageContext::$response->message = Messages::getPageMessage();

    }

    public function edit_organization($businessId, $alias = '')
    {
        Utils::checkUserLoginStatus();
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "edit_business", "user", "default");
        PageContext::addScript('cms_select_state_business.js');
        PageContext::addScript('validations_form.js');
        PageContext::$body_class = 'register';
        PageContext::$response->activeSubMenu = 'business';
        PageContext::$response->baseUrl = BASE_URL;

        $result = Business::getBusinessById($businessId);
        PageContext::$metaTitle = META_TITLE;// = SITE_NAME . " : Your personalised social network";
        PageContext::$metaDes = META_DES;// = SITE_NAME . " - Edit Business";
        PageContext::$metaKey = META_KEYWORDS;//= SITE_NAME . " - Edit Business";
        PageContext::$response->data = Utils::objectToArray($result->data);

        $country = Cmshelper::getAllCountries();
        $country_dropdown = array();
        if ($country) {
            $country_dropdown['--Country--'] = '';
            foreach ($country as $key => $val) {
                $country_dropdown[$val->text] = $val->value;
            }
        }
        PageContext::$response->countries = $country_dropdown;
        $category = Cmshelper::getAllCategoryName();
        if ($category) {
            $category_dropdown['--Category--'] = '';
            foreach ($category as $key => $val) {
                $category_dropdown[$val->text] = $val->value;
            }
        }
        PageContext::$response->categories = $category_dropdown;

        if (PageContext::$request['btnSubmit']) { //--Post action--

            $unsetArray = array('btnSubmit');
            if ($_FILES['business_image_id']['name']) {
                $fileHandler = new Filehandler();   //  print_r($_FILES); exit;
                $bannerFileDetails = $fileHandler->handleUpload($_FILES['business_image_id'], FILE_UPLOAD_DIR);
            }
            if ($_FILES['business_logo_id']['name']) {
                $fileHandler = new Filehandler();   //  print_r($_FILES); exit;
                $logoFileDetails = $fileHandler->handleUpload($_FILES['business_logo_id'], FILE_UPLOAD_DIR);
            }
            if ($bannerFileDetails->file_id) {
                $additionalParameters = array(
                    'business_image_id' => $bannerFileDetails->file_id
                );
                Utils::allResize($bannerFileDetails->file_path, 'small', 190, 134);
                Utils::allResize($bannerFileDetails->file_path, 'medium', 256, 242);
                Utils::allResize($bannerFileDetails->file_path, 'thumb', 50, 50);
            }
            if ($logoFileDetails->file_id > 0) {
                $additionalParameters = array(
                    'business_logo_id' => $logoFileDetails->file_id
                );
                // $additionalParameters['business_logo_id'] = $logoFileDetails->file_id;
                Utils::allResize($logoFileDetails->file_path, 'small', 190, 134);
                Utils::allResize($logoFileDetails->file_path, 'medium', 178, 164);
                Utils::allResize($logoFileDetails->file_path, 'thumb', 50, 30);
            }
            $objUserVo = Utils::arrayToObject($_POST, $additionalParameters, $unsetArray);
            $objUserRes = Business::editBusiness($businessId, $objUserVo);
            if ($objUserRes->status == SUCCESS) {//-----User Registration mail------
                Messages::setPageMessage(BUSINESS_EDIT_SUCCESS, 'success_div');
                $this->redirect('pages');
            } else { //----- User insertion failed--------
                Messages::setPageMessage($objUserRes->message, 'error_div');
            }

        }
        Business::updatebusinessCount();
        PageContext::$response->message = Messages::getPageMessage();

    }

    public function organization_list()
    {
        $from = '';
        if ($_GET['groupby'] != '') {
            $groupby = $_GET['groupby'];
        } else {
            $groupby = '';
        }
        if ($_GET['from'] != '') {
            $user_id = PageContext::$response->sess_user_id;
            $from = 'endorsement';
        } else {
            $user_id = '';
            $from = '';
        }
        if (PageContext::$response->sess_user_id > 0) {
            PageContext::registerPostAction("menu", "home_menu", "index", "default");
        } else {
            PageContext::registerPostAction("menu", "menu", "index", "default");
        }
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "business_list", "user", "default");
        PageContext::addStyle("rateit.css");
        PageContext::addScript("comment_popup.js");
        PageContext::addScript("organisation.js");

        PageContext::$body_class = 'business_profile';
        PageContext::$response->activeSubMenu = 'business';
        $category = Cmshelper::getAllCategoryName();

        if ($category) {
            $category_dropdown['--All Category--'] = '';
            foreach ($category as $key => $val) {
                $category_dropdown[$val->text] = $val->value;
            }
        }
        PageContext::$response->categories = $category_dropdown;
        $orderfield = PageContext::$request['sort'];
        $orderby = PageContext::$request['sortby'];
        $page = PageContext::$request['page'];
        $search = addslashes(PageContext::$request['searchtext']);
        $searchtype = PageContext::$request['searchtype'];
        if ($orderby == '')
            $orderby = ' DESC';
        if ($orderfield == '')
            $orderfield = 'business_id';
        // code to get the arrow for the sort order
        PageContext::$response->business_name_sortorder = Utils::sortarrow();
        PageContext::$response->{$orderfield . '_sortorder'} = Utils::getsortorder($orderby);
        PageContext::$response->searchtext = $search;
        PageContext::$response->searchtype = $searchtype;
        PageContext::$response->page = $page;
        // search field section
        PageContext::$response->search = array('fields' => array(), 'action' => PageContext::$response->baseUrl . 'directory');
        switch ($searchtype) {
            case 'all':
                $searchtypeArray = array('business_name', 'business_email', 'business_type');
                break;
        }
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';
        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
        PageContext::$response->cat_id = $groupby;
        $itemperpage = 12;
        PageContext::$response->itemperpage = $itemperpage;
        $targetpage = BASE_URL . 'directory?searchtext=' . $search . '&searchtype=' . $searchtype . '&sort=' . $orderfield . '&sortby=' . $orderby;
        $leads = Business::getAllBusiness($orderfield, $orderby, $page, $itemperpage, $search, $searchtypeArray, $user_id, $groupby, $from);
        $total_pages = (($leads->totalrecords) / LAZYLOAD_COUNT);
        PageContext::addJsVar('T_PAGE', $total_pages);
        foreach ($leads->records as $k => $com) {
            //echopre($com);
            $type = 'B';
            $type_id = $com->business_id;
            $user_id = PageContext::$response->sess_user_id;
            if ($user_id == '') {
                $user_id = 0;
            }
            $value = 0;
            $flag = 0;
            $rate = Ratings::getRatings($type_id, $type);
            if ($rate->data->count != 0) {
                $value = $rate->data->total / $rate->data->count;
            }
            if ($user_id <= 0) {
                $flag = 1;
            } else {
                if ($user_id == $com->business_created_by) {
                    $flag = 2;
                } else {
                    $rate1 = Ratings::checkIfRated($type_id, $type, $user_id);
                    if ($rate1->data->rating_id > 0 || $rate1->data->rating_id != '') {
                        $flag = 1;
                    }
                }
            }
            $leads->records[$k]->ratetype = $type;
            $leads->records[$k]->ratevalue = $value;
            $leads->records[$k]->rateuser_id = $user_id;
            $leads->records[$k]->rateflag = $flag;
            $leads->records[$k]->ratetype_id = $type_id;
            $leads->records[$k]->owner_name = $com->user_firstname . " " . $com->user_lastname;
        }
        PageContext::addScript("jquery.rateit.js");
        PageContext::addScript("ratinglist.js");
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->slno = 1;
        PageContext::$response->leads = $leads->records;
        PageContext::$response->totalrecords = ($leads->totalrecords == '') ? 0 : $leads->totalrecords;
        PageContext::$response->pagination = Pagination::paginate($page, $itemperpage, $leads->totalrecords, $targetpage);
    }

    public function organization_listajax($pagenum)
    {
        if (PageContext::$response->sess_user_id > 0) {
            PageContext::registerPostAction("menu", "home_menu", "index", "default");
        } else {
            PageContext::registerPostAction("menu", "menu", "index", "default");
        }
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "business_list", "user", "default");
        PageContext::addStyle("rateit.css");
        PageContext::$body_class = 'business_profile';
        PageContext::$response->activeSubMenu = 'business';
        $orderfield = PageContext::$request['sort'];
        $orderby = PageContext::$request['sortby'];
        $page = PageContext::$request['page'];
        $search = addslashes(PageContext::$request['searchtext']);
        $searchtype = PageContext::$request['searchtype'];
        if ($orderby == '')
            $orderby = ' DESC';
        if ($orderfield == '')
            $orderfield = 'business_id';
        // code to get the arrow for the sort order
        PageContext::$response->business_name_sortorder = Utils::sortarrow();
        PageContext::$response->{$orderfield . '_sortorder'} = Utils::getsortorder($orderby);
        PageContext::$response->searchtext = $search;
        PageContext::$response->searchtype = $searchtype;
        PageContext::$response->page = $page;
        // search field section
        PageContext::$response->search = array('fields' => array(), 'action' => PageContext::$response->baseUrl . 'directory');
        switch ($searchtype) {
            case 'all':
                $searchtypeArray = array('business_name', 'business_email', 'business_type');
                break;
        }
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';
        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
        $itemperpage = 8;
        PageContext::$response->itemperpage = $itemperpage;
        $targetpage = BASE_URL . 'directory?searchtext=' . $search . '&searchtype=' . $searchtype . '&sort=' . $orderfield . '&sortby=' . $orderby;
        $leads = Business::getAllBusiness($orderfield, $orderby, $pagenum, 8, $search, $searchtypeArray);
        foreach ($leads->records as $k => $com) {
            $type = 'B';
            $type_id = $com->business_id;
            $user_id = PageContext::$response->sess_user_id;
            if ($user_id == '') {
                $user_id = 0;
            }
            $value = 0;
            $flag = 0;
            $rate = Ratings::getRatings($type_id, $type);
            if ($rate->data->count != 0) {
                $value = $rate->data->total / $rate->data->count;
            }
            if ($user_id <= 0) {
                $flag = 1;
            } else {
                if ($user_id == $com->data->business_created_by) {
                    $flag = 2;
                } else {
                    $rate1 = Ratings::checkIfRated($type_id, $type, $user_id);
                    if ($rate1->data->rating_id > 0 || $rate1->data->rating_id != '') {
                        $flag = 1;
                    }
                }
            }
            $leads->records[$k]->ratetype = $type;
            $leads->records[$k]->ratevalue = $value;
            $leads->records[$k]->rateuser_id = $user_id;
            $leads->records[$k]->rateflag = $flag;
            $leads->records[$k]->ratetype_id = $type_id;
            $leads->records[$k]->owner_name = $com->user_firstname . " " . $com->user_lastname;
        }
        PageContext::addScript("jquery.rateit.js");
        PageContext::addScript("ratinglist.js");
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->slno = 1;
        PageContext::$response->leads = $leads->records;
        PageContext::$response->totalrecords = ($leads->totalrecords == '') ? 0 : $leads->totalrecords;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();

    }

    /*
     * Function for ajax display of My profile
     */
    public function myprofile()
    {
        $objSession = new LibSession();
        PageContext::$response = new stdClass();
        $values = $objSession->get('user_id', 'default');
        $user_id = $_POST['uid'];
        $alias = $_POST['alias'];
        PageContext::$response->alias = $alias;
        PageContext::$response->sess_user_alias = Utils::getAuth('user_alias');
        $userDetails = User::getUserDetails($alias);
        $tagDetails = User::getAssociatedBusiness($userDetails->data->Id, 1, 6);
        PageContext::$response->tagDetails = $tagDetails->data;
        $unsetArray = array('user_firstname', 'user_lastname', 'Image', 'Membership_Type', 'Points', 'Inustry_Name', 'user_last_login', 'user_business_count', 'user_friends_count', 'user_community_count', 'user_image_name', 'user_privacy', 'User Privacy');
        if (($userDetails->data->user_privacy == 'H' || $values == '') && ($userDetails->data->user_privacy != 'SA') && ($values != $userDetails->data->Id)) {
            $unsetArray = array('user_firstname', 'user_lastname', 'Image', 'Membership_Type', 'Points', 'Inustry_Name', 'user_last_login', 'user_business_count', 'user_friends_count', 'user_community_count', 'user_image_name', 'user_privacy', 'Email', 'Date_of_Birth', 'user_country', 'Image', 'user_image_name', 'Address', 'City', 'Country', 'State', 'Phone', 'Zip_Code');
        } else if ($userDetails->data->user_privacy == 'SM' && $userDetails->data->Id != $values) {
            $unsetArray = array('user_firstname', 'user_lastname', 'Image', 'Membership_Type', 'Points', 'Inustry_Name', 'user_last_login', 'user_business_count', 'user_friends_count', 'user_community_count', 'user_image_name', 'user_privacy', 'Email', 'Date_of_Birth', 'Image', 'user_image_name');
        }
        $total_pages = (sizeof($tagDetails->data) / LAZYLOAD_COUNT);
        PageContext::addJsVar('TOTAL_PAGESS', $total_pages);
        PageContext::$response->userDetails = Utils::objectToArray($userDetails->data);
        PageContext::$response->userListDetails = Utils::unsetArrayElements($unsetArray, PageContext::$response->userDetails);
        PageContext::$response->id = $userDetails->data->Id;
        PageContext::$response->userImagePath = USER_IMAGE_URL;
        PageContext::$response->baseUrl = BASE_URL;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function myprofileajax($pagenum = 1, $usr_id)
    {
        $objSession = new LibSession();
        $values = $objSession->get('user_id', 'default');
        $user_id = $_POST['user_id'];
        PageContext::$response->alias = $alias;
        $tagDetails = User::getAssociatedBusiness($user_id, $pagenum, 6);
        PageContext::$response->tagDetails = $tagDetails->data;
        $unsetArray = array('user_firstname', 'user_lastname', 'Image', 'Membership_Type', 'Points', 'Inustry_Name', 'user_last_login', 'user_business_count', 'user_friends_count', 'user_community_count', 'user_image_name', 'user_privacy');
        if (($userDetails->data->user_privacy == 'H' || $values == '') && ($userDetails->data->user_privacy != 'SA') && ($values != $userDetails->data->Id)) {
            $unsetArray = array('user_firstname', 'user_lastname', 'Image', 'Membership_Type', 'Points', 'Inustry_Name', 'user_last_login', 'user_business_count', 'user_friends_count', 'user_community_count', 'user_image_name', 'user_privacy', 'Email', 'Date_of_Birth', 'user_country', 'user_state', 'Image', 'user_image_name', 'Address', 'City', 'Country', 'State', 'Phone', 'Zip_Code');
        } else if ($userDetails->data->user_privacy == 'SM' && $userDetails->data->Id != $values) {
            $unsetArray = array('user_firstname', 'user_lastname', 'Image', 'Membership_Type', 'Points', 'Inustry_Name', 'user_last_login', 'user_business_count', 'user_friends_count', 'user_community_count', 'user_image_name', 'user_privacy', 'Email', 'Date_of_Birth', 'Image', 'user_image_name');
        }
        PageContext::$response->userDetails = Utils::objectToArray($userDetails->data);
        PageContext::$response->userListDetails = Utils::unsetArrayElements($unsetArray, PageContext::$response->userDetails);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    /*
     * Function to list friends
     */
    public function listfriends()
    {

        PageContext::registerPostAction("importcontacts", "importcontacts", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "listfriends", "user", "default");
        PageContext::addScript(BASE_URL . 'project/lib/ckeditor/ckeditor.js');
        PageContext::addScript('timeago.js');
        PageContext::addScript('cloudsponge.js');
        PageContext::$response = new stdClass();
        PageContext::$response->activeSubMenu = 'profile';
        $user_id = $_POST['uid'];
        $alias = $_POST['alias'];
        $groupby = $_POST['groupby'];
        PageContext::$response->alias = $alias;
        PageContext::$response->groupby = $groupby;
        $friends = User::getUserFriends1($alias, 1, 8, '', 'users.user_firstname', 'ASC', $groupby);
       // echopre1($friends);
        PageContext::$response->count = $friends->totalrecords;
        PageContext::$response->friends = $friends->records;
        PageContext::$response->invitation_type = 'user';
        PageContext::$response->sess_user_id = Utils::getAuth('user_id');
        PageContext::$response->sess_user_alias = Utils::getAuth('user_alias');
        PageContext::$response->alias = $alias;
        PageContext::$response->invitation_typeid = PageContext::$response->sess_user_id;
        PageContext::$response->userImagePath = USER_IMAGE_URL;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function listfriendajax($pagenum = 1, $alias, $groupby)
    {
        PageContext::$response->alias = $alias;
        if ($_POST['groupby']) {
            $groupby = $_POST['groupby'];
        }
        $friends = User::getUserFriends1($alias, $pagenum, 8, '', 'users.user_firstname', 'ASC', $groupby);
        if ($friends->records == '') {
            return ' ';
        }
        PageContext::$response->friends = $friends->records;
        PageContext::$response->userImagePath = USER_IMAGE_URL;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function listmembers()
    {
        $itemsPerPage = 5 ;
        $page = 1 ;
        PageContext::$response->activeSubMenu = 'community';
        $communityAlias = $_POST['communityAlias'];
        $communityDetails = Communities::getCommunityAlias($communityAlias);
        $members = Communities::getCommunityMembers($communityAlias, 'A', $itemsPerPage, $orderfield = 'community_id', $orderby = 'DESC',$page);
        $pendingMembers = Communities::getCommunityMembers($communityAlias, 'I');
        PageContext::$response->communityDetails = $communityDetails->data;
        PageContext::$response->members = $members->data;
        PageContext::$response->count = $members->memberCount;
        PageContext::$response->pendingcount = $pendingMembers->memberCount;
        PageContext::$response->pendingMembers = $pendingMembers->data;
        PageContext::$response->communityAlias = $communityAlias;
        PageContext::$response->totalPages = ceil($members->memberCount/$itemsPerPage);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }
    
    public function listmembersajax($nextPage)
    {
        $itemsPerPage = 5 ;
        PageContext::$response->activeSubMenu = 'community';
        $communityAlias = $_POST['community_alias'];
        $communityDetails = Communities::getCommunityAlias($communityAlias);
        $members = Communities::getCommunityMembers($communityAlias, 'A', $itemsPerPage, $orderfield = 'community_id', $orderby = 'DESC', $nextPage);
        $pendingMembers = Communities::getCommunityMembers($communityAlias, 'I');
        PageContext::$response->communityDetails = $communityDetails->data;
        PageContext::$response->members = $members->data;
        PageContext::$response->count = $members->memberCount;
        PageContext::$response->pendingcount = $pendingMembers->memberCount;
        PageContext::$response->pendingMembers = $pendingMembers->data;
        PageContext::$response->communityAlias = $communityAlias;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }
    
    public function group_gallary()
    {
        $itemsPerPage = 5 ;
        $page = 1 ;
       PageContext::$response->activeSubMenu = 'community';
        $communityId = $_POST['comm_id'];
        $communityImageDetails = Communities::getCommunityImages($communityId,$orderfield = 'community_id', $orderby = 'DESC',$page ,$itemsPerPage);
        PageContext::$response->imageDetails = $communityImageDetails->records;
        PageContext::$response->communityId = $communityId;
        PageContext::$response->totalPages = ceil($communityImageDetails->totalrecords/$itemsPerPage);
        PageContext::$response->gallery_display_list = Communities::getMyLatestDiscussionImage($communityId);
        PageContext::$response->friend_display_list = Communities::getCommunityMembers($communityId, 'A', 3, $orderfield = 'community_id', $orderby = 'DESC','');
       
        
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function group_gallaryajax($nextPage)
    {
       PageContext::$response->activeSubMenu = 'community';
        $community_id = $_POST['community_id'];
        $itemsPerPage = 5 ;
        $communityImageDetails = Communities::getCommunityImages($community_id,$orderfield = 'community_id', $orderby = 'DESC', $nextPage, $itemsPerPage);
        PageContext::$response->imageDetails = $communityImageDetails->records;
        PageContext::$response->communityId = $communityId;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }
    
    public function listgroupinvitation()
    {
        PageContext::$response->activeSubMenu = 'community';
        $communityAlias = $_POST['communityAlias'];
        $communityDetails = Communities::getCommunityAlias($communityAlias);
        $invites = Communities::getCommunityInvitationReport($communityAlias, 1, 10);
        PageContext::$response->communityDetails = $communityDetails->data;
        PageContext::$response->invites = $invites->records;
        $invitescount = Communities::getCommunityInvitationCount($communityAlias);
        PageContext::$response->invitationCount = sizeof($invitescount);
        $total_pages = (sizeof($invitescount) / 10);
        PageContext::addJsVar('TOTAL_PAGESS', $total_pages);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function listgroupinvitationajax($pagenum = 1, $communityAlias)
    {
        $communityDetails = Communities::getCommunityAlias($communityAlias);
        $invites = Communities::getCommunityInvitationReport($communityAlias, $pagenum, 10);
        PageContext::$response->communityDetails = $communityDetails->data;
        PageContext::$response->invites = $invites->records;
        $invitescount = Communities::getCommunityInvitationCount($communityAlias);
        PageContext::$response->invitationCount = sizeof($invitescount);
        PageContext::$response->slnostart = (10 * ($pagenum - 1)) + 1;
        $total_pages = (sizeof($invitescount) / 10);
        PageContext::addJsVar('TOTAL_PAGESS', $total_pages);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function listmessages()
    {
        Utils::checkUserLoginStatus();
        if (PageContext::$response->sess_user_status == 'I') {
            $this->redirect("inactiveuser");
        }
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$body_class = 'business_profile';
        $page = PageContext::$request['page'];
        $itemperpage = PAGE_LIST_COUNT;
        if ($orderby == '')
            if ($orderfield == '')
                PageContext::$response->page = $page;
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';
        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
        $targetpage = BASE_URL . 'pending-bizcom-request?order=' . orderby;
        $users = Connections::getAllPendingRequest($orderfield, $orderby, $page, $itemperpage);
        $bizcom = Connections::getAllBizcomPendingRequest($orderfield, $orderby, $page, $itemperpage);
        $bizlist = $bizcom->records;
        $usersList = $users->records;
        PageContext::$response->usersList = array_merge($bizlist, $usersList);
        $message_count_array = Connections::getAllMessagescount();
        $message_count = sizeof($message_count_array->records);
        PageContext::addJsVar('	', $users->totpages);
        PageContext::addScript('pendingbizcom_lazyload.js');
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "inbox", "user", "default");
        PageContext::addScript('community_tab.js');
        PageContext::addScript('community.js');
        PageContext::$body_class = 'member_area';
        PageContext::$response->activeSubMenu = 'community';
        PageContext::$response->invitation_type = 'community';
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$metaTitle = META_TITLE;// = SITE_NAME . " : Your personalised social network";
        $total_pages = $message_count / LAZYLOAD_COUNT;
        PageContext::addJsVar('LAZYCOUNT', LAZYLOAD_COUNT);
        PageContext::addJsVar('TOTAL_PAGES', $total_pages);
        PageContext::addScript('communitymember_lazyload.js');
        PageContext::$response->tojoin = '';
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function listinvitationsinbox()
    {
        Utils::checkUserLoginStatus();
        if (PageContext::$response->sess_user_status == 'I') {
            $this->redirect("inactiveuser");
        }
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$body_class = 'business_profile';
        $page = PageContext::$request['page'];
        $itemperpage = LAZYLOAD_COUNT;
        if ($orderby == '')
            $orderby = ' DESC';
        if ($orderfield == '')
            $orderfield = 'invitation_id';
        PageContext::$response->page = $page;
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';
        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
        $targetpage = BASE_URL . 'pending-bizcom-request?order=' . orderby;
        $users = Connections::getAllPendingRequestinbox($orderfield, $orderby, $page, LAZYLOAD_COUNT);
        $inv_count_array = Connections::getAllPendingRequestinboxcount();
        $bizlist = $bizcom->records;
        $usersList = $users1->records;
        PageContext::$response->usersList = $users->records;
        $inv_count = sizeof($inv_count_array->records);
        PageContext::addJsVar('TOTAL_PAGES', $users->totpages);
        PageContext::addScript('pendingbizcom_lazyload.js');
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "inbox", "user", "default");
        PageContext::addScript('community_tab.js');
        PageContext::addScript('community.js');
        PageContext::$body_class = 'member_area';
        PageContext::$response->activeSubMenu = 'community';
        PageContext::$response->invitation_type = 'community';
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$metaTitle = META_TITLE;// = SITE_NAME . " : Your personalised social network";
        $total_pages = $inv_count / LAZYLOAD_COUNT;
        PageContext::addJsVar('LAZYCOUNT', LAZYLOAD_COUNT);
        PageContext::addJsVar('TOTAL_PAGESS', $total_pages);
        PageContext::addScript('communitymember_lazyload.js');
        PageContext::$response->tojoin = '';
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function listinvitationsajax($pagenum)
    {
        if (!PageContext::$response->sess_user_id) {
            exit();
        }
        if ($orderby == '')
            $orderby = ' DESC';
        if ($orderfield == '')
            $orderfield = 'invitation_id';
        $users = Connections::getAllPendingRequestinbox($orderfield, $orderby, $pagenum, LAZYLOAD_COUNT);
        PageContext::$response->usersList = $users->records;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function listmessagesajax($pagenum)
    {
        if (!PageContext::$response->sess_user_id) {
            exit();
        }
        if ($orderby == '')
            $orderby = ' DESC';
        if ($orderfield == '')
            $orderfield = 'message_id';
        $message_details = Connections::getAllMessages($orderfield, $orderby, $pagenum, LAZYLOAD_COUNT);
        PageContext::$response->message_details = $message_details;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function deletemessages($message_id)
    {
        $objUserRes = new stdClass();
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $result = Connections::deletemessage($message_id);
        $result->message = 'SUCCESS';
        PageContext::$full_layout_rendering = false;
        Messages::setPageMessage('Your message deleted successfully', 'success_div');
        $this->view->disableLayout();
        return json_encode(Utils::objectToArray($result));
    }

    public function listmemberajax($pagenum = 1, $communityAlias)
    {
        $communityDetails = Communities::getCommunityAlias($communityAlias);
        $members = Communities::getAllMemebersCommunity($communityAlias, $pagenum, 9);
        PageContext::$response->communityDetails = $communityDetails->data;
        PageContext::$response->members = $members->records;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function groupmembersearch($pagenum = 1, $communityAlias, $search = '', $lazyloadcount = 100)
    {
        $communityDetails = Communities::getCommunityAlias($communityAlias);
        $members = Communities::getAllMemebersCommunity($communityAlias, $pagenum, $lazyloadcount, $search);
        //echopre1($members);
        PageContext::$response->communityDetails = $communityDetails->data;
        PageContext::$response->members = $members->records;
        PageContext::$response->membercount = $members->totalrecords / LAZYLOAD_COUNT;
        PageContext::$full_layout_rendering = false;
       // print_r($this->view);
        $this->view->disableLayout();
    }

    public function add_group()
    {
        if ($_GET['business_id']) {
            $business_id = $_GET['business_id'];
            PageContext::$response->business_id = $business_id;
        }
        Utils::checkUserLoginStatus();
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("rightcontentbutton", "rightmenubutton", "user", "default");
        PageContext::registerPostAction("leftcontent", "add_community", "user", "default");
        PageContext::addScript('cms_select_state_business.js');
        PageContext::addScript('validations_form.js');
        PageContext::addScript('community.js');
        PageContext::$body_class = 'register';
        PageContext::$response->activeSubMenu = 'community';
        $tagDetails = User::getAssociatedBusiness(PageContext::$response->sess_user_id, 'All');
        $businessDatas = $tagDetails->data;
        $businessArray = array();
        PageContext::$response->org_grp = ORG_GRP;
        $businessArray['--Choose Page--'] = '';
        foreach ($businessDatas AS $businessData) {
            $businessArray[$businessData->business_name] = $businessData->business_id;
        }
        PageContext::$response->businessArray = $businessArray;
        $category = Cmshelper::getAllCategoryName();
        if ($category) {
            $category_dropdown['--Category--'] = '';
            foreach ($category as $key => $val) {
                $category_dropdown[$val->text] = $val->value;
            }
        }
        PageContext::$response->categories = $category_dropdown;
        //---------------community Form-----------------
        if (PageContext::$request['btnSubmit']) { //--Post action--
            $unsetArray = array('btnSubmit');
            if ($_FILES['community_image_id']['name']) {
                $fileHandler = new Filehandler();   //  print_r($_FILES); exit;
                $bannerFileDetails = $fileHandler->handleUpload($_FILES['community_image_id'], FILE_UPLOAD_DIR);
            }
            if ($_FILES['community_logo_id']['name']) {
                $fileHandler = new Filehandler();   //  print_r($_FILES); exit;
                $logoFileDetails = $fileHandler->handleUpload($_FILES['community_logo_id'], FILE_UPLOAD_DIR);
            }
            if (ADMIN_APPROVE_BIZCOM_AUTO == 1) {
                $status = 'A';
                $msg = COMMUNITY_SUCCESS;
            } else {
                $status = 'I';
                $msg = COMMUNITY_SUCCESS . COMMUNITY_SUCCESS_APPROVAL;
            }
            $additionalParameters = array(
                'community_created_by' => Utils::getAuth('user_id'),
                'community_created_on' => date('Y-m-d'),
                'community_status' => $status
            );
            if ($bannerFileDetails->file_id > 0) {
                $additionalParameters['community_image_id'] = $bannerFileDetails->file_id;
                //Utils::allResize($bannerFileDetails->file_path, 'small', 190, 134);
                Utils::allResize($bannerFileDetails->file_path, 'small', '', 134);
                Utils::allResize($bannerFileDetails->file_path, 'medium', '', 164);
                Utils::allResize($bannerFileDetails->file_path, 'thumb', '', 50);
                Utils::allResize($bannerFileDetails->file_path, 'timeline', '', 258);
            }
            if ($logoFileDetails->file_id > 0) {
                $additionalParameters['community_logo_id'] = $logoFileDetails->file_id;
                Utils::allResize($logoFileDetails->file_path, 'small', '', 134);
                Utils::allResize($logoFileDetails->file_path, 'medium', '', 164);
                Utils::allResize($logoFileDetails->file_path, 'thumb', '', 30);
                Utils::allResize($bannerFileDetails->file_path, 'timeline', '', 258);
            }
            $objUserVo = new stdClass();
            $objUserVo->community_name = Utils::escapeString(PageContext::$request['community_name']);
            $objUserVo->community_description = Utils::escapeString(PageContext::$request['community_description']);
            $objUserVo->community_type = Utils::escapeString(PageContext::$request['community_type']);
            $objUserVo->community_business_id = Utils::escapeString(PageContext::$request['business_type']);
            $objUserVo->community_created_by = Utils::getAuth('user_id');
            $objUserVo->community_created_on = date('Y-m-d');
            $objUserVo->community_status = $status;
            $objUserVo->community_image_id = $bannerFileDetails->file_id;
            $objUserVo->community_logo_id = $logoFileDetails->file_id;
            $objUserVo->community_logo_name = $logoFileDetails->file_path;
            if(ORG_GRP == 1){
                $objUserVo->community_organization_relation_status = 1;
            }
            else{
                $objUserVo->community_organization_relation_status = 0;
            }
            if ($objUserVo->community_business_id > 0) {
                $category_id = Communities::getCategoryId($objUserVo->community_business_id);
                $objUserVo->community_category_id = $category_id->business_category_id;
            } else {
                $objUserVo->community_category_id = Utils::escapeString(PageContext::$request['community_category_id_add']);
            }
            $objUserRes = Communities::createCommunity($objUserVo);
            if ($objUserRes->status == SUCCESS) {//-----User Registration mail------
                if (ADMIN_APPROVE_BIZCOM_AUTO == 0) {
                    $mailIds = array();
                    $replaceparams = array();
                    $mailIds[ADMIN_EMAILS] = '';
                    $replaceparams['NAME'] = PageContext::$response->sess_user_name;
                    $replaceparams['TITLE'] = $objUserVo->community_name;
                    $replaceparams['ENTITY'] = 'Group';
                    $objMailer = new Mailer();
                    $objMailer->sendMail($mailIds, 'admin_approval', $replaceparams);
                }
                Messages::setPageMessage($msg, 'success_div');
                Communities::updateCommunityCounts();
                $this->redirect('my-groups');
            } else { //----- User insertion failed--------
                Messages::setPageMessage($objUserRes->message, 'error_div');
            }
        }
        Communities::updateCommunityCounts();
        PageContext::$response->message = Messages::getPageMessage();
    }

    public function edit_group($communitId = '')
    {
        Utils::checkUserLoginStatus();
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "edit_community", "user", "default");
        PageContext::addScript('cms_select_state_business.js');
        PageContext::addScript("jquery.colorbox.js");
        PageContext::addScript('community.js');
        PageContext::addScript('validations_form.js');
        PageContext::$body_class = 'register';
        PageContext::$response->activeSubMenu = 'community';
        PageContext::$response->org_grp = ORG_GRP;
        $result = Communities::getCommunity($communitId);
        $result1                                         = Communities::getCommunityAlias($communitId);
        PageContext::$response->img                     =  $result1->data->file_path;
        PageContext::$metaTitle = META_TITLE;// = SITE_NAME . " : Your personalised social network";
        PageContext::$metaDes = META_DES;// = SITE_NAME . " - Edit Community";
        PageContext::$metaKey = META_KEYWORDS;//= SITE_NAME . " - Edit Community";
        $tagDetails = User::getAssociatedBusiness(PageContext::$response->sess_user_id);
        $businessDatas = $tagDetails->data;
        $businessArray = array();
        $businessArray['--Choose Page--'] = '';
        foreach ($businessDatas AS $businessData) {
            $businessArray[$businessData->business_name] = $businessData->business_id;
        }
        $category = Cmshelper::getAllCategoryName();
        if ($category) {
            $category_dropdown['--Category--'] = '';
            foreach ($category as $key => $val) {
                $category_dropdown[$val->text] = $val->value;
            }
        }
        PageContext::$response->categories = $category_dropdown;
        PageContext::$response->businessArray = $businessArray;
        PageContext::$response->getData = Utils::objectToArray($result->data);

        if (PageContext::$request['btnSubmit']) { //--Post action--
            $unsetArray = array('btnSubmit', 'radiobusiness_type');
            if ($_FILES['community_image_id']['name']) {
                $fileHandler = new Filehandler();   //  print_r($_FILES); exit;
                $bannerFileDetails = $fileHandler->handleUpload($_FILES['community_image_id'], FILE_UPLOAD_DIR);
            }
            if ($_FILES['community_logo_id']['name']) {
                $fileHandler = new Filehandler();   //  print_r($_FILES); exit;
                $logoFileDetails = $fileHandler->handleUpload($_FILES['community_logo_id'], FILE_UPLOAD_DIR);
            }
            $additionalParameters = array();
            if ($bannerFileDetails->file_id > 0) {
                $additionalParameters['community_image_id'] = $bannerFileDetails->file_id;
                Utils::allResize($bannerFileDetails->file_path, 'small', 190, 134);
                Utils::allResize($bannerFileDetails->file_path, 'medium', 178, 164);
                Utils::allResize($bannerFileDetails->file_path, 'thumb', 50, 50);
            }
            if ($logoFileDetails->file_id > 0) {
                $additionalParameters['community_logo_id'] = $logoFileDetails->file_id;
                $additionalParameters['community_logo_name'] = $logoFileDetails->file_path;
                Utils::allResize($logoFileDetails->file_path, 'small', 190, 134);
                Utils::allResize($logoFileDetails->file_path, 'medium', 178, 164);
                Utils::allResize($logoFileDetails->file_path, 'thumb', 50, 30);
            }
            $objUserVo = Utils::arrayToObject($_POST, $additionalParameters, $unsetArray);
            $objUserRes = Communities::editCommunity($communitId, $objUserVo);
            if ($objUserRes->status == SUCCESS) {//-----User Registration mail------
                Messages::setPageMessage(COMMUNITY_ED_SUCCESS, 'success_div');
                $this->redirect('my-groups');
            } else { //----- User insertion failed--------
                Messages::setPageMessage($objUserRes->message, 'error_div');
            }
        }
        Communities::updateCommunityCounts();
        PageContext::$response->message = Messages::getPageMessage();
    }

    public function create_message($to_user_id, $message_subject)
    {
        $objUserRes = new stdClass();
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        PageContext::$response->to_user_id = $to_user_id;
        PageContext::$response->message_subject = $message_subject;
    }

    public function show_message($message_id)
    {
        $objUserRes = new stdClass();
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $result = Connections::showmessage($message_id);
        PageContext::$response->message_detail = $result[0]->message_detail;
        PageContext::$response->message_subject = $result[0]->message_subject;
    }

    public function send_message($to_user_id)
    {
        $message_details = PageContext::$request['message_details'];
        $objUserRes = new stdClass();
        $result = Connections::sendmessage($to_user_id, $message_details);
        $result->message = 'SUCCESS';
        echo json_encode(Utils::objectToArray($result));
        PageContext::$response->to_user_id = $to_user_id;
    }

    public function invite_permission_setting_set()
    {
        if ($_POST['communityId'] != '') {
            $recipients = trim($_POST['txtRecipients']);
            $members = $_POST['inv_check'];
            if ($recipients != '') { //Non members mail
                $recipientArray = explode(',', $recipients);
                foreach ($recipientArray AS $recipient) {
                    if (verify_email($recipient)) {
                        $mailIds = array();
                        $replaceparams = array();
                        $mailIds[$recipient] = $recipient;
                        $replaceparams[''] = ($getUserData->user_firstname) ? $getUserData->user_firstname : $getUserData->Email;
                        $replaceparams['COMMUNITY'] = $communitDetails->community_name;
                        $replaceparams['NAME'] = ($sendUserDetails->user_firstname) ? $sendUserDetails->user_firstname : $sendUserDetails->Email;
                        $replaceparams['INVITE_ID'] = $result->invitation_id;
                        $replaceparams['INVITE_TYPE'] = 'community';
                        $objMailer->sendMail($mailIds, 'community_invite', $replaceparams);
                    }
                }
            }
            if ($members != '') { //Members mail
                foreach ($recipientArray AS $recipient) {
                    $getUserData = User::getUserDetail(PageContext::$request['senderId']);
                    $getUserData = $getUserData->data;
                    $mailIds = array();
                    $replaceparams = array();
                    $mailIds[$getUserData->Email] = ($getUserData->user_firstname) ? user_firstname : $getUserData->Email;
                    $replaceparams['USER_NAME'] = ($getUserData->user_firstname) ? $getUserData->user_firstname : $getUserData->Email;
                    $replaceparams['COMMUNITY'] = $communitDetails->community_name;
                    $replaceparams['NAME'] = ($sendUserDetails->user_firstname) ? $sendUserDetails->user_firstname : $sendUserDetails->Email;
                    $replaceparams['INVITE_ID'] = $result->invitation_id;
                    $replaceparams['INVITE_TYPE'] = 'community';
                    $objMailer->sendMail($mailIds, 'community_invite', $replaceparams);
                }
            }
            $setpermission = Communities::setpermissionsinv($_POST['communityId'], $_POST['inv_check']);
        } else {
            $objUserRes = new stdClass();
            PageContext::$full_layout_rendering = false;
            $this->view->disableLayout();
            $members = Communities::getCommunityMembers($communityId, 'A', 4);
            PageContext::$response->members = $members->data;
            PageContext::$response->communityId = $communityId;
        }
    }

    public function group_list()
    {
        if ($_GET['groupby'] != '') {
            $groupby = $_GET['groupby'];
        } else {
            $groupby = '';
        }
        $user_id = PageContext::$response->sess_user_id;
        if (PageContext::$response->sess_user_id > 0) {
            PageContext::registerPostAction("menu", "home_menu", "index", "default");
        } else {
            PageContext::registerPostAction("menu", "menu", "index", "default");
        }
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "community_list", "user", "default");
        PageContext::addScript("comment_popup.js");
        PageContext::addScript("organisation.js");
       

        PageContext::$body_class = 'business_profile';
        PageContext::$response->activeSubMenu = 'community';
        $category = Cmshelper::getAllCategoryName();
        if ($category) {
            $category_dropdown['--All Category--'] = '';
            foreach ($category as $key => $val) {
                $category_dropdown[$val->text] = $val->value;
            }
        }
        PageContext::$response->categories = $category_dropdown;
        $orderfield = PageContext::$request['sort'];
        $orderby = PageContext::$request['sortby'];
        $page = PageContext::$request['page'];
        $search = addslashes(PageContext::$request['searchtext']);
        $searchtype = PageContext::$request['searchtype'];

        if ($orderby == '')
            $orderby = ' DESC';
        if ($orderfield == '')
            $orderfield = 'community_id';
        // code to get the arrow for the sort order
        PageContext::$response->community_name_sortorder = Utils::sortarrow();
        PageContext::$response->{$orderfield . '_sortorder'} = Utils::getsortorder($orderby);
        PageContext::$response->searchtext = $search;
        PageContext::$response->searchtype = $searchtype;
        PageContext::$response->page = $page;
        // search field section
        PageContext::$response->search = array('fields' => array(), 'action' => PageContext::$response->baseUrl . 'groups');

        switch ($searchtype) {
            case 'all':
                $searchtypeArray = array('community_name');
                break;
            case 'name':
                $searchtypeArray = array();
                break;
            case 'email':
                $searchtypeArray = array();
                break;
            case 'phone':
                $searchtypeArray = array();
                break;
        }
        PageContext::$response->messagebox = Messages::getPageMessage();

        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';

        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
        PageContext::$response->cat_id = $groupby;
        $itemperpage = 10;
        PageContext::$response->itemperpage = $itemperpage;
        $targetpage = BASE_URL . 'groups?searchtext=' . $search . '&searchtype=' . $searchtype . '&sort=' . $orderfield . '&sortby=' . $orderby;
        $leads = Communities::getCommunities($orderfield, $orderby, 1, 10, $search, $searchtypeArray, $user_id, '', $groupby);
        $total_pages = (($leads->totalrecords) / LAZYLOAD_COUNT);
        PageContext::addJsVar('T_PAG', $total_pages);
        PageContext::addStyle("rateit.css");
        $count = 0;
        foreach ($leads->records as $k => $com) {
            $type = 'C';
            $type_id = $com->community_id;
            $user_id = PageContext::$response->sess_user_id;
            if ($user_id == '') {
                $user_id = 0;
            }
            $value = 0;
            $flag = 0;
            $rate = Ratings::getRatings($type_id, $type);
            if ($rate->data->count != 0) {
                $value = $rate->data->total / $rate->data->count;
            }
            if ($user_id <= 0) {
                $flag = 1;
            } else {
                $rate1 = Ratings::checkIfRated($type_id, $type, $user_id);
                if ($rate1->data->rating_id > 0 || $rate1->data->rating_id != '') {
                    $flag = 1;
                }
            }
            $count++;
            $leads->records[$k]->ratetype = $type;
            $leads->records[$k]->ratevalue = $value;
            $leads->records[$k]->rateuser_id = $user_id;
            $leads->records[$k]->rateflag = $flag;
            $leads->records[$k]->ratetype_id = $type_id;
        }
        if ($leads->totpages > 1) {
            PageContext::$response->total_rec = $leads->totalrecords;
        } else {
            PageContext::$response->total_rec = $count;
        }
        PageContext::addScript("jquery.rateit.js");
        PageContext::addScript("ratinglist.js");
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->slno = 1;
        PageContext::$response->leads = $leads->records;
        PageContext::$response->totalrecords = ($leads->totalrecords == '') ? 0 : $leads->totalrecords;
        PageContext::$response->pagination = Pagination::paginate($page, $itemperpage, $leads->totalrecords, $targetpage);

    }

    public function group_listajax($pagenum, $groupby = '')
    {
        $user_id = PageContext::$response->sess_user_id;

        if (PageContext::$response->sess_user_id > 0) {
            PageContext::registerPostAction("menu", "home_menu", "index", "default");
        } else {
            PageContext::registerPostAction("menu", "menu", "index", "default");
        }
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "community_list", "user", "default");
        PageContext::$body_class = 'business_profile';
        PageContext::$response->activeSubMenu = 'community';
        $orderfield = PageContext::$request['sort'];
        $orderby = PageContext::$request['sortby'];
        $page = PageContext::$request['page'];
        $search = addslashes(PageContext::$request['searchtext']);
        $searchtype = PageContext::$request['searchtype'];

        if ($orderby == '')
            $orderby = ' DESC';
        if ($orderfield == '')
            $orderfield = 'community_id';

        // code to get the arrow for the sort order
        PageContext::$response->community_name_sortorder = Utils::sortarrow();

        PageContext::$response->{$orderfield . '_sortorder'} = Utils::getsortorder($orderby);

        PageContext::$response->searchtext = $search;
        PageContext::$response->searchtype = $searchtype;
        PageContext::$response->page = $page;
        // search field section
        PageContext::$response->search = array('fields' => array(), 'action' => PageContext::$response->baseUrl . 'groups');

        switch ($searchtype) {
            case 'all':
                $searchtypeArray = array('community_name');
                break;
            case 'name':
                $searchtypeArray = array();
                break;
            case 'email':
                $searchtypeArray = array();
                break;
            case 'phone':
                $searchtypeArray = array();
                break;
        }
        PageContext::$response->messagebox = Messages::getPageMessage();

        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';

        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
        PageContext::$response->cat_id = $groupby;
        $itemperpage = 10;
        PageContext::$response->itemperpage = $itemperpage;
        $targetpage = BASE_URL . 'community?searchtext=' . $search . '&searchtype=' . $searchtype . '&sort=' . $orderfield . '&sortby=' . $orderby;
        $leads = Communities::getCommunities($orderfield, $orderby, $pagenum, 10, $search, $searchtypeArray, $user_id, '', $groupby);
        PageContext::addStyle("rateit.css");
        $count = 0;
        foreach ($leads->records as $k => $com) {
            $type = 'C';
            $type_id = $com->community_id;
            $user_id = PageContext::$response->sess_user_id;
            if ($user_id == '') {
                $user_id = 0;
            }
            $value = 0;
            $flag = 0;
            $rate = Ratings::getRatings($type_id, $type);
            if ($rate->data->count != 0) {
                $value = $rate->data->total / $rate->data->count;
            }
            if ($user_id <= 0) {
                $flag = 1;
            } else {
                $rate1 = Ratings::checkIfRated($type_id, $type, $user_id);
                if ($rate1->data->rating_id > 0 || $rate1->data->rating_id != '') {
                    $flag = 1;
                }
            }
            $count++;
            $leads->records[$k]->ratetype = $type;
            $leads->records[$k]->ratevalue = $value;
            $leads->records[$k]->rateuser_id = $user_id;
            $leads->records[$k]->rateflag = $flag;
            $leads->records[$k]->ratetype_id = $type_id;
        }
        if ($leads->totpages > 1) {
            PageContext::$response->total_rec = $leads->totalrecords;
        } else {
            PageContext::$response->total_rec = $count;
        }
        PageContext::addScript("jquery.rateit.js");
        PageContext::addScript("ratinglist.js");
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->slno = 1;
        PageContext::$response->leads = $leads->records;
        PageContext::$response->totalrecords = ($leads->totalrecords == '') ? 0 : $leads->totalrecords;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();

    }

    public function my_groups()
    {
        if ($_GET['groupby'] != '') {
            $groupby = $_GET['groupby'];
        } else {
            $groupby = '';
        }
        Utils::checkUserLoginStatus();
        if (PageContext::$response->sess_user_status == 'I') {
            $this->redirect("inactiveuser");
        }
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "my_groups", "user", "default");
        PageContext::addStyle("rateit.css");
        PageContext::addScript("jquery.colorbox.js");
        PageContext::addScript("comment_popup.js");
        PageContext::addScript("organisation.js");
         PageContext::addScript("community.js");
        PageContext::$body_class = 'business_profile';
        PageContext::$response->activeSubMenu = 'community';
        $category = Cmshelper::getAllCategoryName();
        if ($category) {
            $category_dropdown['--All Category--'] = '';
            foreach ($category as $key => $val) {
                $category_dropdown[$val->text] = $val->value;
            }
        }
        PageContext::$response->categories = $category_dropdown;
        $orderfield = PageContext::$request['sort'];
        $orderby = PageContext::$request['sortby'];
        $page = PageContext::$request['page'];
        $search = addslashes(PageContext::$request['searchtext']);
        $searchtype = PageContext::$request['searchtype'];
        PageContext::$response->searchtext = $search;
        PageContext::$response->searchtype = $searchtype;
        PageContext::$response->orderfield = $orderfield;
        PageContext::$response->orderby = $orderby;
        PageContext::$response->org_grp = ORG_GRP;
        if ($orderby == '')
            $orderby = ' DESC';
        if ($orderfield == '')
            $orderfield = 'community_id';
        // code to get the arrow for the sort order
        PageContext::$response->community_name_sortorder = Utils::sortarrow();
        PageContext::$response->{$orderfield . '_sortorder'} = Utils::getsortorder($orderby);

        // search field section
        PageContext::$response->search = array('fields' => array(), 'action' => PageContext::$response->baseUrl . 'my-groups');
        switch ($searchtype) {
            case 'all':
                $searchtypeArray = array('community_name');
                break;
            case 'name':
                $searchtypeArray = array();
                break;
            case 'email':
                $searchtypeArray = array();
                break;
            case 'phone':
                $searchtypeArray = array();
                break;
        }
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';
        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
        PageContext::$response->cat_id = $groupby;
        $itemperpage = 8;
        PageContext::$response->itemperpage = $itemperpage;
        $targetpage = BASE_URL . 'my-groups?searchtext=' . $search . '&searchtype=' . $searchtype . '&sort=' . $orderfield . '&sortby=' . $orderby;
        $leads = Communities::getAllCommunity($orderfield, $orderby, 1, $itemperpage, $search, $searchtypeArray, Utils::getAuth('user_id'), 'A', $groupby);
        $total_pages = (sizeof($leads->records) / 8);
        PageContext::addJsVar('TOT_PAGE', $total_pages);
        foreach ($leads->records as $k => $com) {
            $com->community_name = stripslashes($com->community_name);
            $com->community_description = stripslashes($com->community_description);
            $type = 'C';
            $type_id = $com->community_id;
            $user_id = PageContext::$response->sess_user_id;
            if ($user_id == '') {
                $user_id = 0;
            }
            $value = 0;
            $flag = 0;
            $rate = Ratings::getRatings($type_id, $type);
            if ($rate->data->count != 0) {
                $value = $rate->data->total / $rate->data->count;
            }
            if ($user_id <= 0) {
                $flag = 1;
            } else {

                if ($user_id == $com->community_created_by) {
                    $flag = 2;
                } else {
                    $rate1 = Ratings::checkIfRated($type_id, $type, $user_id);
                    if ($rate1->data->rating_id > 0 || $rate1->data->rating_id != '') {
                        $flag = 1;
                    }
                }
            }
            $leads->records[$k]->ratetype = $type;
            $leads->records[$k]->ratevalue = $value;
            $leads->records[$k]->rateuser_id = $user_id;
            $leads->records[$k]->rateflag = $flag;
            $leads->records[$k]->ratetype_id = $type_id;
        }


        PageContext::addScript("jquery.rateit.js");
        PageContext::addScript("ratinglist.js");
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->slno = 1;
        PageContext::$response->leads = $leads->records;
        PageContext::$response->totalrecords = ($leads->totalrecords == '') ? 0 : $leads->totalrecords;

    }

    public function my_groupsajax($pagenum = 1, $sort = '', $sortby = '', $searchtext = '', $searchtype = '')
    {
        if (PageContext::$response->sess_user_status == 'I') {
            $this->redirect("inactiveuser");
        }
        
        PageContext::addStyle("rateit.css");
        PageContext::addScript("jquery.colorbox.js");
        PageContext::addScript("comment_popup.js");
        PageContext::addScript("organisation.js");
        PageContext::addScript("jquery.rateit.js");
        PageContext::addScript("ratinglist.js");
        PageContext::$body_class = 'business_profile';
        PageContext::$response->activeSubMenu = 'community';
        PageContext::$response->org_grp = ORG_GRP;
        $orderfield = $sort;
        $orderby = $sortby;
        $page = $pagenum;
        $search = addslashes($searchtext);
        $searchtype = $searchtype;

        if ($orderby == '')
            $orderby = ' DESC';
        if ($orderfield == '')
            $orderfield = 'community_id';
        // code to get the arrow for the sort order
        PageContext::$response->community_name_sortorder = Utils::sortarrow();
        PageContext::$response->{$orderfield . '_sortorder'} = Utils::getsortorder($orderby);
        PageContext::$response->searchtext = $search;
        PageContext::$response->searchtype = $searchtype;
        PageContext::$response->page = $page;
        // search field section
        PageContext::$response->search = array('fields' => array(), 'action' => PageContext::$response->baseUrl . 'my-groups');
        switch ($searchtype) {
            case 'all':
                $searchtypeArray = array('community_name');
                break;
            case 'name':
                $searchtypeArray = array();
                break;
            case 'email':
                $searchtypeArray = array();
                break;
            case 'phone':
                $searchtypeArray = array();
                break;
        }
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';
        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
        $itemperpage = 8;
        PageContext::$response->itemperpage = $itemperpage;
        $leads = Communities::getAllCommunity($orderfield, $orderby, $pagenum, $itemperpage, $search, $searchtypeArray, Utils::getAuth('user_id'), 'A', $groupby);
        //echopre1($leads);
        foreach ($leads->records as $k => $com) {
            $com->community_name = stripslashes($com->community_name);
            $com->community_description = stripslashes($com->community_description);
            $type = 'C';
            $type_id = $com->community_id;
            $user_id = PageContext::$response->sess_user_id;
            if ($user_id == '') {
                $user_id = 0;
            }
            $value = 0;
            $flag = 0;
            $rate = Ratings::getRatings($type_id, $type);
            if ($rate->data->count != 0) {
                $value = $rate->data->total / $rate->data->count;
            }
            if ($user_id <= 0) {
                $flag = 1;
            } else {
                $rate1 = Ratings::checkIfRated($type_id, $type, $user_id);
                if ($rate1->data->rating_id > 0 || $rate1->data->rating_id != '') {
                    $flag = 1;
                }
            }
            $leads->records[$k]->ratetype = $type;
            $leads->records[$k]->ratevalue = $value;
            $leads->records[$k]->rateuser_id = $user_id;
            $leads->records[$k]->rateflag = $flag;
            $leads->records[$k]->ratetype_id = $type_id;
        }
        PageContext::$response->leads = $leads->records;
        PageContext::$response->totalrecords = ($leads->totalrecords == '') ? 0 : $leads->totalrecords;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function my_subscribed_group()
    {
        if ($_GET['groupby'] != '') {
            $groupby = $_GET['groupby'];
        } else {
            $groupby = '';
        }
        if ($_GET['groupbystatus'] != '') {
            $groupbystatus = $_GET['groupbystatus'];
        } else {
            $groupbystatus = '';
        }
        $status = array();
        Utils::checkUserLoginStatus();
        if (PageContext::$response->sess_user_status == 'I') {
            $this->redirect("inactiveuser");
        }
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "my_subscribed_community", "user", "default");
        PageContext::addStyle("rateit.css");
        PageContext::addScript("organisation.js");
        PageContext::addScript("community.js");
        PageContext::$body_class = 'business_profile';
        PageContext::$response->activeSubMenu = 'community';
        $category = Cmshelper::getAllCategoryName();
        if ($category) {
            $category_dropdown['--All Category--'] = '';
            foreach ($category as $key => $val) {
                $category_dropdown[$val->text] = $val->value;
            }
        }
        PageContext::$response->categories = $category_dropdown;
        $orderfield = PageContext::$request['sort'];
        $orderby = PageContext::$request['sortby'];
        $page = PageContext::$request['page'];
        $search = addslashes(PageContext::$request['searchtext']);
        $searchtype = PageContext::$request['searchtype'];
        if ($orderby == '')
            $orderby = ' DESC';
        if ($orderfield == '')
            $orderfield = 'community_id';
        // code to get the arrow for the sort order
        PageContext::$response->community_name_sortorder = Utils::sortarrow();
        PageContext::$response->{$orderfield . '_sortorder'} = Utils::getsortorder($orderby);
        PageContext::$response->searchtext = $search;
        PageContext::$response->searchtype = $searchtype;
        PageContext::$response->page = $page;
        PageContext::$response->cat_id = $groupby;
        PageContext::$response->active_status = $groupbystatus;
        // search field section
        PageContext::$response->search = array('fields' => array(), 'action' => PageContext::$response->baseUrl . 'my-subscribed-group');

        switch ($searchtype) {
            case 'all':
                $searchtypeArray = array('community_name');
                break;
            case 'name':
                $searchtypeArray = array();
                break;
            case 'email':
                $searchtypeArray = array();
                break;
            case 'phone':
                $searchtypeArray = array();
                break;
        }
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';
        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
        $itemperpage = 12;
        PageContext::$response->itemperpage = $itemperpage;
        $targetpage = BASE_URL . 'my-subscribed-group?searchtext=' . $search . '&searchtype=' . $searchtype . '&sort=' . $orderfield . '&sortby=' . $orderby . '&groupbystatus=' . $groupbystatus . '&groupby=' . $groupby;
        $leads = Communities::getAllCommunity($orderfield, $orderby, $page, $itemperpage, $search, $searchtypeArray, Utils::getAuth('user_id'), 'U', $groupby, $groupbystatus);
        $total_pages = (($leads->totalrecords) / LAZYLOAD_COUNT);
        PageContext::addJsVar('TOTAL_PAGE', $total_pages);
        foreach ($leads->records as $k => $com) {
            $type = 'C';
            $type_id = $com->community_id;
            $user_id = PageContext::$response->sess_user_id;
            if ($user_id == '') {
                $user_id = 0;
            }
            $value = 0;
            $flag = 0;
            $rate = Ratings::getRatings($type_id, $type);
            if ($rate->data->count != 0) {
                $value = $rate->data->total / $rate->data->count;
            }
            if ($user_id <= 0) {
                $flag = 1;
            } else {
                $rate1 = Ratings::checkIfRated($type_id, $type, $user_id);
                if ($rate1->data->rating_id > 0 || $rate1->data->rating_id != '') {
                    $flag = 1;
                }
            }
            $leads->records[$k]->ratetype = $type;
            $leads->records[$k]->ratevalue = $value;
            $leads->records[$k]->rateuser_id = $user_id;
            $leads->records[$k]->rateflag = $flag;
            $leads->records[$k]->ratetype_id = $type_id;
        }
        PageContext::addScript("jquery.rateit.js");
        PageContext::addScript("ratinglist.js");
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->slno = 1;
        PageContext::$response->leads = $leads->records;
        PageContext::$response->totalrecords = ($leads->totalrecords == '') ? 0 : $leads->totalrecords;
        PageContext::$response->pagination = Pagination::paginate($page, $itemperpage, $leads->totalrecords, $targetpage);

    }

    public function my_subscribed_groupajax($pagenum = 1)
    {
        Utils::checkUserLoginStatus();
        if (PageContext::$response->sess_user_status == 'I') {
            $this->redirect("inactiveuser");
        }
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "my_subscribed_community", "user", "default");
        PageContext::addStyle("rateit.css");
        PageContext::$body_class = 'business_profile';
        PageContext::$response->activeSubMenu = 'community';
        $orderfield = PageContext::$request['sort'];
        $orderby = PageContext::$request['sortby'];
        $page = PageContext::$request['page'];
        $search = addslashes(PageContext::$request['searchtext']);
        $searchtype = PageContext::$request['searchtype'];
        if ($orderby == '')
            $orderby = ' DESC';
        if ($orderfield == '')
            $orderfield = 'community_id';
        // code to get the arrow for the sort order
        PageContext::$response->community_name_sortorder = Utils::sortarrow();
        PageContext::$response->{$orderfield . '_sortorder'} = Utils::getsortorder($orderby);
        PageContext::$response->searchtext = $search;
        PageContext::$response->searchtype = $searchtype;
        PageContext::$response->page = $page;
        // search field section
        PageContext::$response->search = array('fields' => array(), 'action' => PageContext::$response->baseUrl . 'my-subscribed-group');
        switch ($searchtype) {
            case 'all':
                $searchtypeArray = array('community_name');
                break;
            case 'name':
                $searchtypeArray = array();
                break;
            case 'email':
                $searchtypeArray = array();
                break;
            case 'phone':
                $searchtypeArray = array();
                break;
        }
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';
        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
        $itemperpage = 12;
        PageContext::$response->itemperpage = $itemperpage;
        $targetpage = BASE_URL . 'my-subscribed-group?searchtext=' . $search . '&searchtype=' . $searchtype . '&sort=' . $orderfield . '&sortby=' . $orderby;
        $leads = Communities::getAllCommunity($orderfield, $orderby, $pagenum, 6, $search, $searchtypeArray, Utils::getAuth('user_id'), 'U');
        foreach ($leads->records as $k => $com) {
            $type = 'C';
            $type_id = $com->community_id;
            $user_id = PageContext::$response->sess_user_id;
            if ($user_id == '') {
                $user_id = 0;
            }
            $value = 0;
            $flag = 0;
            $rate = Ratings::getRatings($type_id, $type);
            if ($rate->data->count != 0) {
                $value = $rate->data->total / $rate->data->count;
            }
            if ($user_id <= 0) {
                $flag = 1;
            } else {
                $rate1 = Ratings::checkIfRated($type_id, $type, $user_id);
                if ($rate1->data->rating_id > 0 || $rate1->data->rating_id != '') {
                    $flag = 1;
                }
            }
            $leads->records[$k]->ratetype = $type;
            $leads->records[$k]->ratevalue = $value;
            $leads->records[$k]->rateuser_id = $user_id;
            $leads->records[$k]->rateflag = $flag;
            $leads->records[$k]->ratetype_id = $type_id;
        }
        PageContext::addScript("jquery.rateit.js");
        PageContext::addScript("ratinglist.js");
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->slno = 1;
        PageContext::$response->leads = $leads->records;
        PageContext::$response->totalrecords = ($leads->totalrecords == '') ? 0 : $leads->totalrecords;
        PageContext::$response->pagination = Pagination::paginate($page, $itemperpage, $leads->totalrecords, $targetpage);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    /**
     *  Generate view for group from community template
     * 
     * @param string $alias
     * 
     */
    public function group($alias = '')
    {
        PageContext::registerPostAction("importcontacts", "importcontacts", "index", "default");
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "community", "user", "default");
        PageContext::addScript('community_tab.js');
        PageContext::addScript('community.js');
        PageContext::$response->sess_user_id = Utils::getAuth('user_id');
        $img = PageContext::$response->userImagePath;
        $default = PageContext::$response->defaultImage;
        PageContext::$body_class = 'member_area';
        PageContext::$response->activeSubMenu = 'community';
        PageContext::$response->invitation_type = 'community';
        PageContext::$response->messagebox = Messages::getPageMessage();
        $communityData = Communities::getCommunityId($alias);
       // echopre1($communityData);
        $innerlogo = PageContext::$response->innerlogo;
        PageContext::$response = new stdClass();
        PageContext::$response->userImagePath = $img;
        PageContext::$response->defaultImage = $default;
        PageContext::$response->innerlogo= $innerlogo;
        PageContext::$response->org_grp = ORG_GRP;
        //--------------Announcements------------------------------------------
        if($communityData->data->community_id){
            PageContext::$response->communityAnnouncements = Communities::getAnnouncements($communityData->data->community_id);
            //-------------------------------------------------------
            $result = Communities::getCommunityAlias($communityData->data->community_id);

            $results = Communities::getCommunityActivestatus($communityData->data->community_id);
        }
        if (PageContext::$response->sess_user_id != '') {
            if($communityData->data->community_id){
                $communitySuggestions = Communities::getCommunitySuggestions($result->data->community_business_id, $communityData->data->community_id);
            }
            if ($result->data->community_business_id > 0) {
                PageContext::$response->communitySuggestions = $communitySuggestions->data;
            }
        }
        if($result->data->community_id){
            $checkMember = Communities::chekMemeber(Utils::getAuth('user_id'), $result->data->community_id);
        }
        PageContext::$response->communitySuggestions1 = $checkMember->data->cmember_list_id;
        PageContext::$metaTitle = META_TITLE;// = SITE_NAME;
        PageContext::$metaDes = META_DES;// = SITE_NAME;
        PageContext::$metaKey = META_KEYWORDS;//= SITE_NAME;

        $members = Communities::getCommunityMembers($alias, 'A', 10);
      //  echopre1($members);
        PageContext::$response->memberstatus = 0;
        if ($members->status == "SUCCESS") {
            foreach ($members->data as $key => $val) {
                if ($_SESSION['default_user_id'] == ($members->data[$key]->user_id)) {
                    PageContext::$response->memberstatus = 1;
                    break;
                }
            }
        }

        $pendingMembers = Communities::getCommunityMembers($alias, 'I', 4);
        $pendingBizcomMembers = array();
        PageContext::$response->pendingmemberStatus = 0;
        $loggedUserId = Utils::getAuth('user_id');

        foreach ($pendingMembers->data AS $pendingdata) {
            $pendingBizcomMembers[] = $pendingdata->user_id;
        }

        if (in_array($loggedUserId, $pendingBizcomMembers)) {
            PageContext::$response->pendingmemberStatus = 1;
        }

        PageContext::$response->invitation_typeid = $result->data->community_id;
        PageContext::addStyle("rateit.css");
        PageContext::$response->rate_entity = 'C';
        PageContext::$response->rate_entity_alias = $alias;

        $type = 'C';
        $type_alias = $alias;
        $resultRating = Communities::getCommunityId($type_alias);
       // echopre1($resultRating);
        $type_id = $resultRating->data->community_id;
        $user_id = PageContext::$response->sess_user_id;
        $value = 0;
        $flag = 0;
        $rate = Ratings::getRatings($type_id, $type);

        if ($rate->data->count != 0) {
            $value = $rate->data->total / $rate->data->count;
        }

        if ($user_id <= 0) {
            $flag = 1;
        } else {
            if ($user_id == $result->data->community_created_by) {//owner
                $flag = 2;
            } else if ($checkMember->data->cmember_list_id < 0 || $checkMember->status == 'ERROR') {//member
                $flag = 3;
            } else {
                $rate1 = Ratings::checkIfRated($type_id, $type, $user_id);
                if ($rate1->data->rating_id > 0 || $rate1->data->rating_id != '') {
                    $flag = 1;
                }
            }
        }

        PageContext::addJsVar('RATEVALUE', $value);
        PageContext::addJsVar('RATEFLAG', $flag);
        PageContext::addJsVar('RATETYPE_ID', $type_id);
        PageContext::addJsVar('RATETYPE', $type);
        PageContext::addJsVar('RATE_USERID', $user_id);
        PageContext::addScript("jquery.rateit.js");
        PageContext::addScript("rating.js");
        PageContext::registerPostAction("rating", "rate", "index", "default");
        // end rating part

        if (Utils::getAuth('user_id')) {
            if($result->data->community_id){
                $checkMember = Communities::chekMemeber(Utils::getAuth('user_id'), $result->data->community_id);
            }
            PageContext::$response->checkmembers = $checkMember->data;
            PageContext::$response->members = $members->data;
            PageContext::$response->memberCount = $members->memberCount;
            PageContext::$response->pendingMembers = $pendingMembers->data;
            PageContext::$response->pendingCount = $pendingMembers->memberCount;
            $invitescount = Communities::getCommunityInvitationCount($type_alias);
            //echopre1($invitescount);
            PageContext::$response->invitationCount = sizeof($invitescount);
            if($result->data->community_id){
            $announcementCount = Communities::getAnnouncementsCount($result->data->community_id);
            }
            PageContext::$response->announcementCount_all = sizeof($announcementCount);
            $announcementCount = Communities::getAnnouncementCountByUser();
            PageContext::$response->announcementCount = $announcementCount[0]->cmember_announcement_count;
            $total_pages = (sizeof($invitescount) / LAZYLOAD_COUNT);
            PageContext::addJsVar('TOTAL_PAGESS', $total_pages);
            $orderfield = PageContext::$request['sort'];
            $orderby = PageContext::$request['sortby'];
            $page = PageContext::$request['page'];
            $search = addslashes(PageContext::$request['searchtext']);
            $searchtype = 'all';
        }

        if ($orderby == ''){
            $orderby = ' DESC';
        }

        if ($orderfield == ''){
            $orderfield = 'comment_id';
        }

        // code to get the arrow for the sort order
        PageContext::$response->business_name_sortorder = Utils::sortarrow();
        PageContext::$response->{$orderfield . '_sortorder'} = Utils::getsortorder($orderby);
        PageContext::$response->searchtext = $search;
        PageContext::$response->searchtype = $searchtype;
        PageContext::$response->page = $page;

        // search field section
        switch ($searchtype) {
            case 'all':
                $searchtypeArray = array('comment_id', 'comment_content', 'business_type');
                break;
            case 'name':
                $searchtypeArray = array('business_name', 'user_email');
                break;
            case 'email':
                $searchtypeArray = array('user_email', 'business_email');
                break;
            case 'phone':
                $searchtypeArray = array('business_phone');
                break;
        }
        PageContext::$response->order = ($orderby == 'ASC') ? 'DESC' : 'ASC';
        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
        $itemperpage = PAGE_LIST_COUNT;
        PageContext::$response->itemperpage = $itemperpage;
        $targetpage = BASE_URL . "community/$alias?searchtext=" . $search . '&searchtype=' . $searchtype . '&sort=' . $orderfield . '&sortby=' . $orderby;
        PageContext::$response->pendingBizcomrequests = '';
        $bizcomInvite = Connections::getPendingBizComrequest(Utils::getAuth('user_id'));

        foreach ($bizcomInvite->data as $k => $inviteList) {
            if ($inviteList->community_alias == $alias) {
                PageContext::$response->pendingBizcomrequests = $inviteList;
            }
        }
        if($result->data->community_id){
            $comments = Comments::getAllComments($orderfield, $orderby, $page, $itemperpage, $search, $searchtypeArray, 'C', $result->data->community_id);
        }
//echopre1($comments);
        if ($page > 1){
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        } else {
            PageContext::$response->slno = 1;
            PageContext::$response->leads = $comments->records;
            PageContext::$response->totalrecords = $comments->totalrecords;
            PageContext::$response->pagination = Pagination::paginate($page, $itemperpage, $comments->totalrecords, $targetpage);
            PageContext::$response->comments = $comments->records;
        }

        if ($result->status == SUCCESS) {
            PageContext::$response->result = $result->data;
            PageContext::$response->community_image = PageContext::$response->result->file_path;
        } else {
            Messages::setPageMessage($result->message, ERROR_CLASS);
          //  $this->redirect('community');
        }
        PageContext::$response->results = $results->data;

        //--------------------------------------
        if ($communityData->status == SUCCESS) {
            PageContext::$response->communityData = $communityData->data;
        } else {
            Messages::setPageMessage($communityData->message, ERROR_CLASS);
          //  $this->redirect('community');
        }
        //--------------------------------------

        PageContext::addJsVar('ALIAS', $alias);
        PageContext::addJsVar('LAZYCOUNT', LAZYLOAD_COUNT);
        PageContext::addJsVar('TOTAL_PAGES', $members->memberCount / LAZYLOAD_COUNT);
        PageContext::addScript('communitymember_lazyload.js');
        PageContext::$response->tojoin = '';
        PageContext::$response->sess_user_id = Utils::getAuth('user_id');
      //  exit;
        if (PageContext::$response->sess_user_id > 0) {
            $share_array = array();
            $feed_array = array();
            $search = $_GET['search'];
            PageContext::$response->search = $search;
            //-------------Share------------------------
            if ($search == '' OR $search == 'S') {
                $shares = Feed::getFriendShares();
                foreach ($shares->records AS $share_item) {
                    $share_array[strtotime($share_item->share_date)][] = (array)$share_item;
                }
            }
            //----------------------Announcemnet -----------
            if ($search == '' OR $search == 'A' OR $search == 'S') {
                if ($search != 'S') {
                    $feeds = Feed::listUserFeeds('', $searchfeed = '', 1, 10);
                }
                PageContext::addJsVar('TOTAL_FEED_PAGES', $feeds->totpages);
                foreach ($feeds->records AS $feed_item) {
                    $feed_array[strtotime($feed_item->community_announcement_date)][] = (array)$feed_item;
                }
                //----------News feed (Share+announcement)-------------
                $news_array = $share_array + $feed_array;
                krsort($news_array);
                PageContext::$response->feeds = $news_array;
                //--------------------Feed Comments----------------
                foreach ($news_array AS $newsItems) {
                    foreach ($newsItems AS $news) {
       // exit;
                        if ($news['community_announcement_id']) {
                            $comments = Feed::getAnnouncementComments($news['community_announcement_id']);
                        }
                        PageContext::$response->Comments[$news['community_announcement_id']] = $comments->records;
                        PageContext::$response->Page[$news['community_announcement_id']]['totpages'] = $comments->totpages;
                        PageContext::$response->Page[$news['community_announcement_id']]['currentpage'] = $comments->currentpage;
                    }
                }
            }
        }
        if($result->data->community_id){
            PageContext::$response->gallery_display_list = Communities::getMyLatestDiscussionImage($result->data->community_id);
            PageContext::$response->friend_display_list = Communities::getCommunityMembers($result->data->community_id, 'A', 3, $orderfield = 'community_id', $orderby = 'DESC','');
        }
        $messageCount = Messages::getMessageCountByUser();
        PageContext::$response->messageCount = $messageCount[0]->user_message_count;
        $frndcount = Feed::getNumPendingFriendRequestByUser();
        PageContext::$response->NumFriendRequest = $frndcount[0]->user_friend_request_count;
        $users = Feed::getNumPendingPrivateRequestByUser();
        
        PageContext::$response->NumPrivateRequest = $users[0]->user_private_request_count;
        PageContext::$response->ImagePath = IMAGE_MAIN_URL;
        PageContext::$response->userImagePath = USER_IMAGE_URL;
        PageContext::$response->baseUrl = BASE_URL;
        PageContext::$response->sitelogo = SITE_LOGO;
        PageContext::$response->sess_user_status = Utils::getAuth('user_status');
        PageContext::$response->sess_user_name = Utils::getAuth('user_firstname') . ' ' . Utils::getAuth('user_lastname');
        PageContext::$response->sess_user_alias = Utils::getAuth('user_alias');
        PageContext::$response->sess_user_email = Utils::getAuth('user_email');
        PageContext::$response->sess_user_fname = Utils::getAuth('user_firstname');
        PageContext::$response->sess_user_fname = Utils::getAuth('user_lastname');
       // PageContext::$response->sess_user_image = Utils::getAuth('user_image_name');
        PageContext::$response->sess_user_id = Utils::getAuth('user_id');
        PageContext::$response->userImagePath = USER_IMAGE_URL;
         $userDetails = User::getUserDetail(PageContext::$response->sess_user_id);
        // echopre1($userDetails);
        if($userDetails->data->Id == ''){
            PageContext::$response->sess_user_image = '';
          //  PageContext::$response->sess_user_name = '';
        }else{
             PageContext::$response->sess_user_image = $userDetails->data->user_image_name;
        }
    }

    public function inbox()
    {
        PageContext::addScript(BASE_URL . 'project/lib/ckeditor/ckeditor.js');
        Utils::checkUserLoginStatus();
        if (PageContext::$response->sess_user_status == 'I') {
            $this->redirect("inactiveuser");
        }
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$body_class = 'business_profile';

        $page = PageContext::$request['page'];
        $itemperpage = PAGE_LIST_COUNT;
        if ($orderby == '')
            $orderby = ' DESC';
        if ($orderfield == '')
            $orderfield = 'message_id';

        PageContext::$response->page = $page;
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';
        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
        $targetpage = BASE_URL . 'inbox?order=' . orderby;
        $message_details = Connections::getAllMessages($orderfield, $orderby, $page, LAZYLOAD_COUNT);
        $message_count_array = Messages::getMessageCountByUser();
        $message_count = $message_count_array[0]->user_message_count;
        $inv_count_array = Connections::getAllPendingRequestinboxcount();
        $inv_count = sizeof($inv_count_array->records);
        $total_pages = $inv_count / LAZYLOAD_COUNT;
        PageContext::addJsVar('TOTAL_PAGESS', $total_pages);
        PageContext::$response->message_details = $message_details;
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->totalrecords = $users->totalrecords;
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "inbox", "user", "default");
        PageContext::addScript('community_tab.js');
        PageContext::addScript('community.js');
        PageContext::addScript('communitymember_lazyload.js');
        PageContext::addScript('inbox_lazyload.js');
        PageContext::$body_class = 'member_area';
        PageContext::$response->activeSubMenu = 'messages';
        PageContext::$response->invitation_type = 'community';
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$metaTitle = META_TITLE;// = SITE_NAME . " : Your personalised social network";
        $total_pages = $message_count / LAZYLOAD_COUNT;
        PageContext::addJsVar('LAZYCOUNT', LAZYLOAD_COUNT);
        PageContext::addJsVar('TOTAL_PAGES', $total_pages);
        PageContext::$response->tojoin = '';
        PageContext::$response->message_details = $message_details;
        PageContext::$response->itemperpage = $itemperpage;
        PageContext::$response->totalrecords = ($message_details->totalrecords == '') ? 0 : $message_details->totalrecords;
        PageContext::$response->pagination = Pagination::paginate($page, $itemperpage, $message_details->totalrecords, $targetpage);

    }

    public function sendfriendrequest()
    {
        $objMailer = new Mailer();
        $friend_id = $_POST['fid'];
        $objUserVo = new stdClass();
        $objUserVo->invitation_type = 'U';
        $objUserVo->invitation_entity = 'U';
        $objUserVo->invitation_entity_id = PageContext::$response->sess_user_id;
        $objUserVo->invitation_sender_email = PageContext::$response->sess_user_email;
        $objUserVo->invitation_sender_id = PageContext::$response->sess_user_id;
        $objUserVo->invitation_receiver_email = '';
        $objUserVo->invitation_receiver_id = $friend_id;
        $objUserVo->invitation_status = 'P';
        $objUserVo->mail_template = 'friend_request';
        $objUserRes = Connections::addInvitation($objUserVo);
        //------------Friend request recieved feed--------------------
        $feeddata = array();
        $invitation = Utils::setTablePrefix('invitation');
        $feeddata = array('feed_type' => 'FRR',
            'feed_user_id' => $friend_id,
            'from_user_id' => PageContext::$response->sess_user_id,
            'to_user_id' => $friend_id,
            'table_name' => $invitation,
            'table_key_id' => $objUserRes->invitation_id);
        Utils::setUserfeed($feeddata);
        //--------------Friend request sent feed--------------------------
        $feeddata = array();
        $feeddata = array('feed_type' => 'FRS',
            'feed_user_id' => PageContext::$response->sess_user_id,
            'from_user_id' => PageContext::$response->sess_user_id,
            'to_user_id' => $friend_id,
            'table_name' => $invitation,
            'table_key_id' => $objUserRes->invitation_id);
        Utils::setUserfeed($feeddata);
        // echopre($objUserRes);
        if ($objUserRes->status == SUCCESS) {//====================
            $data['cls'] = "success";
            $getUserData = User::getUserDetail($objUserRes->data->invitation_sender_id);
            $getUserData1 = User::getUserDetail($objUserRes->data->invitation_receiver_id);
            $mailIds = array();
            $replaceparams = array();
            $mailIds[$getUserData1->data->Email] =($getUserData1->data->user_firstname) ? $getUserData1->data->Name : $getUserData1->data->Email;
            $replaceparams['USER_NAME'] = ($getUserData1->data->Name) ? $getUserData1->data->Name : $getUserData1->data->Email;
            $replaceparams['NAME'] = $getUserData->data->Name;
            $replaceparams['INVITE_ID'] = $objUserRes->invitation_id;
            $replaceparams['INVITE_TYPE'] = 'friend';
            // print_r($mailIds);
            $objMailer->sendMail($mailIds, 'friend_request', $replaceparams);
            echo json_encode($data);
            exit;
        } else {

            $data['msg'] = $objUserRes->message;
            $data['cls'] = "error_div";
            echo json_encode($data);
            exit;
        }
    }

    public function pendingrequests()
    {
        Utils::checkUserLoginStatus();
        if (PageContext::$response->sess_user_status == 'I') {
            $this->redirect("inactiveuser");
        }
        PageContext::$response->activeSubMenu = 'friends';
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "pendingrequests", "user", "default");
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$body_class = 'business_profile';
        $page = PageContext::$request['page'];
        $search = addslashes(PageContext::$request['searchtext']);
        $itemperpage = PAGE_LIST_COUNT;
        if ($orderby == '')
            $orderby = ' ASC';
        if ($orderfield == '')
            $orderfield = 'user_firstname';
        PageContext::$response->page = $page;
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';
        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
        PageContext::$response->searchtext = $search;
        $targetpage = BASE_URL . 'pending-request?order=' . orderby;
        $users = Connections::getAllPendingRequest($orderfield, $orderby, $page, $itemperpage, $search);
        PageContext::$response->usersList = $users->records;
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->totalrecords = $users->totalrecords;
        PageContext::addJsVar('TOTAL_PAGES', $users->totpages);
        PageContext::addScript('pendingrequest_lazyload.js');
    }

    public function pendingrequestajax($page)
    {

        if (!PageContext::$response->sess_user_id) {
            exit();
        }
        $itemperpage = PAGE_LIST_COUNT;
        if ($orderby == '')
            $orderby = ' ASC';
        if ($orderfield == '')
            $orderfield = 'user_firstname';

        PageContext::$response->page = $page;
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';

        $users = Connections::getAllPendingRequest($orderfield, $orderby, $page, $itemperpage);
        PageContext::$response->usersList = $users->records;
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->totalrecords = $users->totalrecords;

        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function pendingbizcomrequests()
    {
        Utils::checkUserLoginStatus();
        if (PageContext::$response->sess_user_status == 'I') {
            $this->redirect("inactiveuser");
        }
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "pendingbizcomrequests", "user", "default");
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$body_class = 'business_profile';
        PageContext::$response->activeSubMenu = 'community';

        $page = PageContext::$request['page'];
        $itemperpage = PAGE_LIST_COUNT;
        if ($orderby == '')
            $orderby = ' ASC';
        if ($orderfield == '')
            $orderfield = 'community_name';

        PageContext::$response->page = $page;
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';
        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];

        $targetpage = BASE_URL . 'pending-bizcom-request?order=' . orderby;

        $users = Connections::getAllBizcomPendingRequest($orderfield, $orderby, $page, $itemperpage);


        PageContext::$response->usersList = $users->records;
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->totalrecords = $users->totalrecords;
        PageContext::addJsVar('TOTAL_PAGES', $users->totpages);
        PageContext::addScript('pendingbizcom_lazyload.js');
    }

    public function pendingbizcomrequestajax($page)
    {

        if (!PageContext::$response->sess_user_id) {
            exit();
        }
        $itemperpage = PAGE_LIST_COUNT;
        if ($orderby == '')
            $orderby = ' ASC';
        if ($orderfield == '')
            $orderfield = 'community_name';

        PageContext::$response->page = $page;
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';

        $users = Connections::getAllBizcomPendingRequest($orderfield, $orderby, $page, $itemperpage);
        PageContext::$response->usersList = $users->records;
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->totalrecords = $users->totalrecords;

        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function unfriend()
    {
        $friend_id = $_POST['uid'];
        User::unfriend(PageContext::$response->sess_user_id, $friend_id);
    }

    public function getUserLoggedInSession($userid)
    {
        $objUser = User::getUserDetailId($userid);
        $objUserRes = User::adminLoginUser($objUser->data);
       // echopre1($objUserRes);
        if ($objUserRes->status == 'SUCCESS') {
            Utils::setSessions($objUserRes->data);
            $this->redirect('newsfeed/' . $objUserRes->data->user_alias);
        } else {
           session_start(); 
        session_unset(); 
        session_destroy();
            Messages::setPageMessage($objUserRes->message, 'error_div');
        $this->redirect("inactiveuser");
        }
    }

    public function acceptfriendrequest()
    {
        $friend_id = $_POST['fid'];
        $invite_id = $_POST['inviteid'];
        $inviteDetails = array('invitation_status' => 'A',
            'invitation_action_deffered' => '0');
        $inviteVo = Utils::arrayToObject($inviteDetails);
        $inviteRes = Connections::changeInvitationStatus($invite_id, $inviteVo);
        $friend = array('friends_list_user_id' => PageContext::$response->sess_user_id,
            'friends_list_friend_id' => $friend_id
        );
        $friendVo = Utils::arrayToObject($friend);
        $friendsRes = Connections::acceptFriendRequest($invite_id, $friendVo);
        User::updateUserFriendCount(PageContext::$response->sess_user_id);
        User::updateUserFriendCount($friend_id);
        if ($friendsRes->status == SUCCESS) {//====================
            $data['cls'] = "success";
            echo json_encode($data);
            exit;
        } else {
            $data['msg'] = $friendsRes->message;
            $data['cls'] = "error_div";
            echo json_encode($data);
            exit;
        }
    }   
    public function invitation_sent()
    {
        Utils::checkUserLoginStatus();
        if (PageContext::$response->sess_user_status == 'I') {
            $this->redirect("inactiveuser");
        }
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "invitation_sent", "user", "default");

        PageContext::$body_class = 'business_profile';
        PageContext::$response->activeSubMenu = 'messages';
        $user = Utils::getAuth("user_id");
        $orderfield = PageContext::$request['sort'];
        $orderby = PageContext::$request['sortby'];
        $page = PageContext::$request['page'];
        $search = addslashes(PageContext::$request['searchtext']);
        $searchtype = PageContext::$request['searchtype'];
        $filterstatus = addslashes(PageContext::$request['filterstatus']);
        $filtertype = PageContext::$request['filtertype'];
        if ($orderby == '')
            $orderby = 'DESC';
        if ($orderfield == '')
            $orderfield = 'invitation_id';

        // code to get the arrow for the sort order
        PageContext::$response->invitation_created_on_sortorder = Utils::sortarrow();
        PageContext::$response->user_firstname_sortorder = Utils::sortarrow();
        PageContext::$response->invitation_status_sortorder = Utils::sortarrow();
        PageContext::$response->invitation_receiver_email_sortorder = Utils::sortarrow();
        PageContext::$response->invitation_type_sortorder = Utils::sortarrow();
        PageContext::$response->{$orderfield . '_sortorder'} = Utils::getsortorder($orderby);
        PageContext::$response->filterstatus = $filterstatus;
        PageContext::$response->filtertype = $filtertype;
        PageContext::$response->searchtext = $search;
        PageContext::$response->searchtype = $searchtype;
        PageContext::$response->page = $page;
        // search field section
        PageContext::$response->search = array('fields' => array(), 'action' => PageContext::$response->baseUrl . 'invitation-sent');

        switch ($searchtype) {
            case 'all':
                $searchtypeArray = array('user_firstname', 'user_lastname');
                break;
            case 'name':
                $searchtypeArray = array('user_firstname', 'user_lastname');
                break;
            case 'email':
                $searchtypeArray = array('invitation_receiver_email', 'user_email');
                break;
        }
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';
        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
        $itemperpage = PAGE_LIST_COUNT;
        PageContext::$response->itemperpage = $itemperpage;
        $targetpage = BASE_URL . 'invitation-sent?searchtext=' . $search . '&searchtype=' . $searchtype . '&sort=' . $orderfield . '&sortby=' . $orderby . '&filterstatus=' . $filterstatus . '&filtertype=' . $filtertype;
        $leads = Connections::getInvitationReport($orderfield, $orderby, $page, $itemperpage, $search, $searchtypeArray, $user, $searchtype, $filterstatus, $filtertype);
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->slno = 1;
        PageContext::$response->leads = $leads->records;
        PageContext::$response->totalrecords = ($leads->totalrecords == '') ? 0 : $leads->totalrecords;
        PageContext::$response->pagination = Pagination::paginate($page, $itemperpage, $leads->totalrecords, $targetpage);

    }

    public function changepassword($alias = '')
    {
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "changepassword", "user", "default");
        PageContext::$body_class = 'business_profile';
        PageContext::addScript('validations_form.js');


        //Paypal validation
        if (PageContext::$request['btnSubmitCC'] == 'Save') {
            //echopre(PageContext::$request);
            if (is_valid_email(PageContext::$request['paypal_email'])) {
                User::updateUserPaypalEmail(PageContext::$response->sess_user_id, array('user_paypal_email' => PageContext::$request['paypal_email']));
                Messages::setPageMessage('Paypal email id saved successfully', 'success_div');
                PageContext::$response->ccmessage = Messages::getPageMessage();
            } else {
                Messages::setPageMessage('Invalid Email Id', 'error_div');
                PageContext::$response->ccmessage = Messages::getPageMessage();
            }
        }
        $userDetails = User::getUserDetailId(PageContext::$response->sess_user_id);
        PageContext::$response->paypalEmail = $userDetails->data->user_paypal_email;
        PageContext::$response->friendprivacy = $userDetails->data->user_friends_privacy;
        if (PageContext::$request['btnSubmit']) { //==========Post action==========


            $objUserVo = new stdClass();
            $objUserVo->user_id = PageContext::$response->sess_user_id;
            $objUserVo->newpassword = $_POST['user_newpassword'];
            $objUserVo->curpassword = $_POST['user_password'];
            $objUserRes = User::updatePassword($objUserVo);

            if ($objUserRes->status == SUCCESS) {//============User Registration mail========
                Messages::setPageMessage($objUserRes->message, 'success_div');
            } else { //========User insertion failed =======
                Messages::setPageMessage($objUserRes->message, 'error_div');
            }
            $_SESSION['default_user_reset_password'] = 'Y';

            PageContext::$response->message = Messages::getPageMessage();

        }
        if (PageContext::$request['btnSubmitfp'] == 'Save') {

            User::updateUserFriendPrivacy(PageContext::$response->sess_user_id, array('user_friends_privacy' => PageContext::$request['rad_frnd_privacy']));
            Messages::setPageMessage('Friends Privacy saved successfully', 'success_div');
            PageContext::$response->fpmessage = Messages::getPageMessage();
            PageContext::$response->friendprivacy = PageContext::$request['rad_frnd_privacy'];
        }

        $objSession = new LibSession();
        $values = $objSession->get('user_reset_password', 'default');
        if ($values == 'N') {
            PageContext::$response->message = array('msg' => 'Please change your password.', 'msgClass' => 'clserror');
        }

    }


    public function my_pending_bizcom_members()
    {
        Utils::checkUserLoginStatus();
        if (PageContext::$response->sess_user_status == 'I') {
            $this->redirect("inactiveuser");
        }
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "my_pending_bizcom_members", "user", "default");
        PageContext::$response->activeSubMenu = 'community';
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$body_class = 'business_profile';
        $page = PageContext::$request['page'];
        $search = addslashes(PageContext::$request['searchtext']);
        $itemperpage = PAGE_LIST_COUNT;
        if ($orderby == '')
            $orderby = ' ASC';
        if ($orderfield == '')
            $orderfield = 'community_name';
        PageContext::$response->page = $page;
        PageContext::$response->searchtext = $search;
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';
        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
        $targetpage = BASE_URL . 'pending-bizcom-members?order=' . orderby;
        $users = Communities::getMyCommunitiesPendingMembers($page, $itemperpage, $search);
        PageContext::$response->usersList = $users->records;
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->totalrecords = $users->totalrecords;
        PageContext::addJsVar('TOTAL_PAGES', $users->totpages);
        PageContext::addScript('pendingbizcom_lazyload.js');
    }


    public function my_pending_members()
    {
        Utils::checkUserLoginStatus();
        if (PageContext::$response->sess_user_status == 'I') {
            $this->redirect("inactiveuser");
        }
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "my_pending_members", "user", "default");
        PageContext::$response->activeSubMenu = 'community';
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$body_class = 'business_profile';
        $page = PageContext::$request['page'];
        $search = addslashes(PageContext::$request['searchtext']);
        $itemperpage = PAGE_LIST_COUNT;
        if ($orderby == '')
            $orderby = ' ASC';
        if ($orderfield == '')
            $orderfield = 'community_name';
        PageContext::$response->page = $page;
        PageContext::$response->searchtext = $search;
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';
        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
        $targetpage = BASE_URL . 'pending-privatebizcom-members?order=' . orderby;
        $users = Communities::getMyCommunitiesPendingMembersjoin($page, $itemperpage, $search);
        PageContext::$response->usersList = $users->records;
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->totalrecords = $users->totalrecords;
        PageContext::$response->itemperpage = $itemperpage;
        PageContext::addJsVar('TOTAL_PAGES', $users->totpages);
        PageContext::addScript('pendingbizcom_lazyload.js');
        PageContext::$response->pagination = Pagination::paginate($page, $itemperpage, $users->totalrecords, $targetpage);
    }

    public function bizcom_membership_request($userId, $communityId, $type, $ajaxCall = false)
    {
        $objMemvo = new stdClass();
        if ($type == 'accept') {
            $objMemvo->cmember_status = 'A';
            $objMemvo->cmember_id = $userId;
            $objMemvo->cmember_community_id = $communityId;
            $result = Communities::chanegeMemeberCommunityStatus($objMemvo);
            $result->message = COMMUNITY_REQ_ACCEPT;

        } else {
            $objMemvo->cmember_status = 'D';
            $objMemvo->cmember_id = $userId;
            $objMemvo->cmember_community_id = $communityId;
            $result = Communities::chanegeMemeberCommunityStatus($objMemvo);
            $result->message = COMMUNITY_REQ_DECLINE;
        }
        Messages::setPageMessage($result->message, 'success_div');
        if ($type == 'accept') {
            Connections::setJoineeAccountAmount($campaign_id, $userId);
        }
        Communities::updateCommunityCounts();
        if ($ajaxCall == false) {
            $this->redirect('pending-bizcom-members');
        } else {
            return 1;
        }

    }

    public function private_membership_request($userId, $communityId, $type, $ajaxCall = false)
    {
        $objMemvo = new stdClass();
        if ($type == 'accept') {
            $objMemvo->cmember_status = 'A';
            $objMemvo->cmember_id = $userId;
            $objMemvo->cmember_community_id = $communityId;
            $result = Communities::chanegeMemeberCommunityStatus($objMemvo);
            $result->message = COMMUNITY_REQ_ACCEPT;

        } else {
            $objMemvo->cmember_status = 'D';
            $objMemvo->cmember_id = $userId;
            $objMemvo->cmember_community_id = $communityId;
            $result = Communities::chanegeMemeberCommunityStatus($objMemvo);
            $result->message = COMMUNITY_REQ_DECLINE;
        }
        Messages::setPageMessage($result->message, 'success_div');
        if ($type == 'accept') {
           // Connections::setJoineeAccountAmount($campaign_id, $userId);
        }
        Communities::updateCommunityCounts();
        if ($ajaxCall == false) {
            $this->redirect('pending-members');
        } else {
            return 1;
        }

    }

    public function view_my_invitation($id)
    {
        PageContext::$body_class = 'business_profile';
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("leftcontent", "view_my_invitation", "user", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        $special_terms = Connections::getTermsPif();
        PageContext::$response->special_terms = $special_terms->content_description;
        $userDetails = User::getUserDetailId(PageContext::$response->sess_user_id);
        PageContext::$response->paypalEmail = $userDetails->data->user_paypal_email;
        $campaignDetails = Connections::getCampaignDetails($id);
        PageContext::$response->charity = $charityOrganisation->organization;
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$response->campaignDetails = $campaignDetails->data;
        if (PageContext::$response->campaignDetails->refferalcampaign_payment_mode == 'F') {
            $campaignType = 'a good friend';
        } else {
            switch (PageContext::$response->campaignDetails->refferalcampaign_paidrefferalmode) {
                case 1:
                    $campaignType = 'an incentivised';
                    break;
                case 2:
                    $campaignType = 'a charitable';
                    break;
                case 3:
                    $campaignType = 'a free voucher/product';
                    break;
            }
        }

        $userDetails = User::getUserDetail($campaignDetails->data->introduction_from_user_id);
        $bizcom = Communities::getCommunityName($campaignDetails->data->introduction_community_id);
        PageContext::$response->id = $id;
        PageContext::$response->userdetails = $userDetails->data;
        PageContext::$response->useralias = $userDetails->data->user_alias;
        PageContext::$response->campaignType = $campaignType;
        PageContext::$response->bizComOwner = $userDetails->data->Name;
        PageContext::$response->memberName = PageContext::$response->sess_user_name;
        PageContext::$response->bizcom = $bizcom->data->community_name;
    }


    public function changeJoineeStatus()
    {

        $campaign_id = $_POST['campaign_id'];
        $userId = $_POST['joinee_id'];
        $communityId = $_POST['community_id'];
        $type = $_POST['type'];
        $pif_user_id = $_POST['pif_user_id'];
        $user = User::getUserDetailId(Utils::getAuth('user_id'));
        $community = Communities::getCommunity($communityId);
        $objMemvo = new stdClass();
        if ($type == 'accept') {
            $message_detail = 'The new membership request has been accepted for the group ' . $community->data->community_name . ' .Please do the neccesary payment for the campaign ';
            $message_to_id = Utils::getAuth('user_id');
            $message_from_id = $pif_user_id;
            $message_date = date('Y-m-d', time());
            $message_subject = 'Introduction Request';
            Connections::sendMessages($message_detail, $message_to_id, $message_from_id, $message_date, $message_subject);
            $message_detail = 'A new member has joined ' . $community->data->community_name . ' Community as per your introduction request sent by you. Please contact ' . $user->data->user_firstname . ' ' . $user->data->user_lastname . ' for further payment';
            $message_to_id = $pif_user_id;
            $message_from_id = Utils::getAuth('user_id');
            $message_date = date('Y-m-d', time());
            $message_subject = 'Introduction Request';
            Connections::sendMessages($message_detail, $message_to_id, $message_from_id, $message_date, $message_subject);
            $objMemvo->cmember_status = 'A';
            $objMemvo->cmember_id = $userId;
            $objMemvo->cmember_community_id = $communityId;
            $result = Communities::chanegeMemeberCommunityStatus($objMemvo);
            $result->message = COMMUNITY_REQ_ACCEPT;

        } else {
            $message_detail = 'The introduction request on ' . $community->data->community_name . ' has been declined by you ';
            $message_to_id = Utils::getAuth('user_id');
            $message_from_id = $pif_user_id;
            $message_date = date('Y-m-d', time());
            $message_subject = 'Introduction Request';

            Connections::sendMessages($message_detail, $message_to_id, $message_from_id, $message_date, $message_subject);
            $message_detail = 'Your introduction request on ' . $community->data->community_name . ' has been declined by ' . $user->data->user_firstname . ' ' . $user->data->user_lastname;
            $message_to_id = $pif_user_id;
            $message_from_id = Utils::getAuth('user_id');
            $message_date = date('Y-m-d', time());
            $message_subject = 'Introduction Request';
            Connections::sendMessages($message_detail, $message_to_id, $message_from_id, $message_date, $message_subject);

            $objMemvo->cmember_status = 'D';
            $objMemvo->cmember_id = $userId;
            $objMemvo->cmember_community_id = $communityId;
            $result = Communities::chanegeMemeberCommunityStatus($objMemvo);
            $result->message = COMMUNITY_REQ_DECLINE;
        }
        if ($type == 'accept') {
            Connections::setJoineeAccountAmount($campaign_id, $pif_user_id);

        } else {
        }

        Communities::updateCommunityCounts();
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }


    public function view_organization_associated_people()
    {
        //----Associates---
        $business_id = $_POST['business_id'];
        $page = PageContext::$request['page'];
        $associates = User::getAllAssociatesByBusiness($business_id, 1, 6);
        $associatedBiz = Business::getBusinessById($business_id);
        PageContext::$response->business_name = $associatedBiz->data->business_name;
        $itemperpage = PAGE_LIST_COUNT;
        PageContext::$response->associates = $associates->records;
        PageContext::$response->totalrecords = $associates->totalrecords;
        //-------Affilated users-----------
        PageContext::$response->affliatesUsersList = business::getAllAffiliatesIdForBusiness($business_id);
        PageContext::$response->business_id = $business_id;
        
        PageContext::$response->gallery_display_list = Business::getMyLatestDiscussionImage($business_id);
       // echopre(PageContext::$response->gallery_display_list);
        $associates = User::getAllAssociatesByBusiness($business_id, 1, 3);
        PageContext::$response->friend_display_list = $associates->records;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function view_organization_associated_peopleajax($pagenum = 1, $business_id)
    {
        //----Associates---
        $business_id = $_POST['business_id'];
        PageContext::$response->business_name = $_POST['business_name'];
        $page = PageContext::$request['page'];
        $associates = User::getAllAssociatesByBusiness($business_id, $pagenum, 6);
        $itemperpage = PAGE_LIST_COUNT;
        PageContext::$response->associates = $associates->records;
        PageContext::$response->totalrecords = $associates->totalrecords;
        //-------Affilated users-----------
        PageContext::$response->affliatesUsersList = business::getAllAffiliatesIdForBusiness($business_id);
        PageContext::$response->business_id = $business_id;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    /**
     *  Returns partial to be shown when testimonial tab is clicked
     *
     * @params null
     * @return void
     */
    public function view_organization_associated_testimonials()
    {
        $itemsPerPage = 5 ;
        $page = 1 ;
        $searchFieldArray = array('comment_id', 'comment_content', 'business_type');
        $business_id = $_POST['business_id'];
        PageContext::addScript('comment_popup.js');
        if($business_id){
        $testimonials = Comments::getAllTestimonials($orderfield = 'testimonial_id', $orderby = 'DESC',$page ,$itemsPerPage ,$search = '' , $searchFieldArray, $business_id);
        }
        $business = Business::getBusinessById($business_id);

        PageContext::$response->business->status = $business->data->business_status;
        PageContext::$response->business->created_by = $business->data->business_created_by;
        PageContext::$response->leads = $testimonials->records;
        PageContext::$response->totalPages = ceil($testimonials->totalrecords/$itemsPerPage);
        PageContext::$response->testimonials = $testimonials->records;

         PageContext::$response->gallery_display_list = Business::getMyLatestDiscussionImage($business_id);
       // echopre(PageContext::$response->gallery_display_list);
        $associates = User::getAllAssociatesByBusiness($business_id, 1, 3);
        PageContext::$response->friend_display_list = $associates->records;
        
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    /**
     *  Returns paginated testimonial partial to ajax call
     *
     * @params nextPage
     * @return void
     */
    public function view_organization_associated_testimonialsajax($nextPage)
    {
        $searchFieldArray = array('comment_id', 'comment_content', 'business_type');
        $business_id = $_POST['business_id'];
        $itemsPerPage = 5 ;

        $testimonials = Comments::getAllTestimonials($orderfield = 'testimonial_id', $orderby = 'DESC', $nextPage, $itemsPerPage, $search = '', $searchFieldArray, $business_id);
        $business = Business::getBusinessById($business_id);

        PageContext::$response->business->status = $business->data->business_status;
        PageContext::$response->business->created_by = $business->data->business_created_by;
        PageContext::$response->leads = $testimonials->records;
        PageContext::$response->testimonials = $testimonials->records;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    /**
     *  Returns gallery partial to ajax call
     *
     * @params null
     * @return void
     */
    public function view_organization_associated_gallery()
    {
        $page = 1;
        $businessId = $_POST['business_id'];
        $announcementImages = Business::getAnnouncementImages($page, $businessId);
//        echopre1($announcementImages);
        if(($announcementImages->totalrecords) >= 1){
            PageContext::$response->totalRecords = $announcementImages->totalrecords;
            PageContext::$response->imageDetails = $announcementImages->records;
            PageContext::$response->totalPages = $announcementImages->totpages/8;
        } else {
            PageContext::$response->imageDetails = null;
            PageContext::$response->totalRecords = 0;
            PageContext::$response->totalPages = 0;
        }
         PageContext::$response->gallery_display_list = Business::getMyLatestDiscussionImage($businessId);
       // echopre(PageContext::$response->gallery_display_list);
        $associates = User::getAllAssociatesByBusiness($businessId, 1, 3);
        PageContext::$response->friend_display_list = $associates->records;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    /**
     *  Returns paginated gallery partial to ajax call
     *
     * @params $nextPage
     * @return void
     */
    public function view_organization_associated_galleryajax($nextPage)
    {
        $businessId = $_POST['business_id'];
        $announcementImages = Business::getAnnouncementImages($nextPage,$businessId);

//        if(count($announcementImages) > 1){
            PageContext::$response->imageDetails = $announcementImages->records;
//        } else {
//            PageContext::$response->imageDetails = null;
//        }

        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function view_organization_associated_bizcom()
    {
        //----Associates---
        $business_id = $_POST['business_id'];
        $alias = $_POST['alias'];
        $organizationData = Business::getBusinessId($alias);
        $page = PageContext::$request['page'];
        if($organizationData->data->business_id){
        $associatedBizcom = Business::getAllBizcomByBusiness($organizationData->data->business_id, 1, 6);
        $associatedBiz = Business::getBusinessById($organizationData->data->business_id);
        }
       // echopre1($associatedBizcom);
        PageContext::$response->business_name = $associatedBiz->data->business_name;
        $itemperpage = PAGE_LIST_COUNT;
        foreach ($associatedBizcom->records as $k => $com) {
            $type = 'C';
            $type_id = $com->community_id;
            $user_id = PageContext::$response->sess_user_id;
            if ($user_id == '') {
                $user_id = 0;
            }
            $value = 0;
            $flag = 0;
            $rate = Ratings::getRatings($type_id, $type);
            if ($rate->data->count != 0) {
                $value = $rate->data->total / $rate->data->count;
            }
            if ($user_id <= 0) {
                $flag = 1;
            } else {
                $rate1 = Ratings::checkIfRated($type_id, $type, $user_id);
                if ($rate1->data->rating_id > 0 || $rate1->data->rating_id != '') {
                    $flag = 1;
                }
            }
            $associatedBizcom->records[$k]->ratetype = $type;
            $associatedBizcom->records[$k]->ratevalue = $value;
            $associatedBizcom->records[$k]->rateuser_id = $user_id;
            $associatedBizcom->records[$k]->rateflag = $flag;
            $associatedBizcom->records[$k]->ratetype_id = $type_id;
        }

        PageContext::$response->associatedBizcom = $associatedBizcom->records;
        PageContext::$response->totalrecords = $associatedBizcom->totalrecords;
        PageContext::$response->business_id = $business_id;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function view_organization_associated_bizcomajax($pagenum = 1, $business_id)
    {
        PageContext::$response->business_name = $_POST['business_name'];
        $alias = $_POST['alias'];
        $page = PageContext::$request['page'];
        $associatedBizcom = Business::getAllBizcomByBusiness($business_id, $pagenum, 6);
        $itemperpage = PAGE_LIST_COUNT;
        PageContext::$response->associatedBizcom = $associatedBizcom->records;
        PageContext::$response->totalrecords = $associatedBizcom->totalrecords;
        PageContext::$response->business_id = $business_id;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function view_business_affiliates()
    {
        //----Associates---
        $business_id = $_POST['business_id'];
        PageContext::$response->business_id = $business_id;
        PageContext::$response->business_name = $_POST['business_name'];
        $page = PageContext::$request['page'];
        $associates = business::getAllAffiliatesForBusiness($business_id);
        $itemperpage = PAGE_LIST_COUNT;
        $targetpage = BASE_URL . "directory/$alias?searchusertext=" . $searchusertext . '&searchusertype=' . $searchusertype . '&sortuser=' . $orderuserfield . '&sortuserby=' . $ordersortby;
        PageContext::$response->associates = $associates->records;
        PageContext::$response->totalrecords = $associates->totalrecords;
        PageContext::$response->paginationAffilate = Pagination::paginate($page, $itemperpage, $associates->totalrecords, $targetpage);
        //-------Affilated users-----------
        PageContext::$response->affliatesUsersList = Business::getAllAffiliatesIdForBusiness($business_id);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function view_business_affiliate_request()
    {
        $business_id = $_POST['business_id'];
        PageContext::$response->business_id = $business_id;
        PageContext::$response->business_name = $_POST['business_name'];
        $page = PageContext::$request['page'];
        $affiliateRequest = User::getAllAffilateRequestByBusiness($business_id);
        $itemperpage = PAGE_LIST_COUNT;
        $targetpage = BASE_URL . "directory/$alias?searchusertext=" . $searchusertext . '&searchusertype=' . $searchusertype . '&sortuser=' . $orderuserfield . '&sortuserby=' . $ordersortby;
        PageContext::$response->associatesRequest = $affiliateRequest->records;
        PageContext::$response->totalrecords = $affiliateRequest->totalrecords;
        PageContext::$response->paginationAffilateReq = Pagination::paginate($page, $itemperpage, $associates->totalrecords, $targetpage);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }


    public function my_friends()
    {
        Utils::checkUserLoginStatus();
        if (PageContext::$response->sess_user_status == 'I') {
            $this->redirect("inactiveuser");
        }
        PageContext::$response->activeSubMenu = 'friends';
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "my_friends", "user", "default");
        PageContext::$body_class = 'business_profile';
        PageContext::addStyle("rateit.css");
        PageContext::addScript("sendmsg.js");
        $orderfield = PageContext::$request['sort'];
        $orderby = PageContext::$request['sortby'];
        $page = PageContext::$request['page'];
        $groupby = PageContext::$request['groupby'];
        $search = addslashes(PageContext::$request['searchtext']);
        $searchtype = PageContext::$request['searchtype'];
        if ($orderby == '')
            $orderby = ' DESC';
        if ($orderfield == '')
            $orderfield = 'users.user_firstname';
        // code to get the arrow for the sort order
        switch ($orderby) {
            case 'ASC':
                PageContext::$response->business_name_sortorder = Utils::sortuparrow();
                break;
            case 'DESC':
                PageContext::$response->business_name_sortorder = Utils::sortdownarrow();
                break;
            default :
                PageContext::$response->business_name_sortorder = Utils::sortarrow();
                break;
        }
        PageContext::$response->{$orderfield . '_sortorder'} = Utils::getsortorder($orderby);
        PageContext::$response->searchtext = $search;
        PageContext::$response->searchtype = $searchtype;
        PageContext::$response->page = $page;
        PageContext::$response->groupby = $groupby;
        PageContext::$response->order1 = $orderby;
        // search field section
        PageContext::$response->search = array('fields' => array(), 'action' => PageContext::$response->baseUrl . 'my-friends');
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$response->order = ($orderby == 'ASC') ? 'DESC' : 'ASC';
        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
        $itemperpage = 6;
        PageContext::$response->itemperpage = $itemperpage;
        $targetpage = BASE_URL . 'my-friends?searchtext=' . $search . '&sort=' . $orderfield . '&sortby=' . $orderby . '&groupby=' . $groupby;
        $friends = User::getUserFriends1(PageContext::$response->sess_user_alias, $page, $itemperpage, $search, $orderfield, $orderby, $groupby);
        PageContext::addScript("jquery.rateit.js");
        PageContext::addScript("ratinglist.js");
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->slno = 1;
        PageContext::$response->friends = $friends->records;
        PageContext::$response->totalrecords = ($friends->totalrecords == '') ? 0 : $friends->totalrecords;
        PageContext::$response->pagination = Pagination::paginate($page, $itemperpage, $friends->totalrecords, $targetpage);
        PageContext::$response->alias = PageContext::$response->sess_user_alias;
    }


    public function listannouncements()
    {

        PageContext::$response->activeSubMenu = 'community';
        $communityId = $_POST['communityId'];
        $result = Communities::getCommunityAlias($communityId);
        PageContext::$response->community_created = $result->data->community_created_by;
        $communityDetails = Communities::getAnnouncements($communityId);
        PageContext::$response->communityId = $communityId;
        PageContext::$response->communityDetails = $communityDetails;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function addannouncements()
    {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        PageContext::$response->activeSubMenu = 'community';
        $title = $_POST['title'];
        $desc = $_POST['desc'];

        $mode = $_POST['mode'];
        $announcmentArr['community_id'] = $_POST['communityId'];
        $announcmentArr['community_announcement_title'] = Utils::escapeString($title);
        $announcmentArr['community_announcement_content'] = Utils::escapeString($desc);
        $announcmentArr['community_announcement_date'] = date('Y-m-d H:i:s', strtotime('now'));
        $announcmentArr['community_announcement_created_by'] = $_SESSION['default_user_id'];
        $announcmentArr['community_announcement_status'] = $_POST['status'];
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {

            $objUserRes->status = ERROR;
            $objUserRes->message['msg'] = "Please Upload File";
            $div = 'error_div';
        }
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {

            $type = $_FILES['file']['type'];
            $type1 = @explode('/', $type);
            if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "File format not supported.";
                $div = 'error_div';
            }
        }
        if ($mode == "")
            $result = Communities::addAnnouncements($announcmentArr);
        else
            $result = Communities::updateAnnouncements($announcmentArr, $mode);

        $announcementCount = Communities::getAnnouncementsCount($_POST['communityId']);
        $countdata = $result . "@" . sizeof($announcementCount) . "@" . PageContext::$response->userImagePath;
        echo $countdata;
        exit;
    }

    public function deleteannouncements()
    {
        PageContext::$response->activeSubMenu = 'community';
        $announcmentId = $_POST['announcement_id'];
        $result = Communities::deleteAnnouncements($announcmentId);
        $announcementCount = Communities::getAnnouncementsCount($_POST['community_id']);
        $countdata = sizeof($announcementCount);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function editannouncements()
    {
        PageContext::$response->activeSubMenu = 'community';
        $announcmentId = $_POST['announcement_id'];
        $result = Communities::editAnnouncements($announcmentId);
        echo json_encode($result);
        exit;
    }

    /**
     *  Returns view to be displayed for listing organizations
     *
     *  @param null
     *  @return string template 
     * */
    public function organisations_list()
    {
        PageContext::$body_class = 'business_profile';
        PageContext::$response->activeSubMenu = 'classifieds';

        if (PageContext::$response->sess_user_id > 0) {
            PageContext::registerPostAction("menu", "home_menu", "index", "default");
        } else {
            PageContext::registerPostAction("menu", "menu", "index", "default");
        }

        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "businesses_list", "user", "default");
        $orderfield = PageContext::$request['sort'];
        $orderby = PageContext::$request['sortby'];
        $page = PageContext::$request['page'];
        $search = addslashes(PageContext::$request['searchtext']);
        $searchtype = PageContext::$request['searchtype'];
        PageContext::$response->searchtext = $search;
        PageContext::$response->searchtype = $searchtype;
        PageContext::$response->page = $page;
        PageContext::$response->org_grp = ORG_GRP;
        // search field section
        PageContext::$response->search = array('fields' => array(), 'action' => PageContext::$response->baseUrl . 'pages');
        if ($orderby == '')
            $orderby = ' DESC';
        if ($orderfield == '')
            $orderfield = 'business_id';
        $page =1;
        $itemsPerPage = 12;

        // code to get the arrow for the sort order
        PageContext::$response->business_name_sortorder = Utils::sortarrow();
        PageContext::$response->{$orderfield . '_sortorder'} = Utils::getsortorder($orderby);
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';
        PageContext::$response->order;
        $organizationObj = Business::getAllTaggedBusinessWithCount($orderfield, $orderby, $page, $itemsPerPage, $search, $searchtypeArray);
       // echopre($organizationObj);
        $totalPages = ceil($organizationObj->totalrecords/$itemsPerPage);
        PageContext::addJsVar('TOTAL_PAG', $totalPages);
        PageContext::$response->total = $organizationObj->totalrecords;
        PageContext::$response->list = $organizationObj->data;

    }

    /**
     *  Returns organization list template to ajax call
     * 
     * @param $page
     * @return string template
     */
    public function organisations_listajax($page)
    {
        /* Need to change static values to dynamic */
        $orderby = ' DESC';
        $orderfield = 'business_id';
        $itemsPerPage = 12;
        PageContext::$response->org_grp = ORG_GRP;
        $organizationObj = Business::getAllBusinessWithCount($orderfield, $orderby, $page, $itemsPerPage, $search, $searchtypeArray);
        PageContext::$response->list = $organizationObj->data;
        
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();

    }

    public function my_organization_groups($business_id)
    {
        if (PageContext::$response->sess_user_status == 'I') {
            $this->redirect("inactiveuser");
        }
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "my_business_communities", "user", "default");
        PageContext::addStyle("rateit.css");
        PageContext::$body_class = 'business_profile';
        PageContext::$response->activeSubMenu = 'community';
        $orderfield = PageContext::$request['sort'];
        $orderby = PageContext::$request['sortby'];
        $page = PageContext::$request['page'];
        $search = addslashes(PageContext::$request['searchtext']);
        $searchtype = PageContext::$request['searchtype'];

        if ($orderby == '')
            $orderby = ' DESC';
        if ($orderfield == '')
            $orderfield = 'community_id';


        // code to get the arrow for the sort order
        PageContext::$response->community_name_sortorder = Utils::sortarrow();
        PageContext::$response->{$orderfield . '_sortorder'} = Utils::getsortorder($orderby);
        PageContext::$response->searchtext = $search;
        PageContext::$response->searchtype = $searchtype;
        PageContext::$response->page = $page;
        // search field section
        PageContext::$response->search = array('fields' => array(), 'action' => PageContext::$response->baseUrl . 'org-groups/' . $business_id);
        switch ($searchtype) {
            case 'all':
                $searchtypeArray = array('community_name');
                break;
            case 'name':
                $searchtypeArray = array();
                break;
            case 'email':
                $searchtypeArray = array();
                break;
            case 'phone':
                $searchtypeArray = array();
                break;
        }
        PageContext::$response->messagebox = Messages::getPageMessage();

        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';

        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];

        $itemperpage = PAGE_LIST_COUNT;
        PageContext::$response->itemperpage = $itemperpage;
        $targetpage = BASE_URL . 'org-groups/' . $business_id . '?searchtext=' . $search . '&searchtype=' . $searchtype . '&sort=' . $orderfield . '&sortby=' . $orderby;

        $leads = Communities::getAllCommunityByBusiness($orderfield, $orderby, $page, $itemperpage, $search, $searchtypeArray, Utils::getAuth('user_id'), '', $business_id);
        foreach ($leads->records as $k => $com) {
            $type = 'C';
            $type_id = $com->community_id;
            $user_id = PageContext::$response->sess_user_id;
            if ($user_id == '') {
                $user_id = 0;
            }
            $value = 0;
            $flag = 0;
            $rate = Ratings::getRatings($type_id, $type);
            if ($rate->data->count != 0) {
                $value = $rate->data->total / $rate->data->count;
            }
            if ($user_id <= 0) {
                $flag = 1;
            } else {
                $rate1 = Ratings::checkIfRated($type_id, $type, $user_id);
                if ($rate1->data->rating_id > 0 || $rate1->data->rating_id != '') {
                    $flag = 1;
                }
            }

            $leads->records[$k]->ratetype = $type;
            $leads->records[$k]->ratevalue = $value;
            $leads->records[$k]->rateuser_id = $user_id;
            $leads->records[$k]->rateflag = $flag;
            $leads->records[$k]->ratetype_id = $type_id;
        }
        PageContext::addScript("jquery.rateit.js");
        PageContext::addScript("ratinglist.js");
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->slno = 1;
        PageContext::$response->leads = $leads->records;
        PageContext::$response->totalrecords = ($leads->totalrecords == '') ? 0 : $leads->totalrecords;
        PageContext::$response->pagination = Pagination::paginate($page, $itemperpage, $leads->totalrecords, $targetpage);

    }

    public function postMyLike()
    {
        $data = array('community_id' => $_POST['community_id'],
            'announcement_id' => $_POST['announcement_id'],
            'user_id' => PageContext::$response->sess_user_id,
            'user_name' => PageContext::$response->sess_user_name,
            'like_date' => date('Y-m-d')
        );
        $like = Feed::postLike($data);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function shareFeed()
    {
        $data = array('community_id' => $_POST['community_id'],
            'announcement_id' => $_POST['announcement_id'],
            'user_id' => PageContext::$response->sess_user_id,
            'user_name' => PageContext::$response->sess_user_name,
            'share_date' => date('Y-m-d h:i:s')
        );
        $share = Feed::shareFeed($data);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function postfeedcomment()
    {
        $data_array = array(
            'announcement_id' => $_POST['announcement_id'],
            'community_id' => $_POST['community_id'],
            'comment_content' => Utils::escapeString($_POST['comments']),
            'comment_date' => date('Y-m-d h:i:s'),
            'user_id' => PageContext::$response->sess_user_id,
            'user_name' => PageContext::$response->sess_user_name,
            'parent_comment_id' => $_POST['comment_id'],
            'comment_status' => 'A'
        );
        $comments = array();
        $comments['name'] = PageContext::$response->sess_user_name;
        $comments['image'] = PageContext::$response->sess_user_image;

        $comments['comment'] = Feed::postComments($data_array, $_POST['comments']);
        $data = array('announcement_image_status' => 'A', 'comment_id' => $comments['comment']['comment_id']);
        $id = $_POST['image_id'];
        if ($id != 'undefined') {
            $objUserRes = User::UpdateCommentImage($data, $id);
        }
        $comments['parent_comment_id'] = $_POST['comment_id'];
        $comments['community_id'] = $_POST['community_id'];
        PageContext::$response->image_file = $objUserRes;
        PageContext::$response->comments = $comments;
        PageContext::$response->alias = PageContext::$response->sess_user_alias;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function listnewsfeedajax($pagenum, $search, $business_type)
    {
        PageContext::addScript("profile.js");
        //=====================News Feed====================================
        $feeds = Feed::listUserFeeds($business_type, $search, $pagenum, 10);
        PageContext::$response->feeds = $feeds->records;
        //--------------Feed Comments----------------
        foreach ($feeds->records AS $feed) {
            $comments = Feed::getAnnouncementComments($feed->community_announcement_id);
            if (PageContext::$response->sess_user_id != '') {
                $communitySuggestions = Communities::getCommunitySuggestions($feed->community_business_id, $feed->community_id);
                PageContext::$response->Suggestion[$feed->community_announcement_id] = $communitySuggestions->data;
            }
            PageContext::$response->Comments[$feed->community_announcement_id] = $comments->records;
        }
        //=======================================================
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }


    public function feedCommentDelete()
    {
        $comment_id = $_POST['comment_id'];
        $announcement_id = $_POST['announcement_id'];
        Feed::deleteComments($comment_id, $announcement_id);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }
    
    public function newsFeedCommentDelete()
    {
        $comment_id = $_POST['comment_id'];
        $announcement_id = $_POST['announcement_id'];
        Feed::deleteNewsfeedComments($comment_id, $announcement_id);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }
    
    public function orgFeedCommentDelete()
    {
        $comment_id = $_POST['comment_id'];
        $announcement_id = $_POST['announcement_id'];
        Feed::deleteOrgfeedComments($comment_id, $announcement_id);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function loadMoreFeedComments()
    {
        $announcement_id = $_POST['announcement_id'];
        $pagenum = $_POST['pagenum'];
        $comments = Feed::getFeedComments($announcement_id, $pagenum + 1);
        //echopre($comments);exit;
        PageContext::$response->Comments = $comments->records;
        PageContext::$response->TotalPage = $comments->totpages;
        PageContext::$response->CurrentPage = $comments->currentpage;
        // PageContext::$response->image_file  =
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function postCommentLike()
    {
        $data = array('comment_id' => $_POST['comment_id'],
            'announcement_id' => $_POST['announcement_id'],
            'user_id' => PageContext::$response->sess_user_id,
            'user_name' => PageContext::$response->sess_user_name,
            'like_date' => date('Y-m-d')
        );
        $like = Feed::postCommentLike($data);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function showcommentreply()
    {
        $comment_id = $_POST['comment_id'];
        $replies = Feed::showCommentReply($comment_id);
        foreach($replies->records as $value)
        {
            $value->user_image=User::getUserDetail($value->user_id)->data->Image;
        }

        PageContext::$response->Comments = $replies->records;
        PageContext::$response->TotalPage = $replies->totpages;
        PageContext::$response->CurrentPage = $replies->currentpage;

        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();

    }

    public function ajaxUploadCommentImage()
    {
        print_r($_FILES);
    }

    public function feedReplyDelete()
    {
        $comment_id = $_POST['comment_id'];
        $announcement_id = $_POST['announcement_id'];
        Feed::deleteReply($comment_id, $announcement_id);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }
    
    public function newsFeedReplyDelete()
    {
        $comment_id = $_POST['comment_id'];
        $announcement_id = $_POST['announcement_id'];
        Feed::deleteReplyNewsFeed($comment_id, $announcement_id);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }
    
    public function OrgFeedReplyDelete()
    {
        $comment_id = $_POST['comment_id'];
        $announcement_id = $_POST['announcement_id'];
        Feed::deleteReplyOrgFeed($comment_id, $announcement_id);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function uploadimage($id)
    {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        PageContext::$response->file = '';
        PageContext::$response->id = $id;
    }

    public function uploadimagesubmit($id)
    {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $objUserRes = new stdClass();
        $objUserImageData = new stdClass();
        $objUserRes->status = SUCCESS;
        $div = 'success_div';
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message['msg'] = "Please Upload File";
            $div = 'error_div';
        }
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
            $type = $_FILES['file']['type'];
            $type1 = @explode('/', $type);
            if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "File format not supported.";
                $div = 'error_div';
            }
        }
        if ($objUserRes->status == SUCCESS) {
            $objUserImageData->user_id = PageContext::$response->sess_user_id;
            $objUserImageData->file = $_FILES['file'];
            $objUserImageData->announcement_id = $id;
            $objUserImageData->comment_id = '';
            $objUserImageData->announcement_image_date = date('m/d/Y');
            list($width, $height, $type, $attr) = getimagesize($_FILES["file"]['tmp_name']);
            $objUserRes->message = User::addCommentImage($objUserImageData,$width, $height);
            $div = $objUserRes->message['msgcls'];
            PageContext::$response->file = $objUserRes->message['file'];
            //PageContext::$response->image_id = '';
            PageContext::$response->feed_image_id = $objUserRes->message['image_id'];
        }

        PageContext::$response->message['msg'] = $objUserRes->message['msg'];
        PageContext::$response->message['msgClass'] = $div;

    }

    public function communityprofilechange($id)
    {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        PageContext::$response->file = '';
        PageContext::$response->community_id = $id;
        if (PageContext::$request['image_submit']) {
            $objUserRes = new stdClass();
            $objUserImageData = new stdClass();

            $objUserRes->status = SUCCESS;
            $div = 'success_div';
            if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {
                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "Please Upload File";
                $div = 'error_div';
            }
            if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
                $type = $_FILES['file']['type'];
                $type1 = @explode('/', $type);
                if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                    $objUserRes->status = ERROR;
                    $objUserRes->message['msg'] = "File format not supported.";
                    $div = 'error_div';
                }
            }
            if ($objUserRes->status == SUCCESS) {

                $objUserImageData->community_id = PageContext::$request['community_id'];
                $objUserImageData->file = $_FILES['file'];
                list($width, $height, $type, $attr) = getimagesize($_FILES["file"]['tmp_name']);
                $objUserRes->message = User::updateCommunityProfilePic($objUserImageData,$width, $height);
                $div = $objUserRes->message['msgcls'];
                PageContext::$response->file = $objUserRes->message['file'];
            }

            PageContext::$response->message['msg'] = $objUserRes->message['msg'];
            PageContext::$response->message['msgClass'] = $div;
            $_SESSION['default_user_image_name'] = $objUserRes->message['file'];
        }

    }

    public function uploadimagereply($id, $announcement_id)
    {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        PageContext::$response->file = '';
        PageContext::$response->replyid = $id;
        PageContext::$response->announceid = $announcement_id;
    }

    public function uploadimagereplysubmit($id)
    {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $objUserRes = new stdClass();
        $objUserImageData = new stdClass();
        $objUserRes->status = SUCCESS;
        $div = 'success_div';
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message['msg'] = "Please Upload File";
            $div = 'error_div';
        }
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
            $type = $_FILES['file']['type'];
            $type1 = @explode('/', $type);
            if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "File format not supported.";
                $div = 'error_div';
            }
        }
        if ($objUserRes->status == SUCCESS) {
            $objUserImageData->user_id = PageContext::$response->sess_user_id;
            $objUserImageData->file = $_FILES['file'];
            $objUserImageData->newsfeed_id = $id;
            $objUserImageData->newsfeed_comment_id = '';
            $objUserImageData->newsfeed_comment_image_date = date('m/d/Y');
            $objUserRes->message = User::addFeedCommentImage($objUserImageData);
            $div = $objUserRes->message['msgcls'];
            PageContext::$response->file = $objUserRes->message['file'];
            // PageContext::$response->image_id = '';
            PageContext::$response->feed_image_id = $objUserRes->message['image_id'];
        }

        PageContext::$response->message['msg'] = $objUserRes->message['msg'];
        PageContext::$response->message['msgClass'] = $div;

    }

    public function category_businesses_list()
    {
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "category_businesses_list", "user", "default");
        $search = addslashes(PageContext::$request['searchtext']);
        $category_businesses_list = Business::getBusinesscategory($search);
        PageContext::$response->category_business = $category_businesses_list;
        PageContext::$response->total = count($category_businesses_list);
        PageContext::$response->searchtext = $search;
    }

    public function sent_items()
    {
        PageContext::addScript(BASE_URL . 'project/lib/ckeditor/ckeditor.js');
        Utils::checkUserLoginStatus();
        if (PageContext::$response->sess_user_status == 'I') {
            $this->redirect("inactiveuser");
        }
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$body_class = 'business_profile';

        $page = PageContext::$request['page'];
        $itemperpage = PAGE_LIST_COUNT;
        if ($orderby == '')
            $orderby = ' DESC';
        if ($orderfield == '')
            $orderfield = 'message_id';

        PageContext::$response->page = $page;
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';
        PageContext::$response->class = $messageArray['msgClass'];
        $targetpage = BASE_URL . 'sentitems?order=' . orderby;
        $message_details = Connections::getAllSentMessages($orderfield, $orderby, $page, LAZYLOAD_COUNT);
        PageContext::$response->message_details = $message_details;
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->totalrecords = $users->totalrecords;
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "sentitems", "user", "default");
        PageContext::addScript('community_tab.js');
        PageContext::addScript('community.js');
        PageContext::addScript('communitymember_lazyload.js');
        PageContext::addScript('inbox_lazyload.js');
        PageContext::$body_class = 'member_area';
        PageContext::$response->activeSubMenu = 'messages';
        PageContext::$response->invitation_type = 'community';
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$metaTitle = META_TITLE;// = SITE_NAME . " : Your personalised social network";
        $total_pages = $message_count / LAZYLOAD_COUNT;
        PageContext::addJsVar('LAZYCOUNT', LAZYLOAD_COUNT);
        PageContext::addJsVar('TOTAL_PAGES', $total_pages);
        PageContext::$response->tojoin = '';
        PageContext::$response->itemperpage = $itemperpage;
        PageContext::$response->totalrecords = ($message_details->totalrecords == '') ? 0 : $message_details->totalrecords;
        PageContext::$response->pagination = Pagination::paginate($page, $itemperpage, $message_details->totalrecords, $targetpage);

    }

    public function listmutualfriends()
    {
        PageContext::$response->activeSubMenu = 'profile';
        $user_id = $_POST['user_id'];
        $session_id = $_POST['session_id'];
        PageContext::$response->alias = $alias;
        $friends = User::getUserMutualFriends($user_id, $session_id);
        foreach ($friends as $key => $val) {
            $friend_count = User::getFriendscount($val->friends_list_friend_id);
            $friends[$key]->count = $friend_count;
        }
        PageContext::$response->count = $friends->totalrecords;
        PageContext::$response->friends = $friends;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function postMyLikeAdmin()
    {
        $data = array('admin_announcement_id' => $_POST['admin_announcement_id'],
            'user_id' => PageContext::$response->sess_user_id,
            'user_name' => PageContext::$response->sess_user_name,
            'like_date' => date('Y-m-d')
        );
        $like = Feed::postLikeAdmin($data);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function add_announcement()
    {
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "add_announcement", "user", "default");
        PageContext::$response->activeSubMenu = 'community';
        PageContext::addScript('validations_form.js');
        $leads = Communities::getAllCommunitites();
        if ($_POST['submit']) {
            $mode = $_POST['mode'];
            $announcmentArr['community_id'] = Utils::escapeString($_POST['community']);
            $announcmentArr['community_announcement_title'] = Utils::escapeString($_POST['announcement_title']);
            $announcmentArr['community_announcement_content'] = Utils::escapeString($_POST['announcement_desc']);
            $announcmentArr['community_announcement_date'] = date("Y-m-d");
            $announcmentArr['community_announcement_created_by'] = $_SESSION['default_user_id'];
            $announcmentArr['community_announcement_status'] = Utils::escapeString($_POST['announcement_status']);
            $community_alias = Communities::getCommunityAliasFromId(Utils::escapeString($_POST['community']));

            if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {

                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "Please Upload File";
                $div = 'error_div';
            }
            if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {

                $type = $_FILES['file']['type'];
                $type1 = @explode('/', $type);
                if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                    $objUserRes->status = ERROR;
                    $objUserRes->message['msg'] = "File format not supported.";
                    $div = 'error_div';
                }
            }

            if ($mode == "")
                $result = Communities::addAnnouncements($announcmentArr);
            else
                $result = Communities::updateAnnouncements($announcmentArr, $mode);
            Messages::setPageMessage('Announcement Added Successfully', 'success_div');
            $this->redirect("community/" . $community_alias->data->community_alias);
        }
        PageContext::$response->community_created = $result->data->community_created_by;

        PageContext::$response->communityId = $communityId;
        PageContext::$response->communityDetails = $leads;
        PageContext::$response->messagebox = Messages::getPageMessage();

    }


    public function announcement_detail($announcement_id = '')
    {
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "announcement_detail", "user", "default");
        PageContext::$response->activeSubMenu = 'community';
        $communityDetails = Communities::getAnnouncementDetail($announcement_id);
        PageContext::$response->communityDetails = $communityDetails;
    }

    public function sendmessage()
    {
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "sendmessage", "user", "default");
        PageContext::addScript('validations_form.js');
        if (PageContext::$request['btnSubmit']) {
            $to_user_id = PageContext::$request['friend_id'];
            if($to_user_id>0){
                   
                $objUserRes = new stdClass();
                $result = Connections::sendmessage($to_user_id);
                Messages::setPageMessage('Message sent successfully', 'success_div');
                PageContext::$response->to_user_id = $to_user_id;
            }
            else{
               Messages::setPageMessage('Please select a friend', 'error_div'); 
            }
        }

        PageContext::$response->message = Messages::getPageMessage();
    }

    public function changefriendstatus()
    {
        $id = $_POST['id'];
        $type = $_POST['type'];
        $data = array('friends_list_view_status' => $type,
        );
        User::changeStatus($data, $id);
        if ($type == 'P')
            $msg = 'Successfully changed to personal friend';
        if ($type == 'B')
            $msg = 'Successfully changed to business friend';

        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        echo $msg;
        exit;
    }

    public function deletesentmessages($message_id)
    {
        $objUserRes = new stdClass();
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $result = Connections::deletesentmessage($message_id);
        $result->message = 'SUCCESS';
        PageContext::$full_layout_rendering = false;
        Messages::setPageMessage('Your message deleted successfully', 'success_div');
        $this->view->disableLayout();
        return json_encode(Utils::objectToArray($result));
    }


    public function bizcom_owner_approval()
    {
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "bizcom_owner_approval", "user", "default");
        $user_id = Utils::getAuth('user_id');
        $page = PageContext::$request['page'];
        $itemperpage = 9;
        $search = addslashes(PageContext::$request['searchtext']);
        $pif = Referraloffer::getBizcomOwnerApproval($user_id, 1, $itemperpage, $search);
        PageContext::$response->pifs = $pif;
        PageContext::$response->totalrecords = count($pif);
        PageContext::$response->searchtext = $search;
        PageContext::$response->page = $page;

    }

    public function work_flow()
    {
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "work_flow", "user", "default");
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function uploadimagefeed()
    {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $objUserRes = new stdClass();
        $objUserImageData = new stdClass();
        $objUserRes->status = SUCCESS;
        $div = 'success_div';

        list($width, $height, $type, $attr) = getimagesize($_FILES["file"]['tmp_name']);
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message['msg'] = "Please Upload File";
            $div = 'error_div';
        }
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
            $type = $_FILES['file']['type'];
            $type1 = @explode('/', $type);
            if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "File format not supported.";
                $div = 'error_div';
            }
        }
        if ($objUserRes->status == SUCCESS) {

            $objUserImageData->news_feed_user_id = PageContext::$response->sess_user_id;
            $objUserImageData->file = $_FILES['file'];
            $objUserImageData->news_feed_comment = '';
            $objUserRes->message = User::addNewsfeedImage($objUserImageData, $width, $height);
            $div = $objUserRes->message['msgcls'];
            PageContext::$response->file = $objUserRes->message['file'];
            PageContext::$response->feed_image_id = $objUserRes->message['image_id'];
        }
        PageContext::$response->message['msg'] = $objUserRes->message['msg'];
        PageContext::$response->message['msgClass'] = $div;
    }

    public function updatenewsfeed()
    {
        PageContext::addScript('profile.js');
        PageContext::$Ogfbpage = 1;
        $comment = $_POST['comment'];
        $id = $_POST['id'];
         $objUserRes->status = SUCCESS;
        //echopre1($_FILES);
        
         if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message['msg'] = "Please Upload File";
            $div = 'error_div';
        }
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
            $type = $_FILES['file']['type'];
            $type1 = @explode('/', $type);
            if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "File format not supported.";
                $div = 'error_div';
            }
        }
        //echo $objUserRes->status;exit;
        if ($objUserRes->status == SUCCESS) {
            $objUserImageData->user_id = PageContext::$response->sess_user_id;
            $objUserImageData->file = $_FILES['file'];
            $objUserImageData->announcement_id = $id;
            $objUserImageData->comment_id = '';
            $objUserImageData->announcement_image_date = date('m/d/Y');
            list($width, $height, $type, $attr) = getimagesize($_FILES["file"]['tmp_name']);
            $objUserRes->message = User::addCommentImage($objUserImageData,$width, $height);
            $div = $objUserRes->message['msgcls'];
            PageContext::$response->file = $objUserRes->message['file'];
            //PageContext::$response->image_id = '';
            PageContext::$response->feed_image_id = $objUserRes->message['image_id'];
        }
        $data = array(
            'news_feed_comment' => $comment,
            'news_feed_user_name' => Utils::getAuth('user_firstname') . ' ' . Utils::getAuth('user_lastname'),
            'news_feed_image_id' => $objUserRes->message['image_id'],
            'news_feed_image_name' => $objUserRes->message['image']
        );
        $new_id = User::changeNewsfeedComment($data, $id);

        if ($id > 0) {

        } else {
            $id = $new_id;
        }

        $news_feed = User::getNewsFeedById($id);
        //echopre1($news_feed);
        PageContext::$response->news_feed = $news_feed->data;
        $msg = 'Successfully saved newsfeed';

        PageContext::$full_layout_rendering = false;
//        print_r($this->view);
        $this->view->disableLayout();
    }

    public function postMyNewsfeedLike()
    {
        $data = array(
            'news_feed_id' => $_POST['news_feed_id'],
            'news_feed_like_user_id' => PageContext::$response->sess_user_id,
            'news_feed_comment_id' => $_POST['comment_id'],
            'news_feed_like_user_name' => PageContext::$response->sess_user_name,
            'news_feed_like_date' => date('Y-m-d')
        );
        $like = Feed::postNewsfeedLike($data);
        
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function postnewsfeedcomment()
    {
      //  echopre1($_POST);
        $data_array = array(
            'news_feed_id' => $_POST['news_feed_id'],
            'news_feed_comment_content' => Utils::escapeString($_POST['comments']),
            'news_feed_comment_date' => date('Y-m-d h:i:s'),
            'news_feed_comment_user_id' => PageContext::$response->sess_user_id,
            'news_feed_comment_user_name' => PageContext::$response->sess_user_name,
            'parent_comment_id' => $_POST['comment_id'],
            'news_feed_comment_status' => 'A'
        );
        $comments = array();
        $comments['name'] = PageContext::$response->sess_user_name;
        $comments['image'] = PageContext::$response->sess_user_image;
        $comments['comment'] = Feed::postNewsfeedComments($data_array, $_POST['comments']);
        $data = array('newsfeed_comment_image_status' => 'A', 'newsfeed_comment_id' => $comments['comment']['comment_id']);
        $id = $_POST['image_id'];
        if ($id != 'undefined') {
            $objUserRes = User::UpdateNewsfeedCommentImage($data, $id);
        }
        $comments['parent_comment_id'] = $_POST['comment_id'];
        $comments['community_id'] = $_POST['community_id'];
        PageContext::$response->image_file = $objUserRes;
        PageContext::$response->comments = $comments;
        PageContext::$response->alias = PageContext::$response->sess_user_alias;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function showfeedcommentreply()
    {
        $comment_id = $_POST['comment_id'];
        $replies = Feed::showFeedCommentReply($comment_id);
        foreach($replies->records as $value)
        {
            $value->user_image=User::getUserDetail($value->user_id)->data->Image;
        }
        PageContext::$response->Comments = $replies->records;
        PageContext::$response->TotalPage = $replies->totpages;
        PageContext::$response->CurrentPage = $replies->currentpage;
        PageContext::$full_layout_rendering = false;
//        print_r($this->view);
        $this->view->disableLayout();

    }

    public function newsfeed_detail($id = '')
    {
        PageContext::$Ogfbpage = 1;
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "newsfeed_detail", "user", "default");
        PageContext::$response->activeSubMenu = 'community';
        $newsfeedDetails = Feed::getNewsfeedDetails($id);

        PageContext::$ogtype = 'website';
        PageContext::$ogtitle = $newsfeedDetails->news_feed_comment;
        PageContext::$ogdescription = $newsfeedDetails->news_feed_comment;
        PageContext::$ogurl = PageContext::$response->baseUrl . 'newsfeed-detail/' . $newsfeedDetails->news_feed_alias;
        PageContext::$ogimage = PageContext::$response->userImagePath . 'medium/' . $newsfeedDetails->news_feed_image_name;
        PageContext::$response->newsfeedDetails = $newsfeedDetails;
    }

    public function postNewsfeedCommentLike()
    {
        $data = array('newsfeed_comment_id' => $_POST['newsfeed_comment_id'],
            'newsfeed_id' => $_POST['newsfeed_id'],
            'user_id' => PageContext::$response->sess_user_id,
            'user_name' => PageContext::$response->sess_user_name,
            'newsfeed_comment_like_date' => date('Y-m-d')
        );
        $like = Feed::postNewsfeedCommentLike($data);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function uploadfeedcommentimagesubmit($id)
    {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $objUserRes = new stdClass();
        $objUserImageData = new stdClass();
        $objUserRes->status = SUCCESS;
        $div = 'success_div';
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message['msg'] = "Please Upload File";
            $div = 'error_div';
        }
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
            $type = $_FILES['file']['type'];
            $type1 = @explode('/', $type);
            if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "File format not supported.";
                $div = 'error_div';
            }
        }
        if ($objUserRes->status == SUCCESS) {
            //echo "here";exit;
            $objUserImageData->user_id = PageContext::$response->sess_user_id;
            $objUserImageData->file = $_FILES['file'];
            $objUserImageData->newsfeed_id = $id;
            $objUserImageData->newsfeed_comment_id = '';
            $objUserImageData->newsfeed_comment_image_date = date('m/d/Y');
            $objUserRes->message = User::addFeedCommentImage($objUserImageData);
            $div = $objUserRes->message['msgcls'];
            PageContext::$response->file = $objUserRes->message['file'];
            PageContext::$response->feed_image_id = $objUserRes->message['image_id'];
        }

        PageContext::$response->message['msg'] = $objUserRes->message['msg'];
        PageContext::$response->message['msgClass'] = $div;

    }

    public function uploadfeedimagereplysubmit($id)
    {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $objUserRes = new stdClass();
        $objUserImageData = new stdClass();
        $objUserRes->status = SUCCESS;
        $div = 'success_div';
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message['msg'] = "Please Upload File";
            $div = 'error_div';
        }
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
            $type = $_FILES['file']['type'];
            $type1 = @explode('/', $type);
            if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "File format not supported.";
                $div = 'error_div';
            }
        }
        if ($objUserRes->status == SUCCESS) {
            $objUserImageData->user_id = PageContext::$response->sess_user_id;
            $objUserImageData->file = $_FILES['file'];
            $objUserImageData->newsfeed_id = $id;
            $objUserImageData->newsfeed_comment_id = '';
            $objUserImageData->newsfeed_comment_image_date = date('m/d/Y');
            $objUserRes->message = User::addFeedCommentImage($objUserImageData);
            $div = $objUserRes->message['msgcls'];
            PageContext::$response->file = $objUserRes->message['file'];
            PageContext::$response->feed_image_id = $objUserRes->message['image_id'];
        }

        PageContext::$response->message['msg'] = $objUserRes->message['msg'];
        PageContext::$response->message['msgClass'] = $div;

    }

    public function my_gallary()
    {
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "my_gallary", "user", "default");
        PageContext::$response->activeSubMenu = 'community';
        $imageDetails = Feed::getNewsfeedImage();
        PageContext::$response->imageDetails = $imageDetails;
        $total_pages = (sizeof($imageDetails) / 3);
        PageContext::addJsVar('TOT_PAGE', $total_pages);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function my_gallaryajax($page)
    {
        PageContext::registerPostAction("menu", "home_menu", "index", "default");
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "my_gallary", "user", "default");
        PageContext::$response->activeSubMenu = 'community';
        $imageDetails = Feed::getNewsfeedImage($page);
        PageContext::$response->imageDetails = $imageDetails;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function orgtimelineimageupload($id)
    {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $objUserRes = new stdClass();
        $objUserImageData = new stdClass();
        $objUserRes->status = SUCCESS;
        $div = 'success_div';
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message['msg'] = "Please Upload File";
            $div = 'error_div';
        }
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
            $type = $_FILES['file']['type'];
            $type1 = @explode('/', $type);
            list($originalWidth, $originalHeight) = getimagesize($_FILES['file']['name']);
            if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "File format not supported.";
                $div = 'error_div';
            }
        }
        if ($objUserRes->status == SUCCESS) {
            $objUserImageData->business_id = $id;
            $objUserImageData->file = $_FILES['file'];
            $objUserImageData->business_timeline_date = date('m/d/Y');
            list($width, $height, $type, $attr) = getimagesize($_FILES["file"]['tmp_name']);
            $objUserRes->message = Images::addOrgTimelineImage($objUserImageData,$width, $height);
            $div = $objUserRes->message['msgcls'];
            PageContext::$response->image_id = $objUserRes->message['image_id'];
            echo PageContext::$response->file = $objUserRes->message['file'];
            exit;
        }

//        PageContext::$response->message['msg'] = $objUserRes->message['msg'];
//        PageContext::$response->message['img'] = $objUserRes->message['msg'];
//        PageContext::$response->message['msgClass'] = $div;

    }

    /**
     * Uploads background image for group
     *
     * @param $id
     * @return void
     */
    public function grpTimelineImageUpload($groupId)
    {
        // TODO : handle error case for image uploading

        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();

        $imageObj = new stdClass();
        $imageObj->group_id = $groupId;
        $imageObj->file = $_FILES['file'];
        $imageObj->group_timeline_date = date('m/d/Y');
        list($width, $height) = getimagesize($_FILES["file"]['tmp_name']);
        $imageObj = Images::addGrpTimelineImage($imageObj,$width, $height);
        echo $imageObj['data'];
    }

    public function deletetagged()
    {
        $objUserRes = new stdClass();
        $id = $_POST['id'];
        $result = Business::removeTag($id);
        $result->message = 'SUCCESS';
        PageContext::$full_layout_rendering = false;

        $this->view->disableLayout();
        return 'success';
        exit;
    }

    public function communitydiscussion()
    {

        PageContext::$response->activeSubMenu = 'community';
        $alias = $_POST['alias'];
        PageContext::$response->community_alias = $alias;
        // $result                                             = Communities::getCommunityAlias($communityId);
        $communityData = Communities::getCommunityId($alias);
        // PageContext::$response->community_created           = $result->data->community_created_by;
        $communityAnnouncementsCount = Communities::getAnnouncements($communityData->data->community_id,'','');
        PageContext::$response->communityAnnouncementsCount = count($communityAnnouncementsCount)/5;
        PageContext::$response->communityAnnouncements = Communities::getAnnouncements($communityData->data->community_id,1,5);
        $result = Communities::getCommunityAlias($communityData->data->community_id);
        // echopre1(PageContext::$response->communityAnnouncements);
        PageContext::$response->communityId = $communityData->data->community_id;
        $comments = Comments::getAllComments($orderfield, $orderby, $page, $itemperpage, $search, $searchtypeArray, 'C', $communityData->data->community_id);
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
           
            PageContext::$response->slno = 1;
        PageContext::$response->leads = $comments->records;
        PageContext::$response->totalrecords = $comments->totalrecords;
        PageContext::$response->pagination = Pagination::paginate($page, $itemperpage, $comments->totalrecords, $targetpage);
        PageContext::$response->comments = $comments->records;
        if ($result->status == SUCCESS) {
            PageContext::$response->result = $result->data;
            PageContext::$response->community_image = PageContext::$response->result->file_path;
        } else {
            Messages::setPageMessage($result->message, ERROR_CLASS);
            $this->redirect('community');
        }
        PageContext::$response->results = $results->data;
        //--------------------------------------
        if ($communityData->status == SUCCESS) {
            PageContext::$response->communityData = $communityData->data;
        } else {
            Messages::setPageMessage($communityData->message, ERROR_CLASS);
            $this->redirect('community');
        }
        //--------------------------------------
        PageContext::addJsVar('ALIAS', $alias);
        PageContext::addJsVar('LAZYCOUNT', LAZYLOAD_COUNT);
        PageContext::addJsVar('TOTAL_PAGES', $members->memberCount / LAZYLOAD_COUNT);
        PageContext::addScript('communitymember_lazyload.js');
        PageContext::addScript('profile.js');
        PageContext::addScript('common.js');
        PageContext::$response->tojoin = '';
        PageContext::$response->sess_user_id = Utils::getAuth('user_id');


        if (PageContext::$response->sess_user_id > 0) {
            $share_array = array();
            $feed_array = array();
            $search = $_GET['search'];
            PageContext::$response->search = $search;
            //-------------Share------------------------
            if ($search == '' OR $search == 'S') {
                $shares = Feed::getFriendShares();
                foreach ($shares->records AS $share_item) {
                    $share_array[strtotime($share_item->share_date)][] = (array)$share_item;
                }
            }
             //echopre($share_array);
            //----------------------Announcemnet -----------
            if ($search == '' OR $search == 'A' OR $search == 'S') {
                if ($search != 'S') {
                    $feeds = Feed::listUserFeeds('', $searchfeed = '', 1, 5);
                }
                //echopre($feeds);
                PageContext::addJsVar('TOTAL_FEED_PAGES', $feeds->totpages/5);
                foreach ($feeds->records AS $feed_item) {
                    $feed_array[strtotime($feed_item->community_announcement_date)][] = (array)$feed_item;
                }
                //----------News feed (Share+announcement)-------------
                $news_array = $share_array + $feed_array;
                krsort($news_array);
                PageContext::$response->feeds = $news_array;
               // echopre($news_array);
                //--------------------Feed Comments----------------
                foreach ($news_array AS $newsItems) {
                    foreach ($newsItems AS $news) {
                       // echopre($news);
                        if ($news['community_announcement_id']) {
                            $comments = Feed::getAnnouncementComments($news['community_announcement_id']);
                             foreach($comments->records as $value) {
                   //   echopre1($value);
                  // $replies = Feed::showFeedCommentReply($value->news_feed_comments_id); 
                   $like_user_comment_comments2 = Business::showGrpCommentOfCommentsLikeUser($value->announcement_comment_id); 
                  // echopre($like_user_comment_comments1);
                foreach($like_user_comment_comments2 as $data3){
                 //   echo $data2->user_name;
                    $name2 .=  $data3->user_name.",";
                }
                $name2 = rtrim($name2, ",");
                $comments->records['users']= $name2; 
                $value->user_image=User::getUserDetail($value->user_id)->data->Image;
                }
                        }
                         $news_feed_like_users = Feed::getGroupCommentsLikesUsers($news['community_announcement_id']);
               // echopre1($news_feed_like_users);
                        PageContext::$response->newsFeedLikeUsers[$news['community_announcement_id']] = $news_feed_like_users;

                        PageContext::$response->Comments[$news['community_announcement_id']] = $comments->records;
                        PageContext::$response->Page[$news['community_announcement_id']]['totpages'] = $comments->totpages;
                        PageContext::$response->Page[$news['community_announcement_id']]['currentpage'] = $comments->currentpage;
                    }
                }
                // echopre(PageContext::$response->Comments);
            }
            
        }
        PageContext::$response->gallery_display_list = Communities::getMyLatestDiscussionImage($communityData->data->community_id);
        PageContext::$response->friend_display_list = Communities::getCommunityMembers($communityData->data->community_id, 'A', 3, $orderfield = 'community_id', $orderby = 'DESC','');
        // PageContext::$response->communityDetails            = $communityDetails;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }
    
     public function communitydiscussionajax($pagenum)
    {
         $name2 = "";
        PageContext::$response->activeSubMenu = 'community';
        $alias = $_POST['alias'];
        $communityData = Communities::getCommunityId($alias);
        PageContext::$response->communityAnnouncements = Communities::getAnnouncements($communityData->data->community_id,$pagenum,5);
        $result = Communities::getCommunityAlias($communityData->data->community_id);
        PageContext::$response->communityId = $communityData->data->community_id;
        $comments = Comments::getAllComments($orderfield, $orderby, $page, $itemperpage, $search, $searchtypeArray, 'C', $communityData->data->community_id);
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page) - $itemperpage) + 1);
        else
            PageContext::$response->slno = 1;
        PageContext::$response->leads = $comments->records;
        PageContext::$response->totalrecords = $comments->totalrecords;
        PageContext::$response->pagination = Pagination::paginate($page, $itemperpage, $comments->totalrecords, $targetpage);
        PageContext::$response->comments = $comments->records;
        if ($result->status == SUCCESS) {
            PageContext::$response->result = $result->data;
            PageContext::$response->community_image = PageContext::$response->result->file_path;
        } else {
            Messages::setPageMessage($result->message, ERROR_CLASS);
            $this->redirect('community');
        }
        PageContext::$response->results = $results->data;

        //--------------------------------------
        if ($communityData->status == SUCCESS) {
            PageContext::$response->communityData = $communityData->data;
        } else {
            Messages::setPageMessage($communityData->message, ERROR_CLASS);
            $this->redirect('community');
        }
        //--------------------------------------
        PageContext::addJsVar('ALIAS', $alias);
        PageContext::addJsVar('LAZYCOUNT', LAZYLOAD_COUNT);
        PageContext::addJsVar('TOTAL_PAGES', $members->memberCount / LAZYLOAD_COUNT);
        PageContext::addScript('communitymember_lazyload.js');
        PageContext::$response->tojoin = '';
        PageContext::$response->sess_user_id = Utils::getAuth('user_id');


        if (PageContext::$response->sess_user_id > 0) {
            $share_array = array();
            $feed_array = array();
            $search = $_GET['search'];
            PageContext::$response->search = $search;

            //-------------Share------------------------
            if ($search == '' OR $search == 'S') {
                $shares = Feed::getFriendShares();
                foreach ($shares->records AS $share_item) {
                    $share_array[strtotime($share_item->share_date)][] = (array)$share_item;
                }
            }

            //----------------------Announcemnet -----------

            if ($search == '' OR $search == 'A' OR $search == 'S') {
                if ($search != 'S') {
                    $feeds = Feed::listUserFeeds('', $searchfeed = '', 1, 5);
                }

                foreach ($feeds->records AS $feed_item) {
                    $feed_array[strtotime($feed_item->community_announcement_date)][] = (array)$feed_item;
                }

                //----------News feed (Share+announcement)-------------
                $news_array = $share_array + $feed_array;
                krsort($news_array);
                PageContext::$response->feeds = $news_array;
                //--------------------Feed Comments----------------

                foreach (PageContext::$response->communityAnnouncements AS $news) {
                        if ($news->community_announcement_id) {
                            $comments = Feed::getAnnouncementComments($news->community_announcement_id);
                             foreach($comments->records as $value) {
                   //   echopre1($value);
                  // $replies = Feed::showFeedCommentReply($value->news_feed_comments_id); 
                   $like_user_comment_comments2 = Business::showGrpCommentOfCommentsLikeUser($value->announcement_comment_id); 
                  // echopre($like_user_comment_comments1);
                foreach($like_user_comment_comments2 as $data3){
                 //   echo $data2->user_name;
                    $name2 .=  $data3->user_name.",";
                }
                $name2 = rtrim($name2, ",");
                $comments->records['users']= $name2; 
                 $value->user_image=User::getUserDetail($value->user_id)->data->Image;

                }
                        }
                         $news_feed_like_users = Feed::getGroupCommentsLikesUsers($news->community_announcement_id);
               // echopre1($news_feed_like_users);
                        PageContext::$response->newsFeedLikeUsers[$news->community_announcement_id] = $news_feed_like_users;
                        PageContext::$response->Comments[$news->community_announcement_id] = $comments->records;
                        PageContext::$response->Page[$news->community_announcement_id]['totpages'] = $comments->totpages;
                        PageContext::$response->Page[$news->community_announcement_id]['currentpage'] = $comments->currentpage;
                }
            }
        }

        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function addannouncementsfeeds()
    {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        PageContext::$response->activeSubMenu = 'community';
        $title = $_POST['title'];
        $desc = $_POST['desc'];

        $mode = $_POST['mode'];
        $announcmentArr['community_id'] = $_POST['communityId'];
        $announcmentArr['community_announcement_title'] = Utils::escapeString($title);
        $announcmentArr['community_announcement_content'] = Utils::escapeString($desc);
        $announcmentArr['community_announcement_date'] = date('Y-m-d H:i:s', strtotime('now'));
        $announcmentArr['community_announcement_created_by'] = $_SESSION['default_user_id'];
        $announcmentArr['community_announcement_status'] = $_POST['status'];
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {

            $objUserRes->status = ERROR;
            $objUserRes->message['msg'] = "Please Upload File";
            $div = 'error_div';
        }
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {

            $type = $_FILES['file']['type'];
            $type1 = @explode('/', $type);
            if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "File format not supported.";
                $div = 'error_div';
            }
        }
        if ($mode == "")
            $result = Communities::addAnnouncements($announcmentArr);
        else
            $result = Communities::updateAnnouncements($announcmentArr, $mode);

        $announcementCount = Communities::getAnnouncementsCount($_POST['communityId']);
        $countdata = $result . "@" . sizeof($announcementCount) . "@" . PageContext::$response->userImagePath;
        echo $countdata;
        exit;
    }

    public function uploadgroupfeed($group_id)
    {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $objUserRes = new stdClass();
        $objUserImageData = new stdClass();
        $objUserRes->status = SUCCESS;
        $div = 'success_div';

        list($width, $height, $type, $attr) = getimagesize($_FILES["file"]['tmp_name']);
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message['msg'] = "Please Upload File";
            $div = 'error_div';
        }
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
            $type = $_FILES['file']['type'];
            $type1 = @explode('/', $type);
            if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "File format not supported.";
                $div = 'error_div';
            }
        }
        if ($objUserRes->status == SUCCESS) {

            $objUserImageData->community_announcement_user_id = PageContext::$response->sess_user_id;
            $objUserImageData->community_id = $group_id;
            $objUserImageData->file = $_FILES['file'];
            $objUserImageData->community_announcement_content = '';
            $objUserRes->message = User::addGroupNewsfeedImage($objUserImageData, $width, $height);
            $div = $objUserRes->message['msgcls'];
            PageContext::$response->file = $objUserRes->message['file'];
            PageContext::$response->feed_image_id = $objUserRes->message['image_id'];
        }
        PageContext::$response->message['msg'] = $objUserRes->message['msg'];
        PageContext::$response->message['msgClass'] = $div;
    }

    public function updategroupfeed()
    {
        $comment = $_POST['comment'];
        $id = $_POST['id'];
        $community_id = $_POST['community_id'];

        $data = array('community_announcement_content' => $comment,
            'community_id' => $community_id
        );
        
                $objUserRes = new stdClass();
        $objUserImageData = new stdClass();
        $objUserRes->status = SUCCESS;
        $div = 'success_div';

        list($width, $height, $type, $attr) = getimagesize($_FILES["file"]['tmp_name']);
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message['msg'] = "Please Upload File";
            $div = 'error_div';
        }
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
            $type = $_FILES['file']['type'];
            $type1 = @explode('/', $type);
            if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "File format not supported.";
                $div = 'error_div';
            }
        }
        if ($objUserRes->status == SUCCESS) {

            $objUserImageData->community_announcement_user_id = PageContext::$response->sess_user_id;
            $objUserImageData->community_id = $community_id;
            $objUserImageData->file = $_FILES['file'];
            $objUserImageData->community_announcement_content = '';
            $objUserRes->message = User::addGroupNewsfeedImage($objUserImageData, $width, $height);
            $div = $objUserRes->message['msgcls'];
            PageContext::$response->file = $objUserRes->message['file'];
            PageContext::$response->feed_image_id = $objUserRes->message['image_id'];
        }
        //$id=(PageContext::$response->feed_image_id)?PageContext::$response->feed_image_id:$id;
        $new_id = User::changeGroupfeedComment($data, PageContext::$response->feed_image_id);
        if ($id > 0) {

        } else {
            $id = $new_id;
        }
         PageContext::addScript('profile.js');
        
        $community_details = Communities::getCommunityAlias($community_id);
        
        PageContext::$response->community_image = $community_details->data->file_path;
        $id=(PageContext::$response->feed_image_id)?PageContext::$response->feed_image_id:$id;
        $news_feed = Communities::getAnnouncementDetailById($id);
        //print_r($news_feed);exit;
        
        PageContext::$response->news_feed = $news_feed;
        $msg = 'Successfully saved newsfeed';
        
        PageContext::$full_layout_rendering = false;
//        print_r($this->view);
        $this->view->disableLayout();
    }

    public function uploadimagereplysubmitcommunity($id)
    {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $objUserRes = new stdClass();
        $objUserImageData = new stdClass();
        $objUserRes->status = SUCCESS;
        $div = 'success_div';
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message['msg'] = "Please Upload File";
            $div = 'error_div';
        }
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
            $type = $_FILES['file']['type'];
            $type1 = @explode('/', $type);
            if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "File format not supported.";
                $div = 'error_div';
            }
        }
        if ($objUserRes->status == SUCCESS) {
            $objUserImageData->user_id = PageContext::$response->sess_user_id;
            $objUserImageData->file = $_FILES['file'];
            $objUserImageData->announcement_id = $id;
            $objUserImageData->comment_id = '';
            $objUserImageData->announcement_image_date = date('m/d/Y');
             list($width, $height, $type, $attr) = getimagesize($_FILES["file"]['tmp_name']);
            $objUserRes->message = User::addCommentImage($objUserImageData,$width, $height);
            $div = $objUserRes->message['msgcls'];
            PageContext::$response->file = $objUserRes->message['file'];
            //PageContext::$response->image_id = '';
            PageContext::$response->feed_image_id = $objUserRes->message['image_id'];


        }

        PageContext::$response->message['msg'] = $objUserRes->message['msg'];
        PageContext::$response->message['msgClass'] = $div;

    }

    public function organizationdiscussion()
    {
        PageContext::addScript('organisation.js');
        PageContext::addScript('profile.js');
        $alias = $_POST['alias'];
        $organizationData = Business::getBusinessId($alias);
        //echopre1($organizationData);
        if($organizationData->data->business_id){
        $org_details = Business::getBusinessById($organizationData->data->business_id);
        }
        PageContext::$response->organizationimage = $org_details->data->file_path;
        if($organizationData->data->business_id){
        PageContext::$response->Total_records = Business::getAnnouncements('',$organizationData->data->business_id,'');
        }
        $Total_records_count = count(PageContext::$response->Total_records->data);
        PageContext::$response->total_count = $Total_records_count/5;
        // PageContext::addJsVar('TOTAL_ORG_FEED_PAGES',$Total_records_count/PAGE_LIST_COUNT);
        if($organizationData->data->business_id){
        $organizationAnnouncement = Business::getAnnouncements(1,$organizationData->data->business_id,5);
        }
        
        PageContext::$response->organizationAnnouncements = $organizationAnnouncement->data;
        PageContext::$response->organizationId = $organizationData->data->business_id;
        PageContext::$response->organizationAlias = $alias;
        
        foreach (PageContext::$response->organizationAnnouncements AS $news) {
            if ($news['organization_announcement_id']) {
                $comments = Business::getAnnouncementComments($news['organization_announcement_id']);
                    foreach($comments->records as $value) {
                    //  echopre1($value);
                  // $replies = Feed::showFeedCommentReply($value->news_feed_comments_id); 
                   $like_user_comment_comments1 = Business::showOrgCommentOfCommentsLikeUser($value->organization_announcement_comment_id); 
                  // echopre($like_user_comment_comments1);
                foreach($like_user_comment_comments1 as $data2){
                 //   echo $data2->user_name;
                    $name1 .=  $data2->user_name.",";
                }
                $name1 = rtrim($name1, ",");
                $comments->records['users']= $name1; 
                $value->user_image=User::getUserDetail($value->user_id)->data->Image;
                }
            }
            
              $news_feed_like_users = Business::getOrganizationCommentsLikesUsers($news['organization_announcement_id']);
               // echopre1($news_feed_like_users);
            PageContext::$response->newsFeedLikeUsers[$news['organization_announcement_id']] = $news_feed_like_users;
            PageContext::$response->Comments[$news['organization_announcement_id']] = $comments->records;
            PageContext::$response->Page[$news['organization_announcement_id']]['totpages'] = $comments->totpages;
            PageContext::$response->Page[$news['organization_announcement_id']]['currentpage'] = $comments->currentpage;
        }
        if($organizationData->data->business_id){
        PageContext::$response->gallery_display_list = Business::getMyLatestDiscussionImage($organizationData->data->business_id);
        }
       // echopre(PageContext::$response->gallery_display_list);
        if($organizationData->data->business_id){
        $associates = User::getAllAssociatesByBusiness($organizationData->data->business_id, 1, 3);
        }
        PageContext::$response->friend_display_list = $associates->records;
        $associate = $associates->records;
        $tagged = array();
        foreach($associate as $data){
            $tagged[]= $data->user_id;
         }
         PageContext::$response->is_associate=User::checkif_businessassociate($organizationData->data->business_id,PageContext::$response->sess_user_id); 
        PageContext::$response->tagged = $tagged;
        
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function organizationdiscussionajax($pagenum)
    {
        $name1 ='';
        $alias = $_POST['alias'];
        $organizationData = Business::getBusinessId($alias);
        $org_details = Business::getBusinessById($organizationData->data->business_id);
        PageContext::$response->organizationimage = $org_details->data->file_path;
        $organizationAnnouncement = Business::getAnnouncements($pagenum,$organizationData->data->business_id,5);
        PageContext::$response->organizationAnnouncements = $organizationAnnouncement->data;
        PageContext::$response->organizationId = $organizationData->data->business_id;
        foreach (PageContext::$response->organizationAnnouncements AS $news) {
            if ($news['organization_announcement_id']) {
                $comments = Business::getAnnouncementComments($news['organization_announcement_id']);
                    foreach($comments->records as $value) {
                    //  echopre1($value);
                  // $replies = Feed::showFeedCommentReply($value->news_feed_comments_id); 
                   $like_user_comment_comments1 = Business::showOrgCommentOfCommentsLikeUser($value->organization_announcement_comment_id); 
                  // echopre($like_user_comment_comments1);
                foreach($like_user_comment_comments1 as $data2){
                 //   echo $data2->user_name;
                    $name1 .=  $data2->user_name.",";
                }
                $name1 = rtrim($name1, ",");
                $comments->records['users']= $name1; 
                $value->user_image=User::getUserDetail($value->user_id)->data->Image;

                }
            }
            $news_feed_like_users = Business::getOrganizationCommentsLikesUsers($news['organization_announcement_id']);
               // echopre1($news_feed_like_users);
            PageContext::$response->newsFeedLikeUsers[$news['organization_announcement_id']] = $news_feed_like_users;

            PageContext::$response->Comments[$news['organization_announcement_id']] = $comments->records;
            PageContext::$response->Page[$news['organization_announcement_id']]['totpages'] = $comments->totpages;
            PageContext::$response->Page[$news['organization_announcement_id']]['currentpage'] = $comments->currentpage;
        }
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function uploadorganizationfeed($org_id)
    {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $objUserRes = new stdClass();
        $objUserImageData = new stdClass();
        $objUserRes->status = SUCCESS;
        $div = 'success_div';

        list($width, $height, $type, $attr) = getimagesize($_FILES["file"]['tmp_name']);
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message['msg'] = "Please Upload File";
            $div = 'error_div';
        }
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
            $type = $_FILES['file']['type'];
            $type1 = @explode('/', $type);
            if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "File format not supported.";
                $div = 'error_div';
            }
        }
        if ($objUserRes->status == SUCCESS) {

            $objUserImageData->organization_announcement_user_id = PageContext::$response->sess_user_id;
            $objUserImageData->organization_id = $org_id;
            $objUserImageData->file = $_FILES['file'];
            $objUserImageData->organization_announcement_content = '';
            $objUserRes->message = Business::addOrgNewsfeedImage($objUserImageData, $width, $height);
            $div = $objUserRes->message['msgcls'];
            PageContext::$response->file = $objUserRes->message['file'];
            PageContext::$response->feed_image_id = $objUserRes->message['image_id'];
        }
        PageContext::$response->message['msg'] = $objUserRes->message['msg'];
        PageContext::$response->message['msgClass'] = $div;
    }

    public function updateorganizationfeed()
    {
        $comment = $_POST['comment'];
        $id = $_POST['id'];
        $community_id = $_POST['organization_id'];
        $objUserRes->status = SUCCESS;
        $data = array('organization_announcement_content' => $comment,
            'organization_id' => $community_id
        );
        
           list($width, $height, $type, $attr) = getimagesize($_FILES["file"]['tmp_name']);
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message['msg'] = "Please Upload File";
            $div = 'error_div';
        }
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') { 
            $type = $_FILES['file']['type'];
            $type1 = @explode('/', $type);
            if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "File format not supported.";
                $div = 'error_div';
            }
        }
        if ($objUserRes->status == SUCCESS) {

            $objUserImageData->organization_announcement_user_id = PageContext::$response->sess_user_id;
            $objUserImageData->organization_id = $community_id;
            $objUserImageData->file = $_FILES['file'];
            $objUserImageData->organization_announcement_content = '';
            //echopre1($objUserImageData);exit;
            $objUserRes->message = Business::addOrgNewsfeedImage($objUserImageData, $width, $height);
//            echopre1($objUserRes->message);exit;
            $div = $objUserRes->message['msgcls'];
            PageContext::$response->file = $objUserRes->message['file'];
            PageContext::$response->feed_image_id = $objUserRes->message['image_id'];
        } 

        $new_id = Business::changeOrgfeedComment($data, PageContext::$response->feed_image_id);
        if ($id > 0) {

        } else {
            $id = $new_id;
        }
        
        $org_details = Business::getBusinessById($community_id);
        PageContext::$response->organizationimage = $org_details->data->file_path;
         $id=(PageContext::$response->feed_image_id)?PageContext::$response->feed_image_id:$id;
        $news_feed = Business::getAnnouncementDetailById($id);
        
        PageContext::$response->news_feed = $news_feed;
        $msg = 'Successfully saved newsfeed';
        
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
     }
     
     public function postMyLikeOrganization()
    {
        $data = array(
            'organization_id' => $_POST['org_id'],
            'announcement_id' => $_POST['announcement_id'],
            'user_id' => PageContext::$response->sess_user_id,
            'user_name' => PageContext::$response->sess_user_name,
            'like_date' => date('Y-m-d')
        );

        $like = Feed::postLikeOrganization($data);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }
    
     public function uploadorganizationimagesubmit($id)
    {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $objUserRes = new stdClass();
        $objUserImageData = new stdClass();
        $objUserRes->status = SUCCESS;
        $div = 'success_div';
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message['msg'] = "Please Upload File";
            $div = 'error_div';
        }
        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
            $type = $_FILES['file']['type'];
            $type1 = @explode('/', $type);
            if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "File format not supported.";
                $div = 'error_div';
            }
        }
        if ($objUserRes->status == SUCCESS) {
            $objUserImageData->user_id = PageContext::$response->sess_user_id;
            $objUserImageData->file = $_FILES['file'];
            $objUserImageData->announcement_id = $id;
            $objUserImageData->comment_id = '';
            $objUserImageData->announcement_image_date = date('m/d/Y');
             list($width, $height, $type, $attr) = getimagesize($_FILES["file"]['tmp_name']);
            $objUserRes->message = Business::addCommentImage($objUserImageData,$width, $height);
            $div = $objUserRes->message['msgcls'];
            PageContext::$response->file = $objUserRes->message['file'];
            //PageContext::$response->image_id = '';
            PageContext::$response->feed_image_id = $objUserRes->message['image_id'];
        }

        PageContext::$response->message['msg'] = $objUserRes->message['msg'];
        PageContext::$response->message['msgClass'] = $div;

    }
    
     public function postorganizationfeedcomment()
    {
        $data_array = array(
            'announcement_id' => $_POST['announcement_id'],
            'organization_id' => $_POST['organization_id'],
            'comment_content' => Utils::escapeString($_POST['comments']),
            'comment_date' => date('Y-m-d h:i:s'),
            'user_id' => PageContext::$response->sess_user_id,
            'user_name' => PageContext::$response->sess_user_name,
            'parent_comment_id' => $_POST['comment_id'],
            'comment_status' => 'A'
        );
        $comments = array();
        $comments['name'] = PageContext::$response->sess_user_name;
        $comments['image'] = PageContext::$response->sess_user_image;

        $comments['comment'] = Business::postComments($data_array, $_POST['comments']);
        $data = array('announcement_image_status' => 'A', 'comment_id' => $comments['comment']['comment_id']);
        $id = $_POST['image_id'];
        if ($id != 'undefined') {
            $objUserRes = Business::UpdateCommentImage($data, $id);
        }
        $comments['parent_comment_id'] = $_POST['comment_id'];
        $comments['organization_id'] = $_POST['organization_id'];
        PageContext::$response->image_file = $objUserRes;
        PageContext::$response->comments = $comments;
        PageContext::$response->alias = PageContext::$response->sess_user_alias;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }
    
    public function uploadimagereplysubmitorganization($id){
        PageContext::$full_layout_rendering                 = false;
        $this->view->disableLayout();
        $objUserRes = new stdClass();
    	$objUserImageData = new stdClass();
    	$objUserRes->status = SUCCESS;
    	$div = 'success_div';
       if(isset($_FILES['file']['name']) && $_FILES['file']['name'] == '' )
    	{
    		$objUserRes->status = ERROR;
    		$objUserRes->message['msg'] = "Please Upload File";
    		$div = 'error_div';
    	}
    	if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != '' )
    	{
    		$type = $_FILES['file']['type'];
    		$type1 = @explode('/', $type);
    		if($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))){
    		$objUserRes->status = ERROR;
    		$objUserRes->message['msg'] = "File format not supported.";
    		$div = 'error_div';
    		}
    	}
    	if($objUserRes->status == SUCCESS)
    	{
            $objUserImageData->user_id = PageContext::$response->sess_user_id;
    		$objUserImageData->file = $_FILES['file'];
                $objUserImageData->announcement_id = $id;
                $objUserImageData->comment_id = '';
    		$objUserImageData->announcement_image_date = date('m/d/Y');
                list($width, $height, $type, $attr) = getimagesize($_FILES["file"]['tmp_name']);
    		$objUserRes->message = Business::addCommentImage($objUserImageData,$width, $height);
    		$div = $objUserRes->message['msgcls'];
    		PageContext::$response->file = $objUserRes->message['file'];
                //PageContext::$response->image_id = '';
                PageContext::$response->feed_image_id = $objUserRes->message['image_id'];
                
                
    	}
    	
    	PageContext::$response->message['msg'] = $objUserRes->message['msg'];
    	PageContext::$response->message['msgClass'] = $div;
    	                  
    }
    
    public function showorgcommentreply()
    {
        $comment_id = $_POST['comment_id'];
        $replies = Business::showCommentReply($comment_id);
        foreach($replies->records as $value)
        {
            $value->user_image=User::getUserDetail($value->user_id)->data->Image;
        }
        PageContext::$response->Comments = $replies->records;
        PageContext::$response->TotalPage = $replies->totpages;
        PageContext::$response->CurrentPage = $replies->currentpage;
        PageContext::$full_layout_rendering = false;
//        echopre($replies);
//        print_r($this->view);
        $this->view->disableLayout();

    }
    
    public function postorgCommentLike()
    {
        $data = array('comment_id' => $_POST['comment_id'],
            'announcement_id' => $_POST['announcement_id'],
            'user_id' => PageContext::$response->sess_user_id,
            'user_name' => PageContext::$response->sess_user_name,
            'like_date' => date('Y-m-d')
        );
        $like = Business::postCommentLike($data);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }
    
    public function orgfeeddelete()
    {
       // $comment_id = $_POST['comment_id'];
        $announcement_id = $_POST['announcement_id'];
        Business::deleteOrgFeeds($announcement_id);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }
    
    public function groupfeeddelete()
    {
       // $comment_id = $_POST['comment_id'];
        $announcement_id = $_POST['announcement_id'];
        Communities::deleteGroupFeeds($announcement_id);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }
    
      public function profiledelete()
    {
       // $comment_id = $_POST['comment_id'];
        $profile_id = PageContext::$response->sess_user_id;
        Communities::deleteProfile($profile_id);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }
    
    public function newsfeeddelete()
    {
       // $comment_id = $_POST['comment_id'];
        $announcement_id = $_POST['announcement_id'];
        Communities::deleteNewsFeeds($announcement_id);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }
    
    public function feedOrganizationCommentDelete()
    {
        $comment_id = $_POST['comment_id'];
        $announcement_id = $_POST['announcement_id'];
        Business::deleteOrgComments($comment_id, $announcement_id);
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }
    
    public function inboxMessages(){
        $messages = Connections::getAllNewMessages(); 
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
         $object = new stdClass();
foreach ($messages as $key => $value)
{
    $object->$key = $value;
}
    echo json_encode($object);         exit;
    }
}

?>
