//
//  Class:
//      VdfLookupDialog
//
//  This class is a wrapper for lookups. It represents a lookup attachment to an
//  VdfForm. It has several properties for lookups (dialog size, filename, 
//  lookuptable autodisplay (f4)). It is also able to generate a complete lookup
//  using just the tablename and column list.
//
//  Since:
//      02-01-2007
//  Changed:
//      --
//  Version:
//      0.1
//  Creator:
//      Data Access Europe (Harm Wibier)
//

var oLookupForm;    //  Contains form when dialog is opened

//
//  Opens a medium dialog with and opens the sFile in it with the rowid 
//  attribute.
//
//  Params:
//      oForm   VdfForm object that opens the lookup
//      sTable  Name of the main table for the lookup
//      sFile   Filename of the lookup
//      iWidth  Width in pixels of the dialog to open
//      iHeight Height in pixels of the dialog to open
//
function PopLookup(oForm, sTable, sFile, iWidth, iHeight){
    var sUrl = sFile + "?rowid=" + oForm.getStatusField(sTable + '__rowid').getValue();
    
    PopLookupByUrl(oForm, sUrl, iWidth, iHeight);
}

//
//  Opens a medium dialog and opens the sFile with the index and value 
//  attributes.
//
//  Params:
//      oForm   VdfForm used for the find when the lookup is closed
//      sIndex  Index selected in the lookup
//      sValue  Value used for initial find
//      sFile   Filename of the lookup
//      iWidth  Width in pixels of the dialog to open
//      iHeight Height in pixels of the dialog to open
//
function PopLookupByIndex(oForm, sIndex, sValue, sFile, iWidth, iHeight){
    var sUrl = sFile + "?index=" + sIndex + "&value=" + sValue;
    
    PopLookupByUrl(oForm, sUrl, iWidth, iHeight);
}

//
//  Opens a lookup dialog with the given url.
//
//  Params:
//      oForm   VdfForm used for the find when the lookup is closed
//      sUrl    Url to open
//      iWidth  Width in pixels of the dialog to open
//      iHeight Height in pixels of the dialog to open
//
function PopLookupByUrl(oForm, sUrl, iWidth, iHeight){
    oLookupForm = oForm;

    var oDialog = new JModalDialog(iWidth, iHeight);
    oDialog.sTitle = "Lookup";
    oDialog.showPage(sUrl);
}

//
//  Lets the form find the selected record and closes the lookup.
//
//  Params:
//      oForm   VdfForm object of the lookup
//      sTable  Maintable of the lookup
//
function HandleLookup(oForm, sTable){
    window.top.oLookupForm.doFindByRowId(sTable, oForm.getStatusField(sTable + '__rowid').getValue());
    window.top.JModalDialog_Hide();
}

//
//  Closes the modal dialog of the lookup.
//
function CloseLookup(){
    window.top.JModalDialog_Hide();
}



//
//  Constructor: initializes the properties of the object.
//
//  Params:
//      oElement    Html buttom input element
//      oVdfForm    Form to which the lookupdialog belongs
//
function VdfLookupDialog(oElement, oVdfForm){
    var iField;

    this.oVdfForm       = oVdfForm;
    this.oInput         = oElement;
    oElement.oVdfLookupDialog = this;
    
    this.sLookupTable   = browser.dom.getVdfAttribute(this.oInput, "sLookupTable", null);
    this.iDialogWidth   = parseInt(browser.dom.getVdfAttribute(this.oInput, "iDialogWidth", 0));
    this.iDialogHeight  = parseInt(browser.dom.getVdfAttribute(this.oInput, "iDialogHeight", 0));
    this.bAttachKey     = browser.dom.getVdfAttribute(this.oInput, "bAttachKey", true);
    
    this.sLookupFile    = browser.dom.getVdfAttribute(this.oInput, "sLookupFile", null);
    
    this.sWebObject     = browser.dom.getVdfAttribute(this.oInput, "sWebObject", this.oVdfForm.sWebObject);
    this.iRowLength     = browser.dom.getVdfAttribute(this.oInput, "iRowLength", 10);
    this.sLookupFields  = browser.dom.getVdfAttribute(this.oInput, "sLookupFields", null);
        
    if(this.sLookupTable != null){
        this.sLookupTable = this.sLookupTable.toLowerCase();
    }
    
    if(this.sLookupFields != null){
        this.aLookupFields = this.sLookupFields.split(",");
        for(iField = 0; iField < this.aLookupFields.length; iField++){
            this.aLookupFields[iField] = browser.data.trim(this.aLookupFields[iField].toLowerCase());
        }
    }else{
        this.aLookupFields = new Array();
    }
}

