/* QwwJs_ListBoxMgr
 * 
 * Part of the QlikWeb WorkBench Javascript Library (http://www.qlikwebworkbench.com)
 *
 * Copyright (c) 2007 Industrial CodeBox Ltd. All Rights Reserved.
 * http://www.industrialcodebox.com
 * Email support@industrialcodebox.com for licensing and support information.
 */
function listboxresults()
{    
    this.selected = new Array();
    this.disabled = new Array();
    this.associated = new Array();
    
    //
    // Each element in this array will have.
    // elem.text
    // elem.value 
    // elem.state - 0 = associated, 1 = disabled, 2 = selected
    this.all = new Array();
        
    this.GetSummary = function()
    {
       return  "Selected = " + this.selected.length + 
                ", Disabled = " + this.disabled.length + 
                ", Associated = " + this.associated.length;
    };
};

function QwwJs_ListBoxMgr(objectId, pageSize)
{   
    if(pageSize == null)
        pageSize = 20;
        
    var hasPageSizeBeenSet = false;

    var id = objectId;
    
    this.ObjectID = id;
    
    var _Initialized = false;            
    var results = new listboxresults();
    
    // -------------------------------------------------
    // INTERFACE
    
    this.RegisterUpdatedCallBack = function(callback, data)
    {
        this.OnUpdate = callback;
        this.OnUpdateData = data;
    };
    
    this.ClearAll = function(isFinal)
    {
        if(isFinal == null)
            isFinal = true;
            
        var ID = QwwJs_ListBoxMgr.GetID(id);                             
        avqSet(ID, "clear", "", isFinal);    
    };

    this.MakeSingleSelection = function(itemValueOrText, valueIsText, isFinal)
    {
        if(isFinal == null)
            isFinal = true;

        QwwJs_ListBoxMgr.MakeSingleSelection(this.ObjectID, itemValueOrText, valueIsText, isFinal);
    };

    this.MakeSelection = function(arrayOfItems, valueIsText, isFinal)
    {        
        if(isFinal == null)
            isFinal = true;

        QwwJs_ListBoxMgr.MakeSelection(this.ObjectID, arrayOfItems, valueIsText, isFinal);
    };
      
    this.OnAvqUpdateComplete = function()
    {
        this.updateResults();
        
        if(this.OnUpdate)
        {
            if(results.HaveUpdated == true)
            {
                this.OnUpdate(results, this.OnUpdateData);
            }
        }
    };
        
    this.GetValueForItem = function(item)
    {
        for(var i = 0; i < results.all.length; i++)
        {
            if(results.all[i].text == item)
                return results.all[i].value;
        }
    };
    
    this.GetAllSelectedItems = function(){return results.selected;};
    this.GetAllEnabledItems = function(){return results.associated;};
    this.GetAllDisabledItems = function(){return results.disabled;};
    this.GetAllItems = function(){return results.all;};
    
    this.GetAllAvailableItems = function()
    {
        var i = 0;
        var res = new Array();
        
        for(var j = 0; j < results.selected.length; j++)
        {
            res[i] = results.selected[j];
            i++;
        }

        for(var j = 0; j < results.associated.length; j++)
        {
            res[i] = results.associated[j];
            i++;
        }
        
        return res;
    
    };
    // --------------------------------------------------
    
    function a(s)
    {
        alert("ListBoxMgr:" + s);
    };
    
        
    this.getSummary = function()
    {
        return id + " : " + results.getSummary();
    };
    
    function initialize() 
    {       
        var ID = QwwJs_ListBoxMgr.GetID(id);

        var box = AvqSelect(ID);
                             
        if(box == null){        
                 
            avqSet(ID, "add", "text;value;choice;pagesize", false);
            avqSet(ID, "pagesize", pageSize, true);
            return false;
        }
        else
        {
            if(!hasPageSizeBeenSet)
            {
                //
                // We would come into this branch if a listbox on the page
                // had already setup this object. Here though we would override the
                // page size which had been set by the list box.
                //
                avqSet(ID, "pagesize", pageSize, true);
                hasPageSizeBeenSet = true;
            }
        }
        
        _Initialized = true;

        return true;	// handshake - there will not be a new update
    };

    
    this.GetStateAsString = function(state)
    {
        return QwwJs_ListBoxMgr.GetStateAsString(state);
    };
    
    this.CallAction = function(action, isFinal)
    {
        if(isFinal == null)
            isFinal = true;

        QwwJs_ListBoxMgr.CallAction(this.ObjectID, action, isFinal);
    };
    
    this.updateResults = function()
    {           
        results = new listboxresults();                
        results.HaveUpdated = false;
        
        if (!_Initialized) {            
            if (! initialize()) {
                return;
            }
        }
                
        var ID = QwwJs_ListBoxMgr.GetID(id);                        
        var CH = AvqSelect(ID);
        
        if(CH == null)
        {
            // This might be called as the result of an OnAvqUpdateComplete
            // which might be for an unrelated table or lisbox, in which case
            // the XML wont contain that for XH
            return;
        }

        //alert(CH.xml);
                        
        //var vals = CH.selectNodes("choice/element");        
        var vals = CH.selectNodes("value/element");        
        
        if(vals.length == 0)
        {
            vals = CH.selectNodes("choice/element");        
        }
        
        results.HaveUpdated = true;
                     
        var selectedIndex = 0;
        var disabledIndex = 0;
        var associatedIndex = 0;
        
        var pageSize = CH.getAttribute("pagesize");
        var pageOffset = CH.getAttribute("pageoffset");
        var totalSize = CH.getAttribute("totalsize");
        var searchable = CH.getAttribute("searchable");
        var name = CH.getAttribute("name");

        for (var i = 0; i < vals.length; i ++) 
        {        
            var text = vals[i].getAttribute("text");
            var val = vals[i].getAttribute("value");
            
            var all = results.all;
                        
            all[i] = {};
            
            all[i].Value = val;
            all[i].Text = text;
            
            if (vals[i].getAttribute ("selected") != null) //selected
            { 
                all[i].State = 2;
                
                results.selected[selectedIndex++] = text;
            } 
            else if (vals[i].getAttribute ("mode") == "disabled") //excluded
            {
                results.disabled[disabledIndex++] = text;
                
                all[i].State = 1;
            }
            else //associated
            {
                results.associated[associatedIndex++] = text;
                
                all[i].State = 0;
            }
        }
    };
    
    if(qwwHub)
        qwwHub.Register(this);
};

