// last update 2008-10-13

/* problem occurs with
localPath = window.location;
if the site is called including index.php or with hash (e.g. #nogo), therefore:
*/
if (window.location.host == 'www.sigparconordmilano.it' )
    localPath = "https://"+window.location.host+"/vnlib/dreiser/";  // WebGIS
else if (window.location.host == 'www.parconord.milano.it') {
    localPath = "http://"+window.location.host+"/vnlib/dreiser/";  // WebGIS no HTTPS
} else if (/sigweb/.test(window.location)) { //ABP: added switch to test local
  localPath = "http://"+window.location.host+"/~ale/itopen/sigweb/vnlib/dreiser/"; 
} else {
  localPath = "http://"+window.location.host+"/ParcoNord/";         // CDR, ParcoNord, planquadrat
}
//alert("localPath "+localPath);
albFolder = localPath+"alb/";
//alert("albFolder "+albFolder);

var noSVG=1; //  suppress the SVG map: 1, show SVG: 0

/*  embedded SVG is the temporary solution for missing integration in WebGIS
    for Mozilla-Browsers no Plugin is needed
    for IE the Adobe Plugin is needed, which supports drop shadow used here to add some fancy
    this functionality is not available for the Mozilla-Browsers, therefore appearance is more dull
*/
var embedSVG = '<embed id="alb_particella_svg" '+
               'name="alb_particella_svg" '+
               'type="image/svg+xml" '+
               'src="'+albFolder+'svg/subPart_new_5_vet.svg" '+
               'pluginspage="http://www.adobe.com/svg/viewer/install/" >'+
               '</embed>';

// === jquery initialisation ======================

$(document).ready(function() {

/*  set the background image as a temporary solution before integration into WebGIS
    $('div#alb_backgrd').html('<img src="'+albFolder+'img/WebGIS_ohneIE_0.jpg" alt="background screenshot WebGIS" />');
*/

  $('.cont_Child').empty();     // empty all secondary containers

  $('#alb_lnkOpenArchivio').click(function () {   // set onclick events to the link to open the archivio
    $('#alb_Container_frmCompileQuery')
      .load(albFolder+'alb_FormCompileSQLquery.php',
        function () {                   // the callback function follows the load process
          alb_startRequest();           // run the query for records with the default settings
          $('img.menue_toggle'     ).attr('src',albFolder+'img/Transparent_1_1.png');  // set the images src...
          $('img.chboxGroup_toggle').attr('src',albFolder+'img/Transparent_1_1.png');  // ...to a transparent image
          $('img.chboxSub_toggle'  ).attr('src',albFolder+'img/Transparent_1_1.png');  // ...as click changes only the css
          $('img.chbox_toggle'     ).attr('src',albFolder+'img/Transparent_1_1.png');  // ...background images src
          $('img.menue_toggle').click(function () {                     // add the onclick events for the menue toggle images
                $(this).parents('table').siblings('table:first').slideToggle();   // open/close the submenue
                $(this).toggleClass('menue_opened').toggleClass('menue_closed');  // toggle the symbol (+, -)
          });
          $('td.chboxGroup_toggle').click(function () {           // the group toggle icon has 3 states:
                $('img',this)                                     // ...selected: all sub-checkboxes are 'selected'
                      .removeClass('chbox_partial')               // ...unselected: non of the  sub-checkboxes is 'selected'
                      .toggleClass('chbox_checked')               // ...partially selected: one or more of the sub-checkboxes is 'selected'
                      .toggleClass('chbox_unchecked');
                if ($('img',this).hasClass('chbox_checked')) {
                  $(this).parents('table').siblings('table:first').find('img')  // sets all sub-chackboxes of its group to either
                      .removeClass('chbox_unchecked')                           // ... 'selected' of 'unselected'
                      .addClass('chbox_checked'); }
                else {
                  $(this).parents('table').siblings('table:first').find('img')
                      .removeClass('chbox_checked')
                      .addClass('chbox_unchecked'); };
                alb_startRequest();
          });
          $('td.chboxSub_toggle').click(function () {                     // for checkboxes, which are part of a group
                $('img',this)
                  .toggleClass('chbox_checked')
                  .toggleClass('chbox_unchecked');
                $(this).parents('div:first').find('table:first img:last') // their state influences the group toggle icon
                      .removeClass('chbox_partial')                       // set the group toggle icon to 'unselected'...
                      .removeClass('chbox_checked')                       // ... and set it to 'partially selected'
                      .addClass('chbox_unchecked');                       // ... if one or more of the checkboxes of this group are currently selected
                if ($(this).parents('div:first').find('table:last img').hasClass('chbox_checked')) {
                    $(this).parents('div:first').find('table:first img:last')
                            .addClass('chbox_partial'); };
                alb_startRequest();
          });
          $('td.chbox_toggle').click(function () {              // for any other checkbox, which is not part of a group
                $('img',this).toggleClass('chbox_checked').toggleClass('chbox_unchecked');
                alb_startRequest();
          });
       });
   });
});

// === declaration of arrays  ====================================================================

// as these array elements are <img id=, they must be unique for the forms in
// FormCompileSQL and UpdateRecord, hence lots of redundancy

var selCheckboxSpecial    = [ "amministrativi","eliminato","non_pubblico",
                              "man_ordinaria","anno_0"];  // those two are only temporary as long as the DB check has not been completed
var updateCheckboxSpecial = [ "updateAMMINISTRATIVI","updateELIMINATO","updateNON_PUBBLICO"];

// check box arrays for FormCompileSQLquery
// here it is necessary to have the 00 element in order to select the entire group
var selectAR = ["selectAR00","selectAR01","selectAR02","selectAR03","selectAR04","selectAR05",
                "selectAR06","selectAR07","selectAR08","selectAR09","selectAR10","selectAR11",
                "selectAR12","selectAR13","selectAR14"];

var selectGE = ["selectGE00","selectGE01","selectGE02","selectGE03","selectGE04","selectGE05",
                "selectGE06","selectGE07","selectGE08","selectGE09","selectGE10","selectGE11",
                "selectGE12","selectGE13","selectGE14","selectGE15","selectGE16","selectGE17",
                "selectGE18","selectGE19","selectGE20","selectGE21"];

var selectSR = ["selectSR00","selectSR01","selectSR02","selectSR03","selectSR04","selectSR05",
                "selectSR06","selectSR07","selectSR08","selectSR09","selectSR10","selectSR11",
                "selectSR12","selectSR13"];

var selectTD = ["selectTD00","selectTD01","selectTD02","selectTD03","selectTD04","selectTD05",
                "selectTD06","selectTD07","selectTD08","selectTD09","selectTD10","selectTD11"];

var selectPR = ["selectPR00","selectPR01","selectPR02","selectPR03"];


// check box arrays for UpdateRecord
// not included is the 00 element as it is not necessary and would cause problems

var updateAR = [             "updateAR01","updateAR02","updateAR03","updateAR04","updateAR05",
                "updateAR06","updateAR07","updateAR08","updateAR09","updateAR10","updateAR11",
                "updateAR12","updateAR13","updateAR14"];

var updateGE = [             "updateGE01","updateGE02","updateGE03","updateGE04","updateGE05",
                "updateGE06","updateGE07","updateGE08","updateGE09","updateGE10","updateGE11",
                "updateGE12","updateGE13","updateGE14","updateGE15","updateGE16","updateGE17",
                "updateGE18","updateGE19","updateGE20","updateGE21"];

var updateSR = [             "updateSR01","updateSR02","updateSR03","updateSR04","updateSR05",
                "updateSR06","updateSR07","updateSR08","updateSR09","updateSR10","updateSR11",
                "updateSR12","updateSR13"];

var updateTD = [             "updateTD01","updateTD02","updateTD03","updateTD04","updateTD05",
                "updateTD06","updateTD07","updateTD08","updateTD09","updateTD10","updateTD11"];

var updatePR = [             "updatePR01","updatePR02","updatePR03"];


var Lotto2PARTICELLA = [
    ['0a','35a','35b','35c'],               //  0
    ['1a','1b','1c','1d'],                  //  1
    ['2a','2b','2c','2d'],                  //  2
    ['3e'],                                 //  3
    ['4a','4b','4c'],                       //  4
    ['18l','5a','6a','7a','7b','8a','9a'],  //  5
    ['10a','11a','12a','12b','13a'],                                                  //  6
    ['3a','3b','3c','3d','4d','6b','6c','6d','6e','6f','6g','6h','6i'],               //  7
    ['13b','13c','13d'],                                                              //  8
    ['14a','14b','15a','15b','15c','15d','15e','16a','16b'],                          //  9
    ['17a','17b','18a','18b','18c','18d','18e','18f','18i','24g'],                    // 10
    ['19a','19b','19c','20a','20b','21a','21b','21c','22a','26a'],                    // 11
    ['18m','18n','23a','23b','23c','23d','23e','23f','23g','24a','24b','24c'],        // 12
    ['25a','25b','25c','25d','25e'],                                                  // 13
    ['18g','18h','18o','24d','24i','27a','28a','28b'],                                // 14
    ['27b','29a'],                                                                    // 15
    ['22b'],                                                                          // 16
    ['21d','21e','22c','22d','24e','24f','24h','28c','29b','30a','32a'],              // 17
    ['31a','31b','31c'],                                                              // 18
    ['28d','28e','28f','33a'],                                                        // 19
    ['21f','21g','26b','26c','32b','32c','33b','8b'],                                 // 20
    ['29c','33c','34a','34b','34c','34d','34e'],                                      // 21
    ['10b','18p','18q','21h','24l','24m','24n','26d','26e','26f','27c','33d','9b'],   // 22
    ['22e','22f','22g','22h','22i','22l','25f','25g','25h','25i','25l','28g','28h','28i','35d','35e','35f','35g','36a']]; //  23