//
//  Called by the form to initialize the element. It adds itself to the lookup 
//  array of the form and attaches the events.
//
VdfLookupDialog.prototype.init = function(){
    if(this.bAttachKey && this.sLookupTable != null){
        this.oVdfForm.aLookupDialogs[this.sLookupTable] = this;
    }
    
    browser.events.addGenericListener("click", this.oInput, this.onButtonClick);
}

//
//  Displays the lookup, switches between file and generated version. If field 
//  is given without index no lookup is displayed.
//
//  Params:
//      oVdfOpenerField     Field from which the lookup is opened (optional)
//  Returns:
//      True if the lookup is dispayed
//
VdfLookupDialog.prototype.display = function(oVdfOpenerField){
    var bDisplay = false, sIndex;
    
    //  Check if lookup should be displayed (only when no field is given or field belongs to index on the lookuptable)
    if(oVdfOpenerField != null){
        if(oVdfOpenerField.getTableName() == this.sLookupTable){
            sIndex = this.oVdfForm.getVdfFieldAttribute(oVdfOpenerField, "iIndex");
            
            if(sIndex != "" && sIndex != "0"){
                bDisplay = true;
            }
        }
    }else{
        bDisplay = true;
    }

    //  Switch between the generated and the file lookup
    if(bDisplay){
        if(this.sLookupFile == null){
            this.displayGenerated(oVdfOpenerField);
        }else{
            this.displayFile(oVdfOpenerField);
        }
    }
    
    return bDisplay;
}

//
//  Displays a file lookup (modal dialog with iframe). It switches between the 
//  rowid and the index version according to the given openenfield.
//
//  Params:
//      oVdfOpenerField     Field from which the lookup is opened (optional)
//
VdfLookupDialog.prototype.displayFile = function(oVdfOpenerField){
    var iWidth = this.iDialogWidth, iHeight = this.iDialogHeight;
    
    //  File lookup requires pixelsize!
    if(iWidth < 1){
        iWidth = 650;
    }
    if(iHeight < 1){
        iHeight = 250;
    }
    
    //  Switch between fillbyrowid or by value find
    if(oVdfOpenerField != null){
        PopLookupByIndex(this.oVdfForm, this.oVdfForm.getVdfFieldAttribute(oVdfOpenerField, "iIndex"), oVdfOpenerField.getValue(), this.sLookupFile, iWidth, iHeight);
    }else{
        PopLookup(this.oVdfForm, this.sLookupTable, this.sLookupFile, iWidth, iHeight);
    }
}

//
//  Displays a generated lookup (modal dialog with div). It calls the 
//  initialisation methods after each other.
//
//  Params:
//      oVdfOpenerField Field from which the lookup is opened (optional)
//
VdfLookupDialog.prototype.displayGenerated = function(oVdfOpenerField){
    var oDialogDiv, oDialogForm;
    
    //  Check if fields given, else call method for default fields
    if(this.aLookupFields.length == 0){
        this.determineDefaultFields();
    }
    
    //  Generate JModalDialog
    oDialogDiv = this.generateDialog();
    
    //  Generate the form
    this.generateForm(oDialogDiv, oVdfOpenerField);
    
    //  Position the modal dialog
    this.oJModalDialog.positionDialog(true);
    
    //  Do the correct find
    this.initForm(oVdfOpenerField);
}

//
//  Determines the default fields for the lookup by fetching al table fields and
//  filtering the indexed fields.
//
VdfLookupDialog.prototype.determineDefaultFields = function(){
    var aFields, iField, iIndex;
    
    aFields = this.oVdfForm.oVdfInfo.getTableColumns(this.sLookupTable);
    
    for(iField = 0; iField < aFields.length; iField++){
        iIndex = this.oVdfForm.oVdfInfo.getColumnProperty(this.sLookupTable + "__" + aFields[iField], "iIndex");
        if(iIndex != null && iIndex != "0"){
            this.aLookupFields[this.aLookupFields.length] = this.sLookupTable + "__" + aFields[iField];
        }
    }
    
}

//
//  Creates the modal dialog and returns the div in which the lookup should be 
//  created.
//
//  Returns:
//      Html dom div element in which the content of the dialog should be added.
//
VdfLookupDialog.prototype.generateDialog = function(){
    //  Create dialog
    this.oJModalDialog = new JModalDialog(this.iDialogWidth, this.iDialogHeight);
    this.oJModalDialog.sTitle = "Lookup";
    
    //  Init custom dialog and return div
    return this.oJModalDialog.customDialog();
}

