books.js (2426B)
1 // An inefficient, but effective bubble sort 2 function sort(collection, key) { 3 var i, j; 4 var count = collection.length; 5 var parent, child; 6 7 for (i = count - 1; i >= 0; i--) { 8 for (j = 1; j <= i; j++) { 9 if (collection[j - 1][key] > collection[j][key]) { 10 // Move the item both in the local array and 11 // in the tree 12 child = collection[j]; 13 parent = child.parentNode; 14 15 collection[j] = collection[j - 1]; 16 collection[j - 1] = child; 17 18 parent.removeChild(child); 19 parent.insertBefore(child, collection[j]); 20 } 21 } 22 } 23 } 24 25 // Set user properties on the nodes in the collection 26 // based on information found in its children. For example, 27 // make a property "Author" based on the content of the 28 // "Author" element found in the childNode list of the node. 29 // This makes later sorting more efficient 30 function collectInfo(nodes, propNames) { 31 var i, j, k; 32 var ncount = nodes.length; 33 var pcount = propNames.length; 34 35 for (i = 0; i < ncount; i++) { 36 var node = nodes[i]; 37 var childNodes = node.childNodes; 38 var ccount = childNodes.length; 39 40 for (j = 0; j < ccount; j++) { 41 var child = childNodes[j]; 42 43 if (child.nodeType == Node.ELEMENT_NODE) { 44 var tagName = child.tagName; 45 46 for (k = 0; k < pcount; k++) { 47 var prop = propNames[k]; 48 if (prop == tagName) { 49 node[prop] = child.firstChild.data; 50 } 51 } 52 } 53 } 54 } 55 } 56 57 var enabled = true; 58 function toggleStyleSheet() { 59 if (enabled) { 60 document.styleSheets[2].disabled = true; 61 } else { 62 document.styleSheets[2].disabled = false; 63 } 64 65 enabled = !enabled; 66 } 67 68 // XXX This is a workaround for a bug where 69 // changing the disabled state of a stylesheet can't 70 // be done in an event handler. For now, we do it 71 // in a zero-delay timeout. 72 function initiateToggle() { 73 setTimeout(toggleStyleSheet, 0); 74 } 75 76 var sortableProps = ["Author", "Title", "ISBN"]; 77 var books = []; 78 79 // We uppercase the tagName as a workaround for a bug 80 // that loses the original case of the tag. 81 var bookset = document.getElementsByTagName("Book"); 82 83 // We need to create a "non-live" array to operate on. Since 84 // we'll be moving things around in this array, we can't use 85 // the read-only, live one returned by getElementsByTagName. 86 for (var i = 0; i < bookset.length; i++) { 87 books[i] = bookset[i]; 88 } 89 90 collectInfo(books, sortableProps);