<?
/**
 * joe mccorison
 */
require_once $_SERVER['WEB_PATH']."/php/includes/CL_TemplateHandler/CL_TemplateHandler.inc";
require_once $_SERVER['WEB_PATH']."/php/includes/CL_Menu/CL_Menu.inc";
require_once $_SERVER['WEB_PATH']."/php/includes/CLCommonCode/page.php";
require_once $_SERVER['WEB_PATH']."/php/includes/CLCommonCode/CL_Page.inc";
require_once $_SERVER['WEB_PATH']."/pages/modules/BreadCrumb.php";
require_once $_SERVER['WEB_PATH']."/php/includes/CL_Plus/CL_Plus.inc";
require_once $_SERVER['WEB_PATH']."/php/includes/CL_UserManagement/CL_BaseUser.inc";
require_once "Session.php";

require_once $_SERVER['WEB_PATH']."/php/DoctrineInit.php";

//define constants
DEFINE("_HEADERTPL","base/eng/smarty/ladder/pages/header.tpl");
DEFINE("_FOOTERTPL","base/eng/smarty/ladder/pages/footer.tpl");
DEFINE("_PAGETPL","base/eng/smarty/ladder/pages/index.tpl");
DEFINE("_BANNERTPL","base/eng/smarty/ladder/modules/league_header.tpl");
DEFINE("_MENUTPL","base/eng/smarty/ladder/modules/menu.tpl");
DEFINE("_TABSMENUTPL","base/eng/smarty/ladder/modules/menuTabs.tpl");
DEFINE("_SUBMENUTPL","base/eng/smarty/ladder/modules/submenu.tpl");
DEFINE("_SEARCHMODTPL","base/eng/smarty/ladder/modules/breadCrumb.tpl");
DEFINE("_BREADCRUMBMODTPL","base/eng/smarty/ladder/modules/searchMod.tpl");
DEFINE("_BREADCRUMBSERACHTPL","base/eng/smarty/ladder/modules/ModuleGroups/breadCrumbSearch.tpl");
DEFINE("_LOGINTPL","base/eng/smarty/ladder/pages/login.tpl");

DEFINE("_USERLOGIN","base/eng/smarty/ladder/modules/userLogin.tpl");
DEFINE("_PAGESDIR",$_SERVER["WEB_PATH"]."/pages/");
DEFINE("_TEMPLATEDIR","base/eng/smarty/ladder/");
DEFINE("_DEFAULTPAGE",$_SERVER["WEB_PATH"]."/pages/index.php");
DEFINE("_DELETEPAGE",$_SERVER["WEB_PATH"]."/pages/markForDelete.php");
DEFINE("_MERGEPAGE",$_SERVER["WEB_PATH"]."/pages/markForMerge.php");
DEFINE("_PLUSCUSTOMEHOME","plusCustom.php");

class LeaguePage extends CL_TemplateHandler
{
    private $oPage;
    private $oSession;
    private $strPath;
    private $strSlave;
    private $oLadder;
    private $arrText;
    
    public function __construct()
    {
        parent::__construct();
        $this->oPage = New page();
        $this->oSession = Session::getInstance();

        $this->oSession->setCurrentLadder();

        $this->strSlave = $this->oSession->getCurrentLadder()->slave;
        $this->strPath = $this->oSession->getCurrentLadder()->path;

        $this->oLadder = New CL_BaseLadder();
        $this->oLadder->set("ladderlist_path",$this->strPath);

        if (!empty($this->strSlave)) {
            $this->oLadder->set("ladderlist_slave",$this->strSlave);
        }

        $this->oLadder->getLadder();
    }

    public function __destruct(){}

