// JScript File
// Author   : David Goddard, WinWin Solutions Australia Pty Ltd
// Written  : 15 May 2006
// Purpose  : This file contains the basic functions to make AJAX
//            connections to OpenInsight

// Global variables
var xmlhttp
var xmldoc
var xsl
var xmlSysMsg
var oiFileName 
var oiListFields 
var oiListTotals
var oiFormFields 
var oiByClauses 
var oiWithClauses
var oiFormName
var oiListName
var oiListXSLT 
var oiFormXSLT 
var oiProcedure
var oiParms
var oiRefreshListFlag
var oiDialogXMLDoc

//var oiAppId = queryParm("appid")
//var oiServerURL = "http://" + location.hostname +"/cgi-bin/oecgi.exe/"
var oiServerURL = "http://" + location.hostname +"/dms/oecgi2.exe/"
var setFocus = ""

// create the xmldoc object
xmldoc = createXMLDoc(xmldoc)

// Define the XSL stylesheet object
xsl = createXMLDoc(xsl)

// Define the XML document object    
xmlSysMsg = createXMLDoc(xmlSysMsg)

//fireFoxAddSelectNodes()

// Define the stylesheets to use in this web page
// Style Sheet used for list/table views
var listDoc = ""
var listSortTag = ""
var sortTag = ""
var oiXSLListURL = oiServerURL + "inet_table_list_xsl/"
var oiListXSLT = ""

// Style sheet used for form/data entry & edit
var formDoc = ""
var formSelectTag = ""
var selectTag = ""
var oiXSLFormURL = oiServerURL + "inet_table_xsl/"
var oiFormXSLT = ""

writeURL = oiBuildURL("inet_form_write","")
deleteURL = oiBuildURL("inet_form_delete","") 

// Define the processing message window
var procmsg = ""

// Internal Functions
function createXMLDoc() {
    // Creates a cross browser XML document object
    // code for IE
    if (window.ActiveXObject)
      {
      //xmlobj = new ActiveXObject("Microsoft.XMLDOM");
      xmlobj = new ActiveXObject("MSXML2.DOMDocument.3.0");
      xmlobj.async=false;
      }
    // code for Mozilla, etc.
    //else if (document.impementation && document.implementation.createDocument) {
    //  xmlobj= document.implementation.createDocument("","",null);
    //}else{
    //  alert('Your browser does not support XML');
    //}
    // code for Mozilla, etc,
    else {
        var doc = new DOMParser()
        xmlobj = doc.parseFromString("","text/xml")
        //fireFoxAddSelectNodes(xmlobj)
    } 
    return xmlobj
} 

function XMLDocLoad(data) {
    // Creates a cross browser XML document object
    // code for IE
    if (window.ActiveXObject)
      {
      xmlobj = new ActiveXObject("Microsoft.XMLDOM");
      //xmlobj = new ActiveXObject("MSXML2.DOMDocument.3.0");
      xmlobj.async=false;
      xmlobj.loadXML(data)
      
      }
    // code for Mozilla, etc.
    //else if (document.impementation && document.implementation.createDocument) {
    //  xmlobj= document.implementation.createDocument(data,"",null);
    //  alert("here")
    //}else{
    //  alert('Your browser does not support XML');
    //}
    // code for Mozilla, etc,
    else {
        var doc = new DOMParser()
        xmlobj = doc.parseFromString(data,"text/xml")
        fireFoxAddSelectNodes(xmlobj)
    } 
    return xmlobj
} 

function oiRefresh() {
    return "&refresh=" + Math.floor(Math.random()*1001)
}

function oiBuildURL(Procedure,Parms) {
    return oiServerURL + Procedure + "/" + getOISession() + "?" + encodeURI(Parms) + oiRefresh()
}

function getOISession() {
    sessionid = getCookie("sessionid")
    if (sessionid==null) {
        //alert("no session")
        sessionid = ""
    }    
    //sessionid = "&sessionid="+sessionid
return sessionid
}    

function setCookie(c_name,value,expiredays) {
    var exdate=new Date()
    exdate.setDate(expiredays)
    document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate)
}

function getCookie(c_name) {
    if (document.cookie.length>0) {
        c_start=document.cookie.indexOf(c_name + "=") 
        if (c_start!=-1) { 
            c_start=c_start + c_name.length+1 
            c_end=document.cookie.indexOf(";",c_start)
            if (c_end==-1) c_end=document.cookie.length
            return unescape(document.cookie.substring(c_start,c_end))
        } 
    }
    return null
}

function loadXMLDoc(url,callBack) {
// code for Mozilla, etc.
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest()
  xmlhttp.onreadystatechange=callBack
  xmlhttp.open("GET",url,true)
  xmlhttp.send(null)
  }
// code for IE
else if (window.ActiveXObject)
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
    if (xmlhttp)
    {
    xmlhttp.onreadystatechange=callBack
    xmlhttp.open("GET",url,true)
    xmlhttp.send()
    }
  }
}

