//////////////////////////////////////////
// scripts.js
/////////////////////////////////////////

// map parameters
var nW0, nH0, nX0, nY0;
var nX, nY, nH, nW, sH, sW;
var nome_variavel = 'POPULATION';
var label = "";
var style;
var offset = 0.015;
var svgobj_muni;
var svgdoc_muni;
var txtmuni;

var road_width, label_size;

var nome_var_selec;

///////////////////////////Variaveis para o Label ///////////////////

var svgMMdoc;           // Variable as a reference to the svg document in <div ... name="mainMap".. (GN_DPFi... .svg)
var svgMMrootElem;
var gnStyle;

//Test for an info Label, that follows the mouse
var accessInfoLabel;
var svgLabelRoot;
var svgInfoLabel;
var svgInfoLabelText;
var gnIsActive = true;

//////////////////////////FIM   Variaveis para o Label //////////////

function getViewBox() {
      var doc = getSVGDoc();
      var element;

      var vBox = "0 " + doc.getDocumentElement().getAttribute("viewBox") + " 0";
      var vBoxArray = eval("new Array(" + vBox.replace(/(\s|,)+/g, ",") + ");");
      nX0 = vBoxArray[1];
      nY0 = vBoxArray[2];
      nW0 = vBoxArray[3];
      nH0 = vBoxArray[4];


      var reg_adm = doc.getElementById("reg_adm").getStyle();
      road_width = parseInt(reg_adm.getPropertyValue("stroke-width"));

      var labelStyle = doc.getElementById("labels").getStyle();
      label_size = parseInt(labelStyle.getPropertyValue("font-size"));
}

function getMapInfo() {
      var svgElement = svgFile1.getSVGDocument().getDocumentElement();
      var vBox = "0 " + svgElement.getAttribute("viewBox") + " 0";
      var vBoxArray = eval("new Array(" + vBox.replace(/(\s|,)+/g, ",") + ");");
      nX = vBoxArray[1];
      nY = vBoxArray[2];
      nH = vBoxArray[3];
      nW = vBoxArray[4];
      sH = parseFloat(svgElement.getAttribute("width"));
      sW = parseFloat(svgElement.getAttribute("height"));
}

function frmt(expr, decplaces) {
      var str = expr.toString();
      var i = str.indexOf('.');
      return (i<0) ? expr : str.substring(0, Number(i) + Number(decplaces) + 1);
}


var dragTarget;
var dtX, dtY;

function on_drag_begin(event) {
      if (!event.getAltKey()) return;
      dtX = event.getScreenX();
      dtY = event.getScreenY();
      dragTarget = event.target;
      event.preventDefault();
}

function on_drag_end(event) {
      if (dragTarget==null) return;
      var x = parseFloat(dragTarget.getAttribute('x'));
      var y = parseFloat(dragTarget.getAttribute('y'));
      x += (event.getScreenX()-dtX)*(nW/sW);
      y += (event.getScreenY()-dtY)*(nH/sH);
      dragTarget.setAttribute('x', frmt(x, 2));
      dragTarget.setAttribute('y', frmt(y, 2));
      dragTarget = null;
      event.preventDefault();
}

function on_lb_slider_change(value) {
      var doc = getSVGDoc();
      var labelStyle;
      labelStyle = doc.getElementById("labels").getStyle();
      labelStyle.setProperty("font-size", label_size*value);
}

function on_rd_slider_change(value) {
      var doc = getSVGDoc();
      var reg_adm = doc.getElementById("reg_adm").getStyle();
      reg_adm.setProperty("stroke-width", road_width*value);
}

function setLabelColor(value) {
      var doc = getSVGDoc();
      var labelStyle = doc.getElementById("labels").getStyle();
      labelStyle.setProperty("fill",value);
}

function queryMaps() {
      query_maps(event.srcElement.value);
}

var winCpicker;

function customColors() {
      //winCpicker = window.open('cpicker.jsp','cpicker','toolbar=0,directories=0,menu=0,scrollbars=0,status=1,top=50,left=50,width=280,height=940,menubar=0');
      window.showModalDialog('cpicker.jsp', window,'dialogLeft=50,dialogTop=50,dialogWidth=50,help=no,resizable=no,status=yes');
}

function loadColors1() {
      colorSchemes[activeScheme].writeToPicker( winCpicker.document.cpicker.getSVGDocument() );
      winCpicker.focus();
}

function loadColors() {
      colorSchemes[activeScheme].writeToPicker( winCpicker.document.cpicker.getSVGDocument() );
      var option = winCpicker.document.getElementById('cs_select')[0];
      for( var i=0; i<colorSchemes.length; i++) {
            if (colorSchemes[i].sys<0) continue;
            newOption = option.cloneNode(true);
            newOption.value=colorSchemes[i].sys;
            newOption.innerText = colorSchemes[i].name;
            option.parentElement.appendChild(newOption);
      }
      winCpicker.focus();
}

function saveColors() {
      var newScheme = new ColorScheme(null, new Array(11), null, null, -1);
      newScheme.name = winCpicker.document.getElementById('cs_name').value;
      newScheme.readFromPicker(winCpicker.document.cpicker.getSVGDocument());
      // send to server
      saveColorSceme(newScheme);

      /*
      var index = colorSchemes.length;
      colorSchemes[index] = newScheme;
      activeScheme = index;
      winCpicker.close();
      update_cs_controls();
      colorit();
      */
}

function update_cs_controls() {
      var control = document.getElementById('colorchoice');
      var option = control.options[0];
      for (var i = control.options.length; i>=0; i--) {
            control.options.remove(i);
      }
      for (var i=0; i<colorSchemes.length; i++) {
            var newOption = option.cloneNode();
            newOption.selected = (activeScheme==i);
            newOption.value = i;
            newOption.text = colorSchemes[i].name;
            control.options.add(newOption);
      }
}

function buildColorData(win)
{
      for (i=0; i<colorSchemes.length; i++)
      {
            win.document.write("<option value ="+ i + ">" + colorSchemes[i].name + "</option>");
      }
}



// event handler
function changeColorScheme(evt) {
      activeScheme = parseInt(evt.srcElement.value);
      colorit();
}

////////////////////////////////////////
// legend functions
///////////////////////////////////////

var NUM_LEGEND_ELEMENTS = 10;


function setLegendElementsVisible( legendDoc, numElements, flag )
{

      var legendObj;
      var legendStyle;

      if (flag)
      {
            for (i = 0; i < numElements; i++)
            {
                  legendObj = legendDoc.getElementById("lval"+i);
                  legendStyle = legendObj.getStyle();
                  legendStyle.setProperty('visibility','visible');
            }
            legendObj = legendDoc.getElementById("nodata");
            legendStyle = legendObj.getStyle();
            legendStyle.setProperty('visibility','visible');

      } else {
            for (i = 0; i < numElements; i++)
            {
                  legendObj = legendDoc.getElementById("lval"+i);
                  legendStyle = legendObj.getStyle();
                  legendStyle.setProperty('visibility','hidden');
            }
            legendObj = legendDoc.getElementById("nodata");
            legendStyle = legendObj.getStyle();
            legendStyle.setProperty('visibility','hidden');
      }
} // end setLegendElementsVisible( )


