hudson-behavior.js 29.8 KB
Newer Older
K
kohsuke 已提交
1 2 3 4 5 6
//
// JavaScript for Hudson
//     See http://www.ibm.com/developerworks/web/library/wa-memleak/?ca=dgr-lnxw97JavascriptLeaks
//     for memory leak patterns and how to prevent them.
//

7 8 9 10 11 12 13
// create a new object whose prototype is the given object
function object(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

K
kohsuke 已提交
14 15 16
// id generator
var iota = 0;

K
kohsuke 已提交
17 18
// Form check code
//========================================================
K
kohsuke 已提交
19
var FormChecker = {
K
kohsuke 已提交
20 21
    // pending requests
    queue : [],
K
kohsuke 已提交
22

K
kohsuke 已提交
23
    inProgress : false,
K
kohsuke 已提交
24

K
kohsuke 已提交
25 26 27 28
    delayedCheck : function(url, method, target) {
        this.queue.push({url:url, method:method, target:target});
        this.schedule();
    },
K
kohsuke 已提交
29

K
kohsuke 已提交
30 31 32 33 34
    sendRequest : function(url, params) {
        if (params.method == "post") {
            var idx = url.indexOf('?');
            params.parameters = url.substring(idx + 1);
            url = url.substring(0, idx);
K
kohsuke 已提交
35
        }
K
kohsuke 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
        new Ajax.Request(url, params);
    },

    schedule : function() {
        if (this.inProgress)  return;
        if (this.queue.length == 0) return;

        var next = this.queue.shift();
        this.inProgress = true;

        this.sendRequest(next.url, {
            method : next.method,
            onComplete : function(x) {
                next.target.innerHTML = x.responseText;
                FormChecker.inProgress = false;
                FormChecker.schedule();
            }
        });
    }
K
kohsuke 已提交
55 56
}

K
kohsuke 已提交
57 58 59 60 61
function findFollowingTR(input, className) {
    // identify the parent TR
    var tr = input;
    while (tr.tagName != "TR")
        tr = tr.parentNode;
K
kohsuke 已提交
62

K
kohsuke 已提交
63 64 65 66
    // then next TR that matches the CSS
    do {
        tr = tr.nextSibling;
    } while (tr.tagName != "TR" || tr.className != className);
K
kohsuke 已提交
67

K
kohsuke 已提交
68
    return tr;
K
kohsuke 已提交
69 70
}

71 72
// shared tooltip object
var tooltip;
K
kohsuke 已提交
73 74 75 76 77



// Behavior rules
//========================================================
K
kohsuke 已提交
78
// using tag names in CSS selector makes the processing faster
79
function registerValidator(e) {
K
kohsuke 已提交
80 81 82 83
    e.targetElement = findFollowingTR(e, "validation-error-area").firstChild.nextSibling;
    e.targetUrl = function() {
        return eval(this.getAttribute("checkUrl"));
    };
84
    var method = e.getAttribute("checkMethod");
K
kohsuke 已提交
85
    if (!method) method = "get";
86 87 88

    FormChecker.delayedCheck(e.targetUrl(), method, e.targetElement);

89
    e.onchange = e.onblur = function() {
K
kohsuke 已提交
90 91 92 93 94 95 96
        var target = this.targetElement;
        FormChecker.sendRequest(this.targetUrl(), {
            method : method,
            onComplete : function(x) {
                target.innerHTML = x.responseText;
            }
        });
97
    }
K
kohsuke 已提交
98
    e = null; // avoid memory leak
K
kohsuke 已提交
99
}
100

K
kohsuke 已提交
101
var hudsonRules = {
K
kohsuke 已提交
102 103 104
    "BODY" : function() {
        tooltip = new YAHOO.widget.Tooltip("tt", {context:[]});
    },
105

K
kohsuke 已提交
106 107 108 109
    "TABLE.sortable" : function(e) {// sortable table
        ts_makeSortable(e);
    },

K
kohsuke 已提交
110 111 112
    "TABLE.progress-bar" : function(e) {// sortable table
        e.onclick = function() {
            var href = this.getAttribute("href");
K
kohsuke 已提交
113
            if(href!=null)      window.location = href;
K
kohsuke 已提交
114 115 116 117
        }
        e = null; // avoid memory leak
    },

K
kohsuke 已提交
118 119 120 121
    "INPUT.advancedButton" : function(e) {
        e.onclick = function() {
            var link = this.parentNode;
            link.style.display = "none"; // hide the button
K
kohsuke 已提交
122

K
kohsuke 已提交
123
            var container = link.nextSibling.firstChild; // TABLE -> TBODY
K
kohsuke 已提交
124

K
kohsuke 已提交
125 126 127
            var tr = link;
            while (tr.tagName != "TR")
                tr = tr.parentNode;
K
kohsuke 已提交
128

K
kohsuke 已提交
129 130 131 132 133 134
            // move the contents of the advanced portion into the main table
            while (container.lastChild != null)
                tr.parentNode.insertBefore(container.lastChild, tr.nextSibling);
        }
        e = null; // avoid memory leak
    },
K
kohsuke 已提交
135

K
kohsuke 已提交
136 137 138 139 140 141 142
// scripting for having default value in the input field
    "INPUT.has-default-text" : function(e) {
        var defaultValue = e.value;
        Element.addClassName(e, "defaulted");
        e.onfocus = function() {
            if (this.value == defaultValue) {
                this.value = "";
K
kohsuke 已提交
143
                Element.removeClassName(this, "defaulted");
K
kohsuke 已提交
144 145 146 147 148
            }
        }
        e.onblur = function() {
            if (this.value == "") {
                this.value = defaultValue;
K
kohsuke 已提交
149
                Element.addClassName(this, "defaulted");
K
kohsuke 已提交
150 151 152 153
            }
        }
        e = null; // avoid memory leak
    },
K
kohsuke 已提交
154

155 156 157 158 159 160 161 162 163 164 165
// <label> that doesn't use ID, so that it can be copied in <repeatable>
    "LABEL.attach-previous" : function(e) {
        e.onclick = function() {
            var e = this;
            while(e.tagName!="INPUT")
                e=e.previousSibling;
            e.click();
        }
        e = null;
    },

K
kohsuke 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
// form fields that are validated via AJAX call to the server
// elements with this class should have two attributes 'checkUrl' that evaluates to the server URL.
    "INPUT.validated" : registerValidator,
    "SELECT.validated" : registerValidator,
    "TEXTAREA.validated" : registerValidator,

// validate form values to be a number
    "INPUT.number" : function(e) {
        e.targetElement = findFollowingTR(e, "validation-error-area").firstChild.nextSibling;
        e.onchange = function() {
            if (this.value.match(/^(\d+|)$/)) {
                this.targetElement.innerHTML = "";
            } else {
                this.targetElement.innerHTML = "<div class=error>Not a number</div>";
            }
        }
        e = null; // avoid memory leak
    },
K
kohsuke 已提交
184

K
kohsuke 已提交
185 186 187 188
    "A.help-button" : function(e) {
        e.onclick = function() {
            var tr = findFollowingTR(this, "help-area");
            var div = tr.firstChild.nextSibling.firstChild;
K
kohsuke 已提交
189

K
kohsuke 已提交
190 191
            if (div.style.display != "block") {
                div.style.display = "block";
K
kohsuke 已提交
192
        // make it visible
K
kohsuke 已提交
193 194 195 196 197 198 199 200 201 202
                new Ajax.Request(
                        this.getAttribute("helpURL"),
                    {
                        method : 'get',
                        onComplete : function(x) {
                            div.innerHTML = x.responseText;
                        }
                    });
            } else {
                div.style.display = "none";
K
kohsuke 已提交
203 204
            }

K
kohsuke 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
            return false;
        }
        e = null; // avoid memory leak
    },

// deferred client-side clickable map.
// this is useful where the generation of <map> element is time consuming
    "IMG[lazymap]" : function(e) {
        new Ajax.Request(
            e.getAttribute("lazymap"),
            {
                method : 'get',
                onComplete : function(x) {
                    var div = document.createElement("div");
                    document.body.appendChild(div);
                    div.innerHTML = x.responseText;
                    var id = "map" + (iota++);
                    div.firstChild.setAttribute("name", id);
                    e.setAttribute("usemap", "#" + id);
                }
            });
    },
227 228 229 230 231 232 233


    // button to add a new repeatable block
    "INPUT.repeatable-add" : function(e) {
        e.onclick = function() {
            repetableSupport.onAdd(this);
        };
K
kohsuke 已提交
234
        e = null; // avoid memory leak
235 236 237 238 239 240
    },

    "INPUT.repeatable-delete" : function(e) {
        e.onclick = function() {
            repetableSupport.onDelete(this);
        };
K
kohsuke 已提交
241
        e = null; // avoid memory leak
242 243 244 245 246
    },

    "DIV.repeated-container" : function(e) {
        // compute the insertion point
        var ip = e.lastChild;
K
kohsuke 已提交
247
        while (!Element.hasClassName(ip, "repeatable-insertion-point"))
248 249
            ip = ip.previousSibling;
        // set up the logic
K
kohsuke 已提交
250
        object(repetableSupport).init(e, e.firstChild, ip);
251 252
    },

K
kohsuke 已提交
253 254
    // resizable text area
    "TEXTAREA" : function(textarea) {
K
kohsuke 已提交
255 256 257 258 259
        var handle = textarea.nextSibling;
        if(handle==null || handle.className!="textarea-handle") return;

        var Event = YAHOO.util.Event;

K
kohsuke 已提交
260
        handle.onmousedown = function(ev) {
K
kohsuke 已提交
261 262
            ev = Event.getEvent(ev);
            var offset = textarea.offsetHeight-Event.getPageY(ev);
K
kohsuke 已提交
263 264
            textarea.style.opacity = 0.5;
            document.onmousemove = function(ev) {
K
kohsuke 已提交
265
                ev = Event.getEvent(ev);
K
kohsuke 已提交
266
                function max(a,b) { if(a<b) return b; else return a; }
K
kohsuke 已提交
267 268
                textarea.style.height = max(32, offset + Event.getPageY(ev)) + 'px';
                return false;
K
kohsuke 已提交
269 270 271 272 273 274
            };
            document.onmouseup = function() {
                document.onmousemove = null;
                document.onmouseup = null;
                textarea.style.opacity = 1;
            }
K
kohsuke 已提交
275 276 277 278
        };
        handle.ondblclick = function() {
            textarea.style.height = "";
            textarea.rows = textarea.value.split("\n").length;
K
kohsuke 已提交
279 280 281
        }
    },

282 283
    // structured form submission
    "FORM" : function(form) {
K
kohsuke 已提交
284
        // add the hidden 'json' input field, which receives the form structure in JSON
285 286 287 288 289 290 291 292
        var div = document.createElement("div");
        div.innerHTML = "<input type=hidden name=json>";
        form.appendChild(div);
        
        form.onsubmit = function() { buildFormTree(this) };
        form = null; // memory leak prevention
    },

293 294 295
    // hook up tooltip
    "[tooltip]" : function(e) {
        // copied from YAHOO.widget.Tooltip.prototype.configContext to efficiently add a new element
K
kohsuke 已提交
296
        // event registration via YAHOO.util.Event.addListener leaks memory, so do it by ourselves here
297 298 299
        e.onmouseover = function(ev) { return tooltip.onContextMouseOver.call(this,YAHOO.util.Event.getEvent(ev),tooltip); }
        e.onmousemove = function(ev) { return tooltip.onContextMouseMove.call(this,YAHOO.util.Event.getEvent(ev),tooltip); }
        e.onmouseout  = function(ev) { return tooltip.onContextMouseOut .call(this,YAHOO.util.Event.getEvent(ev),tooltip); }
300
        e.title = e.getAttribute("tooltip");
K
kohsuke 已提交
301
        e = null; // avoid memory leak
302
    }
K
kohsuke 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
};

Behaviour.register(hudsonRules);


// used by editableDescription.jelly to replace the description field with a form
function replaceDescription() {
    var d = document.getElementById("description");
    d.firstChild.nextSibling.innerHTML = "<div class='spinner-right'>loading...</div>";
    new Ajax.Request(
        "./descriptionForm",
        {
          method : 'get',
          onComplete : function(x) {
            d.innerHTML = x.responseText;
K
kohsuke 已提交
318
            Behaviour.applySubtree(d);
319
            d.getElementsByTagName("TEXTAREA")[0].focus();
K
kohsuke 已提交
320 321 322 323
          }
        }
    );
    return false;
K
kohsuke 已提交
324 325
}

326 327 328 329 330 331 332
function applyNameRef(s,e,id) {
    $(id).groupingNode = true;
    // s contains the node itself
    for(var x=s.nextSibling; x!=e; x=x.nextSibling)
        x.setAttribute("nameRef",id);
}

333 334
function initOptionalBlock(sid, eid, cid) {
    applyNameRef($(sid),$(eid),cid);
335
    updateOptionalBlock($(cid),false);
336
}
K
kohsuke 已提交
337 338

// used by optionalBlock.jelly to update the form status
339
//   @param c     checkbox element
340
function updateOptionalBlock(c,scroll) {
341 342 343 344 345 346
    // find the start TR
    var s = c;
    while(!s.hasClassName("optional-block-start"))
        s = s.parentNode;

    var tbl = s.parentNode;
K
kohsuke 已提交
347 348 349
    var i = false;
    var o = false;

350
    var checked = c.checked;
K
kohsuke 已提交
351
    var lastRow = null;
K
kohsuke 已提交
352 353 354 355

    for (var j = 0; tbl.rows[j]; j++) {
        var n = tbl.rows[j];

356
        if (i && n.hasClassName("optional-block-end"))
K
kohsuke 已提交
357 358 359
            o = true;

        if (i && !o) {
360
            if (checked) {
K
kohsuke 已提交
361
                n.style.display = "";
K
kohsuke 已提交
362
                lastRow = n;
363
            } else
K
kohsuke 已提交
364 365 366
                n.style.display = "none";
        }

367
        if (n==s) {
K
kohsuke 已提交
368 369 370 371 372
            if (n.getAttribute('hasHelp') == 'true')
                j++;
            i = true;
        }
    }
373

K
kohsuke 已提交
374 375 376 377 378 379 380
    if(checked && scroll) {
        var D = YAHOO.util.Dom;

        var r = D.getRegion(s);
        if(lastRow!=null)   r = r.union(D.getRegion(lastRow));
        scrollIntoView(r);
    }
K
kohsuke 已提交
381
}
K
kohsuke 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441


//
// Auto-scroll support for progressive log output.
//   See http://radio.javaranch.com/pascarello/2006/08/17/1155837038219.html
//
function AutoScroller(scrollContainer) {
    // get the height of the viewport.
    // See http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
    function getViewportHeight() {
        if (typeof( window.innerWidth ) == 'number') {
            //Non-IE
            return window.innerHeight;
        } else if (document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight )) {
            //IE 6+ in 'standards compliant mode'
            return document.documentElement.clientHeight;
        } else if (document.body && ( document.body.clientWidth || document.body.clientHeight )) {
            //IE 4 compatible
            return document.body.clientHeight;
        }
        return null;
    }

    return {
        bottomThreshold : 25,
        scrollContainer: scrollContainer,

        getCurrentHeight : function() {
            var scrollDiv = $(this.scrollContainer);

            if (scrollDiv.scrollHeight > 0)
                return scrollDiv.scrollHeight;
            else
                if (objDiv.offsetHeight > 0)
                    return scrollDiv.offsetHeight;

            return null; // huh?
        },

        // return true if we are in the "stick to bottom" mode
        isSticking : function() {
            var scrollDiv = $(this.scrollContainer);
            var currentHeight = this.getCurrentHeight();

            // when used with the BODY tag, the height needs to be the viewport height, instead of
            // the element height.
            //var height = ((scrollDiv.style.pixelHeight) ? scrollDiv.style.pixelHeight : scrollDiv.offsetHeight);
            var height = getViewportHeight();
            var diff = currentHeight - scrollDiv.scrollTop - height;
            // window.alert("currentHeight=" + currentHeight + ",scrollTop=" + scrollDiv.scrollTop + ",height=" + height);

            return diff < this.bottomThreshold;
        },

        scrollToBottom : function() {
            var scrollDiv = $(this.scrollContainer);
            scrollDiv.scrollTop = this.getCurrentHeight();
        }
    };
}
442