//
//  Generates the objects needed for the form and adds them to the DOM. Also
//  creates the vdf objects needed.
//
//  Params:
//      oParentDiv      Div element in which the lookup is created
//      oVdfOpenerField Field from which the lookup is opened (optional)
//
VdfLookupDialog.prototype.generateForm = function(oParentDiv, oVdfOpenerField){
    var oDomForm, oDomTable, oHeaderRow, oDisplayRow, iField, oCell, oDivControls, oInputSearch, oInputCancel, oInputSelect;
    
    //  Form
    oDomForm = document.createElement("form");
    oDomForm.autocomplete = "off";
    oDomForm.setAttribute("vdfControlType", "form");
    oDomForm.setAttribute("vdfControlName", this.sLookupTable + "_lookup_form");
    oDomForm.setAttribute("vdfMainTable", this.sLookupTable);
    oDomForm.setAttribute("vdfServerTable", this.sLookupTable);
    oDomForm.setAttribute("vdfWebObject", this.sWebObject);
    oDomForm.setAttribute("vdfAutoFill", "false");
    oParentDiv.appendChild(oDomForm);
    
    //  Lookup
    oDomTable = document.createElement("table");
    oDomTable.className = "VdfLookup";
    oDomTable.setAttribute("vdfControlType", "lookup");
    oDomTable.setAttribute("vdfControlName", this.sLookupTable + "_lookup");
    oDomTable.setAttribute("vdfMainTable", this.sLookupTable);
    oDomTable.setAttribute("vdfRowLength", this.iRowLength);
    oDomTable.setAttribute("vdfFocus", "true");
    oDomTable.setAttribute("vdfAutoLabel", "true");
    oDomTable.setAttribute("vdfFixedColumnWidth", "true")
    if(oVdfOpenerField != null){
        oDomTable.setAttribute("vdfIndex", this.oVdfForm.getVdfFieldAttribute(oVdfOpenerField, "iIndex"));
    }
    oDomForm.appendChild(oDomTable);
    
    //  Rows
    oHeaderRow = oDomTable.insertRow(0);
    oHeaderRow.setAttribute("vdfRowType", "header");
    oDisplayRow = oDomTable.insertRow(1);
    oDisplayRow.setAttribute("vdfRowType", "display");
    
    for(iField = 0; iField < this.aLookupFields.length; iField++){
        oCell = document.createElement("th");
        oCell.setAttribute("vdfDataBinding", this.aLookupFields[iField]);
        browser.dom.setCellText(oCell, this.aLookupFields[iField]);
        oHeaderRow.appendChild(oCell);
        
        oCell = oDisplayRow.insertCell(iField);
        oCell.setAttribute("vdfDataBinding", this.aLookupFields[iField]);
        oCell.innertHtml = "&nbsp;";
    }
    
    //  VdfObjects
    oVdfDialogForm = new VdfForm(oDomForm);
    oVdfLookup = new VdfLookup(oDomTable, oVdfDialogForm);
    
    if(this.sWebObject == this.oVdfForm.sWebObject){
        oVdfDialogForm.oVdfInfo = this.oVdfForm.oVdfInfo;
    }
    
    oVdfDialogForm.init();
    
    //  Div with the buttons
    oDivControls = document.createElement("div");
    oDivControls.style.clear = "both";
    oDivControls.className = "VdfLookupDialogControls";
    oDomForm.appendChild(oDivControls);
    
    oInputSelect = document.createElement("input");
    oInputSelect.type = "button";
    oInputSelect.value = "Select";
    oInputSelect.style.margin = "3px";
    oInputSelect.className = "ButtonNormal";
    oDivControls.appendChild(oInputSelect);
    
    oInputCancel = document.createElement("input");
    oInputCancel.type = "button";
    oInputCancel.value = "Cancel";
    oInputCancel.style.margin = "3px";
    oInputCancel.className = "ButtonNormal";
    oDivControls.appendChild(oInputCancel); 
    
    oInputSearch = document.createElement("input");
    oInputSearch.type = "button";
    oInputSearch.value = "Search";
    oInputSearch.style.margin = "3px";
    oInputSearch.className = "ButtonNormal";
    oDivControls.appendChild(oInputSearch); 
    
    //  Attach events
    browser.events.addGenericListener("click", oInputSelect, this.onSelectClick);
    browser.events.addGenericListener("click", oInputCancel, this.onCancelClick);
    browser.events.addGenericListener("click", oInputSearch, this.onSearchClick);
    
    //  Save references
    oDomForm.oVdfLookupDialog = this;
    this.oVdfDialogForm = oVdfDialogForm;
    this.oVdfLookup = oVdfLookup;
}

