function isEmpty(s)
{
   return ((s == null) || (s.length == 0))
}

function isLetter (c)
{
   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}

function isSpace (c)
{
   return (c == " ");
}

function isDigit (c)
{
   return ((c >= "0") && (c <= "9"))
}

function isLetterOrDigit (c)
{
   return (isLetter(c) || isDigit(c))
}


function checkSearch(){

        if (!isEmpty(document.itemForm.progressivoArticolo.value)) {
             isNumber = checkMoney(document.itemForm.progressivoArticolo.value);
             if (!isNumber) {
                 alert('Attenzione :  il progressivo fornito non e\' valido !');
                 return false;
             }
        }
        return true;
}


function checkInserisciArticolo(){

   if (document.itemForm.categoriaArticolo.value=="-1") {
     alert('Scegliere la categoria per l\' articolo');
     return false;
   }

   if (isEmpty(document.itemForm.codiceArticolo.value)) {
     alert('Inserire il codice per l\' articolo');
     return false;
   }

   if (isEmpty(document.itemForm.descrizioneSintArticolo.value)) {
     alert('Inserire una breve descrizione per l\' articolo');
     return false;
   }
   if (isEmpty(document.itemForm.descrizioneArticolo.value)) {
     alert('Inserire la descrizione completa dell\' articolo');
     return false;
   }

   extensionOk =  checkExtension(document.itemForm.immagine.value);
   if (!extensionOk){
         return false;
   }

   prices=checkAllPrices('itemForm','prezzoPromozione','prezzoArticoloPromo');
   if(!prices){
     return false;
   }
   else{
     isMoney = checkMoney(document.itemForm.prezzoArticoloAcquisto.value);
     if (!isMoney) {
      alert('Attenzione :  il prezzo di acquisto '+ document.itemForm.prezzoArticoloAcquisto.value  +' dell\' articolo non e\' valido !');
      return false;
     }  
   }

   return true;

 }


function checkModificaArticolo(){


   if (isEmpty(document.itemForm.descrizioneSintArticolo.value)) {
     alert('Inserire una breve descrizione per l\' articolo');
     return false;
   }
   if (isEmpty(document.itemForm.descrizioneArticolo.value)) {
     alert('Inserire la descrizione completa dell\' articolo');
     return false;
   }

   extensionOk =  checkExtension(document.itemForm.immagine.value);
   if (!extensionOk){
         return false;
   }

   prices=checkAllPrices('itemForm','prezzoPromozione','prezzoArticoloPromo');
   if(!prices){
     return false;
   }
   else{
     isMoney = checkMoney(document.itemForm.prezzoArticoloAcquisto.value);
     if (!isMoney) {
      alert('Attenzione :  il prezzo di acquisto '+ document.itemForm.prezzoArticoloAcquisto.value  +' dell\' articolo non e\' valido !');
      return false;
     }
   }


   return true;

 }


function checkCategoryReviewUpdate(){
   prices=checkAllPrices('categoryReviewForm','prezzoPromozione','prezzoArticoloPromo');
   if(!prices){
     return false;
   }
   return true; 
}


function checkNewsLetter(){



   if (isEmpty(document.newsLetterForm.title.value)) {
     alert('Inserire il titolo della NewsLetter');
     return false;
   }

   if (isEmpty(document.newsLetterForm.text.value)) {
     alert('Inserire il testo della NewsLetter');
     return false;
   }


   extensionOk =  checkListinoExtension(document.newsLetterForm.listino.value);
   if (!extensionOk){
         return false;
   }

   return true;

 }








function checkAllPrices(FormName, CheckName, FieldName)
{

    if(!document.forms[FormName])
		return true;
    var checks = document.forms[FormName].elements[CheckName];
    var prices = document.forms[FormName].elements[FieldName];
	if(!prices) return true;
	var countprices = prices.length;
	if(!countprices)
		return true;
	else
		// set the check value for all check boxes
		for(var i = 0; i < countprices; i++){
          //alert('controllo di '+prices[i].value);
          if (checks[i].checked==true){
             isMoney = checkMoney(prices[i].value);
             if (!isMoney) {
                 alert('Attenzione :  il prezzo '+ prices[i].value  +' dell\' articolo non e\' valido !');
                return false;
             }
          }
        }
    return true;
}

function confirmDeleteItem(itemId){

    var answer = confirm('Sei sicuro di voler eliminare l\'articolo con progressivo '+ itemId + ' ?');
	if (answer){
	    window.location = "deleteItem.do?id="+itemId;
	}
	else{
		//alert("Articolo non cancellato")
	}

}


function checkMoney(sText)

{  var ValidChars = "0123456789,";
   var IsNumber=true;
   var Char;

   if ((sText==null)||(sText.length==0)) return false;

   for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;

   }

 