// -------------------------------------------------------------------------------
//
// QwwJs_ListBoxMgr Static Methods
//
// -------------------------------------------------------------------------------
QwwJs_ListBoxMgr.GetID = function(id)
{   
    var id = AvqView + "." + id; 
            
    return id;
};

QwwJs_ListBoxMgr.MakeSelection = function(objectId, arrayOfItems, optionalUseText, isFinal)
{
    if(isFinal == null) 
        isFinal = true;
    
    var ID = QwwJs_ListBoxMgr.GetID(objectId);    
    
    var mode = "value";
            
    if(optionalUseText)
    {                    
        avqSet(ID, "clear", "", true);
        mode = "text";
    }
    else
    {
        avqSet(ID, "clear", "", false);
    }
    
    for(var i = 0; i < arrayOfItems.length; i++)
    {
        var isActuallyFinal = (i == (arrayOfItems.length - 1)) && isFinal;
                        
        avqSet(ID, mode, arrayOfItems[i], isActuallyFinal);
    }
}

QwwJs_ListBoxMgr.MakeSingleSelection = function(objectId, itemValueOrText, optionalUseText, isFinal)
{
    if(isFinal == null) 
        isFinal = true;
    
    var ID = QwwJs_ListBoxMgr.GetID(objectId);
    
    if(itemValueOrText == null)
    {
        avqSet(ID, "clear", "", isFinal);
    }
    else
    {
        if(optionalUseText)
        {
            avqSet(ID, "clear", "", true); // in text mode seems we must send clear through separately.
            avqSet(ID, "text", itemValueOrText, isFinal);        
        }
        else
        {
            avqSet(ID, "clear", "", false);
            avqSet(ID, "value", itemValueOrText, isFinal);        
        }
    }
};

QwwJs_ListBoxMgr.GetStateAsString = function(state)
{
    if(state == 0)
        return "Associated";
        
    if(state == 1)
        return "Disabled";
        
    if(state == 2)
        return "Selected";

    return "Unknown";    
};


/* 
MI - Minimize
RE - Restore
PR - Print
XL - SendToExcel
CA - ClearMemberFields (ClearAll)
CO - Compare
SA - SelectAll
SE - SelectExcluded
SP - SelectPossible
LS - Lock (LockSelection)
US - Unlock (UnlockSelection) 
*/

QwwJs_ListBoxMgr.GetAllowedActions = function()
{
    if(!QwwJs_ListBoxMgr.AllowedActions)
    {
        var aa = "['MI', 'RE', 'PR', 'XL', 'CA', 'CO', 'SA', 'SE', 'SP', 'LS', 'US']";
                        
        QwwJs_ListBoxMgr.AllowedActions = eval("{" + aa + "}");
        
        QwwJs_ListBoxMgr.AllowedActionsString = aa;
    }
        
    return QwwJs_ListBoxMgr.AllowedActions;
};

QwwJs_ListBoxMgr.CallAction = function(listBoxId, action, isFinal)
{
    if(isFinal == null)
        isFinal = true;
        
    var allowedActions = QwwJs_ListBoxMgr.GetAllowedActions();
    
    var allowed = false;
        
    for(var i = 0; i < allowedActions.length; i++)
    {
        var aa = allowedActions[i];
        
        if(aa == action)
        {
            allowed = true;
            break;
        }
    }
    
    if(allowed){
        avqSet(AvqView + "." + listBoxId + "." + action, "action", "", isFinal);
    }
    else{
        alert("QwwJs_ListBoxMgr.CallAction:Action " + action + " is not allowed, please pass " + QwwJs_ListBoxMgr.AllowedActionsString);
    }
};