var lookupCanBlur = true;

function HTMLLookup(sys, formID, code, posX, posY, width, height, description, value, showValue) {
  this.create(sys, formID, code, posX, posY, width, height, description, value);
  this.type = 1;
  this.openSubForm = false;
  this.style = 0;
  this.showValue = showValue;
  this.expand = true;
  this.report = false;
  this.initialType = 3;
}

HTMLLookup.inherits(HTMLEdit);

HTMLLookup.prototype.name = 'HTMLLookup';
HTMLLookup.prototype.tabable = true;
HTMLLookup.prototype.tagName = 'lookup';
HTMLLookup.prototype.canSelectOnFocus = false;
HTMLLookup.prototype.defaultArrowWidth = 15;
HTMLLookup.prototype.defaultComponentHeight = 21;

HTMLLookup.prototype.lookupInit = function() {
  this.dependent = true;
}

HTMLLookup.prototype.lookupEndInit = function() {
}

HTMLLookup.prototype.setVisible = function(v) {
  this.visible = v;
  visibleDiv(this.div, v);
  if (this.sfdiv) visibleDiv(this.sfdiv, v);
  if (!v) this.removeLookup(true);
}

HTMLLookup.prototype.setEnabled = function(v) {
  this.enabled = v;
  this.setReadOnlyDiv(!v);
  if (this.button) this.button.setEnabled(v);
}

HTMLLookup.prototype.setWidth = function(width) {
  width = parseInt(width);
  this.callMethod(HTMLEdit, 'setWidth', width);

  if (this.button) this.button.setX(width-17);
  if (this.sfdiv) this.sfdiv.style.left = (width+3)+'px';
}

HTMLLookup.prototype.setX = function(x) {
  x = parseInt(x);
  this.callMethod(HTMLEdit, 'setX', x);
  
  if (this.sfdiv) {
    this.sfdiv.style.left = this.getSubFormImagePosX();
  }
}

HTMLLookup.prototype.setY = function(y) {
  y = parseInt(y);
  this.callMethod(HTMLEdit, 'setY', y);
  
  if (this.sfdiv) {
    this.sfdiv.style.top = this.getSubFormImagePosY();
  }
}

HTMLLookup.prototype.getSubFormImagePosX = function() {
  return (this.posX + this.width + 3);
}

HTMLLookup.prototype.getSubFormImagePosY = function() {
  return (this.posY + ((this.height - 20) / 2));
}

HTMLLookup.prototype.setValue = function(value, checkDependences, ignoreShowValue) {
  value = normalizeRuleParam(value);
  var temp = this.getValue();

  this.value = value;
  this.hidden.setValue(value);
  if (trim(this.value) != trim(temp)) {
  	if (this.field == null || this.field.length == 0) {
  		if (!ignoreShowValue) {
  		  var show = getContent("lookupShowValue.do?sys="+this.sys+"&formID="+this.formID+"&comID="+this.code+"&value="+URLEncode(value));
  		  this.setShowValue(show);
  		}  
  	}
    this.changeAction(window.event, null, !checkDependences);
  }
}

HTMLLookup.prototype.setShowValue = function(value) {
  this.showValue = value;
  this.input.value = value;
}

HTMLLookup.prototype.getValue = function() { return this.hidden.value; }

HTMLLookup.prototype.getShowValue = function() { return this.input.value; }

HTMLLookup.prototype.designEditInput = function(doc, name, value) {
  if (IE)
    this.input = document.createElement('<input type="text" readonly>');
  else {
    this.input = document.createElement("input");
    this.input.setAttribute('readonly', 'readonly');
  }

  this.input.className = 'edit';

  if (!name)
    this.input.name  = 'WFRInput'+this.code;
  else
    this.input.name  = name;

  if (this.maxlength) this.input.maxLength = this.maxlength;
  this.input.style.height = this.height;
  this.input.style.width = this.width;
  if (this.align) this.input.style.textAlign = this.align;
  this.input.value = value;
}