443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
// scroll the current window to display the given element or the region.
function scrollIntoView(e) {
    function calcDelta(ex1,ex2,vx1,vw) {
        var vx2=vx1+vw;
        var a;
        a = Math.min(vx1-ex1,vx2-ex2);
        if(a>0)     return -a;
        a = Math.min(ex1-vx1,ex2-vx2);
        if(a>0)     return a;
        return 0;
    }

    var D = YAHOO.util.Dom;

    var r;
    if(e.tagName!=null) r = D.getRegion(e);
    else                r = e;

    var dx = calcDelta(r.left,r.right, document.body.scrollLeft, D.getViewportWidth());
    var dy = calcDelta(r.top, r.bottom,document.body.scrollTop,  D.getViewportHeight());
    window.scrollBy(dx,dy);
}
465 466 467 468 469 470

// used in expandableTextbox.jelly to change a input field into a text area
function expandTextArea(button,id) {
    button.style.display="none";
    var field = document.getElementById(id);
    var value = field.value.replace(/ +/g,'\n');
K
kohsuke 已提交
471 472 473 474
    var n = field;
    while(n.tagName!="TABLE")
        n = n.parentNode;
    n.parentNode.innerHTML =
475 476
        "<textarea rows=8 class='setting-input' name='"+field.name+"'>"+value+"</textarea>";
}
477 478 479 480 481 482 483


