//
//	$Id: Util.js,v 1.9 2004/04/30 08:02:19 vchiperi Exp $
//	Tag $Name: B60-07/13/2005 $
//

/*
* --------------------------------------------------------------------
* FUNCTION : validateFields()
* --------------------------------------------------------------------
* DESCRIPTION: validates some fields
* PARAMETERS:
*   valFields - fields array
* OUTPUT : true or false
* --------------------------------------------------------------------
*/
function validateFields(valFields){
 for(var i=0; i<valFields.length; i++)
 {
     if (valFields[i][0] !=""){
         var valObj = document.getElementById(valFields[i][0]);
         StripBlanks(valObj);
          if (valObj.value !="" && valFields[i][3] !="number" && valFields[i][5]
                && valFields[i][5] == "valsymb" && !validField(valObj.value)) {
            alert(res_insertValid + ' \''+valFields[i][1]+'\' '+ res_value + '. \n \''+valFields[i][1]+'\' '+ res_cantcontain);valObj.focus();
            return false;
            }
            if (valFields[i][0] == "datasets" && valObj.value =="") {
            alert('You must include at least one dataset'); return false;
            }
            else {
          if (valFields[i][4] == "1" && valFields[i][2] != "select"  && valObj.value =="" && valFields[i][0] != "datasets") {
                 alert(res_insert + ' \''+valFields[i][1]+'\' '+res_value);valObj.focus(); return false;
            }    
          if (valFields[i][4] == "1" && valFields[i][2] == "select" && !valObj.options[0]
                && valObj.value =="" && valFields[i][0] != "datasets") {
                  alert(res_insert + ' \''+valFields[i][1]+'\' '+res_value);valObj.focus(); return false;
            }    
    	  if (valFields[i][4] == "1" && valFields[i][2] == "select"
    	        && valObj.options[0] && valObj.value =="" && valFields[i][0] != "datasets") {
    		    alert(res_select + ' \''+valFields[i][1]+'\' '+res_value);valObj.focus(); return false;
    	    }    
    	    }
          if (valObj.value !="" && valFields[i][3] =="email"
                && CheckEMailAddress(valObj.value) !="") {
            alert(CheckEMailAddress(valObj.value)); valObj.focus(); return false;
            }    
          if (valObj.value !="" && valFields[i][3] == "phone" && !CheckPhone(valObj.value)) {
            alert(res_insertValid + ' \''+valFields[i][1]+'\' '+res_value + ' ('+ res_allowed +
                ': \'0-9\', \'+\', \'-\', \'(\', \')\', \' \') ');valObj.focus(); return false;
                }       
          if (valObj.value !="" && valFields[i][3] == "number"
              && !CheckInt( valObj, 0, valFields[i][5])) {
            alert(res_insertValid + ' \''+valFields[i][1]+'\' '+res_value);valObj.focus();
            return false;
            }      
          if (valObj.value !="" && valFields[i][3] == "date" && valFields[i][5]
              && valFields[i][5]!=""
              &&!compDates(document.getElementById(valFields[i][5]).value,valObj.value,
              valFields[i][6], valFields[i][1])) {
                return false;
          }     
      }
 }
 return true;
}


/*
* --------------------------------------------------------------------
* FUNCTION : compDates()
* --------------------------------------------------------------------
* DESCRIPTION: compare 2 data consecutivity long input format
* PARAMETERS:
*   start - start date value (float)
*   end -   end date value (float)
*   startName - Name of the field, string
*   endName - Name of the end field, string
* OUTPUT : true or false
* --------------------------------------------------------------------
*/
function compDates(start,end,startName,endName) {
   if (parseFloat(start)>parseFloat(end)) {
        alert("'"+startName+"'"+" "+res_mustNotBeGreater+" "+"'"+endName+"'");
        return false;
   } else {
        return true;
   }
}


/*
* --------------------------------------------------------------------
* FUNCTION : Trim()
* --------------------------------------------------------------------
* DESCRIPTION: trims white spaces from a text field
* PARAMETERS:
*   field - input field, object
* OUTPUT : no
* --------------------------------------------------------------------
*/
function Trim(field){
	field.value = (field.value.replace(/^\s+/,"")).replace(/\s+$/,"");
}

/*
* --------------------------------------------------------------------
* FUNCTION : CheckPhoneNumber()
* --------------------------------------------------------------------
* DESCRIPTION: checks a phone number and returns true/false
* PARAMETERS:
*   TheNumber - number, string/int
* OUTPUT : boolean
* --------------------------------------------------------------------
*/
function CheckPhoneNumber(TheNumber) {
	var valid = 1;
	var GoodChars = "0123456789";
	var i = 0;
	if (TheNumber=="") {
		valid = 0;
	}
	for (i =0; i <= TheNumber.length -1; i++) {
		if (GoodChars.indexOf(TheNumber.charAt(i)) == -1) {
   			valid = 0;
   			return valid;
		}
	}
	return valid;
}



/*
* --------------------------------------------------------------------
* FUNCTION : CheckPhone()
* --------------------------------------------------------------------
* DESCRIPTION: checks a phone number and returns true/false
*              validation with additional characters
* PARAMETERS:
*   TheNumber - phone number, string
* OUTPUT : boolean
* --------------------------------------------------------------------
*/
function CheckPhone(TheNumber) {
	var valid = 1;
	var GoodChars = "0123456789()+- ";
	var i = 0;
	if (TheNumber=="") {
		valid = 0;
	}
	for (i =0; i <= TheNumber.length -1; i++) {
		if (GoodChars.indexOf(TheNumber.charAt(i)) == -1) {
   			valid = 0;
   			return valid;
		}
	}
	return valid;
}