function SetAllCheckBoxes(FormName, FieldName, CheckValue)
{
	if(!document.forms[FormName])
		return;
	var objCheckBoxes = document.forms[FormName].elements[FieldName];
	if(!objCheckBoxes)
		return;
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes)
		objCheckBoxes.checked = CheckValue;
	else
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++)
			objCheckBoxes[i].checked = CheckValue;
}

var dtCh= "/";
var minYear=1900;
var maxYear=2100;

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"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this
}

function isDate(dtStr)
{
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("Il formato data deve essere : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert(month);
                return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("b");
                return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("c");
                return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("d");
                return false
	}
return true
}
function CheckRegistration()
  {
    var user = document.getElementById('regusr');
    var pwd = document.getElementById('regpwd');
    var pwd_confirm = document.getElementById('regpwdc');
    var surname = document.getElementById('regsurn');
    var name = document.getElementById('regname');
    var mail = document.getElementById('regmail');
    var birth = document.getElementById('regbirth');
    var phone = document.getElementById('regphone');
    var cell = document.getElementById('regmob');
    var fax = document.getElementById('regfax');

    if(user.value.length==0) {
      alert ('Il campo username non puņ essere vuoto');
      user.focus();
      user.select();
      return false;
    }
    if(user.value.indexOf("'")!=-1)
    {
      alert('Il campo username non puņ contenere apici');
      return false;
    }
    if(pwd.value.length==0) {
      alert ('Il campo password non puņ essere vuoto');
      return false;
    }
    if(pwd.value.indexOf("'")!=-1)
    {
      alert('Il campo password non puņ contenere apici');
      return false;
    }
    if(pwd.value!=pwd_confirm.value)
    {
      alert('Le due password inserite non coincidono');
      return false;
    }
    if(surname.value.length==0) {
      alert ('Il campo Cognome non puņ essere vuoto');
      return false;
    }
    if(name.value.length==0) {
      alert ('Il campo nome non puņ essere vuoto');
      return false;
    }
    if(isDate(birth.value)==false) {
      alert ('Il campo Data di Nascita non č correttamente valorizzato');
      return false;
    }
    if(!isEmail(mail.value)) {
      alert ('Il campo E-Mail non e\' correttamente valorizzato');
      return false;
    }
    if(phone.value.length!=0 && isNaN(phone.value.length)) {
      alert ('Il campo Telefono non č correttamente valorizzato');
      return false;
    }
    if(cell.value.length!=0 && isNaN(cell.value.length)) {
      alert ('Il campo Mobile non č correttamente valorizzato');
      return false;
    }
    if(fax.value.length!=0 && isNaN(fax.value.length)) {
      alert ('Il campo Fax non č correttamente valorizzato');
      return false;
    }
  }
function CheckLogin()
  {
    var user = document.getElementById('username');
    var pwd = document.getElementById('password')
    if(user.value.length==0) {
      alert ('Valore obbligatorio per il campo username');
      return false;
    }
    if(pwd.value.length==0) {
      alert ('Valore obbligatorio per il campo password');
      return false;
    }
  }
function checkEmpty()
  {
    var user = document.getElementById('ctgdesc');
    if(user.value.length==0) {
      alert ('Inserire una descrizione categoria valida ');
      return false;
    }
  }
function textCounter(field, countfield, maxlimit) {
  if (field.value.length > maxlimit) // if too long...trim it!
      field.value = field.value.substring(0, maxlimit);
      // otherwise, update 'characters left' counter
  else
      countfield.value = maxlimit - field.value.length;
}


function checkRispostaMessaggio(){


   if (isEmpty(document.rispostaMessaggioForm.titoloRisposta.value)) {
     alert('Inserire il titolo nella risposta al messaggio');
     return false;
   }
   if (isEmpty(document.rispostaMessaggioForm.testoRisposta.value)) {
     alert('Inserire il testo nella risposta al messaggio');
     return false;
   }


   }

function checkEmpty()
  {
    var user = document.getElementById('forgemail');
    if(user.value.length==0) {
      alert ('Inserire una email valida ');
      return false;
    }
  }

function checkExtension(fullName){

if ((fullName!=null)&&(fullName.length>0)){
  shortName = fullName.match(/[^\/\\]+$/);
  splitName = fullName.split(".");
  fileType = splitName[1];
  fileType = fileType.toLowerCase();
if (!(fileType == 'gif' || fileType == 'jpg' || fileType == 'jpeg')) {
   alert('Tipo di file non valido. Allegare immagini gif , jpg o jpeg')
   return false;
   }
 }

 return true;
}

function checkListinoExtension(fullName){

if ((fullName!=null)&&(fullName.length>0)){
  shortName = fullName.match(/[^\/\\]+$/);
  splitName = fullName.split(".");
  fileType = splitName[1];
  fileType = fileType.toLowerCase();
if (!(fileType == 'pdf' || fileType == 'txt' || fileType == 'doc')) {
   alert('Tipo di file non valido. Allegare file in formato pdf , txt o doc')
   return false;
   }
 }

 return true;
}


