var CurrentPositionX = null;
var CurrentPositionY = null;


function RuleIcon(){
   try{
	 
 			 var _img = null;
			 
			 var _container = null;
			 
			 var _isHighlighted = null;
			 
			 var _blankIcon = $("<img src='../../images/blankIcon.jpg' />");
			 
			 var _iconMover = null;
	 
	 
			 this.Load = function(component)
			 {
			   try{
				 		 
					 _img = $("<img/>");
					 
					 _img.attr("src", component.Src);
					 
					 _img.attr("title", component.GetID() + ": " + component.GetComment() );					 
			  
					 _img.attr("id", component.GetID());
					 
					 _img.addClass("icon");
					 
			     _img.css("top", component.GetY());
					 
					 _img.css("left", component.GetX());
					 
					 _img.css("position", "absolute");
					 
					 AddFeatures();
					 
			   }catch(err){ Log.Add("RuleIcon.Load", err, LogType.Error);}
			 }
			 
			 
			 this.AppendTo = function(Container)
			 {
			   try{
  			   _container = Container;
				 
	  			 _container.append(_img);
					 
					 this.ShowComment();					 
				
				 }catch(err){ Log.Add("RuleIcon.AppendTo", err, LogType.Error);}
			 }
			 
			 // removes the image from the canvas
			 this.Delete = function()
			 {

				 _container.find("div[commentid='" + _img.attr("id") + "']").remove();
				 
			   _img.remove();				 
				 
			 }
			 
			 
			 this.GetContainer = function()
			 {
			   try{
				 
			     return _container;

			   }catch(err){ Log.Add("RuleIcon.GetContainer", err, LogType.Error);}					 
			 }
			 
			 
			 
			 
			 this.GetEntryPoint = function()
			 {
			   try{
				 
  			 	 return getEntryPoint();
					 
			   }catch(err){ Log.Add("RuleIcon.GetEntryPoint", err, LogType.Error);}					 
			 }

			 
			 this.GetExitPoint = function()
			 {
			   try{
				 
  			   return getExitPoint();
					 
			   }catch(err){ Log.Add("RuleIcon.GetExitPoint", err, LogType.Error);}					 
			 }
			 
			 this.GetImage = function()
			 {
			   return _img;
			 }
			 
			 this.Highlight = function()
			 {
			   try{
				   
					  if(_isHighlighted == null)
						{
						  _isHighlighted = true;
							_blankIcon.css("position", "absolute").css("top", _img.css("top")).css("left", _img.css("left"));
							_blankIcon.addClass("icon");
							_blankIcon.attr("id", _img.attr("id"));
							_container.append(_blankIcon);
						}

						if(_isHighlighted == false)
						{
						  _isHighlighted = null;
							_container.remove(_blankIcon);
							_blankIcon = null;
							_blankIcon = $("<img src='../../images/blankIcon.jpg' />");
							return;
						}
				 
					 	_blankIcon.fadeTo(250, 0.0, function(){ 
						  try{
							  $(this).fadeTo(500, 0.75, function(){
								  try{ 
  						      var id = $(this).attr("id");
	  							  var ctrl = RuleStorage.GetComponent(id);
		  						  ctrl.Icon.Highlight();
									}catch(err){ }
							  })
							}catch(err){ }    
						});
						
						_blankIcon.unbind("click.ruleiconhighlight").bind("click.ruleiconhighlight", function(){
						  try{

							  $(this).remove();

							}catch(err){ alert("got here");  Log.Add("RuleIcon.Highlight - highlight click", err, LogType.Error)}	
						});
						
						_isHighlighted = true;
				   
				 }catch(err){Log.Add("RuleIcon.Highlight", err, LogType.Error)}
			 }
			 
			 this.IconMoved = function()
			 {
			   try{
					 
					 _iconMover.Refresh();
					 					 
				 }catch(err){Log.Add("RuleIcon.RemoveHighlight", err, LogType.Error)}			   
			 
			 }	
			 
			 this.MoveBy = function(x, y)
			 {
			   var newX = parseInt(_img.css("left").replace("px", "")) + x;
			   var newY = parseInt(_img.css("top").replace("px", "")) + y;
				 
			   _img.css("left", newX).css("top", newY);
				 
				 IconMover.Load(_img.attr("id"));
				 IconMover.Refresh();
			 }
			 
			 this.SetIconMover = function(mover)
			 {
			   _iconMover = mover;
			 }		 
			 
			 
			 this.RemoveHighlight = function()
			 {
			   try{
					 
					 _isHighlighted = false;
					 
				 }catch(err){Log.Add("RuleIcon.RemoveHighlight", err, LogType.Error)}			   
			 
			 }
			 

			 
			 
			 this.ShowComment = function(newComment)
			 {
			   try{
				 
				   if(newComment != null)
					   _img.attr("title", newComment);
				   
					 var _div = _container.find("div[commentid='" + _img.attr("id") + "']");
					 
					 if(_div.length == 0)
					 {
					   _div = $("<div class='RuleIconComment' commentid='" + _img.attr("id") + "'>");
	 					 _container.append(_div);
					 }
						 
					 var disp = _img.attr("title");
					 
					 var lf = String.fromCharCode(10);
					 
					 var cr = String.fromCharCode(13);
					 
					 if((disp.indexOf(lf) > -1) && (disp.indexOf(lf) <= 50))
					   disp = disp.substring(0, disp.indexOf(lf) );
						 
					 _div.text(disp.substring(0, 50));
					 
					 _div.css("top", _img.css("top")).css("left", _img.css("left"));
			 
				 }catch(err){Log.Add("RuleIcon.ShowComment", err, LogType.Error)}			 
			 }
			 
			 

			 
			 
			 
			 function AddFeatures()
			 {
			   try{
				 
 					 _img.draggable({

					   containment: "parent", 

						 grid:[32, 26],
						 
						 start: function(){
						   CurrentPositionX = null;
							 CurrentPositionY = null;
						 },
						 
						 stop: function(){
						   
               var selected = RulesMaker.GetSelected();
                
               if(selected.length == 0)
                 return;
                
               for(var i = 0; i < selected.length; i++)
               {
                 var id = selected[i];
        				 var ctrl = RuleStorage.GetComponent(id);
								 ctrl.Icon.ShowComment();								  
               }
						 },
						 
						 drag: function(){
						 
						   var x = $(this).css("left");

							 var y = $(this).css("top");
						   
						   if((CurrentPositionX == x) && (CurrentPositionY == y))
							   return;

							 var diffX = null;
							 
							 var diffY = null;
							 
							 if((CurrentPositionX != null) && (CurrentPositionY != null))
							 {
							   diffX = parseInt(x.replace("px", ""))- parseInt(CurrentPositionX.replace("px", ""));
							   diffY = parseInt(y.replace("px", "")) -  parseInt(CurrentPositionY.replace("px", ""));
							 }

							 CurrentPositionX = x;
							 CurrentPositionY = y;
							 
							 if($(this).hasClass("ui-selected"))
							 {
						     IconMover.MoveSelected(diffX, diffY);
							 }
							 else
							 {
							   var ctrl = RuleStorage.GetComponent(_img.attr("id"));
							   ctrl.Icon.IconMoved();
							 }
						 }
					 });
  				 
					 
  			   _img.unbind("dblclick.Icon").bind("dblclick.Icon", function(){
  
					 	 var _id = $(this).attr("id");
						 
  				   RulesMaker.ShowProperties(_id);
						 
  				 });
					 
  			   _img.unbind("click.Icon").bind("click.Icon", function(){
  
					 	 var _id = $(this).attr("id");
						 
						 IconConnector.IconClicked(_id);

  				 });					 
		 
  				 _img.unbind("mousedown.Icon").bind("mousedown.Icon", function(){
  				 
					   try{
					 
							 _img.css("cursor", "move");
  						 
  						 var ctrl = RuleStorage.GetComponent(_img.attr("id"));
  						 
  						 IconMover.Load(_img.attr("id"));
  						 
  						 IconMover.Enable();
							 
							 ctrl.Icon.SetIconMover(IconMover);		
							 
							 return false;
							 
  				   }catch(err){ Log.Add("RuleIcon.MouseDown", err, LogType.Error);}
  				 });
  				 
					 
  				 _img.unbind("mouseup.Icon").bind("mouseup.Icon", function(){
					 
					   try{
							 
							 Graphics.Refresh();
  
  						 IconMover.Reset();
  					 
    					 _img.css("cursor", "default");
  						 
  						 var ctrl = RuleStorage.GetComponent(_img.attr("id"));
  						 
  						 ctrl.SetX( Utilities.ToNumber(_img.position().left));
  						 
  						 ctrl.SetY( Utilities.ToNumber(_img.position().top) );
							 
						 }catch(err){ Log.Add("RuleIcon.MouseUp", err, LogType.Error);}
  				 });
					 
					 
					 
			   }catch(err){ Log.Add("RuleIcon.AddFeatures", err, LogType.Error);}				 
			 }
			 
			 

			 
			 function getEntryPoint()
			 {
			   try{
            var t = Utilities.ToNumber(_img.css("top"));
            var l = Utilities.ToNumber(_img.css("left"));
            var w = Utilities.ToNumber(_img.width());
               
            var x = l + parseInt(w / 2);
            var y = t;
            
            return new Graphics.Point(x, y);
						
			   }catch(err){ Log.Add("RuleIcon.getEntryPoint", err, LogType.Error);}						 
			 } 
			 
			 function getExitPoint()
			 {
			   try{
            var t = Utilities.ToNumber(_img.css("top"));
            var l = Utilities.ToNumber(_img.css("left"));
            var w = Utilities.ToNumber(_img.width());
            var h = Utilities.ToNumber(_img.height());
               
            var x = l + parseInt(w / 2);
            var y = t + h;
            
            return new Graphics.Point(x, y);
						
			   }catch(err){ Log.Add("RuleIcon.getExitPoint", err, LogType.Error);}									 
			 }
	 
	 
	 }catch(err){ Log.Add("RuleIcon", err, LogType.Error);}
}