/*
* --------------------------------------------------------------------
* FUNCTION : CheckEMailAddress()
* --------------------------------------------------------------------
* DESCRIPTION: checks email valability
* PARAMETERS:
*   address - email address, string
* OUTPUT : returns void string if valid, message if erroneous
* --------------------------------------------------------------------
*/
function CheckEMailAddress(address)
{
	if (!validEmailField(address)) {
		return res_emailinvalid;
	}
	var emailPat	= /^(.+)@(.+)$/;
	var specialChars= "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
	var validChars	= "\[^\\s" + specialChars + "\]";
	var quotedUser	= "(\"[^\"]*\")";
	var ipDomainPat	= /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom		= validChars + '+';
	var word		= "(" + atom + "|" + quotedUser + ")";
	var userPat		= new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat	= new RegExp("^" + atom + "(\\." + atom +")*$");

	var matchArray = address.match(emailPat);

	if( matchArray == null) {
		return res_emailinvalid2;
	}

	var user = matchArray[1];
	var domain = matchArray[2];

	if( user.match(userPat) == null) {
		return res_badusername;
	}

	var IPArray = domain.match(ipDomainPat);

	if( IPArray != null) {
		for( var i = 1; i <= 4; i++) {
			if( IPArray[i] > 255) {
				return res_badip;
			}
		}
	}

	var domainArray = domain.match(domainPat)
	if( domainArray == null) {
		return res_domain;
	}

	var atomPat = new RegExp(atom,"g");
	var domArr = domain.match(atomPat);
	var len = domArr.length;
	if( domArr[domArr.length-1].length < 2 ||
		domArr[domArr.length-1].length > 3) {
		return res_emailinvalid3;
	}

	if( len < 2) {
		return res_nohostname;
	}

	return "";
}


/*
* --------------------------------------------------------------------
* FUNCTION : CheckInt()
* --------------------------------------------------------------------
* DESCRIPTION: checks an int field value against specified range
* PARAMETERS:
*    field - text field, object
*    minVal - minimal int to check against
*    maxVal - maximal int to check against
* OUTPUT : boolean
* --------------------------------------------------------------------
*/
function CheckInt(field, minVal, maxVal) {
	Trim(field);
	if( ! /^[+-]?\d+$/.test(field.value)) { FocusOn(field); return false; }
	if( arguments.length >= 2) {
		var n = parseInt(field.value,10);
		if( n < minVal || n > maxVal) { FocusOn(field); return false; }
	}
	return true;
}


/*
* --------------------------------------------------------------------
* FUNCTION : CheckFloat()
* --------------------------------------------------------------------
* DESCRIPTION: checks an float field value against specified range
* PARAMETERS:
*    field - text field, object
*    minVal - minimal int to check against
*    maxVal - maximal int to check against
* OUTPUT : boolean
* --------------------------------------------------------------------
*/
function CheckFloat(field, minVal, maxVal){
	Trim(field);
	if( ! /^[+-]?\d+(\.\d*)?$/.test(field.value)) { FocusOn(field); return false; }
	if( arguments.length >= 2) {
		var n = parseFloat(field.value);
		if( n < minVal || n > maxVal) { FocusOn(field); return false; }
	}
	return true;
}


/*
* --------------------------------------------------------------------
* FUNCTION : FocusOn()
* --------------------------------------------------------------------
* DESCRIPTION: focuses on a field
*              does not work in NS:
* PARAMETERS:
*    field - text field, object
* OUTPUT : no
* --------------------------------------------------------------------
*/
function FocusOn(field){
	if( gBrowser == 'ie') {
		field.focus();
		if( field.select) field.select();
	}
}


/*
* --------------------------------------------------------------------
* FUNCTION : IsGroupChecked()
* --------------------------------------------------------------------
* DESCRIPTION: Is one of check boxes or radio buttons checked?
* PARAMETERS:
*    form - a form
*    name - name of elements to check
* OUTPUT : no
* --------------------------------------------------------------------
*/
function IsGroupChecked(form,name)
{
	var elements = document.getElementsByName(name);
	if( elements.length <= 0) return false; 
	var selected = false;
	for(var i = 0;i< elements.length; ++i)
		if(elements[i].checked) {selected = true; break;}
	if(!selected) {
		elements[0].focus();
		return false;
	}
	return true;
}


/*
* --------------------------------------------------------------------
* FUNCTION : SelectAll()
* --------------------------------------------------------------------
* DESCRIPTION: Perform "select all", "unselect all" and "invert selection"
*              on a group of checkboxes
* PARAMETERS:
*	mode:	 0 -- unselect all
*	         1 -- select all
*	        -1 -- invert selection
*    name - name of elements to select
* OUTPUT : no
* --------------------------------------------------------------------
*/
function SelectAll(name,mode)
{
	if( arguments.length < 2) mode = 1;
	var elements = document.getElementsByName(name);
	if( elements.length <= 0) return;
	for( var i = 0; i < elements.length; ++i) {
		var element = elements[i];
		switch(mode) {
		case -1: element.checked = ! element.checked; break;
		case false:
		case  0: element.checked = false; break;
		case true:
		case  1: element.checked = true; break;
		}
	}
}


