summaryrefslogtreecommitdiff
path: root/tests/FunctionalTests/selenium/selenium-browserbot.js
blob: f200368701e10e9387343d43c64d5c22794e2c4b (plain)
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
1001
/*
* Copyright 2004 ThoughtWorks, Inc
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*/

/*
* This script provides the Javascript API to drive the test application contained within
* a Browser Window.
* TODO:
*    Add support for more events (keyboard and mouse)
*    Allow to switch "user-entry" mode from mouse-based to keyboard-based, firing different
*          events in different modes.
*/

// The window to which the commands will be sent.  For example, to click on a
// popup window, first select that window, and then do a normal click command.


// Although it's generally better web development practice not to use browser-detection
// (feature detection is better), the subtle browser differences that Selenium has to
// work around seem to make it necessary. Maybe as we learn more about what we need,
// we can do this in a more "feature-centric" rather than "browser-centric" way.
// TODO we should probably reuse an available browser-detection library
var browserName=navigator.appName;
var isIE = (browserName =="Microsoft Internet Explorer");
var isKonqueror = (browserName == "Konqueror");
var isSafari = (navigator.userAgent.indexOf('Safari') != -1);

// Get the Gecko version as an 8 digit date.
var geckoResult = /^Mozilla\/5\.0 .*Gecko\/(\d{8}).*$/.exec(navigator.userAgent);
var geckoVersion = geckoResult == null ? null : geckoResult[1];

BrowserBot = function(frame) {
    this.frame = frame;
    this.currentPage = null;
    this.currentWindowName = null;

    this.modalDialogTest = null;
    this.recordedAlerts = new Array();
    this.recordedConfirmations = new Array();
    this.recordedPrompts = new Array();
    this.openedWindows = {};
    this.nextConfirmResult = true;
    this.nextPromptResult = '';
    this.newPageLoaded = false;

    var self = this;
    this.recordPageLoad = function() {
        LOG.debug("Page load detected, location=" + self.getCurrentWindow().location);
        self.currentPage = null;
        self.newPageLoaded = true;
    };

    this.isNewPageLoaded = function() {
        return self.newPageLoaded;
    };
};

BrowserBot.createForFrame = function(frame) {
    var browserbot;
    if (isIE) {
        browserbot = new IEBrowserBot(frame);
    }
    else if (isKonqueror) {
        browserbot = new KonquerorBrowserBot(frame);
    }
    else if (isSafari) {
        browserbot = new SafariBrowserBot(frame);
    }
    else {
        // Use mozilla by default
        browserbot = new MozillaBrowserBot(frame);
    }

    // Modify the test IFrame so that page loads are detected.
    addLoadListener(browserbot.getFrame(), browserbot.recordPageLoad);
    return browserbot;
};

BrowserBot.prototype.doModalDialogTest = function(test) {
    this.modalDialogTest = test;
};

BrowserBot.prototype.cancelNextConfirmation = function() {
    this.nextConfirmResult = false;
};

BrowserBot.prototype.setNextPromptResult = function(result) {
    this.nextPromptResult = result;
};

BrowserBot.prototype.hasAlerts = function() {
    return (this.recordedAlerts.length > 0) ;
};

BrowserBot.prototype.getNextAlert = function() {
    return this.recordedAlerts.shift();
};

BrowserBot.prototype.hasConfirmations = function() {
    return (this.recordedConfirmations.length > 0) ;
};

BrowserBot.prototype.getNextConfirmation = function() {
    return this.recordedConfirmations.shift();
};

BrowserBot.prototype.hasPrompts = function() {
    return (this.recordedPrompts.length > 0) ;
};

BrowserBot.prototype.getNextPrompt = function() {
    return this.recordedPrompts.shift();
};

BrowserBot.prototype.getFrame = function() {
    return this.frame;
};

BrowserBot.prototype.selectWindow = function(target) {
    // we've moved to a new page - clear the current one
    this.currentPage = null;
    this.currentWindowName = null;
    if (target && target != "null") {
        // If window exists
        if (this.getTargetWindow(target)) {
            this.currentWindowName = target;
        }
    }
};

BrowserBot.prototype.openLocation = function(target) {
    // We're moving to a new page - clear the current one
    this.currentPage = null;
    this.newPageLoaded = false;

    this.setIFrameLocation(this.getFrame(), target);
};

BrowserBot.prototype.setIFrameLocation = function(iframe, location) {
    iframe.src = location;
};