var subParticella = [
    ['a'],                                //0
    ['a','b','c','d'],                    //1
    ['a','b','c','d'],                    //2
    ['a','b','c','d','e'],                //3
    ['a','b','c','d'],                    //4
    ['a'],                                //5
    ['a','b','c','d','e','f','g','h','i'],//6
    ['a','b'],                            //7
    ['a','b'],                            //8
    ['a','b'],                            //9
    ['a','b'],                            //10
    ['a'],                                //11
    ['a','b'],                            //12
    ['a','b','c','d'],                    //13
    ['a','b'],                            //14
    ['a','b','c','d','e'],                //15
    ['a','b'],                            //16
    ['a','b'],                            //17
    ['a','b','c','d','e','f','g','h','i','l','m','n','o','p','q'],  //18
    ['a','b','c'],                                                  //19
    ['a','b'],                                                      //20
    ['a','b','c','d','e','f','g','h'],                              //21
    ['a','b','c','d','e','f','g','h','i','l'],                      //22
    ['a','b','c','d','e','f','g'],                                  //23
    ['a','b','c','d','e','f','g','h','i','l','m','n'],              //24
    ['a','b','c','d','e','f','g','h','i','l'],                      //25
    ['a','b','c','d','e','f'],                                      //26
    ['a','b','c'],                                                  //27
    ['a','b','c','d','e','f','g','h','i'],                          //28
    ['a','b','c'],                      //29
    ['a'],                              //30
    ['a','b','c'],                      //31
    ['a','b','c'],                      //32
    ['a','b','c','d'],                  //33
    ['a','b','c','d','e'],              //34
    ['a','b','c','d','e','f','g'],      //35
    ['a']];                             //36


// === String manipulation and other useful functions =================================================

function alb_removeWhitespace(str) {
 return str.split(' ').join('');

} 
//-------------------------------------------------------------------

function alb_trimString(str) {

// trim whitespace in string

  str = this != window? this : str;
  return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
//-------------------------------------------------------------------

function alb_Left(str, n){
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else
        return String(str).substring(0,n);
}
//-------------------------------------------------------------------

function alb_Right(str, n){
      if (n <= 0)
         return "";
      else if (n > String(str).length)
         return str;
      else {
         var iLen = String(str).length;
         return String(str).substring(iLen, iLen - n);
      }
}
//-------------------------------------------------------------------

function alb_sortNumber(a,b)  {
    return a - b;
}
//-------------------------------------------------------------------

function alb_in_array(needle, haystack, strict) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: alb_in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true

    var found = false, key, strict = !!strict;

    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }
    return found;
}

// ===== useful Array prototypes =========================

// as IE has a problem with indexOf with arrays, here a patch
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
};
//-------------------------------------------------------------------

Array.prototype.compare = function(testArr) {
// usage:
//  document.writeln(myArray.compare(yourArray));
//  elements must be identical, therfore "80" != 80

    if (this.length != testArr.length) return false;
    for (var i = 0; i < testArr.length; i++) {
        if (this[i].compare) {
            if (!this[i].compare(testArr[i])) return false;
        }
        if (this[i] !== testArr[i]) return false;
    }
    return true;
};
//-------------------------------------------------------------------

Array.prototype.sortNum = function() {
   return this.sort( function (a,b) { return a-b; } );
};
//-------------------------------------------------------------------

Array.prototype.find = function(searchStr) {
/*
  Array.indexOf() is a nice method but this extension
  is a little more powerful and flexible.
  First it will return an array of all the indexes
  it found (it will return false if it doesn't find anything).
  Second in addition to passing the usual string or number
  to look for you can actually pass a regular expression,
  which makes this the ultimate Array prototype in my book.

  var tmp = [5,9,12,18,56,1,10,42,'blue',30, 7,97,53,33,30,35,27,30,'35','Ball', 'bubble'];
  //         0/1/2 /3 /4/5 /6 /7     /8  /9/10/11/12/13/14/15/16/17/  18/    19/      20
  var thirty=tmp.find(30);             // Returns 9, 14, 17
  var thirtyfive=tmp.find('35');       // Returns 18
  var thirtyfive=tmp.find(35);         // Returns 15
  var haveBlue=tmp.find('blue');       // Returns 8
  var notFound=tmp.find('not there!'); // Returns false
  var regexp1=tmp.find(/^b/);          // returns 8,20    (first letter starts with b)
  var regexp1=tmp.find(/^b/i);         // returns 8,19,20 (same as above but ignore case)
*/
  var returnArray = false;
  for (i=0; i<this.length; i++) {
    if (typeof(searchStr) == 'function') {
      if (searchStr.test(this[i])) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    } else {
      if (this[i]===searchStr) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    }
  }
  return returnArray;
};
//-------------------------------------------------------------------

// Array.unique( strict ) - Remove duplicate values
Array.prototype.unique = function( b ) {
 var a = [], i, l = this.length;
 for( i=0; i<l; i++ ) {
  if( a.indexOf( this[i], 0, b ) < 0 ) { a.push( this[i] ); }
 }
 return a;
};

//===== SVG functions =========================

  var svgns   = "http://www.w3.org/2000/svg";
  var xlinkns = "http://www.w3.org/1999/xlink";

/* clip extents of the view used to create it */
  var clipMinX= 1513500;
  var clipMaxX= 1517100;
  var clipMinY= 5040000;
  var clipMaxY= 5044000;

//-------------------------------------------------------------------

function alb_changeSvgSize(newHeight,newWidth) {
  // original is height="857" width="674" 1.271

  var svgdoc = window.document.alb_particella_svg.getSVGDocument();
  var svg_node = svgdoc.getElementById("svgRoot");
//  var old_height = svg_node.getAttribute("height");
//  var old_width = svg_node.getAttribute("width");
  //alert(old_height+ " "+old_width); // 590, 470 1.2553
  svg_node.setAttribute("height",127);  // only FF
  svg_node.setAttribute("width",100); // only FF
 // window.document.alb_particella_svg.src="";
 // window.document.alb_particella_svg.setAttribute("style","display:none");  // only FF
 // window.document.alb_particella_svg.setAttribute("visibility","hidden");
  document.getElementById("alb_Container_SVG").setAttribute("style","left:212px");
}
//-------------------------------------------------------------------

function alb_changePathFill(embedId,itemStr,newFill) {

//  var svgdoc = parent.document.getElementById(embedId).getSVGDocument();
  var svgdoc = window.document.getElementById(embedId).getSVGDocument();
                    // alert(svgdoc);
                    // alert(itemStr);
  var svg_paths = svgdoc.getElementsByTagName("path");

  var itemName = alb_expandParticella(itemStr); /* dati.particella does not list the sub-particelle
                                              if all possible sub-particelle are present
                                              those missing sub-particelle
                                              are added by alb_expandParticella()
                                           */

  for (var i = 0; i < svg_paths.length; i++)  {

    if (svg_paths.item(i).firstChild) {
      NodeList = svg_paths.item(i).childNodes;
      if (NodeList.item(0).nodeName==='title') {
        if (alb_in_array(NodeList.item(0).firstChild.nodeValue, itemName))
            svg_paths.item(i).setAttribute("style", newFill);
      }
      //break;
    }
  }
}
//-------------------------------------------------------------------

function alb_addSvgPointSymbolCircle(embedId,insertAtId,symbolId,radius1,radius2,fillColor,strokeColor,strokeWidth) {
  //var embedID = 'alb_particella_svg';
  var svgdoc = window.document.getElementById(embedId).getSVGDocument();
                   //  alert(svgdoc);
  var svg_paths = svgdoc.getElementById(insertAtId);
/*
<defs>
  <symbol overflow="visible" x="0" y="0" id="alb_round_point_yellow_on_green" width="45" height="45" >
    <circle style="fill:rgb(10,10,10);stroke-width:1.5;stroke-linecap:round;stroke:rgb(10,10,10);" r="6" cx="1" cy="1"/>
    <circle style="fill:rgb(255,255,0);stroke-width:1.5;stroke-linecap:round;stroke:rgb(0,170,0);" r="6" cx="0" cy="0"/>
  </symbol>
 </defs>
*/

  var defs = svgdoc.createElementNS(svgns, "defs");
  var newSym = svgdoc.createElementNS(svgns, "symbol");
  newSym.setAttributeNS(null, "id", symbolId);
  newSym.setAttributeNS(null, "width", 45);
  newSym.setAttributeNS(null, "height", 45);
  newSym.setAttributeNS(null, "x", 0);
  newSym.setAttributeNS(null, "y", 0);
  newSym.setAttributeNS(null, "overflow", "visible");
  defs.appendChild(newSym);

    var cir1 = svgdoc.createElementNS(svgns, "circle");
    cir1.setAttributeNS(null, "r", radius1);
    cir1.setAttributeNS(null, "cx", 1);
    cir1.setAttributeNS(null, "cy", 1);
    cir1.setAttributeNS(null, "style", "fill:rgb(10,10,10);stroke-width:1.5;stroke-linecap:round;stroke:rgb(10,10,10);");
  newSym.appendChild(cir1);

    var cir2 = svgdoc.createElementNS(svgns, "circle");
    cir2.setAttributeNS(null, "r", radius2);
    cir2.setAttributeNS(null, "cx", 0);
    cir2.setAttributeNS(null, "cy", 0);
    var styleStr="fill:"+fillColor+";stroke-width:"+strokeWidth+";stroke:"+strokeColor+";stroke-linecap:round;";
    cir2.setAttributeNS(null, "style", styleStr);
  newSym.appendChild(cir2);

  svg_paths.appendChild(defs);

}
//-------------------------------------------------------------------