// refresh a part of the HTML specified by the given ID,
// by using the contents fetched from the given URL.
function refreshPart(id,url) {
    window.setTimeout(function() {
        new Ajax.Request(url, {
484
            method: "post",
485
            onSuccess: function(rsp) {
486 487 488 489 490 491 492 493
                var hist = $(id);
                var p = hist.parentNode;
                var next = hist.nextSibling;
                p.removeChild(hist);

                var div = document.createElement('div');
                div.innerHTML = rsp.responseText;

494 495
                var node = div.firstChild;
                p.insertBefore(node, next);
K
kohsuke 已提交
496

497
                Behaviour.applySubtree(node);
K
kohsuke 已提交
498 499

                refreshPart(id,url);
500 501
            }
        });
K
kohsuke 已提交
502
    }, 5000);
K
kohsuke 已提交
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
}


/*
    Perform URL encode.
    Taken from http://www.cresc.co.jp/tech/java/URLencoding/JavaScript_URLEncoding.htm
*/
function encode(str){
    var s, u;
    var s0 = "";                // encoded str

    for (var i = 0; i < str.length; i++){   // scan the source
        s = str.charAt(i);
        u = str.charCodeAt(i);          // get unicode of the char

        if (s == " "){s0 += "+";}       // SP should be converted to "+"
        else {
            if ( u == 0x2a || u == 0x2d || u == 0x2e || u == 0x5f || ((u >= 0x30) && (u <= 0x39)) || ((u >= 0x41) && (u <= 0x5a)) || ((u >= 0x61) && (u <= 0x7a))){     // check for escape
                s0 = s0 + s;           // don't escape
            } else {                      // escape
                if ((u >= 0x0) && (u <= 0x7f)){     // single byte format
                    s = "0"+u.toString(16);
                    s0 += "%"+ s.substr(s.length-2);
                } else
                if (u > 0x1fffff){     // quaternary byte format (extended)
                    s0 += "%" + (0xF0 + ((u & 0x1c0000) >> 18)).toString(16);
                    s0 += "%" + (0x80 + ((u & 0x3f000) >> 12)).toString(16);
                    s0 += "%" + (0x80 + ((u & 0xfc0) >> 6)).toString(16);
                    s0 += "%" + (0x80 + (u & 0x3f)).toString(16);
                } else
                if (u > 0x7ff){        // triple byte format
                    s0 += "%" + (0xe0 + ((u & 0xf000) >> 12)).toString(16);
                    s0 += "%" + (0x80 + ((u & 0xfc0) >> 6)).toString(16);
                    s0 += "%" + (0x80 + (u & 0x3f)).toString(16);
                } else {                      // double byte format
                    s0 += "%" + (0xc0 + ((u & 0x7c0) >> 6)).toString(16);
                    s0 += "%" + (0x80 + (u & 0x3f)).toString(16);
                }
            }
        }
    }
    return s0;
545 546
}