/*
* --------------------------------------------------------------------
* FUNCTION : checkDateFormat(element)
* --------------------------------------------------------------------
* DESCRIPTION: Check a date value in dd/mm/yyyy format
* PARAMETERS:
*    element - element to check, object
* OUTPUT : boolean
* --------------------------------------------------------------------
*/
function checkDateFormat(element) {
	Trim(element);
	if( ! /(\d{1,2})[\/|-](\d{1,2})[\/|-](\d{4})$/.test(element.value)) {
		
		alert(res_dateformat);
		return false;
	}
	return true;
}


/*
* --------------------------------------------------------------------
* FUNCTION : checkDateFormat(element)
* --------------------------------------------------------------------
* DESCRIPTION: Check a date value in dd/mm/yy format
* PARAMETERS:
*    element - element to check, object
* OUTPUT : boolean
* --------------------------------------------------------------------
*/
function checkShortDateFormat(element) {
	Trim(element);
	if (is_empty(element)) return false;
	if( ! /(\d{1,2})[\/|-](\d{1,2})[\/|-](\d{2})$/.test(element.value)) {
		FocusOn(element);
		alert(res_shortdateformat);
		return false;
	}
	return true;
}


/*
* --------------------------------------------------------------------
* FUNCTION : CheckDate(element)
* --------------------------------------------------------------------
* DESCRIPTION: Check a date value in dd/mm/yyyy format
* PARAMETERS:
*    element - element to check, object
* OUTPUT : boolean
* --------------------------------------------------------------------
*/
function CheckDate(element)
{
	Trim(element);
	if( ! /(\d{1,2})[\/|-](\d{1,2})[\/|-](\d{4})$/.test(element.value)) {
		FocusOn( element);
		alert(res_dateformat);
		return false;
	}

	var d = Number(RegExp.$1);
	var m = Number(RegExp.$2)-1;
	var y = Number(RegExp.$3)


	var t = new Date(y, m, d);

	if(t.getDay()!=d || t.getMonth()!=m || t.getYear()!=y) {
		FocusOn(element);
		alert(res_inexistingdate);
		return false;
	}

	return true;
}


/*
* --------------------------------------------------------------------
* FUNCTION : DateToXML(element)
* --------------------------------------------------------------------
* DESCRIPTION: Convert a date to XML format: "yyyymmddhhnnss"
* PARAMETERS:
*    date - a date object
* OUTPUT : obj
* --------------------------------------------------------------------
*/
function DateToXML(date)
{
	if(arguments.length <= 0) date = new Date();
	return	date.getFullYear() + Format0(date.getMonth()+1) +
			Format0(date.getDate()) + Format0(date.getHours()) +
			Format0(date.getMinutes()) + Format0(date.getSeconds());
}


/*
* --------------------------------------------------------------------
* FUNCTION : encodeURIComponent()
* --------------------------------------------------------------------
* DESCRIPTION: Encode URI parameter
* PARAMETERS:
*    uri - uri string
* OUTPUT : string
* --------------------------------------------------------------------
*/
function encodeURIComponent(uri)
{
	return uri.replace(
		/\W/g,
		function($0)
		{
			return "%" + $0.charCodeAt(0).toString(16);
		}
	);
}


/*
* --------------------------------------------------------------------
* FUNCTION : Format0()
* --------------------------------------------------------------------
* DESCRIPTION: Used to format number for hours/dates
* PARAMETERS:
*    s - string
* OUTPUT : formatted string
* --------------------------------------------------------------------
*/
function Format0( s)
{
	s = "" + s;
	switch( s.length) {
	case 0:		return "00";
	case 1:		return "0" + s;
	default:	return s;
	}
}

/*
* --------------------------------------------------------------------
* FUNCTION : File_getName()
* --------------------------------------------------------------------
* DESCRIPTION:	Get the file name part of a full path
*               path -- the full path
*               returns: the file name
* PARAMETERS:
*    path - path,string
* OUTPUT : string
* --------------------------------------------------------------------
*/
function File_getName(path)
{
	var i = path.indexOf(":");
	var j = path.lastIndexOf("/");
	var k = path.lastIndexOf("\\");
	var l = path.lastIndexOf(".");
	if( i < j) i = j;
	if( i < k) i = k;
	if( i < 0) i = -1;
	if( l < 0) l = path.length;
	return path.substring(i+1, l);
}

/*
* --------------------------------------------------------------------
* FUNCTION : File_getExt()
* --------------------------------------------------------------------
* DESCRIPTION:	Get the extension part of a full path
*	            path -- the full path
*	            returns: the extension without dot; can be an empty string
* PARAMETERS:
*    path - path,string
* OUTPUT : string
* --------------------------------------------------------------------
*/
function File_getExt(path)
{
	var i = path.lastIndexOf(".");
	return i < 0 ? "" : path.substring(i+1);
}

