// JavaScript Document

function openWindow(param) {
}
function getPosition(e) {
    e = e || window.event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + 
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + 
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }
    return cursor;
}

function popolaSelect(url, id, sql, firstelem, asynch, noprivs, fireonchange) {
  // eseguo la query tramite ajax
  // e imposto i risultati nell'id specificato
  var rn = Math.floor(Math.random( ) * (1000 + 1));
  
  if (asynch) {
    asynch = 1;
  } else {
    asynch = 0;
  }

  url = url + '&act=POPOLASELECT'
  url = url + '&id=' + id
  url = url + '&sql=' + sql
  if (firstelem) url = url + '&firstelem=' + firstelem;
  if (noprivs) url = url + '&fw_noprivs=' + 1;
  if (fireonchange) url = url + '&fireonchange=' + 1;
  url = url + '&randnr=' + rn
  var params = { method : 'GET'
                ,params : 'MANUAL'
                ,urlparams : ''
                ,asynch : asynch
                ,type : 'javascript' // noresponse o javascript
                //,area : 'submodule_' + detail
                //,runscript: 'ajax_call_detail'
                //,onload: 'onRowOverHandler();onContainerswitch();onLoadAjax();'
                ,debug: 0
               }
               
  err = ajaxAce(url, params);
	  
}

function trovaConto(url, codice) {
  var codiceObj = document.getElementById(codice)
  if (codiceObj.value=='') {
    
    if(trovaConto.arguments.length >2) {
      for(var i=2; i<trovaConto.arguments.length; i+=2) {
        document.getElementById(trovaConto.arguments[i+1]).value = ''
      }
    }
  
  } else {
    var rn = Math.floor(Math.random( ) * (1000 + 1));
  
    url = url + '&act=TROVACONTO'
    url = url + '&codice_htmlid=' + codice
    url = url + '&codice=' + codiceObj.value
    
    if(trovaConto.arguments.length >2) {
      for(var i=2; i<trovaConto.arguments.length; i+=2) {
        url = url + '&return_value['+trovaConto.arguments[i+1]+']=' + trovaConto.arguments[i]
      }
    }
    
    url = url + '&randnr=' + rn
  
    var params = { method : 'GET'
                  ,params : 'MANUAL'
                  ,urlparams : ''
                  ,asynch : 1
                  ,type : 'javascript' // noresponse o javascript
                  //,area : 'submodule_' + detail
                  //,runscript: 'ajax_call_detail'
                  //,onload: 'onRowOverHandler();onContainerswitch();onLoadAjax();'
                  ,debug: 0
                 }
  
    err = ajaxAce(url, params);
  }
}

/*
	Copyright Robert Nyman, http://www.robertnyman.com
	Free to use if this text is included
*/
function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)") : null;
	var oCurrent;
	var oAttribute;
	for(var i=0; i<arrElements.length; i++){
		oCurrent = arrElements[i];
		oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName);
		if(typeof oAttribute == "string" && oAttribute.length > 0){
			if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
				arrReturnElements.push(oCurrent);
			}
		}
	}
	return arrReturnElements;
}

function setWaitToStart(elem, pathtoimage, clear) {
  var newNode = document.createElement("div");
  newNode.style.width = elem.style.width
  newNode.style.height = elem.style.height
  newNode.style.textAlign = 'center'
  //newNode.style.backgroundColor = '#FFFFFF'
  newNode.style.backgroundColor = 'transparent'
  newNode.id = 'fw_wait_roller'
  
  
  var newImg = document.createElement("img");
  newImg.src = pathtoimage + '/wait.gif';
  newImg.style.marginLeft = 'auto';
  newImg.style.marginRight = 'auto';
  if(!elem.style.height) var h = '100'; else var h = elem.style.height;
  newImg.style.marginTop = integerDivision(parseInt(h), 2) + 'px';
  
  newNode.appendChild(newImg)
  if(clear) elem.innerHTML = '';
  elem.appendChild(newNode)
  
}