function checkEm1()
  {
    var user = document.getElementById('ctgdesc');
    if(user.value.length==0) {
      alert ('Inserire una email valida ');
      return false;
    }
  }

function checkEm2()
  {
    var user = document.getElementById('prfdesc');
    if(user.value.length==0) {
      alert ('Inserire una email valida ');
      return false;
    }
  }

  function checkEm3()
 {
   var user = document.getElementById('searchusr');
   if(user.value.length==0) {
     alert ('Inserire un identificativo utente valido');
     return false;
   }
 }

function checkMail(str){
    ok = isEmail(str);
    if (!ok){
        alert('Inserire una e-mail valida');
        return false;
    }
}

function isEmail(str) {

  if ((str==null)||(str.length==0)) return false;  

  var supported = 0;
  if (window.RegExp) {
    var tempStr = "a";
    var tempReg = new RegExp(tempStr);
    if (tempReg.test(tempStr)) supported = 1;
  }
  if (!supported)
    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
  return (!r1.test(str) && r2.test(str));
}


function addOption(theSel, theText, theValue)
{
var newOpt = new Option(theText, theValue);
var selLength = theSel.length;
theSel.options[selLength] = newOpt;
}


function deleteOption(theSel, theIndex)
{ var selLength = theSel.length;
if(selLength>0)
{theSel.options[theIndex] = null;}
}

function moveOptions(theSelFrom, theSelTo,field,listName)
{ var selLength = theSelFrom.length;
var selectedText = new Array();
var selectedValues = new Array();
var selectedCount = 0;
var i;
// Find the selected Options in reverse order
// and delete them from the 'from' Select.
for(i=selLength-1; i>=0; i--)
{ if(theSelFrom.options[i].selected)
{
if(theSelFrom.options[i].value!=-1){
 selectedText[selectedCount] = theSelFrom.options[i].text;
 selectedValues[selectedCount] = theSelFrom.options[i].value;
 deleteOption(theSelFrom, i);
 selectedCount++;
}
}

}

// Add the selected text/values in reverse order.
// This will add the Options to the 'to' Select
// in the same order as they were in the 'from' Select.
for(i=selectedCount-1; i>=0; i--)
{
 addOption(theSelTo, selectedText[i], selectedValues[i]);
}

//alert('selectedCount = '+listName.length);
field.value="";
for(c=0;c<listName.length;c++){
   if (field.value.length>0){
      field.value = field.value + ";"+ listName.options[c].value;
   }
   else{
     field.value =  listName.options[c].value;
   }
}

}


function checkPricePromo(checks,fields){



    for (i=0; i<checks.length; i++)
        {
           if (checks[i].checked == true){
            if (fields[i].readOnly==true){
               fields[i].readOnly=false;
               fields[i].value="0,0";
            }
           }
           if (checks[i].checked == false){
             fields[i].readOnly=true;
             fields[i].value="";
           }

    }

}


function checkValueEntry(checks,fields){



    for (i=0; i<checks.length; i++)
        {
           if (checks[i].checked == true){
            if (fields[i].readOnly==true){
               fields[i].readOnly=false;
               fields[i].value="0,0";
            }
           }
           if (checks[i].checked == false){
             fields[i].readOnly=true;
             fields[i].value="";
             fields[i].disabled;  
           }

    }

}

/**
 * Popup code
 */
function openpopup(url, popupName, width, height) {
	var xx, yy;
	xx = 150;
	yy = 100;
	window.open(url , popupName, 'directories=0, location=0, menubar=0, status=0, toolbar=0, width=' + width + ', height=' + height + ', top=' + yy + ', left=' + xx);

}


//cosimo
function checkCategoriaArticolo(){

  if (isEmpty(document.categoriaArticoloForm.desc.value)) {
    alert('Inserire la descrizione della categoria');
    return false;
  }
  return true;
 }

function nuovapagina()
{
  frmtest.target="_blank";
  return true;
}
function stessapagina()
{
  frmtest.target="_self";
  return true;
}
//fine cosimo



function UpdateListino()
{
        
        document.updListino.bottoneSi.value = "Update in corso...";
        document.updListino.bottoneSi.disabled = true;
        document.updListinoNo.bottoneNo.disabled=true;
        //confirm('Update del listino in corso...',null);
        alert('Update del listino in corso\nAttenzione: non rilanciare un nuovo update\nprima del termine di questo!');
        window.setTimeout("EseguiUpdListino()", 3000);
    }


function EseguiUpdListino()
{
    document.updListino.method = "post";
    document.updListino.action = "updateListino.do";
    document.updListino.submit();
}