function alb_addSvgUseTag(embedId,insertAtId,symbolId,useTagName,realX,realY) {

  var svgDocument = window.document.getElementById(embedId).getSVGDocument();
  var svg_paths = svgDocument.getElementById(insertAtId);

  var svg_paths = svgDocument.getElementById("svgRoot");
  var viewBoxArray = svg_paths.getAttribute("viewBox").split(" "); // "0 0 559.000000 632"

  var svgX = viewBoxArray[0]+(realX-clipMinX)*(viewBoxArray[2]-viewBoxArray[0])/(clipMaxX-clipMinX);
  var svgY = viewBoxArray[3]-(realY-clipMinY)*(viewBoxArray[3]-viewBoxArray[1])/(clipMaxY-clipMinY);

  translateXY ="translate("+svgX+","+svgY+")";

  var use1= svgDocument.createElementNS(svgns,"use");
  use1.setAttributeNS(null, "name", useTagName);
  use1.setAttributeNS(null, "transform", translateXY);
  use1.setAttributeNS(xlinkns, "xlink:href", symbolId);

  svg_paths.appendChild(use1);
}
//-------------------------------------------------------------------

function alb_addSvgUseTagByArray(embedId,insertAtId,symbolId,useTagName,coordStr) {
// the coordinates and tagNames come from an array (progressivo,pointname,x,y)


  var svgDocument = window.document.getElementById(embedId).getSVGDocument();
  var svg_paths = svgDocument.getElementById(insertAtId);

  var svg_paths = svgDocument.getElementById("svgRoot");
  var viewBoxArray = svg_paths.getAttribute("viewBox").split(" "); // "0 0 559.000000 632"
/*
  the original GeorefPointList has the form
               [["1","Pt01","1515753.00","5043016.00"],
                ["1","Pt02","1515811.00","5043054.00"],
                ["165","Pt01","1516111.00","5043054.00"],
                ["165","Pt02","1516211.00","5043154.00"],
                ["165","Pt03","1512000.00","5043000.00"]];
 // unfortunately the GeorefPointList comes as anormal string not as array
  "1,Pt01,1515753.00,5043016.00,1,Pt02,1515811.00,5043054.00,165,Pt01,1516111.00,5043054.00"
*/
  var coordArray = coordStr.split(",");

  for (var i = 0; i < coordArray.length; i++) {
    if (i >= coordArray.length) break;
    //alert(coordArray[i+0]+" "+useTagName);
    if (coordArray[i+0] == useTagName) {
      var useTagId = coordArray[i+1];
      var realX    = coordArray[i+2];
      var realY    = coordArray[i+3];
      i = i+3;
        var svgX = viewBoxArray[0]+(realX-clipMinX)*(viewBoxArray[2]-viewBoxArray[0])/(clipMaxX-clipMinX);
        var svgY = viewBoxArray[3]-(realY-clipMinY)*(viewBoxArray[3]-viewBoxArray[1])/(clipMaxY-clipMinY);

        var translateXY ="translate("+svgX+","+svgY+")";

        var use1= svgDocument.createElementNS(svgns,"use");
        use1.setAttributeNS(null, "id", useTagId);
        use1.setAttributeNS(null, "name", useTagName);
        use1.setAttributeNS(null, "transform", translateXY);
        use1.setAttributeNS(xlinkns, "xlink:href", symbolId);

        svg_paths.appendChild(use1);
    }
  }
}
//-------------------------------------------------------------------

function alb_removeSvgUseTags(embedId) {
  var svgDocument = window.document.getElementById(embedId).getSVGDocument();


  while (svgDocument.getElementsByTagName("use").length>0)
    {
    //alert(svg_paths.length);
      var svg_paths = svgDocument.getElementsByTagName("use");
      if (svg_paths.item(0).getParentNode)
        svg_paths.item(0).getParentNode.removeChild(svg_paths.item(0));
  }

}

// === end SVG functions ================================================

function alb_Convert_Lotto2Particella(form_name,input_Lotto_name,input_Part_name) {
// this is a (hopefully) temporary solution to convert changes of the field
// uses the array Lotto2PARTICELLA

 var LottoArray = document.forms[form_name].elements[input_Lotto_name].value.split(",");
 var newPartValueStr = '';
 for (var i=0; i< LottoArray.length; i++) {
  //alert("hi "+Lotto2PARTICELLA[LottoArray[i]]);
  if (i==0) newPartValueStr=                    Lotto2PARTICELLA[LottoArray[i]];
  else      newPartValueStr=newPartValueStr+','+Lotto2PARTICELLA[LottoArray[i]];
 }
 document.forms[form_name].elements[input_Part_name].value = newPartValueStr;
}
//-------------------------------------------------------------------

function alb_checkInputAsYouTypeElName(form_name,field_name,datatype,valid_values_min,valid_values_max) {
// version with form names and element names, which works with form input, but not with form textarea
// should be replaced by the following function in future

    var inputID       = document.forms[form_name].elements[field_name];
    var input_string  = document.forms[form_name].elements[field_name].value;
    var validLottoParticella="0123456789,";
    var validSubParticella="abcdefghilmnopq";
    var valid="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZÄäÖöÜüßáéíóúàèìòùÁÉÍÓÚÀÈÌÒÙ=+-°!?.;,:/%()'@ ";
        // check numeric integer
    if (datatype == 'int') {
      input_string = alb_trimString(input_string); // trim whitespace

      if (parseInt(input_string,10) != input_string) {
        alert('input di questo campo deve essere numerico');
        document.forms[form_name].elements[field_name].value = input_string.substring(0,input_string.length-1);
      }
      else if ((parseInt(input_string,10) < valid_values_min) || (parseInt(input_string) > valid_values_max)) {
        alert('input di questo campo fuori gamma '+valid_values_min+'..'+valid_values_max);
        document.forms[form_name].elements[field_name].value = input_string.substring(0,input_string.length-1);
      }
      //else alert(valid_values_max);
      return false;
    }
    // check alphanumeric text fields for LottoParticella: only numbers and komma valid
    // plus sub-particella
    else if (datatype == 'LottoParticella') {

      input_string = alb_trimString(input_string); // trim whitespace

      if ((validLottoParticella.indexOf(input_string.charAt(input_string.length-1)) < 0) &&
          (validSubParticella.indexOf(input_string.charAt(input_string.length-1).toLowerCase()) < 0)) {
        alert('charattere invalido  '+input_string.charAt(input_string.length-1)+' eliminato');
        document.forms[form_name].elements[field_name].value = input_string.substring(0,input_string.length-1);
      }
       //inputID.focus();
      return false;
    }
    // check alphanumeric text fields
    else if (valid.indexOf(input_string.charAt(input_string.length-1)) < 0) {
        alert('charattere invalido "'+input_string.charAt(input_string.length-1)+'" eliminato');
      document.forms[form_name].elements[field_name].value = input_string.substring(0,input_string.length-1);
      //inputID.focus();
      return false;
    }
    // check maxlength (text input attribute)
    else if (input_string.length > input_string.maxlength) {
      alert('input troppo lunga. maxlength di questo campo '+input_string.maxlength);
      document.forms[form_name].elements[field_name].value = input_string.substring(0,input_string.length-1);
      return false;
    }
  }
//-------------------------------------------------------------------

function alb_checkInputAsYouTypeElID(elemID,datatype,valid_values_min,valid_values_max) {
// like above, but instead we use the element ID here as the above did not work with <form <textarea

    var input_string  = document.getElementById(elemID).value;
    var valid="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZÄäÖöÜüßáéíóúàèìòùÁÉÍÓÚÀÈÌÒÙ=+-°!?.;,:/%()'@ ";

    // check numeric integer
    if (datatype == 'int') {
      input_string = alb_trimString(input_string); // trim whitespace

      if (parseInt(input_string,10) != input_string) {
        alert('input di questo campo deve essere numerico');
        document.getElementById(elemID).value = input_string.substring(0,input_string.length-1);
      }
      else if ((parseInt(input_string,10) < valid_values_min) || (parseInt(input_string) > valid_values_max)) {
        alert('input di questo campo fuori gamma '+valid_values_min+'..'+valid_values_max);
        document.getElementById(elemID).value = input_string.substring(0,input_string.length-1);
      }
      //else alert(valid_values_max);
      return false;
    }
    // check alphanumeric text fields
    else if (valid.indexOf(input_string.charAt(input_string.length-1)) < 0) {
        alert('charattere invalido  '+input_string.charAt(input_string.length-1)+' eliminato');
      document.getElementById(elemID).value = input_string.substring(0,input_string.length-1);
      //inputID.focus();
      return false;
    }
    // check maxlength (text input attribute)
    else if (input_string.length > input_string.maxlength) {
      alert('input troppo lunga. maxlength di questo campo '+input_string.maxlength);
      document.getElementById(elemID).value = input_string.substring(0,input_string.length-1);
      return false;
    }
  }
//-------------------------------------------------------------------

function alb_expandParticella(input_str) {

// dati.particella stores only particella if all sub-particelle are present
// this is done by alb_trimParticella()
// however in order to change the style:fill color of the SVG, all the sub-particelle must be listed
// this function expands the compacted dati.PARticella string
// using array subParticella

  var tempArray = input_str.split(",");
  var outArray = [];

  for (var i=0; i<tempArray.length; i++) {
    if (parseInt(tempArray[i],10) == tempArray[i]) {  // tempArray[i]=particella
      for (var j=0; j<subParticella[tempArray[i]].length; j++)
        outArray.push(tempArray[i]+subParticella[tempArray[i]][j]);
    }
    else
      outArray.push(tempArray[i]);
  }
return outArray;
}
//-------------------------------------------------------------------

