/**
 * @file            common.js
 * @project         DWI
 * @company         CompEd Software Design
 * @author          Yury Fedorov
 * @reason          The script file contains all scripts sharable by DWI project.
 * @created
 * @last_revision   09-Sep-2005
 * @version         3.1.2.52
 * @history         07-Mar-2003 Yury Fedorov: new version created
                    17-May-2005 Pasko Boris: Header changed, code reformatted
                    20-May-2005 Pasko Boris: Added date checking functon
                                isBadDate()
                    23-May-2005 Pasko Boris: Modified isBadDate() to deal with
                                different date formats (mm/dd/yy, dd/mm/yyyy)
                    20-Jun-2005 Pasko Boris: added trim() function
                    21-Jun-2005 Pasko Boris: fixed function isBadDate (2 symbol
                                years were always treated like invalid, bug 689)
                    23-Jun-2005 Pasko Boris: For some reason, standard
                                JavaScript function parseInt can't parse
                                strings with leading spaces (for example '09').
                                I've added new function parseInt2 that cuts off
                                leading spaces and after that passes string to
                                parseInt
                    01-Jul-2005 Pasko Boris: Fixed up parseInt2 to correctly
                                parse 19/09/2003. The case was that IE does not
                                recognize string indexes, while Mozilla does.
                                So now i use charAt method.
                    09-Jul-2005 new feature #746: added functions on_open,
                                on_close, add_window, remove_window, setCookie
                                and getCookie, isReallyClosed, logout.
                                Now every page in project (except for index.jsp
                                and static pages) should call on_open when it
                                is opened (onLoad event) and on_close when it is
                                unloaded (onUnload event).
                                on_open increments number of opened windows
                                every time it is called with add_window function.
                                on_close decrements number of windows by calling
                                remove_window and, if current window was really
                                closed (not refreshed, for example), then logs
                                user out.
                                add_window and remove_window keep track of the
                                number of opened windows using cookies accessed
                                by getCookie and setCookie.
                    20-Jul-2005 Pasko Boris: Turned off feature 746 from
                                v3.1.2.23. It does not work properly, causing
                                bugs. I turned it off by commenting all code in
                                on_close and some code in on_open.
                                Also, to fix To fix bug 801 i added parameter to
                                on_open that will set current window name. Most
                                windows should skip this parameter, but searh
                                and filter windows should supply their names.
                   27-Jul-2005 Pasko Boris: BUGFIX 819. Changed year range to
                               1753-9999 in isBadDate()
                   08-Aug-2005 Pasko Boris: New feature. General Search.
                               added generalSearchClick() function
                   09-Sep-2005 Pasko Boris: BUGFIX 870 Cant use one-symbol
                               search criterion. fixed trim() function.
                   29-Dec-2005 Igor Kohanovsky: BUGFIX 1185 ('Codoce errore NULL'
                               when you try to enter nothing (delete the content
                               during editting) into the fields of
                               Numeric Decimal, Numeric Integer and Date format.)
                               Actions performed: added trim2() function.
                  28-Jul-2006  Alexey Dyachenko: BUGFIX 1107
                  		(Auxiliary windows like "Filter", "Full text search", "New document"
                  		  must not contain menu, status text, toolbars)
                               Actions performed: activateDW() function was added.
                  22-Sep-2006  Alexey Dyachenko: 
                                BugFix 1294 (The possibility of limiting Global Search to a selected area)
                                Actions performed: added parameter for generalSearchClick() method 
                  12-Oct-2006  Alexey Dyachenko: 
                                Bug 2083 (Not enough space for volume fields on the "Nuovo" form)
                                Actions performed: added parameter "scrollbars" in activateDW function   
                  30-Oct-2006 Alexey Dyachenko: 
                                Bug 2005 (Wrong mask of the Date format is suggestid for the user on the 'Ricerca Generale' page.)
                                Actions performed: main corrections are done in "isBadDate" and in "italianDateFmt" functions
                                                   added - "dateFormat" class and "isValidDate" function  
 * Copyright (c) CompEd Software Design 2001-2005
 */
function on_open(windowname)
{
  window.name=windowname;
  // alert("win="+window.name);
  // Function increments total number of DWI windows every time it is called.
  // This function should be called from onLoad event of every page in project
  // that has to be accessed from DWI session. These are all .jsp pages except
  // for the index.jsp
  // var count = add_window();
  //alert("add:"+count);
  //add_window();
}
function on_close()
{
  // Function decrements total number of DWI windows every time it is called.
  // Then, it determines if current window was really closed and not refreshed.
  // If so, it logs user out.
  // var count = remove_window();
  // alert("close:"+count);
  //if (count<=0&&isReallyClosed())
  //	logout();
}
function add_window()
{
	// Function increments total number of DWI windows using cookie
        // dwi_windows_total.
        // It returns then current total number.
	var total = getCookie("dwi_windows_total");
	if (!total)
	{
		total = 1;
	} else {
		total = parseInt(total);
		total++;
	}
	setCookie("dwi_windows_total", ""+total);
	return total;
}
function remove_window()
{
	// Function decrements total number of DWI windows using cookie
        // dwi_windows_total.
        // It returns then current total number.
	var total = getCookie("dwi_windows_total");
	if (!total)
	{
		return 1;
	} else {
		total = parseInt(total);
		total--;
	}
	setCookie("dwi_windows_total", ""+total);
	return total;
}
function get_windows_count()
{
  var total = getCookie("dwi_windows_total");
  return parseInt(total);
}
// Create a cookie with the specified name and value.
// The cookie expires at the end of the session.
function setCookie(sName, sValue)
{
  date = new Date();
  document.cookie = sName + "=" + escape(sValue) ;//+ "; expires=" + date.toGMTString();
}