HTMLLookup.prototype.designInput = function(doc) {
  if (this.style == 0 || this.style == 1) {
    this.designEditInput(doc, 'WFRInput'+this.code+'Show', this.showValue);
  } else if (this.style == 2) {
    this.designEditInput(doc, 'WFRInput'+this.code+'Show', this.showValue);
  }
}


HTMLLookup.prototype.designComponentReport = function() {
  var labelReport = new HTMLLabel(this.sys, this.formID, this.code, 0, 0, this.width, this.height, this.showValue);
  labelReport.id = "reportLabelLookup" + this.code;
  labelReport.design(this.context, false);
}

HTMLLookup.prototype.designComponent = function(doc) {
  this.lookupInit();
  this.url = 'search.do?inputRetornoName=WFRInput'+this.code+'Show&sys='+this.sys+'&action=search&formID='+this.formID+'&componentID='+this.code+'&xml=true';

  this.hidden = new HTMLHidden(this.sys, this.formID, this.code, this.value);
  this.hidden.design(this.context);

  if (this.report) {
    this.designComponentReport();
    return "";
  }

  this.onkeydown = this.checkKey;

  if (this.style == 0 && !this.toGrid) {
    if (this.openSubForm && this.subFormCode && parseInt(this.subFormCode) > 0) {
        var img = new ImageObject();
        this.sfdiv = this.getDiv('WFRLookupSubForm'+this.code, this.getSubFormImagePosX(), this.getSubFormImagePosY(), 20, 20, 99999, true);
        this.img = img.getImage(skin+'lookup.gif', '', this.getAction('openForm'));
        this.sfdiv.appendChild(this.img);
        this.doc.appendChild(this.sfdiv);
    } else {
      if (this.expand) {
        this.width = this.width + 26;
      }
    }
  }

  if (this.openSubForm && this.subFormCode && parseInt(this.subFormCode) > 0 && this.style == 0)
    this.onF5press = this.getAction('openForm');

  if (this.style == 0 && !this.readonly) {
  	var inc = (this.height - this.defaultComponentHeight)/this.defaultComponentHeight;
  	this.buttonWidth = this.defaultArrowWidth + (this.defaultArrowWidth*inc);
    this.button = new HTMLButton(this.sys, this.formID, -1, this.width-(this.buttonWidth+2), IE?3:2, this.buttonWidth, (this.height-4), '', skin+'lookup_more_inner.gif');
    this.button.onclick = this.getAction('openDetails');
    this.button.design(this.context);
  }

  this.onblur_catch = this.onblur;
  this.onblur = this.doOnBlur;

  this.callMethod(HTMLEdit, 'designComponent', doc);
  this.lookupEndInit();
}

HTMLLookup.prototype.focusDoc = function(e) {
  var src =  e.srcElement || e.target;
  parent.changeTitle(src.name);
}

HTMLLookup.prototype.setReadOnly = function(v) {
  this.readonly = v;
  if (this.input) {
    if (this.readonly) this.input.setAttribute('readonly', 'readonly');
    if (this.readonly && !this.bgColor) this.input.style.backgroundColor = '#FFFFE1';
  }

  if (this.button) this.button.setEnabled(!this.readonly);
}

HTMLLookup.prototype.setEnabled = function(v) {
  this.enabled = v;
  if (this.input) this.input.disabled = !this.enabled;

  if (this.button) this.button.setEnabled(this.enabled);
}

HTMLLookup.prototype.doOnBlur = function(evt) {
  if (controller.activeElement == this) {
    controller.activeElement = null;
  }
  this.timeout(this.doOnBlurTO, 100);
}

HTMLLookup.prototype.doOnBlurTO = function(evt) {
  if (controller.activeElement != this && controller.activeElement != this.button && this.onblur_catch) {
    this.onblur_catch.call(this, evt);
  }
}