function setLegendHeadline(legenddoc, dsn)
{
      legendObj = legenddoc.getElementById("headline");
    legendObj = legendObj.getFirstChild();
    legendObj.setData (mdb.getMeta(dsn).description);
} // end setLegendHeadline

function clearRegionLabels(svgdoc)
{
      var labelIndex = 0;
      for (myId in mdb.index) {
            //set the label text to the vmap values
            regionObj = svgdoc.getElementById('rl' + labelIndex);
            if (regionObj==null) continue;
            regionObj = regionObj.getFirstChild();
            regionObj.setData("" );
            labelIndex++;
      }
}// end clearRegionLabels

function setNoDataColor( legendDoc, color ) {
      var legendObj;
      var legendStyle;

      legendObj = legendDoc.getElementById("nodataVal");
      legendStyle = legendObj.getStyle();
      legendStyle.setProperty('fill',color);
}// end setNoDataColor( )

function setDataColor( legendDoc, index, color, label) {
      //alert('label -> ' + label)
      var labelObj = legendDoc.getElementById("textVal"+index).getFirstChild();
      if (label!=null) labelObj.setData(label); else labelObj.setData("");
      var legendStyle = legendDoc.getElementById("val"+index).getStyle();
      legendStyle.setProperty('fill',color);
}

function getSVGDoc() {
      return svgFile1.getSVGDocument();
}


var svgObj;
var svgStyle;
var svgdoc;
var groupnode;
var legendObj;
var legendStyle;
var legenddoc;
var svgvaldoc;
var svgdistrictObj;
var svgsubdistrictObj;
var svgvalObj;
var svgoverviewdoc;
var pluginPixWidth;
var pluginPixHeight;
var svgRect;
var svgMainViewport;
var width;
var height;
var polycolor;

function init() {
      svgdoc = getSVGDoc();
      svgMainViewport = svgdoc.getDocumentElement();

      //pega a referência para o svgoverview.svg and its objects
      svgoverviewdoc = svgOverview.getSVGDocument();
      overviewViewport = svgoverviewdoc.getDocumentElement()            ;
      pluginPixWidth = overviewViewport.getAttribute("width");
      pluginPixHeight = overviewViewport.getAttribute("height");

      svgOverview.width = pluginPixWidth;
      svgOverview.height = pluginPixHeight;

      svgRect = svgoverviewdoc.getElementById("rectForPlace");

      //reference to draggable rectangle and viewport
      getMapInfo();
      getViewBox();

      //toggleSVGElements('labels', checkboxForm.labelsCheck.checked);
      toggleSVGElements('reg_adm', checkboxForm.reg_admCheck.checked);
      toggleSVGElements('shields', checkboxForm.shieldsCheck.checked);
///////INICIO LABEL/////////////////////////////////////////////////

      svgMMdoc = svgFile1.getSVGDocument();


      svgMMrootElem = svgMMdoc.getElementById("root");



      gnStyle = svgMMdoc.getElementById('reg_adm').getStyle();

      accessInfoLabel = document.all.infoLabelLay;

      svgInfoLabel = infoLabel.getSVGDocument();

      svgLabelRoot= svgInfoLabel.getElementById("labelRoot");

      svgInfoLabelText = svgInfoLabel.getElementById("label");

      svgInfoLabelText = svgInfoLabelText.getFirstChild();


      setFollowingLabelEvents();


///////FIM LABEL/////////////////////////////////////////////////

}

//////////////INICIO LABEL //////////////////////////////////////////

function setFollowingLabelEvents(){


        var setFollowIt =svgMMdoc.getElementById('reg_adm').setAttribute("onmousemove","followIt(evt)");

        /*
        var setStopFollowIt = svgMMrootElem.setAttribute('onmouseout','stopFollowIt(evt)');
        */


        }

function showAdmin(id,evt) {

      var myreg;


      if(evt){


            theCircle = evt.getTarget();
            theCircleStyle = theCircle.getStyle();
            theCircleStyle.setProperty('fill','blue');
            theCircleStyle.setProperty('fill-opacity','0.4');
            theCircleStyle.setProperty('stroke','white');
            theCircleStyle.setProperty('stroke-width','5');
      }

        //id stammt aus svg path --> e.g. 'K001' ACHTUNG: FALLS IDS CHARACTERS SIND, DANN MUSS IN SVG-EVENT ' GESETZT WERDEN!!!!!!
        myreg = id;
        //alert('id....' + id);

        findLocation(myreg);

        nome_muni = dados_mundist[foundLocation][1] ;
        nome_dist = dados_mundist[foundLocation][2] ;


      var stringLength = nome_dist.length + 10;

      var infoLabelWidth = stringLength*8.3 ;




      infoLabel.setAttribute("width",infoLabelWidth);
      svgLabelRoot.setAttribute("width",infoLabelWidth);

      //var text = gnname + '  aaa ' + fullValue;
      var text = nome_dist;

      svgInfoLabelText.setData(text);


//--------end new

        svgMMObj = svgMMdoc.getElementById(id)
        svgMMStyle = svgMMObj.getStyle()

        svgMMStyle.setProperty('fill-opacity','0.3')


}


function emptyAdmin(evt) {


        svgMMStyle.setProperty('fill-opacity','1');

}


function followIt(evt) {

      //alert('incio followIt 1....');


      var x = evt.getClientX();
      var y = evt.getClientY();

      var ebene = accessInfoLabel.style;

      //alert('ebene ...' + ebene );


      ebene.visibility = "visible";


      if(x>600){
            if(x>700){ebene.left = x -100;}
            else{ebene.left = x -40;}
      }
      else {ebene.left = x +100;}


      if(y<25){ebene.top = y+50;}
      else {ebene.top = y+20;}

      window.status = 'valor de ebene.left...' + ebene.left + '  ebene.top...' + ebene.top;
      //alert('valor de ebene.left...' + ebene.left + '  ebene.top...' + ebene.top);

      if(!gnIsActive){
            //alert('Entrou no gnIsActive..');
            ebene.visibility = "hidden";
      }

}

function stopFollowIt(evt){

      var ebene = accessInfoLabel.style;

      //alert('ebene' + ebene);

      ebene.visibility = "hidden";



}
/////////////FIM LABEL //////////////////////////////////////////////

/////////////INICIO DA PESQUISA ID EM VETOR /////////////////////////
function findLocation(myreg){

      for (var i=0; i<dados_mundist.length; i++){
            if (myreg == dados_mundist[i][0]){
                  foundLocation = i;
                  return foundLocation;
            }
      }
}

