/*
 *
 * Name: itpostcd.js
 * Author: Sumon Mahbubur Rahman
 *
 * 
 */
// identify the browser
var isIE = (navigator.userAgent.indexOf("MSIE") >= 0);
// compatibility tasks
var cssRules = new Array();
if (isIE) {
  cssRules = document.styleSheets[1].rules;
} else {
  cssRules = document.styleSheets[1].cssRules;
}

var XMLHTTP_UNINITIALIZED = 1;
var XMLHTTP_LOADING       = 2;
var XMLHTTP_LOADED        = 3;
var XMLHTTP_COMPLETED     = 4;

XMLTips = function(title, desc, type){
  if(!type) type = 'TOOLTIP';
  this.type            = type;
  this.title           = title;
  this.description     = desc;
  this.tooltipBody     = desc;
  this.movable        = false;
  this.titleClass      = '';
  this.tableName       = '';
  this.filter         = null;
  this.requestURL     = '';      // request url , if we need to load detail from server
  this.xmlhttp         = null;
  this.triggerEl       = null;
  this.targetEl       = null;
  this.width          = 400;
  this.cacheResult    = true;
  this.spanTips       = null;
  this.ifrTips         = null;
  this.onTipsLoad     = null;
  this.onTipsLoadFunc  = null;
  this.opened         = false;
  this.maxRecord       = 10;
  this.offsetRecord   = 0;
  this.offsetHeight    = 0;
  this.offsetWidth    = 0;
  this.XPos            = 0;
  this.YPos            = 0;
  this.resizeTips      = true;
  this.isIE            = (navigator.userAgent.indexOf("MSIE") >= 0);
  this.cancelTips      = function(){return false;};
  this.onPrepareFunRef = function(){};
  if(type != 'undefined') this.type = type;
  // shows tooltiop
  this.showTips = function (){
    if(this.cancelTips(this)==true) return;
    if(this.description == ''){
      this.tooltipBody = "<div valign='middle' align='center'><img src='"+ResourcePath+"/processing.gif'><br/>&nbsp;</div>";
      this.showTooltip();
      this.loadDetails();
      return;
    }

    this.resizeTips = true;
    this.showTooltip();
    if(this.cacheResult == false) this.description = '';

    this.onTipsLoadFunc(this);

  }

  this.onTipsLoadFunc = function(xTips){
    if(typeof this.onTipsLoad == 'function'){
      if(!this.opened){
        setTimeout(function(){
          xTips.onTipsLoadFunc(xTips);
        },50);
      }else{
        this.onTipsLoad(xTips);
      }
    }
  }

  this.showTooltip = function(){
    iconImage = "info.gif";
    if(!this.titleClass) this.titleClass = 'defpopup';
    if(this.titleClass == 'wintitle') iconImage = 'window.png';
    var spanEL = document.getElementById('spMy' + this.type);
    var ifrEL = document.getElementById('ifrMy' + this.type);
    if(! spanEL ){
      spanEL = document.createElement("SPAN");
      spanEL.id = 'spMy' + this.type;
      spanEL.style.position = 'absolute';
      document.body.appendChild(spanEL);
    }
    
    if(!ifrEL){
      ifrEL = document.createElement("IFRAME");
      ifrEL.id = 'ifrMy'+ this.type;
      ifrEL.name = 'ifrMy'+ this.type;
      ifrEL.width = '100%';
      ifrEL.margin = "auto";
      ifrEL.frameBorder = 0;
      ifrEL.scrolling = 'no';
      spanEL.appendChild(ifrEL);
    }
    if(!isNaN(this.width)) spanEL.style.width = this.width + "px" ;
    this.spanTips = spanEL;
    this.ifrTips = ifrEL;

    // create content
    var respath;
    var idBase = document.getElementById('idBase');
    var idocHTML =     "<html>\n"
                     + "  <head>\n";
    if(idBase) idocHTML +=     "     <base id='idBase' href='"+ idBase.href +"'/>\n";
    // add all stylesheet from current page
    for(var i = 0; i < document.styleSheets.length; i++){
      var style = document.styleSheets.item(i);      
      idocHTML +=         "    <link rel=\"stylesheet\" href=\""+ style.href +"\" type=\"text/css\"/>\n";
      if(i == 0){
        var href = new String(style.href);
        //respath = href.substr(0,href.lastIndexOf('/'));
        // not a good practice.. but had to do for old site
        respath = "rsrc";
      }
    }
    var jsscripts = document.getElementsByTagName("SCRIPT");  // add all javascript from current page
    for(var i = 0; i < jsscripts.length; i++){
      var script = jsscripts.item(i);
      if(!script.src) continue;
      idocHTML +=         "    <script language=\"javascript\" src=\""+script.src+"\" type=\"text/javascript\"></script>\n";
    }
    idocBody = '';

    idocHTML +=           "  </head>\n"
                       + "  <body width='100%' class='tooltipbody'>\n"
                       + "    <table width='100%' cellspacing='0' cellpadding='0'>\n"
                       + "      <colgroup>\n"
                       + "        <col width='20px'/>\n"
                       + "        <col/>\n"
                       + "        <col width='20px'/>\n"
                       + "      </colgroup>\n"
                       + "      <tr id='trPopupTitle' class='"+ this.titleClass + "' valign='top'>\n"
                       + "        <td align='left'><img border='0' src='" + respath + "/"+iconImage+"'/></td>\n"
                       + "        <td align='left' id='tdTooltipTitle'><b>" + this.title + "</b></td>\n"
                       + "        <td align='right'><a href='javascript:cancelTipClose();'><img class='popclose' border='0' src='" + respath + "/close.gif'/></a></td>\n"
                       + "      </tr>\n"
                       + "      <tr valign='top'>\n"
                       + "        <td valign='top' colspan='3' class='tipsbody' id='tdTooltipText'>\n"
                       +            this.tooltipBody
                       + "        </td>\n"
                       + "      </tr>\n"
                       + "    </table>\n"
                       + "  </body>\n"
                       + "</html>";
    try{
      ifrEL.contentWindow.document.open();
      ifrEL.contentWindow.document.write(idocHTML);
      ifrEL.contentWindow.document.close();
      this.opened = false;
    }catch(ex){}
    this.setTooltipWindow(this);
  }

  this.setTooltipWindow = function (xTips){
    var spanEL = xTips.spanTips;
    var ifrEL = xTips.ifrTips;
    if(!spanEL || !ifrEL) return;
    if(ifrEL.contentWindow.document.body == null){ // till body object not set, try next interval
      if (!isIE){
        setTimeout( function(){xTips.setTooltipWindow(xTips)},1000);
      }else{
        setTimeout( function(){xTips.setTooltipWindow(xTips)},50);
      }
      return false;
    }

    this.opened = true; // load complete
    spanEL.style.display = 'inline';
    var  d = new Object()
    var triggerOffsetHeight  = 0;
    d.x  = xTips.XPos; d.y = xTips.YPos;
    if(xTips.triggerEl){
      d = this.findXY(xTips.triggerEl);
      triggerOffsetHeight = this.triggerEl.offsetHeight;
    }
    var ttpHeight =  0;
    if (!isIE){ // firefox
      ttpHeight = ifrEL.contentDocument.height;
    }else{ // IE
		ttpHeight = ifrEL.contentWindow.document.body.scrollHeight;
		// IE 6 or older version
		if (typeof document.body.style.maxHeight == "undefined") {
			ttpHeight = ttpHeight*65/100;
       	}
    }
    var ttpTop = d.y + triggerOffsetHeight + this.offsetHeight;
    var curWinPos = document.body.scrollTop;
    if(xTips.resizeTips == false){
      spanEL.style.top = xTips.prevTop + (xTips.prevHeight - ttpHeight);
      ifrEL.height = ttpHeight;
      return false;
    }
    // if space not availabe, try to open in upper part
    if((ttpTop + ttpHeight) > document.body.clientHeight + curWinPos ){
      ttpTop = ttpTop - ttpHeight - triggerOffsetHeight;
    }
    // sets position
    spanEL.style.left = (d.x + this.offsetWidth) + "px";
    spanEL.style.height = ttpHeight + "px";
    spanEL.style.top = ttpTop + "px";
    spanEL.style.zIndex = 99;
    ifrEL.height = ttpHeight + "px";
    
    xTips.prevTop = ttpTop ; // stores previous top
    xTips.prevHeight = ttpHeight; // stores previous top	
    //sets close icon
    
    var ifrWin = xTips.ifrTips.contentWindow;
    var ifrDoc = ifrWin.document;
/*    var closeEl = ifrDoc.getElementById('closeIcon');
    if( closeEl){
      closeEl['onclick'] = function(){
        xTips.closeTooltip(xTips);
      };
    }
*/
    // sets okay button
    var okEl = ifrDoc.getElementById('btnToolOk');
    if(okEl){
      okEl['onclick'] = function(){
        xTips.closeTooltip(xTips);
        xTips.onTooltipClose(xTips);
      };
    }
    // sets escape key press event
    ifrDoc['onkeypress'] = function(evt){
      var e = getEventObject(evt);
      if(!e) e = ifrWin.event;
      var keyCode = 0;
      if(isIE) keyCode = e.keyCode;
      else keyCode = e.charCode;
      if(!isIE && keyCode == 0) keyCode = e.keyCode;
      if(keyCode==27){
        xTips.closeTooltip(xTips);
      }
    };

    if(this.isIE) xTips.ifrTips.focus();
    ifrWin.focus();

    // move popup window
    if(xTips.movable){
      /*var titleEl = ifrDoc.getElementById('trPopupTitle');
      titleEl['onmousedown'] = function(evt){
          var ifrWin = xTips.ifrTips.contentWindow;
          var ifrDoc = ifrWin.document;
          var e = getEventObject(evt);
          if(!e) e = ifrWin.event;
          xTips.onMouseDown(e,xTips);
        };
      */
    }



    // close info popup if mouse clicks out side popup
    xTips.previousEvent = window.document['onclick'];
    if(xTips.titleClass != 'wintitle'){
      ifrDoc['onmouseout'] = function(){
        window.document['onclick'] = function(){
          xTips.closeTooltip(xTips);
          window.document['onclick'] = xTips.previousEvent;
          if(xTips.triggerEl) xTips.triggerEl['onmouseout'] = null;
        };
      };
      if(xTips.triggerEl){
        xTips.triggerEl['onmouseout'] = function(){
          window.document['onclick'] = function(){
            xTips.closeTooltip(xTips);
            window.document['onclick'] = xTips.previousEvent;
            xTips.triggerEl['onmouseout'] = null;
          };
        };
      };
    }
    xTips.resizeTips = false; // no need to resize for progress bar
  }

  this.onMouseDown = function(evt,xTips){
    var spanTips = xTips.spanTips;
    var ifrWin = xTips.ifrTips.contentWindow;
    var ifrDoc = ifrWin.document;
    var titleEl = ifrDoc.getElementById('trPopupTitle');
    var tdEl = ifrDoc.getElementById('spnTest');
    var prevX = evt.clientX;
    var prevY = evt.clientY;
    var d = xTips.findXY(spanTips);
    titleEl['onmousemove'] = function(){
      var currX = evt.clientX;
      var currY = evt.clientY;
      d.x = d.x + (currX - prevX);
      d.y = d.y + (currY - prevY);
      spanTips.style.left = d.x  ;
      spanTips.style.top = d.y  ;
    }
    titleEl['onmouseup'] = function(){
      titleEl['onmousemove'] = null;
    }
    titleEl['onmouseout'] = function(){
      titleEl['onmousemove'] = null;
    }

  }

  /*this.getEventObject = function(){

  }*/
  // Find absolute co-ordinates of an object
  //
  this.findXY = function(obj) {
    var aobj = obj;
    var left = 0;
    var top = 0;
    while (aobj) {
      left += aobj.offsetLeft;
      top += aobj.offsetTop;

      aobj = aobj.offsetParent;
    }
    return { x: left, y: top };
  }

  // closes tooltips
  this.closeTooltip = function(xTips){
    if(!xTips.opened){
      setTimeout(
        function(){
          xTips.closeTooltip(xTips);
        },25  );
    }
    var spanEL = xTips.spanTips;
    spanEL.style.display = 'none';
    this.resizeTips = true;
    this.offsetRecord   = 0;
    // sets focus to target element, if any
    try{
      if(xTips.titleClass == 'wintitle'){
        xTips.targetEl.focus();
        xTips.targetEl.showPopup = 'N';
      }
      ifrWin.parent.document['onclick'] = xTips.previousEvent;
      xTips.triggerEl['onmouseout'] = null;

    }catch(ex){
      // sets to trigger element
      try{xTips.triggerEl.focus();}catch(ex){};
    };
    return true;
  }

  this.removeToolTips = function(xTips){
    var spanEL = xTips.spanTips;
    var ifrEL = xTips.ifrTips;
    try{
      spanEL.innerHTML = "";
    }catch(ex){};
  }

  // on ok button click
  this.onTooltipClose = function(xTips){

  }

  // load details from server
  this.loadDetails = function (){

    var xmldata = this.prepareXMLRequest(this);
    var url = this.requestURL;
    //document.write(xmldata);
    this.postRequest(url,xmldata,this.onPostRequest,'text/xml');
  }

  this.onPostRequest = function(xTips){
    xTips.onShowTips(xTips);
  }

  // method to sent http request
  this.postRequest = function (URL,postdata,funcRef,contentType) {
    if(!contentType) contentType = 'text/xml';
    try {
      this.xmlhttp = XmlHttp.create();
      var async = true;
      this.xmlhttp.open("POST", URL, async);
      var xTips = this;
      this.xmlhttp.onreadystatechange = function(){funcRef(xTips)};
      this.xmlhttp.setRequestHeader("Content-Type", contentType);
      this.xmlhttp.send(postdata);
    } catch (ex) {alert(ex.toString());}
  }

  // prepares xml request for lookup service
  this.prepareXMLRequest = function(xTips){
    if(typeof this.onPrepareFunRef == 'function'){
      this.onPrepareFunRef(xTips);
    }
    var filters = '';
    for(field in this.filter){
      filters += "<"+field+">"+xTips.filter[field]+"</"+field+">\n";
    }
    if(trim(filters) != '') filters = "<filter>\n"+ filters +"</filter>\n";

    var xmldata = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
              "<ufrequest>\n" +
                "<requestType>dblookup</requestType>\n" +
                "<option>\n" ;
    if( xTips.system){
      xmldata  += "<system>"+ xTips.system +"</system>\n";
    }
    if( xTips.defOperator){
      xmldata  += "<defaultOperator>"+ xTips.defOperator +"</defaultOperator>\n";
    }
    xmldata    += "<maxRecord>"+ xTips.maxRecord +"</maxRecord>\n" +
                  "<offsetRecord>"+ xTips.offsetRecord +"</offsetRecord>\n" +
                  "</option>\n" +
                "<search>\n" +
                  "<tableName>"+ xTips.tableName +"</tableName>\n" +
                  "<columnList type='list'>"+ xTips.fields +"</columnList>\n" +
                    filters +
                "</search>\n" +
              "</ufrequest>" +
              "";
    return xmldata;
  }

  this.onResponse = function (xTips){
    if (xTips.xmlhttp.readyState != XMLHTTP_COMPLETED) return;
    var responseXml = xTips.xmlhttp.responseText;
    responseXml = responseXml.replace(/>\s+</gm,"><");
    xTips.processResponseXml(xTips, responseXml);
    xTips.tooltipBody = xTips.description ;
  }

  // default processor for xml picker

  this.processPickerXml = function(xTips,responseXml){
    var doc = XmlDocument.create();
    doc.loadXML(responseXml);
    var xmlerr = doc.parseError;
    if (xmlerr.errorCode != 0) {
      showError("0501",LC_S["HTTP_INVALID_RESPONSE"]);
      return false;
    }
    var error = doc.getElementsByTagName("error");
    if(!error || error.length > 0){
      var currNode = error.item(0);
      var errCode, errMessage, errRemedy;
      var objNode ;
      if (currNode.childNodes.length >= 1 ){
        objNode = currNode.childNodes[0];
        if(objNode.firstChild) errCode  = objNode.firstChild.nodeValue
      }
      if (currNode.childNodes.length >= 2 ){
        objNode = currNode.childNodes[1];
        if(objNode.firstChild) errMessage = objNode.firstChild.nodeValue
      }
      if (currNode.childNodes.length >= 3 ){
        objNode = currNode.childNodes[2];
        if(objNode.firstChild) errRemedy = objNode.firstChild.nodeValue
      }
      showError(errCode,errMessage,errRemedy);
      return false;
    }
    var results = doc.getElementsByTagName("results");
    var htmlContent = '';
    var itemIndex = 0;
    if(results && results.length > 0){
      var currNode = results.item(0).firstChild;
      while(currNode){
        var objNode = null;
        var keyValue = '';
        var keyTitle = '';
        itemIndex++;
        if (currNode.childNodes.length >= 1 ){
          objNode = currNode.childNodes[0];
          keyValue = objNode.firstChild.nodeValue;
        }
        if (currNode.childNodes.length >= 2 ){
          objNode = currNode.childNodes[1];
          keyTitle = objNode.firstChild.nodeValue;
        }
        htmlContent += "\n<label for='pickItem" + itemIndex + "'>\n"
                      +"  <input type='checkbox' name='pickItem" + itemIndex + "' id='pickItem" + itemIndex + "' value='" + keyValue + "'>\n"
                      +"  &nbsp;" + keyTitle
                      + "\n</label><br/>\n";
        currNode = currNode.nextSibling; // reads next record
      }
    }

    htmlContent = "<form name='frmPicker' id='frmPicker' class='inline'>"
                  + htmlContent
                  + "<input type='hidden' name='hidTotalItem' id='hidTotalItem' value='" + itemIndex + "'>"
                  + "<div align='center'><input type='button' name='btnToolOk' id='btnToolOk' value='" + LC_S["OK"] + "'></div>"
                  + "</form>";
    xTips.description = htmlContent;
  }


  // default processor tooltip xml
  this.processResponseXml = function(xTips, responseXml){
    var doc = XmlDocument.create();
    doc.loadXML(responseXml);
    var xmlerr = doc.parseError;
    if (xmlerr.errorCode != 0) {
      return false;
    }
    var error = doc.getElementsByTagName("error");
    if(!error || error.length > 0){
      var currNode = error.item(0);
      var errCode, errMessage, errRemedy;
      var objNode ;
      if (currNode.childNodes.length >= 1 ){
        objNode = currNode.childNodes[0];
        if(objNode.firstChild) errCode  = objNode.firstChild.nodeValue
      }
      if (currNode.childNodes.length >= 2 ){
        objNode = currNode.childNodes[1];
        if(objNode.firstChild) errMessage = objNode.firstChild.nodeValue
      }
      if (currNode.childNodes.length >= 3 ){
        objNode = currNode.childNodes[2];
        if(objNode.firstChild) errRemedy = objNode.firstChild.nodeValue
      }
      showError(errCode,errMessage,errRemedy);
      return false;
    }
    var results = doc.getElementsByTagName("results");

    if(results && results.length > 0){
      if(results.item(0).childNodes && results.item(0).childNodes.length > 0){
        var currNode = results.item(0).firstChild;
        if (currNode.childNodes.length >= 1 ){
          objNode = currNode.childNodes[0];
          xTips.title = objNode.firstChild.nodeValue
        }
        if (currNode.childNodes.length >= 2 ){
          objNode = currNode.childNodes[1];
          xTips.description = objNode.firstChild.nodeValue;
        }

      }else{
        xTips.description = '<p align="center">No help found.<br/>&nbsp;</p>';
      }
    }
  }

  // on ShowTips event handler
  this.onShowTips = function(xTips){
    this.onResponse(xTips);
    if(xTips.description != ''){
      xTips.showTips(xTips);
    }
  }

  if(this.type=='PICKER'){
    this.processResponseXml = this.processPickerXml;
  }else if(this.type=='SEARCH'){
    this.processResponseXml = this.processSearchResult;
  }

}