    public function NewPage()
    {
        //set up the page title
        parent::assign("TITLE",$this->oLadder->get("ladderlist_name"));
		parent::assign("SERVICE", $this->getServiceName($this->oLadder->get("ladderlist_service")));
        
        $this->oPage->addPageJsFile("/js/MochiKit1.4/MochiKit.js");
        $this->oPage->addPageJsFile("/js/jquery.js");
        $this->oPage->addPageJsFile("/js/jquery.easyform.js");
        $this->oPage->addPageJsFile("/js/myleague.js");

        // showad.js must be loaded from www.myleague.com for impression reporting.
        $this->oPage->addPageJsFile("/js/showad.js", false);

        if (strpos($_SERVER['SCRIPT_URL'], "$this->strPath/myaccount/")) {
            $this->oPage->addPageJsFile("/js/tiny_mce/tiny_mce.js", false);
        }

        parent::assign("JAVASCRIPT",$this->oPage->getPageJsFiles());

        $this->oPage->addPageStyleSheet("/css/common.css");
        $this->oPage->addPageStyleSheet("/css/layout.css");
        $this->oPage->addPageStyleSheet("/css/".$this->oLadder->get("ladderlist_default_style").".css");
        $this->oPage->addPageStyleSheet("/css/jsCal_".$this->oLadder->get("ladderlist_default_style").".css");
        $this->oPage->addPageStyleSheet("/css/smartBox.css");
        $this->oPage->addPageStyleSheet("/css/msg.css");
         $this->oPage->addPageStyleSheet("/css/sendMailThickbox.css");
        parent::assign("STYLESHEET",$this->oPage->getPageStyleSheets());

        parent::assign("PLUSID", $this->getPlusId());

        //set up the template
        $oPage = New CL_Page();
        parent::assign("TOTALLEAGUES",$oPage->getTotalActiveLeagues());
        parent::assign("TOTALPLAYERS",$oPage->getTotalPlayersSignedUp());
        parent::assign("MATCHESPLAYED",$oPage->getTotalMatchesPlayed());

        parent::assign("LEAGUEPATH",$this->strPath);
        parent::assign("LEAGUEDESC", $this->oLadder->getLadderDesc());
        parent::assign("PAGEHEADER",parent::fetch(_HEADERTPL));

        self::buildFooter();
    }

	private function getServiceName($id) {
		$service = null;
    	try {
			list($service) = ORM_query::create()->from("Service")
				->where("id = $id")
				->limit(1)
                ->execute(array(), Doctrine::HYDRATE_ARRAY);
        } catch (Exception $e) {
                //XXX: todo add logging that this failed here
        }

        return $service["name"];
    }

    private function customContent()
    {
        try {
            // seems to be a bug in doctrine where if we use
            // findOneBySql seems to be an an issue not being able to find aliases and columns

            $admin = ORM::getAdminTable()->findBySql("path = '$this->strPath' AND headAdmin > 0");
            $plus = ORM::getPlusTable()->findById($admin[0]->plusId);
            return $plus[0]->enableHomeMod;
        } catch(Exception $e) {
            //XXX: todo add logging that this failed here
        }
    }

    private function getPlusId()
    {
        try {
            $admin = ORM::getAdminTable()->findBySql("path = '$this->strPath' AND headAdmin > 0");
            return $admin[0]->plusId;
        } catch(Exception $e) {
            //XXX: todo add logging that this failed here
        }
    }

    public function buildFooter()
    {
        require_once $_SERVER['WEB_PATH']."/pages/modules/internalLinks.php";
        require_once $_SERVER['WEB_PATH']."/pages/modules/myleagueSearch.php";
        require_once $_SERVER['WEB_PATH']."/pages/modules/myleagueMerchandise.php";

        $user = $this->oSession->getCurrentUser();
        if (isset($user->name)) {
            parent::assign("LOGGEDIN", TRUE);
            parent::assign("GOLD", $user->goldId);
            parent::assign("USERNAME", $user->name);
        }

        $oInternalLinks = New internalLinks();
        parent::assign("INTERNALLINKSMOD",$oInternalLinks->display());

        $myleagueSearch = New myleagueSearch();
        parent::assign("MYLEAGUESEARCHMOD",$myleagueSearch->display());

        $myleagueMerchandise = New myleagueMerchandise();
        parent::assign("MYLEAGUEMERCHANDISEMOD",$myleagueMerchandise->display());

        parent::assign("LEAGUEPATH",$this->strPath);
        parent::assign("PAGEFOOTER",parent::fetch(_FOOTERTPL));
    }

    public function buildBanner()
    {
        parent::assign("LEAGUENAME",$this->oLadder->get("ladderlist_name"));
        parent::assign("LEAGUEPATH",$this->strPath);
        parent::assign("LEAGUESLOGAN",$this->oLadder->get("ladderlist_slogan"));

        if (!is_null($this->oLadder->getHeader())) {
            if (strstr($this->oLadder->getHeader(),".swf")) {
                parent::assign("HEADERTYPE","flash");
            } elseif (strstr($this->oLadder->getHeader(),".gif") || strstr($this->oLadder->getHeader(),".jpg") || strstr($this->oLadder->getHeader(),".png")) {
                parent::assign("HEADERTYPE","image");
            }
            parent::assign("CUSTOMHEADER",$this->oLadder->getHeader());
        }

        parent::assign("BANNER",parent::fetch(_BANNERTPL));
    }

    public function buildUserLogin()
    {
        $user = $this->oSession->getCurrentUser();

        $oPage	= New CL_Page();
        if (isset($user->name)) {
            parent::assign("LOGGEDIN", TRUE);
            parent::assign("USERNAME", $user->name);
            parent::assign("USERBUX", $user->currentBux);
            parent::assign("NEWMESSAGES", $this->oSession->getNewMessages());
        }

        parent::assign("USERLOGINTPL",parent::fetch(_USERLOGIN));
    }