/////////////FIM DA PESQUISA ID EM VETOR ////////////////////////////



//Vars that determine the size and default attr of all maps
var pressed = 0;

function buildThemeData(win)
{
      for (dsn in mdb.data)
      {
            win.document.write("<option value=\"" + dsn + "\" " + ((dsn==init_dsn) ? "selected" : "") + " >" + mdb.getMeta(dsn).description + "</option>");
      }
}

function buildUserEditableThemeData(win)
{

      for (dsn in mdb.data)
      {
            if (  (mdb.getMeta(dsn).dataType == "userData") && (mdb.getMeta(dsn).themeType != "color_only") )
            {
//                alert("<option value=\"" + dsn + "\">" + mdb.getMeta(dsn).description);
                  win.document.write("<option value=\"" + dsn + "\">" + mdb.getMeta(dsn).description );
            }
      }
}

function buildUserThemeData(win)
{

      for (dsn in mdb.data)
      {
            if (  (mdb.getMeta(dsn).dataType == "userData") )
            {
//                alert("<option value=\"" + dsn + "\">" + mdb.getMeta(dsn).description);
                  win.document.write("<option value=\"" + dsn + "\">" + mdb.getMeta(dsn).description );
            }
      }
}



//for sorting numerical arrays
function compareNumbers(a, b) {
   return a - b
}

function select_map() {
      window.top.location.assign(event.srcElement.value);
}

///////////////////////////////////////////
// theming functions
//////////////////////////////////////////
// these values are used so that the person can change their thresholds on a map - if they want.
var  lastTheme = "dummy";
var  lastDSN = "dummy";
var  lastValues = new Array;
var  lastThresholds = new Array;
var  useUserThresholds = false;


function colorit() {
// this is a proxy intended to route 5 types of thematic shading.
//
// The 5 types of thematic shading are:
// by Count - attempt to put the same number of states into each bucket,
//                      legend contains "<threshold"
// by Range - automatically divide the range of values into equal thresholds, then theme across the thresholds.
//                      legend contains "<=threshold"
// by User_Range - let the user defined the thresholds, then theme across the thresholds.
//                      legend contains "<=threshold".  User Range is "by_range" with a flag set on where to get the thresholds.
//
// by Value - let the user specify a mapping of descrete numeric values - to the color map, theme across the descrete values
//                      legend contains the  text description related to the descrete values
// by Color - like by Value, but - with more than 10 breaks allowed, and set region labels in the SVG.
////////////////////////////////////////////////////////////
// by Value and color_only do not allow count and range to be set
//                      - so we manage the enablement of those radio buttons here.
////////////////////////////////////////////////////////////
// lastTheme is used to manage USER_RANGE.  The user must have executed a "range" query first, before USER_RANGE.

      colorStaticElements(colorSchemes[activeScheme]);

      // get the data we are theming
      //aqui alterado com sucesso
      var dsn = selectThemeForm.myVar.value;

      //var dsn = nome_variavel;
      //alert('dsn vale - > ' + dsn);
      nome_var_selec = dsn;


      if (mdb.getMeta(dsn).themeType == 'value' )
      {
            document.forms["themeType"].elements["count"].disabled = true;
            document.forms["themeType"].elements["range"].disabled = true;
            useUserThresholds = false;
            colorit_by_value(dsn);
            lastTheme = 'value';

      }  else if ( mdb.getMeta(dsn).themeType == 'color_only' ){

                  // need to implement color_only
                  document.forms["themeType"].elements["count"].disabled = true;
                  document.forms["themeType"].elements["range"].disabled = true;
                  lastTheme = 'color_only';
                  useUserThresholds = false;
                  colorit_by_color_only(dsn);

      } else if (themeType.count.checked == true) { // check the HTML form

            document.forms["themeType"].elements["count"].disabled = false;
            document.forms["themeType"].elements["range"].disabled = false;
            document.forms["themeType"].elements["count"].checked = true;

            useUserThresholds = false;

            colorit_by_count(dsn);
            lastTheme = 'count';

      } else { // default-Range
            document.forms["themeType"].elements["count"].disabled = false;
            document.forms["themeType"].elements["range"].disabled = false;
            document.forms["themeType"].elements["range"].checked = true;

            colorit_by_range(dsn);
            lastTheme = 'range';
            lastDSN = dsn;
      }

      //toggleLabels(checkboxForm.labelsCheck.checked);

} // end function color_it()

function colorStaticElements(scheme) {
      // paint roads and labels
      var doc = getSVGDoc();
      var reg_adm = doc.getElementById("reg_adm").getStyle();
      reg_adm.setProperty("stroke","#8C0000");
      //var labelStyle = doc.getElementById("labels").getStyle();
      //labelStyle.setProperty("fill",scheme.label_color);
}

function colorit_by_color_only(dsn) {

      alert('aqui');

      var index = mdb.index;
      var data = mdb.getDataSet(dsn);
      var vmap = mdb.getMeta(dsn).vmap;

      var unique = new Array();
      for (ix in index) {
            var i = index[ix];
            try {
                  var value = vmap[data[i]];
                  if (value==null) continue;
                  /*
                  var count = unique[data[i]];
                  count = (count!=null) ? count+1 : 1;
                  */
                  unique[data[i]] = 0; //count;
            } catch (e) {
            }
      }

      var uniqueCnt = 0;
      for (key in unique) {
            uniqueCnt++;
            //unique[key] = Math.floor(unique[key]/2);
      }

      var colors = colorSchemes[activeScheme].getColors(uniqueCnt);

      var svgdoc = getSVGDoc();
      var nodataColor = colors[0];
      for (ix in index) {
            var svgStyle = svgdoc.getElementById(ix).getStyle();
            svgStyle.setProperty('fill', nodataColor);
            try {
                  var svgLabel = svgdoc.getElementById('rl' + index[ix]).getFirstChild();
                  svgLabel.setData('');
            } catch (e) {}
      }

      var color = 1;
      for (key in unique) {
            for (ix in index) {
                  var i = index[ix];
                  if (key!=data[i]) continue;
                  var svgStyle = svgdoc.getElementById(ix).getStyle();
                  svgStyle.setProperty('fill', colors[color]);
                  // !!!!!!
                  /*
                  if (unique[key]==0) {
                        try {
                              var svgLabel = svgdoc.getElementById('rl' + index[ix]).getFirstChild();
                              svgLabel.setData(vmap[data[i]]);
                        } catch (e) {}
                  }
                  unique[key]--;
                  */
                  if (unique[key]==0) {
                        try {
                              var svgLabel = svgdoc.getElementById('rl' + index[ix]).getFirstChild();
                              svgLabel.setData(vmap[data[i]]);
                              unique[key] = 1;
                        } catch (e) {}
                  }
            }
            color++; if (color>=colors.length) color=1;
      }

      var legenddoc = svgFile2.getSVGDocument();
      setLegendHeadline(legenddoc, dsn);
      setLegendElementsVisible( legenddoc, NUM_LEGEND_ELEMENTS, false );

}