BrowserBot.prototype.getCurrentPage = function() {
    if (this.currentPage == null) {
        var testWindow = this.getCurrentWindow();
        this.modifyWindowToRecordPopUpDialogs(testWindow, this);
        this.modifySeparateTestWindowToDetectPageLoads(testWindow);
        this.currentPage = PageBot.createForWindow(testWindow);
        this.newPageLoaded = false;
    }

    return this.currentPage;
};

BrowserBot.prototype.modifyWindowToRecordPopUpDialogs = function(windowToModify, browserBot) {
    windowToModify.alert = function(alert) {
        browserBot.recordedAlerts.push(alert);
    };

    windowToModify.confirm = function(message) {
        browserBot.recordedConfirmations.push(message);
        var result = browserBot.nextConfirmResult;
        browserBot.nextConfirmResult = true;
        return result;
    };

    windowToModify.prompt = function(message) {
        browserBot.recordedPrompts.push(message);
        var result = !browserBot.nextConfirmResult ? null : browserBot.nextPromptResult;
        browserBot.nextConfirmResult = true;
        browserBot.nextPromptResult = '';
        return result;
    };

    // Keep a reference to all popup windows by name
    // note that in IE the "windowName" argument must be a valid javascript identifier, it seems.
    var originalOpen = windowToModify.open;
    windowToModify.open = function(url, windowName, windowFeatures, replaceFlag) {
        var openedWindow = originalOpen(url, windowName, windowFeatures, replaceFlag);
        selenium.browserbot.openedWindows[windowName] = openedWindow;
        return openedWindow;
    };
};

/**
 * The main IFrame has a single, long-lived onload handler that clears
 * Browserbot.currentPage and sets the "newPageLoaded" flag. For separate
 * windows, we need to attach a handler each time. This uses the
 * "callOnWindowPageTransition" mechanism, which is implemented differently
 * for different browsers.
 */
BrowserBot.prototype.modifySeparateTestWindowToDetectPageLoads = function(windowToModify) {
    if (this.currentWindowName != null) {
        this.callOnWindowPageTransition(this.recordPageLoad, windowToModify);
    }
};

/**
 * Call the supplied function when a the current page unloads and a new one loads.
 * This is done with an "unload" handler which attaches a "load" handler.
 */
BrowserBot.prototype.callOnWindowPageTransition = function(loadFunction, windowObject) {
    var attachLoadListener = function() {
        if (windowObject && !windowObject.closed) {
            addLoadListener(windowObject, loadFunction);
        }
    };

    var unloadFunction = function() {
        window.setTimeout(attachLoadListener, 0);
    };
    addUnloadListener(windowObject, unloadFunction);
};

BrowserBot.prototype.getContentWindow = function() {
    return this.getFrame().contentWindow || frames[this.getFrame().id];
};

BrowserBot.prototype.getTargetWindow = function(windowName) {
    LOG.debug("getTargetWindow(" + windowName + ")");
    // First look in the map of opened windows
    var targetWindow = this.openedWindows[windowName];
    if (!targetWindow) {
        var evalString = "this.getContentWindow().window." + windowName;
        targetWindow = eval(evalString);
    }
    if (!targetWindow) {
        throw new SeleniumError("Window does not exist");
    }
    return targetWindow;
};

BrowserBot.prototype.getCurrentWindow = function() {
    var testWindow = this.getContentWindow().window;
    if (this.currentWindowName != null) {
        testWindow = this.getTargetWindow(this.currentWindowName);
    }
    return testWindow;
};

function MozillaBrowserBot(frame) {
    BrowserBot.call(this, frame);
}
MozillaBrowserBot.prototype = new BrowserBot;

function KonquerorBrowserBot(frame) {
    BrowserBot.call(this, frame);
}
KonquerorBrowserBot.prototype = new BrowserBot;

KonquerorBrowserBot.prototype.setIFrameLocation = function(iframe, location) {
    // Window doesn't fire onload event when setting src to the current value,
    // so we set it to blank first.
    iframe.src = "about:blank";
    iframe.src = location;
};

/**
 * Call the supplied function when a the current page unloads and a new one loads.
 * This is done by polling continuously until the document changes and is fully loaded.
 */
