if (!window.My) My=[];
if (!My.Templates) My.Templates=[];


// ****************************************************************
//    Input Cell Template.
// ****************************************************************
My.Templates.Input = Active.Templates.Text.subclass();

My.Templates.Input.create = function()
{
    var obj = this.prototype;

//    editor is not part of the template,
//    there is only one single instance of editor object.
    var editor = new Active.HTML.INPUT;
    editor.setClass("templates", "input");
    editor.setAttribute("type", "text");
    editor.setAttribute("value", function(){
        return template.getItemProperty("text");
    });
  	editor.setAttribute("autocomplete","OFF");

//    template variable provides temporary reference
//    to the parent template during edit mode.
    var template;

    function switchToEditMode(){
        if (template) {
            switchToTextMode()
        }
        template = this;
        template.element().style.padding = 0;
        template.element().innerHTML = editor;
        editor.element().focus();
		editor.setEvent("ondblclick", switchToTextMode);
    }

    //obj.setEvent("onfocus", switchToEditMode);
		obj.setEvent("ondblclick", switchToEditMode);

    function switchToTextMode(){
        var value = editor.element().value;
		var originalText = template.getItemProperty("text");
		if(originalText != value) {
			var idx = template.grid.getProperty("selection/index");
			template.model.setCell(idx,template.column,value);
			template.refresh();
			template.action("changeInputAction");
		}
		else {
			template.refresh();
		}
		template = null;
    }

    editor.setEvent("onblur", switchToTextMode);
		editor.setEvent("onkeypress", changeKey);

		function changeKey(e){
	switch(e.keyCode){
		case 27: // esc
				editor.element().value=template.getItemProperty("text");
				switchToTextMode();
		break;
		case 13: // enter = down
			switchToTextMode();
		break;
		default:
		break;
	}
		}


};

My.Templates.Input.create();


// ****************************************************************
//    ComboBox Cell Template.
// ****************************************************************
My.Templates.ComboBox = Active.Templates.Text.subclass();

My.Templates.ComboBox.create = function()
{
  var obj = this.prototype;
  var editor= new Active.System.HTML;
    var template;
    function switchToEditMode(){
        if (template) {
            switchToTextMode()
        }
        template = this;
				editor = new Active.System.HTML;
				editor.setTag("select");
				editor.setContent(template.contenido);
				editor.setEvent("onblur", switchToTextMode);
        template.element().style.padding = 0;
        template.element().innerHTML = editor;
        editor.element().focus();
    }

    obj.setEvent("ondblclick", switchToEditMode);

    function switchToTextMode(){
        var value =  editor.element().value;
        var originalVal = template.getItemProperty("text");

        if(originalVal != value){
            if(template.url!=undefined){
              if(!(template.url=='null'||template.url=='')){
                  preparaEnvio(template.url+value,template.column,template.model);
              }
            }
            var idx=template.grid.getProperty("selection/index");
						template.model.setCell(idx,template.column,value);
        }
        template.refresh();
        template = null;
    }
    editor.setEvent("onblur", switchToTextMode);


};

My.Templates.ComboBox.create();

// ****************************************************************
//     Checkbox Cell Template.
// ****************************************************************
My.Templates.Checkbox = Active.System.Control.subclass();

My.Templates.Checkbox.create = function(){

  var obj = this.prototype;

  obj.defineModel("checked");
  obj.defineCheckedProperty("true", "Y");
  obj.defineCheckedProperty("false", "N");

  obj.setClass("templates","checkbox");
  var template;
  var checkbox = new Active.HTML.INPUT;
  checkbox.setClass("input","checkbox");
  checkbox.setClass("checkbox", function(){return this.getColumnProperty("index")});
  checkbox.setAttribute("type","checkbox");
  checkbox.setAttribute("checked", function(){
    return (this.getItemProperty("text") == this.getCheckedProperty("true"))
  });

  function toggleValue(src){
  template=this;
 var originalVal = this.getItemProperty("text");
 var newValue = (originalVal == this.getCheckedProperty("true")) ?this.getCheckedProperty("false") : this.getCheckedProperty("true");
 //var idx = template.grid.getProperty("selection/index");
 //HORRIBLE PATCH; MUST FIX AS SOON AS POSSIBLE
 var patch = src.srcElement.id;
 var string = patch.split(':');
 string[1]=parseInt(string[1].replace(/\D+/,''));
 string[2]=parseInt(string[2].replace(/\D+/,''));
 ////////////////////////////////////////////////
 
 template.model.setCell(string[1],string[2],newValue);
 template.refresh();
 template=null;

  }

  checkbox.setEvent("onclick", toggleValue);
	//checkbox.setEvent("ondblclick", toggleValue);

  obj.setContent("checkbox", checkbox);

};
My.Templates.Checkbox.create();



// ****************************************************************
//     CheckboxLabel Cell Template.
// ****************************************************************

My.Templates.CheckboxLabel = My.Templates.Checkbox.subclass();

My.Templates.CheckboxLabel.create = function(){

  var obj = this.prototype;

  var label = new Active.HTML.SPAN;
  label.setClass("checkbox","label");

  obj.setContent("label", label);
};

My.Templates.CheckboxLabel.create();


// ****************************************************************
//     Date Cell Template.
// ****************************************************************
My.Templates.Date = Active.Templates.Text.subclass();