function colorit_by_value(dsn) {

      //alert('Colorindo por faixa de valores');
      //alert('Cororindo por faixa');

      var index = mdb.index;
      var data = mdb.getDataSet(dsn);
      var vmap = mdb.getMeta(dsn).vmap;

      var unique = new Array();
      for (ix in index) {
            var i = index[ix];
            try {
                  var value = vmap[data[i]];
                  if (value==null) continue;
                  unique[data[i]] = value;
            } catch (e) {
            }
      }

      var uniqueCnt = 0;
      for (key in unique) {
            uniqueCnt++;
      }

      if (uniqueCnt>10) {
            alert('Operation not supportes for more than 10 unique groups');
            return;
      }

      var colors = colorSchemes[activeScheme].getColors(uniqueCnt);

      var svgdoc = getSVGDoc();
      var nodataColor = colors[0];
      for (ix in index) {
            var svgStyle = svgdoc.getElementById(ix).getStyle();
            svgStyle.setProperty('fill', nodataColor);
      }

      var color = 1;
      for (key in unique) {
            for (ix in index) {
                  var i = index[ix];
                  if (key!=data[i]) continue;
                  var svgStyle = svgdoc.getElementById(ix).getStyle();
                  svgStyle.setProperty('fill', colors[color]);
            }
            color++; if (color>=colors.length) color=1;
      }

      var legenddoc = svgFile2.getSVGDocument();
      setLegendHeadline(legenddoc, dsn);
      setLegendElementsVisible( legenddoc, NUM_LEGEND_ELEMENTS, false );

      setNoDataColor(legenddoc,colors[0]);

      var i = 0;
      for (key in unique) {
            //set the label text
            legendObj = legenddoc.getElementById("textVal"+i);
            legendObj = legendObj.getFirstChild();
            legendObj.setData(unique[key]);

            //set the color bar
            legendObj = legenddoc.getElementById("val"+i);
            legendStyle = legendObj.getStyle();
            legendStyle.setProperty('fill',colors[i+1]);

            i++;
      }

      //turn the legend back on
      setLegendElementsVisible(legenddoc, i, true );

} // end colorit_by_value()

//Loads Help Window
function ShowHelp(strUrl) {
      window.open(strUrl, "Help", "location=no,toolbar=no,menubar=no,status=yes,scrollbars=yes,resizable=yes,top=0,left=0,width=700,height=400");
}


function colorit_by_count(dsn) { // dsn == data to theme

      var myArray = new Array(); // temp place to hold the data
      var myThresholds = new Array(); // temp place to hold the thresholds


      //grab the current map svg
      svgdoc =getSVGDoc();

      window.status = "determinando a quantidade de valores ...";

      // figure out how many tiles we are doing.
      var nrClasses = selectClassesForm.myClass.value


      // select numeric values
      var ds1 = mdb.getDataSet(dsn);
      var v = new Array();
      var j=0;
      for (var i=0; i<ds1.length; i++) {
            if (isNaN(ds1[i])) continue;
            v[j] = ds1[i];
            j++;
      }

      // sort
      v.sort(num_sf_2);
      //alert('Cororindo por faixa');
      // select unique values
      var uv = new Array();
      var f;
      var j=0;
      for (var i=0; i<v.length; i++) {
            var val = v[i];
            if (f==val) continue;
            f = val; uv[j] = val;
            j++;
      }

      // build histogram
      var uf = new Array(uv.length);
      for (var j=0; j<uv.length; j++) uf[j]=0;

      for (var i=0; i<v.length; i++) {
            var val = v[i];
            for (var j=uv.length-1; j>=0; j--) {
                  if (uv[j]<val) break;
                  uf[j]++;
            }
      }
      delete v;

      // use less classes if dataset hasn't sufficient unique values;
      if (nrClasses>uv.length) nrClasses = uv.length;

      // check if we have sufficient colors for shading (color[0] is reserved for nodata)
      var colors = colorSchemes[activeScheme].getColors(nrClasses);
      if (nrClasses>colors.length-1) nrClasses = colors.length-1;

      var thresholds = null;
      if (nrClasses>0) {
            thresholds = new Array(nrClasses-1);
            if (nrClasses<2) {
                  thresholds[0] = uv[0];
            } else if (nrClasses==uv.length) {
                  for (var i=0; i<nrClasses-1; i++) thresholds[i] = uv[i];
            } else {
                  var delta = uf[uf.length-1]/nrClasses;
                  //alert('delta -> ' + delta);
                  var j=0; var k;
                  for (var i=0; i<nrClasses-1; i++) {
                        while (uf[j]<(i+1)*delta) j++;
                        if (j==k) j++;
                        thresholds[i] = uv[j];
                        //alert('uv[' + j + '] -> ' + uv[j]);
                        k = j;
                  }
            }
      }

      window.status = "pintando o mapa ...";

      for (myId in mdb.index) {
            myValue = mdb.getValue(dsn, myId);
            svgObj = svgdoc.getElementById(myId);
            svgStyle = svgObj.getStyle();
            var color;
            if (isNaN(myValue)) {
                  color = colors[0];
            } else if (myValue<=thresholds[0]) {
                  color = colors[1];
            } else {
                  for (var j=thresholds.length-1; j>=0; j--) {
                        if (myValue>thresholds[j]) {
                              color = colors[j+2]; break;
                        }
                  }
            }
            svgStyle.setProperty('fill', color);
      }

      //set legend
      window.status = "atualizando a legenda do mapa ...";
      legenddoc = svgFile2.getSVGDocument();

      //get/set the title on the legend window
      setLegendHeadline(legenddoc, dsn);

      //make legend elements invisible
      setLegendElementsVisible( legenddoc, NUM_LEGEND_ELEMENTS, false );

      // set the nodata color
      setNoDataColor(legenddoc, colors[0]);
      for (i=0; i < nrClasses-1; i++) {
            setDataColor(legenddoc, i, colors[i+1], "<="+thresholds[i]);
      }
      if (nrClasses>1) setDataColor(legenddoc, thresholds.length, colors[nrClasses], ">"+thresholds[thresholds.length-1]);
      else if (nrClasses==1) setDataColor(legenddoc, 0, colors[1], thresholds[0]);

      //turn the legend on again
      setLegendElementsVisible( legenddoc,nrClasses, true );

      window.status = "Completo, temas por quantidade com " + nrClasses +" cores";
} // end colorit_by_count()

////////////////////////////////////////////////////////////////////////////

function round(number,X) {
      // rounds number to X decimal places, defaults to 2
      X = (!X ? 2 : X);
      return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
      }
////////////////////////////////////////////////////////////////////////////

