// IGSuite 5.0.0
// JavaScript functions

// store variables to control where the popup will appear
// relative to the cursor position positive numbers are below and to
// the right of the cursor, negative numbers are above and to the left
var xOffset = 15;
var yOffset = 25;
var lastMouseX;
var lastMouseY;
var layer = new String();
var style = new String();
var qpv = '[Open Preview]';
var cpv = '[Close Preview]';
var infoBoxTime;

// z-index value
var zidx = 1000;

// Find screen or frame max width and height
var maxWidth  = 500;
var maxHeight = 300;

// Store Textarea changes
var inputHistory = new Object();
var inputCursor1 = new Object();
var inputCursor2 = new Object();

// Capture click event to find mouse coords   
Event.observe(document, 'click', function(event)
 {
  // IE is evil and doesn't pass the event object 
  if (event == null) event = window.event;

  getMouseCoords( event );
  hideCurrentPopups();
 } );


// call from the onContextMenu event, passing the event 
// if this function returns false, the browser's context menu will not show up
Event.observe(document, 'contextmenu', function(event)
 {
  var target = Event.element(event);

  if ( event.button == 2 && target.className == 'protocol' )
   {
    // hide protocol info box
    clearTimeout(window.infoBoxTime);

    // capture protocol ID
    var pId = target.innerHTML;

    // build contextual menu div
    preparePopup('divContext', { style:'line-height:0px' });

    // update contextual menu
    new Ajax.Request('igsuite',
     {
      method:'post',
      encoding: 'iso-8859-1',
      parameters: { action: 'ajaxrequest',
                    ajaxaction: 'contextual_menu',
                    id: pId },
      onSuccess: function(transport)
       {
        $('divContext').innerHTML = transport.responseText || "Error: no response text";
        showPopup('divContext', event, 0);
       },
      onFailure: function()
       { alert('Something went wrong in contextual menu...') }
     });

    Event.stop(event);
   }
 });


// Store each textarea change to permit undo&redo
function storeChanges(id)
 {
  if ( ! inputHistory[id] )
   {
    // initialize values
    inputHistory[id] = new Array();
    inputHistory[id][0] = "";
    inputCursor1[id] = 0;
    inputCursor2[id] = 0;
   }

  inputCursor1[id]++;
  var y = inputCursor1[id];
  inputHistory[id][y] = $(id).value;
 }

function undoChanges(id)
 {
  if ( ! inputHistory[id] ) return false;

  if ( inputCursor2[id] < inputCursor1[id] )
   { inputCursor2[id]++; }

  var z = inputHistory[id].length;
  z = z - inputCursor2[id];
  if ( inputHistory[id][z])
   { $(id).value = inputHistory[id][z]; }
 else
   { $(id).value = inputHistory[id][0]; }
 }

function redoChanges(id)
 {
  if ( ! inputHistory[id] ) return false;

  if (  inputCursor2[id] > 1 )
   { inputCursor2[id]--; }

  var z = inputHistory[id].length;
  z = z - inputCursor2[id];
  if ( inputHistory[id][z])
   { $(id).value = inputHistory[id][z]; }
 else
   { $(id).value = inputHistory[id][0]; }
 }


// Ajax progress indicator
var favicon = '';
var ajaxResponders = Ajax.Responders.register
                      ({ onCreate: function() {
                                   if (! favicon) favicon = $('favicon').src;
                                   $('favicon').src = '/images/ajax_progress.gif';
                                              }, 
                         onComplete: function() {
                                   $('favicon').src = favicon;
                                              }
                       });


// generic ajax request
function ajaxRequest(options)
 {
  var default_args = { 'type'       : 'request',
                       'frequency'  : 2,
                       'decay'      : 0,
                       'cgiaction'  : 'igsuite',
                       'parameters' : {} };

  for (var index in default_args)
   {
    if (typeof options[index] == "undefined") options[index] = default_args[index];
   }

  options['parameters']['action'] = 'ajaxrequest';
  options['parameters']['ajaxaction'] = options['action'];

  if ( options['type'] == 'request' )
   {
    new Ajax.Request( options['cgiaction'],
                      { method: 'post',
                        encoding: 'iso-8859-1',
                        parameters: options['parameters'] });
   }
  else if ( options['type'] == 'updater' )
   {
    new Ajax.Updater( options['container'],
                      options['cgiaction'],
                      { method: 'post',
                        encoding: 'iso-8859-1',
                        evalScripts: true,
                        parameters: options['parameters'] });
   }
  else if ( options['type'] == 'periodical_updater' )
   {
    new Ajax.PeriodicalUpdater( options['container'],
                                options['cgiaction'],
                                { method: 'post',
                                  encoding: 'iso-8859-1',
                                  frequency: options['frequency'],
                                  decay: options['decay'],
                                  evalScripts: true,
                                  parameters: options['parameters'] });
    }
 }