HTMLLookup.prototype.checkKey = function(evt) {
  if (!evt) evt = event;
  var keyCode  = evt.keyCode || evt.which;
  var chr = String.fromCharCode(keyCode).toUpperCase();

  var r = true;
  if (keyCode == 113 || chr == ' ' || keyCode == 40) {
    this.button.click();
    r = false;
  }
  
  if (!r) {
    document.disableEvents = true;
    if (evt.preventDefault) {
      evt.preventDefault();
      evt.stopPropagation();
    } else {
      evt.keyCode = 0;
      evt.returnValue = false;
    }
    return false;
  } else {
    return true;
  }
}

HTMLLookup.prototype.openDetails = function() {
  controller.activeElement = this;
  lookupCanBlur = false;

  if (this.lookup) {
    this.removeLookup();
  } else {
    this.lookup = document.createElement("div");

    this.lookup.style.visibility = "visible";
    this.lookup.style.width      = this.getWidth();
    this.lookup.style.height     = 0;
    this.lookup.style.left       = findPosX(this.context)+1;

    this.lookup.style.top        = findPosY(this.context)+this.getHeight();
    this.lookup.style.position   = 'absolute';
    this.lookup.style.zIndex     = 301;
    this.lookup.name             = 'lookupLayer';

    var maxsize = document.body.clientHeight - pt(this.lookup.style.top) - 35;

    document.body.appendChild(this.lookup);

    this.down    = true;
    if (maxsize < 59) {
      this.down = false;
    }

    sel = '<table width="100%" height="0" border="0" cellspacing="0" cellpadding="0" bgcolor="#E5E5E5"><tr>';

    // TODO Basta retirar o comentário. Foi feito e testado pelo setor de Testes, mas William solicitou 
    // a retirada dessa implementação.
    // Basta procurar pelo trecho acima no código para saber onde retirar os comentários.
    //sel = sel + '<td><img id="lookupImgType" src="'+skin+'lk_type_'+this.initialType+'.gif" class="cur" onclick="HTMLLookup.prototype.changeLookupType(this)" alt="'+this.getSearchLabel()+'" title="'+this.getSearchLabel()+'"></td>';
    sel = sel + '<td><img id="lookupImgType" src="'+skin+'lk_type_'+this.initialType+'.gif" class="cur" onclick="HTMLLookup.prototype.changeLookupType(this)" alt="'+getLocaleMessage("LABEL.STARTING_WITH")+'" title="'+getLocaleMessage("LABEL.STARTING_WITH")+'"></td>';
    sel = sel + '<td><input type="text" id="lookupSearchQuery" class="lookupSearchInput" style="width:'+(this.getWidth()-17-19)+'px; height:18px;"><input type="hidden" id="lookupSearchType" value="'+this.initialType+'"></td>';
    sel = sel + '<td><img id="lookupImgSearch" src="'+skin+'lk_search.gif" class="cur"></td>';
    sel = sel + '</tr><tr><td colspan="3" bgcolor="#CCCCCC" id="lookupQueryContent" valign="top">'+getLocaleMessage("LABEL.WAIT")+'</td></tr>';
    sel = sel + '<tr><td colspan="3"align="right" id="lookupQueryNavigation"  bgcolor="#999999" valign="top"></td></tr></table>';

    this.lookup.innerHTML = sel;

    this.lookupSearch = findNode(this.lookup, 'lookupSearchQuery');
    this.attachEvent(this.lookupSearch, 'keydown', this.lookupKeyPress);
    this.attachEvent(findNode(this.lookup, 'lookupImgSearch'), 'click', this.lookupDoSearch);

    var editedURL = this.url;
    if (d.t && d.t.dependences) {
      var components = d.t.dependences[this.code];
	    if (components && components.length > 0) {
	      for (var code in components) {
	        var component = eval("$mainform().d.c_" + components[code]);
	        if (component) {
	          editedURL += ("&WFRInput" + component.getCode() + "=" + URLEncode(component.getValue()));
  	      }
	      }
	    }
    }

    this.timeout(this.showLookupResults, 0, [editedURL+'&type=1&q=']);
  }
}