/*
* --------------------------------------------------------------------
* FUNCTION : File_checkName()
* --------------------------------------------------------------------
* DESCRIPTION:	check the correctness of a file name
* PARAMETERS:
*    s - string
*    allowDot - boolean
* OUTPUT : boolean
* --------------------------------------------------------------------
*/
function File_checkName(s,allowDot)
{
	if( s.length == 0) return false;
	if( !/\S/.test(s)) return false;
	if( arguments.length < 2) allowDot = false;
	for( var i = 0; i < s.length; ++i) {
		var c = s.charAt(i);
		if(( ! allowDot && c == '.') ||
		(!(( c >= 'a' && c <= 'z')
		 || ( c >= 'A' && c <= 'Z')
		 || ( c >= '0' && c <= '9')
		 || ( " -_()[].".indexOf(c) >= 0)))) return false; 
	}
	if( allowDot && (s.charAt(0) == '.')) return false;
	return true;
}
/*
* --------------------------------------------------------------------
* FUNCTION : sprintf()
* --------------------------------------------------------------------
* DESCRIPTION: Format a message with replacements:
* 	           %1, %2, ... %9 are replaced with arguments, %% is replaced with "%"
* 	           Sample usage:
* 	           alert( sprintf( "The file %1 is not found on drive %2", "a.txt", "c:"));
* PARAMETERS:
*    format - string
* OUTPUT : string, formatted
* --------------------------------------------------------------------
*/
function sprintf(format )
{
	var s = "";
	for( var i = 0; i < format.length; ++i)
	{
		var c = format.charAt(i);
		switch( c) {
		case '%':
			var n = format.charAt(++i);
			switch( n) {
			case '%':
				s += '%';
			break;
			default:
				n = parseInt(n,10);
				if( isNaN(n))
					s += 'ERROR';
				else
					s += arguments[n];
			}
		break;
		default:
			s += c;
		}
	}
	return s;
}

/*
* --------------------------------------------------------------------
* FUNCTION : RemoveEmptyOption()
* --------------------------------------------------------------------
* DESCRIPTION: 	remove first option element of a select element, if the
*               value is empty
* PARAMETERS:
*    select - select object
* OUTPUT : no
* --------------------------------------------------------------------
*/
function RemoveEmptyOption(select)
{
	var options = select.getElementsByTagName("option");
	if( options.length <= 0) return;
	var option0 = options.item(0);
	if( option0.value.length == 0)
		select.removeChild(option0);
}

/*
* --------------------------------------------------------------------
* FUNCTION : AddEmptyOption()
* --------------------------------------------------------------------
* DESCRIPTION: 	ensure the first option of a select element is empty
* PARAMETERS:
*    select - select object
* OUTPUT : no
* --------------------------------------------------------------------
*/
function AddEmptyOption(select)
{
	var options = select.getElementsByTagName("option");
	if( options.length <= 0) return;
	if( options.item(0).value.length == 0) return;
	var empty = document.createElement("option");
	empty.value = "";
	select.insertBefore( empty, options.item(0));
}

/*
* --------------------------------------------------------------------
* FUNCTION : GetSelectValue()
* --------------------------------------------------------------------
* DESCRIPTION: 	get the value of a option; if index is undefined or is negative,
*               then get the value of current option
* PARAMETERS:
*    select - select object
*    index - index, numerical
* OUTPUT : value of corresponding element
* --------------------------------------------------------------------
*/
function GetSelectValue(select,index)
{
	if( arguments.length < 2 || index < 0) index = select.selectedIndex;

	var options = select.getElementsByTagName("option");
	if( options.length <= 0 || index < 0 || index >= options.length) return "";
	return options[index].value;
}


/*
* --------------------------------------------------------------------
* FUNCTION : sendChar()
* --------------------------------------------------------------------
* DESCRIPTION: 	used in internationalization
* PARAMETERS:
*    aChar = string
* OUTPUT : javascript block
* --------------------------------------------------------------------
*/
function sendChar(aChar)
{
	if(!window.opener.closed)
	{
	if(window.opener.document.search_Vars.focused.value == 'no_schars') {alert(res_nofield); return;}
	if (window.opener.document.search_Vars.formname.value!="") {
	    st="top.opener.document.getElementById('"+top.opener.document.search_Vars.formname.value+"')."+
	    top.opener.document.search_Vars.focused.value+".value=top.opener.document.getElementById('"+
	    top.opener.document.search_Vars.formname.value+"')."+
	    top.opener.document.search_Vars.focused.value+".value + aChar";
	} else {
	    st="top.opener.document.getElementById('"+top.opener.document.search_Vars.focused.value+
	    "').value=top.opener.document.getElementById('"+top.opener.document.search_Vars.focused.value+
	    "').value + aChar";
	}
	eval(st);
	}
	else { alert(res_nofield); return;}
	
}

/*
* --------------------------------------------------------------------
* FUNCTION : sendFocus()
* --------------------------------------------------------------------
* DESCRIPTION: 	sends focus, after perfoming sendChar()
* PARAMETERS:
* OUTPUT : javascript block
* --------------------------------------------------------------------
*/
function sendFocus()
{
	if ( window.opener.document.getElementById('search_Vars').focused.value != 'no_schars'){
		st1="window.opener.document.getElementById('"+
		    window.opener.document.getElementById('search_Vars').name.value+
		"')."+window.opener.document.getElementById('search_Vars').focused.value+".focus()";
		eval(st1);
	}
}

/*
* --------------------------------------------------------------------
* FUNCTION : aCheckDate()
* --------------------------------------------------------------------
* DESCRIPTION: 	Check start and end dates
* PARAMETERS: form
* OUTPUT : javascript block
* --------------------------------------------------------------------
*/
function aCheckDate(form)
{
	var d = Number(form.start_day.value);
	var m = Number(form.start_month.value)-1;
	var y = Number(form.start_year.value);

	var t = new Date(y, m, d);

	if( t.getDate() != d || t.getMonth() != m || t.getFullYear() != y) {
		alert(res_inexistingstartdate);
		return false;
	}

	d = Number(form.end_day.value);
	m = Number(form.end_month.value)-1;
	y = Number(form.end_year.value);

	t = new Date(y, m, d);

	if( t.getDate() != d || t.getMonth() != m || t.getFullYear() != y) {
		alert(res_inexistingenddate);
		return false;
	}

	return true;
}

