/**********************************************
* HTjslib.js                                  *  
***********************************************
* Htjslib Rel 1.0 May, 2001                   *
* Written by Mad Max & Company                *
* H.T. Srl                                    *
**********************************************/
var clickedSubmit  = false;

/* Questa variabile è testata per verificare la presenza della
 * libreria HTlib all'interno dei frames.
 */ 
var htLibInstanced = true;

// Questa funzione deve essere invocata per testare l'inclusione
// della libreria HTLib all'interno di un frame specifico.
// Restituisce 'true' se presente, false in caso contrario.
function checkHTLib(searchFrame) {
  if (searchFrame.htLibInstanced == true) {
    return true;
  }
  return false;
}

function testJSInclusion() {
  alert('Libreria FormUtys inclusa');
}
	
function clickSubmit() {
  clickedSubmit = true;
}

function HTSubmitForm(JSPAction,htForm,htTarget) {
  clickSubmit();
  sisterAction  = htForm.action;
  originalTarget = htForm.target;
  if (htTarget!="")
    htForm.target= htTarget;
  if (JSPAction!="")
    sisterAction =JSPAction;
  htForm.action=sisterAction;
  htForm.submit();
  htForm.target= originalTarget;
}

/* Forzatura sottomissione FORM HTML */
function SubmitForm(formToSubmit) {
  clickSubmit();
  formToSubmit.submit();
}

/* Valorizzazione contenuto campo di una FORM */
function SetFormField(formField, fieldValue) {
  formField.value = fieldValue;
}

/* Toggle del valore del radio button di input */
function toggleRadioButton(radio_button) {
  radio_button.checked = !radio_button.checked;
}

/* Funzione per l'ottenimento del valore corrispondente ad un'
 * opzione radio button selezionata.
 */
function getRadioButtonValue(radio_button) {
  num_values = radio_button.length;
  for (i=0; i<num_values; i++){
    if(radio_button[i].checked) {
      var radio_value = radio_button[i].value;
      //alert(radio_value);
    }
  }
  return radio_value;
}

/* Forzatura messaggio in status bar */
function setStatusBarMessage(msg) {
  window.status = msg
  document.returnValue = true;
}

function HTSubmit(JSPAction) {
	HTSubmitForm(JSPAction,document.iForm,'')
}

function HTSubmitPopUp(JSPAction, JSPtarget) {
  var originalTarget = document.iForm.target;
  if (JSPtarget!="")
    document.iForm.target= JSPtarget;
  HTSubmit(JSPAction);
  document.iForm.target= originalTarget;
}

function HTConfirmSubmit(message, url){
  if(confirm(message))HTSubmit(url);
}

function HTSubmitSort(SortField,SortVersus) {
  clickSubmit();
  oldParameters = '';
  sisterAction       = document.location.pathname;
  TheParameters      = document.location.search.substring(1,255)
  TheParametersArray = TheParameters.split("&")
  k = TheParametersArray.length
  for (i= 0 ; i < k; i++) {
   curPar =unescape(TheParametersArray[i]);
   //alert("Current Parameter " + curPar);
   myRE = new RegExp("HTQuery_OrderBy", "i");
   results = curPar.match(myRE);
   parSeparator = '&';
   if (i==0)
     parSeparator = '';
   if (results==null) {
     oldParameters = oldParameters + parSeparator + curPar;
   }
  }
  //alert("Sort Parameters :" + oldParameters);
  if (oldParameters.length == 0) 
    oldParameters = '?HTQuery_OrderBy=' + SortField + '&HTQuery_OrderByVersus=' + SortVersus;
  else 
    oldParameters = oldParameters + '&HTQuery_OrderBy=' + SortField + '&HTQuery_OrderByVersus=' + SortVersus;
  //alert("Page URL " + sisterAction + ' Parameters ' + oldParameters);
  document.iForm.action=sisterAction + '?' +oldParameters;
  document.iForm.submit();
}

function checkOpenerWindow() {
// controlla che esista il padre ; se NON esiste : chiude finestra
  if (self.opener.closed)
    self.close();
// timeout per richiamare se' stesso : 1 secondo
  setTimeout("checkOpenerWindow()" , 1000);
}

