// ----------------------------------------------------------------------------
//
//  File:   validate.js
//  Creation Date:  14/03/10
//  Last Modified:  14/03/10
//  Purpose:
//
// ----------------------------------------------------------------------------

/////////////////////////////
// --- Controllo Alert Form
////////////////////////////
function MM_findObj(n, d) { //v4.01
  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=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function ValidateForm() {
  var i,p,q,nm,test,num,min,max,errors='',args=ValidateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.id; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' deve essere un indirizzo valido.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' deve essere un numero.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' deve essere un numero compreso tra '+min+' e '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' è obbligatorio.\n'; }
  } if (errors) alert('Si sono verificati i seguenti errori:\n'+errors);
  document.ReturnValue = (errors == '');
}

////////////////////////////////
// --- Controllo Alert Immagini
///////////////////////////////
function checkFileUpload(form, extensions, requireUpload, sizeLimit, minWidth, minHeight, maxWidth, maxHeight, saveWidth, saveHeight) {
  var allUploadsOK = true;
  document.MM_returnValue = false;
  for (var i = 0; i < form.elements.length; i++) {
    field = form.elements[i];
    if (!field.type || field.type.toUpperCase() != 'FILE') {
      continue;
    }
    checkOneFileUpload(field,extensions,requireUpload,sizeLimit,minWidth,minHeight,maxWidth,maxHeight,saveWidth,saveHeight);
    if (!field.uploadOK) {
      allUploadsOK = false;
      break;
    }
  }
  if (allUploadsOK) {
    document.MM_returnValue = true;
  }
}