KonquerorBrowserBot.prototype.callOnWindowPageTransition = function(loadFunction, windowObject) {
    // Since the unload event doesn't fire in Safari 1.3, we start polling immediately
    // This works in Konqueror as well
    if (windowObject && !windowObject.closed) {
        LOG.debug("Starting pollForLoad");
        this.pollForLoad(loadFunction, windowObject, windowObject.document);
    }
};

/**
 * For Konqueror (and Safari), we can't catch the onload event for a separate window (as opposed to an IFrame)
 * So we set up a polling timer that will keep checking the readyState of the document until it's complete.
 * Since we might call this before the original page is unloaded, we check to see that the completed document
 * is different from the original one.
 */
KonquerorBrowserBot.prototype.pollForLoad = function(loadFunction, windowObject, originalDocument) {
    if (windowObject.closed) {
        return;
    }

    var sameDoc = (originalDocument === windowObject.document);
    var rs = windowObject.document.readyState;

    if (!sameDoc && rs == 'complete') {
        LOG.debug("pollForLoad complete: " + rs + " (" + sameDoc + ")");
        loadFunction();
        return;
    }
    var self = this;
    LOG.debug("pollForLoad continue");
    window.setTimeout(function() {self.pollForLoad(loadFunction, windowObject, originalDocument);}, 500);
};

function SafariBrowserBot(frame) {
    BrowserBot.call(this, frame);
}
SafariBrowserBot.prototype = new BrowserBot;

SafariBrowserBot.prototype.setIFrameLocation = KonquerorBrowserBot.prototype.setIFrameLocation;
SafariBrowserBot.prototype.callOnWindowPageTransition = KonquerorBrowserBot.prototype.callOnWindowPageTransition;
SafariBrowserBot.prototype.pollForLoad = KonquerorBrowserBot.prototype.pollForLoad;

function IEBrowserBot(frame) {
    BrowserBot.call(this, frame);
}
IEBrowserBot.prototype = new BrowserBot;
IEBrowserBot.prototype.callOnWindowPageTransition = KonquerorBrowserBot.prototype.callOnWindowPageTransition;
IEBrowserBot.prototype.pollForLoad = KonquerorBrowserBot.prototype.pollForLoad;

IEBrowserBot.prototype.modifyWindowToRecordPopUpDialogs = function(windowToModify, browserBot) {
    BrowserBot.prototype.modifyWindowToRecordPopUpDialogs(windowToModify, browserBot);

    // we will call the previous version of this method from within our own interception
    oldShowModalDialog = windowToModify.showModalDialog;

    windowToModify.showModalDialog = function(url, args, features) {
        // Get relative directory to where TestRunner.html lives
        // A risky assumption is that the user's TestRunner is named TestRunner.html
        var doc_location = document.location.toString();
        var end_of_base_ref = doc_location.indexOf('TestRunner.html');
        var base_ref = doc_location.substring(0, end_of_base_ref);

        var fullURL = base_ref + "TestRunner.html?singletest=" + escape(browserBot.modalDialogTest) + "&autoURL=" + escape(url) + "&runInterval=" + runInterval;
        browserBot.modalDialogTest = null;

        var returnValue = oldShowModalDialog(fullURL, args, features);
        return returnValue;
    };
};

SafariBrowserBot.prototype.modifyWindowToRecordPopUpDialogs = function(windowToModify, browserBot) {
    BrowserBot.prototype.modifyWindowToRecordPopUpDialogs(windowToModify, browserBot);

    var originalOpen = windowToModify.open;
    /*
     * Safari seems to be broken, so that when we manually trigger the onclick method
     * of a button/href, any window.open calls aren't resolved relative to the app location.
     * So here we replace the open() method with one that does resolve the url correctly.
     */
    windowToModify.open = function(url, windowName, windowFeatures, replaceFlag) {

        if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/")) {
            return originalOpen(url, windowName, windowFeatures, replaceFlag);
        }

        // Reduce the current path to the directory
        var currentPath = windowToModify.location.pathname || "/";
        currentPath = currentPath.replace(/\/[^\/]*$/, "/");

        // Remove any leading "./" from the new url.
        url = url.replace(/^\.\//, "");

        newUrl = currentPath + url;

        return originalOpen(newUrl, windowName, windowFeatures, replaceFlag);
    };
};