K
kohsuke 已提交
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
// when there are multiple form elements of the same name,
// this method returns the input field of the given name that pairs up
// with the specified 'base' input element.
Form.findMatchingInput = function(base, name) {
    // find the FORM element that owns us
    var f = base;
    while (f.tagName != "FORM")
        f = f.parentNode;

    var bases = Form.getInputs(f, null, base.name);
    var targets = Form.getInputs(f, null, name);

    for (var i=0; i<bases.length; i++) {
        if (bases[i] == base)
            return targets[i];
    }

    return null;        // not found
}

567 568 569 570 571 572 573 574 575 576 577 578 579
// used witih <dropdownList> and <dropdownListBlock> to control visibility
function updateDropDownList(sel) {
    // alert('Yay! '+sel.value+' '+sel.selectedIndex);
    for (var i = 0; i < sel.forms.length; i++) {
        var show = sel.selectedIndex == i;
        var f = sel.forms[i];
        var td = f.start;
        while (true) {
            td.style.display = (show ? "" : "none");
            if (td == f.end) break;
            td = td.nextSibling;
        }
    }
580 581 582 583 584 585 586 587 588 589 590 591 592 593
}


// code for supporting repeatable.jelly
var repetableSupport = {
    // set by the inherited instance to the insertion point DIV
    insertionPoint: null,

    // HTML text of the repeated chunk
    blockHTML: null,

    // containing <div>.
    container: null,

594 595 596
    // block name for structured HTML
    name : null,

597 598 599 600 601 602 603 604
    // do the initialization
    init : function(container,master,insertionPoint) {
        this.container = $(container);
        this.container.tag = this;
        master = $(master);
        this.blockHTML = master.innerHTML;
        master.parentNode.removeChild(master);
        this.insertionPoint = $(insertionPoint);
605
        this.name = master.getAttribute("name");
606 607 608 609 610 611 612 613 614
        this.update();
    },

    // insert one more block at the insertion position
    expand : function() {
        // importNode isn't supported in IE.
        // nc = document.importNode(node,true);
        var nc = document.createElement("div");
        nc.className = "repeated-chunk";
615
        nc.setAttribute("name",name);
616 617 618 619 620 621 622 623 624 625 626 627 628 629
        nc.innerHTML = this.blockHTML;
        this.insertionPoint.parentNode.insertBefore(nc, this.insertionPoint);

        Behaviour.applySubtree(nc);
        this.update();
    },

    // update CSS classes associated with repeated items.
    update : function() {
        var children = [];
        for( var n=this.container.firstChild; n!=null; n=n.nextSibling )
            if(Element.hasClassName(n,"repeated-chunk"))
                children.push(n);

K
kohsuke 已提交
630 631 632
        if(children.length==0) {
            // noop
        } else
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
        if(children.length==1) {
            children[0].className = "repeated-chunk first last only";
        } else {
            children[0].className = "repeated-chunk first";
            for(var i=1; i<children.length-1; i++)
                children[i].className = "repeated-chunk middle";
            children[children.length-1].className = "repeated-chunk last";
        }
    },

    // these are static methods that don't rely on 'this'

    // called when 'delete' button is clicked
    onDelete : function(n) {
        while (!Element.hasClassName(n,"repeated-chunk"))
            n = n.parentNode;

        var p = n.parentNode;
        p.removeChild(n);
        p.tag.update();
    },

    // called when 'add' button is clicked
    onAdd : function(n) {
        while(n.tag==null)
            n = n.parentNode;
        n.tag.expand();
    }
661 662
};

