forked from iamamused/foED-AdvancED-DOM-Scripting
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathADS-final-verbose.js
1620 lines (1418 loc) · 51.3 KB
/
ADS-final-verbose.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ADS Library from Advanced DOM Scripting
* http://advanceddomscripting.com
*
* This library is not compressed and is not recommended for production use in
* its current state. The code is excessively verbose and heavily commented
* as it was written as a teaching tool. It is recommended you edit the code for
* better performance and smaller file size.
* @projectDescription ADS library from the book "AdvancED DOM Scripting" http://advanceddomscripting.com/
* @author Jeffrey Sambells [email protected]
* @copyright Jeffrey Sambells 2007 unless otherwise noted
* @version $Id: ADS-final-verbose.js 183 2007-07-17 20:23:30Z jsambells $
* @see http://advanceddomscripting.com/source/documentation
* @namespace ADS
*/
/**
* Missing getElementById.
* Example of creating a DOM replacement this isn't necessary because the
* library assume browsers that support it.
*/
if(document.all && !document.getElementById) {
document.getElementById = function(id) {
return document.all[id];
}
}
/**
* Repeat a string
* from Chapter 3
* Using the prototype to modify core objects
*/
if (!String.repeat) {
String.prototype.repeat = function(l){
return new Array(l+1).join(this);
}
}
/**
* Remove trailing and leading whitespace
* from Chapter 3
*/
if (!String.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,'');
}
}
/**
* ADS Namespace
* This anonymous function acts as a namespace wrapper for the rest
* of the methods. Methods are then assigned to the window object
* using: window['ADS']['methodName'] = methodReference;
* @alias ADS
*/
(function(){
/**
* The primary namespace object
* @type {Object}
* @alias ADS
*/
if(!window['ADS']) {
window['ADS'] = {};
}
/********************************
* Chapter 1
*********************************/
/**
* Checks to see if the current browser is compatible with the entire library
*/
function isCompatible(other) {
// Use capability detection to check requirements
if( other===false
|| !Array.prototype.push
|| !Object.hasOwnProperty
|| !document.createElement
|| !document.getElementsByTagName
) {
alert('TR- if you see this message isCompatible is failing incorrectly.');
return false;
}
return true;
}
window['ADS']['isCompatible'] = isCompatible;
/**
* document.getElementById(); replacement.
*/
function $() {
var elements = new Array();
// Find all the elements supplied as arguments
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
// If the argument is a string assume it's an id
if (typeof element == 'string') {
element = document.getElementById(element);
}
// If only one argument was supplied, return the element immediately
if (arguments.length == 1) {
return element;
}
// Otherwise add it to the array
elements.push(element);
}
// Return the array of multiple requested elements
return elements;
};
window['ADS']['$'] = $;
/**
* Register an event listener on an element
*/
function addEvent( node, type, listener ) {
// Check compatibility using the earlier method
// to ensure graceful degradation
if(!isCompatible()) { return false }
if(!(node = $(node))) return false;
if (node.addEventListener) {
// W3C method
node.addEventListener( type, listener, false );
return true;
} else if(node.attachEvent) {
// MSIE method
node['e'+type+listener] = listener;
node[type+listener] = function(){node['e'+type+listener]( window.event );}
node.attachEvent( 'on'+type, node[type+listener] );
return true;
}
// Didn't have either so return false
return false;
};
window['ADS']['addEvent'] = addEvent;
/**
* Unregister an event listener on an element
*/
function removeEvent(node, type, listener ) {
if(!(node = $(node))) return false;
if (node.removeEventListener) {
node.removeEventListener( type, listener, false );
return true;
} else if (node.detachEvent) {
// MSIE method
node.detachEvent( 'on'+type, node[type+listener] );
node[type+listener] = null;
return true;
}
// Didn't have either so return false
return false;
};
window['ADS']['removeEvent'] = removeEvent;
/**
* Retrieve an array of element base on a class name
*/
function getElementsByClassName(className, tag, parent){
parent = parent || document;
if(!(parent = $(parent))) return false;
// Locate all the matching tags
var allTags = (tag == "*" && parent.all) ? parent.all : parent.getElementsByTagName(tag);
var matchingElements = new Array();
// Create a regular expression to determine if the className is correct
className = className.replace(/\-/g, "\\-");
var regex = new RegExp("(^|\\s)" + className + "(\\s|$)");
var element;
// Check each element
for(var i=0; i<allTags.length; i++){
element = allTags[i];
if(regex.test(element.className)){
matchingElements.push(element);
}
}
// Return any matching elements
return matchingElements;
};
window['ADS']['getElementsByClassName'] = getElementsByClassName;
/**
* Toggle the style display value between none and the default
*/
function toggleDisplay(node, value) {
if(!(node = $(node))) return false;
if ( node.style.display != 'none' ) {
node.style.display = 'none';
} else {
node.style.display = value || '';
}
return true;
}
window['ADS']['toggleDisplay'] = toggleDisplay;
/**
* Insert a DOM node after another DOM node
*/
function insertAfter(node, referenceNode) {
if(!(node = $(node))) return false;
if(!(referenceNode = $(referenceNode))) return false;
return referenceNode.parentNode.insertBefore(node, referenceNode.nextSibling);
};
window['ADS']['insertAfter'] = insertAfter;
/**
* Remove all teh child nodes from an element
*/
function removeChildren(parent) {
if(!(parent = $(parent))) return false;
// While there is a child remove it
while (parent.firstChild) {
parent.firstChild.parentNode.removeChild(parent.firstChild);
}
// Return the parent again so you can stack the methods
return parent;
};
window['ADS']['removeChildren'] = removeChildren;
/**
* Insert a new node as the first child.
*/
function prependChild(parent,newChild) {
if(!(parent = $(parent))) return false;
if(!(newChild = $(newChild))) return false;
if(parent.firstChild) {
// There is already a child so insert before the first one
parent.insertBefore(newChild,parent.firstChild);
} else {
// No children so just append
parent.appendChild(newChild);
}
// Return the parent again so you can stack the methods
return parent;
}
window['ADS']['prependChild'] = prependChild;
/********************************
* Chapter 2
*********************************/
/**
* Put the given object in teh context of the given method.
*/
function bindFunction(obj, func) {
return function() {
func.apply(obj,arguments);
};
};
window['ADS']['bindFunction'] = bindFunction;
/**
* Retrieve the size of the browser window.
*/
function getBrowserWindowSize() {
var de = document.documentElement;
// window.innerWidth for most browsers
// document.documentElement.clientWidth for MSIE in strict mode
// document.body.clientWidth for MSIE in quirks mode
return {
'width':(
window.innerWidth
|| (de && de.clientWidth )
|| document.body.clientWidth),
'height':(
window.innerHeight
|| (de && de.clientHeight )
|| document.body.clientHeight)
}
};
window['ADS']['getBrowserWindowSize'] = getBrowserWindowSize;
/********************************
* Chapter 3
*********************************/
/**
* Constants for note type comparison
*/
window['ADS']['node'] = {
ELEMENT_NODE : 1,
ATTRIBUTE_NODE : 2,
TEXT_NODE : 3,
CDATA_SECTION_NODE : 4,
ENTITY_REFERENCE_NODE : 5,
ENTITY_NODE : 6,
PROCESSING_INSTRUCTION_NODE : 7,
COMMENT_NODE : 8,
DOCUMENT_NODE : 9,
DOCUMENT_TYPE_NODE : 10,
DOCUMENT_FRAGMENT_NODE : 11,
NOTATION_NODE : 12
};
/**
* Walk the nodes in the DOM tree without maintaining parent/child relationships.
*/
function walkElementsLinear(func,node) {
var root = node || window.document;
var nodes = root.getElementsByTagName("*");
for(var i = 0 ; i < nodes.length ; i++) {
func.call(nodes[i]);
}
};
window['ADS']['walkElementsLinear'] = walkElementsLinear;
/**
* Walk the nodes in the DOM tree maintaining parent/child relationships.
*/
function walkTheDOMRecursive(func,node,depth,returnedFromParent) {
var root = node || window.document;
returnedFromParent = func.call(root,depth++,returnedFromParent);
node = root.firstChild;
while(node) {
walkTheDOMRecursive(func,node,depth,returnedFromParent);
node = node.nextSibling;
}
};
window['ADS']['walkTheDOMRecursive'] = walkTheDOMRecursive;
/**
* Walk the nodes in the DOM tree maintaining parent/child relationships and include the node attributes as well.
*/
function walkTheDOMWithAttributes(node,func,depth,returnedFromParent) {
var root = node || window.document;
returnedFromParent = func(root,depth++,returnedFromParent);
if (root.attributes) {
for(var i=0; i < root.attributes.length; i++) {
walkTheDOMWithAttributes(root.attributes[i],func,depth-1,returnedFromParent);
}
}
if(root.nodeType != ADS.node.ATTRIBUTE_NODE) {
node = root.firstChild;
while(node) {
walkTheDOMWithAttributes(node,func,depth,returnedFromParent);
node = node.nextSibling;
}
}
};
window['ADS']['walkTheDOMWithAttributes'] = walkTheDOMWithAttributes;
/**
* Walk the DOM recursively using a callback function
*/
function walkTheDOM(node, func) {
func(node);
node = node.firstChild;
while (node) {
walkTheDOM(node, func);
node = node.nextSibling;
}
}
window['ADS']['walkTheDOM'] = walkTheDOM;
/**
* Convert hyphenated word-word strings to camel case wordWord strings.
*/
function camelize(s) {
return s.replace(/-(\w)/g, function (strMatch, p1){
return p1.toUpperCase();
});
}
window['ADS']['camelize'] = camelize;
/********************************
* Chapter 4
*********************************/
/**
* Convert camel case wordWord strings to hyphenated word-word strings.
*/
function uncamelize(s, sep) {
sep = sep || '-';
return s.replace(/([a-z])([A-Z])/g, function (strMatch, p1, p2){
return p1 + sep + p2.toLowerCase();
});
}
window['ADS']['camelize'] = camelize;
/**
* Add a load event that will run when the document finishes loading - excluding images.
*/
function addLoadEvent(loadEvent,waitForImages) {
if(!isCompatible()) return false;
// If the wait flag is true use the regular add event method
if(waitForImages) {
return addEvent(window, 'load', loadEvent);
}
// Otherwise use a number of different methods
// Wrap the loadEvent method to assign the correct content for the
// this keyword and ensure that the event doesn't execute twice
var init = function() {
if (arguments.callee.done) return;
// Return if this function has already been called
// Mark this function so you can verify if it was already run
arguments.callee.done = true;
// Run the load event in the context of the document
loadEvent.apply(document,arguments);
};
// Register the event using the DOMContentLoaded event
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
// For Safari, use a setInterval() to see if the document has loaded
if (/WebKit/i.test(navigator.userAgent)) {
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
clearInterval(_timer);
init();
}
},10);
}
// For Internet Explorer (using conditional comments) attach a script
// that is deferred to the end of the load process and then check to see
// if it has loaded
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init();
}
};
/*@end @*/
return true;
}
window['ADS']['addLoadEvent'] = addLoadEvent;
/**
* Stop the propagation of an event
*/
function stopPropagation(eventObject) {
eventObject = eventObject || getEventObject(eventObject);
if(eventObject.stopPropagation) {
eventObject.stopPropagation();
} else {
eventObject.cancelBubble = true;
}
}
window['ADS']['stopPropagation'] = stopPropagation;
/**
* Prevents the default event in the event flow (such as following the href in an anchor).
*/
function preventDefault(eventObject) {
eventObject = eventObject || getEventObject(eventObject);
if(eventObject.preventDefault) {
eventObject.preventDefault();
} else {
eventObject.returnValue = false;
}
}
window['ADS']['preventDefault'] = preventDefault;
/**
* Retrieves the event object in a cross-browser way.
*/
function getEventObject(W3CEvent) {
return W3CEvent || window.event;
}
window['ADS']['getEventObject'] = getEventObject;
/**
* Retrieves the element targeted by the event.
*/
function getTarget(eventObject) {
eventObject = eventObject || getEventObject(eventObject);
// Check if the target is W3C or MSIE
var target = eventObject.target || eventObject.scrElement;
// Reassign the target to the parent
// if it is a text node like in Safari
if(target.nodeType == ADS.node.TEXT_NODE) {
target = node.parentNode;
}
return target;
}
window['ADS']['getTarget'] = getTarget;
/**
* Determine which mouse button was pressed
*/
function getMouseButton(eventObject) {
eventObject = eventObject || getEventObject(eventObject);
// Initialize an object wit the appropriate properties
var buttons = {
'left':false,
'middle':false,
'right':false
};
// Check the toString value of the eventObject
// W3C Dom object have a toString method and in this case it
// should be MouseEvent
if(eventObject.toString && eventObject.toString().indexOf('MouseEvent') != -1) {
// W3C Method
switch(eventObject.button) {
case 0: buttons.left = true; break;
case 1: buttons.middle = true; break;
case 2: buttons.right = true; break;
default: break;
}
} else if(eventObject.button) {
// MSIE method
switch(eventObject.button) {
case 1: buttons.left = true; break;
case 2: buttons.right = true; break;
case 3:
buttons.left = true;
buttons.right = true;
break;
case 4: buttons.middle = true; break;
case 5:
buttons.left = true;
buttons.middle = true;
break;
case 6:
buttons.middle = true;
buttons.right = true;
break;
case 7:
buttons.left = true;
buttons.middle = true;
buttons.right = true;
break;
default: break;
}
} else {
return false;
}
return buttons;
}
window['ADS']['getMouseButton'] = getMouseButton;
/**
* Get the position of the pointer in the document.
*/
function getPointerPositionInDocument(eventObject) {
eventObject = eventObject || getEventObject(eventObject);
var x = eventObject.pageX || (eventObject.clientX +
(document.documentElement.scrollLeft || document.body.scrollLeft));
var y= eventObject.pageY || (eventObject.clientY +
(document.documentElement.scrollTop || document.body.scrollTop));
//x and y now contain the coordinates of the mouse relative to the document origin
return {'x':x,'y':y};
}
window['ADS']['getPointerPositionInDocument'] = getPointerPositionInDocument;
/**
* Get the key pressed from the event object
*/
function getKeyPressed(eventObject) {
eventObject = eventObject || getEventObject(eventObject);
var code = eventObject.keyCode;
var value = String.fromCharCode(code);
return {'code':code,'value':value};
}
window['ADS']['getKeyPressed'] = getKeyPressed;
/********************************
* Chapter 5
*********************************/
/**
* Changes the style of a single element by id
*/
function setStyleById(element, styles) {
// Retrieve an object reference
if(!(element = $(element))) return false;
// Loop through the styles object an apply each property
for (property in styles) {
if(!styles.hasOwnProperty(property)) continue;
if(element.style.setProperty) {
//DOM2 Style method
element.style.setProperty(
uncamelize(property,'-'),styles[property],null);
} else {
//Alternative method
element.style[camelize(property)] = styles[property];
}
}
return true;
}
window['ADS']['setStyle'] = setStyleById;
window['ADS']['setStyleById'] = setStyleById;
/**
* Changes the style of multiple elements by class name
*/
function setStylesByClassName(parent, tag, className, styles) {
if(!(parent = $(parent))) return false;
var elements = getElementsByClassName(className, tag, parent);
for (var e = 0 ; e < elements.length ; e++) {
setStyleById(elements[e], styles);
}
return true;
}
window['ADS']['setStylesByClassName'] = setStylesByClassName;
/**
* Changes the style of multiple elements by tag name
*/
function setStylesByTagName(tagname, styles, parent) {
parent = $(parent) || document;
var elements = parent.getElementsByTagName(tagname);
for (var e = 0 ; e < elements.length ; e++) {
setStyleById(elements[e], styles);
}
}
window['ADS']['setStylesByTagName'] = setStylesByTagName;
/**
* Retrieves the classes as an array
*/
function getClassNames(element) {
if(!(element = $(element))) return false;
// Replace multiple spaces with one space and then
// split the classname on spaces
return element.className.replace(/\s+/,' ').split(' ');
};
window['ADS']['getClassNames'] = getClassNames;
/**
* Check if a class exists on an element
*/
function hasClassName(element, className) {
if(!(element = $(element))) return false;
var classes = getClassNames(element);
for (var i = 0; i < classes.length; i++) {
// Check if the className matches and return true if it does
if (classes[i] === className) { return true; }
}
return false;
};
window['ADS']['hasClassName'] = hasClassName;
/**
* Add a class to an element
*/
function addClassName(element, className) {
if(!(element = $(element))) return false;
// Append the classname to the end of the current className
// If there is no className, don't include the space
element.className += (element.className ? ' ' : '') + className;
return true;
};
window['ADS']['addClassName'] = addClassName;
/**
* remove a class from an element
*/
function removeClassName(element, className) {
if(!(element = $(element))) return false;
var classes = getClassNames(element);
var length = classes.length
//loop through the array in reverse, deleting matching items
// You loop in reverse as you're deleting items from
// the array which will shorten it.
for (var i = length-1; i >= 0; i--) {
if (classes[i] === className) { delete(classes[i]); }
}
element.className = classes.join(' ');
return (length == classes.length ? false : true);
};
window['ADS']['removeClassName'] = removeClassName;
/**
* Add a new stylesheet
*/
function addStyleSheet(url,media) {
media = media || 'screen';
var link = document.createElement('LINK');
link.setAttribute('rel','stylesheet');
link.setAttribute('type','text/css');
link.setAttribute('href',url);
link.setAttribute('media',media);
document.getElementsByTagName('head')[0].appendChild(link);
}
window['ADS']['addStyleSheet'] = addStyleSheet;
/**
* Remove a stylesheet
*/
function removeStyleSheet(url,media) {
var styles = getStyleSheets(url,media);
for(var i = 0 ; i < styles.length ; i++) {
var node = styles[i].ownerNode || styles[i].owningElement;
// Disable the stylesheet
styles[i].disabled = true;
// Remove the node
node.parentNode.removeChild(node);
}
}
window['ADS']['removeStyleSheet'] = removeStyleSheet;
/**
* Retrieve an array of all the stylesheets by URL
*/
function getStyleSheets(url,media) {
var sheets = [];
for(var i = 0 ; i < document.styleSheets.length ; i++) {
if (url && document.styleSheets[i].href.indexOf(url) == -1) { continue; }
if(media) {
// Normaizle the media strings
media = media.replace(/,\s*/,',');
var sheetMedia;
if(document.styleSheets[i].media.mediaText) {
// DOM mehtod
sheetMedia = document.styleSheets[i].media.mediaText.replace(/,\s*/,',');
// Safari adds an extra comma and space
sheetMedia = sheetMedia.replace(/,\s*$/,'');
} else {
// MSIE
sheetMedia = document.styleSheets[i].media.replace(/,\s*/,',');
}
// Skip it if the media don't match
if (media != sheetMedia) { continue; }
}
sheets.push(document.styleSheets[i]);
}
return sheets;
}
window['ADS']['getStyleSheets'] = getStyleSheets;
/**
* Edit a CSS rule
*/
function editCSSRule(selector,styles,url,media) {
var styleSheets = (typeof url == 'array' ? url : getStyleSheets(url,media));
for ( i = 0; i < styleSheets.length; i++ ) {
// Retrieve the list of rules
// The DOM2 Style method is styleSheets[i].cssRules
// The MSIE method is styleSheets[i].rules
var rules = styleSheets[i].cssRules || styleSheets[i].rules;
if (!rules) { continue; }
// Convert to uppercase as MSIIE defaults to UPPERCASE tags.
// this could cause conflicts if you're using case sensetive ids
selector = selector.toUpperCase();
for(var j = 0; j < rules.length; j++) {
// Check if it matches
if(rules[j].selectorText.toUpperCase() == selector) {
for (property in styles) {
if(!styles.hasOwnProperty(property)) { continue; }
// Set the new style property
rules[j].style[camelize(property)] = styles[property];
}
}
}
}
}
window['ADS']['editCSSRule'] = editCSSRule;
/**
* Add a CSS rule
*/
function addCSSRule(selector, styles, index, url, media) {
var declaration = '';
// Build the declaration string from the style object
for (property in styles) {
if(!styles.hasOwnProperty(property)) { continue; }
declaration += property + ':' + styles[property] + '; ';
}
var styleSheets = (typeof url == 'array' ? url : getStyleSheets(url,media));
var newIndex;
for(var i = 0 ; i < styleSheets.length ; i++) {
// Add the rule
if(styleSheets[i].insertRule) {
// The DOM2 Style method
// index = length is the end of the list
newIndex = (index >= 0 ? index : styleSheets[i].cssRules.length);
styleSheets[i].insertRule(selector + ' { ' + declaration + ' } ',
newIndex);
} else if(styleSheets[i].addRule) {
// The Microsoft method
// index = -1 is the end of the list
newIndex = (index >= 0 ? index : -1);
styleSheets[i].addRule(selector, declaration, newIndex);
}
}
}
window['ADS']['addCSSRule'] = addCSSRule;
/**
* retrieve the computed style of an element
*/
function getStyle(element,property) {
if(!(element = $(element)) || !property) return false;
// Check for the value in the element's style property
var value = element.style[camelize(property)];
if (!value) {
// Retrieve the computed style value
if (document.defaultView && document.defaultView.getComputedStyle) {
// The DOM method
var css = document.defaultView.getComputedStyle(element, null);
value = css ? css.getPropertyValue(property) : null;
} else if (element.currentStyle) {
// The MSIE method
value = element.currentStyle[camelize(property)];
}
}
// Return an empty string rather than auto so that you don't
// have to check for auto values
return value == 'auto' ? '' : value;
}
window['ADS']['getStyle'] = getStyle;
window['ADS']['getStyleById'] = getStyle;
/********************************
* Chapter 7: Case Study
*********************************/
// no code added in Chapter 6
/********************************
* Chapter 7
*********************************/
/*
parseJSON(string,filter)
A slightly modified version of the public domain method
at http://www.json.org/json.js This method parses a JSON text
to produce an object or array. It can throw a
SyntaxError exception.
The optional filter parameter is a function which can filter and
transform the results. It receives each of the keys and values, and
its return value is used instead of the original value. If it
returns what it received, then structure is not modified. If it
returns undefined then the member is deleted.
Example:
// Parse the text. If a key contains the string 'date' then
// convert the value to a date.
myData = parseJSON(string,function (key, value) {
return key.indexOf('date') >= 0 ? new Date(value) : value;
});
*/
function parseJSON(s,filter) {
var j;
function walk(k, v) {
var i;
if (v && typeof v === 'object') {
for (i in v) {
if (v.hasOwnProperty(i)) {
v[i] = walk(i, v[i]);
}
}
}
return filter(k, v);
}
// Parsing happens in three stages. In the first stage, we run the
// text against a regular expression which looks for non-JSON
// characters. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause
// mutation. But just to be safe, we will reject all unexpected
// characters.
if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
test(s)) {
// In the second stage we use the eval function to compile the text
// into a JavaScript structure. The '{' operator is subject to a
// syntactic ambiguity in JavaScript: it can begin a block or an
// object literal. We wrap the text in parens to eliminate
// the ambiguity.
try {
j = eval('(' + s + ')');
} catch (e) {
throw new SyntaxError("parseJSON");
}
} else {
throw new SyntaxError("parseJSON");
}
// In the optional third stage, we recursively walk the new structure,
// passing each name/value pair to a filter function for possible
// transformation.
if (typeof filter === 'function') {
j = walk('', j);
}
return j;
};
/**
* Setup the various parts of an XMLHttpRequest Object
*/
function getRequestObject(url,options) {
// Initialize the request object
var req = false;
if(window.XMLHttpRequest) {
var req = new window.XMLHttpRequest();
} else if (window.ActiveXObject) {
var req = new window.ActiveXObject('Microsoft.XMLHTTP');
}
if(!req) return false;
// Define the default options
options = options || {};
options.method = options.method || 'GET';
options.send = options.send || null;
// Define the various listeners for each state of the request
req.onreadystatechange = function() {
switch (req.readyState) {
case 1:
// Loading
if(options.loadListener) {
options.loadListener.apply(req,arguments);
}
break;
case 2:
// Loaded
if(options.loadedListener) {
options.loadedListener.apply(req,arguments);
}
break;
case 3:
// Interactive
if(options.ineractiveListener) {
options.ineractiveListener.apply(req,arguments);
}
break;
case 4:
// Complete
// if aborted FF throws errors
try {
if (req.status && req.status == 200) {
// Specific listeners for content-type
// The Content-Type header can include the charset:
// Content-Type: text/html; charset=ISO-8859-4
// So we'll use a match to extract the part we need.
var contentType = req.getResponseHeader('Content-Type');
var mimeType = contentType.match(/\s*([^;]+)\s*(;|$)/i)[1];
switch(mimeType) {
case 'text/javascript':
case 'application/javascript':
// The response is JavaScript so use the
// req.responseText as the argument to the callback
if(options.jsResponseListener) {
options.jsResponseListener.call(
req,
req.responseText
);
}
break;
case 'application/json':
// The response is json so parse