<?

	/*==================================================================*\
	######################################################################
	#                                                                    #
	# Copyright 2005 Arca Solutions, Inc. All Rights Reserved.           #
	#                                                                    #
	# This file may not be redistributed in whole or part.               #
	# eDirectory is licensed on a per-domain basis.                      #
	#                                                                    #
	# ---------------- eDirectory IS NOT FREE SOFTWARE ----------------- #
	#                                                                    #
	# http://www.edirectory.com | http://www.edirectory.com/license.html #
	######################################################################
	\*==================================================================*/

	# ----------------------------------------------------------------------------------------------------
	# * FILE: /members/index.php
	# ----------------------------------------------------------------------------------------------------

	# ----------------------------------------------------------------------------------------------------
	# LOAD CONFIG
	# ----------------------------------------------------------------------------------------------------
	include("../conf/loadconfig.inc.php");

	# ----------------------------------------------------------------------------------------------------
	# SESSION
	# ----------------------------------------------------------------------------------------------------
	sess_validateSession();

	# ----------------------------------------------------------------------------------------------------
	# AUX
	# ----------------------------------------------------------------------------------------------------
	$account = new Account(sess_getAccountIdFromSession());
	$has_profile = $account->getString("has_profile");
	$is_sponsor = $account->getString("is_sponsor");
    $welcomeMessage = false;
    $accActive = $account->getString("active");
    
    if (SOCIALNETWORK_FEATURE == "on") {
        $profileObj = new Profile($account->getNumber("id"));
        if ($profileObj->getString("profile_complete") == "n") {
            $welcomeMessage = true;
        }
    }

	if ($is_sponsor == 'n') {
		if (!empty($_SESSION[SM_LOGGEDIN])) {
			header("Location: ".DEFAULT_URL."/".MEMBERS_ALIAS."/account/account.php");
			exit;
		}
	}

	$contact = db_getFromDB("contact", "account_id", db_formatNumber($account->getNumber("id")), "1");

	if ($_GET["enable"] == "true") {
		$account->changeProfileStatus(true);
		header("Location: ".DEFAULT_URL."/".MEMBERS_ALIAS."/index.php?success=1&type=1");
		exit;
	}

	# ----------------------------------------------------------------------------------------------------
	# CODE
	# ----------------------------------------------------------------------------------------------------
    //Get Recent Activities
    $deals = system_getUserActivities("deals", 4);
    $reviews = system_getUserActivities("reviews", 4);
    $favorites = system_getUserActivities("favorites", 4);
    
    if ($_SERVER['REQUEST_METHOD'] == "POST") {

        if ($_POST["hiddenValue"]) {
			$reviewObj = new Review($_POST["hiddenValue"]);

			$item_type = $reviewObj->getString("item_type");
			$item_id = $reviewObj->getNumber("item_id");

			$reviewObj->Delete();

			$avg = $reviewObj->getRateAvgByItem($item_type, $item_id);
			if (!is_numeric($avg)) $avg = 0;

			if ($item_type == "listing") {
				$listing = new Listing();
				$listing->setAvgReview($avg, $item_id);
			} elseif ($item_type == "article") {
				$articles = new Article();
				$articles->setAvgReview($avg, $item_id);
			} elseif ($item_type == "promotion"){
                $promotions = new Promotion();
				$promotions->setAvgReview($avg, $item_id);
            }
			
            header("Location: ".DEFAULT_URL."/".MEMBERS_ALIAS."/index.php?messageDel=1");
            exit;
			
		}
        
    }
        
	/*
	 * Preparing to get all items of all domains of account
	 */
	unset($accountObj);
	$accountObj = new Account_Domain();
	$array_domains = $accountObj->getAll(sess_getAccountIdFromSession());
	
	unset($array_tables);
	$array_tables[] = "Listing";
	$array_tables[] = "Banner";
	$array_tables[] = "Event";
	$array_tables[] = "Classified";
	$array_tables[] = "Article";
	

	$array_account_items = array();
	$j = 0;
	for($i=0;$i<count($array_domains);$i++){

		unset($domainObj, $array_items);
		$domainObj = new Domain($array_domains[$i]);

		/*
		 * Get Items
		 */
		$array_items = $accountObj->getAllItemsByAccountID(sess_getAccountIdFromSession(),$array_domains[$i],$array_tables);
		if(is_array($array_items)){
			$array_account_items[$j]["domain_id"]    = $array_domains[$i];
			$array_account_items[$j]["domain_title"] = $domainObj->getString("name");
			$array_account_items[$j]["domain_url"]   = $domainObj->getString("url");
			$array_account_items[$j]["items"]		 = $array_items;
			$j++;
		}
	}

	
	# ----------------------------------------------------------------------------------------------------
	# HEADER
	# ----------------------------------------------------------------------------------------------------
	include(MEMBERS_EDIRECTORY_ROOT."/layout/header.php");

	# ----------------------------------------------------------------------------------------------------
	# NAVBAR
	# ----------------------------------------------------------------------------------------------------
	include(MEMBERS_EDIRECTORY_ROOT."/layout/navbar.php");