function oiSendXMLData(url,callBack,refresh,rowId) {
// Send form data back to OI.

    if (refresh==1) {
        oiRefreshListFlag = 1
    } else {
        oiRefreshListFlag = 0    
    }
    
    if (url==writeURL) {
        // This is an update. So udate the
        // xmldoc as well.
        //alert("update xmldoc id = " + rowId)
        if (rowId) {
            updateXMLFromFormNew("form_oi",rowId)
        }    
    }    

    if (url==deleteURL) {
        // remove the selected row from the xmldoc
        //alert("delete me id = " + rowId)
        //node = xmldoc.selectNodes("//row[@ID='"+rowId+"']")
        //node = xmldoc.getElements("//row[@ID='"+rowId+"']")[0]
        //alert("after node ")
        //xmldoc = xmldoc.removeNodeFromTree(node);
        
        // Check if the user really wants to delete
        returnVal = confirm("Do you really want to delete this item?")
        if (returnVal==false) {
            // Terminate the delete
            return
        }    
    }    
        
    var ctrls = document.forms[0].elements
    var formdata = ""
    for (i=0;i<ctrls.length;i++) {
        // determine the control type and process 
        if (formdata!="") {
            formdata += "&"
        }    
        
        type = ctrls[i].type
        switch (type) {
            case "button":
                // Skip buttons
                value = ""
                break
            case "checkbox":
                if (ctrls[i].checked==true) {
                    value = "Y"
                }else{
                    value = "N"
                }    
                formdata += encodeURIComponent(ctrls[i].id) + "=" + value
                break
            default:
               formdata += encodeURIComponent(ctrls[i].id) + "=" + encodeURIComponent(ctrls[i].value)
        }    
        //alert("control = " + ctrls[i].id + "\nvalue length= " + ctrls[i].value.length)
        //alert("control = " + ctrls[i].id + "\nvalue = [" + ctrls[i].value + "]")
    }

    //url = url + encodeURI(parms) + oiRefresh()
    //url = url + parms + oiRefresh()
    url = url + oiRefresh()
    //alert("sendurl = " + url)
    result = oiHTTPRequest(url,callBack,"saving","oiprocessingmsg","the data has been updated successfully",formdata)

    return result
}

function oiHTTPRequest(url,callBack,processMsgText,msgObject,successMsgText,data) {
    // makes the httpRequest to OpenInsight
    // code for Mozilla, etc.
    if (window.XMLHttpRequest) {
      xmlhttp=new XMLHttpRequest()
      //alert("Mozilla")
    }  
    // code for IE
    else if (window.ActiveXObject) {
        //alert("IE")
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
    }
        
    // Make sure we have a valid xmlhttp object
    if (xmlhttp) {
      //alert("AJAX here we go")
      if (callBack) {
          //alert("AJAX callback ")  
          xmlhttp.onreadystatechange=function(data,response) {
                //alert("ready state = " + xmlhttp.readyState)
                switch (xmlhttp.readyState) {
                    case 0:
                        oiProcessingMsg(processMsgText,msgObject)
                        break
                    case 1:
                        oiProcessingMsg(processMsgText+".",msgObject)
                        break
                    case 2:
                        oiProcessingMsg(processMsgText+"..",msgObject)
                        break
                    case 3: 
                        oiProcessingMsg(processMsgText+"...",msgObject)
                        break
                    case 4:            
                        response = xmlhttp.status
                        
                        //alert("State is 4 = " + xmlhttp.responseText)                    
                        // pulldown the processing message
                        oiProcessingMsg("",msgObject)
                        
                        if (response=="200"){
                            data = xmlhttp.responseText
                            //alert("state change function 4 - data: " + xmlhttp.responseText)        
                            // Check the status of the returned data
                            //alert("here")   
                            //xmlSysMsg.loadXML(data)      
                            var xmlSysMsg = xmlhttp.responseXML
                            //alert("and now here")
                            
                            if (xmlSysMsg) {
                               // We have a valid XML string returned
                               // Check for errors
                               var err = xmlSysMsg.selectNodes("/update/errors/error")
                               if (err.length) {
                                   // We have errors
                               } else {
                                  if (successMsgText) {  
                                    oiProcessingMsg(successMsgText,"oisysmessage")
                                  }  
                               }    
                            }     
                            // Call the Callback routine
                            callBack(data,response)
                        } else {
                            // Status was not 200, so the reqest failed. Display a error message
                            errorMsgText = "arrh:- an error occured - Code: " + xmlhttp.status + " - " + xmlhttp.statusText + ". The process failed"
                            oiProcessingMsg(errorMsgText,"oisysmessage")                        
                            //alert("Error Code: " + xmlhttp.status + "\n\nError Desc: " + xmlhttp.statusText)
                        }    
                        break
                 }    
          }
      
          if (data==null) {
            // We are getting data
            //alert("url = " + url)
            xmlhttp.open("GET",url,true)
          } else {
            // We are sending data
            xmlhttp.open("POST",url,true)
          }
          xmlhttp.send(data)
      } else {
        // no callback, this is a syncrinous connection
        if (data==null) {
            // We are getting data
            //alert("url = " + url)
            xmlhttp.open("GET",url,false)
          } else {
            // We are sending data
            xmlhttp.open("POST",url,false)
          }
          xmlhttp.send(data)
          return xmlhttp.responseText
      }    
    } else {
       // no valid xmlhttp object. 
       // display an error message
       alert("Your browser does not support AJAX applications")
    } 
    return "" 
}