// TODO Basta retirar o comentário. Foi feito e testado pelo setor de Testes, mas William solicitou 
// a retirada dessa implementação.
// Basta procurar pelo trecho acima no código para saber onde retirar os comentários.
/*HTMLLookup.prototype.getSearchLabel = function(type) {
  var typeValue = (type || this.initialType);
  try {
    typeValue = parseInt(typeValue);
    if (!(/[1-4]/.test(typeValue))) {
      typeValue = 3;
    }
  } catch (e) { /*do nothing* / }

  var value;
  switch(typeValue) {
    case 1: {
      value = getLocaleMessage("LABEL.EQUAL");
      break;
    }
    case 2: {
      value = getLocaleMessage("LABEL.CONTAINING");
      break;
    }
    case 4: {
      value = getLocaleMessage("LABEL.ENDING_WITH");
      break;  
    }
    default: {
      value = getLocaleMessage("LABEL.STARTING_WITH"); 
    }
  }
  return value;
}*/

HTMLLookup.prototype.getXMLData = function(url) {
  return getXMLContent(url);
}

HTMLLookup.prototype.showLookupResultsAction = function(e, obj, url) {
  this.showLookupResults(url);
}

HTMLLookup.prototype.showLookupResults = function(url, type, query) {

  if (this.lookup) {

    var xmldoc = this.getXMLData(url, type, query);

    if (xmldoc != null) {
      var root = xmldoc.getElementsByTagName('root').item(0);
      var data = root.getElementsByTagName('data');

      var size = (data.length * 14)+6;

      var maxsize = document.body.clientHeight - pt(this.lookup.style.top) - 35;
      var maxlistsize = (14 * 14)+6;

      if (!this.down) {
        maxsize = findPosY(this.div) - 35;
        size = (data.length * 14)+6;
      }

      if (size > maxsize) size = maxsize;
      if (size > maxlistsize) size = maxlistsize;
      size = (size - (size % 14))+6;

      if (!this.down) {
        var totalsize = size + 18 + 13;
        this.lookup.style.top = findPosY(this.div) - totalsize;
      }
      sel = '<select id="lookupInput" size="2" class="lookupSearch" style="width:'+this.getWidth()+'px; height:'+size+'px;">';

      for (var iNode = 0; iNode < data.length; iNode++) {
        var node = data.item(iNode);
        var text = '&nbsp;';
        if (node.firstChild && node.firstChild.nodeValue && trim(node.firstChild.nodeValue) != '') text = node.firstChild.nodeValue;
        sel = sel + '  <option value="'+node.getAttribute('value')+'">'+replaceAll(replaceAll(text, '>', '&gt;'),'<', '&lt;')+'</option>';

      }

      sel = sel + '</select>';

      var query_content = MM_findObj('lookupQueryContent');
      query_content.innerHTML = sel;

      this.lookupInput = query_content.firstChild;

      this.attachEvent(this.lookupInput, 'click', this.lookupChangeSelectValue, this, [this]);

      var nav = root.getElementsByTagName('navigation').item(0);

      sel = '<table border="0" cellspacing="0" cellpadding="3"><tr>';

      for (var iNode = 0; iNode < nav.childNodes.length; iNode++) {
        var node = nav.childNodes.item(iNode);
        var des = '_des';
        var an  = "";
        if (node.getAttribute('enabled') == 'true') {
          des = '';
          an = ' class="cur" ';

        }
        sel = sel + '<td><img id="lookupNavigation'+node.tagName+'" src="'+skin+'lk_'+node.tagName+des+'.gif" border="0"'+an+'></td>';
      }

      sel = sel + '</tr></table>';

      MM_findObj('lookupQueryNavigation').innerHTML = sel;

      for (var iNode = 0; iNode < nav.childNodes.length; iNode++) {
        var node = nav.childNodes.item(iNode);
        if (node.getAttribute('enabled') == 'true')
          this.attachEvent(MM_findObj('lookupNavigation'+node.tagName), 'click', this.showLookupResultsAction, this, [node.firstChild.nodeValue]);
      }

      MM_findObj('lookupSearchQuery').focus();

      this.attachEvent(this.lookupInput,'keydown',this.lookupSelectPress);
      this.attachEvent(document,'click',this.closeCurrentLookup);
    } else
      this.removeLookup();
  }

}