function alb_trimParticella(arrayOrg) {

// to avoid clutter in dati.particella,
// in the UpdateRecord <input>
// and in the iframe title
// exchange the sub-particelle with the particella,
// if all sub-particelle are present in the original array

      arrayOrg.sort();
                  //alert("arrayOrg  "+arrayOrg+" length "+arrayOrg.length);
      
      var a = [], s=[], p =[], c=[];
      for (var i=0; i<arrayOrg.length; ++i)  {
        var j = arrayOrg[i]; 
        var k = parseInt(j,10);
        if (!isNaN(k) &&     // avoid single characters like "1a,b,c"
            k >=0  &&          // avoid values outside the range
            k <=36) {
          a.push(k+"");    // create a particella array with only the numeric part of the sub-particella as string
                            // original: 1a,1b,1c,2,3,4a result: 1,1,1,2,3,4
          if (j == k+"")
            p.push(j);    // write particelle 1,2 etc. in extra array p
          else
            s.push(j);    // write subparticelle 1a,1b etc. in extra array s
         }
      }
      var a = a.unique();  // eliminate duplicates in the particella array. result: 1,2,3,4
                            //alert("a  "+a);
      
      for (var l=0; l<a.length; l++) {    // loop through all possible particella of part of them
        if (alb_in_array(a[l],p)) {       // if the particella is in array a (which should be the case)
          c.push(a[l]);                   // add it to the result array
        }
        else {                        // if not we need to see whether the subparticells are a "full set"
          var t1=[], t2 =[];                // open a some new arrays
          for (var i=0; i<subParticella[a[l]].length; i++ ) {
            t2.push(a[l]+subParticella[a[l]][i]);  // temporary array contains all possible sub-particelle
          }
          //alert(t2);
          for (var i=0; i<s.length; i++) {  // collect all s-members, which start with number a[l]
            var j = s[i];            
            var k = parseInt(j,10);
            if (a[l] == k+"")
              t1.push(s[i]);
          }
          var t1 = t1.unique();  // eliminate duplicates 
          t1.sort();
          //alert(t1);
          
          if (t1.compare(t2))    // if the two temporary arrays match, 
                                // i.e. all possible sub-particelle are present in the original array
            c.push(a[l]);
          else
            for (i=0; i<t1.length; i++) {
             c.push(t1[i]);        // if not, take the sub-particelle which are present
            }
        }
      }
      

/*
      for (var i=0; i<a.length; ++i)  { // loop through the original particella array
        var incomplete = 0;
        var t1=[], t2=[];             // arrays for temporary values
        var mainPart = a[i];
                                      //alert(arrayOrg+" "+"mainPart "+mainPart);

        if (alb_in_array(mainPart,arrayOrg)) {   // if particella is in array, take it into the new array
                                                 //alert("mainPart in "+mainPart);
          c.push(mainPart);
        }
        else {                                  // here are the sub-particelle
                                                //alert("subParticella[mainPart].length "+ mainPart+" "+subParticella[mainPart].length);

          for (var l=0; l<subParticella[mainPart].length; l++ ) { // subParticella contains a,b,c of every particella
            t2.push(mainPart+subParticella[mainPart][l]);            // temporary array contains all possible sub-particelle
            if (alb_in_array(mainPart+subParticella[mainPart][l],arrayOrg))  // if the integer+subPart character in the original array
              //t1.push(mainPart+subParticella[mainPart][l]);    // temporary array contains only the sub-particelle present in original array
              t1.push(arrayOrg[i]);    // temporary array contains only the sub-particelle present in original array
          } // for
          var t2 = t2.unique();  // eliminate duplicates 

                                 //alert("t1 "+t1+"   t2"+t2);
          if (t1.compare(t2))    // if the two temporary arrays match, i.e. all possible sub-particelle are present in the original array

            c.push(mainPart);
          else
             c.push(t1);        // if not, take the sub-particelle which are present

        } // else
      } // for
*/


  var arrayOrg = c;
  //alert(arrayOrg);

  return arrayOrg;
}



//-------------------------------------------------------------------


// ==== AJaX functions ==========================

// löst das browser problem
/*@cc_on @if (@_win32 && @_jscript_version >= 5) if (!window.XMLHttpRequest)
    function XMLHttpRequest() { return new ActiveXObject('Microsoft.XMLHTTP') }
@end @*/


// ===== AJAX UpdateRecord ===========================================
// called by onlick of Aggiorna button in div UpdateRecord
// calls script UpdateRecord which either updates existing record or adds new record