function oiGetXMLData(url,callBack){
    // get data from OI
    result = oiHTTPRequest(url,callBack,"loading","oiprocessingmsg","")
    return result
}    

function oiProcessingMsg(message,id) {
    if (id==null) {
        id = "datafromoi"
    }    
    //alert("message = " + message)
    switch (id) {
        case "datafromoi":
            document.getElementById(id).innerHTML="<p align='center'><image src='images/waiting_animation.gif'></image><br /><br />" + message + "</p>"    
            break
        case "oiprocessingmsg": 
            document.getElementById("oiprocessingmsg").innerHTML= message        
            //alert("message = " + message)
            if (message=="") {
                // set the cursor back to auto
                document.body.style.cursor = "auto"
                document.getElementById("oisysmessage").innerHTML = ""
            } else {
                // set the cursor to wait
                document.body.style.cursor = "wait"
            }
            break
        default:    
            document.getElementById(id).innerHTML="<img src=\"images/dmssysmsgleft.jpg\" align=\"top\" height=\"13px\" /><font class=\"sysmessage\">" + message + "</font><img src=\"images/dmssysmsgright.jpg\" align=\"top\" height=\"13px\" />"              
            break
    }    
}  

function oi_iconv(ctrl,iconvs) {
    var returnval = true
    var patterns = iconvs.split("|")
    for (x in patterns) {
        switch (patterns[x]) {
            case "TOUPPER": 
                ctrl.value = ctrl.value.toUpperCase()
                break
            case "NOSPACE":
                ctrl.value = ctrl.value.replace(/ /g,"")
                break
            case "DATE":
                checkdate(ctrl)
                break
        }    
        
        // Stop processing if we have an error
        if (returnval==false) {break}
    }    
return returnval
}    

function updateXMLFromForm(formName,rowid) {
    // Update the XML document with the new values
    var form = document.getElementById(formName)
    //alert(xmldoc.xml)
    
    for (i=0;i<(form.length);i++) {
        value = ""
        var control = form.item(i)
        controlid = control.id
        type = control.type
        switch (type) {
            case "button":
                // Ignore
                break
            //case "hidden":
                // ignore
            //    break
            case "checkbox":
                // get the checked state first
                if (control.checked==true) {
                    value = control.value
                } else {
                    value = "N"
                }
                //alert("control " + control.id + " - value " + value)
                break
            default:        
                value = control.value                    
                break
        }
        //alert("Control Name = " + controlid + "\nControl Value = " + control.value)                
        if (value!="") {       
            column = xmldoc.selectNodes("//row["+rowid+"]/"+controlid)
            if (column.length) {
                //alert("Control Name = " + controlid + "\nControl Value = " + control.value)
                column.item(0).text = value
            }    
        }    
    }    
}

function updateXMLFromFormNew(formName,rowid) {

    // Update the XML document with the new values
    var form = document.getElementById(formName)
    //alert(xmldoc.xml)
    
    for (i=0;i<(form.length);i++) {
        value = ""
        var control = form.item(i)
        controlid = control.id
        type = control.type
        
        switch (type) {
            case "button":
                // Ignore
                break
            case "hidden":
                // ignore
                break
            case "checkbox":
                // get the checked state first
                if (control.checked==true) {
                    value = control.value
                } else {
                    value = "0"
                }
                break
            default:        
                value = control.value                    
                break
        }
        //newvalue = value.replace(/'/,"&apos;")
        //alert("Control " + control.id + " = " + newvalue)
        if (value!="") {
            column = xmldoc.selectNodes('//row[@ID="'+rowid+'"]/'+controlid)
            if (column.length) {
                //alert("Control Name = " + controlid + "\nControl Value = " + control.value)
                column.item(0).text = value
            }    
        }    
    }        
}