K
kohsuke 已提交
663 664 665 666 667
// Used by radioBlock.jelly to wire up expandable radio block
function addRadioBlock(id) {
    // prototype object to be duplicated for each radio button group
    var radioBlockSupport = {
        buttons : null,
668

K
kohsuke 已提交
669 670 671 672
        updateButtons : function() {
            for( var i=0; i<this.buttons.length; i++ )
                this.buttons[i]();
        },
673

K
kohsuke 已提交
674
        // update one block based on the status of the given radio button
675
        updateSingleButton : function(radio, blockStart, blockEnd) {
K
kohsuke 已提交
676 677 678 679
            var tbl = blockStart.parentNode;
            var i = false;
            var o = false;
            var show = radio.checked;
680

681 682
            for (var j = 0; tbl.rows[j]; j++) {
                var n = tbl.rows[j];
683

684 685
                if (n == blockEnd)
                    o = true;
686

687 688 689 690 691 692
                if (i && !o) {
                    if (show)
                        n.style.display = "";
                    else
                        n.style.display = "none";
                }
693

694 695
                if (n == blockStart)
                    i = true;
K
kohsuke 已提交
696
            }
697
        }
K
kohsuke 已提交
698
    };
699

K
kohsuke 已提交
700 701 702
    // when one radio button is clicked, we need to update foldable block for
    // other radio buttons with the same name. To do this, group all the
    // radio buttons with the same name together and hang it under the form object
703 704 705 706 707 708 709 710 711 712 713 714
    var r = document.getElementById('Rb' + id);
    var f = r.form;
    var radios = f.radios;
    if (radios == null)
        f.radios = radios = {};

    var g = radios[r.name];
    if (g == null) {
        radios[r.name] = g = object(radioBlockSupport);
        g.buttons = [];
    }

715 716 717
    var s = document.getElementById("rb_s"+id);
    var e = document.getElementById("rb_e"+id);

718
    var u = function() {
719
        g.updateSingleButton(r,s,e);
720
    };
721
    applyNameRef(s,e,'Rb'+id);
722 723 724 725 726 727 728 729 730 731
    g.buttons.push(u);

    // apply the initial visibility
    u();

    // install event handlers to update visibility.
    // needs to use onclick and onchange for Safari compatibility
    r.onclick = r.onchange = function() { g.updateButtons(); };
}

