(function(){
  
  try{
    // try to load local control class name
    var bmClassNameRegExp = new RegExp(" ?(" + bmLocalClassNameRegExp + "){1} ?", "i");
  } catch( e ){
    // load default control class name
    var bmClassNameRegExp = new RegExp(" ?(bm-reader){1} ?", "i");
  }
    
  var bmPopupParams = {
    "width"       : window.screen.width,
    "height"      : window.screen.height,
    "top"         : "0",
    "left"        : "0",
    "directories" : "no",
    "location"    : "no",
    "resizeable"  : "yes",
    "menubar"     : "no",
    "toolbar"     : "no",
    "scrollbars"  : "yes",
    "status"      : "no"
  };

  if( window.addEventListener )
    window.addEventListener( "load", bmOnLoad, false );

  else if( window.attachEvent )
    window.attachEvent( "onload", bmOnLoad );
    
  function bmOnLoad( event ){
    var nodes = document.getElementsByTagName("A");

    for (var i=0; i < nodes.length; i++) {
      var nodeClass = nodes[i].className.match(bmClassNameRegExp);
      if( nodeClass && nodeClass[1] ){
        if( nodes[i].addEventListener )
          (function( node ){
            node.addEventListener( "click", function( event ){ bmOnClick.call( window, event, node ); }, false );
          })( nodes[i] );
        else if ( nodes[i].attachEvent )
          (function( node ){
            node.attachEvent( "onclick", function( event ){ bmOnClick.call( window, event, node ); } );
          })( nodes[i] );
      }
    };
    
  };
  
  function bmOnClick( event, node ){
    // prevent default action
    if( event.preventDefault )
      event.preventDefault();

    // prevent bubbling
    if( event.stopPropagation )
      event.stopPropagation();
      
    event.returnValue = false;
    event.cancelBubble = false;
    
    // find book href
    var href = node.getAttribute("href");

    // catch window name or generate own
    var windowName = node.getAttribute("target");
    if( !windowName )
      windowName = "BookmateReader" + (new Date()).getTime();
    
    // prepare params
    var params = "";
    for( key in bmPopupParams )
      params += key + "=" + bmPopupParams[key] + ",";

    params = params.replace(/,$/, "");
    
    // open popup;
    var popupWindow = window.open( href, windowName, params );
    popupWindow.focus();
  };
  
  
})();