?>
    <script language="javascript" type="text/javascript" src="<?=DEFAULT_URL?>/scripts/activationEmail.js"></script>

	<script language="javascript" type="text/javascript">

		function enableProfile() {
			var is_sponsor = '<?=$is_sponsor?>';
			var success = '<?=$_GET["success"]?>';
			var type = '<?=$_GET["type"]?>';
			if (success == 1 && type == 1) {
				showTabs('tab_2');
			} else if (is_sponsor == 1 || is_sponsor == 'y') {
				$('#tab_1').css('display', '');
				$('#member_options').css('display', '');
				showTabs('tab_1');
			} else {
				$('#tab_1').css('display', 'none');
				$('#member_options').css('display', 'none');
				showTabs('tab_2');
			}
		}

		function showTabs(type) {
			if (type == 'tab_1') {
				$('#tab_2').removeClass("tabActived");
				$('#tab_1').addClass("tabActived");
				$('#member_options').css('display', '');
				$('#member_profile').css('display', 'none');
			} else {
				$('#tab_1').removeClass("tabActived");
				$('#tab_2').addClass("tabActived");
				$('#member_profile').css('display', '');
				$('#member_options').css('display', 'none');
			}
		}
        
        function closeMessage(acc_id) {
            $.get("<?=DEFAULT_URL."/".MEMBERS_ALIAS."/account/complete.php"?>", {
                acc_id: acc_id
            }, function () {
                $("#boxWelcome").css("display", "none");
            });
        }
	</script>

	<div class="content">

		<? require(EDIRECTORY_ROOT."/".SITEMGR_ALIAS."/registration.php"); ?>
		<? require(EDIRECTORY_ROOT."/includes/code/checkregistration.php"); ?>
		<? require(EDIRECTORY_ROOT."/frontend/checkregbin.php"); ?>

        <? if ($welcomeMessage) { ?>
            <div id="boxWelcome">
                
                <h2><?=string_strtoupper(LANG_LABEL_WELCOME);?></h2>
                
                <blockquote class="high">
                    
                    <p class="successMessage" id="messageEmail" style="display:none"><?=system_showText(LANG_LABEL_ACTIVATEEMAIL_SENT);?></p>
                    <p class="errorMessage" id="messageEmailError" style="display:none"></p>
                    
                    <a href="javascript: void(0);" onclick="closeMessage(<?=(sess_getAccountIdFromSession() ? sess_getAccountIdFromSession() : 0)?>);" class="remove"></a>

                    <p><?=($accActive == "y" ? system_showText(LANG_LABEL_PROFILE_WELCOME_ACT) : system_showText(LANG_LABEL_PROFILE_WELCOME_NOTACT))?></p>

                    <? if ($accActive == "y") { ?>
                        <a href="<?=DEFAULT_URL."/".MEMBERS_ALIAS."/account/account.php?id=".sess_getAccountIdFromSession()?>"><?=system_showText(LANG_LABEL_PROFILE_COMPLETE);?></a>
                    <? } else { ?>
                        <p><a href="javascript: void(0);" onclick="sendEmailActivation(<?=(sess_getAccountIdFromSession() ? sess_getAccountIdFromSession() : 0)?>);"><?=system_showText(LANG_MSG_CLICKTO);?></a> <?=system_showText(LANG_LABEL_ACTIVATEEMAIL_GETNEW);?> <img id="loadingEmail" src="<?=DEFAULT_URL?>/images/img_loading.gif" width="15px;" style="display: none;" /></p>
                    <? } ?>
                </blockquote>
                
            </div>
        <? } ?>
        	
        <? if (SOCIALNETWORK_FEATURE == "on") { ?>
        
            <h2><?=system_showText(LANG_LABEL_PROFILE_RECENT_ACTIVITY);?></h2>
            
            <? if ($deals || $reviews || $favorites) { ?>

                <? if ($reviews) {

                    if ($_GET["messageDel"] == 1) { ?>
                        <p class="successMessage"><?=system_showText(LANG_MSG_REVIEW_SUCCESS_DELETED);?></p>
                    <? } ?>

                    <div id="reviews" style="display:none">
                        <form name="reviews_post" id="reviews_post" action="<?=system_getFormAction($_SERVER["PHP_SELF"])?>" method="post">
                            <input type="hidden" name="hiddenValue" />
                        </form>
                    </div>

                    <div class="member-activity cont_100">
                        
                        <h2><?=system_showText(LANG_REVIEW_PLURAL);?></h2>
                        
                        <?
                        $counterReviews = 0;
                        foreach ($reviews as $k => $row) {

                            $reviewStatus = $row["approved"];

                            if ($row["item_type"] == "listing") {

                                $itemTitle = $row["title"];
                                unset($listing);
                                $listing = new Listing($row["id"]);

                                $levelObj = new ListingLevel();
                                if ($levelObj->getDetail($listing->getString('level')) == "y") {
                                    $itemLink = "<a href=\"".LISTING_DEFAULT_URL."/".$listing->getString("friendly_url").".html\">$itemTitle</a>";
                                } else {
                                    $itemLink = "<a href=\"".LISTING_DEFAULT_URL."/results.php?id=".$listing->getString("id")."\">$itemTitle</a>";
                                }

                            } else if ($row["item_type"] == "article") {

                                $itemTitle = $row["title"];
                                unset($article);
                                $article = new Article($row["id"]);

                                $itemLink = "<a href=\"".ARTICLE_DEFAULT_URL."/".$article->getString("friendly_url").".html\">$itemTitle</a>";

                            } elseif ($row["item_type"] == "promotion") {

                                $itemTitle = $row["name"];
                                unset($promotion);
                                $promotion = new Promotion($row["id"]);

                                $listingObj = new Listing($promotion->getNumber("listing_id"));
                                $levelObj = new ListingLevel(true);

                                if (!$promotion->getNumber("id") || $promotion->getNumber("id") <= 0 || !$listingObj->getNumber("id") || $listingObj->getNumber("id") <= 0 || $listingObj->getString("status") != "A" || $levelObj->getHasPromotion($listingObj->getNumber("level")) != "y" || (!validate_date_deal($promotion->getDate("start_date"), $promotion->getDate("end_date"))) || (!validate_period_deal($promotion->getNumber("visibility_start"), $promotion->getNumber("visibility_end")))) {
                                    $itemLink = $itemTitle;
                                } else {
                                    $itemLink = "<a href=\"".PROMOTION_DEFAULT_URL."/".$promotion->getString("friendly_url").".html\">$itemTitle</a>";
                                }
                            }

                            $linkView = DEFAULT_URL."/".MEMBERS_ALIAS."/account/reviews.php?idView=".$row["rID"];
                            
                            $counterReviews++;

                        ?>

                            <div class="cont_50">

                                <div class="activity">
                                    <p><?=system_showText(LANG_LABEL_PROFILE_REVIEWON);?> <?=$itemLink;?></p>
                                </div>

                                <div class="option">
                                    <em class="status-<?=($reviewStatus == 1 ? "active" : "pending")?>"><?=($reviewStatus == 1 ? system_showText(LANG_LABEL_ACTIVE) : system_showText(LANG_LABEL_PENDING))?></em>
                                    <span><a href="<?=$linkView;?>"><?=system_showText(LANG_LABEL_VIEW);?></a> | <a href="javascript:void(0);" onclick="dialogBox('confirm', '<?=system_showText(LANG_MESSAGE_MSGAREYOUSURE);?>', '<?=$row["rID"];?>', 'reviews_post', '150','<?=system_showText(LANG_BUTTON_OK);?>','<?=system_showText(LANG_BUTTON_CANCEL);?>');" title="<?=system_showText(LANG_MSG_CLICK_TO_DELETE_THIS_REVIEW);?>"><?=system_showText(LANG_LABEL_DELETE);?></a></span>
                                </div>

                            </div>
                        
                            <? if ($counterReviews == 2) { ?>
                                <br class="clear" />
                            <? 
                                $counterReviews = 0;
                                }
                        } ?>

                    </div>

                <? }
                        
                if ($favorites) {
                    
                    $auxListing = new Listing();
                    $auxClassified = new Classified();
                    $auxEvent = new Event();
                    $auxArticle = new Article();
                    $levelObjListing = new ListingLevel(true);
                    $levelObjClassified = new ClassifiedLevel(true);
                    $levelObjEvent = new EventLevel(true);
                ?>
                        
                    <div class="member-activity cont_100">

                        <h2><?=system_showText(LANG_LABEL_FAVORITES);?></h2>
                        
                        <?
                        $counterFavs = 0;
                        foreach ($favorites as $favorite) {

                            if ($favorite->getString("status") == "A") {
                                
                                if ($favorite instanceof $auxListing) {

                                    $type = "listing";
                                    $label = system_showText(LANG_LISTING_FEATURE_NAME);

                                    if ($levelObjListing->getDetail($favorite->getNumber("id")) == "y") {
                                        $detailLink = "".LISTING_DEFAULT_URL."/".htmlspecialchars($favorite->getString("friendly_url")).".html";
                                    } else {
                                        $detailLink = "".LISTING_DEFAULT_URL."/results.php?id=".htmlspecialchars($favorite->getString("id"))."";
                                    }
                                    $itemName = $favorite->getString("title");


                                } elseif ($favorite instanceof $auxClassified) {

                                    $type = "classified";
                                    $label = system_showText(LANG_CLASSIFIED_FEATURE_NAME);

                                    $detailLink = "";
                                    if ($levelObjClassified->getDetail($favorite->getNumber("id")) == "y") {
                                        $detailLink = "".CLASSIFIED_DEFAULT_URL."/".htmlspecialchars($favorite->getString("friendly_url")).".html";
                                    } else {
                                        $detailLink = "".CLASSIFIED_DEFAULT_URL."/results.php?id=".htmlspecialchars($favorite->getString("id"))."";
                                    }
                                    $itemName = $favorite->getString("title");

                                } elseif ($favorite instanceof $auxEvent) {

                                    $type = "event";
                                    $label = system_showText(LANG_EVENT_FEATURE_NAME);

                                    $detailLink = "";
                                    if ($levelObjEvent->getDetail($favorite->getNumber("id")) == "y") {
                                        $detailLink = "".EVENT_DEFAULT_URL."/".htmlspecialchars($favorite->getString("friendly_url")).".html";
                                    } else {
                                        $detailLink = "".EVENT_DEFAULT_URL."/results.php?id=".htmlspecialchars($favorite->getString("id"))."";
                                    }
                                    $itemName = $favorite->getString("title");

                                } elseif ($favorite instanceof $auxArticle) {

                                    $type = "article";
                                    $label = system_showText(LANG_ARTICLE_FEATURE_NAME);

                                    $detailLink = "".ARTICLE_DEFAULT_URL."/".htmlspecialchars($favorite->getString("friendly_url")).".html";
                                    $itemName = $favorite->getString("title");

                                }

                                $remove_favorites_click = "onclick=\"itemInQuicklist('remove', '".sess_getAccountIdFromSession()."', '".$favorite->getNumber("id")."', '$type');\"";
                                
                                $counterFavs++;
                        ?>

                                <div class="cont_50">

                                    <div class="activity">
                                        <p><?=$label?> <a href="<?=$detailLink;?>"><?=$itemName;?></a></p>
                                    </div>

                                    <div class="option">
                                        <span><a href="<?=$detailLink;?>"><?=system_showText(LANG_LABEL_VIEW);?></a> | <a href="javascript:void(0);" <?=$remove_favorites_click?>><?=system_showText(LANG_QUICKLIST_REMOVE);?></a></span>
                                    </div>

                                </div>
                        
                                <? if ($counterFavs == 2) { ?>
                                    <br class="clear" />
                                <? 
                                    $counterFavs = 0;
                                    }
                        
                            } ?>
                        
                        <? } ?>
                        
                    </div>
                        
                <? }
                        
                if ($deals) { ?>
                                              
                    <div class="member-activity cont_100">
                        
                        <h2><?=system_showText(LANG_LABEL_ACCOUNT_DEALS);?></h2>
                        
                        <?
                        $counterDeals = 0;
                        foreach ($deals as $deal) {
                        
                            $promotionObj = new Promotion($deal["promotion_id"]);
                            $promotionLink = $promotionObj->getString("friendly_url").".html";
                            $listingObj = new Listing($promotionObj->getNumber("listing_id"));
                            $levelObj = new ListingLevel(true);

                            if (!$promotionObj->getNumber("id") || $promotionObj->getNumber("id") <= 0 || !$listingObj->getNumber("id") || $listingObj->getNumber("id") <= 0 || $listingObj->getString("status") != "A" || $levelObj->getHasPromotion($listingObj->getNumber("level")) != "y" || (!validate_date_deal($promotionObj->getDate("start_date"), $promotionObj->getDate("end_date"))) || (!validate_period_deal($promotionObj->getNumber("visibility_start"), $promotionObj->getNumber("visibility_end")))) {
                                unset($promotionLink);
                            }
                            
                            if ($promotionObj->getNumber("id")) {
                                
                                $counterDeals++;
                            ?>
                        
                            <div class="cont_50">
                                
                                <div class="activity">
                                    <p><?=system_showText(LANG_PROMOTION_FEATURE_NAME);?>
                                        <? if ($promotionLink) { ?>
                                        <a href="<?=PROMOTION_DEFAULT_URL?>/<?=$promotionLink?>"><?=$promotionObj->getString("name")?></a>
                                    <? } else { ?>
                                        <?=$promotionObj->getString("name")?>
                                    <? } ?>
                                    </p>
                                </div>

                                <div class="option">
                                    
                                    <em><?=format_date($deal["datetime"], DEFAULT_DATE_FORMAT)?></em>
                                    
                                    <? if ($promotionLink) { ?>
                                        <span><a href="<?=PROMOTION_DEFAULT_URL?>/<?=$promotionLink?>"><?=system_showText(LANG_LABEL_VIEW);?></a></span>
                                    <? } ?>
                                        
                                </div>
                            </div>
                        
                            <? if ($counterDeals == 2) { ?>
                                <br class="clear" />
                            <? 
                                $counterDeals = 0;
                                }
                        
                            } ?>
                        
                        <? } ?>
                        
                    </div>
                        
                <? } ?>

            <? } else { ?>

                <blockquote class="low">
                    <p><?=system_showText(LANG_LABEL_PROFILE_RECENT_ACTIVITY_EMPTY);?></p>
                </blockquote>

            <? } ?>

            <div class="clear"></div>
        
        <? } ?>
		
		<? if ($is_sponsor == "y") { ?>
			<h2><?=LANG_SITE_ITEMS?></h2> 
		<? } else if ($has_profile == "y") { ?>
			<h2><?=system_showText(LANG_MSG_WELCOME2);?></h2>
        <?
		}

		$contentObj = new Content();
		$content = $contentObj->retrieveContentByType("Sponsor Home");
		if ($content) {
			echo "<blockquote>";
				echo "<div class=\"dynamicContent\">".$content."</div>";
			echo "</blockquote>";
		}
		
		if ($_GET["success"] == 1) { ?>
			<p class="successMessage">
				<?=system_showText(LANG_MSG_PROFILE_ENABLED);?>
			</p>
			<?
		}
		
		/*
		 * Show all items by account
		 */
		if (count($array_account_items) > 0){
			for($i=0;$i<count($array_account_items);$i++){
				?>

				<div class="domainItems">
					<h2 class="domainItemsTitle">
						<?=$array_account_items[$i]["domain_title"];?>
					</h2>

						<?

						for($j=0;$j<count($array_account_items[$i]["items"]);$j++){

							/*
							 * Prepare module name
							 */
							unset($aux_module_name);
							if($array_account_items[$i]["items"][$j]["table"] == "Listing"){
								$aux_module_name = string_ucwords(LANG_LISTING_FEATURE_NAME);
							}elseif($array_account_items[$i]["items"][$j]["table"] == "Event"){
								$aux_module_name = string_ucwords(LANG_EVENT_FEATURE_NAME);
							}elseif($array_account_items[$i]["items"][$j]["table"] == "Classified"){
								$aux_module_name = string_ucwords(LANG_CLASSIFIED_FEATURE_NAME);
							}elseif($array_account_items[$i]["items"][$j]["table"] == "Article"){
								$aux_module_name = string_ucwords(LANG_ARTICLE_FEATURE_NAME);
							}elseif($array_account_items[$i]["items"][$j]["table"] == "Banner"){
								$aux_module_name = string_ucwords(LANG_BANNER_FEATURE_NAME);
							}


							for($k=0;$k<count($array_account_items[$i]["items"][$j]["items"]);$k++){
								unset($item_link);
								$item_link = "/".string_strtolower($array_account_items[$i]["items"][$j]["table"])."/".string_strtolower(($array_account_items[$i]["items"][$j]["table"] == "Banner" ? "edit" : $array_account_items[$i]["items"][$j]["table"])).".php?id=".$array_account_items[$i]["items"][$j]["items"][$k]["id"];
								?>
								<div class="domainItemsList">
									<div class="itemName">

										<a href="javascript:void(0)" onclick="changeDomainInfo(<?=$array_account_items[$i]["domain_id"];?>,'<?=DEFAULT_URL?>/<?=MEMBERS_ALIAS?>','<?=$item_link?>','?id=<?=$array_account_items[$i]["items"][$j]["items"][$k]["id"]?>',true)">
											<?
											if($array_account_items[$i]["items"][$j]["table"] == "Banner"){
												echo $array_account_items[$i]["items"][$j]["items"][$k]["caption"];
											}else{
												echo $array_account_items[$i]["items"][$j]["items"][$k]["title"];
											}
											?>
										</a>
									</div>
									<div class="moduleName"><?=($array_account_items[$i]["items"][$j]["items"][$k]["level_name"] != "article" ? $aux_module_name." ".string_ucwords($array_account_items[$i]["items"][$j]["items"][$k]["level_name"]) : $aux_module_name)?></div>
									<div class="statusName"><?=$array_account_items[$i]["items"][$j]["items"][$k]["status"]?></div>
									<div class="itemCheckOut">
										<?
										if($array_account_items[$i]["items"][$j]["items"][$k]["NeedToCheckout"]){
											unset($link_to_pay);
											$link_to_pay = "/billing/index.php";
											?>
											<a href="javascript:void(0)" onclick="changeDomainInfo(<?=$array_account_items[$i]["domain_id"];?>,'<?=DEFAULT_URL?>/<?=MEMBERS_ALIAS?>','<?=$link_to_pay?>','',true)">
												<?=system_showText(LANG_MENU_MAKEPAYMENT)?>
											</a>
											<?
										}
										?>
									</div>
								</div>

								<?
							}
						}
						?>
				</div>
				<?
			}
		} else {
			echo "<p class=\"informationMessage\">".system_showText(LANG_MSG_NO_ITEMS_FOUND)."</p>";
		}
		
		$contentObj = new Content();
		$content = $contentObj->retrieveContentByType("Sponsor Home Bottom");
		if ($content) {
			echo "<blockquote>";
				echo "<div class=\"dynamicContent\">".$content."</div>";
			echo "</blockquote>";
		}
		?>
		<script type="text/javascript">
			enableProfile();
		</script>
	</div>

<?
	# ----------------------------------------------------------------------------------------------------
	# FOOTER
	# ----------------------------------------------------------------------------------------------------
	include(MEMBERS_EDIRECTORY_ROOT."/layout/footer.php");
?>