var checkedRows  = '';
var firstCheckedRow = '';
// Questo metodo viene richiamato sull'evento onClick delle checkbox di selezione record in cluster 'HT_CHECKROWKEY_chiave'.
// raccoglie in una stringa separandole con '&' tutte le chiavi dei record selezionati con checkbox. Questa stessa stringa
// può essere utilizzata per passare come parametri le chiavi alle pagine successiva. 
function updateCheckedRows(check) {
  found=false;
  firstCheckedRow = '';
  curParameters   = '';
  curPar          = '';
  lastPar          = '';
  checked         = checkedRows;
  TheCheckedArray = checked.split("&");
  k = TheCheckedArray.length;
  for (i= 0 ; i < k; i++) {
    curPar =unescape(TheCheckedArray[i]);
    // Se la riga esiste già la 'deCecco' (deseleziono).
    myRE = new RegExp(check + '=true', "i");
    results = curPar.match(myRE);
    parSeparator = '&';
    if (i==0) 
      parSeparator = '';
    if (results==null) {
      curParameters = curParameters + parSeparator + curPar;
      lastPar       = curPar;
    }
    else found = true;
  }
  parSeparator = '';
  if (curParameters !='')
    parSeparator = '&';
  checkedRows = curParameters;
  //Se checcata riga nuova la aggiungo alla String delle checked rows e la designo come prima da gestire.
  if (!found) {
    checkedRows = curParameters + parSeparator + check + '=true';
    //firstCheckedRow = check.substring(15,check.length);
    startIdx = check.lastIndexOf('_') + 1;
    firstCheckedRow = check.substring(startIdx,check.length);
  }
  else {
    startIdx = lastPar.lastIndexOf('_') + 1;
    lastIdx  = lastPar.indexOf("=");
    //firstCheckedRow = lastPar.substring(15,lastIdx);
    firstCheckedRow = lastPar.substring(startIdx,lastIdx);
  }
  //alert("Ultima riga ceccata :" + firstCheckedRow);
  //alert("Righe checcate" + checkedRows);
}

function popUpPars(pageURL,pageParameters,popPars) {
  if (pageParameters!='')
    pageURL = pageURL + '?' + pageParameters;
  popUpWindow = window.open(pageURL, "popUpWindow" , popPars);
}

function popUp(pageURL,pageParameters) {
  if (pageParameters!='')
    pageURL = pageURL + '?' + pageParameters;
  popUpWindow = window.open(pageURL, "popUpWindow" , "width=550,height=300,top=10,left=10,toolbar=no,location=no,scrollbars=yes,resizable=yes");
}

function popUp(pageURL,pageParameters,popUpWidth,popUpHeight,popUpTop,popUpLeft,popUpToolBar,popUpLocation,popUpStatusBar,popUpScrollBars,popUpResizable) {
  if (pageParameters!='')
    pageURL = pageURL + '?' + pageParameters;
  popUpAttributes = "width=" + popUpWidth + ",height=" + popUpHeight + 
                    ",top=" + popUpTop + ",left=" + popUpLeft + ",toolbar=" + popUpToolBar + 
                    ",location=" + popUpLocation + ",status=" + popUpStatusBar + 
                    ",scrollbars=" + popUpScrollBars + ",resizable=" + popUpResizable;
  popUpWindow = window.open(pageURL, "popUpWindow" , popUpAttributes);
}

var msg = 'No rows selected!';
function checkedPopUp(pageURL,pageParameters,msg) {
  if (pageParameters!='')
    popUp(pageURL,pageParameters);
  else
    alert(msg);
}

var msg = 'No rows selected!';
function checkedPopUp(pageURL,pageParameters,msg,popUpWidth,popUpHeight,popUpTop,popUpLeft,popUpToolBar,popUpLocation,popUpStatusBar,popUpScrollBars,popUpResizable) {
  if (pageParameters!='')
    popUp(pageURL,pageParameters,popUpWidth,popUpHeight,popUpTop,popUpLeft,popUpToolBar,popUpLocation,popUpStatusBar,popUpScrollBars,popUpResizable);
  else
    alert(msg);
}

function HTSubmitChecked(JSPAction,msg) {
  if (firstCheckedRow=='')
    alert(msg);
  else 
    HTSubmit(JSPAction);
}

function closeWindow() {
  window.close();
}


/**********************************************
* Nuove funzioni by Bruno                     *  
***********************************************
* Rollover, mostra layer, Preloading di img   *
* Visualizzazione MSG sulla StatusBar         *
**********************************************/

function trova(n, d) { 
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=trova(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function mostraLayer() { 
  var i,p,v,obj,args=mostraLayer.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=trova(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v='hide')?'hidden':v; }
    obj.visibility=v; }
}

function swapImgRestore() { 
  var i,x,a=document.sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function preloadImg() { 
  var d=document; if(d.images){ if(!d.p) d.p=new Array();
    var i,j=d.p.length,a=preloadImg.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.p[j]=new Image; d.p[j++].src=a[i];}}
}