    public function buildBreadCrumbSearch()
    {
        $breadCrumb = new BreadCrumb();
        $arrBreadCrumb = $breadCrumb->buildBreadCrumb();
        parent::assign("arrBreadCrumb",$arrBreadCrumb);

        $strSearch = parent::fetch(_SEARCHMODTPL);
        $strBreadCrumb= parent::fetch(_BREADCRUMBMODTPL);

        parent::assign("SEARCHMOD",$strSearch);
        parent::assign("BREADCRUMBMOD",$strBreadCrumb);

        $strBreadSearch= parent::fetch(_BREADCRUMBSERACHTPL);

        parent::assign("BREADCRUMBSEARCH",$strBreadSearch);
    }

    public function buildSite()
    {
        self::parseUrl();
    }

    public function buildSiteMenus()
    {
        $oSession = Session::getInstance();

        $oMenu = New CL_Menu();
        $oBreadCrumb = New BreadCrumb();
        $oSubMenu = New CL_Menu();

        $strCurrent = $oBreadCrumb->getCurrentMainPage(); // should be titleNode->nodeValue ?
        $currentPage = strtolower($strCurrent);

        if ($currentPage == '' || empty($currentPage)) {
            $currentPage = "home";
        }

        // menu.xml :: /data1/ladder
        $menuXmlFile = $_SERVER["MASTER_PATH"] . "/menu.xml";

        $oDom = New DOMDocument();
        $oDom->load($menuXmlFile);
        $menuItems = $oDom->getElementsByTagName('MenuItem');

        //---------------------------
        // Check for valid main tab... in case of 'incorrectly structured' url, use "home" as selected main tab
        $validCurrent = false;
        foreach ($menuItems as $menuItem) {
            $titleNodes = $menuItem->getElementsByTagName('Title');
            $titleNode  = $titleNodes->item(0);
            $titleValue = $titleNode->nodeValue;

            if(strcasecmp($titleValue,$currentPage)==0)
                {$validCurrent = true;}
        }

        if (!$validCurrent) {
            $currentPage='home';
        }
        //---------------------------

        //$current = true;
        foreach ($menuItems as $menuItem)
        {
            $idNodes = $menuItem->getElementsByTagName('Id');
            $idNode = $idNodes->item(0);
            $idValue = strtolower($idNode->nodeValue);

            $titleNodes = $menuItem->getElementsByTagName('Title');
            $titleNode = $titleNodes->item(0);
            $titleValue = $titleNode->nodeValue;

            $urlNodes = $menuItem->getElementsByTagName('Url');
            $urlNode = $urlNodes->item(0);
            $urlValue = strtolower($urlNode->nodeValue);

            //--------------------
            // prevent doubleslash on home page url
            //if($current)
            //{$current = null;}

            if (strcasecmp($idValue,'Home')!=0) {
                $urlValue .= '/';
            }

            $url = "/".$oSession->getCurrentLadder()->path.'/'.$urlValue;

            if (!isset($current)) {
                $current = null;
            }
            $oMenu->add($idValue,$titleValue,$url,$current);

            $subMenuNodes = $menuItem->getElementsByTagName('SubMenu');
            $subMenuNode  = $subMenuNodes->item(0);
            $subMenuItems = $subMenuNode->getElementsByTagName('SubMenuItem');

            //if(strcasecmp($urlValue,$currentPage)==0)
            if (strcasecmp($idValue,$currentPage) == 0) { // should be comparing idValue with currentValue.. ie.. idValue == titleValue
                $subCurrent = true;
                foreach ($subMenuItems as $subMenuItem) {
                    $subIdNodes = $subMenuItem->getElementsByTagName('Id');
                    $subIdNode = $subIdNodes->item(0);
                    $subIdValue = $subIdNode->nodeValue;

                    $subTitleNodes = $subMenuItem->getElementsByTagName('Title');
                    $subTitleNode = $subTitleNodes->item(0);
                    $subTitleValue = $subTitleNode->nodeValue;

                    $subUrlNodes = $subMenuItem->getElementsByTagName('Url');
                    $subUrlNode = $subUrlNodes->item(0);
                    $subUrlValue = $subUrlNode->nodeValue;

                    if ($subUrlValue > '') {
                        // adding support for messages link in MyAccount submenu
                        // modifying url since it is not under myaccount
                        if (strcasecmp($subIdValue, 'messages') == 0) {
                            $url = "/" . $oSession->getCurrentLadder()->path . "/$subUrlValue/";
                        } else {
                            if (strcasecmp($idValue, 'Home') == 0 && $subIdValue != 'gettingStarted' && $subIdValue != 'rules') {
                                $subUrlValue = 'home/' . $subUrlValue;
                            }

                            $url = '/' . $oSession->getCurrentLadder()->path . '/' . $urlValue . $subUrlValue . '/';
                        }
                    } else {
                        $url = "/".$oSession->getCurrentLadder()->path.'/'.$urlValue;
                    }

                    if ($subMenuItem->hasAttribute('hidden')) {
                        $hidden = $subMenuItem->getAttribute('hidden');
                    }

                    if ($hidden!="1") {
                        $oSubMenu->add($subIdValue,$subTitleValue,$url,$subCurrent);
                    }

                    if ($subCurrent) {
                        $subCurrent = null;
                    }
                }
            }
        }
        //-----------------------------------------

        $oMenu->setCurrent($currentPage);
        $oMenu->setTemplate(_TABSMENUTPL);

        parent::assign("TABS",$oMenu->display());

        //-------
        self::buildUserLogin();
        parent::assign("MENU",parent::fetch(_MENUTPL));

        //----------------------------------------

        // if this is a plus league and we are on the front page add a voting booth link
        $admin = ORM::getAdminTable()->findBySql("path = '$this->strPath' AND headAdmin > 0");
       	if ($admin[0]->plusId > 0 && $currentPage == "home") {
      		$oSubMenu->add("plus","Voting Booth",sprintf("/%s/community/VotingBooth/", $this->strPath));
       	}
        $oSubMenu->setTemplate(_SUBMENUTPL);
        parent::assign("SUBMENU",$oSubMenu->display());

        //-----------------------------------------
    }