function setPermanentCookie(sName, sValue)
{
  var date = new Date();
  date.setYear(date.getYear()+1);
  document.cookie = sName + "=" + sValue + "; expires=" + date.toGMTString();
}

// Retrieve the value of the cookie with the specified name.
function getCookie(sName)
{
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    // a name/value pair (a crumb) is separated by an equal sign
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0])
      return unescape(aCrumb[1]);
  }

  // a cookie with the requested name does not exist
  return null;
}
function isReallyClosed()
{
  // Function returns true if current window was really closed (not refreshed)
  if (window.closed) return true;
  var top=self.screenTop;
  if (top>9000) {
     return true;
  } else {
    return false;
  }
}

function logout()
{
  	alert("logout");
       	window.open("servlet/login?p1=LOG_OUT&autoclose=1");
}

function go2( address )
{
    getRoot().document.location.href = encodeUrl( address );
}

function openWnd( address )
{
	return window.open( encodeUrl( address ) );
}

function onHelp( page2go )
{
	var w       = null;
	var name    = "Aiuto";
    /* @todo: remove after debug of 10.3
	if ( isNN() )
	{
		w = window.open( page2go, name );
	}
	else
	{
		w = window.showModelessDialog( page2go, name,
		 "dialogHeight:  400px; dialogWidth:    400px; "   +
		 "dialogTop:     50px;  dialogLeft:     400px; "   +
		 "edge: Sunken; center: No; help: No; resizable: Yes; status: No;" );
	}
    */
    w = window.open( page2go, name,
                     "height=400,width=400,scrollbars=1,resizable=1" );
	w.focus();
}

function getRoot()
{
	var root = window;
	while ( true )
	{
		var r = root.parent;
		if ( r == root || r == null )
		{
			break;
		}
		root = r;
	}
	return root;
}

function getDocObj( doc, name )
{
	// the function got from the site for transplatform DHTML
	if ( doc.getElementById )
	{
		// return doc.getElementById( name ).style;
		return doc.getElementById( name );
	}
	else if ( doc.all )
	{
		return doc.all[name].style;
	}
	else if ( document.layers )
	{
		return doc.layers[name];
	}
}

function getObj( name )
{
	return getDocObj( document, name );
}

function activate( href, name )
{

        var go2 = encodeUrl( href );
        var w = window.open( go2, name );
	w.focus();
	return w;
}

function activateDW( href, name )
{
	var go2 = encodeUrl( href );
        var w = window.open(go2,name,'width=640,height=480,toolbar=no,status=no,menubar=no,resizable=yes,scrollbars=yes');
	w.focus();
	return w;
}

/**
 * Returns the name of the window for the browser.
 * @param   volumeName  - the name of the volume.
 * @param   windowClass - the name of the class.
 * @return  returns the name of the window.
 */
function getWndName( volumeName, windowClass )
{
	var wndName = windowClass + "_";
	for ( var i = 0; i < volumeName.length; i++ )
	{
		wndName = wndName.concat( volumeName.charCodeAt( i ) );
	}
	return wndName;
}

// Sveta added the methods for dynamic menu. They're not used.
function newImage(arg) {
	if (document.images) {
		rslt = new Image();
		rslt.src = arg;
		return rslt;
	}
}
function changeImages() {
	if (document.images && (preloadFlag == true)) {
		for (var i=0; i<changeImages.arguments.length; i+=2) {
			document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
		}
	}
}

/**
 * The method replaces all spaces onto %20 sequencies.
 */
function encodeUrl( strIn )
{
	return strIn.replace (" ", "%20");
}

/**
 * Creates a link to navigate to the top of the page.
 */
function updateToTopLink()
{
	if ( isNN() )
	{
		document.getElementById( 'pToTop' ).style.visibility = "hidden";
	}
}

function isOpera()
{
	return navigator.userAgent.indexOf( "Opera" ) >= 0;
}

function isNN()
{
	return navigator.appName == "Netscape" || isOpera();
}

/**
 * Supposes that there're only IE and NN.
 */
function isIE()
{
	return !isOpera() && navigator.appName == "Microsoft Internet Explorer";
}

/**
 * @since 11.1
function onLogoff()
{
	go2( 'servlet/login?p1=LOG_OUT' );
}
 */

/**
 * The window is closed and the its parent is activated
 * and refreshed if necessary.
 * @since 10.12
 */
function go2parent( refresh )
{
    if ( refresh )
    {
        // reloads the page from the server
        window.opener.location.reload( true );
    }
    window.opener.focus();
    window.close();
}