732 733 734 735 736 737 738 739

function updateBuildHistory(nBuild) {
    $('buildHistory').headers = ["n",nBuild];

    function updateBuilds() {
        var bh = $('buildHistory');
        new Ajax.Request("./ajaxBuildHistoryUpdate", {
            requestHeaders: bh.headers,
740
            onSuccess: function(rsp) {
741 742 743 744 745 746 747 748 749
                var rows = bh.rows;

                //delete rows with transitive data
                while (rows.length > 2 && Element.hasClassName(rows[1], "transitive"))
                    Element.remove(rows[1]);

                // insert new rows
                var div = document.createElement('div');
                div.innerHTML = rsp.responseText;
K
kohsuke 已提交
750
                Behaviour.applySubtree(div);
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765

                var pivot = rows[0];
                var newRows = div.firstChild.rows;
                for (var i = newRows.length - 1; i >= 0; i--) {
                    pivot.parentNode.insertBefore(newRows[i], pivot.nextSibling);
                }

                // next update
                bh.headers = ["n",rsp.getResponseHeader("n")];
                window.setTimeout(updateBuilds, 5000);
            }
        });
    }
    window.setTimeout(updateBuilds, 5000);
}
766 767 768 769 770 771

// send async request to the given URL (which will send back serialized ListBoxModel object),
// then use the result to fill the list box.
function updateListBox(listBox,url) {
    new Ajax.Request(url, {
        method: "post",
772
        onSuccess: function(rsp) {
773 774 775 776 777 778 779 780 781 782 783
            var l = $(listBox);
            while(l.length>0)   l.options[0] = null;

            var opts = eval('('+rsp.responseText+')').values;
            for( var i=0; i<opts.length; i++ ) {
                l.options[i] = new Option(opts[i].name,opts[i].value);
                if(opts[i].selected)
                    l.selectedIndex = i;
            }
        }
    });
784 785
}