function checkdate(objName) {
var datefield = objName;
if (chkdate(objName) == false) {
datefield.select();
alert("That date is invalid.  Please try again.");
datefield.focus();
return false;
}
else {
return true;
   }
}
function chkdate(objName) {
//var strDatestyle = "US"; //United States date style
var strDatestyle = "EU";  //European date style
var strDate;
var strDateArray;
var strDay;
var strMonth;
var strYear;
var intday;
var intMonth;
var intYear;
var booFound = false;
var datefield = objName;
var strSeparatorArray = new Array("-"," ","/",".");
var intElementNr;
var err = 0;
var strMonthArray = new Array(12);
strMonthArray[0] = "Jan";
strMonthArray[1] = "Feb";
strMonthArray[2] = "Mar";
strMonthArray[3] = "Apr";
strMonthArray[4] = "May";
strMonthArray[5] = "Jun";
strMonthArray[6] = "Jul";
strMonthArray[7] = "Aug";
strMonthArray[8] = "Sep";
strMonthArray[9] = "Oct";
strMonthArray[10] = "Nov";
strMonthArray[11] = "Dec";
strDate = datefield.value;
if (strDate.length < 1) {
return true;
}
for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
strDateArray = strDate.split(strSeparatorArray[intElementNr]);
if (strDateArray.length != 3) {
err = 1;
return false;
}
else {
strDay = strDateArray[0];
strMonth = strDateArray[1];
strYear = strDateArray[2];
}
booFound = true;
   }
}
if (booFound == false) {
if (strDate.length>5) {
strDay = strDate.substr(0, 2);
strMonth = strDate.substr(2, 2);
strYear = strDate.substr(4);
   }
}
if (strYear.length == 2) {
strYear = '20' + strYear;
}
// US style
if (strDatestyle == "US") {
strTemp = strDay;
strDay = strMonth;
strMonth = strTemp;
}
intday = parseInt(strDay, 10);
if (isNaN(intday)) {
err = 2;
return false;
}
intMonth = parseInt(strMonth, 10);
if (isNaN(intMonth)) {
for (i = 0;i<12;i++) {
if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
intMonth = i+1;
strMonth = strMonthArray[i];
i = 12;
   }
}
if (isNaN(intMonth)) {
err = 3;
return false;
   }
}
intYear = parseInt(strYear, 10);
if (isNaN(intYear)) {
err = 4;
return false;
}
if (intMonth>12 || intMonth<1) {
err = 5;
return false;
}
if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
err = 6;
return false;
}
if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
err = 7;
return false;
}
if (intMonth == 2) {
if (intday < 1) {
err = 8;
return false;
}
if (LeapYear(intYear) == true) {
if (intday > 29) {
err = 9;
return false;
}
}
else {
if (intday > 28) {
err = 10;
return false;
}
}
}
if (strDatestyle == "US") {
datefield.value = strMonthArray[intMonth-1] + " " + intday+" " + strYear;
}
else {
datefield.value = intday + " " + strMonthArray[intMonth-1] + " " + strYear;
}
return true;
}
function LeapYear(intYear) {
if (intYear % 100 == 0) {
if (intYear % 400 == 0) { return true; }
}
else {
if ((intYear % 4) == 0) { return true; }
}
return false;
}
function doDateCheck(from, to) {
if (Date.parse(from.value) <= Date.parse(to.value)) {
alert("The dates are valid.");
}
else {
if (from.value == "" || to.value == "") 
alert("Both dates must be entered.");
else 
alert("To date must occur after the from date.");
   }
}

function oiXSLTTransform(styleSheetURL,xmlTransformDoc){ 
    // transforms an XML document in xmlDoc into HTML using 
    // the XSLT styleSheet in styleSheetURL 
    
    //Check if the form has been enabled
    if (styleSheetURL=="") {
        // Terminate processing
        return
    }    
    
   var xslDoc=new ActiveXObject("MSXML2.FreeThreadedDOMDocument")
   xslDoc.async=false
   var rsltDoc=new ActiveXObject("MSXML2.FreeThreadedDOMDocument")
   var xslTemplate=new ActiveXObject("MSXML2.XSLTemplate")
   //alert("stylesheet = " + styleSheetURL)
   xslDoc.load(styleSheetURL)
   
   if (xslDoc.parseError!=0) {
        if (xslDoc.parseError.srcText=="no session") {
            alert("no session")
            location.replace("dms_online.htm")
            return
        } else {
        
            msg = "XSLT Transformation Error\n"
            msg += "Code: " + xslDoc.parseError.errorCode + "\n"
            msg += "Reason: " + xslDoc.parseError.reason + "\n"
            msg += "Line No: " + xslDoc.parseError.line + "\n"
            msg += "Position: " + xslDoc.parseError.linepos + "\n"
            msg += "Text: " + xslDoc.parseError.srcText + "\n"
            //alert(msg)
            errorMsgText = "arrh:- an xsl parse error occured - Code:["+xslDoc.parseError.errorCode+"]. The transformation failed"
            oiProcessingMsg(errorMsgText,"oisysmessage")
       }                            
   } else {
       // Display a processing message
       oiProcessingMsg(" transforming ","oiprocessingmsg")   
       xslTemplate.stylesheet=xslDoc
       
       var xslProc=xslTemplate.createProcessor()
       //alert(xmlDoc.xml)
       xslProc.input=xmlTransformDoc;
       xslProc.output=rsltDoc;
       
       if (arguments.length >2 && 
          arguments.length % 2 == 0){
          
          for (var i=0;
             i<Math.floor((arguments.length)/2)-1;
             i++){   
             
             paramName=arguments[2*i+2];
             paramValue=arguments[2*i+3];
             //alert(paramName + " = " + paramValue)
             xslProc.addParameter(paramName,paramValue);
          }
       }

       // Perform the transformation
       xslProc.transform()
       
       //alert("after transform = " + rsltDoc.parseError)
       if (rsltDoc.parseError!=0) {
        msg = "XSLT Transformation Error\n"
        msg += "Code: " + rsltDoc.parseError.errorCode + "\n"
        msg += "Reason: " + rsltDoc.parseError.reason + "\n"
        msg += "Line No: " + rsltDoc.parseError.line + "\n"
        msg += "Text: " + rsltDoc.parseError.srcText + "\n"
        //alert(msg)
        errorMsgText = "arrh:- an xsl transformation error occured - Code:["+xslDoc.parseError.errorCode+"]. The transformation failed"
       oiProcessingMsg(errorMsgText,"oisysmessage")       
       } 
     // Pull down processing message
     oiProcessingMsg("","oiprocessingmsg")
     //alert("End here")
   }
   return rsltDoc;
}