function colorit_by_range(dsn) {
      //by range
      var myArray = new Array();
      var myThresholds = new Array();
      //alert('Aqui...');

      svgdoc =getSVGDoc();

      window.status = "determinando a quantidade de valores por faixa...";

      //get the data and sort it for quantile calculation
      nrClasses = selectClassesForm.myClass.value

      // Get the data
      //mdb.copyDataSet(dsn, myArray);
      var ds1 = mdb.getDataSet(dsn);
      var myArray = new Array();
      var j=0;
      for (var i=0; i<ds1.length; i++) {
            if (isNaN(ds1[i])) continue;
            myArray[j] = ds1[i];
            j++;
      }

      // sort the data
      myArray.sort(num_sf_2);

      // get quantil values - by range.
      // get the min and max, then find the data values within that range that
      // are equidistant from each other.
      // then select the array elements based on that.

      window.status = "finished sort quantile values ...";
      // If the shading type is Colorize it
      // Now - find how many unique values there are
      // wtf is "ids"

      var unique_counter =1;
      var  unique_values = new Array;
      unique_values[0] = myArray[0];
      lastValues[0] = myArray[0];

      for (i=1; i<myArray.length; i++) {
            if (unique_values[unique_counter-1] != myArray[i] ) {
                  unique_values[unique_counter] = myArray[i];
                  lastValues[unique_counter] = myArray[i];
                  unique_counter++;
            }
      }


      if (useUserThresholds == true)  // The user set thresholds through the GUI so use those.
      {

            if (nrClasses >=unique_values.length)  // look to see if the array has less unique values that asked for...
            {
                  nrClasses = unique_values.length;
            }

            for (i=0; i<lastThresholds.length; i++)
            {
                  myThresholds[i]= lastThresholds[i]; // use the last thresholds
            }

      } else {  // otherwise calculate new thresholds

      if (nrClasses >=unique_values.length)  // look to see if the array has less unique values that asked for...
      {   // if so, use the uniques as thresholds
            nrClasses = unique_values.length;
            for (i=0; i<unique_values.length; i++)
            {
                  myThresholds[i]= unique_values[i]; // use the unique values as thresholds
                  lastThresholds[i]= unique_values[i]; // use the unique values as thresholds
            }
            lastThresholds.length = myThresholds.length;

      } else { // otherwise calculate the new thresholds

            // break the range of values into equal chunks
            threshold =  (myArray[myArray.length-1] - myArray[0]) / nrClasses;

            myThreshold = threshold;
            var num_01 = myThreshold
            //alert('num_01 : ' + num_01);


            myThreshold = round(num_01,2);

            //alert('myThreshold : ' + myThreshold);


            //myThresholds[0] = myArray[0] + Math.round(myThreshold);
            //lastThresholds[0] = myArray[0] + Math.round(myThreshold);
            myThresholds[0] = myArray[0] + myThreshold;
            lastThresholds[0] = myArray[0] + myThreshold;


            //alert('myArray[0] -> ' + myArray[0] + ' myThreshold -> ' + myThreshold + ' myThresholds[0] -> ' + myThresholds[0] + ' lastThresholds[0] -> ' + lastThresholds[0]);

            for (i = 1; i < nrClasses -1; i++) {
                  myThresholds[i] = round(myThresholds[i-1]  + myThreshold,2);
                  lastThresholds[i] = round(myThresholds[i-1]  + myThreshold,2);
                  //alert('myThresholds[' + i + '] ' + myThresholds[i] + ' lastThresholds[' + i + '] ' + lastThresholds[i]);
            }
                  myThresholds[i] = myArray[myArray.length - 1];
                  lastThresholds[i] = myArray[myArray.length - 1];
                  lastThresholds.length = myThresholds.length;
      }

      }

      if (myArray.length ==0) nrClasses=0;

      //set array with color-values

      window.status = "colocando cores por valor ...";
      var myColors =  colorSchemes[activeScheme].getColors(nrClasses);

      //color it
      window.status = "pintado o mapa ...";


      for (myId in mdb.index) {
            myValue = mdb.getValue(dsn, myId);
            svgObj = svgdoc.getElementById(myId);
            svgStyle = svgObj.getStyle();
            if (isNaN(myValue)) {
                  svgStyle.setProperty('fill',myColors[0]);
            } else {
                  for (j = myColors.length -2; j >0 ; j--) {
                        if ((myValue <= myThresholds[j]) && myValue> (myThresholds[j-1]) )  {
                              svgStyle.setProperty('fill',myColors[j+1]);
                              break;
                        } else if (j==1) {
                              svgStyle.setProperty('fill',myColors[1]);
                              break;
                        }
                  }
            }
      }

      //set legend
      window.status = "atuzalizando a legenda do mapa ...";
      legenddoc = svgFile2.getSVGDocument();

      //get/set the title on the legend window
      setLegendHeadline(legenddoc, dsn);


      // set ALL the legend labels to be invisible to clean-up from the last state
      setLegendElementsVisible( legenddoc, NUM_LEGEND_ELEMENTS, false );


      // set the nodata color
      setNoDataColor(legenddoc,myColors[0]);

      // set the legend colors
      for (i = 0; i < nrClasses; i++) {
            legendObj = legenddoc.getElementById("textVal"+i).getFirstChild();
            if (i!=nrClasses-1) legendObj.setData("<= "+myThresholds[i]); else legendObj.setData("> "+myThresholds[i-1]);
            legendObj = legenddoc.getElementById("val"+i);
            legendStyle = legendObj.getStyle();
            legendStyle.setProperty('fill',myColors[i+1]);
      }

      // set the active legend labels to be visible
      setLegendElementsVisible( legenddoc, nrClasses, true );

      window.status = "Completado, temas por faixa com "+ nrClasses +" única cor";

} // colorit_by_range()



// used to turn on/off the map layers
function toggleSVGElements(id,checkVal) {
    var svgStyle = getSVGDoc().getElementById(id).getStyle();
      if (checkVal) {
            svgStyle.setProperty('visibility','visible');
      } else {
            svgStyle.setProperty('visibility','hidden');
      }
}

function toggleInGroup(id1,id2,checkVal) {
      var childNodes = getSVGDoc().getElementById(id1).childNodes;
      for (var i=0; i<childNodes.length; i++) {
            var node = childNodes.item(i);
            try {
                  if (node.tagName!='g') continue;
                  var vis = ((node.id==id2) && checkVal) ? 'visible' : 'hidden';
                  node.style.setProperty('visibility', vis);
            } catch (e) {}
      }
}

function toggleLabels(checkVal) {
      //alterado aqui
      //var dsn = selectThemeForm.myVar.value;
      var dsn = nome_variavel;
      var target = (mdb.getMeta(dsn).themeType == 'color_only' ) ? 'rl' : 'gl';
      toggleInGroup('labels', target, checkVal);
}