function alb_startRequestUpdateRecord(edit_add,gruppo_sel_unsel) {

  //alert("alb_startRequestUpdateRecord WebGIS_mode "+WebGIS_mode);
  //alert(thisProgressivo);

  var req = new XMLHttpRequest();
  var url = albFolder+"alb_UpdateRecord.php";
  var requestString = "edit_add="+ edit_add;
  req.onreadystatechange = function() { alb_hndResponseUpdateRecord(req)};
  req.open('POST', url, true);
  req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

  // if non-edit mode (edit_add=="ADD"), all input fields are reset and a new max_progressivo is set
  // if edit mode, all input values need to be retrieved and send to an UPDATE SQL
  if (edit_add=="EDIT") {

    // re-populate the two <select> <option> lists according to the selection and button pressed
    // must run also if neither => nor <= was pressed , i.e. only AGGIORNA RECORD

    //alert(document.forms["alb_frmUpdateRecord"].GRUPPO_SEL.options.length);
      var arrayA      = [];
      var arrayB      = [];
      var arrayShift  = [];
      var countA      = 0;
      var countB      = 0;
      var countShift  = 0;

        if (gruppo_sel_unsel == "=>" ) {  // if options should be shifted from disponibili to associati
            var objA    = document.forms["alb_frmUpdateRecord"].gruppo_sel;
            var objB    = document.forms["alb_frmUpdateRecord"].gruppo_unsel;
        } else {                           // if options should be shifted from associati to disponibili
            var objA    = document.forms["alb_frmUpdateRecord"].gruppo_unsel;
            var objB    = document.forms["alb_frmUpdateRecord"].gruppo_sel;
        }

        for (i=0; i< objA.options.length; i++) {  //
          if (objA.options[i].selected) {        // write selected options in extra array
            //if (objA.options[i].value!="")
              arrayShift[countShift] = objA.options[i].value;
            countShift++;
          } else {                                        // write unselected options in standard array
            //if (objA.options[i].value!="")
              arrayA[countA] = objA.options[i].value;
            countA++;
          }
        }
        for (i=0; i< objB.options.length; i++) {  // the other list is composed of existing options ...
          //if (objB.options[i].value!="")
            arrayB[countB] = objB.options[i].value;
          countB++;
        }
        for (i=0; i<arrayShift.length; i++) {      // ... plus the options which are supposed to be shifted
          //if (objB.options[i].value!="")
            arrayB[countB] = arrayShift[i];
          countB++;
        }


         // write resulting array to gruppo
         var gruppo = '';
         if (gruppo_sel_unsel == "=>" ) {  // if options should be shifted from disponibili to associati
            arrayB.sort(alb_sortNumber); // needs the alb_sortNumber function because otherwise result is like 1,10,2,3
            for (i=0; i<arrayB.length; i++) {
              if (i==0)   gruppo =             arrayB[i];
              else        gruppo = gruppo+','+ arrayB[i];
            }
         } else {     // this includes also that neither => nor <= was pressed
            arrayA.sort(alb_sortNumber); // needs the alb_sortNumber function because otherwise result is like 1,10,2,3
            for (i=0; i<arrayA.length; i++) {
              if (i==0)   gruppo =             arrayA[i];
              else        gruppo = gruppo+','+ arrayA[i];
            }
         }
        requestString =  requestString +'&gruppo='+gruppo;  //

    // whitelist of readonly fields
     var readonly_fields        = ['progressivo','faldone','posizione','documento'];
    for (var i = 0; i < readonly_fields.length; ++i) {
      if (document.forms["alb_frmUpdateRecord"].elements[readonly_fields[i]].value.length > 0)
      {
          requestString =  requestString +'&'+readonly_fields[i]+'='+document.forms["alb_frmUpdateRecord"].elements[readonly_fields[i]].value;
     }
    }
    // alert("line857 "+requestString);

    // reset the integer version of particella (used for the pull down menu selection)
    var strPart_int = ""; // will be re-populated if particella string length >0

    // ***** CDR here we should also reset the gid_array and extent +++++++

    // eliminate duplicates in particella
    var input_string = document.forms["alb_frmUpdateRecord"].elements['particella'].value;
    //alert("vor "+input_string);
    input_string = alb_removeWhitespace(input_string);    // eliminate all whitespace in string
    //alert("nach "+input_string);

    if (input_string.length>0) {
      var arrayPart = input_string.split(",");    // split members in array
      var arrayPart = arrayPart.unique();         // eliminate duplicates

      // avoid the co-existence of 1 and 1a,1b etc. as this is not logical
      // existence of 1 overrides sub-particelle

      var a = [], c=[];
      for (var i = 0; i < arrayPart.length; ++i)  {
        var j = arrayPart[i];
        var k = parseInt(j,10);
        if (!isNaN(k) &&     // avoid single characters like "1a,b,c"
            k >=0  &&          // avoid values outside the range
            k <=36) {
          if (k != j) { // e.g.1a,10b,etc.
            if( arrayPart.indexOf( j.substring(0,j.length-1),0 ) < 0 ) // if 1 or 10 does not exists in array
              if (k <= 9) a.push( j.substring(0,2) ); // trim all bejond the first character, avoid "1abc"
              else        a.push( j.substring(0,3) ); // trim all bejond the first character, avoid "1abc"
          } else { a.push( j ); } // take the 1,10,32 into the the new array
          c.push( k ); // array c takes integer value of all valid array elements, necessary to fill field part_int
        }
      } // for

      var c = c.unique();   // eliminate duplicates


      // re-populate the integer version of the subparticelle list is necessary
      // to have the records selected by the pull-down list of the form
      // write array to part_int string
      for (var i = 0; i < c.length; ++i)  
        strPart_int=strPart_int+","+c[i];
      strPart_int = strPart_int.substring(1,strPart_int.length); // clip the leading ","

      // exchange sub-particelle with particella if all possible sub-particelle are present      
      var arrayPart = alb_trimParticella(a);    

      // in order to sort properly we add a leasing 0, which we clip after sorting
      for (var i = 0; i < arrayPart.length; ++i)
        if (parseInt(arrayPart[i],10)<10) arrayPart[i]="0"+arrayPart[i];

      var arrayPart = arrayPart.sort();
      for (var i = 0; i < arrayPart.length; ++i) {
          //alert("nach sort "+arrayPart+" "+arrayPart[i]);
          if (parseInt(arrayPart[i],10)<10)
            if(parseInt(arrayPart[i],10)==arrayPart[i])
                  arrayPart[i]=arrayPart[i].substring(1,2);
            else  arrayPart[i]=arrayPart[i].substring(1,3);
      }

      var strPart = "";       // write array to particella string
      for (var i = 0; i < arrayPart.length; ++i)
        strPart=strPart+","+arrayPart[i];
      strPart = strPart.substring(1,strPart.length); // clip the leading ","
      document.forms["alb_frmUpdateRecord"].elements['particella'].value = strPart;
    }
    else  // if input_string.length ==0 i.e. input particella is empty. This is important if user deletes particella completely (not realistic but possible)
      document.forms["alb_frmUpdateRecord"].elements['particella'].value = "";
      
      // Ajax call to Update_GID_and_Extents.php to update dati.gid_array and dati.extent_box for strPart,
      // i.e. expand it, and get the gid from the PostGIS table Subparticelle
      // and the extent for the zoom-to-extent
      // as this is only useful for the WebGIS-version of this application
      // we make an exception in running this update not through alb_UpdateRecord.php

      var gid_and_extent_json_data = jQuery.ajax({
            type: "POST",
            data: "progressivo="+document.forms['alb_frmUpdateRecord'].progressivo.value+"&short_subparticella_array="+document.forms["alb_frmUpdateRecord"].elements['particella'].value,
            url:  albFolder+"alb_Update_GID_and_Extents.php",
            async: false
       }).responseText;



    // ====== eliminate duplicates and sort the lotto string
    if (document.forms["alb_frmUpdateRecord"].elements['lotto'].value.length>0) {
      var input_string = document.forms["alb_frmUpdateRecord"].elements['lotto'].value;

      // eliminate whitespace
      input_string = alb_trimString(input_string);

      // split members in array
      var arrayLotto = input_string.split(",");
      // eliminate duplicates
      var arrayLotto = arrayLotto.unique();

     // in order to sort properly we add a leasing 0, which we clip after sorting
      for (var i = 0; i < arrayLotto.length; ++i) {
        if (arrayLotto[i].length==1) arrayLotto[i]="0"+arrayLotto[i];
        }

      var arrayLotto = arrayLotto.sort();

      for (var i = 0; i < arrayLotto.length; ++i)
          if (arrayLotto[i].charAt(0)=="0") arrayLotto[i]=arrayLotto[i].substring(1,arrayLotto[i].length);
        //arrayLotto[i] = parseInt(arrayLotto[i],10);

      var strLotto = "";       // write array to lotto string
      for (var i = 0; i < arrayLotto.length; ++i)
        strLotto=strLotto+","+arrayLotto[i];
      strLotto = strLotto.substring(1,strLotto.length); // clip the leading ","
      document.forms["alb_frmUpdateRecord"].elements['lotto'].value = strLotto;
/*

      var strLotto = "";
      for (var i = 0; i < arrayLotto.length; ++i)
        if (parseInt(arrayLotto[i],10) == arrayLotto[i])
          strLotto = strLotto+","+parseInt(arrayLotto[i],10);
*/
    }

    // whitelist of user input text fields
    var user_input_text        = ['titolo','descrizione','autore','data_estesa','lotto','particella','tipologia','argomento','note','uri','map_uri'];

    for (var i = 0; i < user_input_text.length; ++i) {
      if (document.forms["alb_frmUpdateRecord"].elements[user_input_text[i]].value.length > 0)
      {
          requestString =  requestString +'&'+user_input_text[i]+'='+document.forms["alb_frmUpdateRecord"].elements[user_input_text[i]].value;
     }
    }

    // overwrite the part_int which contains the integer values of the particella, i.e. without the sub-particella
    requestString =  requestString +'&part_int='+strPart_int;

    // whitelist of user input numeric fields
    var user_input_int    = ['anno','n_pagine'];

    requestString =  requestString +'&anno='     + document.forms["alb_frmUpdateRecord"].anno.value;
    requestString =  requestString +'&n_pagine=' + document.forms["alb_frmUpdateRecord"].n_pagine.value;

    // check boxes AR
    for (var i = 0; i < updateAR.length; ++i) {
      if (jQuery('#alb_'+updateAR[i]).hasClass('chbox_checked'))
            requestString =  requestString +'&'+updateAR[i].substring(6,10).toLowerCase()+'=x';
      else  requestString =  requestString +'&'+updateAR[i].substring(6,10).toLowerCase()+'=';
    }
    // check boxes GE
    for (var i = 0; i < updateGE.length; ++i) {
      if (jQuery('#alb_'+updateGE[i]).hasClass('chbox_checked'))
            requestString =  requestString +'&'+updateGE[i].substring(6,10).toLowerCase()+'=x';
      else  requestString =  requestString +'&'+updateGE[i].substring(6,10).toLowerCase()+'=';
    }
    // check boxes SR
    for (var i = 0; i < updateSR.length; ++i) {
      if (jQuery('#alb_'+updateSR[i]).hasClass('chbox_checked'))
            requestString =  requestString +'&'+updateSR[i].substring(6,10).toLowerCase()+'=x';
      else  requestString =  requestString +'&'+updateSR[i].substring(6,10).toLowerCase()+'=';
    }
    // check boxes TD
    for (var i = 0; i < updateTD.length; ++i) {
      if (jQuery('#alb_'+updateTD[i]).hasClass('chbox_checked'))
            requestString =  requestString +'&'+updateTD[i].substring(6,10).toLowerCase()+'=x';
      else  requestString =  requestString +'&'+updateTD[i].substring(6,10).toLowerCase()+'=';
    }
    // check boxes PR
    for (var i = 0; i < updatePR.length; ++i) {
      if (jQuery('#alb_'+updatePR[i]).hasClass('chbox_checked'))
            requestString =  requestString +'&'+updatePR[i].substring(6,10).toLowerCase()+'=x';
      else  requestString =  requestString +'&'+updatePR[i].substring(6,10).toLowerCase()+'=';
    }
    // check boxes "updateAMMINISTRATIVI","updateELIMINATO","updateNON_PUBBLICO"
    for (var i = 0; i < updateCheckboxSpecial.length; ++i) {
      if (jQuery('#alb_'+updateCheckboxSpecial[i]).hasClass('chbox_checked'))
            requestString =  requestString +'&'+updateCheckboxSpecial[i].substring(6,updateCheckboxSpecial[i].length).toLowerCase()+'=x';
      else  requestString =  requestString +'&'+updateCheckboxSpecial[i].substring(6,updateCheckboxSpecial[i].length).toLowerCase()+'=';
    }
  }
  //alert(requestString);
  req.send(requestString);
}
  function alb_hndResponseUpdateRecord(req) { // as soon as request is executed, result HTML is written to <div>
  if (req.readyState == 4) {
    if (req.status == 200) {
      var json_data = req.responseText;
      document.getElementById("alb_Container_UpdateRecord").innerHTML = json_data;
      //showVisibility("alb_Container_UpdateRecord");

      json_data='';  // clean up
      }
    }
  }


// ===== AJAX GenerateResultList ===========================================
// called by each change in the FormCompileSQL as a short version (only number of records found)
// called in full version (all data necessary to compile result list) by onlick of button "List xxx records" in FormCompileSQL
// calls CompileSQLquery and receives the result from SQL query