786 787 788 789 790
// get the cascaded computed style value. 'a' is the style name like 'backgroundColor'
function getStyle(e,a){
  if(document.defaultView && document.defaultView.getComputedStyle)
    return document.defaultView.getComputedStyle(e,null).getPropertyValue(a.replace(/([A-Z])/g, "-$1"));
  if(e.currentStyle)
K
kohsuke 已提交
791 792
    return e.currentStyle[a];
  return null;
793 794 795
};

// set up logic behind the search box
796 797 798 799 800
function createSearchBox(searchURL) {
    var ds = new YAHOO.widget.DS_XHR(searchURL+"suggest",["suggestions","name"]);
    ds.queryMatchCase = false;
    var ac = new YAHOO.widget.AutoComplete("search-box","search-box-completion",ds);
    ac.typeAhead = false;
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837

    var box   = $("search-box");
    var sizer = $("search-box-sizer");
    var comp  = $("search-box-completion");
    var minW  = $("search-box-minWidth");

    Behaviour.addLoadEvent(function(){
        // make sure all three components have the same font settings
        function copyFontStyle(s,d) {
            var ds = d.style;
            ds.fontFamily = getStyle(s,"fontFamily");
            ds.fontSize = getStyle(s,"fontSize");
            ds.fontStyle = getStyle(s,"fontStyle");
            ds.fontWeight = getStyle(s,"fontWeight");
        }

        copyFontStyle(box,sizer);
        copyFontStyle(box,minW);
    });

    // update positions and sizes of the components relevant to search
    function updatePos() {
        function max(a,b) { if(a>b) return a; else return b; }

        sizer.innerHTML = box.value;
        var w = max(sizer.offsetWidth,minW.offsetWidth);
        box.style.width =
        comp.style.width = 
        comp.firstChild.style.width = (w+60)+"px";

        var pos = YAHOO.util.Dom.getXY(box);
        pos[1] += YAHOO.util.Dom.get(box).offsetHeight + 2;
        YAHOO.util.Dom.setXY(comp, pos);
    }

    updatePos();
    box.onkeyup = updatePos;
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
}