PageBot = function(pageWindow) {
    if (pageWindow) {
        this.currentWindow = pageWindow;
        this.currentDocument = pageWindow.document;
        this.location = pageWindow.location;
        this.title = function() {return this.currentDocument.title;};
    }

    // Register all locateElementBy* functions
    // TODO - don't do this in the constructor - only needed once ever
    this.locationStrategies = {};
    for (var functionName in this) {
        var result = /^locateElementBy([A-Z].+)$/.exec(functionName);
        if (result != null) {
            var locatorFunction = this[functionName];
            if (typeof(locatorFunction) != 'function') {
                continue;
            }
            // Use a specified prefix in preference to one generated from
            // the function name
            var locatorPrefix = locatorFunction.prefix || result[1].toLowerCase();
            this.locationStrategies[locatorPrefix] = locatorFunction;
        }
    }

    /**
     * Find a locator based on a prefix.
     */
    this.findElementBy = function(locatorType, locator, inDocument) {
        var locatorFunction = this.locationStrategies[locatorType];
        if (! locatorFunction) {
            throw new SeleniumError("Unrecognised locator type: '" + locatorType + "'");
        }
        return locatorFunction.call(this, locator, inDocument);
    };

    /**
     * The implicit locator, that is used when no prefix is supplied.
     */
    this.locationStrategies['implicit'] = function(locator, inDocument) {
        if (locator.startsWith('//')) {
            return this.locateElementByXPath(locator, inDocument);
        } 
        if (locator.startsWith('document.')) {
            return this.locateElementByDomTraversal(locator, inDocument);
        }
        return this.locateElementByIdentifier(locator, inDocument);
    };
    
};

PageBot.createForWindow = function(windowObject) {
    if (isIE) {
        return new IEPageBot(windowObject);
    }
    else if (isKonqueror) {
        return new KonquerorPageBot(windowObject);
    }
    else if (isSafari) {
        return new SafariPageBot(windowObject);
    }
    else {
        // Use mozilla by default
        return new MozillaPageBot(windowObject);
    }
};

MozillaPageBot = function(pageWindow) {
    PageBot.call(this, pageWindow);
};
MozillaPageBot.prototype = new PageBot();

KonquerorPageBot = function(pageWindow) {
    PageBot.call(this, pageWindow);
};
KonquerorPageBot.prototype = new PageBot();

SafariPageBot = function(pageWindow) {
    PageBot.call(this, pageWindow);
};
SafariPageBot.prototype = new PageBot();

IEPageBot = function(pageWindow) {
    PageBot.call(this, pageWindow);
};
IEPageBot.prototype = new PageBot();

/*
* Finds an element on the current page, using various lookup protocols
*/
PageBot.prototype.findElement = function(locator) {
    var locatorType = 'implicit';
    var locatorString = locator;
    
    // If there is a locator prefix, use the specified strategy
    var result = locator.match(/^([A-Za-z]+)=(.+)/);
    if (result) {
        locatorType = result[1].toLowerCase();
        locatorString = result[2];
    }

    var element = this.findElementBy(locatorType, locatorString, this.currentDocument);
    if (element != null) {
        return element;
    }
    for (var i = 0; i < this.currentWindow.frames.length; i++) {
        element = this.findElementBy(locatorType, locatorString, this.currentWindow.frames[i].document);
        if (element != null) {
            return element;
        }
    }

    // Element was not found by any locator function.
    throw new SeleniumError("Element " + locator + " not found");
};

/**
 * In non-IE browsers, getElementById() does not search by name.  Instead, we
 * we search separately by id and name.
 */
PageBot.prototype.locateElementByIdentifier = function(identifier, inDocument) {
    return PageBot.prototype.locateElementById(identifier, inDocument)
            || PageBot.prototype.locateElementByName(identifier, inDocument)
            || null;
};

/**
 * In IE, getElementById() also searches by name - this is an optimisation for IE.
 */
IEPageBot.prototype.locateElementByIdentifer = function(identifier, inDocument) {
    return inDocument.getElementById(identifier);
};

/**
 * Find the element with id - can't rely on getElementById, coz it returns by name as well in IE..
 */
PageBot.prototype.locateElementById = function(identifier, inDocument) {
    var element = inDocument.getElementById(identifier);
    if (element && element.id === identifier) {
        return element;
    }
    else {
        return null;
    }
};

/**
 * Find an element by name, refined by (optional) element-filter
 * expressions.
 */
PageBot.prototype.locateElementByName = function(locator, document) {
    var elements = document.getElementsByTagName("*");

    var filters = locator.split(' ');
    filters[0] = 'name=' + filters[0];

    while (filters.length) {
        var filter = filters.shift();
        elements = this.selectElements(filter, elements, 'value');
    }

    if (elements.length > 0) {
        return elements[0];
    }
    return null;
};

