/* 	Copyright 2008 Maximum Processing Inc
	This script provides javascript Control Objects that control the behavior of the editor

	ABOUT THIS SCRIPT [* = not required on EditableContent Container]
	Required public methods
	  0. AppendTo
          1. DefaultMode
          2  EditMode
          3. GetControl
          4. Load
          
        Required Public Properties
          1. Ref
          2. NameRequired
	
        Dependencies:
        1. logging.js
        2. container.rules.js
        3. utilities.js

	Change Log
 	Created 11/20/2008 Nathan Townsend
 	11/22/2008 - added logging NT
 	12/01/2008 - added max length & filter drop down
 	
 	
*/







//  Editor Text Control [NT 11/17/2008]
function EditorText(){
  try{
	
  this.inheritFrom = TemplateBase;

	this.inheritFrom();
	
	this.inheritFrom = ValidationBase;
	
	this.inheritFrom();	

  /* PRIVATE PROPERTIES */
  var control = null;

  var featuresAdded = false;
  
  var input = null;

  var properties = null;
  
  var span = null;

  
  /* PUBLIC METHODS */

	
    // Appends the control to a container element
    this.AppendTo = function(ContainerElement)
    {
      try{
    
          $(ContainerElement).append(control);
          
					this.BaseLoad(control, input);
					
					this.ValidationBaseLoad(control, input);
					
          if(Editor.IsEnabled())
            this.EditMode();
            
          this.Refresh(); 
					
  				control.attr("origT", control.css("top"));	

					control.attr("origL", control.css("left"));				       
          
      } catch(err){ Log.Add("EditorText.AppendTo", err, LogType.Error); }
    };
    
    this.Create = function(ctrlName)
    {
      try{
    
          var name = ctrlName;

          control = $("<div condition='' />");

          control.html("<span>Text</span><input id='" + name + "' name='" + name + "' maxlength='30'>");

          control.addClass("component EditorText");

          control.attr("ref", "EditorText");

          input = $($(control).find("input"));

          span = $($(control).find("span"));

          span.css("cursor", "text");

          span.addClass("notRequired");

          span.click(function(){input.focus()});
					
          //Log.Add("EditorText.Create", "Created: " + input.attr("name"), LogType.Info);
          
      } catch(err){ Log.Add("EditorText.Create", err, LogType.Error); }
    };

    this.DefaultMode = function()
    {
      try{
				
	      RemoveFeatures();
				
				this.AttachFilter();
				
				this.AttachFunctions();
				
				input.css("margin-left", "");
				
				// Date fields should automatically show a date selector on focus
				if(this.GetFilters && !PropertiesEditor.Saving)
				{
				  var _boolSetDate = false;
					var _minDate = null;
					var _maxDate = null;
				  var filters = this.GetFilters();

					for(var i = 0; i<filters.length; i++)
					{
					  var filter = filters[i];
						
						if(filter.Filter == "DATE")
						  _boolSetDate = true;
						
						if(filter.DType == "DATE")
						{
						  var s = filter.Param.split("/");
							
							var y = parseInt(s[2]);
							var m = parseInt(s[0]) - 1;
							var d = parseInt(s[1]);
							
						  if(filter.Filter == "GREATERTHANEQUALS")
							  _minDate = new Date(y, m, d);
								
						  if(filter.Filter == "GREATERTHAN")
							  _minDate = new Date(y, m, d + 1);
								
						  if(filter.Filter == "LESSTHANEQUALS")
							  _maxDate = new Date(y, m, d);
								
						  if(filter.Filter == "LESSTHAN")
							  _maxDate = new Date(y, m, d - 1);
						}
					}
					
					if(input.attr("disabled") || input.attr("readonly"))
					  _boolSetDate = false;
					
					if(_boolSetDate)
					{
					  input.datepicker({
						  minDate: _minDate,
							maxDate: _maxDate
						});
					}
				}
        
        Helper.RemoveComponentID(control);
        
      } catch(err){ Log.Add("EditorText.DefaultMode", err, LogType.Error);}
    };

    this.EditMode = function()
    {
      try{
			
				control.attr("origT", control.css("top"));
				
				control.attr("origL", control.css("left"));

				var v = Utilities.Trim(input.val());
				
				input.val(v);			
      
        AddFeatures();
				
				input.css("margin-left", ""); // added for a fix after adding doctype

				this.DetachFilter();
				
				this.DetachFunctions();
				
				input.datepicker("destroy");
				
				input.removeClass("hasDatepicker");
				
      } catch(err){ Log.Add("EditorText.EditMode", err, LogType.Error); }
    };
    
    this.GetProperties = function()
    {
      try{
          var pref = Helper.GetParentRef(control);
             
          var properties = this.GetBaseProperties();
          
          properties[properties.length] = new PropertiesEditor.Property(PropertyFields.GetProperty("Name"), this.GetName, null);
          
          properties[properties.length] = new PropertiesEditor.Property(PropertyFields.GetProperty("Caption"), this.GetCaption, this.SetCaption);
          
          properties[properties.length] = new PropertiesEditor.Property(PropertyFields.GetProperty("MaxLength"), this.GetMaxLength, this.SetMaxLength);

          properties[properties.length] = new PropertiesEditor.Property(PropertyFields.GetProperty("Required"), this.GetRequired, this.SetRequired);
					
//          properties[properties.length] = new PropertiesEditor.Property(PropertyFields.GetProperty("Tags"), this.GetValueLessAttrs, this.SetValueLessAttrs);					
					
          if(pref == "StaticContainer")
            properties[properties.length] = new PropertiesEditor.Property(PropertyFields.GetProperty("Width"), this.GetWidth, this.SetWidth);

					properties = this.GetValidationProperties(properties);
            
          return properties;
          
       } catch(err){ Log.Add("EditorText.GetProperties", err, LogType.Error); }
    };
		
    this.Load = function(ControlElement)
    {
      try{
          control = $(ControlElement);

          span = $(control.find("span"));

          span.css("cursor", "text");
            
          input = $(control.find("input"));

          span.click(function(){input.focus()});
					
					this.BaseLoad(control, input);
					
					this.ValidationBaseLoad(control, input);
					
          //Log.Add("EditorText.Load", "Loaded: " + input.attr("name"), LogType.Info);
          
      } catch(err){ Log.Add("EditorText.Load", err, LogType.Error); }
    };

    this.Refresh = function()
    {
      try{
      
          ResizeControl();
          
          //Log.Add("EditorText.Refresh", "Refreshed: " + input.attr("name"), LogType.Info);
          
      } catch(err){ Log.Add("EditorText.Refresh", err, LogType.Error); }
    };
		
		
		this.ErrorStatus = function(boolStatus)
		{
      try{
			
			  if(boolStatus)
				  control.addClass("error");
				else
				  control.removeClass("error");			  
			  
			           
      } catch(err){ Log.Add("EditorText.ErrorStatus", err, LogType.Error); }		
		}
		
		this.SetFocus = function()
		{
      try{

			  input.focus();
				
      } catch(err){ Log.Add("EditorText.SetFocus", err, LogType.Error); }
		}
		
    this.GetControl = function()
    { 
      try{
       
       return control; 
      
      } catch(err){ Log.Add("EditorText.GetControl", err, LogType.Error); }
    };

    this.GetCaption = function()
    { 
      try{
        return span.text(); 
      } catch(err){ Log.Add("EditorText.GetCaption", err, LogType.Error); }
    };
		
		/*
    this.GetValueLessAttrs = function()
    {
      try{
        
				var html = new HTMLParser(input);
				
				var attrs = html.Attributes();
				
				var ret = "";
				
				for(var i = 0; i< attrs.length; i++)
				{
				  if(attrs[i].indexOf("=") == -1)
					  ret += attrs[i] + " ";
				}
				
				ret = Utilities.ReplaceAll(ret, "  ", " ");
				
				if(ret.charAt(0) == " ")
				  ret = ret.substring(1);
					
				if(ret.charAt(ret.length-1) == " ")
				  ret = ret.substring(0, ret.length-1);				
					
				return ret;
      
      } catch(err){ Log.Add( this.Ref + ".GetChecked", err, LogType.Error); }
    };
		
		this.SetValueLessAttrs = function(newValue)
    {
      try{
			
			  if(Utilities.ReplaceAll(newValue, " ", "").length == 0)
				  return;

				var parser = new HTMLParser(input);
				
				var attrs = parser.Attributes();
				
				parser = null;
				
				for(var i = 0; i< attrs.length; i++)
				{
				  if(attrs[i].indexOf("=") == -1)
					{
					  var attr = attrs[i].replace(/\s+/g, "");
					  input.removeAttr(attr);
					}
				}

				newValue = Utilities.ReplaceAll(newValue, "  ", " ");				
				
				if(newValue.charAt(0) == " ")
				  newValue = newValue.substring(1);
					
				if(newValue.charAt(newValue.length-1) == " ")
				  newValue = newValue.substring(0, newValue.length-1);
					
				attrs = newValue.split(" ");
				
				for(var i = 0; i<attrs.length; i++)
				{
				  var attr = attrs[i];
					
					input.attr(attr.toUpperCase(), "");
				}
			       
      } catch(err){ Log.Add("EditorText.SetDisabled", err, LogType.Error); }
    };	
		*/
		
		
		this.GetErrorMessage = function()
		{
      try{ 
			  if(this.GetRequired())
				{
				  if( Utilities.Trim(input.val()).length == 0 )
					{
					  return "You must enter the field marked '" + span.text() + "'";
					}
					
					return null;
				}
      } catch(err){ Log.Add("EditorText.GetErrorMessage", err, LogType.Error); }		  
		}		
    

    this.GetMaxLength = function()
    { 
      try{ 
        return input.attr("maxlength"); 
      } catch(err){ Log.Add("EditorText.GetMaxLength", err, LogType.Error); }
    };


    this.GetName = function()
    { 
      try{ 
        return input.attr("name"); 
      } catch(err){ Log.Add("EditorText.GetName", err, LogType.Error); }
    };

    this.GetRequired = function()
    {
      try{ 
        return span.hasClass("required");
      } catch(err){ Log.Add("EditorText.GetRequired", err, LogType.Error); }
    };
		

		
    this.GetWidth = function()
    { 
      try{
        return input.width(); 
      } catch(err){ Log.Add("EditorText.GetWidth", err, LogType.Error); }
    };
		
		
		
	
		
		
		
		

    this.SetCaption = function(newCaption){
      try{
        span.text(newCaption);
      } catch(err){ Log.Add("EditorText.SetCaption", err, LogType.Error); }
    };
      

    this.SetMaxLength = function(newValue){
      try{
        input.attr("maxlength", newValue);
      } catch(err){ Log.Add("EditorText.SetMaxLength", err, LogType.Error); }
    };

    this.SetName = function(newName){
      try{
        
        var ctrl = Helper.GetEditorComponent(control);

        var ml = ctrl.GetMaxLength();
        
        var filter = ctrl.GetFilter();
        
        var width = ctrl.GetWidth();
        
        var value = input.val();
        
        var newInput = $("<input id='" + newName + "' name='" + newName + "' >");
        
        newInput.attr("maxlength", ml);
        
        newInput.attr("filter", filter);
        
        newInput.css("width", width);
        
        newInput.val(value);
        
        input.replaceWith(newInput);
        
        input = newInput;
        
      } catch(err){ Log.Add("EditorText.SetName", err, LogType.Error); }
    };

    this.SetRequired = function(required){
      try{
          span.removeClass("required").removeClass("notRequired");

          if(required == "true")
					{
            span.addClass("required");
						//input.attr("required", "");
					}
          else
					{
            span.addClass("notRequired");
						//input.removeAttr("required");
					}
            
      } catch(err){ Log.Add("EditorText.SetRequired", err, LogType.Error); }
    };

    this.SetWidth = function(newWidth){
      try{
          var w = Utilities.ToNumber(newWidth);
          input.css("width", w);
          ResizeControl();
      } catch(err){ Log.Add("EditorText.SetWidth", err, LogType.Error); }
    };


    /* PUBLIC PROPERTIES */    
    this.NameRequired = true;
    
    this.Ref = "EditorText";
		



  /* PRIVATE METHODS */
  // sizes the control around the input element
  function ResizeControl(){
    try{
 
        var width = input.outerWidth();

        var height = input.outerHeight();

        var top = ( (height - input.innerHeight()) / 2 ) - 4;

        if(top < 0)
          top = 0;

        span.css("width", width - 6).css("height", height);

        width = width + Utilities.ToNumber(control.css("padding-left")) + Utilities.ToNumber(control.css("padding-right")) + Utilities.ToNumber(control.css("border-left-width")) + Utilities.ToNumber(control.css("border-right-width"));
        
        control.css("width", width);
				
				control.css("top", control.attr("origT"));
				
				control.css("left", control.attr("origL"));
        
    } catch(err){ Log.Add("EditorText.ResizeControl", err, LogType.Error); }
  }


  // adds features to the control based on the rules specified for this type of control
  function AddFeatures()
  {
    try{
        if(featuresAdded)
          return;
        
        var pref = Helper.GetParentRef(control);

        if(pref == "StaticContainer")
        {
          control.css("cursor", "move");
          control.draggable({
					  containment: "parent", 
						delay:500,
						stop: function(){
						  control.attr("origT", control.css("top"));
							control.attr("origL", control.css("left"));
						}
					});
        }

        if(pref == "StaticContainer")
        {
          control.resizable({
						autoHide: true,
            distance: 25,
            maxHeight: control.height(),
            minHeight: control.height(),
            resize: function(e, ui){ 
              input.width(ui.size.width);
              ResizeControl();
            }
          });
        }
        
        control.bind("dblclick.EditorText", function(event){event.stopPropagation(); Editor.ShowProperties(control); Editor.ShowAcceptedComponents(this); });
        
        control.addClass("editing");
        
        span.attr("unselectable", "on");
				
        featuresAdded = true;
        
        //Log.Add("EditorText - AddFeatures", "Features Added", LogType.Info);
        
    } catch(err){ Log.Add("EditorText.AddFeatures", err, LogType.Error); }
  }

  // removes features from the control that were previously added 
  function RemoveFeatures()
  {
    try{
				
        if(!featuresAdded)
          return;
        
        control.css("cursor", "default");

        control.draggable("destroy");

        control.resizable("destroy");
          
        control.unbind("dblclick.EditorText");
        
        control.removeClass("editing");
        
        span.removeAttr("unselectable");
				
        featuresAdded = false;
        
        //Log.Add("EditorText - RemoveFeatures", "Features Removed", LogType.Info);
        
    } catch(err){ Log.Add("EditorText.RemoveFeatures", err, LogType.Error); }
  }

 // Catches every error in Editor Text
 } catch(err){ Log.Add("EditorText", err, LogType.Error); }
}


/* +++++++++++++++++++ END EditorText CONTROL +++++++++++++++++++*/