//highlights on mouse over
function showDistrict(evt) {


      //incio alteração
      svgdoc = evt.getTarget() != null ? evt.getTarget().getOwnerDocument() : null;
      svgroot = svgdoc.getDocumentElement();

      //alert("svgdoc : " + svgdoc);




      //initialize cursor parameters
      var vbox = (svgroot.getAttribute("viewBox")).split(' ');

      x0 = parseFloat(vbox[0]);
      y0 = parseFloat(vbox[1]);
      vboxW = parseFloat(vbox[2]);
      vboxH = parseFloat(vbox[3]);

      //alert("x0 : " + x0 + " y0 : " + y0+ " vboxW : " + vboxW+ " vboxH : " + vboxH);
      //alert("vbox : " + vbox);

      svgW = parseFloat(svgroot.getAttribute("width"));
      svgH = parseFloat(svgroot.getAttribute("height"));
      //alert("svgW : " + svgW + " svgH : " + svgH);
      // initialize label text


      var data = svgdoc.createTextNode(" ");
      var text = svgdoc.createElement("text");
      alert("text : " + text);

      text.setAttribute("transform","translate("+ x0 + "," + y0 + ")");

      text.setAttribute("style", "fill:#2d8c30;font-size:4600;");

      text.setAttribute("teste", "label");
      text.appendChild(data);
      svgroot.appendChild(text);

      /*
      var idObj = evt.target;
      while (idObj.id.length ==0 && idObj!=null) {
            alert("Passou aqui");
            idObj = idObj.getParentNode();
      }
      alert("idObj.id ->" + idObj.id);
      svgStyle = idObj.getStyle();
      polycolor = svgStyle.getPropertyValue("fill"); //get PropertyValue, store orginial color
      svgStyle.setProperty("fill","url(#Gradient)"); //set PropertyValue, generate gardient highlight
      */



      //
}


function on_load(e){

      svgdoc = e.getTarget() != null ? e.getTarget().getOwnerDocument() : null;
      svgroot = svgdoc.getDocumentElement();

      //inicializa os parâmentro do cursor
      var vbox = (svgroot.getAttribute("viewBox")).split(' ');
      x0 = parseFloat(vbox[0]);
      y0 = parseFloat(vbox[1]);
      vboxW = parseFloat(vbox[2]);
      vboxH = parseFloat(vbox[3]);
      svgW = parseFloat(svgroot.getAttribute("width"));
      svgH = parseFloat(svgroot.getAttribute("height"));
      // initialize label text
      var data = svgdoc.createTextNode(" ");
      var text = svgdoc.createElement("text");
      text.setAttribute("transform","translate("+ x0 + "," + y0 + ")");
      text.setAttribute("style", "fill:#2d8c30;font-size:4600;");
      text.setAttribute("id", "label");
      text.appendChild(data);
      //alert("text : " + text);
      svgroot.appendChild(text);

}


// mouse_over
function over(e,muni3) {
      target = e.currentTarget;
      var id = target.id;
      var id2 = muni3;
      if (id!="") {
            //var X = x0 + offset +(e.getClientX() - svgroot.currentTranslate.x)*(vboxW/(svgW*svgroot.currentScale));
            var X = x0 + 7000 + e.getClientX();

            //var Y = y0 - offset + (e.getClientY() - svgroot.currentTranslate.y)*(vboxH/(svgH*svgroot.currentScale));
            var Y = y0 + 7000 ;
            label =  svgdoc.getElementById("label");
            label.setAttribute("transform","translate("+ X + "," + Y + ")");
            label.getFirstChild().setData(id + "Y : " + Y);
            var svgstyle = e.currentTarget.getStyle();
            style = svgstyle.getPropertyValue('fill');
            svgstyle.setProperty ('fill','#ffcc99');
      }
}


function out(e) {
      //rollover label off
      var label =  svgdoc.getElementById("label");
      label.getFirstChild().setData(" ");
      var svgstyle = e.currentTarget.getStyle();
      svgstyle.setProperty ('fill',style);
      ////////////////////
      //var data_view2 = document.data_view.getSVGDocument();
      //data_view2.getElementById('nome_muni').getFirstChild().setData('');

}
function DoOnMouseMove(e) {
      var X = x0 + (e.getClientX() - svgroot.currentTranslate.x)*(vboxW/(svgW*svgroot.currentScale));
            var Y = y0 - offset + (e.getClientY() - svgroot.currentTranslate.y)*(vboxH/(svgH*svgroot.currentScale));
      //label =  svgdoc.getElementById("label");
      label.setAttribute("transform","translate("+ X + "," + Y + ")");
}

//restores on mouse out.
function emptyDistrict(evt) {
      svgStyle.setProperty("fill", polycolor);  //set PropertyValue, restore original color
}

function showDetailData(evt) {
      var idObj = evt.target;
      while (idObj.id.length ==0 && idObj!=null) {
            idObj = idObj.getParentNode();
      }
      dataWindow=open("","","toolbar=0,directories=0,menu=0,scrollbars=0,location=0,resizable=1,status=0,top=50,left=50,width=300,height=200,menubar=0,dependent=1,hotkeys=0");
      escreveDetalhedosDados(idObj.id);
}


function escreveDetalhedosDados(id) {
      myreg = id;
        findLocation(myreg);

        var nomemuni = dados_mundist[foundLocation][1] ;
        var nomedist = dados_mundist[foundLocation][2] ;
        var val ;
        val = mdb.getValue(nome_var_selec, id);
        //var geoid = dados_mundist[foundLocation][0] ;
        var geoid = val ;


      dataWindow.document.open();
      //dataWindow.document.write("<HTML><HEAD><TITLE>Informações");
      dataWindow.document.write("<HTML><HEAD><TITLE>Informações");
      dataWindow.document.write("</TITLE><link rel=stylesheet type='text/css' href='styles.css'></HEAD>");
      dataWindow.document.write("<BODY bgcolor='#FFFFFF' marginheight='0' marginwidth='0' topmargin='0' leftmargin='0'>");
      dataWindow.document.write("<h4>Informações</h4><table>");
      dataWindow.document.write("<tr><td >Nome: " + nomemuni + " </td></tr>");
      dataWindow.document.write("<tr><td ></td></tr>");
      dataWindow.document.write("<tr><td >Valor da variável : " + val + " </td></tr>");

      dataWindow.document.write("</table></BODY></HTML>");
      dataWindow.document.close();


}