/**
* Finds an element using by evaluating the "document.*" string against the
* current document object. Dom expressions must begin with "document."
*/
PageBot.prototype.locateElementByDomTraversal = function(domTraversal, inDocument) {
    if (domTraversal.indexOf("document.") != 0) {
        return null;
    }

    // Trim the leading 'document'
    domTraversal = domTraversal.substr(9);
    var locatorScript = "inDocument." + domTraversal;
    var element = eval(locatorScript);

    if (!element) {
        return null;
    }

    return element;
};
PageBot.prototype.locateElementByDomTraversal.prefix = "dom";

/**
* Finds an element identified by the xpath expression. Expressions _must_
* begin with "//".
*/
PageBot.prototype.locateElementByXPath = function(xpath, inDocument) {

    // Trim any trailing "/": not valid xpath, and remains from attribute
    // locator.
    if (xpath.charAt(xpath.length - 1) == '/') {
        xpath = xpath.slice(0, -1);
    }

    // Handle //tag
    var match = xpath.match(/^\/\/(\w+|\*)$/); 
    if (match) {
        var elements = inDocument.getElementsByTagName(match[1].toUpperCase()); 
        if (elements == null) return null;
        return elements[0];
    }

    // Handle //tag[@attr='value']
    var match = xpath.match(/^\/\/(\w+|\*)\[@(\w+)=('([^\']+)'|"([^\"]+)")\]$/); 
    if (match) {
        return this.findElementByTagNameAndAttributeValue(
            inDocument,
            match[1].toUpperCase(),
            match[2].toLowerCase(),
            match[3].slice(1, -1)
        );
    }

    // Handle //tag[text()='value']
    var match = xpath.match(/^\/\/(\w+|\*)\[text\(\)=('([^\']+)'|"([^\"]+)")\]$/); 
    if (match) {
        return this.findElementByTagNameAndText(
            inDocument,
            match[1].toUpperCase(),
            match[2].slice(1, -1)
        );
    }

    return this.findElementUsingFullXPath(xpath, inDocument);
};

PageBot.prototype.findElementByTagNameAndAttributeValue = function(
    inDocument, tagName, attributeName, attributeValue
) {
    if (isIE && attributeName == "class") {
        attributeName = "className";
    }
    var elements = inDocument.getElementsByTagName(tagName); 
    for (var i = 0; i < elements.length; i++) { 
        var elementAttr = elements[i].getAttribute(attributeName); 
        if (elementAttr == attributeValue) { 
            return elements[i]; 
        } 
    } 
    return null;
};

PageBot.prototype.findElementByTagNameAndText = function(
    inDocument, tagName, text
) {
    var elements = inDocument.getElementsByTagName(tagName); 
    for (var i = 0; i < elements.length; i++) { 
        if (getText(elements[i]) == text) { 
            return elements[i]; 
        } 
    } 
    return null;
};

PageBot.prototype.findElementUsingFullXPath = function(xpath, inDocument) {
    if (isIE && !inDocument.evaluate) {
        addXPathSupport(inDocument);
    }

	alert("find by xpath");

    // Use document.evaluate() if it's available
    if (inDocument.evaluate) {
        return inDocument.evaluate(xpath, inDocument, null, 0, null).iterateNext();
    }



    // If not, fall back to slower JavaScript implementation
    var context = new XPathContext();

    context.expressionContextNode = inDocument;
    var xpathResult = new XPathParser().parse(xpath).evaluate(context);
    if (xpathResult && xpathResult.toArray) {
        return xpathResult.toArray()[0];
    }
    return null;
};

/**
* Finds a link element with text matching the expression supplied. Expressions must
* begin with "link:".
*/
PageBot.prototype.locateElementByLinkText = function(linkText, inDocument) {
    var links = inDocument.getElementsByTagName('a');
    for (var i = 0; i < links.length; i++) {
        var element = links[i];
        if (PatternMatcher.matches(linkText, getText(element))) {
            return element;
        }
    }
    return null;
};
PageBot.prototype.locateElementByLinkText.prefix = "link";

