/* *********************************************************************** */

var com = com ? com : {}
    com.bigllc  = com.bigllc ? com.bigllc : {};   
    
/* *********************************************************************** */

if(!com.bigllc.ui) {

/* *********************************************************************** */

com.bigllc.ui = {};

/* *********************************************************************** */
/**
 * Need to add the following line anywhere in your code, with specific id.
 * <iframe id="DivShim" src="javascript:false;" scrolling="no" frameborder="0" style="position:absolute; top:0px; left:0px; display:none;"></iframe>
 */
com.bigllc.ui.PopupBackground = function(elem, id) {
  this.elem = elem;
  this.background = document.getElementById(id);
}

/* *********************************************************************** */

com.bigllc.ui.PopupBackground.prototype = {
  show : function() {
    if(!this.elem.style.zIndex) this.elem.style.zIndex = 100;

    var pos = com.bigllc.lang.System.getPosition(this.elem);
    this.background.style.width = pos.width + 4;
    this.background.style.height = pos.height + 4;
    this.background.style.top = pos.top - 2;
    this.background.style.left = pos.left - 2;
    this.background.style.zIndex = this.elem.style.zIndex - 1;
    this.background.style.display = "block";
    //this.background.style.background = "blue";
    //alert(this.background.style.width + " " + this.background.style.height +  " " + this.background.style.top + " " + this.background.style.left + " " + this.background.style.zIndex);
  },

  hide : function() {
    this.background.style.display = "none";
  }
}

/* *********************************************************************** */

/**
 * A dialog. Will look for <id>-pb to see if there is a popup blocker
 * field. If it exists then it will use it.
 */
com.bigllc.ui.Dialog = function(id, width, height) {
  if(!id) {
    id = "dlg-" + new Date().getTime() + "-" + Math.floor(Math.random()*10000); 
  }
  
  this.id = id;
  this.width = width ? parseInt(width) != NaN ? parseInt(width) : parse : 300;
  this.height = height ? parseInt(height) != NaN ? parseInt(height) : parse : 200;

  this.el = null;
  this.content = null;
  this.title = null;
  this.frame = null;
}

/* *********************************************************************** */

com.bigllc.ui.Dialog.prototype = {
  show : function() {
    if(!this.el) this.render();
    this.el.style.visibility = "visible";
    if(this.blocker) this.blocker.show();
    //this.el.style.display = "block";

    return false;
  },
  
  hide : function() {
    if(!this.el) this.render();
    this.el.style.visibility = "hidden";
    if(this.blocker) this.blocker.hide();
  },
  
  isVisible: function() {
    if(!this.el) return false;
    return this.el.style.visibility == "visible";
  },
  
  setPosition: function(left, top) {
    if(!this.el) this.render();
    this.el.style.left = left + "px";
    this.el.style.top = top + "px";
    if(this.blocker) this.blocker.show();
  },
  
  getPosition: function() {
    return com.bigllc.lang.System.getPosition(this.el);
  },
  
  
  center: function() {
    var sys = com.bigllc.lang.System;
    
    var pos = sys.getPosition(this.el);
    var ww = sys.getWinWidth();
    var wh = sys.getWinHeight();
    var wx = sys.getScrollX();
    var wy = sys.getScrollY();
    
    var top = (wh - pos.height) / 2 + wy;
    var left = (ww - pos.width) / 2 + wx;
    
    this.setPosition(left, top);  
    //this.setTitle(ww + " " + wh + " " + wx + " " + wy + " " + pos.width + " " + pos.height + " " + left +  " " + top);
  },
  
  setAlignment: function(element, side, flush, xMargin, yMargin) {
    if(!this.el) this.render();
    var epos = com.bigllc.lang.System.getPosition(element);
    var dpos = com.bigllc.lang.System.getPosition(this.el);
    
    xMargin = parseInt(xMargin ? xMargin : 0);
    yMargin = parseInt(yMargin ? yMargin : 0);
    
    if(!side) {
      side  = "left";
      flush = "top";
    }
    
    if(!flush) {
      if(side == "left" || side == "right") flush = "top";
      else flush = "left";
    }

    var top;
    var left;
    
    if(side == 'top') {
      top = epos.top - dpos.height - yMargin;
    }
    else if(side == 'bottom') {
      top = epos.top + epos.height + yMargin;
    }
    else if(side == 'left') {
      left = epos.left - dpos.width - xMargin;
    }
    else if(side == 'right') {
      left = epos.left + epos.width + xMargin;
    }

    if(flush == 'top') {
      top = epos.top + yMargin;
    }
    else if(flush == 'bottom') {
      top = epos.top + epos.height - dpos.height - yMargin;
    }
    else if(flush == 'left') {
      left = epos.left + xMargin;
    }
    else if(flush == 'right') {
      left = (epos.left + epos.width) - dpos.width - xMargin;
    }
    
    this.setPosition(left, top);  
  },
  
  setHref: function(href) {
    if(!this.el) this.render();

    //if(!this.frame) {
      var frame = document.createElement("IFRAME");
      frame.scrolling = 'no';
      frame.name = this.id + '-frame';
      frame.id = this.id + '-frame';
      frame.border = 0;
      frame.frameBorder = 1;
      frame.style.border = "0px solid white";
      frame.style.width  = this.width;
      frame.style.height = this.height;
      frame.width  = this.width;
      frame.height = this.height;
      this.frame = frame;
      this.content.innerHTML = '';
      this.content.appendChild(frame);
      
      /*
      var self = this;
      this.frame.onblur = function() {
          self.hide();
      }
      */
    //}
    
    this.frame.src = href;
    
  },
  
  setTitle: function(title) {
    if(!this.el) this.render();
    
    this.title.innerHTML = title;
    this.title.style.display = title ? 'block' : 'none';
  },
  
  render: function() {
    if(!this.el) {
      this.el = document.getElementById(this.id);
      
      if(!this.el) {
        this.el = document.createElement("DIV");
        this.el.id = this.id;
      }
      this.el.className = 'dialog';
      this.el.innerHTML = '';
      this.el.style.visibility = "hidden";
      //this.el.style.display = "none";
      this.el.style.position = 'absolute';
      this.el.style.zIndex = 100;
      this.el.style.border = '1px #666666 solid';
      this.el.style.margin = '0px';
      this.el.style.top  = '50px';
      this.el.style.left = '50px';
      this.el.style.width  = this.width + "px";
      this.el.style.overflow = 'hidden';
      this.el.style.background = '#F2F2E6';
      this.el.style.zIndex = 100;
      
      this.title = document.createElement("DIV");
      this.title.className = 'dialog-title';
      //this.title.style.background = '#006634';
      this.title.style.color = 'white';
      this.title.style.fontSize = '1.1em';
      this.title.style.fontWeight = 'bold';
      this.title.style.padding = '3px 10px';
      this.title.style.textAlign = "left";
      this.title.innerHTML = 'Dialog';
      this.title.onselectstart= function() { return false;}
      
      var self = this;
      this.title.onmousedown = function(event) {
        self.startDialogMove(new com.bigllc.lang.Event(event));
      };
      
      this.el.appendChild(this.title);
      
      this.content = document.createElement("DIV");
      this.className = 'dialog-content';
      this.content.style.height = this.height + "px";
      this.content.style.background = '#F2F2E6';
      this.el.appendChild(this.content);
      
      document.body.appendChild(this.el);      
      
      if(document.getElementById(this.id + "-pb")) {
        this.blocker = new com.bigllc.ui.PopupBackground(this.el, this.id + "-pb");
      }
      
    }
  },
    
  startDialogMove: function(event)
  {
      try
      {
        this.draggingX = this.el.style.pixelLeft ? this.el.style.pixelLeft : parseInt(this.el.style.left);
        this.draggingY = this.el.style.pixelTop ? this.el.style.pixelTop : parseInt(this.el.style.top);
        this.mouseX = event.clientX;
        this.mouseY = event.clientY;
        
        var self = this;
        document.onmousemove = function(ev) {
          self.moveDialog(new com.bigllc.lang.Event(ev));
        };

        document.onmouseup = function(ev) {
          self.stopDialogMove(new com.bigllc.lang.Event(ev));
        };
        

        if(frames && frames[this.id + '-frame']) {
          var selfWin = frames[this.id + '-frame'].window;
          frames[self.id + '-frame'].document.onmousemove = function(ev) {
            try {
              var event = new com.bigllc.lang.Event(ev ? ev : selfWin.event);
              
              if(!ev) {
                //log(event.clientX + " " + event.clientY + " " + self.el.style.pixelLeft + " " + self.el.style.pixelTop);
                event.clientX += self.el.style.pixelLeft;
                event.clientY += self.el.style.pixelTop;
              }
              
              self.moveDialog(event);
            }
            catch(exception) {}
          };
          
          frames[this.id + '-frame'].document.onmouseup = function(ev) {
            try {
              self.stopDialogMove(new com.bigllc.lang.Event(ev ? ev : selfWin.event));
            }
            catch(exception) {              
            }
          };
        }
      }
      catch(exception)
      {
        alert('drag:' + exception.message);
      }
  },

  stopDialogMove: function(event) {
    try {
      document.onmousemove = null
      document.onmouseup = null

      if(frames && frames[this.id + '-frame']) {
        frames[this.id + '-frame'].document.onmousemove = null;
        frames[this.id + '-frame'].document.onmouseup = null;
      }
      

    }
    catch(exception) {
      alert('stop:' + exception.message);
    }
  },

  moveDialog: function(event) {
    try  {
      var pos = com.bigllc.lang.System.getPosition(this.el);
      var winWidth = com.bigllc.lang.System.getWinWidth();
      var winHeight = com.bigllc.lang.System.getWinHeight();
      var left = this.draggingX + (event.clientX - this.mouseX)
      var top =  this.draggingY +  (event.clientY - this.mouseY)
      if(left <= 0) left = 1; 
      
      if(top <= 0)  top = 1; 
      //if((left + pos.width) >= winWidth) left = winWidth - pos.width - 4; 
      //if((top + pos.height) >= winHeight) top = winHeight - pos.height - 4; 
      
      this.el.style.top = top
      this.el.style.left = left
      if(this.blocker) this.blocker.show();
      //log((left + this.width) + " " + winWidth);
    }
    catch(exception) {
      //alert(this.draggingX + (event.clientX - this.mouseX));
      //alert(this.draggingY + (event.clientY - this.mouseY));
      //alert('move:' + exception.message);
    }
  }
}

/* *********************************************************************** */

com.bigllc.ui.MultiKeyCombo = function(combo) {
  this.combo = combo;
  this.keypad = null;
  this.oldkeydown = null;
  this.fastlookup;
  this.lastSelectedIndex;
  
  var self = this;
  this.combo.onkeypress = function(ev) {
    return self.keyHandler(new com.bigllc.lang.Event(ev));
  }
  
  this.combo.onkeyup = function(ev) {
    return self.backspaceHandler(new com.bigllc.lang.Event(ev));
  }
  
  this.combo.onblur = function(ev) {
    return self.hideKeypad();
  }
  
}

/* *********************************************************************** */

com.bigllc.ui.MultiKeyCombo.prototype = {
  
  backspaceHandler : function(event) {
    this.lazyInitialiser();
    
    var currentString = this.keypad.innerHTML;
    var key = event.which;

    if (key == 8) {
      if(currentString.length > 0) {
        currentString = currentString.substring(0, currentString.length - 1);
        this.keypad.innerHTML = currentString;
        this.selectFirstMatch(currentString);
      }

      if(currentString.length == 0) {
        this.hideKeypad();
        //this.keypad.style.display = 'none';
      }
      
      return false;
    }
    
    return true;
  },
  
  keyHandler : function(event) {
    this.lazyInitialiser();

    var key = event.which;
    if (key > 31 && key < 127) {
      var ch = event.getKeyChar();
      if(ch) {
        this.showKeypad();
        var currentString = this.keypad.innerHTML + ch;

        if(this.selectFirstMatch(currentString)) {
          this.keypad.innerHTML = currentString;
        }
        else {
          this.combo.options.selectedIndex = this.lastSelectedIndex;
        }
      }

      return false;
    }

    else if (key == 8) {
      this.combo.onkeyup = null;
      return this.backspaceHandler(event);
    }
    else if (key == 13) {
      this.hideKeypad();
      //alert("enter");
    }
    
    return true;
  },
  
  selectFirstMatch : function (search) {
    var opts = this.combo.options;
    var lcs = search.toLowerCase();

    var lookup = this.fastlookup[lcs.charAt(0)];
    if(lookup) {
      for(var i = 0 ; i < lookup.length; ++i) {
        if(opts[lookup[i]].innerHTML.toLowerCase().indexOf(lcs) == 0) {
          this.lastSelectedIndex = lookup[i];
          opts.selectedIndex = lookup[i];
          return true;
        }
      }
    }

    return false;
  },

  showKeypad: function() {
    this.lazyInitialiser();
    if(this.keypad.style.display == 'block') return;
    this.keypad.style.display = 'block';
    this.oldkeydown = document.onkeydown;
    this.oldkeypress = document.onkeypress;
    this.currentValue = this.combo.value;
    var self = this;

    document.onkeypress = function(e) {
      if(self.keypad.style.display == 'block') {
        var keyCode = (e && e.which) ? e.which : window.event ? window.event.keyCode : null; 
        if(keyCode == 13) { 
          self.hideKeypad();
          if(window.event) {
            window.event.cancelBubble = true;
            window.event.returnValue = false;
          }
          return false;
        }
      }
      /*
      else {
        self.oldkeypress();
      }
      */
    }
    
    document.onkeydown = function(e) {
      if(self.keypad.style.display == 'block') {
        // only for ie
        if(window.event && window.event.keyCode == 8) {        
          window.event.cancelBubble = true;
          window.event.returnValue = false;
          return false;
        }
      }
    }  
    
  },
  
  hideKeypad: function() {
    this.lazyInitialiser();
    this.keypad.innerHTML = '';
    this.keypad.style.display = 'none';

    if(this.onkeydown)  document.onkeydown = this.oldkeydown;
    if(this.onkeypress) document.onkeypress = this.oldkeypress;
    if(this.currentValue != this.combo.value) {
        com.bigllc.lang.System.fireEvent(this.combo, "change");
    };
  },
  
  createFastLookup: function() {
      var opts = this.combo.options;
      this.fastlookup = new Array();
      
      for(var i = 0 ; i < opts.length; ++i) {
        var val = opts[i].innerHTML.toLowerCase();
        var code = val.charAt(0);
        
        if(!this.fastlookup[code]) {
          this.fastlookup[code] = new Array();
        }
        
        this.fastlookup[code].push(i);
      }
  }, 
  
  lazyInitialiser : function() {
    if(!this.keypad) {
      this.createFastLookup();      
      
      var pos = com.bigllc.lang.System.getPosition(this.combo);
      this.keypad = document.createElement("DIV");  
      this.keypad.className         = "combokeypad";
      this.keypad.style.position    = 'absolute';
      this.keypad.style.border      = '1px #666666 solid';
      this.keypad.style.background  = '#FFFFE1';
      this.keypad.style.margin      = '0px';
      this.keypad.style.top         = pos.top - pos.height;
      this.keypad.style.left        = pos.left;
      this.keypad.style.width       = pos.width + "px";
      this.keypad.style.height      = pos.height + "px";
      this.keypad.style.overflow    = 'hidden';
      this.keypad.style.textAlign   = 'left';
      this.keypad.style.display     = 'none';
      document.body.appendChild(this.keypad);
    }       
  }

}

/* *********************************************************************** */

com.bigllc.ui.MultiKeyComboInit = function() {
  var system = com.bigllc.lang.System;
  var multic = system.getElementsByTagAndClassName("select", "multikey");
  for(var i = 0; i < multic.length; ++i) {
    multic[i].multikey = new com.bigllc.ui.MultiKeyCombo(multic[i]);
  }
}

/*
var logger;
function log(msg) {
  if(!logger) {
    logger = document.createElement("DIV");
    document.body.appendChild(logger);
  }
  logger.innerHTML = msg + "<br/>" + logger.innerHTML;
}
*/

com.bigllc.lang.System.addEvent(window, "load", com.bigllc.ui.MultiKeyComboInit);

/* *********************************************************************** */


}
