/*
 * Author: Vertex Logic, Inc
 * Copyright 2005, 2006, 2007 - All rights reserved
 *
 * Vertex Logic, Inc., California, USA 
 *
 * Vertex Logic grants you ("Licensee") a non-exclusive license to use
 * and modify this source and recompile it in
 * accordance with the terms of the Agreement under which this software is bought
 * and provided that (i) this copyright notice appear on all copies of the Software; 
 * (ii) Licensee does not sale the software as is or with modification without
 * the prior consent of Vertex Logic. (iii) Licensee agrees that it does not have any 
 * title or ownership of the Software.
 *
 * The program is provided "as is" without any warranty express or
 * implied, including the warranty of non-infringement and the implied
 * warranties of merchantibility and fitness for a particular purpose.
 * Vertex Logic will not be liable for any damages suffered 
 * by you as a result of using the Program. 
 * In no event will Vertex Logic be liable for any
 * special, indirect or consequential damages or lost profits even if
 * Vertex Logic have been advised of the possibility of their occurrence. 
 * Vertex Logic will not be liable for any third party claims against you.
 */
 Af.HtmlTable = Class.create();

Af.HtmlTable.prototype = {


	initialize: function(tableId, columns, ec) {
		this.tableId = tableId;
		this.columns = columns;
		this.tableElement = null;
		this.listener = null;
		this.selectedCell = null;
		this.selectedRowNumber = -1;
		this.previousRowNumber = -1;
		this.normalBackcolor = "";
		this.selectionColor = "#e0eeef";
		this.normalTextColor = "#000000";
		this.dndMgr2 = null;
		this.draggableAttr = null;
		this.header = null;
		this.draggableType = "Unknown";
		this.ec = ec;
		this.draggables = new Array();
		this.autoDeselect = true;
	    this.init();
	},

	init: function() {
	    this.columnList = this.columns.split(',');
	    for (var i=0; i<this.columnList.length; i++) {
	       this.columnList[i] = trim(this.columnList[i]);
	    }
	    var te;
	    if (this.ec == null) {
	       te = document.getElementById(this.tableId);
	    } else {
	       te = this.ec.getFirstElementById(this.tableId);
	    }
	    this.tableElement  = te;
	    if (te == null) {
	       return;
	    }
	    
	    if (te.tBodies.length == 0) {
	       return;
	    }
	    
	    var tb = te.tBodies[0];
	    
	    if (tb.rows.length == 0) {
	       return;
	    }
	  
	    var ec = new Af.ElementCollection(this.tableElement);
	    var e = ec.getFirstElement("TH");
	    var r = null;
	    if (e == null) {
			this.templateRow = this.tableElement.rows[0];
			r = this.tableElement.rows[0];
	    } else {
	        this.header = this.tableElement.rows[0];
	        this.templateRow = this.tableElement.rows[1];
	        r = this.tableElement.rows[1];
	    }
	    if (this.templateRow.id == null) {
	       this.templateRow.id = this.tableElement.id + "TR";
	    }
	    this.columnsWidth = new Array(r.length);
	    for (var i=0; i<r.cells.length; i++) {
	       this.columnsWidth[i] = r.cells[i].offsetWidth;
	    }
	    removeAll(tb);
	  
	 },
	 
	 cleanup: function() {
	   var tb = this.tableElement.tBodies[0];
	   if (this.header != null) {
	      this.header.style.display = "none";
	      tb.appendChild(this.header);
	   }
	   if (this.templateRow != null) {
	      this.templateRow.style.display = "none";
	      tb.appendChild(this.templateRow);
	   }
	   this.draggables.length = 0;
	 },
	 
	 setDataList: function(dlist) {
	    this.dlist = dlist;
	    this.draggables.length = 0;
	    if (this.dlist == null) {
	       this.dlist = new Array();
	    }
	    if (this.dndMgr2 != null) {
			this.dndMgr2.clearDraggables();
		}
	    this.selectedRowNumber = -1;
		this.previousRowNumber = -1;
	    var tb = this.tableElement.tBodies[0];
	    removeAll(tb);
	    if (this.header != null && this.dlist.length > 0) {
	       tb.appendChild(this.header);
	    }
	    for (var i=0; i<this.dlist.length; i++) {
	       var data = this.dlist[i];
	       var row = this.templateRow.cloneNode(true);
	       row.id = "" + i;
	       tb.appendChild(row);
	       var n = this.columnList.length;
	       if (row.cells.length < n) {
	          n = row.cells.length;
	       }
	       for (var j=0; j < n; j++) {
	         var cell = row.cells[j];
	         cell.id = 'C_'+ i + '_' + j;
	         var s = this.columnList[j];
	         if (s == '') {
	            continue;
	         }

	         var v = data[s];
	         
	         if (v == null) {
	           v = '';
	         } else {
	           v = '' + v;
	         }
	         
	         
	         
	         var child = null;
	         
	         if (cell.childNodes.length > 0) {
	            child = cell.childNodes[0];
	            
	            for (var k=0; k<cell.childNodes.length; k++) {
	               var t = cell.childNodes[k];
	               if (t.tagName != null) {
	                  child = t;
	                  break;
	               }
	            }
	            if (child == null) {
	                child = cell.childNodes[0];
	            }
	         }
	         if (child != null) {
	            if (child.tagName == "INPUT") {
	                var t = child.type;
	                if (t != null) {
	                   t = t.toLowerCase();
	                }
	                if (t == "checkbox") {
	                   v = v.toLowerCase();
	                   if (v == "true") {
	                      child.checked = true;
	                   } else {
	                      child.checked = false;
	                   }
	                } else {
	                   child.value = v;
	                }
	                //  Adding onfocus to behave the same as selected
	                child.onfocus = this.cellSelected.bindAsEventListener(this);
	                child.onchange = this.cellChanged.bindAsEventListener(this);

	            } else {
					if(v != null){
						cell.innerHTML = htmlEncode(v);
					}else{
						cell.innerHTML = v;
					}
				}
	         } else {
					if(v != null){
						cell.innerHTML = htmlEncode(v);
					}else{
						cell.innerHTML = v;
					}
	         }
	        

	         if (this.dndMgr2 != null && this.draggableAttr == s) {
				var d = this.dndMgr2.registerDraggable(this.draggableType, i, cell, v);
				this.draggables.push(d);
			 }
	         cell.onclick = this.cellSelected.bindAsEventListener(this);
	         cell.ondblclick = this.cellDoubleSelected.bindAsEventListener(this);

	       }
	       
	    }
	 },
	 
	 cellDoubleSelected: function(evt) {
	    this.cellSelected(evt, true);
	 },
	 
	 cellSelected: function(evt, doubleClick) {
	    
	    var e = evt.target ? evt.target : evt.srcElement;
	    if (e.tagName != "TD") {
	       if (e.parentNode != null && e.parentNode.tagName == "TD") {
	          e = e.parentNode;
	       } else {
	          return;
	       }
	    }
	    var cellId = e.id;
        var idx = cellId.indexOf("_");
        var idx2 = cellId.lastIndexOf("_");
        var row = parseInt(cellId.substring(idx+1, idx2));
        var col = parseInt(cellId.substring(idx2+1));
        var cell = this.getCell(row, col);
        this.selectedCell = cell;
        this.previousRowNumber = this.selectedRowNumber;
        
		
        if (this.listener != null && this.listener.cellSelected != null) {
           if (this.selectedRowNumber != row && this.autoDeselect) {
			   this.unselectRow(this.selectedRowNumber);
		   }
		   this.selectedRowNumber = row;
		   this.listener.cellSelected(row, col, this.previousRowNumber == row, this);
		   if (doubleClick && this.previousRowNumber != row) {
		      this.listener.cellSelected(row, col, true, this);
		   }
        } else {
           this. setSelectedRow(row);
        }
        return true;
	 },
	 
	 cellChanged: function(evt) {
	    
	    var e = evt.target ? evt.target : evt.srcElement;
	    var cell = e;
	    while (cell != null && cell.tagName != "TD") {
	       cell = cell.parentNode;
	    }
	    if (cell == null) {
	       return;
	    }
	    var cellId = cell.id;
        var idx = cellId.indexOf("_");
        var idx2 = cellId.lastIndexOf("_");
        var row = parseInt(cellId.substring(idx+1, idx2));
        var col = parseInt(cellId.substring(idx2+1));
        
        var t = e.type;
        if (t != null) {
           t = t.toLowerCase();
        }
        
        if (t == "checkbox") {
           v = e.checked;
        } else {
           v = e.value;
        }
 
        if (this.listener != null && this.listener.cellChanged != null) {
		   this.listener.cellChanged(row, col, e.id, v);
        }
		else {// update the data
		  //debugA("cellChanged->update:"+this.columnList[col]);
		  var obj = this.dlist[row];
			  if (v == null) {
				 v = "";
			   }
			  obj[this.columnList[col]] = v;
		}
	 },
	 
	 setSelectedRow: function(row) {
	   this.previousRowNumber = this.selectedRowNumber;
       if (this.selectedRowNumber != row) {
           this.unselectRow(this.selectedRowNumber);
           this.selectedRowNumber = row;
           this.selectRow(this.selectedRowNumber);
       }
        
     },
	 
	 selectRow: function(row, selectionColor, color) {
	    var tb = this.tableElement.tBodies[0];
	    var n = tb.childNodes.length;
	    if (row < 0 || row >= n) {
	       return;
	    }
	    this.selectedRowNumber = row;
	    if (selectionColor == null) {
	       selectionColor = this.selectionColor;
	    }
	    if (color == null) {
	       color = this.normalTextColor;
	    }
	    var tr = tb.childNodes[row];
	    
	    for (var j=0; j < tr.cells.length; j++) {
	       tr.cells[j].style.backgroundColor = selectionColor;
	       tr.cells[j].style.color = color;
	    }
	 },
	 
	
	 unselectRow: function(row) {
	    if (row < 0) {
	       return;
	    }
	    var tb = this.tableElement.tBodies[0];
	    var n = tb.childNodes.length;
	    if (row < 0 || row >= n) {
	       return;
	    }
	    var tr = tb.childNodes[row];
	    
	    for (var j=0; j < tr.cells.length; j++) {
	       tr.cells[j].style.backgroundColor = this.normalBackcolor;
	       tr.cells[j].style.color = this.normalTextColor;
	    }
	    if (this.selectedRowNumber == row) {
           this.selectedRowNumber = -1;
           this.selectedCell = null;
        }
	 },
	 
	 getCell: function(row, col) {
	    var tb = this.tableElement.tBodies[0];
	    var n = tb.childNodes.length;
	    if (row < 0 || row >= n) {
	       return null;
	    }
	    n = tb.childNodes[row].cells.length;
	    if (col < 0 || col >= n) {
	       return null;
	    }
	    return tb.childNodes[row].cells[col];
	 },
	 
	 getSelectedRowData: function() {
	    if (this.dlist == null || this.selectedRowNumber < 0 ||
	      this.selectedRowNumber > this.dlist.length) {
	       return null;  
	    }
	    return this.dlist[this.selectedRowNumber];
	 },
	 
	 draggableTextChanged: function(row, text) {
	    var n = this.draggables.length;
	    if (row < 0 || row >= n) {
	       return;
	    }
	    this.draggables[row].text = text;
	 },
	 
	 disableCheckedColumn: function(col) {
		var tb = this.tableElement.tBodies[0];
	    var n = tb.childNodes.length;
	    var tr;
	    for (var i=0; i<n; i++) {
			tr = tb.childNodes[i];
			if (tr.cells[col].childNodes[0].checked) {
				tr.cells[col].childNodes[0].disabled = true;
		    }
	    }
	 }

}