function alb_startRequest(request_full_data) {
  var req = new XMLHttpRequest();
  //XMLHttpRequest.overrideMimeType('text/xml;charset=ISO-8859-1');
  var url = albFolder+"alb_CompileSQLquery.php";
  var requestString = "";
  req.onreadystatechange = function() { alb_hndResponse(req)};
  req.open('POST', url, true);
  req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

  // set the POST variables (use the input names as usual for form submit)

    // decide whether only number of records are sent or all data for result list
    if (request_full_data == 1) {
      requestString = requestString + "req_full_data=x";
    }
    //alert("req_full_data "+req_full_data);

       //alert(PrivUpdateRecords);
       //alert(PrivUploadFiles);

     // CompileQuery needs to know about privileges and include() gives problems
      requestString = requestString + "&PrivDispAMMINISTRATIVI="+PrivDispAMMINISTRATIVI;
      requestString = requestString + "&PrivDispELIMINATO="+PrivDispELIMINATO;
      requestString = requestString + "&PrivDispNON_PUBBLICO="+PrivDispNON_PUBBLICO;
      requestString = requestString + "&PrivUpdateRecords="+PrivUpdateRecords;
      requestString = requestString + "&PrivUploadFiles="+PrivUploadFiles;

    // easy are text and non-multiselect select inputs
    requestString = requestString +"&search_str=" + document.forms['alb_frmCompileQuery'].search_str.value;
    requestString = requestString +"&anno_da="    + document.getElementById('alb_lab_anno_da').firstChild.nodeValue;
    requestString = requestString +"&anno_a="     + document.getElementById('alb_lab_anno_a').firstChild.nodeValue;
    //alert(requestString);

    // to avoid that particella will be included into the query if not enabled
    if (document.forms["alb_frmCompileQuery"].alb_selectPart.className == 'alb enabled') {
      // particella multi selection
      // start counting at 1 as 0=ParcoNord, i.e. part='';
      var part_str = "";
      var part = [];

      for (var i=1; i<document.forms["alb_frmCompileQuery"].part.length; i++){
          if(document.forms["alb_frmCompileQuery"].part[i].selected)  part.push(i-1); // there is a Particella 0, therefore i-1
      }
          //part_str = part_str.substring(1,part_str.length); // get rid of leading comma
          //alert("part_str "+part_str);
          requestString = requestString +"&part="+part;
    }

    // to avoid that lotto will be included into the query if not enabled
    if (document.forms["alb_frmCompileQuery"].alb_selectLotto.className == 'alb enabled') {
      // lotto multi selection
      // start counting at 1 as 0=ParcoNord, i.e. lotto='';
      var lotto_str = "";
      for (var i=1; i<document.forms["alb_frmCompileQuery"].lotto.length; i++){
          if(document.forms["alb_frmCompileQuery"].lotto[i].selected)  lotto_str = lotto_str+','+i;
      }
          lotto_str = lotto_str.substring(1,lotto_str.length); // get rid of leading comma
          //alert("lotto_str "+lotto_str);
          requestString = requestString +"&lotto="+ lotto_str;
    }

    // selection (non-multiy select!! hence only a number, not an array) gruppo
    for (var i=0; i<document.forms["alb_frmCompileQuery"].gruppo.length; i++){
        if(document.forms["alb_frmCompileQuery"].gruppo[i].selected)
          requestString = requestString +"&gruppo="+ document.forms["alb_frmCompileQuery"].gruppo[i].value;
    }

    // radio button and_or
    for (count_radio=0; count_radio<document.forms["alb_frmCompileQuery"].and_or.length; count_radio++){
        if(document.forms["alb_frmCompileQuery"].and_or[count_radio].checked)
          requestString = requestString +"&and_or="+ document.forms["alb_frmCompileQuery"].and_or[count_radio].value;
    }

    // check boxes AR
    for (var i = 1; i < selectAR.length; ++i) {
      if (jQuery('#alb_'+selectAR[i]).hasClass('chbox_checked')) {
         requestString =  requestString +'&'+ selectAR[i].substring(6,10).toLowerCase()+'=x';  // extract field name from variable
      }
    }
    // check boxes GE
    for (var i = 1; i < selectGE.length; ++i) {
      if (jQuery('#alb_'+selectGE[i]).hasClass('chbox_checked')) {
         requestString =  requestString +'&'+ selectGE[i].substring(6,10).toLowerCase()+'=x';
      }
    }
    // check boxes SR
    for (var i = 1; i < selectSR.length; ++i) {
      if (jQuery('#alb_'+selectSR[i]).hasClass('chbox_checked')) {
         requestString =  requestString +'&'+ selectSR[i].substring(6,10).toLowerCase()+'=x';
      }
    }
    // check boxes TD
    for (var i = 1; i < selectTD.length; ++i) {
      if (jQuery('#alb_'+selectTD[i]).hasClass('chbox_checked')) {
         requestString =  requestString +'&'+ selectTD[i].substring(6,10).toLowerCase()+'=x';
      }
    }
    // check boxes PR
    for (var i = 1; i < selectPR.length; ++i) {
      if (jQuery('#alb_'+selectPR[i]).hasClass('chbox_checked')) {
         requestString =  requestString +'&'+ selectPR[i].substring(6,10).toLowerCase()+'=x';
      }
    }
    // check boxes "amministrativi","eliminato","non_pubblico", and temporarily "man_ordinaria" and "anno_0"
    for (var i = 0; i < selCheckboxSpecial.length; ++i) {
      if (jQuery('#alb_'+selCheckboxSpecial[i]).hasClass('chbox_checked')) {
         requestString =  requestString +'&'+ selCheckboxSpecial[i]+'=x'; // no extract as element name=field name
      }
    }

    //alert(requestString);

  req.send(requestString);
}