/*
* --------------------------------------------------------------------
* FUNCTION : StripBlanks()
* --------------------------------------------------------------------
* DESCRIPTION: 	Strip blacks chars from a field object
* PARAMETERS: field, object
* OUTPUT : none
* --------------------------------------------------------------------
*/
function StripBlanks(field) {
	var reStartBlanks = /^\s*/;
	var reEndBlanks = /\s*$/;
	field.value = field.value.replace(reStartBlanks,"");
	field.value = field.value.replace(reEndBlanks,"");
}


/*
* --------------------------------------------------------------------
* FUNCTION : Cookie_set()
* --------------------------------------------------------------------
* DESCRIPTION: A function that sets cookie values properly
* PARAMETERS: The cookieName and cookieValue arguments are mandatory
*                but all other arguments are optional.
*                The expires argument is a Date object.
*                The path defines the part of the document tree on the server
*                that the cookie is valid for.
*                The domain argument allows multiple server hosts to be used.
*                The secure value is boolean and only applicable for use
*                with HTTPS: connections.
* OUTPUT : a cookie! :)
* --------------------------------------------------------------------
*/
function Cookie_set(cookieName, cookieValue, expires, domain, secure)
{
    document.cookie = escape(cookieName) + "=" + escape(cookieValue)
		+ (expires ?	"; EXPIRES="	+ expires.toGMTString() : "")
		+ "; PATH=/"
		+ (domain ?		"; DOMAIN="		+ domain				: "")
		+ (secure ?		"; SECURE"								: "");
}

/*
* --------------------------------------------------------------------
* FUNCTION : Cookie_get()
* --------------------------------------------------------------------
* DESCRIPTION: unwrap a cookie
* PARAMETERS: cookieName - name of the cookie
* OUTPUT : none
* --------------------------------------------------------------------
*/
function Cookie_get(cookieName)
{
	var cookieValue = null;
	var posName = document.cookie.indexOf(escape(cookieName) + '=');
	if( posName >= 0) {
		var posValue = posName + (escape(cookieName) + "=").length;
		var endPos = document.cookie.indexOf(";", posValue);
		if( endPos > 0) {
			cookieValue = unescape(document.cookie.substring(posValue, endPos));
		} else {
			cookieValue = unescape(document.cookie.substring(posValue));
		}
	}
	return cookieValue;
}

/*
* --------------------------------------------------------------------
* FUNCTION : Cookie_remove()
* --------------------------------------------------------------------
* DESCRIPTION: removes a cookie
* PARAMETERS: cookieName - name of the cookie
* OUTPUT : none
* --------------------------------------------------------------------
*/
function Cookie_remove(cookieName){
	Cookie_set( cookieName, "", new Date(0));
}

/*
* --------------------------------------------------------------------
* FUNCTION : validField()
* --------------------------------------------------------------------
* DESCRIPTION: check a field for validity aginst special chars
*              like &<?!(){}|*\.,{ etc
* PARAMETERS: field - a field value
* OUTPUT : boolean
* --------------------------------------------------------------------
*/
function validField(field){
			if (field.indexOf("&") >= 0||
			field.indexOf("@") >= 0||
			field.indexOf("=") >= 0||
			field.indexOf("<") >= 0||
		        field.indexOf("?") >= 0||
			field.indexOf("!") >= 0||
			field.indexOf(">") >= 0||
			field.indexOf("(") >= 0||
			field.indexOf(")") >= 0||
			field.indexOf("[") >= 0||
			field.indexOf("]") >= 0||
			field.indexOf("|") >= 0||
			field.indexOf("*") >= 0||
			field.indexOf("\'") >= 0||
			field.indexOf("\"") >= 0||
			field.indexOf("/") >= 0||
			field.indexOf("\\") >= 0||
			field.indexOf("}") >= 0||
			field.indexOf(".") >= 0||
			field.indexOf(",") >= 0||
			field.indexOf("{") >= 0||
			field.indexOf("#") >= 0||
			field.indexOf("$") >= 0||
			field.indexOf("%") >= 0||
			field.indexOf("^") >= 0) {
		return false;
	}

	return true;
}
/*
* --------------------------------------------------------------------
* FUNCTION : validField()
* --------------------------------------------------------------------
* DESCRIPTION: check a field for validity aginst special chars
*              like &<(){}|*\.,{ etc
* PARAMETERS: field - a field value
* OUTPUT : boolean
* --------------------------------------------------------------------
*/
function validSearchField(field){
			if (field.indexOf("<") >= 0||
                field.indexOf(">") >= 0||
                field.indexOf("(") >= 0||
                field.indexOf(")") >= 0||
                field.indexOf("[") >= 0||
                field.indexOf("]") >= 0||
                field.indexOf("|") >= 0||
                field.indexOf("*") >= 0||
                field.indexOf("\'") >= 0||
                field.indexOf("\"") >= 0||
                field.indexOf("/") >= 0||
                field.indexOf("\\") >= 0||
                field.indexOf("%") >= 0||
                field.indexOf("^") >= 0) {
		return false;
	}
	return true;
}