function ajaxizeElement( elementType, elementId, url )
 {
  new Effect.Opacity(elementId, { from: 1.0, to: 0.5, duration: 0.1 });
  new Ajax.Updater( elementId,
                    url,
                    { method: 'get',
                      evalScripts: true,
                      encoding: 'iso-8859-1',
                      parameters: { ajaxize_id:elementId,
                                    ajaxize_type:elementType },
                      onSuccess: function(transport)
                       {
                        new Effect.Opacity(elementId, 
                                           { from: 0.5, to: 1.0, duration: 0.1 });
                       }
                    } );
 }

// Get personalized field list from IGForms
function getIGFormsMask( formid, recordid, container )
 {
  new Ajax.Updater( container,
                    'igforms',
                    { method: 'post',
                      parameters: { action: 'build_form_mask',
                                    igformid: formid,
                                    recordid: recordid }
                    });
 }


// Prepare/Create Popups
function preparePopup(popupId, options)
 {
  if ( ! $('popupId') )
   {
    options = options || {};
    var default_opts = { className : 'infobox',
                         id        : popupId };

    for (var index in default_opts)
     {
      if (typeof options[index] == "undefined")
        options[index] = default_opts[index];
     }

    var cdiv = Builder.node('div', options, 'Loading...' );
    $('main_body').insert(cdiv);
   }
 }


// Show Protocol Info Box
function showPInfoBox(elemId, divName, objEvent)
 {
  var evt = objEvent || window.event;
  var evtCopy = {};
  for (var i in evt) evtCopy[i] = evt[i];

  preparePopup( divName, { style   : 'width:300px',
                           onclick : 'Event.stop(event)' } );

  clearTimeout(window.infoBoxTime);
  window.infoBoxTime = setTimeout(function working()
   {
    ajaxRequest({ action: 'docinfo',
                  type: 'updater',
                  container: divName,
                  parameters: { id: elemId } });

    Prototype.Browser.IE
    ? showPopup(divName, evtCopy, 1)
    : showPopup(divName, evt, 1);
   }, 500 );
 }


// Hide Protocol Info Box
function hidePInfoBox(divName)
 {
  clearTimeout(window.infoBoxTime);
  var hideStr = "changeVisibility('" + divName + "', 'hidden', 'none')";
  window.infoBoxTime = setTimeout(hideStr, 4000);
 }

// Show an alert Popup
function alertPopup(msg, popupId, popupStyle)
 {
  popupId = popupId || 'alertpopup';
  msg = msg || 'Empty message';
  popupStyle = popupStyle || {};

  var default_opts = { backgroundColor: '#ff0000',
                       opacity: 0.8,
                       color: '#ffffff',
                       width: '300px',
                       zIndex: 1000,
                       padding: '30px',
                       textAlign: 'center',
                       fontSize: '14px' };
  for (var index in default_opts)
   {
    if (typeof popupStyle[index] == "undefined")
      popupStyle[index] = default_opts[index];
   }

  // build the popup
  preparePopup(popupId);
  $(popupId).setStyle(popupStyle);
  $(popupId).innerHTML = '<div style="cursor:pointer;position:absolute;top:5;right:5;" onclick="$(\''+popupId+'\').fade();">X</div>' + msg;

  // place popup to the center of viewport
  getViewportSize();
  var popupPos = $(popupId).getDimensions()
  moveObject(popupId,
             ((maxWidth / 2) - (popupPos.width / 2)),
             ((maxHeight / 2) - (popupPos.height / 2)));
  changeVisibility(popupId, 'visible', 'block');
  Effect.Shake(popupId);
  new Draggable(popupId);
 }

function delShow (script, id)
 {
  new Ajax.Request('igsuite',
   {
    method:'post',
    encoding: 'iso-8859-1',
    evalScripts: true,
    parameters: {ajaxaction: 'delshow',
                 action:     'ajaxrequest',
                 script:     script,
                 id:         id },
    onSuccess: function(transport)
     {
      alertPopup('Loading...', 'delshow', { backgroundColor:'#dddddd',
                                            color:'#000000' } );
      var content = transport.responseText;
      if ( content )
       { $('delshow').innerHTML = content; }
      else
       { alertPopup('Error: no response text from IGSuite application'); }
     },
    onFailure: function()
     { alertPopup('Something went wrong in delete element') }
   });
 }