function oiPrepareXSLT(){
    // Define the stylesheets to use in this web page
    // Style Sheet used for list/table views
    oiListXSLT = oiXSLListURL + getOISession() + "?" + "filename=" + oiFileName 
    
    if(oiListName!="") {
        oiListXSLT += "&form=" + oiListName
    }
    
    if (oiListFields!="") {
        oiListXSLT += "&fields=" + oiListFields
    }
    if (oiByClauses!="") {
        oiListXSLT += "&byClauses=" + oiByClauses
    }
    if (oiWithClauses!="") {
        oiListXSLT += "&withClauses=" + oiWithClauses
    }    
    if (oiListTotal!="") {
        oiListXSLT += "&total=" + oiListTotal
    }
    
    if (oiPageTitle!="") {
        oiListXSLT += "&title=" + oiPageTitle
        oiFormXSLT += "&title=" + oiPageTitle
    }        

    // Style sheet used for form/data entry & edit
    // If form set to NONE then set this to null
    if (oiFormName=="NONE"){
        // Do not set a form, no editing available
        oiFormXSLT = ""
    } else {    
        oiFormXSLT = oiXSLFormURL + getOISession() + "?" + "filename=" + oiFileName 
        if (oiFormFields!="") {
            oiFormXSLT += "&fields=" + oiFormFields
        }
        
        if(oiFormName!="") {
            oiFormXSLT += "&form=" + oiFormName
        }
    }    

    oiParms = "filename=" + oiFileName
    if (oiByClauses!="") {
        oiParms += "&by_clauses=" + oiByClauses
    }
    
    if (oiWithClauses!="") {
        oiParms += "&with_clauses=" + oiWithClauses
    }

}

function pb_add_onclick() {
    // User wants to add a row to the system
    var xmlNew = createXMLDoc(xmlNew)
    var text = '<?xml version="1.0" encoding="windows-1252" ?>'
    text += '<rows xmlns:rti="http://www.revelation.com/XMLSchema" rti:noNamespaceSchemaLocation="">'
    text += "\n\t<row ID='1' >"
    text += "\n\t\t<id></id>"      
    text += "\n\t</row>"            
    text += "\n</rows>"
    xmlNew.loadXML(text)
    
    var html = oiXSLTTransform(oiFormXSLT,xmlNew,"filterKey","1")
    datafromoi.innerHTML = html.xml    
}

function pb_refresh() {
    url = oiBuildURL(oiProcedure,oiParms)
    oiGetXMLData(url,state_Change_body_onload_new)
    //var html = oiXSLTTransform(oiListXSLT,xmldoc)
    //alert("html = " + html.xml)
    //datafromoi.innerHTML = html.xml
}

function pb_reset() {
    hash = location.hash
    hash = hash.substring(1)
    document.getElementById(hash).click()
}

function oiViewForm(id) {
    oiWithClausesBak = oiWithClauses 
    oiWithClauses = "WITH @ID = '" + id + "'"
    oiPrepareXSLT()
    url = oiBuildURL(oiProcedure,oiParms)
    oiGetXMLData(url,state_Change_body_onload_form)
    oiWithClauses = oiWithClausesBak
    
    //var html = oiXSLTTransform(oiListXSLT,xmldoc)
    //alert("html = " + html.xml)
    //datafromoi.innerHTML = html.xml
}

function postWriteRow(data,response) {
    // Refresh the list
    //x = body_onload()
    //var html = oiXSLTTransform(oiListXSLT,xmldoc)
    //datafromoi.innerHTML=html.xml
    //alert("post write flag =" + oiRefreshListFlag)
    
    page = location.hash
    //alert("page = " + page)
    if (page=="#lk_order") {
        // If this is an ADMIN or SYSADMIN user then take them to the new order form directly
        usertype = getCookie("snusertype")
        if (usertype=="ADMIN"|usertype=="SYSADMIN") {
            //viewOrder("","")
            //alert("here")
            lk_ordermaint.click()
            //oiXMLTransform("xsl/orders_wizard_step4.xsl")
        } else {
            oiXMLTransform("xsl/orders_wizard_step4.xsl")
        }    
    }
    
    if (page=="#lk_ordermaint") {
        // check the status. If the status is 3 then
        // update the correspondent
        //alert("post write data = \n" + data)
        //rowxml = XMLDocLoad(data)
        //status = rowxml.selectNodes("//status").item(0).text
        //if (status=="3") {
        //    pending_sent_to = rowxml.selectNodes("//pending_sent_to").item(0).text
        //    //alert("pending sent to = " + pending_sent_to)
        //    document.getElementById("pending_sent_to").value = pending_sent_to
        //}    
    }
    
    if (page=="#lk_quotewizard") {
        oiXMLTransform("dmsonline/xsl/quote_wizard_step4.xsl")
    }
        
    if (oiRefreshListFlag==1) {
        // refresh
        pb_refresh()
    }else{    
        // Do not refresh
    }   
    
}

