/// <summmary>
		/// Enable a button
		/// Helper function for delegate
		/// </summary>
		public static void EnableButton(UIButton b)
		{
			b.State = UIButtonState.RELEASE;
		}//EnableOkButton()
        /// <summary>
        /// Initialize the button and register to ui
        /// </summary>
        public void Init()
        {
            Log.Debug(gameObject.name+ " Init");

            UIManager uiManager = UIManager.Instance;

            //only add collider if not yet exist
            Collider2D c = gameObject.GetComponent<Collider2D>();
            if(c == null)
            {
                //gameObject.AddComponent<PolygonCollider2D>();
                gameObject.AddComponent<BoxCollider2D>();
            }

            //Log.Debug(gameObject.name+" ============== uiType:"+uiType);
            if(uiType == UIType.Button && toggle)
                uiType = UIType.ToggleButton;

            //TODO FIXME this should NOT be here
            // if((gameObject.name.EndsWith("btn_SoundEffects")) ||
            //    (gameObject.name.EndsWith("btn_Sound")))
            // 	uiType = UIType.SoundButton;

            // if((gameObject.name.EndsWith("btn_CityHall")) ||
            //    (gameObject.name.EndsWith("btn_Engineer")) ||
            //    (gameObject.name.EndsWith("btn_Settings")) ||
            //    (gameObject.name.EndsWith("btn_LeaveScreen")) ||
            //    (gameObject.name.EndsWith("btn_MessageHead")) ||
            //    (gameObject.name.EndsWith("btn_Emails")) ||
            //    (gameObject.name.EndsWith("btn_Play")))
            // 	uiType = UIType.SettingsButton;

            // if(gameObject.name.EndsWith("btn_Earth") ||
            //    gameObject.name.EndsWith("btn_Future") ||
            //    gameObject.name.EndsWith("btn_Sun") ||
            //    gameObject.name.EndsWith("btn_Water") ||
            //    gameObject.name.EndsWith("btn_WhatIsEnergy") ||
            //    gameObject.name.EndsWith("btn_Wind"))
            // 	uiType = UIType.TouchButton;

            // TODO fix this for more cases, localization and
            //use resourcePath only if given
            if(resourcePath.Length > 0)
            {
                // Log.Info("add res:"+resourcePath);
                uiButton = (UIButton)uiManager.Add(uiType, gameObject, resourcePath);
            }
            else
            {
                ////check if we have sprite to use instead
                SpriteRenderer sr = gameObject.GetComponent<SpriteRenderer>();
                if(sr != null && sr.sprite != null)
                {
                    //TODO fix localization and find a way to load the rest of the sprites..
                    Log.Info("We have a sprite:"+gameObject.name);
                    uiButton = (UIButton)uiManager.Add(uiType, gameObject, "", sr.sprite);
                }
                else
                {
                    Log.Debug("No resource nor sprite set in button: "+gameObject.name);
                    uiButton = (UIButton)uiManager.Add(uiType, gameObject, "");

                }
            }

            uiButton.SetSpriteOrder(spriteOrder);
            Register(uiButton);

            if(text != null)
            {
                uiButton.SetTextColors(
                    upColor, downColor, overColor, disabledColor, activeColor);
                uiButton.SetText(text);
            }
        }
 /// <summary>
 /// Register the button functions
 /// </summary>
 public virtual void Register(UIButton b)
 {
     b.Register(UIEvent.Pressed, ButtonOnPressed);
     b.Register(UIEvent.Release, ButtonOnRelease);
     b.Register(UIEvent.Click, ButtonOnClick);
     b.Register(UIEvent.Over, ButtonOnOver);
     b.Register(UIEvent.OverExit, ButtonOnOverExit);
 }
 /// <summary>
 /// Button handler
 /// </summary>
 public virtual void ButtonOnPressed(UIButton button)
 {
     //Log.Info("onClick - Button");
     if(handler != null && onPressed != "")
     {
         handler.SendMessage(onPressed, gameObject.name);
     }
 }
 /// <summary>
 /// Button handler
 /// </summary>
 public virtual void ButtonOnRelease(UIButton button)
 {
     //Log.Info("onRelease - Button");
     if(handler != null && onRelease != "")
     {
         handler.SendMessage(onRelease, gameObject.name);
         if(ReleaseAudio.Length > 0)
             audioManager.PlaySound(ReleaseAudio);
     }
 }
		/// <summary>
		///Process inputs and update state of ui element.
		/// </summary>
		public void Update()
		{
			//Log.Debug("UI Update");
			//
			if(modalWindow != null)
			{
				if(!modalWindow.active)
				{
					//modal not active anymore, remove it
					modalWindow = null;
				}
			}
	
			//move slider
			if (lastButton != null
				&& lastButton.Type == UIType.Slider
				&& lastButton.State == UIButtonState.PUSH
				&& Input.GetMouseButton(0))	
			{
				lastButton.Push();
				return;
			}

			//check if we have anything under the cursor
			UIButton button = null;
			GameObject obj = GetObjectUnderCursor();
			if(obj != null)
			{
				//check if we are in modal mode
				//and only allows clicks on window
				if(modalWindow != null)
				{
					//check if obj is in the modals list
					if(!modals.ContainsKey(obj.GetInstanceID()))
					{
						if(lastButton != null)
						{
							lastButton.Release();
							lastButton = null;
						}
						//not in the list
						return;
					}
				}
				
				//get button if any
				//check if this is a button.
				button = GetUIButtonFromObject(obj);
				if(button != null)
				{

					// Debug.Log("button="+button.Name+" state:"+button.State);

					//check if last button was different (overlaps)
					//and release it properly
					if(lastButton != null && lastButton != button)
					{
						lastButton.Release();
						lastButton = null;
					}


					//we have a valid ui button under our cursor
					if(Input.GetMouseButton(0))
					{

						// Debug.Log("<color=white>MOUSE DOWN, buttons state=</color>"+button.State);

						//left button down or screen touched
						if(button.State == UIButtonState.RELEASE 
							|| button.State == UIButtonState.ACTIVE_RELEASE
							|| button.State == UIButtonState.OVER
							|| button.State == UIButtonState.ACTIVE_OVER
							)
						{
							//push it once
							button.Push();
						}

					}
					else
					{
						//up can be trigger for click or over with mouse
						if(button.State == UIButtonState.PUSH 
							|| button.State == UIButtonState.ACTIVE_PUSH
							)
						{
							button.Release();
							button.Click();
						}
						else
						{
							if(button.State == UIButtonState.RELEASE
								|| button.State == UIButtonState.ACTIVE_RELEASE)
							{
								button.Over();
							}
						}

					}
					//last focus on the button
					lastButton = button;

					return;

				}
				else
				{
					//no uibutton but something else
					if(lastButton != null)//&& button != lastButton)
					{
						if(lastButton.State == UIButtonState.PUSH 
							|| lastButton.State == UIButtonState.ACTIVE_PUSH
							|| lastButton.State == UIButtonState.OVER
							|| lastButton.State == UIButtonState.ACTIVE_OVER)
						{
							lastButton.Release();
						}

					}
				}
				
		
			}
			else{


				//always release, but only once if not in focus anymore
				if(lastButton != null)//&& button != lastButton)
				{

					if(lastButton.State != UIButtonState.DISABLED
					   && lastButton.State != UIButtonState.ACTIVE_DISABLED)
					{
						lastButton.Release();
					}

					lastButton = null;
				}
			}
		}//Update()
        /// <summary>
        //TODO : remove Button from the hierarchy
        /// </summary>
        public void RemoveButton(UIButton button)
        {
            //create button with mail subject as text

            button.GameObject.transform.parent = null;
            button.GameObject.SetActive(false);
            Object.Destroy(button.GameObject);
        }
		/// <summary>
		///Process inputs and update state of ui element.
		/// </summary>
		public void Update()
		{
			//Log.Debug("UI Update");
			//
			if(modalWindow != null)
			{
				if(!modalWindow.active)
				{
					//modal not active anymore, remove it
					modalWindow = null;
				}
			}
			
			//get mouse Position and check if we have something under the pointer
			Vector3 mp = Input.mousePosition;
			LayerMask mask = uiCamera.cullingMask;

			RaycastHit2D topHit;
			int topHitOrder = -1;

			Vector3 click = uiCamera.ScreenToWorldPoint(mp);
			RaycastHit2D[] hits = Physics2D.LinecastAll(click, click, mask);

			// Debug.Log("HITS:"+hits.Length);

			foreach (RaycastHit2D hit in hits)
			{
				if(hit.collider)
				{
					GameObject obj = hit.collider.gameObject;
					SpriteRenderer spriteRenderer = obj.GetComponent<SpriteRenderer>();
					
					// Log.Debug("Collider:"+obj.name);
					if (spriteRenderer != null)
					{
						if (spriteRenderer.sortingOrder > topHitOrder)
						{
							topHit = hit;
							topHitOrder = spriteRenderer.sortingOrder;
						}
					}
					else 
					{
						MeshRenderer meshRenderer = obj.GetComponent<MeshRenderer>();
						SortingOrder sortingOrder = obj.GetComponent<SortingOrder>();
						if (meshRenderer != null)
						{
							if (meshRenderer.sortingOrder > topHitOrder)
							{
								topHit = hit;
								topHitOrder = meshRenderer.sortingOrder;
							}
						}
						else if (sortingOrder != null)
						{
							if (sortingOrder.sortingOrder > topHitOrder)
							{
								topHit = hit;
								topHitOrder = sortingOrder.sortingOrder;
							}
						}
						else //document button
						{
							if (topHitOrder < 1)
							{
								topHit = hit;
								topHitOrder = 1;
							} 
						}
					}
				}
			}
			// Log.Debug("TopHit:"+topHitOrder);

			if(topHitOrder > -1)
			{
				GameObject obj = topHit.collider.gameObject;
				
				//check if we are in modal mode
				if(modalWindow != null)
				{
					//check if obj is in the modals list
					if(!modals.ContainsKey(obj.GetInstanceID()))
					{
						if(lastButton != null)
						{
							lastButton.Release();
							lastButton = null;
						}
						//not in the list
						return;
					}
				}

				//check if this is a button.
				
				// Log.Info("HIT something:"+obj.name+" images:"+images.Count);
				UIButton button = null;
				if(images.ContainsKey(obj.GetInstanceID()))
				{	
					try
					{
						UIObject b = (UIObject)images[obj.GetInstanceID()];
						UIType t = b.GetType();
						// if(t ==  UIType.Button
						// ||	t.GetType().IsSubclassOf(typeof(UIButton)))
						if(t == UIType.Button 
							|| t == UIType.ToggleButton
							|| t == UIType.Slider
							|| t == UIType.Checkbox)
						{
							button = (UIButton)b;
						}
					}
					catch(System.Exception e)
					{
					 	Log.Debug("Could not find ui key:"+obj.name);
					 	Log.Debug("error :"+e.ToString());
					}
				}

				// if(button!=null)
				//  	Log.Debug("---------------- Button:"+button.Name);
				// else
				// 	Log.Debug("---------------- Button NULL");

				if(button != null && lastButton != null
				 	&& button != lastButton )
				{
					//Log.Debug("Release!!");
					lastButton.OverExit();
					lastButton.Release();
					lastButton = null;

					return;
				}
				else if(button == null && lastButton != null )
				{
					lastButton.OverExit();
					lastButton.Release();
					lastButton = null;

				}

				if(button != null && 
				   button.State != UIButtonState.OVER && 
				   button.State != UIButtonState.DISABLED && 
				   button.State != UIButtonState.ACTIVE_DISABLED && 
				   GameManager.Instance.hidTouch)
				{
					if(lastButton != null)
					{
						lastButton.Release();
					}
					lastButton = button;
					button.Push();
					
					activeButton = button;
				}
				else if(button != null && button.State != UIButtonState.DISABLED && button.State != UIButtonState.ACTIVE_DISABLED)
				{
					//Log.Debug("button:"+button.Name);
					if(Input.GetMouseButtonDown((int)MouseButton.Left))
					{
						//Log.Debug("button Push1:"+button.Name);
						if(lastButton != null)
						{
							lastButton.Release();
						}
						lastButton = button;
						button.Push();

						activeButton = button;
					}					
					else if(Input.GetMouseButton((int)MouseButton.Left))
					{
						//Log.Debug("button push:"+button.Name);
						//lastButton = button;
						if(activeButton == button)
						{
							button.Push();
							lastButton = button;
						}
						else if(lastButton != null)
						{
							lastButton.Release();
						}
				
					}				
					else if (Input.GetMouseButtonUp((int)MouseButton.Left))
					{
						//Log.Debug("button Up:"+button.Name+" ab:"+lastButton.Name+" s:"+button.State);
						
						if(activeButton == button)
						{								
							button.Click();
							button.Release();
						}
						if(lastButton != null)
							lastButton.Release();

						lastButton = null;
						activeButton = null;

					}
					else
					{
						if(lastButton != null && button != lastButton)
						{
							lastButton.OverExit();
							lastButton.Release();
						}
						else if(activeButton == null)
						{
							lastButton = button;
							button.Over();
						}
					}
				}
			}//tophit
			else if(lastButton != null)
			{
				lastButton.OverExit();
				//Log.Debug("***********************");
				lastButton.Release();
				lastButton = null;
				//WebPlayerDebugManager.addOutput("------------- not tophit, activeButton="+activeButton+", lastButton="+lastButton,1);
				
			}
		
		}//Update()
        /// <summary>
        /// Button OnClick handler
        /// </summary>
        public virtual void ButtonOnClick(UIButton button)
        {
            Log.Debug("onClick - Button "+ gameObject.name);
            if(handler != null && onClick != "")
            {
                handler.SendMessage(onClick, gameObject.name);
                if(ClickAudio.Length > 0)
                    audioManager.PlaySound(ClickAudio);

            }

            if(eventID != "")
            {
                GameManager.Instance.Event("BUTTON", eventID, "onClick");
            }
        }
 // TODO check this why works and sometimes not works
 // void Start()
 // {
 // 	Log.Warning(" 1111 - Start");
 // 	base.Init();
 // }
 /// <summary>
 /// Register the slider's functions
 /// </summary>
 public override void Register(UIButton slider)
 {
     uiSlider = (UISlider)slider;
     base.Register(uiSlider);
     uiSlider.Register(UIEvent.Update, UpdateValue);
     uiSlider.Set(sliderType, dimension, value, minValue, maxValue, step);
 }
 /// <summary>
 /// go to next screen
 /// </summary>
 public void nextScreen(UIButton button)
 {
     uiManager.ActivateScreen("Screen1");
 }
 /// <summary>
 ///Test function to process release even from buttons
 /// </summary>
 public void testOnRelease(UIButton button)
 {
     Debug.Log("Test release: "+button.Name);
 }
 /// <summary>
 /// test function to process over state from buttons
 /// </summary>
 public void testOnOver(UIButton button)
 {
     Debug.Log("Test over :"+button.Name);
 }
        /// <summary>
        /// go to next screen
        /// </summary>
        public void nextScreen(UIButton button)
        {
            Debug.Log("Test click :"+button.Name);

            uiManager.ActivateScreen("Screen2");
        }
		}//EnableOkButton()

		/// <summmary>
		/// Disable a button
		/// Helper function for delegate
		/// </summary>
		public static void DisableButton(UIButton b)
		{
			b.State = UIButtonState.DISABLED;
		}//DisableButton()
        /// <summary>
        /// Button handler
        /// </summary>
        public virtual void ButtonOnOver(UIButton button)
        {
            //Log.Info("onOver - Button");
            if(handler != null && onOver != "")
            {
                handler.SendMessage(onOver, gameObject.name);
                if(OverAudio.Length > 0)
                    audioManager.PlaySound(OverAudio);

            }
        }
		}//LoadResources()

		/// <summary>
		/// Load object resources from dictionary
		/// TODO make more generic helpers and way of parse similar stuff.
		/// ie. transform parameter should be one parser for all
		/// </summary>
		public Dictionary<string, UIObject> LoadResources(
			Dictionary<string,object> dict, 
		    GameObject                gameObject = null)
		{
			//parse list of objects
			if(dict.ContainsKey("objects"))
			{

				// Log.Debug("Number of objects:"+((List<object>)dict["objects"]).Count);

				Dictionary<string, UIObject> screenObjects = new Dictionary<string, UIObject>();
			
				foreach(Dictionary<string,object> obj
					in ((List<object>)dict["objects"]))
				{
					 
					//Log.Debug("objects:"+obj["id"].ToString()+" type:"+obj["type"].ToString());
	

					if(obj.ContainsKey("type") 
						&& obj.ContainsKey("id"))
					{
						//string objId = obj["id"].ToString();
						
						//get id and prefix it by parent name
						string objId = obj["id"].ToString();						
						if(gameObject!=null) objId = gameObject.name+"."+objId;

						
						string objType = obj["type"].ToString();						
						// Log.Debug("Create ui object:"+objId+":"+objType);

						
						//create objects based on types
						if(objType == "image")
						{
							
							// Log.Debug("Create Image:"+objId);
							//TODO add creation of an image gameObject here or there?
							UIImage image = new UIImage(obj);
							if(gameObject)
								image.GameObject.transform.parent = gameObject.transform;

							image.Name = objId;
							//images.Add(objId, image);
							images.Add(image.GameObject.GetInstanceID(), image);

							screenObjects.Add(obj["id"].ToString(),image);


						}
						else if(objType == "button")
						{
							
							Log.Debug("Create Button:<color=yellow>"+objId+"</color>");
							UIButton button = new UIButton(obj);
							if(gameObject)
							{
								button.GameObject.transform.parent = gameObject.transform;
								button.Name = objId;
							}


							//images.Add(objId, button);
							images.Add(button.GameObject.GetInstanceID(), button);
							screenObjects.Add(obj["id"].ToString(),button);

						}

						else if(objType == "togglebutton" )
						{
							Log.Debug("Create Toggle Button:<color=yellow>"+objId+"</color>");
							UIToggleButton button = new UIToggleButton(obj);
							if(gameObject)
							{
								button.GameObject.transform.parent = gameObject.transform;
								button.Name = objId;
							}

							//TODO FIX_TOGGLE this hack! move button init to Settings.cs to Enter()
							// for SoundButton:
							// 	bool mutedMusic = AUDIO.AudioManager.Instance.MuteMusic;
							// 	bool mutedSfx = AUDIO.AudioManager.Instance.MuteSfx;
							// 	if(((mutedMusic) && (objId == "Settings.btn_Sound")) ||		// sets Sound button
							// 	   ((mutedSfx) && (objId == "Settings.btn_SoundEffects")))	// sets SoundEffects button
							// 	{
							// 		//button.SoundState = UISoundButton.UISoundButtonState.SOUNDOFF;
							// 		//button.SaveState = "Off";
							// 		button.Active = false;
							// 	}

							//images.Add(objId, button);
							images.Add(button.GameObject.GetInstanceID(), button);
							screenObjects.Add(obj["id"].ToString(),button);

						}
						else if(objType == "text")
						{
							
							Log.Debug("Create TEXT:<color=yellow>"+objId+"</color>");
							
							GameObject txt = new GameObject();
							txt.SetActive(false);
							txt.name = objId;
							UIText uiText = txt.AddComponent<UIText>() as UIText;
							uiText.Parse(obj);

							if(gameObject)
								txt.transform.parent = gameObject.transform;


							//images.Add(objId, text);
							txt.SetActive(true);
							screenObjects.Add(obj["id"].ToString(),uiText);

						}
						else if(objType == "popup")
						{
							//set prefab default to id and reset if defined							
							string prefab = (obj.ContainsKey("prefab")) 
								? obj["prefab"].ToString() : obj["id"].ToString();
							
							GameObject popup = GetPopup(obj["id"].ToString(), prefab);
							popup.SetActive(true);

							if(obj.ContainsKey("position"))
							{
								
								string pos = obj["position"].ToString();
								float px = System.Convert.ToSingle(pos.Split(',')[0]);
								float py = System.Convert.ToSingle(pos.Split(',')[1]);
								
								Log.Debug("HUD "+objId+" Position:"+px+","+py);
								popup.transform.position = new Vector3(px, py, 0);
								//this.gameObject.name = dict["position"].ToString();
							}
							if(obj.ContainsKey("rotation"))
							{
								
								string rot = obj["rotation"].ToString();
								float rx = System.Convert.ToSingle(rot.Split(',')[0]);
								float ry = System.Convert.ToSingle(rot.Split(',')[1]);
								
								//Log.Debug("Rotation:"+rot+":"+rx+","+ry);
								popup.transform.localRotation = Quaternion.Euler(new Vector3(rx, ry, 0));
							}
							if(obj.ContainsKey("scale"))
							{
								
								string sc = obj["scale"].ToString();
								float sx = System.Convert.ToSingle(sc.Split(',')[0]);
								float sy = System.Convert.ToSingle(sc.Split(',')[1]);
								
								popup.transform.localScale = new Vector3(sx, sy, 0);
								Log.Debug("Scale:"+sx+","+sy);
							}
							if(dict.ContainsKey("layer"))
							{
								string layer = dict["layer"].ToString();
								popup.layer = LayerMask.NameToLayer(layer);
								ChangeLayers(popup, layer);
								
							}
						}
						else if(objType == "hud")
						{

							//set prefab default to id and reset if defined							
							string prefab = (obj.ContainsKey("prefab")) 
									? obj["prefab"].ToString() : obj["id"].ToString();
							
							//Log.Debug("Create HUD as:"+prefab);
							GameObject hud = GetHud(obj["id"].ToString(), prefab);
							hud.SetActive(true);

							//Log.Warning("dict"+dict["layer"].ToString());
							if(obj.ContainsKey("position"))
							{

								string pos = obj["position"].ToString();
								float px = System.Convert.ToSingle(pos.Split(',')[0]);
								float py = System.Convert.ToSingle(pos.Split(',')[1]);

								Log.Debug("HUD "+objId+" Position:"+px+","+py);
								hud.transform.position = new Vector3(px, py, 0);
								//this.gameObject.name = dict["position"].ToString();
							}
							if(obj.ContainsKey("rotation"))
							{

								string rot = obj["rotation"].ToString();
								float rx = System.Convert.ToSingle(rot.Split(',')[0]);
								float ry = System.Convert.ToSingle(rot.Split(',')[1]);

								//Log.Debug("Rotation:"+rot+":"+rx+","+ry);
								hud.transform.localRotation = Quaternion.Euler(new Vector3(rx, ry, 0));
							}
							if(obj.ContainsKey("scale"))
							{
								string[] sc = obj["scale"].ToString().Split(',');
								float sx = System.Convert.ToSingle(sc[0]);
								float sy = System.Convert.ToSingle(sc[1]);
								float sz = 0;
								if (sc.Length > 2)
								{
									sz = System.Convert.ToSingle(sc[2]);
								}

								hud.transform.localScale = new Vector3(sx, sy, sz);
								Log.Debug(string.Format("Scale: {0}, {1}, {2}", sx, sy, sz));
							}
							// if(obj.ContainsKey("order"))
							// {
							// 	int order = System.Convert.ToInt32(obj["order"].ToString());
							// 	SortingOrder = order;

							// }
							if(obj.ContainsKey("layer"))
							{
								string layer = obj["layer"].ToString();
								hud.layer = LayerMask.NameToLayer(layer);
								ChangeLayers(hud, layer);

							}

							
						}
						else if(objType == "model")
						{
							
							//set prefab default to id and reset if defined							
							string prefab = (obj.ContainsKey("prefab")) 
								? obj["prefab"].ToString() : obj["id"].ToString();
							
							//Log.Debug("Create HUD as:"+prefab);
							GameObject hud = GetModel(obj["id"].ToString(), prefab);
							hud.SetActive(true);
							
							//Log.Warning("dict"+dict["layer"].ToString());
							if(obj.ContainsKey("position"))
							{
								
								string pos = obj["position"].ToString();
								float px = System.Convert.ToSingle(pos.Split(',')[0]);
								float py = System.Convert.ToSingle(pos.Split(',')[1]);
								float pz = System.Convert.ToSingle(pos.Split(',')[2]);
								
								Log.Debug("Model "+objId+" Position:"+px+","+py+","+pz);
								hud.transform.position = new Vector3(px, py, pz);
								//this.gameObject.name = dict["position"].ToString();
							}
							if(obj.ContainsKey("rotation"))
							{
								
								string rot = obj["rotation"].ToString();
								float rx = System.Convert.ToSingle(rot.Split(',')[0]);
								float ry = System.Convert.ToSingle(rot.Split(',')[1]);
								
								//Log.Debug("Rotation:"+rot+":"+rx+","+ry);
								hud.transform.localRotation = Quaternion.Euler(new Vector3(rx, ry, 0));
							}
							if(obj.ContainsKey("scale"))
							{
								
								string sc = obj["scale"].ToString();
								float sx = System.Convert.ToSingle(sc.Split(',')[0]);
								float sy = System.Convert.ToSingle(sc.Split(',')[1]);
								
								hud.transform.localScale = new Vector3(sx, sy, 0);
								Log.Debug("Scale:"+sx+","+sy);
							}
							// if(obj.ContainsKey("order"))
							// {
							// 	int order = System.Convert.ToInt32(obj["order"].ToString());
							// 	SortingOrder = order;
							
							// }
							if(obj.ContainsKey("layer"))
							{
								string layer = obj["layer"].ToString();
								hud.layer = LayerMask.NameToLayer(layer);
								ChangeLayers(hud, layer);
								
							}
							
							
						}
						else if(objType == "character")
						{
							
							Log.Debug("Create Character:<color=yellow>"+objId+"</color>");
							UICharacter uiChar = new UICharacter(obj);
							if(gameObject)
							{
								uiChar.GameObject.transform.parent = gameObject.transform;
								uiChar.Name = objId;
							}

							//TODO we might want this later
							//NPCView npcview = uiChar.GameObject.AddComponent<NPCView>();
							//npcview.id = objId;
							//npcview.image = uiChar;

							//read bubble info if any
							//TODO move this somewhere else? Should a bubble exist outside of uichar?
							if(obj.ContainsKey("bubble"))
							{
								foreach(Dictionary<string,object> bobj
									in ((List<object>)obj["bubble"]))
								{
									//TODO parse text parameter. (as text section?) This part is parsed
									//by UIText already, so we should only pass it over.
									//size (of text area), font, fontSize, anchor, alignment, wrapsize
									if(bobj.ContainsKey("position"))
									{

										string pos = bobj["position"].ToString();
										float px = System.Convert.ToSingle(pos.Split(',')[0]);
										float py = System.Convert.ToSingle(pos.Split(',')[1]);
										uiChar.bubblePosition = new Vector3(px, py, 0);
										Log.Debug("HUD "+objId+" bubble.Position:"+px+","+py);
									}

									if(bobj.ContainsKey("scale"))
									{

										string sc = bobj["scale"].ToString();
										float  sx = System.Convert.ToSingle(sc.Split(',')[0]);
										float  sy = System.Convert.ToSingle(sc.Split(',')[1]);
										uiChar.bubbleScale = new Vector3(sx, sy, 1);
										//Log.Debug("---------- bubble.scale:"+sx+","+sy);
									}

									if(bobj.ContainsKey("tail"))
									{

										uiChar.bubbleTail = bobj["tail"].ToString();
										
									}

								}
							}
							


							images.Add(uiChar.GameObject.GetInstanceID(), uiChar);
							screenObjects.Add(obj["id"].ToString(),uiChar);

						}
						else if(objType == "skit")
						{
							UISkit uiSkit = new UISkit(obj);
							if(gameObject)
							{
								uiSkit.GameObject.transform.parent = gameObject.transform;
								uiSkit.Name = objId;
							}

							if(obj.ContainsKey("bubble"))
							{
								foreach(Dictionary<string,object> bobj in ((List<object>)obj["bubble"]))
								{
									//TODO parse text parameter. (as text section?) This part is parsed
									//by UIText already, so we should only pass it over.
									//size (of text area), font, fontSize, anchor, alignment, wrapsize
									if(bobj.ContainsKey("position"))
									{

										string pos = bobj["position"].ToString();
										float px = System.Convert.ToSingle(pos.Split(',')[0]);
										float py = System.Convert.ToSingle(pos.Split(',')[1]);
										uiSkit.bubblePosition = new Vector3(px, py, 0);
									}

									if(bobj.ContainsKey("scale"))
									{

										string sc = bobj["scale"].ToString();
										float sx = System.Convert.ToSingle(sc.Split(',')[0]);
										float sy = System.Convert.ToSingle(sc.Split(',')[1]);
										uiSkit.bubbleScale = new Vector3(sx, sy, 1);
									}

									if(bobj.ContainsKey("tail"))
									{
										uiSkit.bubbleTail = bobj["tail"].ToString();
									}
								}
							}

							images.Add(uiSkit.GameObject.GetInstanceID(), uiSkit);
							screenObjects.Add(obj["id"].ToString(), uiSkit);
						}
						else if(objType == "video")
						{
							//Log.Info(" ---------------------------- -- ");
							//create canvas
							GameObject canvas = GameObject.CreatePrimitive(PrimitiveType.Quad);					
							GameObject.Destroy(canvas.GetComponent("MeshCollider"));
							canvas.name = objId;
							if(gameObject)
								canvas.transform.parent = gameObject.transform;

							UIVideo video = new UIVideo(canvas, obj);

							images.Add(video.GameObject.GetInstanceID(), video);
							screenObjects.Add(obj["id"].ToString(),video);

						}
					}
					else
					{
						Log.Error("Object missing id and/or type definition");
					}
				}

				return screenObjects;

			}

			return null;
		}//LoadResources()
 /// <summary>
 /// Button handler
 /// </summary>
 public virtual void ButtonOnOverExit(UIButton button)
 {
     //Log.Info("onOverExit - Button");
     if(handler != null && onOverExit != "")
     {
         handler.SendMessage(onOverExit, gameObject.name);
     }
 }
		}//LoadSprite()
		
		/// <summary>
		/// Adds a UI button.		
		/// </summary>
		/// <param name="obj">Parent game object.</param>
		/// <param name="fileName">Resource file name with path, relative to Rersources folder.</param>
		public UIObject Add(UIType type, GameObject obj, string fileName, Sprite spr = null)
		{
			Log.Info("Add: <color=yellow>"+obj.name+" - id:"+obj.GetComponent<GUIText>()+"</color> type:"+type);

			//// Log.GameTimes("_______________-_-_-_-_-_ <color=yellow>"+fileName+" _____ obj: "+obj+"</color>, type: "+type);


			if(images.ContainsKey(obj.GetInstanceID()))
			{
			 	//give warning, then return existing one (ignore new registration)
			 	Log.Debug("This button already registered, ignoring new registration. <color=cyan>" + obj.name+"</color> ");
			 	return images[obj.GetInstanceID()];
			}

			Sprite[] sprList = new Sprite[1];
			if(fileName.Length == 0)
			{

				if(spr == null)
				{
					Log.Debug("This button <color=yellow>"+obj.name+"</color> has no image.");
				}
				else
				{
					Log.Debug("Sprite >>>>>>>>>>>>>>>>> "+spr.name);
					sprList[0] = spr;
				}
			}
			else
			{
				sprList = LoadSprite(fileName);
			}



			UIObject image = null;
			switch(type)
			{
				case UIType.Image:
					Log.Debug("Add UIImage");
					image = new UIImage(obj, sprList);
					break;

				case UIType.Button:
					Log.Debug("Add UIButton");
					image = new UIButton(obj, sprList);
					break;

				case UIType.ToggleButton:
					Log.Debug("Add UIToggleButton");
					image = new UIToggleButton(obj, sprList);
					break;
					
				case UIType.Slider:
					Log.Debug("Add UISlider");
					image = new UISlider(obj, sprList);
					break;

				case UIType.Character:
					Log.Debug("Add UICharacter");
					image = new UICharacter(obj, sprList);
					break;

				case UIType.ChartPie:
					Log.Debug("Add UIChartPie");
					image = new UIChartPie(obj);
					break;

				case UIType.ChartLine:
					Log.Debug("Add UIChartLine");
					image = new UIChartLine(obj);
					break;

				case UIType.Checkbox:
					Log.Debug("Add Checkbox");
					image = new UICheckbox(obj, sprList);
					break;

				default:
					Log.Exception("Invalid UIType to add:" + type);
					break;
			}

			//TODO remove this
			images.Add(obj.GetInstanceID(), image);
			
			//
			//images.Add(""+lastId++, image);
			//Log.Info("Button added:"+obj.name+" image:"+image.Name);

			return image;

		}//Add()
        /// <summary>
        /// Handler for message head buttons
        /// Open the popup message with the right mail
        /// </summary>
        public void OnMessageClick(UIButton button)
        {
            Log.Debug("Message selected:"+button.Text);

            ShowMessage(button.Text);
        }