//
// structured form submission handling
//   see http://hudson.gotdns.com/wiki/display/HUDSON/Structured+Form+Submission
function buildFormTree(form) {
    // I initially tried to use an associative array with DOM elemnets as keys
    // but that doesn't seem to work neither on IE nor Firefox.
    // so I switch back to adding a dynamic property on DOM.
    form.formDom = {}; // root object

    var doms = []; // DOMs that we added 'formDom' for.
    doms.push(form);

    function addProperty(parent,name,value) {
854 855 856 857
        // abc.def.ghi -> ghi
        var idx = name.lastIndexOf('.');
        if(idx>=0)  name = name.substring(idx+1);
        
858
        if(parent[name]!=null) {
859
            if(parent[name].push==null) // is this array?
860 861 862 863 864 865 866 867 868 869 870 871
                parent[name] = [ parent[name] ];
            parent[name].push(value);
        } else {
            parent[name] = value;
        }
    }

    // find the grouping parent node, which will have @name.
    // then return the corresponding object in the map
    function findParent(e) {
        while(e!=form) {
            e = e.parentNode;
872 873 874 875 876 877 878

            // this is used to create a group where no single containing parent node exists,
            // like <optionalBlock>
            var nameRef = e.getAttribute("nameRef");
            if(nameRef!=null)
                e = $(nameRef);
            
879 880
            var name = e.getAttribute("name");
            if(name!=null) {
881 882 883
                if(e.tagName=="INPUT" && !e.checked)
                    return {};  // field is not active

884 885 886 887 888 889 890 891 892 893 894 895 896 897
                var m = e.formDom;
                if(m==null) {
                    // this is a new grouping node
                    doms.push(e);
                    e.formDom = m = {};
                    addProperty(findParent(e), name, m);
                }
                return m;
            }
        }

        return form.formDom; // guaranteed non-null
    }

898 899
    var jsonElement = null;

900 901
    for( var i=0; i<form.elements.length; i++ ) {
        var e = form.elements[i];
902 903 904 905
        if(e.name=="json") {
            jsonElement = e;
            continue;
        }
906
        var p;
907 908 909
        var type = e.getAttribute("type");
        if(type==null)  type="";
        switch(type.toLowerCase()) {
910
        case "button":
911
        case "submit":
912 913 914
            break;
        case "checkbox":
            p = findParent(e);
915 916 917 918 919 920
            if(!e.groupingNode)
                addProperty(p, e.name, e.checked);
            else {
                if(e.checked)
                    addProperty(p, e.name, e.formDom = {});
            }
921 922 923
            break;
        case "radio":
            if(!e.checked)  break;
924 925 926 927 928 929
            if(e.groupingNode) {
                p = findParent(e);
                addProperty(p, e.name, e.formDom = { value: e.value });
                break;
            }

930 931 932 933 934 935 936 937
            // otherwise fall through
        default:
            p = findParent(e);
            addProperty(p, e.name, e.value);
            break;
        }
    }

938
    jsonElement.value = Object.toJSON(form.formDom);
939 940 941 942 943 944

    // clean up
    for( i=0; i<doms.length; i++ )
        doms[i].formDom = null;
    

K
kohsuke 已提交
945
    return jsonElement.value;
K
kohsuke 已提交
946 947 948 949
}

// this used to be in prototype.js but it must have been removed somewhere between 1.4.0 to 1.5.1
String.prototype.trim = function() {
K
kohsuke 已提交
950 951 952 953 954 955 956 957
    var temp = this;
    var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
    if (obj.test(temp))
        temp = temp.replace(obj, '$2');
    obj = /  /g;
    while (temp.match(obj))
        temp = temp.replace(obj, " ");
    return temp;
K
kohsuke 已提交
958
}