function alb_hndResponse(req) {
  if (req.readyState == 4) {
    if (req.status == 200) {
      var json_data = req.responseText;


     // alert (json_data);
      // json_data contains the data which were sent off in CompileQuery.php
      // through   echo json_encode($arrReturn)."\n";
      // $arrReturn is a array which contains 3 arrays:
      // ALB_ResultList: info to compile result list here
      // PartNumList: all sub-particelle of the result list with number of docs attached
      // GeorefPointList: all georeferenced points indicating its progressivo, name, x and y


      /*
      example {"ALB_ResultList":[["1992","36","01","00","1 bis rilievi fotografici","0000","","","",""],
                             ["2082","38","07","00","119-progetto segnaletica consortile ","1999","","","",""],
                             ["1788","34","08","12","Cameraria-cameraria presentazione","2000","","","",""]],

       example "PartNumList":[["Pa01a","11","1516446.13","5043559.00"],
                              ["Pa01b","11","1516555.75","5043592.50"],
                              ["Pa01c","11","1516461.63","5043338.50"],
                              ["Pa01d","11","1516577.50","5043377.50"]],
      example  "GeorefPointList":[["165","Pt01 ","1512000.00","5038001.00"],
                                  ["165","Pt02 ","1512000.00","5038001.00"],
                                  ["165","Pt03 ","1512000.00","5038001.00"]]}
      */

      var output = "";
      eval("var the_result = (" + json_data + ")");
      if ((the_result.length == 1) && (!isNaN(the_result[0])))   {  // if any field in form has been changed only the number of records is returned
        output='lista '+ the_result[0] +' record';
        document.getElementById('alb_btnRunMainQuery').innerHTML = output;

      } else {  // here comes the JSON for the WebGIS result list



       /* === this is only temporary as long as we need to show the result list
              in the final version the result list will be generated by WebGIS
              from the json_data string compiled in this function

              Originally the close button image and table definition and closure was in a separate file
              alb_Container_ResultList but as MSIE cannot use innerHTML for <tbody>, it needs to be included here
       */


       if (the_result.ALB_ResultList) {

         // display the embedded SVG pinMap
         if (noSVG!=1) jQuery('#alb_Container_SVG').html(embedSVG);


         var resultListTab = ""+
         "<div class='ResultListBody'>"+
          "<img class='alb close_button ALB_ResultList' "+
          "  onclick='jQuery(this).parents(\"div\").empty();' "+
          "  src='"+albFolder+"img/Semitransp_black10_10_10.png' alt='chiudi' title='chiudi ResultList' />"+
          "<table class='alb resultList' frame='void' rules='rows' width='99%'>"+
          "<colgroup>"+
            "<col width='1%'>"+
            "<col width='1%'>"+
            "<col width='1%'>"+
            "<col width='3%'>"+
            "<col width='3%'>"+
            "<col width='90%'>"+
          "</colgroup>";


         for (i=0; i < the_result.ALB_ResultList.length; i++) {
            // as set in DefineArrays.php the sequence in the_result is
            // 0:progressivo  1:faldone 2:posizione 3:documento 4:titolo  5:anno  6:lotto 7:particella  8:eliminato 9:map_uri 10:uri
            progressivo = the_result.ALB_ResultList[i][0];
            faldone     = the_result.ALB_ResultList[i][1];
            posizione   = the_result.ALB_ResultList[i][2];
            documento   = the_result.ALB_ResultList[i][3];
            titolo      = the_result.ALB_ResultList[i][4];
            anno        = the_result.ALB_ResultList[i][5];
            lotto       = the_result.ALB_ResultList[i][6];
            particella  = the_result.ALB_ResultList[i][7];
            eliminato   = the_result.ALB_ResultList[i][8];
            map_uri     = the_result.ALB_ResultList[i][9];
            uri         = the_result.ALB_ResultList[i][10];
            minx        = the_result.ALB_ResultList[i][11];
            miny        = the_result.ALB_ResultList[i][12];
            maxx        = the_result.ALB_ResultList[i][13];
            maxy        = the_result.ALB_ResultList[i][14];

            if (faldone == "") {    // if the database record was added through this application, i.e. new files with no FALDONE
              codice = progressivo; //  progressivo is used as filename for the pdf-document
            }
            else {

              // sometimes leading 0 were omitted during data entry
              faldone   = parseInt(faldone);
              posizione = parseInt(posizione);
              documento = parseInt(documento);
              if      ( faldone < 10)     { faldone   = "0"  + faldone; }

              if      ( posizione < 10)   { posizione = "0"  + posizione; }

              if      ( documento < 10)   { documento = "00" + documento; }
              else if ( documento < 100)  { documento = "0"  + documento; }

              codice = faldone + '_' + posizione + '_' + documento;
            }



          // ------ resultListTab ------------

          // check the content of a new field URI and extract the last 4 letters

          //uri must be full path name like C:/www/ParcoNord/archivio_pdf/02_04_06.pdf";
         // uri = "file:///"+uri;


            if ((typeof(uri) != "undefined") || PrivUploadFiles == 1) {  // to avoid list entries for missing files without privilege to upload files
                resultListTab = resultListTab +"<tr>";

                // add the recordset update icon
              if (PrivUpdateRecords == 1) {
                resultListTab = resultListTab +
                  "<td> "+
                    "<img class='alb button update' "+
                        "src='"+albFolder+"img/img_update_alpha.png' "+
                        "alt='link aggiorna record' "+
                        "title='aggiorna' "+
                        "onclick='jQuery(\"#alb_Container_SVG\").empty(); "+
                                 "jQuery(\"#alb_Container_UpdateRecord\").load(\""+albFolder+"alb_UpdateRecord.php\","+
                                   "{ progressivo:\""+progressivo+"\"});' />"+
                  "</td>";
              }
              else {
                resultListTab = resultListTab +
                  "<td> "+
                    "<img class='alb missing' "+
                          "src='"+albFolder+"img/img_empty_dummy_alpha.png' "+
                          "alt='dummy' />"+
                  "</td>";
              }

              // add the icon to add/edit georef points
              if (PrivUpdateRecords == 1) {
                resultListTab = resultListTab +
                  "<td>"+
                    "<img class='alb button update' "+
                          "src='"+albFolder+"img/icon_marker.png' "+
                          "title='aggiungi o modifica punto georeferenziato' "+
                          "alt='add point' "+
                          "onclick='alb_webgis_addeditpoint("+progressivo+");' />"+
                  "</td>";
              }
              else {
                resultListTab = resultListTab +
                  "<td> "+
                    "<img class='alb missing' "+
                          "src='"+albFolder+"img/img_empty_dummy_alpha.png' "+
                          "alt='dummy' /> "+
                  "</td>";
              }

              // add the icon for maps if map_uri has content
              if (map_uri.length >4 ) {

                resultListTab = resultListTab +
                  "<td> "+
                    "<a class='alb' href="+albFolder+map_uri+" >"+
                      "<img class='alb button geodata' "+
                          "src='"+albFolder+"img/img_googleearth.png' "+
                          "alt='apri geodata in WebGIS o GoogleEarth' "+
                          "title='visualizza mappa in WebGIS o GoogleEarth' />"+
                    "</a>"+
                  "</td>";
              }
              else {

                resultListTab = resultListTab +
                  "<td> "+
                      "<img class='alb button geodata' "+
                        "src='"+albFolder+"img/img_googleearth_grey.png' "+
                        "alt='carica map file' "+
                        "onclick='alb_webgis_uploadmap("+progressivo+");' /> "+
                  "</td>";
              }

            if (noSVG!=1) {
                var onmouseoverEvt = " onmouseover='alb_changePathFill(\"alb_particella_svg\",\""+particella +"\",\"fill:rgb(255,0,0)\")";
                if (the_result.GeorefPointList)
                  onmouseoverEvt = onmouseoverEvt+
                   ";alb_addSvgUseTagByArray(\"alb_particella_svg\",\"L0\",\"#alb_round_point_yellow_on_green\",\""+progressivo +"\",\""+the_result.GeorefPointList+"\");' ";
                else
                  onmouseoverEvt = onmouseoverEvt+";'";

                onmouseoverEvt = onmouseoverEvt+
                                     " onmouseout ='alb_changePathFill(\"alb_particella_svg\",\""+particella +"\",\"fill:rgb(68,255,0)\")";

                if (the_result.GeorefPointList)
                  onmouseoverEvt = onmouseoverEvt+
                   ";alb_removeSvgUseTags(\"alb_particella_svg\");'";
                else
                  onmouseoverEvt = onmouseoverEvt+";'";
              }
              else onmouseoverEvt = "";

              if (uri.length < 4) {    // if no uri
                  if (eliminato == 'x')
                      resultListTab = resultListTab +
                        "<td class='alb titolo_eliminato' >"+progressivo +"</td>"+
                        "<td class='alb titolo_eliminato' "+onmouseoverEvt+" >"+anno+"</td>"+
                        "<td class='alb titolo_eliminato' ";
                  else
                      resultListTab = resultListTab +
                        "<td class='alb titolo_no_uri' >"+progressivo +"</td>"+
                        "<td class='alb titolo_no_uri' "+onmouseoverEvt+" >"+anno+"</td>"+
                        "<td class='alb titolo_no_uri' ";
                  if (PrivUploadFiles == 1) {
                      resultListTab = resultListTab +
                        "onclick='alb_webgis_uploaddoc(\""+codice+"\");' "+
                        "title='file per "+codice+" non esistente. Clicca qui per file upload!'>";
                  }
                  resultListTab = resultListTab + titolo +
                  "</td>";
            }
            else  {
                  if (eliminato == 'x')
                      resultListTab = resultListTab +
                        "<td class='alb titolo_eliminato' >"+progressivo +"</td>"+
                        "<td class='alb titolo_eliminato' "+onmouseoverEvt+" >"+anno+"</td>"+
                        "<td class='alb titolo_eliminato' ";
                  else
                      resultListTab = resultListTab +
                        "<td class='alb titolo_uri' >"+progressivo +"</td>"+
                        "<td class='alb titolo_uri' "+onmouseoverEvt+" >"+anno+"</td>"+
                        "<td class='alb titolo_uri' ";
                  resultListTab = resultListTab +
                    "onclick=\"jQuery('#alb_Container_SVG').empty(); "+
                    "jQuery('#alb_Container_Documents').load('"+albFolder+"alb_Iframe.php',{ titolo:'"+titolo+"', anno:'"+anno+"', particella:'"+particella+"', filename:'"+albFolder+uri+"' });\" " +
                      " title='visualiza " + localPath+uri + "'>"+titolo+
                    "</td>";
            }

              resultListTab = resultListTab + "</tr>";
              //alert(resultListTab);
            }
         } // end for loop
       } // if ALB_ResultList

      else { // WebGIS_mode ==1, i.e. no ALB_ResultList

        writeQResult(the_result.queryResult, "frame"); // communicates the ResultList string to WebGIS
        //ABP: show info window
        if(Layout.InfoZoneStyle == 4){
            $('#infoZone').fadeIn("slow");
            $('#infoZone').fadeTo("fast", 0.9);
            $('div.LAYERHEADER').prepend('<a href="javascript:void(0);" onclick="$(\'#infoZone\').fadeOut();return false;"><img src="images/close.gif" border=0 ></a>&nbsp;');
        }
      }

 // ------ end resultListTab ------------
/*

//********************************************
das svg kann hier noch nicht angesprochen werden.
vielleicht muss der Ablauf warten,
bis es geladen ist

              alert(parent.document.embeds["alb_particella_svg"].getSVGDocument());
               for (i=0; i < the_result.PartNumList.length; i++) {
                  // as written by CompileSQLquery the sequence in the_result.PartNumList is
                  // 0:REF_P_SUB_A  1:NUMREC 2:X 3:Y
                  REF_P_SUB_A = the_result.PartNumList[i][0];
                  NUMREC      = the_result.PartNumList[i][1];
                  X           = the_result.PartNumList[i][2];
                  Y           = the_result.PartNumList[i][3];

                  // test phase
                  REF_P_SUB_A = "P01A"; NUMREC = 17;

                  if (NUMREC >= 17) {
                    var paths_many   = parent.document.embeds["alb_particella_svg"].getSVGDocument().getElementsByName(REF_P_SUB_A);
                    for (j=0; j< paths_many.length; j++) paths_many(j).setAttribute("class","col_red");
                  }
                  else if (NUMREC >= 5) {
                    var paths_medium = parent.document.embeds["alb_particella_svg"].getSVGDocument().getElementsByName(REF_P_SUB_A);
                    for (j=0; j< paths_medium.length; j++) paths_medium(j).setAttribute("class","col_yellow");
                  }
                  else {
                    var paths_few    = parent.document.embeds["alb_particella_svg"].getSVGDocument().getElementsByName(REF_P_SUB_A);
                    for (j=0; j< paths_few.length; j++) paths_few(j).setAttribute("class","col_green");
                  }
                }

// ========  PinMap raster solution ( only good before sub-particella were introduced) ==========

            // NUMREC of the REF_P_SUB_A determins the size of pin-icons at the coordinates
            // a label shows the NUMREC

                "<img id='alb_Part_backgr' "+
                        "src='imgPart/Particella_all.png' "+
                "style='position:absolute;width:494px; height:550px; left:125px; top:8px;z-index:9;' />";


              pinMapTab = pinMapTab +
              "<img id='alb_Part_backgr' "+
                "src='imgPart/Particella_all.png' "+
                "style='position:absolute;width:494px; height:550px; left:125px; top:8px;z-index:9;' />";
              pinMapTab = pinMapTab +
              "<img id='alb_Part_geoExtent' "+
                "src='imgPart/Semitransp_orange50_10_10.png' "+
                "style='position:absolute;width:0px; height:0px; left:0px; top:0px;z-index:10;border:1px solid;border-color:#000000;' />";


           for (i=0; i < the_result.PartNumList.length; i++) {
              // as written by CompileSQLquery the sequence in the_result.PartNumList is
              // 0:REF_P_SUB_A  1:NUMREC 2:X 3:Y
              REF_P_SUB_A = the_result.PartNumList[i][0];
              NUMREC      = the_result.PartNumList[i][1];
              X           = the_result.PartNumList[i][2];
              Y           = the_result.PartNumList[i][3];


              // pin size depends on NUMREC
              var imgWidth = 15 + (2* NUMREC);
              if (NUMREC >= 17) var imgWidth = 15 + (2* 17);

              var width_ratio = imgWidth / pin_width;


              X = Math.round((X - x_offset)* xy_scale-(pin_focal_x*width_ratio));
              Y = Math.round((y_offset - Y)* xy_scale-(pin_focal_y*width_ratio)); // count from top
              var labelY = Y+2;
              var labelX = X-5; // label left of pin


              pinMapTab = pinMapTab +
              "<img id='"+REF_P_SUB_A+"' "+
                "title='"+REF_P_SUB_A+"' "+
                "src='"+albFolder+"img/icon_marker50.png' "+
                "style='position:absolute;top:"+Y+"px;left:"+X+"px; width:"+imgWidth+"px;z-index:10;' />"+
              "<span style='align:right;color:white;position:absolute;top:"+labelY+"px;left:"+labelX+"px;"+
                           "height:14px;background-image:url("+albFolder+"img/Semitransp_black50_10_10.png);z-index:10;'>"+
              +NUMREC+"</span>";
           } // end of loop to write  PinMap div

// ==========  end PinMap raster solution ======================


 }   // if PartNumList exists
 */



      eval("var the_result = (" + json_data + ")");

          // ------ resultListTab closing sequence------------
          // close table
          resultListTab = resultListTab + "</table></div>";
          // show resultListTab
          document.getElementById('alb_Container_ResultList').innerHTML = resultListTab;

          //showVisibility('alb_Container_ResultList');
          // ------ end resultListTab ------------

     }  // else

      // reset variables for next request
      json_data='';
      output='';
      the_result='';


      return;
    }
    else {
      alert('There was a problem with the URL.');
    }
  }
}

