/**
 * $Id: JSWorkflowExpressionEditBox.js,v 1.4 2011-11-01 12:00:23 lan Exp $
 *
 * Input edit box with workflow variable selector.
 */

function JSWorkflowExpressionEditBox( propInfo, format )
{
    JSEditBox.call(this, propInfo, format); // call parent constructor
    this.objectClassName = "JSWorkflowExpressionEditBox";
};

JSWorkflowExpressionEditBox.prototype = new JSEditBox();
JSWorkflowExpressionEditBox.superClass = JSEditBox.prototype;

// override
JSWorkflowExpressionEditBox.prototype.createHTMLNode = function()
{
    var element = JSEditBox.prototype.createHTMLNode.apply(this);
    var result = $('<div/>');
    var detailsButton = $("<input type='button' class='button' value='...'/>").addClass("ui-corner-all").addClass("ui-state-default");
    result.append(element);
    result.append(detailsButton);
    this.diagramPath = opennedDocuments[activeDocumentId].completeName;
    var workflowViewPart = lookForViewPart("diagram.workflow.main");
    if(workflowViewPart && workflowViewPart.selectedNodeName)
    	this.diagramPath = getElementPath(this.diagramPath+"/"+workflowViewPart.selectedNodeName);
    var _this = this;
    this.rnd = rnd();
    $(detailsButton).click(function() {_this.showVariableSelector();});
    return result.get(0);
};

JSWorkflowExpressionEditBox.prototype.onVariableSelected = function(varPath)
{
    var text = this.HTMLNode.value;
    var selectionStart = this.HTMLNode.selectionStart;
    text = text.substring(0, selectionStart)+"$"+varPath+"$"+text.substring(selectionStart);
    this.HTMLNode.focus();
    this.HTMLNode.value = text;
    this.HTMLNode.selectionStart = selectionStart;
    this.HTMLNode.selectionEnd = selectionStart+varPath.length+2;
};

JSWorkflowExpressionEditBox.prototype.getBranchNode = function(branch)
{
    return this.dialogContent.find(getJQueryIdSelector("#var_"+branch)).get(0);
};

JSWorkflowExpressionEditBox.prototype.loadBranch = function(branch)
{
    var _this = this;
    if(branch == null) branch = "";
    var node = this.getBranchNode(branch);
    $(node).children("ul").children("li").each(function()
    {
        _this.tree.remove(this);
    });
    _this.creatingItem = true;
    var dummy = _this.tree.create({
        attributes: {
            id: ("#var!dummy_"+branch),
            rel: "disabled"
        },
        data: {
            title: "Loading..."
        }
    }, node);
    dummy.addClass("treeitem-disabled");
    dummy.children("a").get(0).style.backgroundImage = "url('icons/busy.png')";
    _this.creatingItem = false;
    queryBioUML('web/research', {
        action : "var_tree",
        de : this.diagramPath,
        branch : branch
    }, function(data)
    {
        $(node).children("ul").children("li").each(function()
        {
            _this.tree.remove(this);
        });
        _this.creatingItem = true;
        for(var i=0; i<data.values.children.length; i++)
        {
            var item = data.values.children[i];
            var name = item.name.substring(item.name.lastIndexOf("/")+1);
            var childNode = _this.tree.create({
                attributes: {
                    id: "#var_"+item.name,
                    "data-value": item.value,
                    "data-path": item.name
                },
                data: {
                    title: name
                }
            }, node);
            if(item.leaf)
            {
            	childNode.children("a").get(0).style.backgroundImage = "url('icons/leaf.gif')";
            } else
            {
                var dummy = _this.tree.create({
                    attributes: {
                        id: ("#var!dummy_"+item.name),
                        rel: "disabled"
                    },
                    data: {
                        title: "Loading..."
                    }
                }, childNode);
                dummy.addClass("treeitem-disabled");
                dummy.children("a").get(0).style.backgroundImage = "url('icons/busy.png')";
                _this.tree.close_branch(childNode, true);
            }
        }
        _this.creatingItem = false;
    });
};

JSWorkflowExpressionEditBox.prototype.showVariableSelector = function()
{
    var _this = this;
    var treeId = "vartree";
    this.dialogContent = $('<div><div id="'+treeId+'" style="height: 300px; overflow: auto"><ul><li id="#var_" class="open"><a href="#">/</a></li></ul></div>Selected variable:<br><input type="text" readonly id="varname" style="width: 100%"><br>Value:<br><input type="text" readonly id="varvalue" style="width: 100%"></div>');
    this.tree = $.tree_create();
    this.tree.rnd = _this.rnd;
    this.tree.init(this.dialogContent.find("#"+treeId), {
		callback : {
			onopen : function(node, treeObj) {
    			if(!_this.creatingItem)
    				_this.loadBranch(node.getAttribute("data-path"));
			},
			onselect : function(node, treeObj) {
				if(node.getAttribute("data-path"))
				{
					_this.dialogContent.find("#varname").val(node.getAttribute("data-path"));
					_this.dialogContent.find("#varvalue").val(node.getAttribute("data-value"));
				}
			}
		}
	});
    this.loadBranch();
    this.dialogContent.dialog(
    {
        modal: true,
        autoOpen: true,
        width: 400,
        title: "Select variable",
        buttons: 
        {
            "Cancel": function()
            {
    			_this.tree.destroy();
                $("#" + treeId + " li").die();
                $("#" + treeId + " li a").die();
                $(this).dialog("close");
                $(this).remove();
            },
            "Ok": function()
            {
                _this.onVariableSelected(_this.dialogContent.find("#varname").val());
                _this.tree.destroy();
                $("#" + treeId + " li").die();
                $("#" + treeId + " li a").die();
                $(this).dialog("close");
                $(this).remove();
            }
        }
    });
};