function delExec (script, id)
 {
  new Ajax.Request(script,
   {
    method:      'post',
    encoding:    'iso-8859-1',
    evalScripts: true,
    parameters:  { action: 'delexec',
                   id:     id },
    onSuccess: function(transport)
     {
      var content = transport.responseText;
      if ( content )
       { $('delshow').innerHTML = content; }
      else
       { alertPopup('Error: no response text from IGSuite appliction'); }
     },
    onFailure: function()
     { alertPopup('Something went wrong in delete element') }
   });
 }


// Correctly handle PNG transparency in Win IE 5.5 or higher.
// http://homepage.ntlworld.com/bobosola. Updated 02-March-2004
function correctPNG() 
 {
  for(var i=0; i<document.images.length; i++)
   {
    var img = document.images[i];
    var imgName = img.src.toUpperCase();
    if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
     {
      var imgID = (img.id) ? "id='" + img.id + "' " : "";
      var imgClass = (img.className) ? "class='" + img.className + "' " : "";
      var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
      var imgStyle = "display:inline-block;" + img.style.cssText;
      if (img.align == "left") imgStyle = "float:left;" + imgStyle;
      if (img.align == "right") imgStyle = "float:right;" + imgStyle;
      var strNewHTML = "<span " + imgID + imgClass + imgTitle
       + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
       + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
       + "(src='" + img.src + "', sizingMethod='scale');\"></span>";
      img.outerHTML = strNewHTML;
     }
   }
 }


// Update textarea element and content with an FCKeditor
function updateTextArea(areaname, toolbar, areaWidth, areaHeight, uiLang, uiColor)
 {
  new Ajax.Request('igsuite',
   {
    method:'post',
    parameters: {action: 'ajaxrequest',
                 ajaxaction: 'text2html',
                 text: $(areaname).value },
    onSuccess: function(transport)
     {
      $(areaname).value = transport.responseText || "Error: no response text";
      replaceTextArea(areaname, toolbar, areaWidth, areaHeight, uiLang, uiColor);
     },
    onFailure: function(){ alert('Something went wrong in textarea replacing...') }
   });
 }

function replaceTextArea(areaname, toolbar, areaWidth, areaHeight, uiLang, uiColor)
 {
  if ( !toolbar )   { toolbar='IGBasic'; }
  if ( !areaWidth)  { areaWidth='530'; }
  if ( !areaHeight) { areaHeight='530'; }
  if ( !uiLang)     { uiLang='it'; }
  if ( !uiColor)    { uiColor='#CCCCCC'; }

  if ( typeof CKEDITOR !== 'undefined' )                            
   {
    // Use new CKEditor
    CKEDITOR.replace( areaname,
     {
      customConfig : '/images/igckeditor.js',
      baseHref : '/ckeditor/',
      toolbar : toolbar,
      width : areaWidth,
      height : areaHeight,
      language : uiLang,
      uiColor : uiColor
     } );
   }
  else
   {  
    // Use old FCKEditor
    var oFCKeditor = new FCKeditor( areaname ) ;
    oFCKeditor.Config["CustomConfigurationsPath"] = "/images/igfckeditor.js";
    oFCKeditor.Config['DefaultLanguage'] = uiLang;
    oFCKeditor.ToolbarSet = toolbar;
    oFCKeditor.Height = areaHeight;
    oFCKeditor.Width = areaWidth;
    oFCKeditor.BasePath = '';
    oFCKeditor.ReplaceTextarea() ;
   }

  // clean some useless element
  if ( $(areaname+'_toolbar') ) $(areaname+'_toolbar').hide();  
  $('div_field_'+areaname).setStyle({border:'0px'});
 }