function zoomIt() {

      window.status = "zoom do mapa - espere um momento por favor ...";

      if (document.all) {
            zoomVal = parseFloat(selectZoomVal.myZoomSelect.value)
      }
      else {
            zoomVal = parseFloat(document.overviewZoom.document.selectZoomVal.myZoomSelect.options[document.overviewZoom.document.selectZoomVal.myZoomSelect.options.selectedIndex].value)
      }

      //get values from draggable rectangle
      xulcorner = parseFloat(svgRect.getAttribute("x"));
      yulcorner = parseFloat(svgRect.getAttribute("y"));
      width = parseFloat(svgRect.getAttribute("width"));
      height = parseFloat(svgRect.getAttribute("height"));

      //calcs
      xcenter = xulcorner + width / 2;
      ycenter = yulcorner + height / 2;
      xnulcorner = xcenter - nW0 / 2 * (100/zoomVal);
      ynulcorner = ycenter - nH0 / 2 * (100/zoomVal);
      nWidth = nW0 * (100/zoomVal);
      nHeight = nH0 * (100/zoomVal);

      if (zoomVal == 100) {
            xnulcorner = nX0
            ynulcorner = nY0
      }
      //set values of draggable rectangle
      svgRect.setAttribute("x",xnulcorner);
      svgRect.setAttribute("y",ynulcorner);
      svgRect.setAttribute("width",nWidth);
      svgRect.setAttribute("height",nHeight);

      //set viewport of main map
      newViewport = xnulcorner + " " + ynulcorner + " " + nWidth + " " + nHeight;
      svgMainViewport.setAttribute("viewBox",newViewport);

      getMapInfo();

      window.status = "... done";
}

function beginPan(evt) {
      pressed = 1;
      width = parseFloat(svgRect.getAttribute("width"));
      height = parseFloat(svgRect.getAttribute("height"));
      evtX = parseFloat(evt.getClientX());
      evtY = parseFloat(evt.getClientY());
      rectUlXCorner = parseFloat(svgRect.getAttribute("x"));
      rectUlYCorner = parseFloat(svgRect.getAttribute("y"));
      //alert("evtX="+evtX+", evtY="+evtY);
}
function doPan(evt) {
      if (pressed == 1) {
            newEvtX = parseFloat(evt.getClientX());
            newEvtY = parseFloat(evt.getClientY());
            toMoveX = rectUlXCorner + (newEvtX - evtX) * nW0 / pluginPixWidth;
            toMoveY = rectUlYCorner + (newEvtY - evtY) * nH0 / pluginPixHeight;

            //restrict to borders of overviewmap
            if (toMoveX < nX0) {
                  svgRect.setAttribute("x",nX0);
            }
            else if ((toMoveX + width) > (nX0 + nW0)) {
                  svgRect.setAttribute("x",nX0 + nW0 - width);
            }
            else {
                  svgRect.setAttribute("x",toMoveX);
            }
            if (toMoveY < nY0) {
                  svgRect.setAttribute("y",nY0);
            }
            else if ((toMoveY + height) > (nY0 + nH0)) {
                  svgRect.setAttribute("y",nY0 + nH0 - height);
            }
            else {
                  svgRect.setAttribute("y",toMoveY);
            }

            evtX = newEvtX;
            evtY = newEvtY;
            rectUlXCorner = parseFloat(svgRect.getAttribute("x"));
            rectUlYCorner = parseFloat(svgRect.getAttribute("y"));
      }
}

function endPan(evt) {
      window.status = "panning map - please be patient ...";
      pressed = 0;
      //set viewport of main map
      xulcorner = parseFloat(svgRect.getAttribute("x"));
      yulcorner = parseFloat(svgRect.getAttribute("y"));
      width = parseFloat(svgRect.getAttribute("width"));
      height = parseFloat(svgRect.getAttribute("height"));
      newViewport = xulcorner + " " + yulcorner + " " + width + " " + height;
      svgMainViewport.setAttribute("viewBox", newViewport);
      window.status = "... done";
}

function groupgeographies() {
      dataWindow=open("grupload.jsp?id_map="+map_id,"gr_upload","toolbar=0,directories=0,menu=0,scrollbars=1,location=0,resizable=0,status=0,top=50,left=50,width=450,height=430,menubar=0,dependent=1,hotkeys=0");
      dataWindow.focus();
}


function printmaps() {
      dataWindow=open("print.jsp?id_map="+map_id,"print","toolbar=0,directories=0,menu=0,scrollbars=1,location=0,resizable=1,status=1,top=50,left=50,width=670,height=600,menubar=1,dependent=1,hotkeys=0");
      dataWindow.focus();
}

function viewdata() {
      dataWindow=open("","","toolbar=0,directories=0,menu=0,scrollbars=1,location=0,resizable=0,status=0,top=50,left=50,width=400,height=500,menubar=0,dependent=1,hotkeys=0");
      dataWindow.opener = this.window;
      dataWindow.document.write("<HTML><HEAD><TITLE>Custom Mapping System");
      dataWindow.document.write("</TITLE><link rel=stylesheet type='text/css' href='styles.css'></HEAD>");


      var dsn = selectThemeForm.myVar.value;

      dataWindow.document.write("<BODY bgcolor='#FFFFFF' marginheight='0' marginwidth='0' topmargin='0' leftmargin='0' onBlur='window.close()'>");
      dataWindow.document.write("<TABLE cellspacing=0 cellpadding=6 BORDER=1 BGCOLOR='#004080' height='100%' width='100%'>");
      dataWindow.document.write("<TR><TD height=25 background='images/page_bg.gif'COLSPAN=2 valign='middle' align='left'><b class='window'>&nbsp; View Data</b></TD></TR>");
      dataWindow.document.write("<TR><TD valign='top'>");
      dataWindow.document.write("<TABLE Width='100%' cellspacing=5 bgcolor='#F8F4F8' border=0>");
      dataWindow.document.write("<form method='POST' name='selectThemeForm'>\n");
      dataWindow.document.write("<TR><TD colspan=3 align='center' valign='bottom'><font class='big'>"+ mdb.getMeta(dsn).description +"</font><br></br></td></tr> ");
      dataWindow.document.write("<TR><TD WIDTH='50%' ALIGN='center' bgcolor='darkred'><b><font color='white'>"+mdb.getMeta('i0').description+"</b></TD>\n");
//    dataWindow.document.write("<TD WIDTH='33%' ALIGN='center' bgcolor='darkred'><b><font color='white'>"+mdb.getMeta('i1').description+"</b></TD>\n");
      dataWindow.document.write("<TD WIDTH='50%' ALIGN='center' bgcolor='darkred'><b><font color='white'>Value</b></TD>\n");

      var tempArray = new Array();
      var newArray = new Array();
      var origArray = new Array();
      var stringFlag = false;
      mdb.copyIdDataSet('i0', tempArray); // get the ID on which to sort

      for (var i=0; i< tempArray.length; i++ )
      {
            origArray[i]=tempArray[i];   // unsorted copy of the original

      }

      // sort and build the x-ref array based on the type of geo-label (text or numeric)
      if (  mdb.getMeta('i0').dataType == "integer")
      {
            tempArray.sort(num_sf);
            for (var i=0; i< tempArray.length; i++ )
            {
                  newArray[eval(origArray[i])]=i;     // as number
            }

      } else {
            tempArray.sort(cis_sf);
            stringFlag = true;
            for (var i=0; i< tempArray.length; i++ )
            {
                  newArray[origArray[i]]=i; // as string
            }

      }

      var myArray = mdb.getDataSet(dsn);
      var myArray2 = new Array();
      var localIndex = 0;
      var lastGeoLabel = "";

      mdb.copyIdDataSet('i1', myArray2);

      for ( i in mdb.index) {
            if ( lastGeoLabel != tempArray[localIndex]) {
                  dataWindow.document.write("<TR><TD WIDTH='50%' ALIGN='left' bgcolor='#F8F4F8'>");
                  dataWindow.document.write("<b>\n"+ tempArray[localIndex] + "</b></TD>");

                  if (mdb.getMeta(dsn).themeType == 'value' ) {
                        dataWindow.document.write("<TD ALIGN='left' bgcolor='#F8F4F8'><b>"
                        + mdb.getMappedValueFromData(dsn, myArray[newArray[tempArray[localIndex]]])
                        + "</b></TD></TR>");
                  } else {
                        var val = myArray[newArray[tempArray[localIndex]]]
                        dataWindow.document.write("<TD ALIGN='left' bgcolor='#F8F4F8'><b>"
                        + (isNaN(val) ? "No Data" : val) + "</b></TD></TR>");
                  }
                  lastGeoLabel = tempArray[localIndex];
            }
            localIndex++;
      }
      dataWindow.document.write("</form>\n");
      dataWindow.document.write("</TABLE>");
      dataWindow.document.write("</TD></TR>");
      dataWindow.document.write("</TABLE>");
      dataWindow.document.write("</BODY></HTML>");
} // end viewdata()