function swapImg() { 
  var i,j=0,x,a=swapImg.arguments; document.sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=trova(a[i]))!=null){document.sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function displayStatusMsg(msgStr) { 
  status=msgStr;
  document.returnValue = true;
}

/************************************************
 * Nuove funzioni by MAD                        *  
 * Funzioni di Utilita' generale sulle Stringhe *
 ************************************************/
function ltrim( s ) {
  return s.replace( /^\s*/, "" )
}

function rtrim( s ) {
  return s.replace( /\s*$/, "" );
}

function trim( s ) {
  return rtrim(ltrim(s));
}

/************************************************
 * Funzioni per la Gestione di Combo Correlate  *
 ************************************************/
function switch_select(slave_opt_Array,slave_lbl_Array,masterSelectBox,slaveSelectBox,selectedOption) {
  selectedIdx = 0;
  for (loop = slaveSelectBox.options.length-1; loop > 0; loop--) {
    slaveSelectBox.options[loop] = null;
  }
  for (loop = 0; loop < slave_opt_Array[masterSelectBox.selectedIndex + 1].length; loop++) {
    slaveSelectBox.options[loop]       = new Option(slave_opt_Array[masterSelectBox.selectedIndex + 1][loop]);
    slaveSelectBox.options[loop].value = slave_opt_Array[masterSelectBox.selectedIndex + 1][loop];
    slaveSelectBox.options[loop].text  = slave_lbl_Array[masterSelectBox.selectedIndex + 1][loop];
    if (selectedOption!=null && slaveSelectBox.options[loop].value!=null &&
        trim(selectedOption) == trim(slaveSelectBox.options[loop].value)) {
      selectedIdx = loop;
    }
  }
  if (selectedOption!=null)
    slaveSelectBox.selectedIndex = selectedIdx;
}

function findArrayValue(slave_opt_Array,masterSelectBox,searchValue) {
  valueFound = false;
  for (loop = 0; loop < slave_opt_Array[masterSelectBox.selectedIndex + 1].length; loop++) {
    if (searchValue!=null &&
        trim(searchValue) == trim(slave_opt_Array[masterSelectBox.selectedIndex + 1][loop])) {
      valueFound = true;
      break;
    }
  }
  return valueFound;	
}

//Advanced Email Check credit-
//By JavaScript Kit (http://www.javascriptkit.com)
//Over 200+ free scripts here!
var testresults
function checkemail(str){
//var str=document.validation.emailcheck.value
var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if (filter.test(str))
testresults=true
else{
//alert("Please input a valid email address!")
testresults=false
}
return (testresults)
}

/** Funzione per verificare che una data stringa di input termini con
  * la sottostringa indicata.
  **/
function endsWith(input_str,search_str) {
  //alert ("Entrato")
  if (input_str != null) {
    str_len        = input_str.length
    search_str_len = search_str.length
    //alert ("Lunghezze " + str_len + "-" + search_str_len)
    if (input_str.indexOf(search_str) == str_len - search_str_len) {
      return true
    }
  }
  return false
}

/** Escaping HTTP di stringhe **/
function HTTPEscape(a) {
	a = escape(a);
	a = replace(a,'+','%2B');
	a = replace(a,'%20','+');
	a = replace(a,'%A1','%B0');
	a = replace(a,'%80','%C4');
	a = replace(a,'%81','%C5');
	a = replace(a,'%82','%C7');
	a = replace(a,'%83','%C9');
	a = replace(a,'%84','%D1');
	a = replace(a,'%85','%D6');
	a = replace(a,'%86','%DC');
	a = replace(a,'%87','%E1');
	a = replace(a,'%88','%E0');
	a = replace(a,'%89','%E2');
	a = replace(a,'%8A','%E4');
	a = replace(a,'%8B','%E3');
	a = replace(a,'%8C','%E5');
	a = replace(a,'%8D','%E7');
	a = replace(a,'%8E','%E9');
	a = replace(a,'%8F','%E8');
	a = replace(a,'%90','%EA');
	a = replace(a,'%91','%EB');
	a = replace(a,'%92','%ED');
	a = replace(a,'%93','%EC');
	a = replace(a,'%94','%EE');
	a = replace(a,'%95','%EF');
	a = replace(a,'%96','%F1');
	a = replace(a,'%97','%F3');
	a = replace(a,'%98','%F2');
	a = replace(a,'%99','%F4');
	a = replace(a,'%9A','%F6');
	a = replace(a,'%9B','%F5');
	a = replace(a,'%9C','%FA');
	a = replace(a,'%9D','%F9');
	a = replace(a,'%9E','%FB');
	a = replace(a,'%9F','%FC');

	return a
}

function replace (data,find,replace)  {
	var flen = find.length;
	var dlen = data.length;
	for (i=0; i<dlen; i++) {
		var j = i + flen;
		if (data.substring(i,j) == find)  {
			data = data.substring(0,i) + replace + data.substring(j,dlen);
		}
	}
	return data
}

