<?php
defined('ROOT_DIR') or die(__FILE__.' requires egConfig.inc.php');

include_once(ROOT_DIR.'egBrowser.class.php');


class egManager {
    var $objectsList;
	var $containersList;

    var $objectStyles;
    var $objectScripts;
    var $additionalScripts;

	var $browser;
	var $browserType;
	var $browserMajorVersion;
	var $browserMinorVersion;

	var $title;
	var $runtimeHtml;
	var $containersLoaded;

    function egManager($title) {
		$this->title = $title;
        $this->objectsList = array();
        $this->containersList = array();
        $this->objectStyles = array();
        $this->objectScripts = array();
        $this->browser = new egBrowser();
        $this->browserType = $this->browser->getType();
        $this->browserMajorVersion = $this->browser->getVersion(MAJOR);
        $this->browserMinorVersion = $this->browser->getVersion(MINOR);
        $this->runtimeHtml = "";
		    $this->containersLoaded = false;
    }

    function &getInstance($title='easy-GUI') {
    	static $instance = null;

      if (is_null($instance)){
        	$instance = new egManager($title);
			}
      return $instance;
    }

    function addContainer(&$container) {
        if (is_object($container)) {
					$this->containersList[] = &$container;
				}
		}

		/**
		 * @private
		 */
    function loadContainers($parentContainer) {
        if(!$this->containersLoaded) {
  				foreach($parentContainer->containersList as $container) {
  					foreach($container->objectsList as $id => $object) {
  							if(!isset($this->objectsList[$container->getId()."_".$id])) {
  		         		$this->objectsList[$container->getId()."_".$id] = &$object;
  							}
  							if (!isset($this->objectStyles[$object->getClassName()])) {
          	    	$this->addStyles($object);
        	      }

      	        if (!isset($this->objectScripts[$object->getClassName()])) {
    	          	$this->addScripts($object);
  	            }
  					}
  					$this->loadContainers($container);
  				}
        }
    }

		/**
		 * @private
		 */
		function addScripts(&$object) {
        $scriptsFiles = &$object->getScriptsFiles();
        $scriptsFile = "";

				if(count($scriptsFiles)) {
	        if (isset($scriptsFiles[$this->browserType])) {
	            if (isset($scriptsFiles[$this->browserType][$this->browserMajorVersion])) {
	                if (isset($scriptsFiles[$this->browserType][$this->browserMajorVersion][$this->browserMinorVersion])) {
	                    $scriptsFile = $scriptsFiles[$this->browserType][$this->browserMajorVersion][$this->browserMinorVersion];
	                } else {
	                    $scriptsFile = $scriptsFiles[$this->browserType][$this->browserMajorVersion]['default'];
	                }
	            } else {
	                $scriptsFile = $scriptsFiles[$this->browserType]['default'];
	            }
	        } else {
	            $scriptsFile = $scriptsFiles['default'];
	        }

				}
				if($object->getClassName() == 'egScript' && strlen($object->getScript()) > 0) {
					$this->runtimeHtml .= $object->getScript();
				}
        $this->objectScripts[$object->getClassName()] = $scriptsFile;
		}

		/**
		 * @private
		 */
    function addStyles(&$object) {
        $stylesFiles = $object->getStylesFiles();
        $stylesFile = "";

        if (isset($stylesFiles[$this->browserType])) {
            if (isset($stylesFiles[$this->browserType][$this->browserMajorVersion])) {
                if (isset($stylesFiles[$this->browserType][$this->browserMajorVersion][$this->browserMinorVersion])) {
                    $stylesFile = $stylesFiles[$this->browserType][$this->browserMajorVersion][$this->browserMinorVersion];
                }
								else {
                    $stylesFile = $stylesFiles[$this->browserType][$this->browserMajorVersion]['default'];
                }
            }
						else {
                $stylesFile = $stylesFiles[$this->browserType]['default'];
            }
        }
				else {
            $stylesFile = $stylesFiles['default'];
        }

        $this->objectStyles[$object->getClassName()] = $stylesFile;
    }