// Init Tool Tips 
function initToolTip(options)
 {
  var default_args = { 'visible'    : 'true',
                       'position'   : 'center',
                       'hpos'       : 1,
                       'vpos'       : 1,
                       'draggable'  : 'true' };

  for (var index in default_args)
   { if (typeof options[index] == "undefined") options[index] = default_args[index]; }

  getViewportSize();
  var theRoot   = $(options['ttid']);
  var rootPos   = theRoot.getDimensions();

  // positioning     
  if ( options['position'] == 'center' )
   {
    moveObject( options['ttid'],
                ((maxWidth / 2) - (rootPos.width / 2)),
                ((maxHeight / 2) - (rootPos.height / 2)));
   }

  // make it draggable
  if ( options['draggable'] == 'true' )
   { new Draggable(theRoot, { handle: $(options['ttid'] + 'bar') } ); }

  // adjust zindex
  $(options['ttid']).style.zIndex = zidx++;

  // make it visible
  if ( options['visible'] == 'true' )
    changeVisibility( options['ttid'], 'visible', 'block'); 
 }


// Check all checkboxes
function checkAllCheckboxes( master, slaves )
 {
  var elements = $$('input[name='+slaves+']');
  for (var i=0; i < elements.length;i++)
   {
    var e = elements[i];
    e.checked = master.checked;
   }
 }


// Check cookies availability at login time
function ckCookie()
 {
  document.cookie = "testcookie";
  return (document.cookie.indexOf("testcookie")!=-1) ? true : false;
 }                    


// Get Viewport size
function getViewportSize()
 {
  maxWidth  =  document.viewport.getWidth()
            || window.innerWidth 
            || document.documentElement.clientWidth 
            || document.body.clientWidth;
  maxHeight =  document.viewport.getHeight()
            || window.innerHeight 
            || document.documentElement.clientHeight 
            || document.body.clientHeight;
 }


// Javascript error handler
window.onerror = tellerror;
function tellerror(msg, url, linenumber)
 {
  alert('Error message=['+msg+'] URL=['+url+'] Line Number=['+linenumber+']');
  return true;
 }


// Needed by MkRepository
function pv(url, id, pwidth, pheight, omsg, cmsg)
 {
  qpv = omsg;
  cpv = cmsg;

  if(document.all || document.getElementById)
   {
    document.write('<a title="Click to preview" id="link'+id+'" style="font-size:inherit;" href="'+url+'" onClick="pview(this,'+pwidth+','+pheight+');return false">'+qpv+'</a>');
   }
 }

function pview(link, pwidth, pheight)
 {
  var iframe = 'if' + link.id;
      iframe = $(iframe);

  if(link.innerHTML == qpv)
   {
    if(iframe)
     {
      // Reuses the IFrame if open already
      iframe.src = link.href;
      iframe.style.height = pheight;
      iframe.style.visibility = 'visible';
     }
    else
     {
      // Build the Frame and Load the URL
      myBR = document.createElement('br');
      myBR.setAttribute('id','br'+link.id);
      link.parentNode.appendChild(myBR);
      myIframe = document.createElement('iframe');
      myIframe.setAttribute('id','if'+link.id);
      myIframe.setAttribute('name','myframe');
      myIframe.setAttribute('width','100%');
      myIframe.setAttribute('height',pheight);
      myIframe.setAttribute('style','border:1px solid #999999'); 
      myIframe.setAttribute('src',link.href);
      link.parentNode.appendChild(myIframe);
     }
    link.innerHTML = cpv;
   }
  else if(iframe)
   {
    myBR = 'br'+link.id;
    myBR = $(myBR);
    link.innerHTML = qpv;
    link.parentNode.removeChild(iframe);
    link.parentNode.removeChild(myBR);
   }
 }

// to increase or decrease textarea field
function increaseTextArea(thisTextarea, add)
 {
  var dimensions = thisTextarea.getDimensions();
  var newHeight = parseInt(dimensions.height) + add;
  thisTextarea.style.height = newHeight + "px";
 }

function decreaseTextArea(thisTextarea, subtract)
 {
  var dimensions = thisTextarea.getDimensions();

  if ((parseInt(dimensions.height) - subtract) > 20)
   {
    var newHeight = parseInt(dimensions.height) - subtract;
    thisTextarea.style.height = newHeight + "px";
   }
  else
   {
    thisTextarea.style.height = "30px";
   }
 }


// needed by Input element "multiselect"
function moveTo(lform,lname,l1,l2)
 {
  var catList1 = eval('document.' + lform + '.' + lname + l1);
  var catList2 = eval('document.' + lform + '.' + lname + l2);
  var found = false;
  
  for (var i = catList2.length-1; i >= 0; i--)
   {
    if (catList2.options[i].selected)
     {
      var newVal = catList2.options[i].value;
      var newTex = catList2.options[i].text;
      catList1[catList1.length] = new Option(newTex,newVal);
      catList2.options[i] = null;
      found = true;
     }
   }

  var catList = eval('document.' + lform + '.' + lname + '2');
  var List = "";
  for (var i = 0; i < catList.options.length; i++)
   {
    // the '\n' here is important to get netscape and IE on the same page
    List += catList.options[i].value + '\n';
   }
  var myValue = eval('document.' + lform + '.' + lname);
  myValue.value = List;
 }