function clearWaitDMLdetail(elem) {
    elem.removeChild(document.getElementById('fw_wait_roller'))
    elem.removeChild(document.getElementById('fw_wait_roller_txt'))
    elem.removeChild(document.getElementById('fw_wait_roller_img'))
    elem.removeChild(document.getElementById('fw_wait_roller_btn'))
  
}
function setWaitDMLdetail(elem, pathtoimage, clear) {

  var elemSavePos  = elem.style.position;
  elem.style.position = 'relative';
  
  var newNode = document.createElement("div");
  newNode.style.width = elem.clientWidth
  newNode.style.height = elem.clientHeight
  newNode.style.textAlign = 'center'
  newNode.style.position = 'absolute'
  newNode.style.left = '0px'
  newNode.style.top = '0px'
  newNode.style.backgroundColor = '#000000'
  newNode.id = 'fw_wait_roller'
  newNode.style.opacity = 0.20;
  newNode.style.MozOpacity = 0.20; /* older Gecko-based browsers */
  newNode.style.filter = 'alpha(opacity=20)'; /* For IE6&7 */
  newNode.style.zIndex = 1000
  elem.appendChild(newNode)
  
  var txtNode = document.createElement("div");
  txtNode.style.fontFamily = 'Verdana'
  txtNode.style.fontSize = '16px'
  txtNode.style.fontWeight = 'bold'
  txtNode.style.color = 'red'
  txtNode.style.textAlign = 'center'
  txtNode.style.backgroundColor = 'transparent'
  txtNode.id = 'fw_wait_roller_txt'
  txtNode.innerHTML = 'Attendere. Salvataggio in corso!'
  txtNode.style.position = 'absolute'
  txtNode.style.width = '300px'
  txtNode.style.height = '30px'
  txtNode.style.lineHeight = '30px'
  txtNode.style.top = integerDivision(parseInt(elem.clientHeight) - 30, 2) +'px'
  txtNode.style.left = integerDivision(parseInt(elem.clientWidth) - 300, 2) +'px'
  txtNode.style.zIndex = 1100
  elem.appendChild(txtNode)
  
  
  var newImg = document.createElement("img");
  //newImg.src = pathtoimage + '/wait.gif';
  newImg.src = pathtoimage + '/wait_bar.gif';
  newImg.style.marginLeft = 'auto';
  newImg.style.marginRight = 'auto';
  newImg.style.position = 'absolute'
  newImg.id = 'fw_wait_roller_img'
  newImg.style.top = integerDivision(parseInt(elem.clientHeight) + 30, 2) +'px'
  //newImg.style.left = integerDivision(parseInt(elem.clientWidth)-30, 2) +'px'
  newImg.style.left = integerDivision(parseInt(elem.clientWidth)-220, 2) +'px'
  newImg.style.zIndex = 1100
  elem.appendChild(newImg)
  
  
  var btnNode = document.createElement("button");
  btnNode.style.fontFamily = 'Verdana'
  btnNode.style.fontSize = '12px'
  btnNode.style.fontWeight = 'bold'
  btnNode.style.color = 'blue'
  btnNode.style.textAlign = 'center'
  btnNode.style.border = '1px solid #000000'
  btnNode.style.backgroundColor = 'white'
  btnNode.id = 'fw_wait_roller_btn'
  btnNode.innerHTML = 'In caso di attesa eccessiva premere qui !'
  btnNode.style.position = 'absolute'
  btnNode.style.width = '400px'
  btnNode.style.height = '30px'
  btnNode.style.lineHeight = '30px'
  btnNode.style.top = integerDivision(parseInt(elem.clientHeight) + 100, 2) +'px'
  btnNode.style.left = integerDivision(parseInt(elem.clientWidth) - 400, 2) +'px'
  btnNode.style.zIndex = 1100
  btnNode.onclick = function() {
    elem.removeChild(txtNode)
    elem.removeChild(newImg)
    elem.removeChild(btnNode)
    elem.removeChild(newNode)
    //if (document.getElementById(elem.id.substr(10)+'_invia')) document.getElementById(elem.id.substr(10)+'_invia').disabled = false
  };
  elem.appendChild(btnNode)
  
  if(clear) elem.innerHTML = '';
  elem.style.position = elemSavePos
  
}

function setWaitToStop() {
  if(document.getElementById('fw_wait_roller')) {
    document.body.removeChild(document.getElementById('fw_wait_roller'))
  }
}