/**
 * Returns encoded URL for openening volume specified.
 * @since 10.15
 */
function getVolumeHref( volume )
{
    return encodeUrl( "volume.jsp?volume=" + volume );
}

/**
 * The current windows closes (filter, search). Its parent is activated
 * the content of the volume specified shown.
 * @since 10.15
 */
function showAllDox( volume )
{
    window.opener.location.href = getVolumeHref( volume );
    window.opener.focus();
    window.close();
}

/**
 * Reads a cookie.
 * @return the cookie.
 * @since 10.13
function readCookie( name )
{
    name += "=";
    var str = document.cookie;
    var j = str.indexOf( name, 0 );
    if ( j < 0 ) return "";
    j += name.length;
    var n = str.indexOf( ";", j );
    if ( n < 0 ) n = str.length;
    return unescape( str.substring( j, n ) );
}
*/

/**
 * Write a cookie.
 * @since 10.13
function writeCookie( name, data, dt )
{
    var dtExp = new Date();
    dtExp.setDate( dtExp.getDate() + dt );
    document.cookie = name + "=" + escape( data ) +
                      ";expires=" + dtExp.toGMTString() + ";path=/dfm_web";
}
 */
var systemDateFormat = "dd/mm/yyyy"; // by 

/*
 * Date Structure 
 */
function dateFormat(day,month,year)
{
        this.day = day;
        this.month = month;
        this.year = year;
        this.ysimb = false; //if the year part of the date format consists of 4 symbols 
}
/*
 * Parses the inputted date and fills dateFormat structure
 * also the validity check is executed here   
*/
 
function isValidDate(str,format)
{
   var dateValue = new dateFormat(0,1,2); 
   var d = /d/; var m = /m/; var y = /y/;
   
   var datef = format.split('/'); // date templet
   var datev = str.split('/'); // inputted date
   
   if (datev.length < 3) return false;
   
   for(var i = 0; i < datef.length; i++)
   {
      if (!isInteger(datev[i])) return false;
      
      
      if (d.test(datef[i])) dateValue.day = datev[i];
      if (m.test(datef[i])) dateValue.month = datev[i];
      if (y.test(datef[i])) 
      { 
        if (datev[i].length < datef[i].length) return false;
        dateValue.year = datev[i];
        dateValue.ysimb  = datef[i].length > 2 ? true: false; 
      }
   }
   return dateValue;
}

function isBadDate(str, format)
{
  var date;
  
  if (format==null) format = systemDateFormat;
   
  if (!(date = isValidDate(str,format))) return true;
 
  if (date.day < 0 || date.day > 31) return true;
  if (date.month < 0 || date.month > 12) return true;
  
  if (date.ysimb && date.year < 1753) return true;
  if (date.ysimb && date.year > 9999) return true;
  if (!date.ysimb && date.year < 0) return true;
  if (!date.ysimb && date.year > 99) return true;
 
  var day = parseInt2(date.day);
  var month = parseInt2(date.month);
  var year = parseInt2(date.year);

  date = new Date(year, month-1, day);
  date = new Date(date.getTime());

  if (day!=date.getDate()) return true;
  if (month!=date.getMonth()+1) return true;
   
  return false;
}

function parseInt2(s)
{
  s = "0"+s;
  while (s.length>0 && s.charAt(0)=='0') s = s.substr(1);
  return parseInt(s);
}

function isInteger(s){
  var i;
  for (i = 0; i < s.length; i++){
    // Check that current character is number.
    var c = s.charAt(i);
    if ((c < "0" || c > "9") && c!=" ") return false;
  }
  // All characters are numbers.
  return true;
}

function italianDateFmt(format)
{
    
  if (format==null) format = systemDateFormat;
 
  var d = /d/g;
  var y = /y/g;
 
  f = format.replace(d,"g"); 
  f = f.replace(y,"a");
 
  return f;
}

function trim(s)
{
  while (s.length>0 && s.charCodeAt(0)==0x20)
  {
    if (s.length<=1) return "";
    s = s.substr(1);
  }
  while (s.length>0 && s.charCodeAt(s.length-1)==0x20)
  {
    if (s.length<=1) return "";
    s = s.substring(0, s.length-2);
  }
  return s;
}

function trim2(s)
{
// 0xA0 -  "&nbsp;" value
  while (s.length>0 && (s.charCodeAt(0)==0x20 || s.charCodeAt(0)==0xA0) )
  {
    if (s.length<=1) return "";
    s = s.substr(1);
  }
  while (s.length>0 && (s.charCodeAt(s.length-1)==0x20 || s.charCodeAt(s.length-1)==0xA0) )
  {
    if (s.length<=1) return "";
    s = s.substring(0, s.length-2);
  }
  return s;
}

var _GlobalSearchWindow = null;

function generalSearchClick(areaName)
{
	if (_GlobalSearchWindow == null || _GlobalSearchWindow.closed)
	{
		var href = "gsearch.jsp?"+areaName;
		_GlobalSearchWindow =
			activate(  href, "gsearch" );
	}
        _GlobalSearchWindow.focus();
	// window.focus();
	// r._searchWindow.focus();
}