// needed by Input element "multiselect"
function moveUp(lform,lname,l1)
 {
  var catList = eval('document.' + lform + '.' + lname + l1);
  var found = false;

  for (var i = catList.length-1; i >= 0; i--)
   {
    if ( catList.options[i].selected && !found && i>0 )
     {
      var oriValue = catList.options[i].value;
      var oriText = catList.options[i].text;
      catList.options[i].value = catList.options[i-1].value;
      catList.options[i].text = catList.options[i-1].text;
      catList.options[i-1].value = oriValue;
      catList.options[i-1].text = oriText;
      catList.selectedIndex = i-1;
      found = true;
     }
   } 

  var catList = eval('document.' + lform + '.' + lname + '2');
  var List = "";
  for (var i = 0; i < catList.options.length; i++)
   {
    // the '\n' here is important to get netscape and IE on the same page
    List += catList.options[i].value + '\n';
   }
  var myValue = eval('document.' + lform + '.' + lname);
  myValue.value = List;
 }


// needed by Input element "multiselect"
function moveDown(lform,lname,l1)
 {
  var catList = eval('document.' + lform + '.' + lname + l1);
  var found = false;

  for (var i = catList.length-1; i >= 0; i--)
   {
    if ( catList.options[i].selected && !found && i<catList.length-1 )
     {
      var oriValue = catList.options[i].value;
      var oriText = catList.options[i].text;
      catList.options[i].value = catList.options[i+1].value;
      catList.options[i].text = catList.options[i+1].text;
      catList.options[i+1].value = oriValue;
      catList.options[i+1].text = oriText;
      catList.selectedIndex = i+1;
      found = true;
     }
   }

  var catList = eval('document.' + lform + '.' + lname + '2');
  var List = "";
  for (var i = 0; i < catList.options.length; i++)
   {
    // the '\n' here is important to get netscape and IE on the same page
    List += catList.options[i].value + '\n';
   }
  var myValue = eval('document.' + lform + '.' + lname);
  myValue.value = List;
 }


// needed by MkTabPan to show or hide panels
function goOver(objectId,name)
 {
  if ( !name ) { name='layer'; }
  for ( var i=0; i<=20; i++ )
   { changeVisibility(name + i, 'hidden', 'none'); }

  changeVisibility(name + objectId, 'inherit', 'block');
  return true;
 }


// need to positioning elements near mouse pointer
function getMouseCoords(e)
 {
  lastMouseX = Event.pointerX(e);
  lastMouseY = Event.pointerY(e);
 }


// make a new window browser (popup)
function winPopUp(str, Width, Height, title, option)
 {
  if ( !Height ) { Height = '200'; }
  if ( !Width )  { Width  = '200'; }
  if ( !title )  { title  = 'IGSuite'; }
  if ( !option ) { option = 'location=no,status=no,dependent=yes,scrollbars=yes,resizable=yes'; }

  if (lastMouseX - Width < 0)
   { lastMouseX = Width; }
  if (lastMouseY + Height > screen.height)
   { lastMouseY -= (lastMouseY + Height + 50) - screen.height; }
  lastMouseX -= Width;
  lastMouseY += 10;

  option += ",height=" + Height + ",width=" + Width;
  option += ",left=" + lastMouseX + ",top=" + lastMouseY;
  var newwindow = window.open(str, title, option);

  if (!newwindow)
   {
    alert("A popup window could not be opened. Your browser may be blocking popups for this application.");
   }
  else
   {
    if ( typeof newwindow.name == 'undefined')
     { newwindow.name = title; }

    // In some browsers, setting the "window.opener" property to any window
    // object will make the browser believe that the window was opened with
    // Javascript so we can close it without warnings message.
    if (typeof newwindow.opener == 'undefined')
     { newwindow.opener = self; }
   }

  // return newwindow;
 }