IconMover = new function()
{
  

  return{
	  
		Load: function(id)
		{
		  try{
		
        this.Ctrl = RuleStorage.GetComponent(id);
				
  		  this.Ctrl.OldEntry = this.Ctrl.GetIcon().GetEntryPoint();
  						 
    		this.Ctrl.OldExit = this.Ctrl.GetIcon().GetExitPoint();				
    
  
  			var temp = RuleXML.GetFromComponent(id);
  			
  			if(temp != null)
  			{
  			  this.FromJ1 = (temp.GetJ1() == this.Ctrl.GetID());
          this.From = temp.GetIcon().GetExitPoint();
  			}
        
  			
  			if(this.Ctrl.GetJ1() != "")
  			{
          temp = RuleStorage.GetComponent(this.Ctrl.GetJ1());
  			
  			  this.J1 = temp.GetIcon().GetEntryPoint();
  			}
  			
  			if((this.Ctrl.GetJ2 != null) && (this.Ctrl.GetJ2() != ""))
  			{
          temp = RuleStorage.GetComponent(this.Ctrl.GetJ2());
  			
  			  this.J2 = temp.GetIcon().GetEntryPoint();
  			}
			}catch(err){ Log.Add("IconMover.Load", err, LogType.Error);}
		},
		
		MoveSelected: function(x,y)
		{
		  var selected = RulesMaker.GetSelected();
			
			if(selected.length == 0)
			  return;

			for(var i = 0; i < selected.length; i++)
			{
			  var ctrl = RuleStorage.GetComponent(selected[i]);
				
				ctrl.Icon.MoveBy(x, y);
				
				//ctrl.Icon.IconMoved();
			
			}
		},
		
		Reset: function()
		{
		  this.Ctrl = null;
			
			this.From = null;
			
			this.FromJ1 = null;
			
			this.J1 = null;
			
			this.J2 = null;
			
			this.Enabled = false;
			
		},
		
    Enable: function()
		{
		  this.Enabled = true;
		},
		
		Refresh: function()
		{
		  try{

  			if(!this.Enabled)
  			  return;
					
				this.Ctrl.Icon.ShowComment();
  
  		  Graphics.ReDraw();
				
			}catch(err){ Log.Add("IconMover.Refresh", err, LogType.Error);}					
		},
		
		Enabled: false, 				// whether the control is enabled
  	
		Ctrl: null,			  			// a rules maker component
  	
		J1: null,				 	 	 		// the primary point the control goes to
  	
		J2: null,				 		 		// the secondary point the control goes to 
  	
		From: null,			 			  // the point that goes to the control
		
		FromJ1: null,
		
		RefreshRate: 500				// the rate at which the canvas refreshes
		
  }	
	
}