//
//  Initializes the form by doing the finds (bAutoFill of form is set to false
//  so no double finds are done).
//
//  Params:
//      oVdfOpenerField Field from which the lookup is opened (optional)
//
VdfLookupDialog.prototype.initForm = function(oVdfOpenerField){
    var oVdfLookupDialog = this;
    
    //  Do find (if field given) or fill (if no or rowid field gfiven)
    if(oVdfOpenerField && oVdfOpenerField.getFieldName() != "rowid"){
        this.oVdfLookup.findByIndex(oVdfOpenerField.getValue());
    }else{
        this.oVdfDialogForm.getStatusField(this.sLookupTable + '__rowid').setValue(this.oVdfForm.getStatusField(this.sLookupTable + '__rowid').getValue(), true);
        this.oVdfDialogForm.fill();
    }
    
    //  Attach onEnter (done here to spare memory instead of in generateForm with many local variables)
    this.oVdfDialogForm.onEnter = function(){
        oVdfLookupDialog.finished(true);
        return true;
    }
}

//
//  Handles the results of the generated dialog and hides / removes the dialog.
//
//  Params:
//      bSelectResult   If true the result is given to the opener form (false 
//                      for cancel)
//
VdfLookupDialog.prototype.finished = function(bSelectResult){
    if(bSelectResult){
        this.oVdfForm.doFindByRowId(this.sLookupTable, this.oVdfDialogForm.getStatusField(this.sLookupTable + '__rowid').getValue());
    }
    
    this.oVdfDialogForm.oForm.oVdfLookupDialog = null;
    this.oVdfDialogForm = null;
    this.oVdfLookup = null;
    
    this.oJModalDialog.hide();
    this.oJModalDialog = null;
}


//
//  Catches the onclick event of the button that belongs to the dialog and calls
//  the display method.
//
//  Params:
//      e   Event object on some browsers
//
VdfLookupDialog.prototype.onButtonClick = function(e){
    var oVdfLookupDialog, oTarget;
    
    oTarget = browser.events.getTarget(e);
    if(oTarget == null || oTarget.oVdfLookupDialog == null)
        return false;
    
    oVdfLookupDialog = oTarget.oVdfLookupDialog;
    
    oVdfLookupDialog.display();
}


//
//  Fetches the onclick event from the select button and searches the 
//  lookupdialog object and calls the finished method.
//
//  Params:
//      e   Event object on some browsers
//
VdfLookupDialog.prototype.onSelectClick = function(e){
    var oTarget, oVdfLookupDialog;
    
    oTarget = browser.events.getTarget(e);
    if(oTarget == null)
        return false;
        
    oTarget = browser.dom.searchParent(oTarget, "form");
    if(oTarget == null || oTarget.oVdfLookupDialog == null)
        return false;
    
    oVdfLookupDialog = oTarget.oVdfLookupDialog;
    
    oVdfLookupDialog.finished(true);
}

//
//  Fetches the onclick event from the cancel button and searches the 
//  lookupdialog object and calls the finished method.
//
//  Params:
//      e   Event object on some browsers
//
VdfLookupDialog.prototype.onCancelClick = function(e){
    var oTarget, oVdfLookupDialog;

    oTarget = browser.events.getTarget(e);
    if(oTarget == null)
        return false;

    oTarget = browser.dom.searchParent(oTarget, "form");
    if(oTarget == null || oTarget.oVdfLookupDialog == null)
        return false;

    oVdfLookupDialog = oTarget.oVdfLookupDialog;
    
    oVdfLookupDialog.finished(false);
}

//
//  Fetches the onclick event from the search button and searches the 
//  lookupdialog object and calls the jumpIntoListDisplay method of the lookup.
//
//  Params:
//      e   Event object on some browsers
//
VdfLookupDialog.prototype.onSearchClick = function(e){
    var oTarget, oVdfLookupDialog;
    
    oTarget = browser.events.getTarget(e);
    if(oTarget == null)
        return false;
        
    oTarget = browser.dom.searchParent(oTarget, "form");
    if(oTarget == null || oTarget.oVdfLookupDialog == null)
        return false;
    
    oVdfLookupDialog = oTarget.oVdfLookupDialog;
    
    oVdfLookupDialog.oVdfLookup.jumpIntoListDisplay();
}