// end ==== AJaX functions ==========================
/*
  function submitForm() {


    //alert(document.getElementById('SEARCH_STR').value);
    //document.getElementById(thisFormID).submit();

        // the trick to execute a php as a scr of an hidden image
        //ACHTUNG die php Datei muss in root liegen !!!
      document.load_php.src ='schrei.php';

    } // function submitForm()

*/

// ======= AJAX for file name array compilation ================================

  function alb_startRequestMakeExistingFilesArray() {
   var req = new XMLHttpRequest();
   var url = albFolder+"alb_MakeExistingFileArray.php";
   var requestString = "localPath="+localPath;
   req.onreadystatechange = function() {

      hndResponseMakeExistingFilesArray(req)
    };
   req.open('POST', url, true);
   req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
   req.send(requestString);
  }

  function hndResponseMakeExistingFilesArray(req) {
  if (req.readyState == 4) {
    if (req.status == 200) {

      var json_data = req.responseText;
      var output = "";
      eval("var the_result = (" + json_data + ")");
      output= the_result[0].length +' PDF '
            + the_result[1].length +' DOC '
            +' array XLS '+ the_result[2].length +' files'
            +'\n array JPG '+ the_result[3].length +' files';
      document.getElementById('alb_resultMakeExistingFiles').innerHTML = output;

      json_data = "";
      the_result = "";
      output = "";
      }
    }
  }

// ====== the dragable year bar ===================================================

// === function for year selection bar ==============
//  unfortunately it is not possible to load the CSS style.right
//  at the beginning of the function through document.getElementById()
//  therefore we need the variables plus the hidden <b> tags with the correct initialisation values

var dragobject={
  z: 0, x: 0, y: 0,
  offsetx : null,
  offsety : null,
  targetobj : null,
  dragapproved : 0,
  initialize:function() {
    document.onmousedown = this.drag;
    document.onmouseup   = function()  { this.dragapproved=0; } //alb_startRequest();
  },
  drag:function(e){
    var evtobj=window.event? window.event : e;
    this.targetobj=window.event? event.srcElement : e.target;
    if ((this.targetobj.className=="drag_min") || (this.targetobj.className=="drag_max")) {
      this.dragapproved=1;

      if (this.targetobj.className=="drag_min") { var start_pos = arrow_min_start; }
      else                                      { var start_pos = arrow_max_start; }

      if (isNaN(parseInt(this.targetobj.style.right,10)))  { this.targetobj.style.right = start_pos; }

      this.offsetx=parseInt(this.targetobj.style.right,10);
      this.x=evtobj.clientX;
      if (evtobj.preventDefault) { evtobj.preventDefault(); }
      document.onmousemove=dragobject.moveit;
    }
  },
  moveit:function(e){
    var evtobj=window.event? window.event : e;
    if (this.dragapproved==1) {

      var new_right = this.offsetx - evtobj.clientX + this.x;

      if (this.targetobj.className=="drag_min") {
        max_right = parseInt(document.getElementById('alb_lab_max').firstChild.nodeValue,10);

        if (new_right  < arrow_min_start)            { new_right = arrow_min_start; }
        else if (new_right>max_right-img_half_width) { new_right = max_right;       }

        this.targetobj.style.right = new_right+"px";
        document.getElementById('alb_lab_min').firstChild.nodeValue = new_right;
        min_right = new_right;
      }
      if (this.targetobj.className=="drag_max") {
        min_right = parseInt(document.getElementById('alb_lab_min').firstChild.nodeValue,10);

        if (new_right  > arrow_max_start) { new_right= arrow_max_start; }
        else if (new_right  < min_right)  { new_right= min_right;       }

        this.targetobj.style.right = new_right+"px";
        document.getElementById('alb_lab_max').firstChild.nodeValue = new_right;
        max_right = new_right;
      }

      distance_right = min_right + img_half_width;
      distance_width = max_right - min_right;

      document.getElementById('alb_distance').style.right = distance_right+"px";
      document.getElementById('alb_distance').style.width = distance_width+"px";


      var anno_a  = document.getElementById('alb_lab_anno_a_org' ).firstChild.nodeValue;
      var anno_da = document.getElementById('alb_lab_anno_da_org').firstChild.nodeValue;

      var year_per_unit = (anno_a - anno_da)/distance;
      var dist_zu_start =  distance_right - distance_start;
      var dist_zu_end   =  dist_zu_start  + distance_width;
      var year_min = dist_zu_start * year_per_unit;
      var year_max = dist_zu_end   * year_per_unit;

      document.getElementById('alb_lab_anno_a' ).firstChild.nodeValue = anno_a - Math.round(year_min);
      document.getElementById('alb_lab_anno_da').firstChild.nodeValue = anno_a - Math.round(year_max);
      document.getElementById('alb_lab_anno_a' ).style.right = min_right-30 +"px";
      document.getElementById('alb_lab_anno_da').style.right = max_right+10 +"px";

      return false;
    }
  }
};

var img_half_width  = 6;   // must be same value as CSS .drag_max {width}
var arrow_min_start = 50;  // must be same value as CSS .drag_min {right}
var arrow_max_start = 300; // must be same value as CSS .drag_max {right}
var distance_start  = 56;  // must be same value as CSS .distance {right} = arrow_min_start + img_half_width
var distance = 250;      // must be same value as CSS .distance {width} = arrow_max_start - arrow_min_start
//var anno_da = 1945;     // this will be read from SQL query ANNO_DA value
//var anno_a  = 2007;     // this will be read from SQL query ANNO_A value


dragobject.initialize();


// == WebGIS_ResultList commands ====================================================

/**
* ABP: called from custom.js openHyperlink()
* @param fldName field name
* @param fldValue field value
* @param action to perform
* @param param2 additional custom parameter
* @param Itemid record id (primary key)
*/
function alb_webgis_handle_request(fldName, fldValue, action, param2, Itemid){
    if(action == 'showdoc') {
        alb_webgis_showdoc(fldValue);
    } else if (action == 'showdoc') {
        alb_webgis_update(Itemid);
    } else if (action == 'uploaddoc') {
        alb_webgis_uploaddoc(fldValue);
    } else if (action == 'uploadmap') {
        alb_webgis_uploadmap(fldValue);
    } else if (action == 'addeditpoint') {
        alb_webgis_addeditpoint(fldValue);
    } else {
        alert('Error - No such action in alb_webgis_handle_request: ' + action);
    }
}

function alb_webgis_showdoc(uri) {
  jQuery('#alb_Container_Documents').load(albFolder+'alb_Iframe.php',{ filename:'"+localPath+uri+"', application:'"+application+"' });
}

function alb_webgis_update(progressivo) {
  jQuery('#alb_Container_UpdateRecord').load(albFolder+'alb_UpdateRecord.php',{ progressivo:"'+progressivo+'"});
}

function alb_webgis_uploaddoc(_thisCodice) {
  var _thisUri = albFolder+"alb_UploadFile.php?mode=doc&layer_type_map=0&codice="+_thisCodice;
  var _thisWindow = window.open(_thisUri, "UploadFile", "width=550,height=200,left=300,top=200");
  _thisWindow.focus();
}

function alb_webgis_uploadmap(_thisProgressivo) {
  var _thisUri = albFolder+"alb_UploadFile.php?mode=map&layer_type_map=0&codice="+_thisProgressivo;
  var _thisWindow = window.open(_thisUri, "UploadFile", "width=550,height=200,left=300,top=200");
  _thisWindow.focus();
}

function alb_webgis_addeditpoint(_thisProgressivo) {
  jQuery('#alb_Container_FormAddGeorefPoint')
         .load(albFolder+'alb_AddGeorefPoint_WebGIS.php',
         { progressivo:_thisProgressivo});
}

// == Call back for alb_AddGeorefPoint_WebGIS.php ===============================================

function getCoordinatesForGeorefPointInput(imgxy){

   var coordsList = imgxy.split('+');
   var mpoint = getGeoCoords(coordsList[0], coordsList[1], false);

   // Round values (function 'roundN()' in 'measure.js')
   var rfactor = 4;
   var px = isNaN(mpoint.x) ? '' : roundN(mpoint.x, rfactor);
   var py = isNaN(mpoint.y) ? '' : roundN(mpoint.y, rfactor);

   // Send the values into the input fields of form id=#alb_frmAddGeorefPoint_WebGIS
   jQuery("#alb_input_georefpoint_x").attr("value",px );
   jQuery("#alb_input_georefpoint_y").attr("value",py );
}

//-------------------------------------------------------------------

function getCoordinatesForGeorefPointInput_old(e) {

var IE = document.all?true:false;

var tempX = 0;
var tempY = 0;

var ulX_s = 150;
var lrX_s = 920;
var ulY_s = 50;
var lrY_s = 500;
var ulX_m = 1512000;
var lrX_m = 1518000;
var ulY_m = 5045000;
var lrY_m = 5038000;
  if (IE) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX + document.body.scrollLeft;
    tempY = event.clientY + document.body.scrollTop;
  }
  else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX;
    tempY = e.pageY;
  }
  if (tempX < 0){tempX = 0;}
  if (tempY < 0){tempY = 0;}

  if (tempX > ulX_s && tempX < lrX_s && tempY > ulY_s && tempY < lrY_s ) {
    var tempX = ulX_m + (tempX-ulX_s)*(lrX_m-ulX_m)/(lrX_s - ulX_s);
    var tempY = ulY_m + (ulY_s-tempY)*(ulY_m-lrY_m)/(lrY_s - ulY_s);

    jQuery("#alb_input_georefpoint_x").attr("value",tempX);
    jQuery("#alb_input_georefpoint_y").attr("value",tempY);
  }
return true;
}
// == End ===============================================

