// ======================================================================================
//  File        : ProgmanLibWeb.js
//  Project     : Library
//  Company     : Progman Oy
//  Author      : Sergey Borisov (SB)
//  Date        : 13.05.2004
//  Description : Some useful JavaScript functions
// ======================================================================================
//  Version History : 
//  V 1.00  13.05.2004  First Revision
// ======================================================================================

// -------------------------------------------------------------------------------- SB --
/// <summary>
/// Check all parameters and return true, if function/method/property is defined.
/// </summary>
// --------------------------------------------------------------------------------------
function IsDefined() {
   for ( var i = 0; i < arguments.length; ++i ) {
      if (    arguments[i] == null
           || typeof ( arguments[i] )== "" 
           || typeof ( arguments[i] )=="undefined" )
         return false;
   }
   return true;
}

// -------------------------------------------------------------------------------- SB --
/// <summary>
/// Open modal window if possible, otherwise normal browser window
/// </summary>
/// <param name="url">URL of page to open</param>
/// <param name="width">Width of window</param>
/// <param name="height">Height of window</param>
// --------------------------------------------------------------------------------------
function POpenDialog ( url, width, height )
{
  var WindowParams = null
  if ( IsDefined ( window.showModalDialog ) ) {
    WindowParams = "dialogWidth:"+width+"px;dialogHeight:"+height+"px;help:0;resizable:0;scroll:0;status:0;center:1;copyhistory:0;"
    if ( window.showModalDialog ( url, window, WindowParams ) > 0 )    // modal window
       window.location.replace ( window.location.href );               // reload page
   }
   else {
      WindowParams = "width="+width+",height="+height+",top=20,left=20,screenX=20,screenY=20,toolbar=0,location=0,status=0,menubar=0,directories=0,scrollbars=0,resizable=1,dependent=1,titlebar=0,copyhistory=0"
      window.name = "PmWebMain";
      var win = window.open ( url, "PmWebModalDialog", WindowParams ); // normal window
      if ( win != null )
         win.focus();
   }
  return true;
}

// -------------------------------------------------------------------------------- SB --
/// <summary>
/// Function to close pop-up dialog
/// </summary>
/// <param name="ReturnValue">Return value (int)</param>
/// <param name="RefreshOpener">Refresh opener window (bool)</param>
// --------------------------------------------------------------------------------------
function PCloseDialog ( ReturnValue, RefreshOpener )
{
   window.returnValue = ReturnValue;
   if (  IsDefined ( window.opener ) && RefreshOpener )
      window.opener.location.replace ( window.opener.location.href );
   window.close();
}

// -------------------------------------------------------------------------------- SB --
/// <summary>
/// Open browser window
/// </summary>
/// <param name="url">URL of page to open</param>
/// <param name="name">Name of window</param>
/// <param name="params">Paramerers of window</param>
// --------------------------------------------------------------------------------------
function POpenWindow ( url, name, params )
{
   var win = null;
   win = window.open ( url, name, params );
   if ( win != null )
      win.focus();
}

// -------------------------------------------------------------------------------- MP --
/// <summary>
/// Return string - rounded value
/// </summary>
/// <param name="ValueToRound">Value to round</param>
/// <param name="NumberOfDecimals">Number of decimals to show</param>
// --------------------------------------------------------------------------------------
function RoundValue ( ValueToRound, NumberOfDecimals )
{
   // Erroneous values to zero
   if (   !ValueToRound 
        || ValueToRound == Number.NaN
        || ValueToRound == Number.MAX_VALUE 
        || ValueToRound == Number.MIN_VALUE 
        || ValueToRound == Number.NEGATIVE_INFINITY 
        || ValueToRound == Number.POSITIVE_INFINITY )
      ValueToRound = 0;
   
   // Decimal factor is needed for getting the right accuracy
   var DecimalFactor = Math.pow ( 10, NumberOfDecimals );
   // This is the final rounded value, but if it's a double value,
   // but it may be missing some zeroes after decimal point.
   var RoundedValue = Math.round ( ValueToRound*DecimalFactor ) / DecimalFactor;
   
   // Put "." if the value is a double value and it misses decimal point
   if ( NumberOfDecimals > 0 ) {
      if ( RoundedValue == Math.floor ( RoundedValue ) )
         RoundedValue += '.';
   }              
   else // If the value is integer value (NumberOfDecimals == 0), it is ready. Return it.
      return RoundedValue;
           
   // Add the missing zeroes after decimal point
   for ( var i = NumberOfDecimals - 1; i >= 0; i-- )
      if ( RoundedValue * Math.pow(10, i) == Math.floor ( RoundedValue * Math.pow(10,i) ) )
         RoundedValue += '0';
               
   // Return the double value with needed accuracy
   return RoundedValue;
}