    function getContainerHTML(&$container, $parentContainer) {
				$html = $container->getContainerHTML($parentContainer);

				$radioButtonsIdList = array();
				$checkBoxesIdList = array();
        foreach($container->objectsList as $id => $object) {
						//$html .= "<!-- ".$id." -->\n";
        		$html .= $object->getHTML($container->getId());
						// additional processing needed for some controls
						if($object->getClassName() == 'egRadioButton' && !$object->hasMultipleSelection()) {
							for($i = 0; $i < count($radioButtonsIdList); ++$i) {
								$html .= "radioButton_".$radioButtonsIdList[$i].".addSibling(radioButton_".$object->getId().");";
							}
							$radioButtonsIdList[] = $object->getId();
						}
						if($object->getClassName() == 'egCheckBox' && !$object->hasMultipleSelection()) {
							for($i = 0; $i < count($checkBoxesIdList); ++$i) {
								$html .= "checkBox_".$checkBoxesIdList[$i].".addSibling(checkBox_".$object->getId().");";
							}
							$checkBoxesIdList[] = $object->getId();
						}
						if($object->getClassName() == 'egPropertySheet') {
						  // on startup, select the first tab if any
							$this->runtimeHtml .= "if(propertySheet_".$object->getId().".tabs > 0) {";
							$this->runtimeHtml .= "  var elem = document.getElementById('".$object->getId()."_tab_0');";
							$this->runtimeHtml .= "  propertySheet_".$object->getId().".selectTab(elem, 0);";
							$this->runtimeHtml .= "}";
						}
						if($object->getClassName() == 'egPropertyList') {
						  // on startup, select the first elem if any
							$this->runtimeHtml .= "if(propertyList_".$object->getId().".tabs > 0) {";
							$this->runtimeHtml .= "  var elem = document.getElementById('".$object->getId()."_list_item_0');";
							$this->runtimeHtml .= "  propertyList_".$object->getId().".selectListItem(elem, 0);";
							$this->runtimeHtml .= "}";
						}
						if($object->getClassName() == 'egDropDownPropertyList') {
						  // on startup, select the first elem if any
							$this->runtimeHtml .= "if(dropDownPropertyList_".$object->getId().".tabs > 0) {";
							$this->runtimeHtml .= "  var itemId = 0;";
							$this->runtimeHtml .= "  if(dropDownPropertyList_".$object->getId().".selectedItem) {";
							$this->runtimeHtml .= "    itemId = dropDownPropertyList_".$object->getId().".selectedItem";
							$this->runtimeHtml .= "  }";
							$this->runtimeHtml .= "  var elem = document.getElementById('".$object->getId()."_list_item_'+itemId);";
							$this->runtimeHtml .= "  dropDownPropertyList_".$object->getId().".selectListItem(elem, itemId);";
							$this->runtimeHtml .= "}";
						}
						if($object->getClassName() == 'egTreeList') {
							$this->runtimeHtml .= "if(treeList_".$object->getId().".rootNode != null) {";
							$this->runtimeHtml .= "treeList_".$object->getId().".selectItem(document.getElementById(treeList_".$object->getId().".rootNode.id), treeList_".$object->getId().".rootNode.value, '');";
							$this->runtimeHtml .= "}";
						}
        }

				foreach($container->containersList as $subContainer) {
					$html .= $this->getContainerHTML($subContainer, $container->getContainerName());
				}

				return $html;
		}

    function getHTML() {
		$this->loadContainers($this);
        $this->containersLoaded = true;

		$html = "<html>\n";
		$html .= "<head><title>".$this->title."</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head>\n";
		$html .= "<style>".$this->getStyles()."</style>\n";
		$html .= "<script>".$this->getScripts()."</script>\n";
		$html .= "<body>\n";
		$html .= "<form id=\"egform\" action=\"\" enctype=\"multipart/form-data\" method=\"post\">";
		$html .= $this->getLayersHTML();
		$html .= "</form>";
		$html .= $this->getRuntimeHTML();
		$html .= "</body>\n";
		$html .= "</html>";

        return $html;
    }

    function getLayersHTML() {
        $html = "";
        $html .= "<div id=\"easy-GUI_bottomLayer\" style=\"position: absolute; left: 0px; top: 0px; z-index: 50;\"></div>";
        $html .= "<div id=\"easy-GUI_mainLayer\" style=\"position: absolute; left: 0px; top: 0px; z-index: 100;\"></div>";
        $html .= "<div id=\"easy-GUI_topLayer\" style=\"position: absolute; left: 0; top: 0; z-index: 200;\"></div>";

        return $html;
    }

