/*
  opwin automatically centers window based on the parent window
  and resizes the windows width and height if specified
  to automatically fit on the screen
  lastly the window is raised and focused automatically
*/
function opwin (lnk,target,opts,w,h) {
  if (window.screen && w && h) {
    var s = window.screen;

    var max_width = s.availWidth - 10;
    var max_height = s.availHeight - 30;

    // subtract extra for toolbar and menubar
    if (opts.indexOf('toolbar',0) != -1) {
      max_height -= 40;
    }
    if (opts.indexOf('menubar',0) != -1) {
      max_height -= 35;
    }
    if (opts.indexOf('location',0) != -1) {
      max_height -= 35;
    }



    var width  = (w > max_width)?max_width:w;
    var height = (h > max_height)?max_height:h;

    
    var par_left_offset = (window.screenX == null)?0:window.screenX;
    var par_top_offset  = (window.screenY == null)?0:window.screenY;
    var par_width;
    if (window.outerWidth != null) {
      par_width = window.outerWidth;
      if (par_width < width) {
        par_left_offset -= parseInt((width - par_width)/2);
      }
    } else {
      par_width = max_width;
    }


    var par_height;
    if (window.outerHeight != null) {
      par_height = window.outerHeight;
      if (par_height < height) {
        par_top_offset -= parseInt((height - par_height)/2);
      }
    } else {
      par_height = max_height;
    }

    var left = parseInt(par_width /2 - width /2) + par_left_offset;
    var top  = parseInt(par_height/2 - height/2) + par_top_offset;

    var newopts = 'width='+width+',height='+height+',left='+left+',top='+top;
    opts = (opts && opts != '')?newopts+','+opts:newopts;

    opts += ',status';

//    window.alert('Options: '+opts+'\nParent: par_left_offset='+par_left_offset+'\n        par_top_offset='+par_top_offset+'\n        par_width='+par_width+'\n        par_height='+par_height+'\n        max_h='+max_height+'\n        max_w='+max_width);

  }
  var w = window.open(lnk,target,opts);
  if (w.focus) { w.focus(); }
  return w;
}