/**
* Returns an attribute based on an attribute locator. This is made up of an element locator
* suffixed with @attribute-name.
*/
PageBot.prototype.findAttribute = function(locator) {
    // Split into locator + attributeName
    var attributePos = locator.lastIndexOf("@");
    var elementLocator = locator.slice(0, attributePos);
    var attributeName = locator.slice(attributePos + 1);

    // Find the element.
    var element = this.findElement(elementLocator);

    // Handle missing "class" attribute in IE.
    if (isIE && attributeName == "class") {
        attributeName = "className";
    }

    // Get the attribute value.
    var attributeValue = element.getAttribute(attributeName);

    return attributeValue ? attributeValue.toString() : null;
};

/*
* Select the specified option and trigger the relevant events of the element.
*/
PageBot.prototype.selectOption = function(element, option) {
    triggerEvent(element, 'focus', false);
    if (!option.selected) {
        option.selected = true;
        triggerEvent(element, 'change', true);
    }
    triggerEvent(element, 'blur', false);
};

PageBot.prototype.replaceText = function(element, stringValue) {
    triggerEvent(element, 'focus', false);
    triggerEvent(element, 'select', true);
    element.value=stringValue;
    triggerEvent(element, 'change', true);
    triggerEvent(element, 'blur', false);
};

MozillaPageBot.prototype.clickElement = function(element) {

    triggerEvent(element, 'focus', false);

    // Add an event listener that detects if the default action has been prevented.
    // (This is caused by a javascript onclick handler returning false)
    var preventDefault = false;
    if (geckoVersion) {
        element.addEventListener("click", function(evt) {preventDefault = evt.getPreventDefault();}, false);
    }

    // Trigger the click event.
    triggerMouseEvent(element, 'click', true);

    // In FireFox < 1.0 Final, and Mozilla <= 1.7.3, just sending the click event is enough.
    // But in newer versions, we need to do it ourselves.
    var needsProgrammaticClick = (geckoVersion > '20041025');
    // Perform the link action if preventDefault was set.
    if (needsProgrammaticClick && !preventDefault) {
        // Try the element itself, as well as it's parent - this handles clicking images inside links.
        if (element.href) {
            this.currentWindow.location.href = element.href;
        }
        else if (element.parentNode && element.parentNode.href) {
            this.currentWindow.location.href = element.parentNode.href;
        }
    }

    if (this.windowClosed()) {
        return;
    }

    triggerEvent(element, 'blur', false);
};

KonquerorPageBot.prototype.clickElement = function(element) {

    triggerEvent(element, 'focus', false);

    if (element.click) {
        element.click();
    }
    else {
        triggerMouseEvent(element, 'click', true);
    }

    if (this.windowClosed()) {
        return;
    }

    triggerEvent(element, 'blur', false);
};

SafariPageBot.prototype.clickElement = function(element) {

    triggerEvent(element, 'focus', false);

    var wasChecked = element.checked;
    
    // For form element it is simple.
    if (element.click) {
        element.click();
    }
    // For links and other elements, event emulation is required.
    else {
        triggerEvent(element, 'click', true);

        // Unfortunately, triggering the event doesn't seem to activate onclick handlers.
        // We currently call onclick for the link, but I'm guessing that the onclick for containing
        // elements is not being called.
        var success = true;
        if (element.onclick) {
            var evt = document.createEvent('HTMLEvents');
            evt.initEvent('click', true, true);
            var onclickResult = element.onclick(evt);
            if (onclickResult === false) {
                success = false;
            }
        }

        if (success) {
            // Try the element itself, as well as it's parent - this handles clicking images inside links.
            if (element.href) {
                this.currentWindow.location.href = element.href;
            }
            else if (element.parentNode.href) {
                this.currentWindow.location.href = element.parentNode.href;
            } else {
                // This is true for buttons outside of forms, and maybe others.
                LOG.warn("Ignoring 'click' call for button outside form, or link without href."
                        + "Using buttons without an enclosing form can cause wierd problems with URL resolution in Safari." );
                // I implemented special handling for window.open, but unfortunately this behaviour is also displayed
                // when we have a button without an enclosing form that sets document.location in the onclick handler.
                // The solution is to always use an enclosing form for a button.
            }
        }
    }

    // Onchange event is not triggered automatically in Safari.
    if (isDefined(element.checked) && wasChecked != element.checked) {
        triggerEvent(element, 'change', true);
    }

    if (this.windowClosed()) {
        return;
    }

    triggerEvent(element, 'blur', false);
};