function showPopup ( targetObjectId, eventObj, objAutoHide )
 {
  if (!eventObj) var eventObj = window.event;

  // hide any currently-visible popups
  hideCurrentPopups();

  // stop event from bubbling up any farther
  Event.stop(eventObj);

  // set a display:block attribute to the object
  changeVisibility(targetObjectId, 'hidden', 'block');

  // place the popup near the cursor
  moveObject(targetObjectId, 0, 0, eventObj);

  // adjust zindex
  $(targetObjectId).style.zIndex = zidx++;

  // and make it visible
  if ( changeVisibility(targetObjectId, 'visible', 'block') )
   {
    // if we successfully showed the popup
    // store its Id on a globally-accessible object
    if ( objAutoHide ) window.currentlyVisiblePopup = targetObjectId;
    return true;
   }
  else
   {
    // we couldn't show the popup, boo hoo!
    return false;
   }
 }


// Hide all current popups
function hideCurrentPopups()
 {
  // note: we've stored the currently-visible popup on the
  // global object window.currentlyVisiblePopup
  if (window.currentlyVisiblePopup)
   {
    changeVisibility(window.currentlyVisiblePopup, 'hidden', 'none');
    window.currentlyVisiblePopup = false;
   }

  // hide contextual menu 
  if ( $('divContext') )
   changeVisibility('divContext','hidden','none');
 }


// thumbnails generator
function mkImgThumbs(imgList)
 {
  for (i=0; i<imgList.length; i++)
   {
    ajxImgThumbReq.delay(((i*2)+1), i, imgList);
   }
 }

function ajxImgThumbReq(imgIdx, imgList)
 {
   new Ajax.Request(imgUpdateUrl + imgList[imgIdx],
                    {
                     method:'get',
                     onSuccess: function(transport)
                      {
                       var s = transport.responseText || "";
                       if ( s )
                        {
                         $(s).src = imgThumbUrl + s + '.png';
                         $('qe_' + s).src = imgThumbUrl + s + '.png';
                        }
                      }
                    }
                   );
 }


// ************************
// layer utility routines *
// ************************


/*
 * Orginal: http://adomas.org/javascript-mouse-wheel/
 * prototype extension by "Frank Monnerjahn" <themonnie@gmail.com>
 */

// Usage:
// Event.observe($('my_div'), "mousewheel", handleDIV, false);
// Event.observe($('my_div'), "DOMMouseScroll", handleDIV, false); // Firefox
//
// function handleDIV(e) {
//  alert( Event.wheel(e) < 0 ? 'down' : 'up' ); }

Object.extend(Event, {
  wheel:function (event){
    var delta = 0;
    if (!event) event = window.event;
    if (event.wheelDelta) {
      delta = event.wheelDelta/120; 
      if (window.opera) delta = -delta;
    } else if (event.detail) { delta = -event.detail/3;	}
    return Math.round(delta); //Safari Round
  }
});



function serializeId(containerId)
 {
  var result = '';
  var elements = $(containerId).childElements();
  elements.each( function(s)
                  {
                   var elementId = s.readAttribute( 'id' );
                   result += elementId + '|';
                  });
  return result;
 }


function changeVisibility(objectId, newVisibility, newDisplay)
 {
  if ( ! $(objectId) ) return false;
  $(objectId).setStyle( { visibility: newVisibility,
                           display:    newDisplay } );
  return true;
 }


function moveObject(objectId, newXCoordinate, newYCoordinate, eventObj)
 {
  if ( ! $(objectId) ) return false;

  // use specified coordinates or cursor position
  newXCoordinate = newXCoordinate || Event.pointerX(eventObj) + 10;
  newYCoordinate = newYCoordinate || Event.pointerY(eventObj) + 10;

  // refresh screen size available
  getViewportSize();

  // get object dimensions
  var pos = Element.getDimensions(objectId);
  var objWidth = pos.width;
  var objHeight = pos.height;

  // modify "X" coordinate if it's out of screen
  if (( newXCoordinate + objWidth + 10) > maxWidth)
   {
    var min = $('main_body').scrollLeft || 1;
    newXCoordinate = (newXCoordinate - objWidth - 10) < min
                   ? min
                   : newXCoordinate - objWidth - 10;
   }

  // modify "Y" coordinate if it's out of screen
  if ((newYCoordinate + objHeight + 10) > maxHeight)
   {
    var min = $('main_body').scrollTop || 1;
    newYCoordinate = (newYCoordinate - objHeight - 10) < min
                   ? min
                   : newYCoordinate - objHeight - 10;
   }

  $(objectId).setStyle( { left: newXCoordinate,
                           top:  newYCoordinate } );
  return true;
 }