    public function display()
    {
        self::NewPage();
        self::buildBanner();
        self::buildSiteMenus();
        self::buildBreadCrumbSearch();
        self::buildSite();

        try {
            $tpl_source = parent::fetch(_PAGETPL);

            // curious about count
            $memcache_obj = new Memcache;
            $memcache_obj->connect($_SERVER['MEMCACHE_HOST'], 11211);

            $count = $memcache_obj->get('visitcount');

            if(empty($count)){
                $memcache_obj->add('visitcount',0);
            }
            // increment counter by 1
            $current_value = $memcache_obj->increment('visitcount', 1);

            print $tpl_source;
        } catch (Exception $e) {
            print "Error: ".$e->getMessage();
        }
    }

    /**
     * Parses the url for key terms to diplay pages called and to
     * fire actions called
     *
     */
    private function parseUrl()
    {
        $arrUrl = parse_url($_SERVER['REQUEST_URI'],PHP_URL_QUERY);
        $arrQuery = split("&",$arrUrl);
        $arrQueryValPair = array();

        foreach ($arrQuery AS $queryVar) {
            $arrValuePair	= split("=",$queryVar);
            if (count($arrValuePair) > 1) {
                $arrQueryValPair[$arrValuePair[0]] = $arrValuePair[1];
            }
        }

        if (isset($_GET["p"]) && !is_null($_GET["p"]) && !empty($_GET["p"]) && !isset($_GET["sub"])) {
            parent::assign("CONTENT",self::getRequire($_SERVER["WEB_PATH"]."/pages/".$_GET["p"].".php"));
        } elseif (isset($_GET["p"]) && !is_null(!$_GET["p"]) && !empty($_GET["p"]) && isset($_GET["sub"]) && !is_null($_GET["sub"])) {
            parent::assign("CONTENT",self::getRequire($_SERVER["WEB_PATH"]."/pages/".$_GET["sub"].".php"));
        } elseif (self::customContent()) {
            parent::assign("CONTENT",self::getRequire($_SERVER["WEB_PATH"]."/pages/"._PLUSCUSTOMEHOME));
        } else {
            parent::assign("CONTENT",self::getRequire($_SERVER["WEB_PATH"]."/pages/index.php"));
        }
    }

    //gets the content from an included file and out puts to buffer for capture
    private function getRequire($strFile)
    {
        /**
         * check to see if the league is in delete state if so
         * if so show league is being deleted page
         */
        $premSupport = '/web/pages/premiumSupport.php';
        if (file_exists("/$this->strSlave/$this->strPath/mergeme") && $strFile != $premSupport) {
            include(_MERGEPAGE);
        } else if (file_exists("/$this->strSlave/$this->strPath/deleteme") && $strFile != $premSupport) {
            include(_DELETEPAGE);
        } else if (file_exists($strFile)) {
            include($strFile);
        } else {
            include(_DEFAULTPAGE);
        }
        $return = ob_get_clean();
        return $return;
    }
}

$oPage= New LeaguePage();
$oPage->display();

?>
