JS code style

hinted-selects
Vitaliy Filippov 2014-10-13 20:33:51 +04:00
parent cfd8911bdc
commit 00b9c3a608
12 changed files with 638 additions and 575 deletions

View File

@ -153,17 +153,16 @@ function DataFieldHandler()
} }
} }
function clearAttachmentFields() { function clearAttachmentFields()
{
var element; var element;
document.getElementById('data').value = ''; document.getElementById('data').value = '';
DataFieldHandler(); DataFieldHandler();
if ((element = document.getElementById('bigfile'))) if ((element = document.getElementById('bigfile')))
element.checked = ''; element.checked = '';
document.getElementById('description').value = ''; document.getElementById('description').value = '';
/* Fire onchange so that the disabled state of the content-type /* Fire onchange so that the disabled state of the content-type
* radio buttons are also reset * radio buttons are also reset */
*/
element = document.getElementById('ispatch'); element = document.getElementById('ispatch');
element.checked = ''; element.checked = '';
bz_fireEvent(element, 'change'); bz_fireEvent(element, 'change');
@ -173,12 +172,16 @@ function clearAttachmentFields() {
/* Functions used when viewing patches in Diff mode. */ /* Functions used when viewing patches in Diff mode. */
function collapse_all() { function collapse_all()
{
var elem = document.checkboxform.firstChild; var elem = document.checkboxform.firstChild;
while (elem != null) { while (elem != null)
if (elem.firstChild != null) { {
if (elem.firstChild != null)
{
var tbody = elem.firstChild.nextSibling; var tbody = elem.firstChild.nextSibling;
if (tbody.className == 'file') { if (tbody.className == 'file')
{
tbody.className = 'file_collapse'; tbody.className = 'file_collapse';
twisty = get_twisty_from_tbody(tbody); twisty = get_twisty_from_tbody(tbody);
twisty.firstChild.nodeValue = '(+)'; twisty.firstChild.nodeValue = '(+)';
@ -190,12 +193,16 @@ function collapse_all() {
return false; return false;
} }
function expand_all() { function expand_all()
{
var elem = document.checkboxform.firstChild; var elem = document.checkboxform.firstChild;
while (elem != null) { while (elem != null)
if (elem.firstChild != null) { {
if (elem.firstChild != null)
{
var tbody = elem.firstChild.nextSibling; var tbody = elem.firstChild.nextSibling;
if (tbody.className == 'file_collapse') { if (tbody.className == 'file_collapse')
{
tbody.className = 'file'; tbody.className = 'file';
twisty = get_twisty_from_tbody(tbody); twisty = get_twisty_from_tbody(tbody);
twisty.firstChild.nodeValue = '(-)'; twisty.firstChild.nodeValue = '(-)';
@ -209,53 +216,71 @@ function expand_all() {
var current_restore_elem; var current_restore_elem;
function restore_all() { function restore_all()
{
current_restore_elem = null; current_restore_elem = null;
incremental_restore(); incremental_restore();
} }
function incremental_restore() { function incremental_restore()
if (!document.checkboxform.restore_indicator.checked) { {
if (!document.checkboxform.restore_indicator.checked)
{
return; return;
} }
var next_restore_elem; var next_restore_elem;
if (current_restore_elem) { if (current_restore_elem)
{
next_restore_elem = current_restore_elem.nextSibling; next_restore_elem = current_restore_elem.nextSibling;
} else { }
else
{
next_restore_elem = document.checkboxform.firstChild; next_restore_elem = document.checkboxform.firstChild;
} }
while (next_restore_elem != null) { while (next_restore_elem != null)
{
current_restore_elem = next_restore_elem; current_restore_elem = next_restore_elem;
if (current_restore_elem.firstChild != null) { if (current_restore_elem.firstChild != null)
{
restore_elem(current_restore_elem.firstChild.nextSibling); restore_elem(current_restore_elem.firstChild.nextSibling);
} }
next_restore_elem = current_restore_elem.nextSibling; next_restore_elem = current_restore_elem.nextSibling;
} }
} }
function restore_elem(elem, alertme) { function restore_elem(elem, alertme)
if (elem.className == 'file_collapse') { {
if (elem.className == 'file_collapse')
{
twisty = get_twisty_from_tbody(elem); twisty = get_twisty_from_tbody(elem);
if (twisty.nextSibling.checked) { if (twisty.nextSibling.checked)
{
elem.className = 'file'; elem.className = 'file';
twisty.firstChild.nodeValue = '(-)'; twisty.firstChild.nodeValue = '(-)';
} }
} else if (elem.className == 'file') { }
else if (elem.className == 'file')
{
twisty = get_twisty_from_tbody(elem); twisty = get_twisty_from_tbody(elem);
if (!twisty.nextSibling.checked) { if (!twisty.nextSibling.checked)
{
elem.className = 'file_collapse'; elem.className = 'file_collapse';
twisty.firstChild.nodeValue = '(+)'; twisty.firstChild.nodeValue = '(+)';
} }
} }
} }
function twisty_click(twisty) { function twisty_click(twisty)
{
tbody = get_tbody_from_twisty(twisty); tbody = get_tbody_from_twisty(twisty);
if (tbody.className == 'file') { if (tbody.className == 'file')
{
tbody.className = 'file_collapse'; tbody.className = 'file_collapse';
twisty.firstChild.nodeValue = '(+)'; twisty.firstChild.nodeValue = '(+)';
twisty.nextSibling.checked = false; twisty.nextSibling.checked = false;
} else { }
else
{
tbody.className = 'file'; tbody.className = 'file';
twisty.firstChild.nodeValue = '(-)'; twisty.firstChild.nodeValue = '(-)';
twisty.nextSibling.checked = true; twisty.nextSibling.checked = true;
@ -263,10 +288,12 @@ function twisty_click(twisty) {
return false; return false;
} }
function get_tbody_from_twisty(twisty) { function get_tbody_from_twisty(twisty)
{
return twisty.parentNode.parentNode.parentNode.nextSibling; return twisty.parentNode.parentNode.parentNode.nextSibling;
} }
function get_twisty_from_tbody(tbody) { function get_twisty_from_tbody(tbody)
{
return tbody.previousSibling.firstChild.nextSibling.firstChild.firstChild; return tbody.previousSibling.firstChild.nextSibling.firstChild.firstChild;
} }
@ -291,12 +318,11 @@ function redoEditAsComment(patchviewerinstalled)
function viewDiff(attachment_id, patchviewerinstalled) function viewDiff(attachment_id, patchviewerinstalled)
{ {
switchToMode('diff', patchviewerinstalled); switchToMode('diff', patchviewerinstalled);
// If we have not viewed as diff before, set the view diff frame URL // If we have not viewed as diff before, set the view diff frame URL
if (!has_viewed_as_diff) { if (!has_viewed_as_diff)
{
var viewDiffFrame = document.getElementById('viewDiffFrame'); var viewDiffFrame = document.getElementById('viewDiffFrame');
viewDiffFrame.src = viewDiffFrame.src = 'attachment.cgi?id=' + attachment_id + '&action=diff&headers=0';
'attachment.cgi?id=' + attachment_id + '&action=diff&headers=0';
has_viewed_as_diff = 1; has_viewed_as_diff = 1;
} }
} }
@ -315,38 +341,46 @@ function switchToMode(mode, patchviewerinstalled)
} }
// Switch out of current mode // Switch out of current mode
if (current_mode == 'edit') { if (current_mode == 'edit')
{
hideElementById('editFrame'); hideElementById('editFrame');
hideElementById('undoEditButton'); hideElementById('undoEditButton');
} else if (current_mode == 'raw') { }
else if (current_mode == 'raw')
{
hideElementById('viewFrame'); hideElementById('viewFrame');
if (patchviewerinstalled) if (patchviewerinstalled)
hideElementById('viewDiffButton'); hideElementById('viewDiffButton');
hideElementById(has_edited ? 'redoEditButton' : 'editButton'); hideElementById(has_edited ? 'redoEditButton' : 'editButton');
hideElementById('smallCommentFrame'); hideElementById('smallCommentFrame');
} else if (current_mode == 'diff') { }
else if (current_mode == 'diff')
{
if (patchviewerinstalled) if (patchviewerinstalled)
hideElementById('viewDiffFrame'); hideElementById('viewDiffFrame');
hideElementById('viewRawButton'); hideElementById('viewRawButton');
hideElementById(has_edited ? 'redoEditButton' : 'editButton'); hideElementById(has_edited ? 'redoEditButton' : 'editButton');
hideElementById('smallCommentFrame'); hideElementById('smallCommentFrame');
} }
// Switch into new mode // Switch into new mode
if (mode == 'edit') { if (mode == 'edit')
{
showElementById('editFrame'); showElementById('editFrame');
showElementById('undoEditButton'); showElementById('undoEditButton');
} else if (mode == 'raw') { }
else if (mode == 'raw')
{
showElementById('viewFrame'); showElementById('viewFrame');
if (patchviewerinstalled) if (patchviewerinstalled)
showElementById('viewDiffButton'); showElementById('viewDiffButton');
showElementById(has_edited ? 'redoEditButton' : 'editButton'); showElementById(has_edited ? 'redoEditButton' : 'editButton');
showElementById('smallCommentFrame'); showElementById('smallCommentFrame');
} else if (mode == 'diff') { }
if (patchviewerinstalled) else if (mode == 'diff')
{
if (patchviewerinstalled)
showElementById('viewDiffFrame'); showElementById('viewDiffFrame');
showElementById('viewRawButton'); showElementById('viewRawButton');
showElementById(has_edited ? 'redoEditButton' : 'editButton'); showElementById(has_edited ? 'redoEditButton' : 'editButton');
showElementById('smallCommentFrame'); showElementById('smallCommentFrame');
@ -359,16 +393,17 @@ function switchToMode(mode, patchviewerinstalled)
function hideElementById(id) function hideElementById(id)
{ {
var elm = document.getElementById(id); var elm = document.getElementById(id);
if (elm) { if (elm)
elm.style.display = 'none'; elm.style.display = 'none';
}
} }
function showElementById(id, val) function showElementById(id, val)
{ {
var elm = document.getElementById(id); var elm = document.getElementById(id);
if (elm) { if (elm)
if (!val) val = 'inline'; {
if (!val)
val = 'inline';
elm.style.display = val; elm.style.display = val;
} }
} }
@ -377,14 +412,13 @@ function normalizeComments()
{ {
// Remove the unused comment field from the document so its contents // Remove the unused comment field from the document so its contents
// do not get transmitted back to the server. // do not get transmitted back to the server.
var small = document.getElementById('smallCommentFrame'); var small = document.getElementById('smallCommentFrame');
var big = document.getElementById('editFrame'); var big = document.getElementById('editFrame');
if ( (small) && (small.style.display == 'none') ) if (small && small.style.display == 'none')
{ {
small.parentNode.removeChild(small); small.parentNode.removeChild(small);
} }
if ( (big) && (big.style.display == 'none') ) if (big && big.style.display == 'none')
{ {
big.parentNode.removeChild(big); big.parentNode.removeChild(big);
} }

View File

@ -4,64 +4,64 @@
function onChangeType() function onChangeType()
{ {
var type_field = document.getElementById('type'); var type_field = document.getElementById('type');
var value_field = document.getElementById('value_field_id'); var value_field = document.getElementById('value_field_id');
if (type_field.value == constants.FIELD_TYPE_SINGLE_SELECT || if (type_field.value == constants.FIELD_TYPE_SINGLE_SELECT ||
type_field.value == constants.FIELD_TYPE_MULTI_SELECT) type_field.value == constants.FIELD_TYPE_MULTI_SELECT)
{
value_field.disabled = false;
document.getElementById('value_field_row').style.display = '';
if (document.getElementById('action').value == 'new')
{ {
document.getElementById('default_value_row').style.display = 'none'; value_field.disabled = false;
document.getElementById('value_field_row').style.display = '';
if (document.getElementById('action').value == 'new')
{
document.getElementById('default_value_row').style.display = 'none';
}
} }
} else
else {
{ value_field.disabled = true;
value_field.disabled = true; document.getElementById('value_field_row').style.display = 'none';
document.getElementById('value_field_row').style.display = 'none'; document.getElementById('default_value_row').style.display = '';
document.getElementById('default_value_row').style.display = ''; }
} var rev_value_field = document.getElementById('bug_id_rev_value_field_id');
var rev_value_field = document.getElementById('bug_id_rev_value_field_id'); if (type_field.value == constants.FIELD_TYPE_BUG_ID_REV)
if (type_field.value == constants.FIELD_TYPE_BUG_ID_REV) {
{ rev_value_field.name = 'value_field_id';
rev_value_field.name = 'value_field_id'; value_field.name = '';
value_field.name = ''; document.getElementById('bug_id_rev_row').style.display = '';
document.getElementById('bug_id_rev_row').style.display = ''; }
} else
else {
{ rev_value_field.name = '';
rev_value_field.name = ''; value_field.name = 'value_field_id';
value_field.name = 'value_field_id'; document.getElementById('bug_id_rev_row').style.display = 'none';
document.getElementById('bug_id_rev_row').style.display = 'none'; }
} document.getElementById('add_to_deps_row').style.display
document.getElementById('add_to_deps_row').style.display = type_field.value == constants.FIELD_TYPE_BUG_ID ? '' : 'none';
= type_field.value == constants.FIELD_TYPE_BUG_ID ? '' : 'none'; var u = document.getElementById('nullable');
var u = document.getElementById('nullable'); u.disabled = type_field.value != constants.FIELD_TYPE_SINGLE_SELECT;
u.disabled = type_field.value != constants.FIELD_TYPE_SINGLE_SELECT; if (u.disabled)
if (u.disabled) u.checked = false;
u.checked = false; u = type_field.value == constants.FIELD_TYPE_EXTURL;
u = type_field.value == constants.FIELD_TYPE_EXTURL; document.getElementById('url_row').style.display = u ? '' : 'none';
document.getElementById('url_row').style.display = u ? '' : 'none'; onChangeNullable();
onChangeNullable();
} }
function onChangeNullable() function onChangeNullable()
{ {
var u = document.getElementById('nullable'); var u = document.getElementById('nullable');
var n = document.getElementById('allow_null_in_row'); var n = document.getElementById('allow_null_in_row');
var c = document.getElementById('null_field_id_row'); var c = document.getElementById('null_field_id_row');
c.style.display = u.checked ? '' : 'none'; c.style.display = u.checked ? '' : 'none';
if (n) if (n)
n.style.display = c.style.display; n.style.display = c.style.display;
} }
function onChangeCloned() function onChangeCloned()
{ {
var u = document.getElementById('clone_bug'); var u = document.getElementById('clone_bug');
var n = document.getElementById('allow_clone_in_row'); var n = document.getElementById('allow_clone_in_row');
var c = document.getElementById('clone_field_id_row'); var c = document.getElementById('clone_field_id_row');
c.style.display = u.checked ? '' : 'none'; c.style.display = u.checked ? '' : 'none';
if (n) if (n)
n.style.display = c.style.display; n.style.display = c.style.display;
} }

View File

@ -20,32 +20,36 @@
* André Batosti <batosti@async.com.br> * André Batosti <batosti@async.com.br>
*/ */
if (!Node) { if (!Node)
{
// MSIE doesn't define Node, so provide a compatibility object // MSIE doesn't define Node, so provide a compatibility object
var Node = { TEXT_NODE: 3 } var Node = { TEXT_NODE: 3 }
} }
if (!highlighted) { if (!highlighted)
{
var highlighted = 0; var highlighted = 0;
var highlightedclass = ""; var highlightedclass = "";
var highlightedover = 0; var highlightedover = 0;
} }
function doToggle(node, event) { function doToggle(node, event)
{
var deep = event.altKey || event.ctrlKey; var deep = event.altKey || event.ctrlKey;
if (node.nodeType == Node.TEXT_NODE) if (node.nodeType == Node.TEXT_NODE)
node = node.parentNode; node = node.parentNode;
var toggle = node.nextSibling; var toggle = node.nextSibling;
while (toggle && toggle.tagName != "UL") while (toggle && toggle.tagName != "UL")
toggle = toggle.nextSibling; toggle = toggle.nextSibling;
if (toggle)
if (toggle) { {
if (deep) { if (deep)
{
var direction = toggleDisplay(toggle, node); var direction = toggleDisplay(toggle, node);
changeChildren(toggle, direction); changeChildren(toggle, direction);
} else { }
else
{
toggleDisplay(toggle, node); toggleDisplay(toggle, node);
} }
} }
@ -56,9 +60,11 @@ function doToggle(node, event) {
return false; return false;
} }
function changeChildren(node, direction) { function changeChildren(node, direction)
{
var item = node.firstChild; var item = node.firstChild;
while (item) { while (item)
{
/* find the LI inside the UL I got */ /* find the LI inside the UL I got */
while (item && item.tagName != "LI") while (item && item.tagName != "LI")
item = item.nextSibling; item = item.nextSibling;
@ -69,38 +75,40 @@ function changeChildren(node, direction) {
var child = item.firstChild; var child = item.firstChild;
while (child && child.tagName != "A") while (child && child.tagName != "A")
child = child.nextSibling; child = child.nextSibling;
if (!child) { if (!child)
return return
}
var bullet = child; var bullet = child;
/* and check if it has its own sublist */ /* and check if it has its own sublist */
var sublist = item.firstChild; var sublist = item.firstChild;
while (sublist && sublist.tagName != "UL") while (sublist && sublist.tagName != "UL")
sublist = sublist.nextSibling; sublist = sublist.nextSibling;
if (sublist) { if (sublist)
if (direction && isClosed(sublist)) { {
if (direction && isClosed(sublist))
openNode(sublist, bullet); openNode(sublist, bullet);
} else if (!direction && !isClosed(sublist)) { else if (!direction && !isClosed(sublist))
closeNode(sublist, bullet); closeNode(sublist, bullet);
}
changeChildren(sublist, direction) changeChildren(sublist, direction)
} }
item = item.nextSibling; item = item.nextSibling;
} }
} }
function openNode(node, bullet) { function openNode(node, bullet)
{
node.style.display = "block"; node.style.display = "block";
bullet.className = "b b_open"; bullet.className = "b b_open";
} }
function closeNode(node, bullet) { function closeNode(node, bullet)
{
node.style.display = "none"; node.style.display = "none";
bullet.className = "b b_closed"; bullet.className = "b b_closed";
} }
function isClosed(node) { function isClosed(node)
{
/* XXX we should in fact check our *computed* style, not the display /* XXX we should in fact check our *computed* style, not the display
* attribute of the current node, which may be inherited and not * attribute of the current node, which may be inherited and not
* set. However, this really only matters when changing the default * set. However, this really only matters when changing the default
@ -108,25 +116,27 @@ function isClosed(node) {
return node.style.display == "none"; return node.style.display == "none";
} }
function toggleDisplay(node, bullet) { function toggleDisplay(node, bullet)
if (isClosed(node)) { {
if (isClosed(node))
{
openNode(node, bullet); openNode(node, bullet);
return true; return true;
} }
closeNode(node, bullet); closeNode(node, bullet);
return false; return false;
} }
function duplicated(element) { function duplicated(element)
var allsumm= document.getElementsByTagName("span"); {
if (highlighted) { var allsumm = document.getElementsByTagName("span");
for (i = 0;i < allsumm.length; i++) { if (highlighted)
if (allsumm.item(i).id == highlighted) { {
for (var i = 0; i < allsumm.length; i++)
if (allsumm.item(i).id == highlighted)
allsumm.item(i).className = highlightedclass; allsumm.item(i).className = highlightedclass;
} if (highlighted == element)
} {
if (highlighted == element) {
highlighted = 0; highlighted = 0;
return; return;
} }
@ -134,24 +144,25 @@ function duplicated(element) {
highlighted = element; highlighted = element;
var elem = document.getElementById(element); var elem = document.getElementById(element);
highlightedclass = elem.className; highlightedclass = elem.className;
for (var i = 0;i < allsumm.length; i++) { for (var i = 0;i < allsumm.length; i++)
if (allsumm.item(i).id == element) { if (allsumm.item(i).id == element)
allsumm.item(i).className = "summ_h"; allsumm.item(i).className = "summ_h";
}
}
} }
function duplicatedover(element) { function duplicatedover(element)
if (!highlighted) { {
if (!highlighted)
{
highlightedover = 1; highlightedover = 1;
duplicated(element); duplicated(element);
} }
} }
function duplicatedout(element) { function duplicatedout(element)
if (highlighted == element && highlightedover) { {
if (highlighted == element && highlightedover)
{
highlightedover = 0; highlightedover = 0;
duplicated(element); duplicated(element);
} }
} }

View File

@ -78,25 +78,25 @@ function showEditableField(e, ContainerInputArray)
* var ContainerInputArray[3]: the original value from the page loading. * var ContainerInputArray[3]: the original value from the page loading.
* *
*/ */
function checkForChangedFieldValues(e, ContainerInputArray ) { function checkForChangedFieldValues(e, ContainerInputArray)
{
var el = document.getElementById(ContainerInputArray[2]); var el = document.getElementById(ContainerInputArray[2]);
var unhide = false; var unhide = false;
if ( el ) { if (el)
if ( el.value != ContainerInputArray[3] || {
( el.value == "" && el.id != "alias") ) { if (el.value != ContainerInputArray[3] ||
el.value == "" && el.id != "alias")
{
unhide = true; unhide = true;
} }
else { else
var set_default = document.getElementById("set_default_" + {
ContainerInputArray[2]); var set_default = document.getElementById("set_default_" + ContainerInputArray[2]);
if ( set_default ) { if (set_default && set_default.checked)
if(set_default.checked){ unhide = true;
unhide = true;
}
}
} }
} }
if(unhide) if (unhide)
{ {
addClass(ContainerInputArray[0], 'bz_default_hidden'); addClass(ContainerInputArray[0], 'bz_default_hidden');
removeClass(ContainerInputArray[1], 'bz_default_hidden'); removeClass(ContainerInputArray[1], 'bz_default_hidden');
@ -243,7 +243,8 @@ function setResolutionToDuplicate(duplicate_or_move_bug_status)
bz_fireEvent(status, 'change'); bz_fireEvent(status, 'change');
resolution.value = "DUPLICATE"; resolution.value = "DUPLICATE";
bz_fireEvent(resolution, 'change'); bz_fireEvent(resolution, 'change');
if (e.preventDefault) e.preventDefault(); if (e.preventDefault)
e.preventDefault();
return false; return false;
} }

View File

@ -17,7 +17,7 @@
var mini_login_constants; var mini_login_constants;
function show_mini_login_form( suffix ) function show_mini_login_form(suffix)
{ {
var login_link = document.getElementById('login_link' + suffix); var login_link = document.getElementById('login_link' + suffix);
var login_form = document.getElementById('mini_login' + suffix); var login_form = document.getElementById('mini_login' + suffix);
@ -29,7 +29,7 @@ function show_mini_login_form( suffix )
return false; return false;
} }
function hide_mini_login_form( suffix ) function hide_mini_login_form(suffix)
{ {
var login_link = document.getElementById('login_link' + suffix); var login_link = document.getElementById('login_link' + suffix);
var login_form = document.getElementById('mini_login' + suffix); var login_form = document.getElementById('mini_login' + suffix);
@ -40,7 +40,7 @@ function hide_mini_login_form( suffix )
return false; return false;
} }
function show_forgot_form( suffix ) function show_forgot_form(suffix)
{ {
var forgot_link = document.getElementById('forgot_link' + suffix); var forgot_link = document.getElementById('forgot_link' + suffix);
var forgot_form = document.getElementById('forgot_form' + suffix); var forgot_form = document.getElementById('forgot_form' + suffix);
@ -51,7 +51,7 @@ function show_forgot_form( suffix )
return false; return false;
} }
function hide_forgot_form( suffix ) function hide_forgot_form(suffix)
{ {
var forgot_link = document.getElementById('forgot_link' + suffix); var forgot_link = document.getElementById('forgot_link' + suffix);
var forgot_form = document.getElementById('forgot_form' + suffix); var forgot_form = document.getElementById('forgot_form' + suffix);
@ -62,7 +62,7 @@ function hide_forgot_form( suffix )
return false; return false;
} }
function init_mini_login_form( suffix ) function init_mini_login_form(suffix)
{ {
var mini_login = document.getElementById('Bugzilla_login' + suffix ); var mini_login = document.getElementById('Bugzilla_login' + suffix );
var mini_password = document.getElementById('Bugzilla_password' + suffix ); var mini_password = document.getElementById('Bugzilla_password' + suffix );

View File

@ -41,8 +41,7 @@ function generateHelp()
// Create help controls (a div to hold help text and an iframe // Create help controls (a div to hold help text and an iframe
// to mask any and all controls under the popup) // to mask any and all controls under the popup)
document.write('<div id="helpDiv" style="display: none;"><\/div>'); document.write('<div id="helpDiv" style="display: none;"><\/div>');
document.write('<iframe id="helpIframe" src="about:blank"'); document.write('<iframe id="helpIframe" src="about:blank" frameborder="0" scrolling="no"><\/iframe>');
document.write(' frameborder="0" scrolling="no"><\/iframe>');
return true; return true;
} }
@ -61,13 +60,10 @@ function enableHelp()
// MS decided to add fieldsets to the elements array; and // MS decided to add fieldsets to the elements array; and
// Mozilla decided to copy this brokenness. Grr. // Mozilla decided to copy this brokenness. Grr.
for (var i = 0; i < document.forms.length; i++) { for (var i = 0; i < document.forms.length; i++)
for (var j = 0; j < document.forms[i].elements.length; j++) { for (var j = 0; j < document.forms[i].elements.length; j++)
if (document.forms[i].elements[j].tagName != 'FIELDSET') { if (document.forms[i].elements[j].tagName != 'FIELDSET')
document.forms[i].elements[j].onmouseover = showHelp; document.forms[i].elements[j].onmouseover = showHelp;
}
}
}
document.body.onclick = hideHelp; document.body.onclick = hideHelp;
return true; return true;
@ -76,7 +72,8 @@ function enableHelp()
/** /**
* Show the help popup for a form element. * Show the help popup for a form element.
*/ */
function showHelp() { function showHelp()
{
if (!g_helpIframe || !g_helpDiv || !g_helpTexts[this.name]) if (!g_helpIframe || !g_helpDiv || !g_helpTexts[this.name])
return; return;
@ -101,9 +98,9 @@ function showHelp() {
/** /**
* Hide the help popup. * Hide the help popup.
*/ */
function hideHelp() { function hideHelp()
{
if (!g_helpIframe || !g_helpDiv) if (!g_helpIframe || !g_helpDiv)
return; return;
g_helpIframe.style.display = g_helpDiv.style.display = 'none'; g_helpIframe.style.display = g_helpDiv.style.display = 'none';
} }

View File

@ -17,7 +17,8 @@
* Contributor(s): Marc Schumann <wurblzap@gmail.com> * Contributor(s): Marc Schumann <wurblzap@gmail.com>
*/ */
function sortedList_moveItem(paramName, direction, separator) { function sortedList_moveItem(paramName, direction, separator)
{
var select = document.getElementById('select_' + paramName); var select = document.getElementById('select_' + paramName);
var inputField = document.getElementById('input_' + paramName); var inputField = document.getElementById('input_' + paramName);
var currentIndex = select.selectedIndex; var currentIndex = select.selectedIndex;
@ -26,11 +27,14 @@ function sortedList_moveItem(paramName, direction, separator) {
var optionNewIndex; var optionNewIndex;
/* Return if no selection */ /* Return if no selection */
if (currentIndex < 0) return; if (currentIndex < 0)
return;
/* Return if trying to move upward out of list */ /* Return if trying to move upward out of list */
if (newIndex < 0) return; if (newIndex < 0)
return;
/* Return if trying to move downward out of list */ /* Return if trying to move downward out of list */
if (newIndex >= select.length) return; if (newIndex >= select.length)
return;
/* Move selection */ /* Move selection */
optionNewIndex = select.options[newIndex]; optionNewIndex = select.options[newIndex];
@ -44,17 +48,16 @@ function sortedList_moveItem(paramName, direction, separator) {
populateInputField(select, inputField, separator); populateInputField(select, inputField, separator);
} }
function populateInputField(select, inputField, separator) { function populateInputField(select, inputField, separator)
{
var i; var i;
var stringRepresentation = ''; var stringRepresentation = '';
for (i = 0; i < select.length; i++)
for (i = 0; i < select.length; i++) { {
if (select.options[i].value == separator) { if (select.options[i].value == separator)
break; break;
} if (stringRepresentation != '')
if (stringRepresentation != '') {
stringRepresentation += ','; stringRepresentation += ',';
}
stringRepresentation += select.options[i].value; stringRepresentation += select.options[i].value;
} }
inputField.value = stringRepresentation; inputField.value = stringRepresentation;

View File

@ -50,7 +50,8 @@
* @global last_sel Array that contains last list of products so we know what * @global last_sel Array that contains last list of products so we know what
* has changed, and optimize for additions. * has changed, and optimize for additions.
*/ */
function selectProduct(product, component, version, milestone, anyval) { function selectProduct(product, component, version, milestone, anyval)
{
// This is to avoid handling events that occur before the form // This is to avoid handling events that occur before the form
// itself is ready, which could happen in buggy browsers. // itself is ready, which could happen in buggy browsers.
if (!product) if (!product)
@ -63,7 +64,8 @@ function selectProduct(product, component, version, milestone, anyval) {
// If this is the first load and nothing is selected, no need to // If this is the first load and nothing is selected, no need to
// merge and sort all lists; they are created sorted. // merge and sort all lists; they are created sorted.
if ((first_load) && (product.selectedIndex == -1)) { if (first_load && product.selectedIndex == -1)
{
first_load = false; first_load = false;
return; return;
} }
@ -87,27 +89,27 @@ function selectProduct(product, component, version, milestone, anyval) {
// If nothing is selected, or the special "Any" option is selected // If nothing is selected, or the special "Any" option is selected
// which represents all products, then pick all products so we show // which represents all products, then pick all products so we show
// all components. // all components.
var findall = (product.selectedIndex == -1 var findall = (product.selectedIndex == -1 || (anyval != null && product.options[0].selected));
|| (anyval != null && product.options[0].selected));
if (useclassification) { if (useclassification)
{
// Update index based on the complete product array. // Update index based on the complete product array.
sel = get_selection(product, findall, true, anyval); sel = get_selection(product, findall, true, anyval);
for (var i=0; i<sel.length; i++) for (var i = 0; i < sel.length; i++)
sel[i] = prods[sel[i]]; sel[i] = prods[sel[i]];
} }
else { else
sel = get_selection(product, findall, false, anyval); sel = get_selection(product, findall, false, anyval);
} if (!findall)
if (!findall) { {
// Save sel for the next invocation of selectProduct(). // Save sel for the next invocation of selectProduct().
var tmp = sel; var tmp = sel;
// This is an optimization: if we have just added products to an // This is an optimization: if we have just added products to an
// existing selection, no need to clear the form controls and add // existing selection, no need to clear the form controls and add
// everybody again; just merge the new ones with the existing // everybody again; just merge the new ones with the existing
// options. // options.
if ((last_sel.length > 0) && (last_sel.length < sel.length)) { if (last_sel.length > 0 && last_sel.length < sel.length)
{
sel = fake_diff_array(sel, last_sel); sel = fake_diff_array(sel, last_sel);
merging = true; merging = true;
} }
@ -115,19 +117,22 @@ function selectProduct(product, component, version, milestone, anyval) {
} }
// Do the actual fill/update. // Do the actual fill/update.
if (component) { if (component)
{
var saved_cpts = get_selection(component, false, true, null); var saved_cpts = get_selection(component, false, true, null);
updateSelect(cpts, sel, component, merging, anyval); updateSelect(cpts, sel, component, merging, anyval);
restoreSelection(component, saved_cpts); restoreSelection(component, saved_cpts);
} }
if (version) { if (version)
{
var saved_vers = get_selection(version, false, true, null); var saved_vers = get_selection(version, false, true, null);
updateSelect(vers, sel, version, merging, anyval); updateSelect(vers, sel, version, merging, anyval);
restoreSelection(version, saved_vers); restoreSelection(version, saved_vers);
} }
if (milestone) { if (milestone)
{
var saved_tms = get_selection(milestone, false, true, null); var saved_tms = get_selection(milestone, false, true, null);
updateSelect(tms, sel, milestone, merging, anyval); updateSelect(tms, sel, milestone, merging, anyval);
restoreSelection(milestone, saved_tms); restoreSelection(milestone, saved_tms);
@ -160,16 +165,19 @@ function selectProduct(product, component, version, milestone, anyval) {
* *
* This would clear compsel and add 'ComponentC' and 'ComponentD' to it. * This would clear compsel and add 'ComponentC' and 'ComponentD' to it.
*/ */
function updateSelect(array, sel, target, merging, anyval) { function updateSelect(array, sel, target, merging, anyval)
{
var i, item; var i, item;
// If we have no versions/components/milestones. // If we have no versions/components/milestones.
if (array.length < 1) { if (array.length < 1)
{
target.options.length = 0; target.options.length = 0;
return false; return false;
} }
if (merging) { if (merging)
{
// Array merging/sorting in the case of multiple selections // Array merging/sorting in the case of multiple selections
// merge in the current options with the first selection. // merge in the current options with the first selection.
item = merge_arrays(array[sel[0]], target.options, 1); item = merge_arrays(array[sel[0]], target.options, 1);
@ -178,7 +186,8 @@ function updateSelect(array, sel, target, merging, anyval) {
for (i = 1 ; i < sel.length ; i++) for (i = 1 ; i < sel.length ; i++)
item = merge_arrays(array[sel[i]], item, 0); item = merge_arrays(array[sel[i]], item, 0);
} }
else if (sel.length > 1) { else if (sel.length > 1)
{
// Here we micro-optimize for two arrays to avoid merging with a // Here we micro-optimize for two arrays to avoid merging with a
// null array. // null array.
item = merge_arrays(array[sel[0]],array[sel[1]], 0); item = merge_arrays(array[sel[0]],array[sel[1]], 0);
@ -187,7 +196,8 @@ function updateSelect(array, sel, target, merging, anyval) {
for (i = 2; i < sel.length; i++) for (i = 2; i < sel.length; i++)
item = merge_arrays(item, array[sel[i]], 0); item = merge_arrays(item, array[sel[i]], 0);
} }
else { else
{
// Single item in selection, just get me the list. // Single item in selection, just get me the list.
item = array[sel[0]]; item = array[sel[0]];
} }
@ -212,7 +222,8 @@ function updateSelect(array, sel, target, merging, anyval) {
* @param control Select element of which selected options are to be restored. * @param control Select element of which selected options are to be restored.
* @param selnames Array of option names to select. * @param selnames Array of option names to select.
*/ */
function restoreSelection(control, selnames) { function restoreSelection(control, selnames)
{
// Right. This sucks but I see no way to avoid going through the // Right. This sucks but I see no way to avoid going through the
// list and comparing to the contents of the control. // list and comparing to the contents of the control.
for (var j = 0; j < selnames.length; j++) for (var j = 0; j < selnames.length; j++)
@ -229,19 +240,19 @@ function restoreSelection(control, selnames) {
* @param b Second array to compare. * @param b Second array to compare.
* @return Array of elements in a but not in b. * @return Array of elements in a but not in b.
*/ */
function fake_diff_array(a, b) { function fake_diff_array(a, b)
{
var newsel = new Array(); var newsel = new Array();
var found = false; var found = false;
// Do a boring array diff to see who's new. // Do a boring array diff to see who's new.
for (var ia in a) { for (var ia in a)
{
for (var ib in b) for (var ib in b)
if (a[ia] == b[ib]) if (a[ia] == b[ib])
found = true; found = true;
if (!found) if (!found)
newsel[newsel.length] = a[ia]; newsel[newsel.length] = a[ia];
found = false; found = false;
} }
@ -259,7 +270,8 @@ function fake_diff_array(a, b) {
* an array. * an array.
* @return Merged and sorted array. * @return Merged and sorted array.
*/ */
function merge_arrays(a, b, b_is_select) { function merge_arrays(a, b, b_is_select)
{
var pos_a = 0; var pos_a = 0;
var pos_b = 0; var pos_b = 0;
var ret = new Array(); var ret = new Array();
@ -268,25 +280,29 @@ function merge_arrays(a, b, b_is_select) {
// Iterate through both arrays and add the larger item to the return // Iterate through both arrays and add the larger item to the return
// list. Remove dupes, too. Use toLowerCase to provide // list. Remove dupes, too. Use toLowerCase to provide
// case-insensitivity. // case-insensitivity.
while ((pos_a < a.length) && (pos_b < b.length)) { while (pos_a < a.length && pos_b < b.length)
{
aitem = a[pos_a]; aitem = a[pos_a];
if (b_is_select) if (b_is_select)
bitem = b[pos_b].value; bitem = b[pos_b].value;
else else
bitem = b[pos_b]; bitem = b[pos_b];
// Smaller item in list a. // Smaller item in list a.
if (aitem.toLowerCase() < bitem.toLowerCase()) { if (aitem.toLowerCase() < bitem.toLowerCase())
{
ret[ret.length] = aitem; ret[ret.length] = aitem;
pos_a++; pos_a++;
} }
else { else
{
// Smaller item in list b. // Smaller item in list b.
if (aitem.toLowerCase() > bitem.toLowerCase()) { if (aitem.toLowerCase() > bitem.toLowerCase())
{
ret[ret.length] = bitem; ret[ret.length] = bitem;
pos_b++; pos_b++;
} }
else { else
{
// List contents are equal, include both counters. // List contents are equal, include both counters.
ret[ret.length] = aitem; ret[ret.length] = aitem;
pos_a++; pos_a++;
@ -297,11 +313,13 @@ function merge_arrays(a, b, b_is_select) {
// Catch leftovers here. These sections are ugly code-copying. // Catch leftovers here. These sections are ugly code-copying.
if (pos_a < a.length) if (pos_a < a.length)
for (; pos_a < a.length ; pos_a++) for (; pos_a < a.length; pos_a++)
ret[ret.length] = a[pos_a]; ret[ret.length] = a[pos_a];
if (pos_b < b.length) { if (pos_b < b.length)
for (; pos_b < b.length; pos_b++) { {
for (; pos_b < b.length; pos_b++)
{
if (b_is_select) if (b_is_select)
bitem = b[pos_b].value; bitem = b[pos_b].value;
else else
@ -325,15 +343,13 @@ function merge_arrays(a, b, b_is_select) {
* be null if not used. * be null if not used.
* @return Array of all or selected indexes or values. * @return Array of all or selected indexes or values.
*/ */
function get_selection(control, findall, want_values, anyval) { function get_selection(control, findall, want_values, anyval)
{
var ret = new Array(); var ret = new Array();
if (!findall && control.selectedIndex == -1)
if ((!findall) && (control.selectedIndex == -1))
return ret; return ret;
for (var i = (anyval != null ? 1 : 0); i < control.length; i++) for (var i = (anyval != null ? 1 : 0); i < control.length; i++)
if (findall || control.options[i].selected) if (findall || control.options[i].selected)
ret[ret.length] = want_values ? control.options[i].value : i; ret[ret.length] = want_values ? control.options[i].value : i;
return ret; return ret;
} }

View File

@ -5,57 +5,57 @@
// Requires global vars: queryform, checkwidths, userAutocomplete // Requires global vars: queryform, checkwidths, userAutocomplete
onDomReady(function() onDomReady(function()
{ {
document.forms[queryform].content.focus(); document.forms[queryform].content.focus();
if (document.getElementById('deadlinefrom')) if (document.getElementById('deadlinefrom'))
{
Calendar.set('deadlinefrom');
Calendar.set('deadlineto');
}
new SimpleAutocomplete("email1", userAutocomplete, { emptyText: 'No users found' });
new SimpleAutocomplete("email2", userAutocomplete, { emptyText: 'No users found' });
Calendar.set('chfieldfrom');
Calendar.set('chfieldto');
new SimpleAutocomplete("chfieldwho", userAutocomplete, { emptyText: 'No users found' });
addKeywordsAutocomplete();
var lim = 250;
function checkw(e)
{
var s = document.getElementById(e);
s.style.minWidth = '100%';
// Expand select fields on hover to maximum available screen width
if (s && s.offsetWidth > lim)
{ {
s.style.minWidth = lim+'px'; Calendar.set('deadlinefrom');
s.style.width = lim+'px'; Calendar.set('deadlineto');
addListener(s, 'mouseover', function(e) }
{ new SimpleAutocomplete("email1", userAutocomplete, { emptyText: 'No users found' });
e = e || window.event; new SimpleAutocomplete("email2", userAutocomplete, { emptyText: 'No users found' });
var f = e.relatedTarget || e.fromElement; Calendar.set('chfieldfrom');
if (f == s || f.parentNode == s || !s.style.width && s.offsetWidth <= lim) Calendar.set('chfieldto');
return; new SimpleAutocomplete("chfieldwho", userAutocomplete, { emptyText: 'No users found' });
var c = s; addKeywordsAutocomplete();
while (c && c.nodeName != 'TABLE')
c = c.parentNode; var lim = 250;
var w = (lim+c.parentNode.offsetWidth-c.offsetWidth); function checkw(e)
if (w > lim+10) {
{ var s = document.getElementById(e);
s.style.width = 'auto'; s.style.minWidth = '100%';
s.style.maxWidth = w + 'px'; // Expand select fields on hover to maximum available screen width
} if (s && s.offsetWidth > lim)
}); {
addListener(s, 'mouseout', function(e) { s.style.minWidth = lim+'px';
e = e || window.event; s.style.width = lim+'px';
var t = e.relatedTarget || e.toElement; addListener(s, 'mouseover', function(e)
if (t == s || t.parentNode == s) {
return; e = e || window.event;
s.style.width = lim+'px'; var f = e.relatedTarget || e.fromElement;
s.style.maxWidth = ''; if (f == s || f.parentNode == s || !s.style.width && s.offsetWidth <= lim)
}); return;
var c = s;
while (c && c.nodeName != 'TABLE')
c = c.parentNode;
var w = (lim+c.parentNode.offsetWidth-c.offsetWidth);
if (w > lim+10)
{
s.style.width = 'auto';
s.style.maxWidth = w + 'px';
}
});
addListener(s, 'mouseout', function(e) {
e = e || window.event;
var t = e.relatedTarget || e.toElement;
if (t == s || t.parentNode == s)
return;
s.style.width = lim+'px';
s.style.maxWidth = '';
});
}
}
for (var i in checkwidths)
{
checkw(checkwidths[i]);
} }
}
for (var i in checkwidths)
{
checkw(checkwidths[i]);
}
}); });

View File

@ -11,17 +11,17 @@
resizeParentIframe = function() resizeParentIframe = function()
{ {
if ((/resize/.exec(window.location.hash) || if ((/resize/.exec(window.location.hash) ||
/[&\?]_resize=1/.exec(window.location.href)) && 'postMessage' in parent) /[&\?]_resize=1/.exec(window.location.href)) && 'postMessage' in parent)
{ {
var w = document.body.scrollWidth; var w = document.body.scrollWidth;
var h = document.body.scrollHeight; var h = document.body.scrollHeight;
parent.postMessage('resize(w='+w+';h='+h+')', '*'); parent.postMessage('resize(w='+w+';h='+h+')', '*');
} }
return true; return true;
}; };
if (window.addEventListener) if (window.addEventListener)
window.addEventListener('load', resizeParentIframe, false); window.addEventListener('load', resizeParentIframe, false);
else if (window.attachEvent) else if (window.attachEvent)
window.attachEvent('onload', resizeParentIframe); window.attachEvent('onload', resizeParentIframe);

View File

@ -13,335 +13,335 @@ var cuttedids = [];
// Добавить карточки для багов с ID'шниками из поля addbugs // Добавить карточки для багов с ID'шниками из поля addbugs
function addNewCards() function addNewCards()
{ {
for (var i = idlist.length-1; i >= 0; i--) for (var i = idlist.length-1; i >= 0; i--)
{ {
if (idlist[i] === '') if (idlist[i] === '')
idlist.pop(); idlist.pop();
else else
break; break;
} }
var val = document.getElementById('addbugs').value; var val = document.getElementById('addbugs').value;
var re = /(\d+)/g; var re = /(\d+)/g;
var m; var m;
while (m = re.exec(val)) while (m = re.exec(val))
idlist.push(m[1]); idlist.push(m[1]);
document.getElementById('idlist_value').value = idlist.join(','); document.getElementById('idlist_value').value = idlist.join(',');
document.getElementById('scrumform').submit(); document.getElementById('scrumform').submit();
} }
// Добавить пустую страницу // Добавить пустую страницу
function addEmptyPage() function addEmptyPage()
{ {
for (var i = 0; i < nr*nc; i++) for (var i = 0; i < nr*nc; i++)
idlist.push(''); idlist.push('');
document.getElementById('idlist_value').value = idlist.join(','); document.getElementById('idlist_value').value = idlist.join(',');
document.getElementById('scrumform').submit(); document.getElementById('scrumform').submit();
} }
// Обработчик нажатия Enter на поле addbugs // Обработчик нажатия Enter на поле addbugs
function addNewIfEnter(ev) function addNewIfEnter(ev)
{ {
if (ev.keyCode == 10 || ev.keyCode == 13) if (ev.keyCode == 10 || ev.keyCode == 13)
{ {
addNewCards(); addNewCards();
return true; return true;
} }
return false; return false;
} }
// Удалить все карточки // Удалить все карточки
function deleteAllCards() function deleteAllCards()
{ {
idlist = []; idlist = [];
document.getElementById('idlist_value').value = idlist.join(','); document.getElementById('idlist_value').value = idlist.join(',');
document.getElementById('pages').innerHTML = ''; document.getElementById('pages').innerHTML = '';
document.getElementById('scrumform').submit(); document.getElementById('scrumform').submit();
} }
// Сбросить состояние кнопок, выделение карточек, режим вставки // Сбросить состояние кнопок, выделение карточек, режим вставки
function resetAll() function resetAll()
{ {
if (pressedButton) if (pressedButton)
{ {
buttonHandler(null, pressedButton); buttonHandler(null, pressedButton);
pressedButton = null; pressedButton = null;
} }
deselectAll(); deselectAll();
stopPaste(); stopPaste();
return true; return true;
} }
// Снять выделение // Снять выделение
function deselectAll() function deselectAll()
{ {
for (var i in selectedcards) for (var i in selectedcards)
{ {
var e = document.getElementById('cardtd_'+i); var e = document.getElementById('cardtd_'+i);
e.className = 'cardtd'; e.className = 'cardtd';
} }
selectedcards = {}; selectedcards = {};
} }
// Обработчик, пытающийся по иерархии найти кнопку (id=btn_*), // Обработчик, пытающийся по иерархии найти кнопку (id=btn_*),
// и вызвать на ней buttonHandler // и вызвать на ней buttonHandler
function guessButton(ev) function guessButton(ev)
{ {
ev = DragMaster.fixEvent(ev); ev = DragMaster.fixEvent(ev);
var t; var t;
if (t = searchButtonTarget(ev)) if (t = searchButtonTarget(ev))
return buttonHandler(ev, t); return buttonHandler(ev, t);
return true; return true;
} }
// Обработчик mousedown и mouseup на кнопках (id=btn_*) // Обработчик mousedown и mouseup на кнопках (id=btn_*)
function buttonHandler(ev, target) function buttonHandler(ev, target)
{ {
if (!pressedButton) if (!pressedButton)
{ {
pressedButton = target; pressedButton = target;
target.style.borderStyle = 'inset'; target.style.borderStyle = 'inset';
target.style.padding = '4px 2px 2px 4px'; target.style.padding = '4px 2px 2px 4px';
} }
else if (pressedButton == target) else if (pressedButton == target)
{ {
target.style.borderStyle = 'outset'; target.style.borderStyle = 'outset';
target.style.padding = '3px'; target.style.padding = '3px';
pressedButton = null; pressedButton = null;
if (target.id == 'btn_cut') if (target.id == 'btn_cut')
deleteSelectedCards(true); deleteSelectedCards(true);
else if (target.id == 'btn_delete') else if (target.id == 'btn_delete')
deleteSelectedCards(false); deleteSelectedCards(false);
else if (target.id == 'btn_paste') else if (target.id == 'btn_paste')
pasteCards(); pasteCards();
else if (target.id == 'btn_paste_beg') else if (target.id == 'btn_paste_beg')
doPasteCards(0); doPasteCards(0);
return true; return true;
} }
return false; return false;
} }
// Обработчик клика-выделения по карточке // Обработчик клика-выделения по карточке
function selectCard(ev, target) function selectCard(ev, target)
{ {
var empty = isEmptyHash(selectedcards, target.id.substr(7)); var empty = isEmptyHash(selectedcards, target.id.substr(7));
if (pasteMode) if (pasteMode)
{ {
doPasteCards(id_to_coord(target.id)+1); doPasteCards(id_to_coord(target.id)+1);
return true; return true;
} }
else if (ctrl || !selectedcards[target.id.substr(7)]) else if (ctrl || !selectedcards[target.id.substr(7)])
{ {
if (!ctrl) if (!ctrl)
deselectAll(); deselectAll();
var issel = target.className == 'cardtd selected'; var issel = target.className == 'cardtd selected';
target.className = issel ? 'cardtd' : 'cardtd selected'; target.className = issel ? 'cardtd' : 'cardtd selected';
if (issel) if (issel)
delete selectedcards[target.id.substr(7)]; delete selectedcards[target.id.substr(7)];
else else
selectedcards[target.id.substr(7)] = true; selectedcards[target.id.substr(7)] = true;
return true; return true;
} }
return false; return false;
} }
// Подсветка карточки в режиме вставки // Подсветка карточки в режиме вставки
function highlightCard(ev) function highlightCard(ev)
{ {
if (pasteMode) if (pasteMode)
{ {
ev = DragMaster.fixEvent(ev); ev = DragMaster.fixEvent(ev);
var t = searchCardTarget(ev); var t = searchCardTarget(ev);
t.className = 'cardtd highlight'; t.className = 'cardtd highlight';
highlitCard = t; highlitCard = t;
} }
} }
// Снятие подсветки карточки в режиме вставки // Снятие подсветки карточки в режиме вставки
function unlightCard(ev) function unlightCard(ev)
{ {
if (pasteMode) if (pasteMode)
{ {
ev = DragMaster.fixEvent(ev); ev = DragMaster.fixEvent(ev);
var t = searchCardTarget(ev); var t = searchCardTarget(ev);
t.className = 'cardtd'; t.className = 'cardtd';
} }
} }
// Преобразование номера в координаты [лист, строка, столбец] // Преобразование номера в координаты [лист, строка, столбец]
function to_coord(i) function to_coord(i)
{ {
var to_k = Math.floor(i / nr / nc); var to_k = Math.floor(i / nr / nc);
var to_i = Math.floor((i / nc) % nr); var to_i = Math.floor((i / nc) % nr);
var to_j = Math.floor(i % nc); var to_j = Math.floor(i % nc);
return [to_k, to_i, to_j]; return [to_k, to_i, to_j];
} }
// Преобразование номера в строку с координатами лист_строка_столбец // Преобразование номера в строку с координатами лист_строка_столбец
function to_coord_id(i) function to_coord_id(i)
{ {
return to_coord(i).join('_'); return to_coord(i).join('_');
} }
// Преобразование id элемента (.*лист_строка_столбец.*) в номер // Преобразование id элемента (.*лист_строка_столбец.*) в номер
function id_to_coord(id) function id_to_coord(id)
{ {
var m = /(\d+)_(\d+)_(\d+)/.exec(id.substr(7)); var m = /(\d+)_(\d+)_(\d+)/.exec(id.substr(7));
return (parseInt(m[1])*nr+parseInt(m[2]))*nc+parseInt(m[3]); return (parseInt(m[1])*nr+parseInt(m[2]))*nc+parseInt(m[3]);
} }
// Удалить(cut=0)/вырезать(cut=1) выделенные карточки // Удалить(cut=0)/вырезать(cut=1) выделенные карточки
function deleteSelectedCards(cut) function deleteSelectedCards(cut)
{ {
var shift = 0; var shift = 0;
var coord = 0; var coord = 0;
var n = nr * nc * np; var n = nr * nc * np;
if (cut) if (cut)
{
cuttedcards = [];
cuttedids = [];
}
for (var k = 0; k < np; k++)
{
for (var i = 0; i < nr; i++)
{ {
for (var j = 0; j < nc; j++, coord++) cuttedcards = [];
{ cuttedids = [];
var s = selectedcards[k+'_'+i+'_'+j];
var e = document.getElementById('cardtd_'+k+'_'+i+'_'+j);
if (!e)
continue;
if (s)
{
if (cut)
{
cuttedcards.push(e.innerHTML);
cuttedids.push(idlist[coord]);
}
shift++;
}
else if (shift > 0)
{
var to = to_coord_id(coord-shift);
document.getElementById('cardtd_'+to).innerHTML = e.innerHTML;
idlist[coord-shift] = idlist[coord];
}
else if (coord + shift < n)
continue;
// во всех трёх случаях - если выделена для
// удаления, если перемещена в другую, или
// если находится в конце - очищаем
e.innerHTML = emptycell;
idlist[coord] = '';
}
} }
} for (var k = 0; k < np; k++)
if (cut && cuttedids.length) {
document.getElementById('cut_status').innerHTML = 'Вырезано '+cuttedids.length+' карточек.'; for (var i = 0; i < nr; i++)
deselectAll(); {
document.getElementById('idlist_value').value = idlist.join(','); for (var j = 0; j < nc; j++, coord++)
{
var s = selectedcards[k+'_'+i+'_'+j];
var e = document.getElementById('cardtd_'+k+'_'+i+'_'+j);
if (!e)
continue;
if (s)
{
if (cut)
{
cuttedcards.push(e.innerHTML);
cuttedids.push(idlist[coord]);
}
shift++;
}
else if (shift > 0)
{
var to = to_coord_id(coord-shift);
document.getElementById('cardtd_'+to).innerHTML = e.innerHTML;
idlist[coord-shift] = idlist[coord];
}
else if (coord + shift < n)
continue;
// во всех трёх случаях - если выделена для
// удаления, если перемещена в другую, или
// если находится в конце - очищаем
e.innerHTML = emptycell;
idlist[coord] = '';
}
}
}
if (cut && cuttedids.length)
document.getElementById('cut_status').innerHTML = 'Вырезано '+cuttedids.length+' карточек.';
deselectAll();
document.getElementById('idlist_value').value = idlist.join(',');
} }
// Перейти в режим выбора места вставки вырезанных карточек // Перейти в режим выбора места вставки вырезанных карточек
function pasteCards() function pasteCards()
{ {
if (!pasteMode) if (!pasteMode)
{
if (!cuttedids.length)
{ {
alert('Сначала выделите и вырежьте какие-нибудь карточки!'); if (!cuttedids.length)
return; {
alert('Сначала выделите и вырежьте какие-нибудь карточки!');
return;
}
alert('Кликните на карточку, после которой нужно вставить вырезанное, либо на кнопку "В начало".');
deselectAll();
pasteMode = true;
document.getElementById('btn_paste_beg').style.display = '';
} }
alert('Кликните на карточку, после которой нужно вставить вырезанное, либо на кнопку "В начало".');
deselectAll();
pasteMode = true;
document.getElementById('btn_paste_beg').style.display = '';
}
} }
// Вставить вырезанные карточки в позицию coord // Вставить вырезанные карточки в позицию coord
function doPasteCards(coord) function doPasteCards(coord)
{ {
stopPaste(); stopPaste();
var nx = cuttedids.length; var nx = cuttedids.length;
if (nx <= 0) if (nx <= 0)
return; return;
if (!document.getElementById('cardtd_'+to_coord_id(coord))) if (!document.getElementById('cardtd_'+to_coord_id(coord)))
{
alert('Некуда вставлять');
return;
}
var n = nr * nc * np;
var from, to;
for (var i = n-nx-1; i >= coord; i--)
{
from = to_coord_id(i);
to = to_coord_id(i+nx);
if (document.getElementById('cardtd_'+from) &&
document.getElementById('cardtd_'+to))
{ {
document.getElementById('cardtd_'+to).innerHTML = alert('Некуда вставлять');
document.getElementById('cardtd_'+from).innerHTML; return;
idlist[i+nx] = idlist[i];
} }
} var n = nr * nc * np;
for (var i = 0; i < nx; i++) var from, to;
{ for (var i = n-nx-1; i >= coord; i--)
to = to_coord_id(i+coord); {
document.getElementById('cardtd_'+to).innerHTML = cuttedcards[i]; from = to_coord_id(i);
document.getElementById('cardtd_'+to).className = 'cardtd selected'; to = to_coord_id(i+nx);
idlist[i+coord] = cuttedids[i]; if (document.getElementById('cardtd_'+from) &&
selectedcards[to] = true; document.getElementById('cardtd_'+to))
} {
cuttedids = []; document.getElementById('cardtd_'+to).innerHTML =
cuttedcards = []; document.getElementById('cardtd_'+from).innerHTML;
document.getElementById('cut_status').innerHTML = ''; idlist[i+nx] = idlist[i];
document.getElementById('idlist_value').value = idlist.join(','); }
}
for (var i = 0; i < nx; i++)
{
to = to_coord_id(i+coord);
document.getElementById('cardtd_'+to).innerHTML = cuttedcards[i];
document.getElementById('cardtd_'+to).className = 'cardtd selected';
idlist[i+coord] = cuttedids[i];
selectedcards[to] = true;
}
cuttedids = [];
cuttedcards = [];
document.getElementById('cut_status').innerHTML = '';
document.getElementById('idlist_value').value = idlist.join(',');
} }
// Выйти из режима вставки // Выйти из режима вставки
function stopPaste() function stopPaste()
{ {
if (highlitCard) if (highlitCard)
highlitCard.className = 'cardtd'; highlitCard.className = 'cardtd';
document.getElementById('btn_paste_beg').style.display = 'none'; document.getElementById('btn_paste_beg').style.display = 'none';
pasteMode = false; pasteMode = false;
} }
// Обработчик keydown/keyup, записывает состояние ctrl // Обработчик keydown/keyup, записывает состояние ctrl
function ctrlDown(ev) function ctrlDown(ev)
{ {
if (ev.keyCode == 17) if (ev.keyCode == 17)
{ {
ctrl = ev.type == 'keydown'; ctrl = ev.type == 'keydown';
return true; return true;
} }
return false; return false;
} }
// Попробовать найти по иерархии карточку (id=cardtd_*) // Попробовать найти по иерархии карточку (id=cardtd_*)
function searchCardTarget(e) function searchCardTarget(e)
{ {
var nt = e._target, i; var nt = e._target, i;
while (nt && (!nt.attributes || while (nt && (!nt.attributes ||
!(i = nt.attributes.getNamedItem('id')) || !(i = nt.attributes.getNamedItem('id')) ||
i.value.substr(0, 7) != 'cardtd_')) i.value.substr(0, 7) != 'cardtd_'))
nt = nt.parentNode; nt = nt.parentNode;
return nt; return nt;
} }
// Попробовать найти по иерархии кнопку (id=btn_*) // Попробовать найти по иерархии кнопку (id=btn_*)
function searchButtonTarget(e) function searchButtonTarget(e)
{ {
var nt = e._target, i; var nt = e._target, i;
while (nt && (!nt.attributes || while (nt && (!nt.attributes ||
!(i = nt.attributes.getNamedItem('id')) || !(i = nt.attributes.getNamedItem('id')) ||
i.value.substr(0, 4) != 'btn_')) i.value.substr(0, 4) != 'btn_'))
nt = nt.parentNode; nt = nt.parentNode;
return nt; return nt;
} }
// Попробовать найти по иерархии что-нибудь кроме карточек и кнопок, // Попробовать найти по иерархии что-нибудь кроме карточек и кнопок,
// по сути это только <input> и <textarea>, клик по чему не сбрасывает всё нахрен // по сути это только <input> и <textarea>, клик по чему не сбрасывает всё нахрен
function searchNonResetTarget(e) function searchNonResetTarget(e)
{ {
var nt = e._target, i; var nt = e._target, i;
while (nt && (!(i = nt.nodeName.toLowerCase()) || while (nt && (!(i = nt.nodeName.toLowerCase()) ||
!(i == 'input' || i == 'textarea'))) !(i == 'input' || i == 'textarea')))
nt = nt.parentNode; nt = nt.parentNode;
return nt; return nt;
} }
// Глобальный обработчик события mouseup // Глобальный обработчик события mouseup
function mouseUpHandler(e) function mouseUpHandler(e)
{ {
e = DragMaster.fixEvent(e); e = DragMaster.fixEvent(e);
var t; var t;
if (searchNonResetTarget(e)) {} if (searchNonResetTarget(e)) {}
else if (t = searchCardTarget(e)) else if (t = searchCardTarget(e))
selectCard(e, t); selectCard(e, t);
else if (t = searchButtonTarget(e)) else if (t = searchButtonTarget(e))
buttonHandler(e, t); buttonHandler(e, t);
else else
resetAll(); resetAll();
return true; return true;
} }
// Класс "Перетаскиваемая карточка", унаследованный от "Перетаскиваемого объекта" // Класс "Перетаскиваемая карточка", унаследованный от "Перетаскиваемого объекта"
// Логика - при начале перетаскивания удаляется из родительского элемента, // Логика - при начале перетаскивания удаляется из родительского элемента,
@ -350,97 +350,97 @@ function mouseUpHandler(e)
// обработчики вырезания и вставки карточек. // обработчики вырезания и вставки карточек.
var CardDragObject = function(e) var CardDragObject = function(e)
{ {
DragObject.call(this, e); DragObject.call(this, e);
this.n = id_to_coord(e.id); this.n = id_to_coord(e.id);
}; };
CardDragObject.prototype = new DragObject(); CardDragObject.prototype = new DragObject();
CardDragObject.prototype.onDragStart = function() { CardDragObject.prototype.onDragStart = function() {
this.tmp = document.createElement('td'); this.tmp = document.createElement('td');
this.element.style.opacity = 0.5; this.element.style.opacity = 0.5;
this.element.parentNode.insertBefore(this.tmp, this.element); this.element.parentNode.insertBefore(this.tmp, this.element);
this.element.parentNode.parentNode.parentNode.appendChild(this.element); this.element.parentNode.parentNode.parentNode.appendChild(this.element);
}; };
CardDragObject.prototype.onDragSuccess = function(target, pos) { CardDragObject.prototype.onDragSuccess = function(target, pos) {
this.tmp.parentNode.insertBefore(this.element, this.tmp); this.tmp.parentNode.insertBefore(this.element, this.tmp);
this.tmp.parentNode.removeChild(this.tmp); this.tmp.parentNode.removeChild(this.tmp);
if (!selectedcards[this.element.id.substr(7)]) if (!selectedcards[this.element.id.substr(7)])
{ {
deselectAll(); deselectAll();
selectedcards[this.element.id.substr(7)] = true; selectedcards[this.element.id.substr(7)] = true;
} }
var to = id_to_coord(target.element.id)+1; var to = id_to_coord(target.element.id)+1;
var w = target.element.scrollWidth; var w = target.element.scrollWidth;
if (pos.x < w/2) if (pos.x < w/2)
to--; to--;
var decr = 0; var decr = 0;
for (var i = 0; i < to; i++) for (var i = 0; i < to; i++)
if (selectedcards[to_coord_id(i)]) if (selectedcards[to_coord_id(i)])
decr++; decr++;
to -= decr; to -= decr;
deleteSelectedCards(true); deleteSelectedCards(true);
doPasteCards(to); doPasteCards(to);
}; };
CardDragObject.prototype.onDragFail = function() { CardDragObject.prototype.onDragFail = function() {
this.tmp.parentNode.insertBefore(this.element, this.tmp); this.tmp.parentNode.insertBefore(this.element, this.tmp);
this.tmp.parentNode.removeChild(this.tmp); this.tmp.parentNode.removeChild(this.tmp);
}; };
// Каждая карточка также является целью перетаскивания // Каждая карточка также является целью перетаскивания
// Тут вся логика - подсветить левый/правый край в зависимости // Тут вся логика - подсветить левый/правый край в зависимости
// от положения мышки // от положения мышки
var CardDropTarget = function(e) var CardDropTarget = function(e)
{ {
DropTarget.call(this, e); DropTarget.call(this, e);
this.n = id_to_coord(e.id); this.n = id_to_coord(e.id);
}; };
CardDropTarget.prototype = new DropTarget(); CardDropTarget.prototype = new DropTarget();
CardDropTarget.prototype.onLeave = function() CardDropTarget.prototype.onLeave = function()
{ {
this.element.style.border = '1px dashed black'; this.element.style.border = '1px dashed black';
}; };
CardDropTarget.prototype.onMove = function(pos) CardDropTarget.prototype.onMove = function(pos)
{ {
var w = this.element.scrollWidth; var w = this.element.scrollWidth;
this.element.style.border = '1px dashed black'; this.element.style.border = '1px dashed black';
if (pos.x < w/2) if (pos.x < w/2)
this.element.style.borderLeft = '5px solid red'; this.element.style.borderLeft = '5px solid red';
else else
this.element.style.borderRight = '5px solid red'; this.element.style.borderRight = '5px solid red';
}; };
// 2 если hash пуст // 2 если hash пуст
// 1 если в нём один ключ key // 1 если в нём один ключ key
// 0 если в нём есть ключ, не равный key // 0 если в нём есть ключ, не равный key
function isEmptyHash(hash, key) function isEmptyHash(hash, key)
{ {
var empty = 2; var empty = 2;
for (var i in hash) for (var i in hash)
{
if (key !== undefined && i == key)
empty = 1;
else
{ {
empty = 0; if (key !== undefined && i == key)
break; empty = 1;
else
{
empty = 0;
break;
}
} }
} return empty;
return empty;
} }
// Установка обработчиков событий: // Установка обработчиков событий:
for (var k = 0; k < np; k++) for (var k = 0; k < np; k++)
{ {
for (var i = 0; i < nr; i++) for (var i = 0; i < nr; i++)
{
for (var j = 0; j < nc; j++)
{ {
var e = document.getElementById('cardtd_'+k+'_'+i+'_'+j); for (var j = 0; j < nc; j++)
if (e) {
{ var e = document.getElementById('cardtd_'+k+'_'+i+'_'+j);
addListener(e, 'mouseover', highlightCard); if (e)
addListener(e, 'mouseout', unlightCard); {
new CardDragObject(e); addListener(e, 'mouseover', highlightCard);
new CardDropTarget(e); addListener(e, 'mouseout', unlightCard);
} new CardDragObject(e);
new CardDropTarget(e);
}
}
} }
}
} }
addListener(document, "mousedown", guessButton); addListener(document, "mousedown", guessButton);
addListener(document, "mouseup", mouseUpHandler); addListener(document, "mouseup", mouseUpHandler);

View File

@ -190,7 +190,8 @@ function ctrlEnter(event, formElem)
return true; return true;
} }
if (typeof Node == 'undefined') { if (typeof Node == 'undefined')
{
/* MSIE doesn't define Node, so provide a compatibility object */ /* MSIE doesn't define Node, so provide a compatibility object */
window.Node = { window.Node = {
TEXT_NODE: 3, TEXT_NODE: 3,