function changeprofile() {
      dataWindow=open("uedit.jsp","edit_profile","toolbar=0,directories=0,menu=0,scrollbars=0,location=0,resizable=0,status=0,top=50,left=50,width=420,height=390,menubar=0,dependent=1,hotkeys=0");
      dataWindow.focus();
}


function setthresh() {

      if (lastTheme != 'range' )
      {

            alert("Sorry, but you must select 'By Range' before setting your own thresholds");
      } else {

            var height;
            height = (lastThresholds.length * 40) + 250;

            dataWindow=open("","","toolbar=0,directories=0,menu=0,scrollbars=1,location=0,resizable=0,status=0,top=50,left=50,width=400,height="+height+",menubar=0,dependent=1,hotkeys=0");
            dataWindow.opener = this.window;
            dataWindow.document.write("<HTML><HEAD><TITLE>Custom Mapping System");
            dataWindow.document.write("</TITLE><link rel=stylesheet type='text/css' href='styles.css'>");

            dataWindow.document.write("\n<Script> \n");
            dataWindow.document.write("\n\nfunction compareNumbers(a, b) { return a - b }\n\n");

            dataWindow.document.write("function setNewThresholdValues(form)\n{\n ");

            dataWindow.document.write("var tempArray = new Array(); \n");
            dataWindow.document.write("for (var i = 0; i<form.elements.length-1; i++){\n");
            dataWindow.document.write("   if (isNaN(form.elements[i].value) ){alert('You have entered null data or non-numeric data: ' + form.elements[i].value + '. Please enter numeric data only.');\n event.returnValue=false;return;}\n");

            dataWindow.document.write("tempArray[i] = form.elements[i].value;}\n\n");
            dataWindow.document.write("tempArray.sort(compareNumbers);\n");
            dataWindow.document.write("for (var i = 0; i<form.elements.length-1; i++){\n");
            dataWindow.document.write(" if (tempArray[i] != form.elements[i].value) {alert('You must enter threshold data in ascending order.'); \n event.returnValue=false;return;}\n");
            dataWindow.document.write("}\n");

            dataWindow.document.write("for (var i = 0; i<form.elements.length-1; i++) \n{\n");
            dataWindow.document.write("    opener.lastThresholds[i]=form.elements[i].value;\n}\n");
            dataWindow.document.write("opener.useUserThresholds = true;\n")

            dataWindow.document.write("opener.colorit();opener.useUserThresholds = false;close();}\n</script>\n");
            dataWindow.document.write("</HEAD>");

            dataWindow.document.write("<BODY bgcolor='#FFFFFF' marginheight='0' marginwidth='0' topmargin='0' leftmargin='0' >");
            dataWindow.document.write("<TABLE cellspacing=0 cellpadding=6 BORDER=1 BGCOLOR='#004080' height='100%' width='100%'>");
            dataWindow.document.write("<TR><TD background='images/page_bg.gif'COLSPAN=2 valign='middle' align='left'><b class='window'>&nbsp; Set Threshold Values</b></TD></TR>");
            dataWindow.document.write("<TR><TD VALIGN='TOP'>");
            dataWindow.document.write("<TABLE cellspacing=0 cellpadding=6 BORDER=0 WIDTH='100%' bgcolor='#004080'>");
            dataWindow.document.write("<TR><TD COLSPAN=2 class='whitetext' AlIGN='LEFT' bgcolor='#004080'>You may alter the values that determine the thematic shading thresholds below.  Click <b class='yellow'>Apply New Thresholds</b> to apply the new thresholds.<br></br></TD></TR>");
            dataWindow.document.write("<TR><TD WIDTH='50%' ALIGN='center' bgcolor='#800000'><font color='white'>Minimum Value In Data Set:</TD><TD ALIGN='center' bgcolor='800000'><font color='white'>Maximum Value in Data Set:</td></TR>");
            dataWindow.document.write("<TR><TD ALIGN='center' bgcolor='#800000'><b><font color='white'>"+ lastValues[0] +"</b></TD><TD ALIGN='center' bgcolor='800000'><b><font color='white'>"+ lastValues[lastValues.length-1] +"</b></td></TR>");
            dataWindow.document.write("\n\n<form name='setNewThresholds' method='POST' onsubmit='setNewThresholdValues(this);' >");

            for (i = 0; i < lastThresholds.length-1; i++) {
                  dataWindow.document.write("\n<TR><td align='right' bgcolor='#F8F4F8'><b>Threshold #"+ [i+1] +":</b></td><TD align=left bgcolor='#F8F4F8'><input name='thresh_values"+ [i] +"' size='5' value='"+ lastThresholds[i] + "'></TD></TR>");
            }
            dataWindow.document.write("\n<TR><TD COLSPAN=2 height='30' valign='TOP' align='center' bgcolor='#F8F4F8'><br></br><input type='submit' name='button' value='Apply New Thresholds'   ></TD></TR>");

            dataWindow.document.write("\n</form>\n\n");

            dataWindow.document.write("</TABLE>");
            dataWindow.document.write("</TABLE>");
            dataWindow.document.write("</BODY></HTML>");

      }


}

