PageRenderTime 20ms CodeModel.GetById 13ms app.highlight 2ms RepoModel.GetById 2ms app.codeStats 0ms

/examples/ArcGISLink/bin-release/srcview/source/html-template/history/history.js.txt

http://gmaps-utility-library-flash.googlecode.com/
Plain Text | 697 lines | 618 code | 79 blank | 0 comment | 0 complexity | e6cf5b76e2862971e07766c210c98ddd MD5 | raw file
  1BrowserHistoryUtils = {
  2    addEvent: function(elm, evType, fn, useCapture) {
  3        useCapture = useCapture || false;
  4        if (elm.addEventListener) {
  5            elm.addEventListener(evType, fn, useCapture);
  6            return true;
  7        }
  8        else if (elm.attachEvent) {
  9            var r = elm.attachEvent('on' + evType, fn);
 10            return r;
 11        }
 12        else {
 13            elm['on' + evType] = fn;
 14        }
 15    }
 16}
 17
 18BrowserHistory = (function() {
 19    // type of browser
 20    var browser = {
 21        ie: false, 
 22        ie8: false, 
 23        firefox: false, 
 24        safari: false, 
 25        opera: false, 
 26        version: -1
 27    };
 28
 29    // if setDefaultURL has been called, our first clue
 30    // that the SWF is ready and listening
 31    //var swfReady = false;
 32
 33    // the URL we'll send to the SWF once it is ready
 34    //var pendingURL = '';
 35
 36    // Default app state URL to use when no fragment ID present
 37    var defaultHash = '';
 38
 39    // Last-known app state URL
 40    var currentHref = document.location.href;
 41
 42    // Initial URL (used only by IE)
 43    var initialHref = document.location.href;
 44
 45    // Initial URL (used only by IE)
 46    var initialHash = document.location.hash;
 47
 48    // History frame source URL prefix (used only by IE)
 49    var historyFrameSourcePrefix = 'history/historyFrame.html?';
 50
 51    // History maintenance (used only by Safari)
 52    var currentHistoryLength = -1;
 53
 54    var historyHash = [];
 55
 56    var initialState = createState(initialHref, initialHref + '#' + initialHash, initialHash);
 57
 58    var backStack = [];
 59    var forwardStack = [];
 60
 61    var currentObjectId = null;
 62
 63    //UserAgent detection
 64    var useragent = navigator.userAgent.toLowerCase();
 65
 66    if (useragent.indexOf("opera") != -1) {
 67        browser.opera = true;
 68    } else if (useragent.indexOf("msie") != -1) {
 69        browser.ie = true;
 70        browser.version = parseFloat(useragent.substring(useragent.indexOf('msie') + 4));
 71        if (browser.version == 8)
 72        {
 73            browser.ie = false;
 74            browser.ie8 = true;
 75        }
 76    } else if (useragent.indexOf("safari") != -1) {
 77        browser.safari = true;
 78        browser.version = parseFloat(useragent.substring(useragent.indexOf('safari') + 7));
 79    } else if (useragent.indexOf("gecko") != -1) {
 80        browser.firefox = true;
 81    }
 82
 83    if (browser.ie == true && browser.version == 7) {
 84        window["_ie_firstload"] = false;
 85    }
 86
 87    function hashChangeHandler()
 88    {
 89        currentHref = document.location.href;
 90        var flexAppUrl = getHash();
 91        //ADR: to fix multiple
 92        if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) {
 93            var pl = getPlayers();
 94            for (var i = 0; i < pl.length; i++) {
 95                pl[i].browserURLChange(flexAppUrl);
 96            }
 97        } else {
 98            getPlayer().browserURLChange(flexAppUrl);
 99        }
100    }
101
102    // Accessor functions for obtaining specific elements of the page.
103    function getHistoryFrame()
104    {
105        return document.getElementById('ie_historyFrame');
106    }
107
108    function getAnchorElement()
109    {
110        return document.getElementById('firefox_anchorDiv');
111    }
112
113    function getFormElement()
114    {
115        return document.getElementById('safari_formDiv');
116    }
117
118    function getRememberElement()
119    {
120        return document.getElementById("safari_remember_field");
121    }
122
123    // Get the Flash player object for performing ExternalInterface callbacks.
124    // Updated for changes to SWFObject2.
125    function getPlayer(id) {
126        var i;
127
128		if (id && document.getElementById(id)) {
129			var r = document.getElementById(id);
130			if (typeof r.SetVariable != "undefined") {
131				return r;
132			}
133			else {
134				var o = r.getElementsByTagName("object");
135				var e = r.getElementsByTagName("embed");
136                for (i = 0; i < o.length; i++) {
137                    if (typeof o[i].browserURLChange != "undefined")
138                        return o[i];
139                }
140                for (i = 0; i < e.length; i++) {
141                    if (typeof e[i].browserURLChange != "undefined")
142                        return e[i];
143                }
144			}
145		}
146		else {
147			var o = document.getElementsByTagName("object");
148			var e = document.getElementsByTagName("embed");
149            for (i = 0; i < e.length; i++) {
150                if (typeof e[i].browserURLChange != "undefined")
151                {
152                    return e[i];
153                }
154            }
155            for (i = 0; i < o.length; i++) {
156                if (typeof o[i].browserURLChange != "undefined")
157                {
158                    return o[i];
159                }
160            }
161		}
162		return undefined;
163	}
164    
165    function getPlayers() {
166        var i;
167        var players = [];
168        if (players.length == 0) {
169            var tmp = document.getElementsByTagName('object');
170            for (i = 0; i < tmp.length; i++)
171            {
172                if (typeof tmp[i].browserURLChange != "undefined")
173                    players.push(tmp[i]);
174            }
175        }
176        if (players.length == 0 || players[0].object == null) {
177            var tmp = document.getElementsByTagName('embed');
178            for (i = 0; i < tmp.length; i++)
179            {
180                if (typeof tmp[i].browserURLChange != "undefined")
181                    players.push(tmp[i]);
182            }
183        }
184        return players;
185    }
186
187	function getIframeHash() {
188		var doc = getHistoryFrame().contentWindow.document;
189		var hash = String(doc.location.search);
190		if (hash.length == 1 && hash.charAt(0) == "?") {
191			hash = "";
192		}
193		else if (hash.length >= 2 && hash.charAt(0) == "?") {
194			hash = hash.substring(1);
195		}
196		return hash;
197	}
198
199    /* Get the current location hash excluding the '#' symbol. */
200    function getHash() {
201       // It would be nice if we could use document.location.hash here,
202       // but it's faulty sometimes.
203       var idx = document.location.href.indexOf('#');
204       return (idx >= 0) ? document.location.href.substr(idx+1) : '';
205    }
206
207    /* Get the current location hash excluding the '#' symbol. */
208    function setHash(hash) {
209       // It would be nice if we could use document.location.hash here,
210       // but it's faulty sometimes.
211       if (hash == '') hash = '#'
212       document.location.hash = hash;
213    }
214
215    function createState(baseUrl, newUrl, flexAppUrl) {
216        return { 'baseUrl': baseUrl, 'newUrl': newUrl, 'flexAppUrl': flexAppUrl, 'title': null };
217    }
218
219    /* Add a history entry to the browser.
220     *   baseUrl: the portion of the location prior to the '#'
221     *   newUrl: the entire new URL, including '#' and following fragment
222     *   flexAppUrl: the portion of the location following the '#' only
223     */
224    function addHistoryEntry(baseUrl, newUrl, flexAppUrl) {
225
226        //delete all the history entries
227        forwardStack = [];
228
229        if (browser.ie) {
230            //Check to see if we are being asked to do a navigate for the first
231            //history entry, and if so ignore, because it's coming from the creation
232            //of the history iframe
233            if (flexAppUrl == defaultHash && document.location.href == initialHref && window['_ie_firstload']) {
234                currentHref = initialHref;
235                return;
236            }
237            if ((!flexAppUrl || flexAppUrl == defaultHash) && window['_ie_firstload']) {
238                newUrl = baseUrl + '#' + defaultHash;
239                flexAppUrl = defaultHash;
240            } else {
241                // for IE, tell the history frame to go somewhere without a '#'
242                // in order to get this entry into the browser history.
243                getHistoryFrame().src = historyFrameSourcePrefix + flexAppUrl;
244            }
245            setHash(flexAppUrl);
246        } else {
247
248            //ADR
249            if (backStack.length == 0 && initialState.flexAppUrl == flexAppUrl) {
250                initialState = createState(baseUrl, newUrl, flexAppUrl);
251            } else if(backStack.length > 0 && backStack[backStack.length - 1].flexAppUrl == flexAppUrl) {
252                backStack[backStack.length - 1] = createState(baseUrl, newUrl, flexAppUrl);
253            }
254
255            if (browser.safari) {
256                // for Safari, submit a form whose action points to the desired URL
257                if (browser.version <= 419.3) {
258                    var file = window.location.pathname.toString();
259                    file = file.substring(file.lastIndexOf("/")+1);
260                    getFormElement().innerHTML = '<form name="historyForm" action="'+file+'#' + flexAppUrl + '" method="GET"></form>';
261                    //get the current elements and add them to the form
262                    var qs = window.location.search.substring(1);
263                    var qs_arr = qs.split("&");
264                    for (var i = 0; i < qs_arr.length; i++) {
265                        var tmp = qs_arr[i].split("=");
266                        var elem = document.createElement("input");
267                        elem.type = "hidden";
268                        elem.name = tmp[0];
269                        elem.value = tmp[1];
270                        document.forms.historyForm.appendChild(elem);
271                    }
272                    document.forms.historyForm.submit();
273                } else {
274                    top.location.hash = flexAppUrl;
275                }
276                // We also have to maintain the history by hand for Safari
277                historyHash[history.length] = flexAppUrl;
278                _storeStates();
279            } else {
280                // Otherwise, just tell the browser to go there
281                setHash(flexAppUrl);
282            }
283        }
284        backStack.push(createState(baseUrl, newUrl, flexAppUrl));
285    }
286
287    function _storeStates() {
288        if (browser.safari) {
289            getRememberElement().value = historyHash.join(",");
290        }
291    }
292
293    function handleBackButton() {
294        //The "current" page is always at the top of the history stack.
295        var current = backStack.pop();
296        if (!current) { return; }
297        var last = backStack[backStack.length - 1];
298        if (!last && backStack.length == 0){
299            last = initialState;
300        }
301        forwardStack.push(current);
302    }
303
304    function handleForwardButton() {
305        //summary: private method. Do not call this directly.
306
307        var last = forwardStack.pop();
308        if (!last) { return; }
309        backStack.push(last);
310    }
311
312    function handleArbitraryUrl() {
313        //delete all the history entries
314        forwardStack = [];
315    }
316
317    /* Called periodically to poll to see if we need to detect navigation that has occurred */
318    function checkForUrlChange() {
319
320        if (browser.ie) {
321            if (currentHref != document.location.href && currentHref + '#' != document.location.href) {
322                //This occurs when the user has navigated to a specific URL
323                //within the app, and didn't use browser back/forward
324                //IE seems to have a bug where it stops updating the URL it
325                //shows the end-user at this point, but programatically it
326                //appears to be correct.  Do a full app reload to get around
327                //this issue.
328                if (browser.version < 7) {
329                    currentHref = document.location.href;
330                    document.location.reload();
331                } else {
332					if (getHash() != getIframeHash()) {
333						// this.iframe.src = this.blankURL + hash;
334						var sourceToSet = historyFrameSourcePrefix + getHash();
335						getHistoryFrame().src = sourceToSet;
336                        currentHref = document.location.href;
337					}
338                }
339            }
340        }
341
342        if (browser.safari) {
343            // For Safari, we have to check to see if history.length changed.
344            if (currentHistoryLength >= 0 && history.length != currentHistoryLength) {
345                //alert("did change: " + history.length + ", " + historyHash.length + "|" + historyHash[history.length] + "|>" + historyHash.join("|"));
346                var flexAppUrl = getHash();
347                if (browser.version < 528.16 /* Anything earlier than Safari 4.0 */)
348                {    
349                    // If it did change and we're running Safari 3.x or earlier, 
350                    // then we have to look the old state up in our hand-maintained 
351                    // array since document.location.hash won't have changed, 
352                    // then call back into BrowserManager.
353                currentHistoryLength = history.length;
354                    flexAppUrl = historyHash[currentHistoryLength];
355                }
356
357                //ADR: to fix multiple
358                if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) {
359                    var pl = getPlayers();
360                    for (var i = 0; i < pl.length; i++) {
361                        pl[i].browserURLChange(flexAppUrl);
362                    }
363                } else {
364                    getPlayer().browserURLChange(flexAppUrl);
365                }
366                _storeStates();
367            }
368        }
369        if (browser.firefox) {
370            if (currentHref != document.location.href) {
371                var bsl = backStack.length;
372
373                var urlActions = {
374                    back: false, 
375                    forward: false, 
376                    set: false
377                }
378
379                if ((window.location.hash == initialHash || window.location.href == initialHref) && (bsl == 1)) {
380                    urlActions.back = true;
381                    // FIXME: could this ever be a forward button?
382                    // we can't clear it because we still need to check for forwards. Ugg.
383                    // clearInterval(this.locationTimer);
384                    handleBackButton();
385                }
386                
387                // first check to see if we could have gone forward. We always halt on
388                // a no-hash item.
389                if (forwardStack.length > 0) {
390                    if (forwardStack[forwardStack.length-1].flexAppUrl == getHash()) {
391                        urlActions.forward = true;
392                        handleForwardButton();
393                    }
394                }
395
396                // ok, that didn't work, try someplace back in the history stack
397                if ((bsl >= 2) && (backStack[bsl - 2])) {
398                    if (backStack[bsl - 2].flexAppUrl == getHash()) {
399                        urlActions.back = true;
400                        handleBackButton();
401                    }
402                }
403                
404                if (!urlActions.back && !urlActions.forward) {
405                    var foundInStacks = {
406                        back: -1, 
407                        forward: -1
408                    }
409
410                    for (var i = 0; i < backStack.length; i++) {
411                        if (backStack[i].flexAppUrl == getHash() && i != (bsl - 2)) {
412                            arbitraryUrl = true;
413                            foundInStacks.back = i;
414                        }
415                    }
416                    for (var i = 0; i < forwardStack.length; i++) {
417                        if (forwardStack[i].flexAppUrl == getHash() && i != (bsl - 2)) {
418                            arbitraryUrl = true;
419                            foundInStacks.forward = i;
420                        }
421                    }
422                    handleArbitraryUrl();
423                }
424
425                // Firefox changed; do a callback into BrowserManager to tell it.
426                currentHref = document.location.href;
427                var flexAppUrl = getHash();
428                //ADR: to fix multiple
429                if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) {
430                    var pl = getPlayers();
431                    for (var i = 0; i < pl.length; i++) {
432                        pl[i].browserURLChange(flexAppUrl);
433                    }
434                } else {
435                    getPlayer().browserURLChange(flexAppUrl);
436                }
437            }
438        }
439        //setTimeout(checkForUrlChange, 50);
440    }
441
442    var _initialize = function () {
443        if (browser.ie)
444        {
445            var scripts = document.getElementsByTagName('script');
446            for (var i = 0, s; s = scripts[i]; i++) {
447                if (s.src.indexOf("history.js") > -1) {
448                    var iframe_location = (new String(s.src)).replace("history.js", "historyFrame.html");
449                }
450            }
451            historyFrameSourcePrefix = iframe_location + "?";
452            var src = historyFrameSourcePrefix;
453
454            var iframe = document.createElement("iframe");
455            iframe.id = 'ie_historyFrame';
456            iframe.name = 'ie_historyFrame';
457            iframe.src = 'javascript:false;'; 
458
459            try {
460                document.body.appendChild(iframe);
461            } catch(e) {
462                setTimeout(function() {
463                    document.body.appendChild(iframe);
464                }, 0);
465            }
466        }
467
468        if (browser.safari)
469        {
470            var rememberDiv = document.createElement("div");
471            rememberDiv.id = 'safari_rememberDiv';
472            document.body.appendChild(rememberDiv);
473            rememberDiv.innerHTML = '<input type="text" id="safari_remember_field" style="width: 500px;">';
474
475            var formDiv = document.createElement("div");
476            formDiv.id = 'safari_formDiv';
477            document.body.appendChild(formDiv);
478
479            var reloader_content = document.createElement('div');
480            reloader_content.id = 'safarireloader';
481            var scripts = document.getElementsByTagName('script');
482            for (var i = 0, s; s = scripts[i]; i++) {
483                if (s.src.indexOf("history.js") > -1) {
484                    html = (new String(s.src)).replace(".js", ".html");
485                }
486            }
487            reloader_content.innerHTML = '<iframe id="safarireloader-iframe" src="about:blank" frameborder="no" scrolling="no"></iframe>';
488            document.body.appendChild(reloader_content);
489            reloader_content.style.position = 'absolute';
490            reloader_content.style.left = reloader_content.style.top = '-9999px';
491            iframe = reloader_content.getElementsByTagName('iframe')[0];
492
493            if (document.getElementById("safari_remember_field").value != "" ) {
494                historyHash = document.getElementById("safari_remember_field").value.split(",");
495            }
496
497        }
498
499        if (browser.firefox || browser.ie8)
500        {
501            var anchorDiv = document.createElement("div");
502            anchorDiv.id = 'firefox_anchorDiv';
503            document.body.appendChild(anchorDiv);
504        }
505
506        if (browser.ie8)        
507            document.body.onhashchange = hashChangeHandler;
508        //setTimeout(checkForUrlChange, 50);
509    }
510
511    return {
512        historyHash: historyHash, 
513        backStack: function() { return backStack; }, 
514        forwardStack: function() { return forwardStack }, 
515        getPlayer: getPlayer, 
516        initialize: function(src) {
517            _initialize(src);
518        }, 
519        setURL: function(url) {
520            document.location.href = url;
521        }, 
522        getURL: function() {
523            return document.location.href;
524        }, 
525        getTitle: function() {
526            return document.title;
527        }, 
528        setTitle: function(title) {
529            try {
530                backStack[backStack.length - 1].title = title;
531            } catch(e) { }
532            //if on safari, set the title to be the empty string. 
533            if (browser.safari) {
534                if (title == "") {
535                    try {
536                    var tmp = window.location.href.toString();
537                    title = tmp.substring((tmp.lastIndexOf("/")+1), tmp.lastIndexOf("#"));
538                    } catch(e) {
539                        title = "";
540                    }
541                }
542            }
543            document.title = title;
544        }, 
545        setDefaultURL: function(def)
546        {
547            defaultHash = def;
548            def = getHash();
549            //trailing ? is important else an extra frame gets added to the history
550            //when navigating back to the first page.  Alternatively could check
551            //in history frame navigation to compare # and ?.
552            if (browser.ie)
553            {
554                window['_ie_firstload'] = true;
555                var sourceToSet = historyFrameSourcePrefix + def;
556                var func = function() {
557                    getHistoryFrame().src = sourceToSet;
558                    window.location.replace("#" + def);
559                    setInterval(checkForUrlChange, 50);
560                }
561                try {
562                    func();
563                } catch(e) {
564                    window.setTimeout(function() { func(); }, 0);
565                }
566            }
567
568            if (browser.safari)
569            {
570                currentHistoryLength = history.length;
571                if (historyHash.length == 0) {
572                    historyHash[currentHistoryLength] = def;
573                    var newloc = "#" + def;
574                    window.location.replace(newloc);
575                } else {
576                    //alert(historyHash[historyHash.length-1]);
577                }
578                //setHash(def);
579                setInterval(checkForUrlChange, 50);
580            }
581            
582            
583            if (browser.firefox || browser.opera)
584            {
585                var reg = new RegExp("#" + def + "$");
586                if (window.location.toString().match(reg)) {
587                } else {
588                    var newloc ="#" + def;
589                    window.location.replace(newloc);
590                }
591                setInterval(checkForUrlChange, 50);
592                //setHash(def);
593            }
594
595        }, 
596
597        /* Set the current browser URL; called from inside BrowserManager to propagate
598         * the application state out to the container.
599         */
600        setBrowserURL: function(flexAppUrl, objectId) {
601            if (browser.ie && typeof objectId != "undefined") {
602                currentObjectId = objectId;
603            }
604           //fromIframe = fromIframe || false;
605           //fromFlex = fromFlex || false;
606           //alert("setBrowserURL: " + flexAppUrl);
607           //flexAppUrl = (flexAppUrl == "") ? defaultHash : flexAppUrl ;
608
609           var pos = document.location.href.indexOf('#');
610           var baseUrl = pos != -1 ? document.location.href.substr(0, pos) : document.location.href;
611           var newUrl = baseUrl + '#' + flexAppUrl;
612
613           if (document.location.href != newUrl && document.location.href + '#' != newUrl) {
614               currentHref = newUrl;
615               addHistoryEntry(baseUrl, newUrl, flexAppUrl);
616               currentHistoryLength = history.length;
617           }
618        }, 
619
620        browserURLChange: function(flexAppUrl) {
621            var objectId = null;
622            if (browser.ie && currentObjectId != null) {
623                objectId = currentObjectId;
624            }
625            pendingURL = '';
626            
627            if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) {
628                var pl = getPlayers();
629                for (var i = 0; i < pl.length; i++) {
630                    try {
631                        pl[i].browserURLChange(flexAppUrl);
632                    } catch(e) { }
633                }
634            } else {
635                try {
636                    getPlayer(objectId).browserURLChange(flexAppUrl);
637                } catch(e) { }
638            }
639
640            currentObjectId = null;
641        },
642        getUserAgent: function() {
643            return navigator.userAgent;
644        },
645        getPlatform: function() {
646            return navigator.platform;
647        }
648
649    }
650
651})();
652
653// Initialization
654
655// Automated unit testing and other diagnostics
656
657function setURL(url)
658{
659    document.location.href = url;
660}
661
662function backButton()
663{
664    history.back();
665}
666
667function forwardButton()
668{
669    history.forward();
670}
671
672function goForwardOrBackInHistory(step)
673{
674    history.go(step);
675}
676
677//BrowserHistoryUtils.addEvent(window, "load", function() { BrowserHistory.initialize(); });
678(function(i) {
679    var u =navigator.userAgent;var e=/*@cc_on!@*/false; 
680    var st = setTimeout;
681    if(/webkit/i.test(u)){
682        st(function(){
683            var dr=document.readyState;
684            if(dr=="loaded"||dr=="complete"){i()}
685            else{st(arguments.callee,10);}},10);
686    } else if((/mozilla/i.test(u)&&!/(compati)/.test(u)) || (/opera/i.test(u))){
687        document.addEventListener("DOMContentLoaded",i,false);
688    } else if(e){
689    (function(){
690        var t=document.createElement('doc:rdy');
691        try{t.doScroll('left');
692            i();t=null;
693        }catch(e){st(arguments.callee,0);}})();
694    } else{
695        window.onload=i;
696    }
697})( function() {BrowserHistory.initialize();} );