    function getRuntimeHTML() {
				$this->loadContainers($this);
        $this->containersLoaded = true;

        $html = "";
				$html .= "<script type=\"text/javascript\">";

				foreach($this->containersList as $container) {
					$this->runtimeHtml .= "container_".$container->getId().".show();";
					$html .= $this->getContainerHTML($container, 'easy-GUI_mainLayer');
				}
				$html .= "document.body.onclick = egOnBodyClick; document.body.onmouseover = egOnBodyMouseOver;";
				$html .= $this->runtimeHtml;
				$html .= "</script>\n";

        if(strlen(EASY_GUI_APP_DIR) > 0) {
          $html = str_replace(ROOT_DIR, EASY_GUI_APP_DIR.ROOT_DIR, $html);
        }

        return $html;
    }

    function getStyles() {
			$this->loadContainers($this);
      $this->containersLoaded = true;

    	$styles = "\n";

			if($this->browser->isBrowser(INTERNET_EXPLORER)) {
			    if($this->browser->getVersion(MAJOR) == "7") {
						$cssContentFile = "easy-GUI_ie70.css";
			    }
			    elseif($this->browser->getVersion(MAJOR) == "6") {
						$cssContentFile = "easy-GUI_ie60.css";
			    }
			    elseif($this->browser->getVersion(MAJOR) == "5") {
						$cssContentFile = "easy-GUI_ie50.css";
			    }
			    else {
						$cssContentFile = "easy-GUI_ie50.css";
			    }
			}
			elseif($this->browser->isBrowser(FIREFOX)) {
				$cssContentFile = "easy-GUI_ff15.css";
			}
			else {
				$cssContentFile = "easy-GUI_default.css";
			}

			// easyGUI common styles
			if(is_file(ROOT_DIR.$cssContentFile)) {
				$styles .= file_get_contents(ROOT_DIR.$cssContentFile);
			}

			// styles of used controls
			foreach($this->objectStyles as $class => $style) {
				if(is_file(ROOT_DIR.$style)) {
					$styles .= file_get_contents(ROOT_DIR.$style);
				}
			}

			// ajust background URLs
			$styles = ereg_replace("(url[ ]*\('?([\/\\a-zA-Z0-9\._-]*)'?\))", "url('".EASY_GUI_APP_DIR.ROOT_DIR."\\2')", $styles);
      // note : additional modifications are required in easy-GUI_xxxx.css
      // for sahdow under IE : use of "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			$cr = array("\n", "\r", "\r\n");
			return str_replace($cr, '', $styles);
		}

    function getScripts() {
			$this->loadContainers($this);
      $this->containersLoaded = true;

			$scripts = "\n";

			// browser version
			$version = $this->browser->getVersion(MAJOR);
			// browser type
			$type = "IE";

			if($this->browser->isBrowser(INTERNET_EXPLORER)) {
				$type = "IE";
			}
			elseif($this->browser->isBrowser(FIREFOX)) {
				$type = "FF";
			}
			elseif($this->browser->isBrowser(NETSCAPE)) {
				$type = "NS";
			}
			elseif($this->browser->isBrowser(OPERA)) {
				$type = "OPE";
			}
			elseif($this->browser->isBrowser(SAFARI)) {
				$type = "SAF";
			}
			elseif($this->browser->isBrowser(MOZILLA)) {
				$type = "MOZ";
			}

			// easyGUI specific vars
			$scripts .= "\n\n";
			$scripts .= "var egBrowserType = '$type';\n";
			$scripts .= "var egBrowserVersion = '$version';\n";
			$scripts .= "var egObjectsArray = new Array();\n";
			$scripts .= "\n\n";
			// easyGUI common scripts
			if(is_file(ROOT_DIR."easy-GUI.js")) {
			     $scripts .= file_get_contents(ROOT_DIR."easy-GUI.js");
			}

			// egContainer class
			if(is_file(ROOT_DIR."egContainer_default.js")) {
			     $scripts .= file_get_contents(ROOT_DIR."egContainer_default.js");
			}

			// test : jquery
			if(is_file(ROOT_DIR."jquery.js")) {
			     $scripts .= file_get_contents(ROOT_DIR."jquery.js");
			     $scripts .= ';';
			}

			// scripts of used controls
			foreach($this->objectScripts as $class => $script) {
				if(is_file(ROOT_DIR.$script)) {
					//$scripts .= "\n\n/** $class scripts **/\n\n\n";
					$scripts .= file_get_contents(ROOT_DIR.$script);
				}
			}
			$cr = array("\n", "\r", "\r\n");
			return $scripts;
			return str_replace($cr, '', $scripts);
		}
}
?>