function integerDivision ( numerator, denominator ) {
    // In JavaScript, dividing integer values yields a floating point result (unlike in Java, C++, C)
    // To find the integer quotient, reduce the numerator by the remainder first, then divide.
    var remainder = numerator % denominator;
    var quotient = ( numerator - remainder ) / denominator;

    // Another possible solution: Convert quotient to an integer by truncating toward 0.
    // Thanks to Frans Janssens for pointing out that the floor function is not correct for negative quotients.
    /****************************************************
    if ( quotient >= 0 )
        quotient = Math.floor( quotient );
    else  // negative
        quotient = Math.ceil( quotient );
     *****************************************************/

    return quotient;
}

function gotoMenuStampaElenco(modulo, titolo, fwindex, wc, ob, configas) {

  var selectrowparam = '';
  var wccond = '';
  var ordercond = '';
  var ftscond = ''
  var configasacction = '';
  if (configas != '') configasacction = '&configas='+configas;
    
  // passo il selectrow
  if (document.getElementById('selectrow0')) {
    var tot_rec = document.getElementById('nrrec').value
    for(var i=0; i<tot_rec; i++) {
      if(document.getElementById('selectrow'+i)) {
        if(document.getElementById('selectrow'+i).checked) {
          selectrowparam = selectrowparam + '&selectrow['+i+']=1';
        }
      }
    }
  }
  // devo anche passare le condizioni di where
  // where['.$obj->name.'][alias]
  // where['.$obj->name.'][dbname]
  // where['.$obj->name.'][op]
  // where['.$obj->name.'][value]
  if(wc!='') {
    var fc = wc.split('@')
    for(var i=0; i<fc.length;i++) {
      var pc = fc[i].split('|');
      wccond = wccond + '&' + 'where['+pc[0]+'][alias]='+pc[1];
      wccond = wccond + '&' + 'where['+pc[0]+'][dbname]='+pc[2];
      wccond = wccond + '&' + 'where['+pc[0]+'][op]='+pc[3];
      wccond = wccond + '&' + 'where['+pc[0]+'][value]='+pc[4];
    }
  }
  
  // devo anche passare le condizioni di ordinemanto
  // orderby['.$obj->name.'] = asc|desc
  if(ob!='') {
    var fc = ob.split('@')
    for(var i=0; i<fc.length;i++) {
      var pc = fc[i].split('|');
      ordercond = ordercond + '&' + 'orderby['+pc[0]+']='+pc[1];
    }
  }
  
  // passo anche il fieldtoshow
  var fts = document.getElementsByName('fieldtoshow[]');
  var ftsrun  = 0
  for(var i=0; i<fts.length;i++) {
    if (fts.item(i).checked) {
      ftscond = ftscond + '&' + 'fieldtoshow[' + ftsrun + ']=' + fts.item(i).value
      ftsrun++;
    }
  }
  
  // passo anche il firstrec
  var firstRec = '&firstrec='+document.getElementById('firstrec').value
  
  modal('Stampa Elenco ' + titolo, fwindex+'?mod='+modulo+'&act=MENUSTAMPAELENCO'+configasacction+selectrowparam+wccond+ordercond+ftscond+firstRec, 700, 500);
}

function gotoStampaElenco() {
  //parent.parent.GB_hide();
  return true;
}

function ControllaPIVA(pi)
{
	if( pi == '' )  return '';
	if( pi.length != 11 )
		return "La lunghezza della partita IVA non è\n" +
			"corretta: la partita IVA dovrebbe essere lunga\n" +
			"esattamente 11 caratteri.\n";
	validi = "0123456789";
	for( i = 0; i < 11; i++ ){
		if( validi.indexOf( pi.charAt(i) ) == -1 )
			return "La partita IVA contiene un carattere non valido `" +
				pi.charAt(i) + "'.\nI caratteri validi sono le cifre.\n";
	}
	s = 0;
	for( i = 0; i <= 9; i += 2 )
		s += pi.charCodeAt(i) - '0'.charCodeAt(0);
	for( i = 1; i <= 9; i += 2 ){
		c = 2*( pi.charCodeAt(i) - '0'.charCodeAt(0) );
		if( c > 9 )  c = c - 9;
		s += c;
	}
	if( ( 10 - s%10 )%10 != pi.charCodeAt(10) - '0'.charCodeAt(0) )
		return "La partita IVA non è valida:\n" +
			"il codice di controllo non corrisponde.\n";
	return '';
}