// -------------------------------------------------------------------------------- SB --
/// <summary>
/// Create client sniffer object which has all information about browser compatibility
/// </summary>
// --------------------------------------------------------------------------------------
function ClientSnifferJr(){
  this.ua=navigator.userAgent.toLowerCase();
  this.major=parseInt(navigator.appVersion);
  this.minor=parseFloat(navigator.appVersion);
  if (document.addEventListener && document.removeEventListener) this.dom2events=true;
  if (document.getElementById) this.dom1getbyid=true;
  if (window.opera){
    this.opera=true;
    this.opera5=(this.ua.indexOf("opera 5") !=-1 || this.ua.indexOf("opera/5") !=-1);
    this.opera6=(this.ua.indexOf("opera 6") !=-1 || this.ua.indexOf("opera/6") !=-1);
    this.opera5or6=this.opera5 || this.opera6;
    this.opera7=(this.ua.indexOf("opera 7") !=-1 || this.ua.indexOf("opera/7") !=-1);
    return;
  }
  this.konq=this.ua.indexOf('konqueror') != -1;
  this.safari=this.ua.indexOf('safari') != -1;
  this.ie=this.ua.indexOf('msie') !=-1;
  if (this.ie){
    this.ie3=this.major < 4;
    this.ie4=(this.major==4 && this.ua.indexOf('msie 5')==-1 && this.ua.indexOf('msie 6')==-1);
    this.ie4up=this.major >=4;
    this.ie5=(this.major==4 && this.ua.indexOf('msie 5.0') !=-1);
    this.ie5up=!this.ie3 && !this.ie4;
    this.ie6=(this.major==4 && this.ua.indexOf('msie 6.0') !=-1);
    this.ie6up=(!this.ie3 && !this.ie4 && !this.ie5 && this.ua.indexOf("msie 5.5")==-1);
    return;
  }
  this.hotjava=this.ua.indexOf('hotjava') !=-1;
  this.webtv=this.ua.indexOf('webtv') !=-1;
  this.aol=this.ua.indexOf('aol') !=-1;
  if (this.hotjava || this.webtv || this.aol) return;
  // Gecko, NN4, and NS6
  this.gecko=this.ua.indexOf('gecko') !=-1;
  this.nav=(this.ua.indexOf('mozilla') !=-1 && this.ua.indexOf('spoofer')==-1 && this.ua.indexOf('compatible')==-1);
  if (this.nav){
    this.nav4=this.major==4;
    this.nav4up=this.major >=4;
    this.nav5up=this.major >=5;
    this.nav6=this.major==5;
    this.nav6up=this.nav5up;
  }
}

window.is = new ClientSnifferJr();

// -------------------------------------------------------------------------------- SB --
/// <summary>
/// Return width of browser window
/// </summary>
// --------------------------------------------------------------------------------------
function WindowWidth(){
  var w=0;
  if (is.opera5or6){w=window.innerWidth;}
  else if (is.ie && document.documentElement && document.documentElement.clientWidth) w=document.documentElement.clientWidth; // ie6 compat mode
  else if (document.body && document.body.clientWidth) w=document.body.clientWidth; // ie4up and gecko
  else if (IsDefined(window.innerWidth,window.innerHeight,document.height)){// nn4
    w=window.innerWidth;
    if (document.height > window.innerHeight) w -=16;
 }
  return w;
}

// -------------------------------------------------------------------------------- SB --
/// <summary>
/// Return height of browser window
/// </summary>
// --------------------------------------------------------------------------------------
function WindowHeight(){
  var h=0;
  if (is.opera5or6){h=window.innerHeight;}
  else if (is.ie && document.documentElement && document.documentElement.clientHeight) h=document.documentElement.clientHeight;
  else if (document.body && document.body.clientHeight) h=document.body.clientHeight;
  else if (IsDefined(window.innerWidth,window.innerHeight,document.width)){
    h=window.innerHeight;
    if (document.width > window.innerWidth) h -=16;
 }
  return h;
}