function checkOneFileUpload(field, extensions, requireUpload, sizeLimit, minWidth, minHeight, maxWidth, maxHeight, saveWidth, saveHeight) {
  var fileName = field.value.replace(/"/gi,'');
  field.uploadOK = false;
  if (fileName == '') {
    if (requireUpload) {
      alert('È necessario il file !!!');
      field.focus();
      return;
    } else {
      field.uploadOK = true;
    }
  } else {
    if (extensions != '') {
      checkFileExtension(field, fileName, extensions);
    } else {
      field.uploadOK = true;
    }
    if (!document.layers && field.uploadOK) {
      document.PU_uploadForm = field.form;
      re = new RegExp("\.(gif|jpg|png|bmp|jpeg)$","i");
      if(re.test(fileName) && (sizeLimit != '' || minWidth != '' || minHeight != '' || maxWidth != '' || maxHeight != '' || saveWidth != '' || saveHeight != '')) {
        checkImageDimensions(field,sizeLimit,minWidth,minHeight,maxWidth,maxHeight,saveWidth,saveHeight);
      }
    }
  }
  return;
}

function checkFileExtension(field, fileName, extensions) {
  var re = new RegExp("\\.(" + extensions.replace(/,/gi,"|").replace(/\s/gi,"") + ")$","i");
  var agt = navigator.userAgent.toLowerCase();
  var is_mac = (agt.indexOf("mac") != -1);
  var is_op = (agt.indexOf("opera") != -1);
  if (is_op) {
    var ext = fileName.substring(fileName.lastIndexOf('.')+1, fileName.length);
    var extArr = extensions.split(',');
    var extCheck = false;
    for (var i = 0; i < extArr.length; i++) {
      if (extArr[i].toLowerCase() == ext.toLowerCase()) {
        extCheck = true;
        break;
      }
    }
    if (extCheck == false) {
      alert('Questo tipo di file non è consentito per il caricamento.\nSolo le seguenti estensioni di file sono ammessi: ' + extensions + '.\nSi prega di selezionare un altro file e riprovare.');
      field.focus();
      field.uploadOK = false;
      return;
    }
  } else {
    if (!re.test(fileName)) {
      alert('Questo tipo di file non è consentito per il caricamento.\nSolo le seguenti estensioni di file sono ammessi: ' + extensions + '.\nSi prega di selezionare un altro file e riprovare.');
      field.focus();
      field.uploadOK = false;
      return;
    }
  }
  field.uploadOK = true;
}

function checkImageDimensions(field,sizeL,minW,minH,maxW,maxH,saveW,saveH) {
  var agt = navigator.userAgent.toLowerCase();
  var is_mac = (agt.indexOf("mac") != -1);
  var is_ie = document.all;
  var is_ns6 = (!document.all && document.getElementById ? true : false);
  var fileURL = field.value;
  if (is_ie && is_mac) {
    begPos = fileURL.indexOf('/',1);
    if (begPos != -1) {
      fileURL = fileURL.substring(begPos+1,fileURL.length);
    }
  }
  fileURL = 'file:///' + fileURL.replace(/:\\/gi,'|/').replace(/\\/gi,'/').replace(/:([^|])/gi,'/$1').replace(/"/gi,'').replace(/^\//,'');
  if (!field.gp_img || (field.gp_img && field.gp_img.src != fileURL) || is_ns6) {
    if (is_ie && is_mac) {
      var dummyImage;
      dummyImage = document.createElement('IMG');
      dummyImage.src = 'dummy.gif';
      dummyImage.name = 'PPP';
      field.gp_img = dummyImage;
    } else {
      field.gp_img = new Image();
    }
    with (field) {
      gp_img.field = field;
      gp_img.sizeLimit = sizeL*1024;
      gp_img.minWidth = minW;
      gp_img.minHeight = minH;
      gp_img.maxWidth = maxW;
      gp_img.maxHeight = maxH;
      gp_img.saveWidth = saveW;
      gp_img.saveHeight = saveH;
      gp_img.onload = showImageDimensions;
      gp_img.src = fileURL+'?a=123'; // +(Math.round(Math.random()*998)+1);
    }
  }
}

function showImageDimensions(fieldImg) {
  var is_ns6 = (!document.all && document.getElementById ? true : false);
  var img = (fieldImg && !is_ns6 ? fieldImg : this);
  if (img.width > 0 && img.height > 0) {
    if ((img.minWidth != '' && img.minWidth > img.width) || (img.minHeight != '' && img.minHeight > img.height)) {
      alert('Caricato immagine è troppo piccola!\nDovrebbe essere almeno ' + img.minWidth + ' x ' + img.minHeight);
      img.field.uploadOK = false;
      return;
    }
    if ((img.maxWidth != '' && img.width > img.maxWidth) || (img.maxHeight != '' && img.height > img.maxHeight)) {
      alert('Caricato immagine è troppo grande!\nDovrebbe essere max ' + img.maxWidth + ' x ' + img.maxHeight);
      img.field.uploadOK = false;
      return;
    }
    if (img.sizeLimit != '' && img.fileSize > img.sizeLimit) {
      alert('Uploaded Image Dimensione file è troppo grande!\nDovrebbe essere max ' + (img.sizeLimit/1024) + ' KBytes');
      img.field.uploadOK = false;
      return;
    }
    if (img.saveWidth != '') {
      document.PU_uploadForm[img.saveWidth].value = img.width;
    }
    if (img.saveHeight != '') {
      document.PU_uploadForm[img.saveHeight].value = img.height;
    }
    if (document.PU_uploadForm[img.field.name+'_width']) {
      document.PU_uploadForm[img.field.name+'_width'].value = img.width;
    }
    if (document.PU_uploadForm[img.field.name+'_height']) {
      document.PU_uploadForm[img.field.name+'_height'].value = img.height;
    }
    img.field.uploadOK = true;
  }
}


function showProgressWindow(progressFile,popWidth,popHeight) {
  var showProgress = false, form, field;
  for (var f = 0; f<document.forms.length; f++) {
    form = document.forms[f];
    for (var i = 0; i<form.elements.length; i++) {
      field = form.elements[i];
      if (!field.type || field.type.toUpperCase() != 'FILE') {
        continue;
      }
      if (field.value != '') {
        showProgress = true;
        break;
      }
    }
  }
  if (showProgress && document.MM_returnValue) {
    var w = 480, h = 340;
    if (document.all || document.layers || document.getElementById) {
      w = screen.availWidth; h = screen.availHeight;
    }
    var leftPos = (w-popWidth)/2, topPos = (h-popHeight)/2;
    document.progressWindow = window.open(progressFile,'ProgressWindow','toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=' + popWidth + ',height='+popHeight);
    document.progressWindow.moveTo(leftPos, topPos);
    document.progressWindow.focus();
    window.onunload = function () {
      document.progressWindow.close();
    };
  }
}

///////////////////////
// --- Valida URL, NUM
//////////////////////
function onlynumers(s){
  Filtro = /[^0-9.]/;
  s.value = s.value.replace(Filtro,"");
}

function onlylettere(s){
  Filtro = /[^0-9A-z ]/;
  s.value = s.value.replace(Filtro,"");
}

/////////////
// --- Popup
/////////////
var stile = "top=50, left=50, width=350, height=100, status=no, menubar=no, toolbar=no scrollbar=no";
function Popup(apri) {
	window.open(apri, "", stile);
}

/////////////////////////////////////
// --- Popup showMailProgressWindow
/////////////////////////////////////
function showMailProgressWindow(progressFile,popWidth,popHeight) { //v1.00
  if (document.MM_returnValue!=false) {
    var w = 480, h = 340;
    if (document.all || document.layers || document.getElementById) {
      w = screen.availWidth; h = screen.availHeight;}
    var leftPos = (w-popWidth)/2, topPos = (h-popHeight)/2;
    document.progressWindow = window.open(progressFile,'ProgressWindow','toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=' + popWidth + ',height='+popHeight);
    document.progressWindow.moveTo(leftPos, topPos);document.progressWindow.focus();
   window.onunload = function () {document.progressWindow.close();};
} }