function postDeleteRow(data,response) {
    // Refresh the list
    //x = body_onload()
    //oiXMLTransform(listDoc,listSortTag,"date","")
    //var html = oiXSLTTransform(oiListXSLT,xmldoc)
    //datafromoi.innerHTML=html.xml
    pb_refresh()
}

function oi_popup(mode,filename,columns,byclause,returnCols) {
    // Displays  a modal dialog box with a list of 
    // rows values to choose from. 
    // Returns the row id  
    switch(mode) {
        case "create":
            // create a popup dialog box             
            var args = new Object()
            args.filename = filename
            args.columns = columns
            args.byclause = byclause
            args.returnCols = returnCols
            var list = "dialogHeight : 480px; dialogWidth : 640px; center: yes; resizable: no; status: no; help: no"
            rtnValue = window.showModalDialog("oi_popup.htm",args,list)
            //rtnValue = window.showModalDialog("about:blank",args,list)
            if (rtnValue) {
               //alert("return value is " + rtnValue)
               //returnto = document.activeElement.returnto
               //document.getElementById(returnto).value = rtnValue
               return rtnValue
            } else {
               //alert("no return value")
            }    
            break
        case "build":
            // get the data to display in the dialog box
            // Get the arguaments passed via dialogArguments
            var args = window.dialogArguments
            document.title = args.filename + " Popup - Please choose from the list below"
            oiFileName = args.filename
            oiPageTitle = args.filename + " Popup"
            oiListName = "INET_TABLE_XSL_POPUP_DEFAULT"
            oiFormName = ""
            oiListFields = args.columns
            oiListTotal = ""
            oiFormFields = ""
            oiByClauses = args.byclause
            oiWithClauses = ""
            oiProcedure = "inet_oi_xml"
            defaultButton = "pb_search"
            oiPrepareXSLT()
            url = oiBuildURL(oiProcedure,oiParms)
            oiGetXMLData(url,state_Change_body_onload_new) 
            break   
        case "return":
            // returns the selected value(s) back to the parent.
            if (filename!="") {
                var args = window.dialogArguments
                returnCols = args.returnCols.toLowerCase()
                colsArray = returnCols.split(",")
                if (colsArray.length>1) {
                   returnVal = new Array()
                   for (i in colsArray) {
                      //alert("column = " + colsArray[i])
                      returnVal[i] = xmldoc.selectNodes("//row[@ID='" + filename+ "']/" + colsArray[i] + "").item(0).text
                      //alert("value = " + returnVal[i])
                   }   
                } else {
                    //returnVal = filename
                    returnVal = xmldoc.selectNodes("//row[@ID='" + filename+ "']/" + colsArray[0] + "/text()").item(0).xml
                }  
            } else {
                returnVal = ""
            }      
            //alert("text = " + returnVal)
            //window.returnValue = filename
            window.returnValue = returnVal
            window.close()
            break
    }        
}