/*
* --------------------------------------------------------------------
* FUNCTION : validEmailField()
* --------------------------------------------------------------------
* DESCRIPTION: check a email field for validity aginst special chars
*              like &<?!(){}|*\.,{ etc
* PARAMETERS: field - a field
* OUTPUT : boolean
* --------------------------------------------------------------------
*/
function validEmailField(field)
{
	if (field.indexOf("&") >= 0||
			field.indexOf("<") >= 0||
			field.indexOf(">") >= 0||
			field.indexOf("(") >= 0||
			field.indexOf(")") >= 0||
			field.indexOf("[") >= 0||
			field.indexOf("]") >= 0||
			field.indexOf("|") >= 0||
			field.indexOf("*") >= 0||
			field.indexOf("\'") >= 0||
			field.indexOf("\"") >= 0||
			field.indexOf("/") >= 0||
			field.indexOf("}") >= 0||
			field.indexOf(",") >= 0||
			field.indexOf("{") >= 0||
			field.indexOf("#") >= 0||
			field.indexOf("$") >= 0||
			field.indexOf("%") >= 0||
			field.indexOf("^") >= 0) {
		return false;
	}

	return true;
}

/*
* --------------------------------------------------------------------
* FUNCTION : IsValidTime()
* --------------------------------------------------------------------
* DESCRIPTION: Validate time in format HH:MM (military time)
* PARAMETERS: timeStr - time string
* OUTPUT : boolean
* --------------------------------------------------------------------
*/
function IsValidTime(timeStr) {
        var ntimeStr = timeStr.value

      
      var timePat = /^(\d{1,2}):(\d{2})?$/;
      var matchArray = ntimeStr.match(timePat);

    if (matchArray == null) {
          alert(res_timenotvalid);
          timeStr.focus();
        return false;
    }
    hour = matchArray[1];
    minute = matchArray[2];
    if (hour < 0 || hour > 23) {
        alert(res_invhour);
          timeStr.focus();
      return false;
      }
    if (minute<0 || minute > 59) {
      alert (res_invminute);
          timeStr.focus();
      return false;
    }
  return true;
}

/*
* --------------------------------------------------------------------
* FUNCTION : WaitDisplay()
* --------------------------------------------------------------------
* DESCRIPTION: displays "Please Wait..."
* PARAMETERS:
* OUTPUT : none
* --------------------------------------------------------------------
*/
function WaitDisplay(){
	if (document.getElementById('waitspan').innerHTML == '. . . ') {
		document.getElementById('waitspan').innerHTML = '';
		} else {
      		document.getElementById('waitspan').innerHTML += '. ';
      		}
	window.setTimeout("WaitDisplay()",1000)
}


/*
* --------------------------------------------------------------------
* FUNCTION : preload()
* --------------------------------------------------------------------
* DESCRIPTION: preloads an image
* PARAMETERS: url - url of the image
* OUTPUT : img object
* --------------------------------------------------------------------
*/
function preload(url) { var i = new Image; i.src = url;  return i;  }

/*
* --------------------------------------------------------------------
* FUNCTION : WaitSpanInf()
* --------------------------------------------------------------------
* DESCRIPTION: displays "Please Wait..."
* PARAMETERS: spanid - id of the used span
* OUTPUT : none
* --------------------------------------------------------------------
*/
function WaitSpanInf(spanid){
	      if (document.getElementById(spanid).innerHTML == '. . . ') {
	        document.getElementById(spanid).innerHTML = '';
	        } else {document.getElementById(spanid).innerHTML += '. ';	}
	     	      window.setTimeout("WaitSpanInf('"+spanid+"')",500)
}

/*
* --------------------------------------------------------------------
* FUNCTION : WaitSpan()
* --------------------------------------------------------------------
* DESCRIPTION: displays "Please Wait..."
* PARAMETERS: spanid - id of the used span
*             numSpan - span name
*             randValue - random value
* OUTPUT : none
* --------------------------------------------------------------------
*/
function WaitSpan(spanid, numSpan,randValue){
    if (document.getElementById('span'+spanid).innerHTML == '. . . ') {
	    document.getElementById('span'+spanid).innerHTML = '';
	} else {document.getElementById('span'+spanid).innerHTML += '. ';}
	randValue--;
	if (randValue>=0)
	  window.setTimeout("WaitSpan('"+spanid+"', "+numSpan+", "+randValue+")",500);
	else
	if (parseInt(spanid)+1<=numSpan) {
      document.getElementById('span'+spanid).innerHTML='';
      document.getElementById('imgfin'+spanid).innerHTML='<img src="/images/checked.gif"/>&nbsp;&nbsp;';
      WaitSpan(parseInt(spanid)+1, numSpan, Math.round(Math.random()*10));
    } else WaitSpanInf('span'+spanid);
}