var STR_PAD_LEFT = 1;
var STR_PAD_RIGHT = 2;
var STR_PAD_BOTH = 3;

function pad(str, len, pad, dir) {

    if (typeof(len) == "undefined") { var len = 0; }
    if (typeof(pad) == "undefined") { var pad = ' '; }
    if (typeof(dir) == "undefined") { var dir = STR_PAD_RIGHT; }

    if (len + 1 >= str.length) {

        switch (dir){

            case STR_PAD_LEFT:
                str = Array(len + 1 - str.length).join(pad) + str;
            break;

            case STR_PAD_BOTH:
                var right = Math.ceil((padlen = len - str.length) / 2);
                var left = padlen - right;
                str = Array(left+1).join(pad) + str + Array(right+1).join(pad);
            break;

            default:
                str = str + Array(len + 1 - str.length).join(pad);
            break;

        } // switch

    }

    return str;

}

/**
 * gotoACTION
 * attiva una azione (azione) di un modulo (modulo)
 * e ritorna al chiamante quando dall'azione chiamata si esce con BACK o con UPDATE o con INSERT
 * oltre ai parametri modulo e azione si possono aggiungere altri parametri che saranno passati al chiamante
 * e devono essere specificati a coppie <nome del parametro>, <valore del parametro>
 */
function gotoACTION(modulo, azione) {

  if (document.getElementById('site_frm')) {
    var offset = 2;
    
    var f = document.getElementById('site_frm'); // form che dovrebbe essere sempre presente nel sito
                                                 
    var mod = document.createElement('input');
    mod.setAttribute('name', 'mod');
    mod.setAttribute('value', modulo);
    
    var act = document.createElement('input');
    act.setAttribute('name', 'act');
    act.setAttribute('value', azione);
    
    // modulo e azione a cui tornare con il BACK
    var actualMod = document.getElementById('mod').value
    
    var mod_back = document.createElement('input');
    mod_back.setAttribute('name', 'mod_back');
    mod_back.setAttribute('value', actualMod);
    
    var actualAct = document.getElementById('act').value
    if (actualAct == 'UPDATE') actualAct = 'MODIF';
    if (actualAct == 'INSERT') actualAct = 'NEW';
    
    var act_back = document.createElement('input');
    act_back.setAttribute('name', 'act_back');
    act_back.setAttribute('value', actualAct);
    
    // modulo e azione a cui tornare con il submit
    var fw_succ_module = document.createElement('input');
    fw_succ_module.setAttribute('name', 'fw_succ_module');
    fw_succ_module.setAttribute('value', actualMod);
    
    var fw_succ_action = document.createElement('input');
    fw_succ_action.setAttribute('name', 'fw_succ_action');
    fw_succ_action.setAttribute('value', actualAct);
    
    f.appendChild(mod)
    f.appendChild(act)
    f.appendChild(act_back)
    f.appendChild(mod_back)
    f.appendChild(fw_succ_module)
    f.appendChild(fw_succ_action)
    
    // parametri
    if(gotoACTION.arguments.length > offset) {
      for(i=offset; i < gotoACTION.arguments.length; i=i+2) {
      	var pname = gotoACTION.arguments[i];
      	var pvalue = gotoACTION.arguments[i+1];
      	
        var p = document.createElement('input');
        p.setAttribute('name', pname);
        p.setAttribute('value', pvalue);
        
        f.appendChild(p)
      }
    }

    // resetting fieldtoshow on return
    
    var fw_fieldtoshow_reset = document.createElement('input');
    fw_fieldtoshow_reset.setAttribute('name', 'fw_fieldtoshow_reset');
    fw_fieldtoshow_reset.setAttribute('value', 1);
    f.appendChild(fw_fieldtoshow_reset)
    
    
    f.submit();
    
    
  } else {
    alert('Impossibile eseguire l\'Azione!');
  }
}


    
  function trim(stringa) {
    while (stringa.substring(0,1) == ' ') {
      stringa = stringa.substring(1, stringa.length);
    }
    while (stringa.substring(stringa.length-1, stringa.length) == ' ') {
      stringa = stringa.substring(0,stringa.length-1);
    }
    return stringa;
  }