HTMLLookup.prototype.openForm = function() {
  eval(this.subFormOpenCommand);
}

HTMLLookup.prototype.openFormKeyboard = function() {
  eval(this.subFormOpenCommand);
}

// TODO Basta retirar o comentário. Foi feito e testado pelo setor de Testes, mas William solicitou 
// a retirada dessa implementação.
// Basta procurar pelo trecho acima no código para saber onde retirar os comentários.
/*HTMLLookup.prototype.changeLookupType = function(o) {
  var type = MM_findObj('lookupSearchType').value;
  if (type == '3') {
    type = '1';
  } else if (type == '4') {
    type = '2';
  } else if (type == '2') {
    type = '3';
  } else if (type == '1') {
    type = '4';
  }

  var label = this.getSearchLabel(type);

  o.src = skin+'lk_type_'+type+'.gif';
  o.alt = label;
  o.setAttribute('title', label);

  MM_findObj('lookupSearchType').value = type;
}*/

HTMLLookup.prototype.changeLookupType = function(o) {
  var type = MM_findObj('lookupSearchType').value;
  var alt  = '';
  var altTitle  = '';
  
  if (type == '3') {
    type = '1';
    alt = getLocaleMessage("LABEL.EQUAL");
    altTitle = getLocaleMessage("LABEL.EQUAL");
  } else if (type == '4') {
    type = '2';
    alt = getLocaleMessage("LABEL.CONTAINING");
    altTitle = getLocaleMessage("LABEL.CONTAINING");
  } else if (type == '2') {
    type = '3';
    alt = getLocaleMessage("LABEL.STARTING_WITH");
    altTitle = getLocaleMessage("LABEL.STARTING_WITH");
  } else if (type == '1') {
    type = '4';
    alt = getLocaleMessage("LABEL.ENDING_WITH");
    altTitle = getLocaleMessage("LABEL.ENDING_WITH");
  }

  o.src = skin+'lk_type_'+type+'.gif';
  o.alt = alt;
  o.setAttribute('title', altTitle);
  MM_findObj('lookupSearchType').value = type;
}

HTMLLookup.prototype.closeCurrentLookup = function(evt) {
  var target   = evt.target || evt.srcElement;
  if (this.lookup && target != this.button.btdiv) {
    if (!target.id || target.id.indexOf('lookup') != 0) {
      if (!(target.parentNode && target.parentNode.id && target.parentNode.id.indexOf('lookup') ==0))
        this.removeLookup();
    }
  }
}

HTMLLookup.prototype.lookupChangeSelectValue = function(sel) {
  this.lookupChangeValue(sel.options[sel.selectedIndex].value, sel.options[sel.selectedIndex].text);
}

HTMLLookup.prototype.lookupChangeValue = function(v, t) {
  this.setValue(v, true, true);
  this.setShowValue(t);
  this.timeout(this.lookupDoChangeValue, 0);
}

HTMLLookup.prototype.lookupDoChangeValue = function() {
  this.removeLookup();
}

HTMLLookup.prototype.removeLookup = function(nofocus) {
  if (this.lookup && this.lookup.parentNode) {
    this.lookup.parentNode.removeChild(this.lookup);
    this.removeEvent(document, 'click');

    if (!nofocus)
      this.focus();
    this.lookup = null;
  }
  lookupCanBlur = true;
}