/*
* --------------------------------------------------------------------
* FUNCTION : reclame()
* --------------------------------------------------------------------
* DESCRIPTION: please wait... for searching
* PARAMETERS: dfields - fields
*             alength - length
* OUTPUT : none
* --------------------------------------------------------------------
*/
function reclame(dfields, alength){
    var sp=document.getElementById('spanReclame');
    if (sp.innerHTML ==''){
        sp.innerHTML+='<br/><span class="bluetext">'
                      +res_searchingfor+':</span><br/><br/>';
        var indx=0;
           for(var i=0; i<alength; i++)
           {
              if (document.getElementById(dfields[i]).value)
              {
                 valueArray = document.getElementById(dfields[i]).value.split("; ");
                 arLength=valueArray.length; if (arLength>1) arLength--;
                   for(var j=0; j<arLength; j++)
              {
                   sp.innerHTML+='<span id="imgfin'+indx
                   +'" ><img src="/images/spacer.gif" width="15" height="1"/>&nbsp;&nbsp;</span>';
                        sp.innerHTML+=valueArray[j];
                     sp.innerHTML+='<span id="span'+indx+'" />';
                     sp.innerHTML+="<br/>"; indx++;
                 }
              }
        }
        if (document.search.job_role
            && document.search.job_role.options[document.search.job_role.selectedIndex].text != ''){
          sp.innerHTML+='<span id="imgfin'+indx
                      +'" ><img src="/images/spacer.gif" width="15" height="1"/>&nbsp;&nbsp;</span>';
          sp.innerHTML+=document.search.job_role.options[document.search.job_role.selectedIndex].text;
          sp.innerHTML+='<span id="span'+indx+'" />';
          sp.innerHTML+="<br/>";
          indx++;
        }

        if (document.search.outletsearch && document.search.personsearch){
            if (document.search.outletsearch.checked
                && document.search.personsearch.checked
                && !document.search.personsearch.disabled){
                sp.innerHTML+='<span id="imgfin'+indx
                    +'" ><img src="/images/spacer.gif" width="15" height="1"/>&nbsp;&nbsp;</span>';
                sp.innerHTML+=res_searchingforoutlets;
                sp.innerHTML+='<span id="span'+indx+'" />';
                sp.innerHTML+="<br/>";
                indx++;
                sp.innerHTML+='<span id="imgfin'+indx
                    +'" ><img src="/images/spacer.gif" width="15" height="1"/>&nbsp;&nbsp;</span>';
                sp.innerHTML+=res_searchingforpeople;
                sp.innerHTML+='<span id="span'+indx+'" />';
                sp.innerHTML+="<br/>";
                indx++;
                sp.innerHTML+='<span id="imgfin'+indx
                +'" ><img src="/images/spacer.gif" width="15" height="1"/>&nbsp;&nbsp;</span>';
                sp.innerHTML+=res_combining;
                sp.innerHTML+='<span id="span'+indx+'" />';
                sp.innerHTML+="<br/>";
                indx++;
            }
            else {
                if(document.search.outletsearch.checked){
                    sp.innerHTML+='<span id="imgfin'+indx
                    +'" ><img src="/images/spacer.gif" width="15" height="1"/>&nbsp;&nbsp;</span>';
                    sp.innerHTML+=res_searchOutlets;
                    sp.innerHTML+='<span id="span'+indx+'" />';
                    sp.innerHTML+="<br/>";
                    indx++;
                }
                if(document.search.personsearch.checked && !document.search.personsearch.disabled){
                    sp.innerHTML+='<span id="imgfin'+indx
                        +'" ><img src="/images/spacer.gif" width="15" height="1"/>&nbsp;&nbsp;</span>';
                    sp.innerHTML+=res_searchPeople;
                    sp.innerHTML+='<span id="span'+indx+'" />';
                    sp.innerHTML+="<br/>"; indx++;
                }
            }
        }

    if (document.search.circ_from
        && document.search.circ_from.options[document.search.circ_from.selectedIndex].text != ''){
      sp.innerHTML+='<span id="imgfin'+indx
             +'" ><img src="/images/spacer.gif" width="15" height="1"/>&nbsp;&nbsp;</span>';
      sp.innerHTML+="from "
             +document.search.circ_from.options[document.search.circ_from.selectedIndex].text;
      if (document.search.circ_to
          && document.search.circ_to.options[document.search.circ_to.selectedIndex].text !='')
      sp.innerHTML+=" to "+document.search.circ_to.options[document.search.circ_to.selectedIndex].text;
      sp.innerHTML+='<span id="span'+indx+'" />';
      sp.innerHTML+="<br/>";
      indx++;
    }
       sp.innerHTML+="<br/>"+res_merging;
       sp.innerHTML+='<span id="span'+indx+'" />';
       sp.innerHTML+="<br/>";
       indx++;
    if (indx>0) WaitSpan('0',indx-1,Math.round(Math.random()*10));
}
}


/*
* --------------------------------------------------------------------
* FUNCTION : openCoverage()
* --------------------------------------------------------------------
* DESCRIPTION: opens a Coverage window
* PARAMETERS: thisid - coverage window id
* OUTPUT : none
* --------------------------------------------------------------------
*/
function openCoverage(thisid) {
    window.open('preloadcoverage.do',thisid,
                'scrollbars=yes,resizable=yes,width=860,height=575,toolbar=no');
}