My.Templates.Date.create = function()
{
  var obj = this.prototype;

  // editor is not part of the template,
  // there is only one single instance of editor object.
  var editor = new Active.HTML.INPUT;
  editor.setClass("templates", "input");
  editor.setAttribute("type", "text");
  editor.setAttribute("autocomplete","OFF");
	editor.setAttribute("readonly","true");
  editor.setAttribute("value", function(){
      return template.getItemProperty("text");
  });
  // template variable provides temporary reference
  // to the parent template during edit mode.
  var template;

  function switchToEditMode(){
      if (template) {
          switchToTextMode()
      }
      template = this;
      template.element().style.padding = 0;
      template.element().innerHTML = editor;
      editor.element().focus();
      // pop-up calendar now
      var onSelect = function(calendar, date){
          if(calendar.dateClicked){
              editor.element().value = date;
              calendar.callCloseHandler();
              editor.element().blur();
          }
      }
      var onClose = function(calendar){calendar.hide();calendar.destroy();}
      var cal = new Calendar(1, null, onSelect, onClose);
      cal.weekNumbers = false;
      cal.setDateFormat("%m/%d/%Y");
      cal.create();

      cal.parseDate(editor.element().value);
      cal.showAtElement(editor.element());
  }

  //obj.setEvent("onclick", switchToEditMode);
	obj.setEvent("ondblclick", switchToEditMode);
	editor.setEvent("onclick", switchToTextMode);

  function switchToTextMode(src){
      var originalVal = template.getItemProperty("text");
      var value = editor.element().value;
      if(originalVal != value){
					var idx = template.grid.getProperty("selection/index");
					template.model.setCell(idx,template.column,value);
      }
      template.refresh();
      template = null;
  }

  editor.setEvent("onblur", switchToTextMode);

};

My.Templates.Date.create();


// ****************************************************************
//    Grid Select Cell Template.
// ****************************************************************
My.Templates.GridSelect = Active.System.Control.subclass();

My.Templates.GridSelect.create = function()
{
    var obj = this.prototype;

    obj.defineModel("grid");

	obj.defineGridProperty("count", 0);

	obj.defineGridProperty("name", '');

	obj.defineGridPropertyArray("rows", 0);

	obj.defineGridPropertyArray("columns", 0);

	obj.defineGridProperty("valuecolumn", 0);

	obj.defineGridProperty("selectedrow", 0);

	obj.setClass("templates", "text");

	obj.setContent("text", function(){return this.getItemProperty("text")});

	function getAbsolutePos(el) {
		var SL = 0, ST = 0;
		var is_div = /^div$/i.test(el.tagName);
		if (is_div && el.scrollLeft) SL = el.scrollLeft;
		if (is_div && el.scrollTop)	ST = el.scrollTop;
		var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
		if (el.offsetParent) {
			var tmp = getAbsolutePos(el.offsetParent);
			r.x += tmp.x;
			r.y += tmp.y;
		}
		return r;
	};

    var template;

    function switchToTextMode() {
		var ddGridSpan = document.getElementById('ddGridSpan');
		if(ddGridSpan) {
			ddGridSpan.innerHTML='';
			document.body.removeChild(ddGridSpan);
		}
        if(template) {
			template.refresh();
			template = null;
		}
	}

    function switchToEditMode()
    {
		if(template) {
			switchToTextMode();
		}
        template = this;

		var grid = new Active.HTML.DIV;
		grid.setClass("templates", "ddgrid");
		grid.setContent("grid", function() {
				selectAction = function(src) {
					selectedRow = src.getProperty("item/index");
					var ddData = template.getGridProperty("rows");
					var originalText = template.getItemProperty("text");
					var text = ddData[selectedRow][template.getGridProperty("valuecolumn")];
					if(originalText != text) {

						var idx = template.grid.getProperty("selection/index");
						template.model.setCell(idx,template.column,text);
						template.setGridProperty("selectedrow",ddData[selectedRow]);
						template.action("change"+template.getGridProperty("name")+"Action");
					}
					switchToTextMode();
				}

				var ddGrid = new Active.Controls.Grid;
				var ddColumns = template.getGridProperty("columns");
				var ddData = template.getGridProperty("rows");
				var row = ddGrid.getTemplate("row");
				row.setEvent("ondblclick", function(){ this.action("selectAction"); } );
				ddGrid.setId("ddgrid");
				ddGrid.setAction("selectAction", selectAction);
				ddGrid.setRowProperty("count", ddData.length);
				ddGrid.setColumnProperty("count", ddColumns.length);
				ddGrid.setColumnProperty("text", function(i){return ddColumns[i]});
				ddGrid.setRowHeaderWidth("0px");
				ddGrid.setColumnHeaderHeight("20px");
				ddGrid.getDataText = function(i, j){ return ddData[i][j]; };

				return ddGrid.toString();
			}
		);

		var ddGridSpan = document.getElementById('ddGridSpan');
		if(!ddGridSpan) {
			ddGridSpan = document.createElement('span');
			ddGridSpan.id = 'ddGridSpan';
			document.body.appendChild(ddGridSpan);
		}

		// rigged to capture mousedown events on the grid owning this template.  probably a better way to do this.
		this.element().parentNode.parentNode.parentNode.onmousedown = switchToTextMode;

		ddGridSpan.innerHTML=grid;
		var el = template.element();
		var pos = getAbsolutePos(el);
		grid.setStyle("left", pos.x);
		grid.setStyle("top", pos.y + el.offsetHeight);
		grid.setStyle("width",170);
		grid.setStyle("height",150);
		grid.setStyle("visibility", "visible");
    }

    //obj.setEvent("onfocus", switchToEditMode);
		obj.setEvent("ondblclick", switchToEditMode);
};

My.Templates.GridSelect.create();