// -------------------------------------------------------------------------------- SB --
/// <summary>
/// Disable all form elements and create div to protect page from accidental click
/// </summary>
// --------------------------------------------------------------------------------------
function DisablePageOnFormSubmit()
{
   return true;
   if ( IsDefined ( document.forms[0].nodisabling ) )       // do not disable form in some cases
      return true;

   if ( document.forms[0].submitted ) 
      return false;                                         // form already submitted

   document.forms[0].submitted = true;
   
   // disable all form elements disabled: disabled items can't post back
//   for ( var i = 0; i < document.forms[0].elements.length; i++ )
//       document.forms[0].elements[i].disabled = true;       // disable all form elements
       
   if ( !IsDefined ( document.createElement ) )
     return true;
   
   var div = document.createElement ( 'div' );              // create "div"  to hide page
   div.setAttribute ( 'id', "DisablePageDiv" );
   div.style.position         = 'absolute';
   div.style.left             = 0;
   div.style.top              = 0;
   div.style.width            = WindowWidth();
   div.style.height           = WindowHeight();
   div.style.backgroundImage  = "url(../images/empty.gif)";
   div.style.zIndex           = "9999";
  
   if ( !IsDefined ( document.getElementsByTagName ) )       // add div to page
     return true;
   
   document.getElementsByTagName('body').item(0).appendChild(div);
   
   return true;
}

// -------------------------------------------------------------------------------- SB --
/// <summary>
/// Function to return the value of the cookie specified by "name".
/// </summary>
// --------------------------------------------------------------------------------------
function GetCookie(name)
{
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;

  while ( i < clen ) {
    var j = i + alen;
    if ( document.cookie.substring(i, j) == arg ) {
      var endstr = document.cookie.indexOf ( ";", j );
      if ( endstr == -1 )
         endstr = document.cookie.length;
      return unescape ( document.cookie.substring(j, endstr) );
    }
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break;
  }
  return null;
}

// -------------------------------------------------------------------------------- SB --
/// <summary>
/// Function to create or update a cookie.
/// </summary>
// --------------------------------------------------------------------------------------
function SetCookie(name, value)
{
  var argv = SetCookie.arguments;
  var argc = SetCookie.arguments.length;

  var expires = (argc < 2) ? argv[2] : null;
  var path    = (argc < 3) ? argv[3] : null;
  var domain  = (argc < 4) ? argv[4] : null;
  var secure  = (argc < 5) ? argv[5] : false;


  document.cookie = name + "=" + escape (value) +
    ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
    ((path == null) ? "" : ("; path=" + path)) +
    ((domain == null) ? "" : ("; domain=" + domain)) +
    ((secure == true) ? "; secure" : "");
}

// -------------------------------------------------------------------------------- SB --
/// <summary>
/// Function to delete a cookie. (Sets expiration date to current date/time)
/// </summary>
// --------------------------------------------------------------------------------------
function DeleteCookie(name)
{
  var exp = new Date();

  exp.setTime (exp.getTime() - 1);  // This cookie is history

  var cval = GetCookie (name);

  document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}

// -------------------------------------------------------------------------------- SB --
/// <summary>
/// Function to set enabled/disable classes for input controls
/// </summary>
// --------------------------------------------------------------------------------------
function SetButtonStyle()
{
   var arrInputs = document.getElementsByTagName('BUTTON');
   // find all inputs
   for ( i = 0; i < arrInputs.length; i++ ) {
      if ( arrInputs[i].type == 'submit' || arrInputs[i].type == 'button' ) {
         var index_disabled = arrInputs[i].className.indexOf ( "_disabled", 0 );
         if ( index_disabled == -1 && arrInputs[i].disabled == true )
            arrInputs[i].className = arrInputs[i].className + "_disabled";
         if ( index_disabled != -1 && arrInputs[i].disabled == false )
            arrInputs[i].className = arrInputs[i].className.slice ( 0, index_disabled );
      }
   }
}