function oi_search(mode,filename,columns,byclause,returnCols) {
    // Displays  a modal dialog box with a list of 
    // rows values to choose from. 
    // Returns the row id  
    switch(mode) {
        case "create":
            // create a popup dialog box             
            var args = new Object()
            args.filename = filename
            args.columns = columns
            args.byclause = byclause
            args.returnCols = returnCols
            var list = "dialogHeight : 480px; dialogWidth : 640px; center: yes; resizable: no; status: no; help: no"
            rtnValue = window.showModalDialog("oi_search.htm",args,list)
            //rtnValue = window.showModalDialog("about:blank",args,list)
            if (rtnValue) {
               //alert("return value is " + rtnValue)
               //returnto = document.activeElement.returnto
               //document.getElementById(returnto).value = rtnValue
               return rtnValue
            } else {
               //alert("no return value")
            }    
            break
        case "build":
            // get the data to display in the dialog box
            // Get the arguaments passed via dialogArguments
            var args = window.dialogArguments
            document.title = args.filename + " Please enter a value to search for"
            oiFileName = args.filename
            oiPageTitle = args.filename + " Popup"
            oiListName = "INET_TABLE_XSL_LIST_SEARCH"
            oiFormName = ""
            oiListFields = args.columns
            oiListTotal = ""
            oiFormFields = ""
            oiByClauses = args.byclause
            oiWithClauses = ""
            oiProcedure = "inet_oi_xml"
            defaultButton = "pb_search"
            oiPrepareXSLT()
            url = oiBuildURL(oiProcedure,oiParms)
            
            var xmlNew = createXMLDoc(xmlNew)
            var text = '<?xml version="1.0" encoding="windows-1252" ?>'
            text += '<rows xmlns:rti="http://www.revelation.com/XMLSchema" rti:noNamespaceSchemaLocation="">'
            text += "\n</rows>"
            xmlNew.loadXML(text)
            //alert("here")
            var html = oiXSLTTransform(oiListXSLT,xmlNew)
            datafromoi.innerHTML = html.xml
            break   
        case "return":
            // returns the selected value(s) back to the parent.
            if (filename!="") {
                var args = window.dialogArguments
                returnCols = args.returnCols.toLowerCase()
                colsArray = returnCols.split(",")
                if (colsArray.length>1) {
                   returnVal = new Array()
                   for (i in colsArray) {
                    //alert("column = " + colsArray[i])
                      returnVal[i] = xmldoc.selectNodes("//row[@ID='" + filename+ "']/" + colsArray[i] + "").item(0).text
                   }   
                } else {
                    //returnVal = filename
                    returnVal = xmldoc.selectNodes("//row[@ID='" + filename+ "']/" + colsArray[0] + "").item(0).text
                }  
            } else {
                returnVal = ""
            }          
            //alert("text = " + returnText)
            //window.returnValue = filename
            window.returnValue = returnVal
            window.close()
            break
    }        
}

function oi_dialog(mode,filename,columns,byclause,form,title,data,returnCols) {
    // Displays  a modal dialog box with a list of 
    // rows values to choose from. 
    // Returns the row id 
    switch(mode) {
        case "create":
            // create a search dialog box             
            var args = new Object()
            args.filename = filename
            args.columns = columns
            args.byclause = byclause
            args.returnCols = returnCols
            args.data = data
            args.form = form
            args.title = title
            var list = "dialogHeight : 480px; dialogWidth : 640px; center: yes; resizable: no; status: no; help: no"
            rtnValue = window.showModalDialog("oi_dialog.htm",args,list)
            //rtnValue = window.showModalDialog("about:blank",args,list)
            if (rtnValue) {
               //alert("return value is " + rtnValue)
               //returnto = document.activeElement.returnto
               //document.getElementById(returnto).value = rtnValue
               return rtnValue
            } else {
               //alert("no return value")
            }    
            break
        case "build":
            // get the data to display in the dialog box
            // Get the arguaments passed via dialogArguments
            var args = window.dialogArguments
            document.title = args.title
            oiFileName = args.filename
            oiPageTitle = args.title
            oiListName = ""
            oiFormName = args.form
            if (oiFormName=="") {
                oiFormName = "INET_TABLE_XSL_FORM_DIALOG"
            }    
            oiListFields = ""
            oiListTotal = ""
            oiFormFields = args.columns
            oiByClauses = ""
            oiWithClauses = ""
            oiProcedure = "inet_oi_xml"
            defaultButton = "pb_save"
            oiPrepareXSLT()
            url = oiBuildURL(oiProcedure,oiParms)
            //oiGetXMLData(url,state_Change_body_onload_new)
            //alert("data = " + args.data) 
            text = args.data
            //oiDialogXMLDoc = xmldoc
            xmldoc = XMLDocLoad(text)
            var html = oiXSLTTransform(oiFormXSLT,xmldoc,"filterKey","NEW")
            //alert("html = " + html.xml)
            datafromoi.innerHTML = html.xml
            break  
        case "save":
            // User wants to save the data.
            //alert("id = " + filename)
            oiSendXMLData(writeURL,postWriteRow,0,filename)
            oi_dialog("return",filename)
            break
        case "return":
            // returns the selected value(s) back to the parent.
            if (filename) {
                var args = window.dialogArguments
                returnCols = args.returnCols.toLowerCase()
                //alert("before \n[" + returnCols + "]")
                colsArray = returnCols.split(",")
                colsArrayLen = colsArray.length
                //alert("colsArrayLen = " + colsArrayLen)
                switch (colsArrayLen) {
                    case 0:
                        // No data to return
                        //alert("No data to return")
                        returnVal = ""
                        break
                    case 1:
                        // return one column
                        //alert("One column of data to return")
                        returnVal = xmldoc.selectNodes("//row[@ID='" + filename + "']/" + returnCols + "").item(0).text                        
                        break
                    default:
                        // return more than one column
                        //alert("More than one column of data to return")
                        returnVal = new Array()
                        for (i in colsArray) {
                            //alert("column = " + colsArray[i])
                            returnVal[i] = xmldoc.selectNodes("//row[@ID='" + filename + "']/" + colsArray[i] + "").item(0).text
                        }    
                        break
                }            
            } else {
                returnVal = ""
            }       
            //alert("returnval = " + returnVal)   
            // restore XMLDOC
            //xmldoc = oiDialogXMLDoc
            window.returnValue = returnVal
            window.close()
            break
    }        
}