/*
* --------------------------------------------------------------------
* FUNCTION : doDate()
* --------------------------------------------------------------------
* DESCRIPTION: returns a date in needed local format
* PARAMETERS: strDate - date string
*             onlyDate - true/false value
* OUTPUT : local format of the date
* --------------------------------------------------------------------
*/
function doDate(strDate, onlyDate, withLocale) {
  var myString = new String(strDate)
  var strArr = myString.split("T");
  var strDate = strArr[0].split("-");
  var strTime = strArr[1].split(":");
  if (onlyDate){
    var myDate = new Date(strDate[0],strDate[1]-1,strDate[2]);
    if(!withLocale) {
            return myDate.toLocaleDateString();
        } else {
            return String(strDate[2])+"/"+String(strDate[1])+"/"+String(strDate[0]);
        }
  }
  if ((strTime[0]=="02") && (strTime[1]=="00")
       && (strTime[2].slice(0,2)=="00") && (strTime[2].slice(3)=="000")) {
    var myDate = new Date(strDate[0],strDate[1]-1,strDate[2]);
    return myDate.toLocaleDateString();
  } else {
     var myDate = new Date(strDate[0],strDate[1]-1,strDate[2],strTime[0],
                           strTime[1],strTime[2].slice(0,2));
     return myDate.toLocaleString();
  }
}

/*
* --------------------------------------------------------------------
* FUNCTION : returnTime()
* --------------------------------------------------------------------
* DESCRIPTION: returns a date in needed local format
* PARAMETERS: strDate - date string
* OUTPUT : local format of the time
* --------------------------------------------------------------------
*/
function returnTime(strDate) {
  var myString = new String(strDate)
  var strArr = myString.split("T");
  var strDate = strArr[0].split("-");
  var strTime = strArr[1].split(":");
  if ((strTime[0]=="02") && (strTime[1]=="00")
       && (strTime[2].slice(0,2)=="00") && (strTime[2].slice(3)=="000")) {
    var myDate = new Date(strDate[0],strDate[1]-1,strDate[2]);
    return myDate.getTime();
  } else {
     var myDate = new Date(strDate[0],strDate[1]-1,strDate[2],
                           strTime[0],strTime[1],strTime[2].slice(0,2));
     return myDate.getTime();
  }
}

/*
* --------------------------------------------------------------------
* FUNCTION : is_empty()
* --------------------------------------------------------------------
* DESCRIPTION: verifies if the object value exists and is not empty
* PARAMETERS: vobj, object
* OUTPUT : true or false
* --------------------------------------------------------------------
*/
function is_empty(vobj) {
    if (vobj.value) {
        StripBlanks(vobj);
    }
    var marker=false;
    if (!vobj) marker=true;
    if (!vobj.value) marker=true;
    if (vobj.value==null) marker=true;
    if (vobj.value=="") marker=true;
    return marker;
}

/*
* --------------------------------------------------------------------
* FUNCTION : verifyCalendar()
* --------------------------------------------------------------------
* DESCRIPTION: verify mouse click out of calendar and hide it
* OUTPUT : none
* --------------------------------------------------------------------
*/
var overCalendar = 0;
var shownCalendarId = '';
function verifyCalendar(){
     if (shownCalendarId && shownCalendarId != ''
         && overCalendar==0)
     hideCurrCalendar();
     overCalendar =0;
}

/*
* --------------------------------------------------------------------
* FUNCTION : verifyFeat()
* --------------------------------------------------------------------
* DESCRIPTION: verify mouse click out of FF desacription and hide it
* OUTPUT : none
* --------------------------------------------------------------------
*/
var overFeat = 0;
var shownFeat = '';
function verifyFeat(){
    if (shownFeat && shownFeat != '' && overFeat==0){
    	document.getElementById(shownFeat).style.visibility='hidden';
    	shownFeat='';
	}
	overFeat =0;
}
/*
* --------------------------------------------------------------------
* FUNCTION : getcookies()
* --------------------------------------------------------------------
* DESCRIPTION: verify mouse click out of FF desacription and hide it
* OUTPUT : none
* --------------------------------------------------------------------
*/

function viewCookies()
	{ 
	var cookiePage = window.open('about:blank','cookieP','scrollbars=yes,resizable=yes,width=570,height=600,toolbar=no');
	var arr = new Array(); 
	var the_cookies = document.cookie; 
	var raw_cookies=the_cookies.split("; "); 
	cookiePage.document.write("cookies:"+raw_cookies.length+"<br/>");
	cookiePage.document.write("<table border = '1'>");	
	cookiePage.document.write("<tr><td align='center'><b>Name</b></td><td align='center'><b>Value</b></td></tr>");	
	for (x=0;x<raw_cookies.length;x++)
		{ 
		var tmp_arr= new Array(); 
		var tmp_raw_cookies = raw_cookies[x].split("="); 
		cookiePage.document.write("<tr><td>"+tmp_raw_cookies[0]+"</td><td>"+tmp_raw_cookies[1]+"</td></tr>");	
		var tmp_cookie_names = unescape(tmp_raw_cookies[1]).split("/"); 
		for (y=0;y<tmp_cookie_names.length;y++)
			{ 
			var tmp_cookie_vals = tmp_cookie_names[y].split(":"); 
			tmp_arr[tmp_cookie_vals[0]] = tmp_cookie_vals[1]; 
			} 
		arr[tmp_raw_cookies[0]] = tmp_arr; 
		
		} 
	cookiePage.document.write("</table>");	
	}

/*
* --------------------------------------------------------------------
* FUNCTION : xGetElementById()
* --------------------------------------------------------------------
* DESCRIPTION: getElemebyById for all browsers
* OUTPUT : none
* --------------------------------------------------------------------
*/
function xGetElementById(e) {
  if(typeof(e)!="string") return e;
  if(document.getElementById) e=document.getElementById(e);
  else if(document.all) e=document.all[e];
  else e=null;
  return e;
}