IEPageBot.prototype.clickElement = function(element) {

    triggerEvent(element, 'focus', false);

    var wasChecked = element.checked;

    // Set a flag that records if the page will unload - this isn't always accurate, because
    // <a href="javascript:alert('foo'):"> triggers the onbeforeunload event, even thought the page won't unload
    var pageUnloading = false;
    var pageUnloadDetector = function() {pageUnloading = true;};
    this.currentWindow.attachEvent("onbeforeunload", pageUnloadDetector);

    element.click();

    // If the page is going to unload - still attempt to fire any subsequent events.
    // However, we can't guarantee that the page won't unload half way through, so we need to handle exceptions.
    try {
        this.currentWindow.detachEvent("onbeforeunload", pageUnloadDetector);

        if (this.windowClosed()) {
            return;
        }

        // Onchange event is not triggered automatically in IE.
        if (isDefined(element.checked) && wasChecked != element.checked) {
            triggerEvent(element, 'change', true);
        }

        triggerEvent(element, 'blur', false);
    }
    catch (e) {
        // If the page is unloading, we may get a "Permission denied" or "Unspecified error".
        // Just ignore it, because the document may have unloaded.
        if (pageUnloading) {
            LOG.warn("Caught exception when firing events on unloading page: " + e.message);
            return;
        }
        throw e;
    }
};

PageBot.prototype.windowClosed = function(element) {
    return this.currentWindow.closed;
};

PageBot.prototype.bodyText = function() {
    return getText(this.currentDocument.body);
};

PageBot.prototype.getAllButtons = function() {
    var elements = this.currentDocument.getElementsByTagName('input');
    var result = '';

    for (var i = 0; i < elements.length; i++) {
        if (elements[i].type == 'button' || elements[i].type == 'submit' || elements[i].type == 'reset') {
            result += elements[i].id;

            result += ',';
        }
    }

    return result;
};


PageBot.prototype.getAllFields = function() {
    var elements = this.currentDocument.getElementsByTagName('input');
    var result = '';

    for (var i = 0; i < elements.length; i++) {
        if (elements[i].type == 'text') {
            result += elements[i].id;

            result += ',';
        }
    }

    return result;
};

PageBot.prototype.getAllLinks = function() {
    var elements = this.currentDocument.getElementsByTagName('a');
    var result = '';

    for (var i = 0; i < elements.length; i++) {
        result += elements[i].id;

        result += ',';
    }

    return result;
};

PageBot.prototype.setContext = function(strContext) {
     //set the current test title
    context.innerHTML=strContext;
};

function isDefined(value) {
    return typeof(value) != undefined;
}

PageBot.prototype.goBack = function() {
    this.currentWindow.history.back();
};

PageBot.prototype.goForward = function() {
    this.currentWindow.history.forward();
};

PageBot.prototype.close = function() {
    this.currentWindow.close();
};

/**
 * Refine a list of elements using a filter.
 */
PageBot.prototype.selectElementsBy = function(filterType, filter, elements) {
    var filterFunction = PageBot.filterFunctions[filterType];
    if (! filterFunction) {
        throw new SeleniumError("Unrecognised element-filter type: '" + filterType + "'");
    }

    return filterFunction(filter, elements);
};

PageBot.filterFunctions = {}; 

PageBot.filterFunctions.name = function(name, elements) {
    var selectedElements = [];
    for (var i = 0; i < elements.length; i++) {
        if (elements[i].name === name) {
            selectedElements.push(elements[i]);
        }
    }
    return selectedElements;
};

PageBot.filterFunctions.value = function(value, elements) {
    var selectedElements = [];
    for (var i = 0; i < elements.length; i++) {
        if (elements[i].value === value) {
            selectedElements.push(elements[i]);
        }
    }
    return selectedElements;
};

PageBot.filterFunctions.index = function(index, elements) {
    index = Number(index);
    if (isNaN(index) || index < 0) {
        throw new SeleniumError("Illegal Index: " + index);
    }
    if (elements.length <= index) {
        throw new SeleniumError("Index out of range: " + index);
    }
    return [elements[index]];
};

PageBot.prototype.selectElements = function(filterExpr, elements, defaultFilterType) {    

    var filterType = (defaultFilterType || 'value');
    
    // If there is a filter prefix, use the specified strategy
    var result = filterExpr.match(/^([A-Za-z]+)=(.+)/);
    if (result) {
        filterType = result[1].toLowerCase();
        filterExpr = result[2];
    }

    return this.selectElementsBy(filterType, filterExpr, elements);
};