function oi_printPreview(mode,filename,columns,byclause,form,title,data,id,returnCols) {
    // Displays  a modal dialog box with a list of 
    // rows values to choose from. 
    // Returns the row id
    
    switch(mode) {
        case "create":
            // create a search dialog box             
            var args = new Object()
            args.filename = filename
            args.columns = columns
            args.byclause = byclause
            args.returnCols = returnCols
            args.data = data
            args.form = form
            args.title = title
            args.oiProcedure = oiProcedure
            args.id = id
            var list = "dialogHeight : 600px; dialogWidth : 800px; center: yes; resizable: no; status: no; help: no; unadorned: no;"
            rtnValue = window.showModalDialog("oi_ui_process.htm?process=printpreview",args,list)
            //rtnValue = window.showModalDialog("about:blank",args,list)
            if (rtnValue) {
               //alert("return value is " + rtnValue)
               //returnto = document.activeElement.returnto
               //document.getElementById(returnto).value = rtnValue
               return rtnValue
            } else {
               //alert("no return value")
            }    
            break
        case "build":
            // get the data to display in the dialog box
            // Get the arguaments passed via dialogArguments
            datafromoi.innerHTML = "...Please Wait..."
            var args = window.dialogArguments
            document.title = args.title
            oiFileName = args.filename
            oiPageTitle = args.title
            oiListName = ""
            oiFormName = ""
            oiListFields = ""
            oiListTotal = ""
            oiFormFields = ""
            oiByClauses = ""
            oiWithClauses = ""
            oiProcedure = args.oiProcedure
            defaultButton = "pb_save"
            //oiPrepareXSLT()
            //url = oiBuildURL(oiProcedure,oiParms)
            //oiGetXMLData(url,state_Change_body_onload_new)
            //alert("data = " + args.data) 
            //text = args.data
            //xmldoc.loadXML(text)
            id = args.id
            printPreviewXSLT = args.form + "&format=print&printid=" + encodeURIComponent(id)
            //alert("url = " + printPreviewXSLT)
            var html = oiXSLTTransform(printPreviewXSLT,xmldoc)
            //alert("html = " + html.xml)
            datafromoi.innerHTML = html.xml
            break  
        case "save":
            // User wants to save the data.
            //alert("id = " + filename)
            oiSendXMLData(writeURL,postWriteRow,0,filename)
            oi_dialog("return",filename)
            break
        case "return":
            // returns the selected value(s) back to the parent.
            if (filename!="") {
                var args = window.dialogArguments
                returnCols = args.returnCols.toLowerCase()
                colsArray = returnCols.split(",")
                if (colsArray.length>1) {
                   returnVal = new Array()
                   for (i in colsArray) {
                    //alert("column = " + colsArray[i])
                      returnVal[i] = xmldoc.selectNodes("//row[@ID='" + filename+ "']/" + colsArray[i] + "").item(0).text
                   }   
                } else {
                    //returnVal = filename
                    returnVal = xmldoc.selectNodes("//row[@ID='" + filename+ "']/" + colsArray[0] + "").item(0).text
                }  
            } else {
                returnVal = ""
            }          
            //alert("text = " + returnText)
            //window.returnValue = filename
            window.returnValue = returnVal
            window.close()
            break
    }        
}

function oiRequiredProcessing(cols,hiLiteColor) {
    // checks the passed array of controls to make sure 
    // that a value has been entered.
    failedList = ""
    returnval = true
    for (x in cols) {
        if (document.getElementById(cols[x]).value=="") {
            failedList += cols[x] + "\n"
            document.getElementById(cols[x]).style.backgroundColor = hiLiteColor
            returnval = false
        } else {
            document.getElementById(cols[x]).style.backgroundColor = ''
        }    
    }
    
    if (returnval==false) {
        alert("The following data is required.\n\n" + failedList + "\nPlease enter a value before proceeding.")
    }
    
    return returnval
}        

function fireFoxAddSelectNodes(xmlDoc) {
// check for XPath implementation 
if( document.implementation.hasFeature("XPath", "3.0") ) { 
    alert("firefox here")
	// prototying the XMLDocument 
	XMLDocument.prototype.selectNodes = function(cXPathString, xNode) { 
	//xmlDoc.prototype.selectNodes = function(cXPathString, xNode) { 
		if( !xNode ) { xNode = this; }
		var oNSResolver = this.createNSResolver(this.documentElement) 
		var aItems = this.evaluate(cXPathString, xNode, oNSResolver,
		XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null) 
		var aResult = [];
		for( var i = 0; i < aItems.snapshotLength; i++) { 
			aResult[i] = aItems.snapshotItem(i);
		} 
		return aResult;
	} 

	// prototying the Element 
	Element.prototype.selectNodes = function(cXPathString) 	{ 
		if(this.ownerDocument.selectNodes) { 
			return this.ownerDocument.selectNodes(cXPathString, this);
		}else{
			throw "For XML Elements Only";
		} 
	} 
} 
}