IconConnector = new function()
{

 $(document).bind("keydown", function(event){
  IconConnector.KeyDown(event);
 });	

 $(document).bind("keyup", function(){
  IconConnector.KeyUp();
 }); 
 
 var _keyIsDown = false;
 var _keyCode = null;
 var _clickedComponentID = null;
 var _j1Set = false;
 var get = null;
 var set = null;
 
 return {
 
 
   IconClicked: function(ID)
	 {
	   try{
		   
  	   if(!_keyIsDown)
			   return;
		 
	     if(_clickedComponentID == null)
		   {
 		     _clickedComponentID = ID;		// remembers the first component clicked
				 
				 return;
 			 }
				 
	     if(_clickedComponentID == ID) 
			   return;


			 // two separate components have been clicked

       var f = RuleStorage.GetComponent(_clickedComponentID);
			 
			 if(f.SetJ1 == null)
			   return;

       var t = RuleStorage.GetComponent(ID);
			 
			 if(_j1Set == false)
			 {
			 	 get = f.GetJ1 
			 } else {
			   if(f.GetJ2 != null)
				   get =  f.GetJ2;
			 }
				 
			 if(_j1Set == false)
			 {
			 	 set = f.SetJ1 
			 } else {
			   if(f.SetJ2 != null)
				   set =  f.SetJ2;
			 }
      
       switch(get())
			 {
			   case "":
				   this.Connect(f, t, set);
					 if(f.GetJ2 != null)
					   _j1Set = true;
				   break;
					 
				 case ID:
				   this.DisConnect(f, t, set);
					 if(f.GetJ2 != null)
					   _j1Set = true;
				   break;
			 
			   default:
				   this.Connect(f, t, set);
					 if(f.GetJ2 != null)
					   _j1Set = true;
			 }

				 
			 
		}catch(err){ Log.Add("IconConnector.IconClicked", err, LogType.Error);} 	 
	 },
	 
	 
	 Connect: function(From, To, Set)
	 {
 	   Global.ShowEditModeMessage("Connect From: " + From.GetID() + " To: " + To.GetID());
 		 Set(To.GetID());
		 Graphics.Refresh();
	 },
	 
	 DisConnect: function(From, To, Set)
	 {
	   Global.ShowEditModeMessage("DisConnect From: " + From.GetID() + " To: " + To.GetID());
		 Set("");
		 Graphics.Refresh();
	 },
   
	 KeyDown: function(event)
	 {
	   try{
 
  	   _keyCode = event.keyCode;

	  	 if(_keyCode == 16)
			 {
  	  	 _keyIsDown = true;
				 
			 }
				 
		}catch(err){ Log.Add("IconConnector.KeyDown", err, LogType.Error);}
	 },
	 
	 KeyUp: function()
	 {
	   Reset();
	 }
	 

 }
 
 function Reset()
 {
   _keyIsDown = false;
   _keyCode = null;
   _clickedComponentID = null;
	 _j1Set = false;
 }
 
 
 


}