HTMLLookup.prototype.lookupSelectPress = function(evt) {
  var alt  = evt.altKey;
  var ctrl = evt.ctrlKey;
  var sel = this.lookupInput;

  var r = true;
  if (evt.keyCode == 33) {
    var x = sel.selectedIndex - 10;
    if (x < 0) x = -1;
    sel.selectedIndex = x;
    r = false;
  }

  else if (evt.keyCode == 34) {
    var x = sel.selectedIndex + 10;
    if (x > sel.length-1) x = sel.length-1;
    sel.selectedIndex = x;
    r = false;
  }

  else if (evt.keyCode == 27) {
    this.removeLookup();
    r = false;
  }

  else if (evt.keyCode == 10 || evt.keyCode == 13) {

    this.lookupChangeSelectValue(sel);
    r = false;
  }

  else if (evt.keyCode == 38 && sel.selectedIndex == 0) {
    sel.options[0].selected = false;
    var o = MM_findObj('lookupSearchQuery');
    try {o.focus();}catch(e){}
  }

  else if (evt.keyCode == 9) {
    r = false;
  }

  else if (!alt && !ctrl && (evt.keyCode == 39 || evt.keyCode == 37)) {
    var dofocus = false;
    var idx  = sel.selectedIndex;

    if (evt.keyCode == 39) {
      var nav = MM_findObj('lookupNavigationnext');
      if (nav.onclick) {
        nav.onclick();
        if (!IE)
          idx = idx -1;
        dofocus = true;
      }
    }

    if (evt.keyCode == 37) {
      var nav = MM_findObj('lookupNavigationprevious');
      if (nav.onclick) {
        if (!IE && sel.selectedIndex != sel.length-1)
          idx = idx +1;
        nav.onclick();
        dofocus = true;
      }
    }

    sel = MM_findObj('lookupInput');

    sel.selectedIndex = idx;
    sel.focus();
  }


  if (!r) {
    document.disableEvents = true;
    if (evt.preventDefault) {
      evt.preventDefault();
      evt.stopPropagation();
    } else {
      evt.keyCode = 0;
      evt.returnValue = false;
    }
    return false;
  } else
    return true;

}

HTMLLookup.prototype.lookupKeyPress = function(evt) {

  var alt  = evt.altKey;
  var ctrl = evt.ctrlKey;
  var chr  = String.fromCharCode(evt.keyCode).toUpperCase();

  var r = true;

  if (evt.keyCode == 40) {
    this.lookupInput.focus();
  }
  else if (evt.keyCode == 9) {
    r = false;
  }

  else if (evt.keyCode == 10 || evt.keyCode == 13) {
    this.lookupDoSearch();
  }

  else if (evt.keyCode == 38) {
    this.removeLookup();
  }

  else if (evt.keyCode == 27) {
    this.removeLookup();
    r = false;
  }

  else if (ctrl && chr == ' ') {
    MM_findObj('lookupImgType').onclick();
    r = false;
  }

  if (!r) {
    document.disableEvents = true;
    if (evt.preventDefault) {
      evt.preventDefault();
      evt.stopPropagation();
    } else {
      evt.keyCode = 0;
      evt.returnValue = false;
    }
    return false;
  } else
    return true;
}

HTMLLookup.prototype.lookupDoSearch = function() {


  var editedURL = this.url;
  if (d.t && d.t.dependences) {
    var components = d.t.dependences[this.code];
   if (components && components.length > 0) {
     for (var code in components) {
       var component = eval("$mainform().d.c_" + components[code]);
       if (component) {
         editedURL += ("&WFRInput" + component.getCode() + "=" + URLEncode(component.getValue()));
	        }
     }
   }
  }

  this.showLookupResults(editedURL+'&type='+MM_findObj('lookupSearchType').value+'&q='+MM_findObj('lookupSearchQuery').value,
                         MM_findObj('lookupSearchType').value,
                         MM_findObj('lookupSearchQuery').value
                        );
}

HTMLLookup.prototype.freeComponent = function() {
  if (this.sfdiv)
    this.doc.removeChild(this.sfdiv);
}

HTMLLookup.prototype.setHint = function(hint) {
  this.callMethod(HTMLElementBase, "setHint", [hint]);
  
  if (this.context) {
    this.context.alt = hint;
    this.context.title = hint;
  }
  
  if (this.img != null){
    this.img.alt = hint;
    this.img.title = hint;
  }
}