﻿// ---------------------------------------------------------------------------------------------------
// DYNAMIC REGISTRATION OF PAGE ONLOAD EVENT HANDLER
// ---------------------------------------------------------------------------------------------------
// Author : D. Barsotti
// Date   : 11.2008
// ---------------------------------------------------------------------------------------------------
//
// WARNING:
//   In order to work, this script and it's call MUST BE INCLUDED IN THE BODY OF THE PAGE.
//   If included and/or called from the head, the script won't work because at the time the
//   head is evaluated, the body does not yet exist.
//
// Example of usage: This will register myOnLoad2 function as onload event handler for the page.
//
//  <html>
//  <head>
//  </head>
//  <body>
//      <script type="text/javascript" src="SafeOnLoad.js"></script>
//      <script type="text/javascript">
//
//          function myOnLoad2() { alert('Second event handler'); }
//
//          setOnLoadHandler(myOnLoad2);
//      </script>
//  </body>
//  </html>


var __old_onload_handler = null;    //*** Save the old onload event handler
var __new_onload_handler = null;    //*** The new onload event handler


//*** Register the new event handler
function setOnLoadHandler(new_handler) {

    var body = document.getElementsByTagName('body')[0];

    __old_onload_handler = window.onload;
    __new_onload_handler = new_handler;
    
    if (body.addEventListener) {
        window.onload = __on__load__;
    }
    else {
        body.onload = __on__load__;
    }
}

//*** Internal event handler. It will call the function passed in parameter, and then call the saved onload event handler
function __on__load__() {

    // Call the new event handler
    if (__new_onload_handler != null) __new_onload_handler();
    
    // Call the old event handler
    if ((typeof (__old_onload_handler) != 'undefined') && (__old_onload_handler != null)) {
        __old_onload_handler();
    }
}