function addHelpText(iconId,textId){
  XMLTips.add({
    fields  : 'name,t001',
    tableName    : 'dc',
    triggerId    : iconId,
    filter       : {
                    catg : "HELPTEXT",
                    dccd : textId
                  }
                });
}


XMLTips.add = function (params){
    if(!params.eventName) params.eventName = 'click';
    if(!params.type) params.type = 'TOOLTIP';
    if(params.movable == 'undefined') params.movable = false;
    if(params.titleClass == 'undefined') params.titleClass = '';
    triggerEl = document.getElementById(params.triggerId);
    if(!triggerEl) return;
    var xTips = new XMLTips('','',params.type);
    if(params.title) xTips.title        = params.title;
    xTips.titleClass  = params.titleClass;
    xTips.movable     = params.movable;
    xTips.tableName    = params.tableName;
    xTips.fields      = params.fields;
    xTips.filter       = params.filter;
    xTips.requestURL   = getLookupURL();  // populates URL to web service
    xTips.triggerEl   = triggerEl;
    xTips.targetEl    = document.getElementById(params.inputId);
    triggerEl.xTips = xTips;
    if(!isNaN(params.width)) xTips.width = params.width;
    if(params.cacheResult != 'undefined') xTips.cacheResult = params.cacheResult;
    // override processResponseXml
    if(typeof params.processFunRef == 'function'){
      xTips.processResponseXml = function(xT,resXml){
        params.processFunRef(xT,resXml);
      }
    }
    // override onTooltips event
    if(typeof params.onLoadFunc == 'function'){
      xTips.onTipsLoad = function (xT){
        params.onLoadFunc(xT);
      }
    }

    // override xml request generation function
    if(typeof params.prepareFunRef == 'function'){
      xTips.prepareXMLRequest = function(xT){
        params.prepareFunRef(xT);
      }
    }

    // override function which is called before xml request generation
    if(typeof params.onPrepareFunRef == 'function'){
      xTips.onPrepareFunRef = function(xT){
        params.onPrepareFunRef(xT);
      }
    }

    // override ontooltip event
    if(typeof params.onTooltipClose == 'function'){
      xTips.onTooltipClose = function(xT){
        params.onTooltipClose(xT)
      }
    }

    // override cancelTips  method to cancel tooltips
    if(typeof params.cancelTips == 'function'){
      xTips.cancelTips = function(xT){
        return params.cancelTips(xT)
      }
    }

    // attach event to triger icon
    triggerEl['on' + params.eventName] = function(){
      if(typeof xTips != 'object') return;
      xTips.showTips(xTips);
    }

    // process returned xml response
    xTips.onPostRequest = function(){
      xTips.onShowTips(xTips);
    }
}

function getEventObject(evt) {
  return (evt) ? evt : ((window.event) ? event : null);
}
// global
var xTips = new XMLTips("Select address","");


// Flag - this file is loaded and executes
//
document.xtips_js = true;
                                                                                                                           


