  var args = getargs(); // nab any URL-based arguments
  var leg_global = '';
  function Extent(minx, miny, maxx, maxy) {
    this.minx = minx;
    this.miny = miny;
    this.maxx = maxx;
    this.maxy = maxy;
  } 
  
  var d = new Date(currenttime);
  
  if (d.getMonth()<10) month = '0'+(d.getMonth()+1);
  else month = (d.getMonth()+1);
  
  if (d.getDate()<10) day = '0'+d.getDate();
  else day = d.getDate();

  config = new Object();
  config.ms_executable = "/cgi-bin/mapserv";
  //config.mapfile = '/ms4w/Apache/htdocs/meio_ambiente/dados/'+d.getFullYear()+'-'+month+'-'+day+'/qualidade_ar.map';
  config.mapfile = '/extra/apache/http/projetos/meioambiente.cptec.inpe.br/qualidade_ar.map';
  //config.mapfile = "/ms4w/apps/dbox-0.9a1/example/itasca.map";
  //config.dlegend_xml_executable = "/cgi-bin/make_dlegend_xml_cgi.py";
  config.dlegend_server = "localhost";
  config.gpath = "/images";
  config.gpath_bb = "/images/azul";
  config.gpath_bl = "/images/laranja";
  config.gpath_bc = "/images/cinza";
  config.minscale = 1;
  config.maxscale = 1000000;
  //config.app_extent = new Extent(388107.634400379, 5203120.88405952, 500896.339019834, 5310243.30613897);
  //config.app_extent = new Extent(-75, -34, -45, 5);
  //config.app_extent = new Extent(-89.08, -52.963, -27.03, 12.247);
  config.app_extent = new Extent(-81., -46., -30., 10.);
  // interface buttons
  var buttons = new Array('state', 'zoomin', 'pan', 'zoomout', 'info', 'perfil_vertical', 'series_temporais');
  var active_button = '';

  var buttons_info = new Array('duv', 'anime', 'leg', 'camadas');
  var active_button_info = '';

  var buttons_hour = new Array('hour_00h1', 'hour_03h1', 'hour_06h1', 'hour_09h1', 'hour_12h1', 'hour_15h1', 'hour_18h1', 'hour_21h1', 'hour_00h2', 'hour_03h2', 'hour_06h2', 'hour_09h2', 'hour_12h2', 'hour_15h2', 'hour_18h2', 'hour_21h2', 'hour_00h3', 'hour_03h3', 'hour_06h3', 'hour_09h3', 'hour_12h3', 'hour_15h3', 'hour_18h3', 'hour_21h3', 'hour_00h4');
  var active_button_hour = '';

  // interface mapsize
  var mapsizex=550, mapsizey=622;

  // the DHTML legend container (note the significance of the name "main" here and the anchor image/div in the main body of the page)
  
  // the DHTML main mapping window (note the significance of the name "main" here and the anchor image/div in the main body of the page)
  var main = new dBox("main");
  main.color = "red";
  main.thickness = 2;
  main.verbose = true;
  main.useBusyMessage();
  

  // the DHTML reference map  

  var ms = new Mapserv(config.ms_executable, config.mapfile, config.app_extent.minx, config.app_extent.miny, config.app_extent.maxx, config.app_extent.maxy, mapsizex, mapsizey);
  ms.queryfile = config.mapfile;
  ms.minscale = config.minscale;
  ms.maxscale = config.maxscale;  
  //ms.options = '&map_Estados_class_outlinecolor=0 0 0';
  //ms.options = '&map_IMAGETYPE=PNG&map_TRANSPARENT=off';
  // 
  // Process any input args (only a couple are supported). This is demo specific but is generally 
  // a useful extension.
  // 
  if(args.mapxy) {      
    var coords = args.mapxy.split(" ");
    if(coords.length != 2) alert("Not enough coordinates for mapxy. Using default extent.");
    if(args.scale) ms.setExtentFromScale(parseFloat(coords[0]), parseFloat(coords[1]), parseFloat(args.scale));
    else if(args.radius) ms.setExtentFromRadius(parseFloat(coords[0]), parseFloat(coords[1]), parseFloat(args.radius));
    else alert("Coordinate given but no scale or radius. Using default extent.");
  }

  if(args.mapext) {
    var coords = args.mapext.split(" ");
    if(coords.length != 4) alert("Not enough coordinates for mapext. Using default extent.");
    ms.setExtent(parseFloat(coords[0]), parseFloat(coords[1]), parseFloat(coords[2]), parseFloat(coords[3]));
  }

  if(args.layers) {
    var layers = args.layers.split(" ");
    ms.layersOff(); // turn all layers off
    for(var i=0; i<layers.length; i++)  
      ms.setLayer(layers[i], true);
  }

  //
  // drawing callback, calling ms.draw will invoke this function after building appropriate URLs
  // 
	ms.setHandler(MAPSERV_DRAW, ms_draw);
  function ms_draw() {
		main.setImage(ms.url);

    // update the scalebars    
    //document.scalebar_miles.src = ms.mapserver + "?map=" + config.mapfile + "&mode=scalebar&mapext=0+0+" + (ms.extent[2] - ms.extent[0]) + "+" + (ms.extent[3] - ms.extent[1]) + "&mapsize=" + ms.width + "+" + ms.height;
   document.scalebar_kilometers.src = ms.mapserver + "?map=" + config.mapfile + "&map_scalebar_units=kilometers&mode=scalebar&mapext=0+0+" + (ms.extent[2] - ms.extent[0]) + "+" + (ms.extent[3] - ms.extent[1]) + "&mapsize=" + ms.width + "+" + ms.height;


		// debug
		var e = document.getElementById("debug");
    if(e) e.innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;<a target=new href='" + ms.url + "'>open current image in a new window</a>";

  }

  //
  // querying callback
  //
  ms.setHandler(MAPSERV_QUERY, ms_query);  
	function ms_query() {    
    var xTela = ms.querypoint[0];
    var yTela = ms.querypoint[1];    
    
    if (active_button == 'info'){
      ajaxFunction(ms.url, xTela, yTela);
    }    
    else if (active_button == 'perfil_vertical'){
      ajaxPerfil(xTela, yTela, config.mapfile, ms.extent[0], ms.extent[1], ms.extent[2], ms.extent[3]);
    } 
    else if (active_button == 'series_temporais'){
      ajaxSeries(xTela, yTela, config.mapfile, ms.extent[0], ms.extent[1], ms.extent[2], ms.extent[3]);
    }     
    //querywin.focus();
  }

 	main.setHandler(DBOX_SETBOX, main_setbox);
main.setHandler(DBOX_MOUSEMOVE, main_setbox);
  function main_setbox(minx, miny, maxx, maxy) {    
    if(ms.mode == 'map') {
      if(minx != maxx && miny != maxy)
        ms.applyBox(minx, miny, maxx, maxy);       
      else
        ms.applyZoom(minx, miny);       
      ms.draw();  // builds draw URL and calls draw callback         
    } else if(ms.mode != 'map') {      
      ms.applyBoxQuery(minx, miny, maxx, maxy);
      ms.applyPointQuery(minx, miny);
      ms.query(); // builds query URL and calls query callback 
    }     
  }

  // various event handlers called by jBox/dBox
	main.setHandler(DBOX_MOUSEMOVE, main_mousemove);
  function main_mousemove(x, y) {    
    var text = '';
    var utmx = Number(ms.extent[0] + x*ms.cellsize);
    var utmy = Number(ms.extent[3] - y*ms.cellsize);
    mouse_x=x;
    mouse_y=y;

    //text = "&nbsp;UTM Coordinates:  x =" + Math.round(utmx) + " and y = " + Math.round(utmy) +" and estado = "+ estado;
    text = "&nbsp;Longitude:" + (utmx.toFixed(3)) + " Latitude:" + (utmy.toFixed(3));

    var e2 = document.getElementById("coords");

    if(e2) e2.innerHTML = "Coordenadas UTM <br>"+ text;    
    var main_img = document.getElementById('main');	

    e2.style.top = getAbsTop(main_img)+main_img.clientHeight-e2.clientHeight+'px';
    e2.style.left = getAbsLeft(main_img)+main_img.clientWidth-e2.clientWidth+'px';
    
    
  }
	
  main.setHandler(DBOX_MOUSEEXIT, clear_coords);
	main.setHandler(DBOX_MOUSEENTER, clear_coords);
  function clear_coords() { 
    var e2 = document.getElementById("coords"); 
    if(e2) e2.innerHTML = '&nbsp;'; 
    //if(e) e.innerHTML = 'Coordenadas UTM <br>';
  }

  main.setHandler(DBOX_MEASURE, main_measure);
  function main_measure(s, t, n, a) {    
    var text = '&nbsp;Distance: ' + Math.round(t*ms.cellsize) + " m. (" + n + " points)";
    var e = document.getElementById("measure");
    if(e) e.innerHTML = text;
  }

  main.setHandler(DBOX_AREA, main_area);
  function main_area(a, d, l, n) {    
    var text = '&nbsp;Area: ' + Math.round(a*ms.cellsize) + " sq. m. Distance: " + Math.round(l*ms.cellsize) +  " m. (" + n + " points)";
    var e = document.getElementById("measure");
    if(e) e.innerHTML = text;
  }

  //
  // Demo Specific Functions: these are associated with the various icons
  // and form controls on the page. You may or may not care about these.
  // 
  function change_scale() {
    var x = (ms.extent[0] + ms.extent[2])/2.0;
    var y = (ms.extent[1] + ms.extent[3])/2.0;
    ms.zoomScale(x, y, document.scaleform.scale.value);
    document.scaleform.scale.value = '';
    return false;
  }

  function pan(direction) {
    domouseclick('pan');
    ms.pan(direction);
  }

  function domouseclick(button) {
    var img;
    var last_active_button;

    last_active_button = active_button;
    active_button = '';
    
    for(var i=0; i<buttons.length; i++)
      domouseout(buttons[i]);    
    
    img = eval("document." + button);
    img.src = config.gpath + "/" + button + '_down.gif';
    
    if(button == 'state') {
      ms.mode = "map";
      ms.setExtent(config.app_extent.minx, config.app_extent.miny, config.app_extent.maxx, config.app_extent.maxy);      
      domouseclick('zoomin');
      close_('animated', 'teste_iframe_animated');      
      if (regiao_select == 1){
	regiao_select = 0;
	gera_dados();
      }
      ms.draw();
    } else if(button == 'info') {
      // document.main.setcursor("hand");	  
      ms.mode = "query";
      main.boxOff();
      active_button = button;
	regiao_select = 0;
	var combo = document.getElementById("taxa_"+arq_map);
      	if (combo) combo.selectedIndex = 1;
	var combo = document.getElementById("poluente_"+arq_map);
      	if (combo) combo.selectedIndex = 0;
	chgCampos(combo);
      	var combo = document.getElementById("campos_co_"+arq_map);
      	if (combo) combo.selectedIndex = 1;
	ms.draw();
      close_('animated', 'teste_iframe_animated');
    } else if(button == 'perfil_vertical') {
      // document.main.setcursor("hand");	  
      ms.mode = "query";
      main.boxOff();
      active_button = button;
      close_('animated', 'teste_iframe_animated');
    } else if(button == 'series_temporais') {
      // document.main.setcursor("hand");	  
      ms.mode = "query";
      main.boxOff();
      active_button = button;
      close_('animated', 'teste_iframe_animated');
	
    } else {
      // document.main.setcursor("crosshair");
      ms.mode = "map";
      if(button == 'zoomin') {
	    ms.zoomdir = 1;            
	    main.boxOn();
	    close_('animated', 'teste_iframe_animated');
      } else if(button == 'zoomout') { 
	    ms.zoomdir = -1;
	    main.boxOff();
            close_('animated', 'teste_iframe_animated');
      } else {
	    ms.zoomdir = 0;
	    main.dragOn();
      }
      active_button = button;
    }
  }  

  function domouseover(button) {
    var img;

    if(button == active_button) return;

    img = eval("document." + button);
    img.src = config.gpath + "/" + button + '_over.gif';
  }

  function domouseout(button) {
    var img;

    if(button == active_button) return;

    img = eval("document." + button);

    img.src = config.gpath + "/" + button + '.gif';
  }  

  function domouseclick_info(button) {
    var img;
    var last_active_button_info;

    last_active_button_info = active_button_info;
    active_button_info = '';
    
    for(var i=0; i<buttons_info.length; i++)
      domouseout_info(buttons_info[i]);    
    
    img = eval("document." + button);
    img.src = config.gpath + "/" + button + '_down.gif';
    
    if(button == 'duv') {
	showDuv();      
    } else if(button == 'anime') {
      animated(ms.extent[0], ms.extent[1], ms.extent[2], ms.extent[3]);      
    } else if(button == 'leg') {
      showLeg('vertical');      
    } else if(button == 'camadas') {
      showCamadas();      
    }    

    //active_button_info = button;
    
  }  

  function domouseover_info(button) {
    var img;

    if(button == active_button_info) return;

    img = eval("document." + button);
    img.src = config.gpath + "/" + button + '_over.gif';
  }

  function domouseout_info(button) {
    var img;

    if(button == active_button_info) return;

    img = eval("document." + button);

    img.src = config.gpath + "/" + button + '.gif';
  }  

  function domouseclick_hour(button, valor) {
    var img;
    var last_active_button;

    last_active_button = active_button_hour;
    active_button_hour = '';
    
    for(var i=0; i<buttons_hour.length; i++)
      domouseout_hour(buttons_hour[i]);    
    
    img = eval("document." + button + "_" + arq_map);

    if (arq_map == "emissoes_queimadas") 
       img.src = config.gpath_bl + "/" + button + '_down.gif';
    else if (arq_map == "emissoes_urbano")
       img.src = config.gpath_bc + "/" + button + '_down.gif';
    else
       img.src = config.gpath_bb + "/" + button + '_down.gif';        

    if (button == "gerar"){
      gera_dados();
    }else{
      choose_date(valor);    
      active_button_hour = button;
    }
    
}  

  function domouseover_hour(button) {

    var img;

    if(button == active_button_hour) return;	
    img = eval("document." + button + "_" + arq_map);

    if (arq_map == "emissoes_queimadas") 
       img.src = config.gpath_bl + "/" + button + '_over.gif';
    else if (arq_map == "emissoes_urbano")
       img.src = config.gpath_bc + "/" + button + '_over.gif';
    else
       img.src = config.gpath_bb + "/" + button + '_over.gif';    
  }

  function domouseout_hour(button) {
    var img;

    if(button == active_button_hour) return;

    img = eval("document." + button + "_" + arq_map);

    if (arq_map == "emissoes_queimadas") 
       img.src = config.gpath_bl + "/" + button + '.gif';
    else if (arq_map == "emissoes_urbano")
       img.src = config.gpath_bc + "/" + button + '.gif';
    else
       img.src = config.gpath_bb + "/" + button + '.gif';
  }

  //
  // Browser specific event handlers
  //
  window.onresize = function() {
    main.sync();  
  }

  window.onload = function() {
    setActiveStyleSheet('qa_azul');      

    main.initialize();

    

    domouseclick('zoomin');

    domouseclick_hour('hour_00h1', 1);
    
    //ms.setLayer('Estados', true);
    //ms.setLayer('Regioes', true);

    MM_preloadImages('images/p_10b.gif','images/p_11b.gif','images/p_09b.gif');

    MM_swapImgRestore();

    MM_swapImage('qa','','images/p_09b.gif',1);

    get_date(arq_map);

   //gera_dados();

    showLeg('vertical');

    Drag.init(document.getElementById("camadas_combo"));

    Drag.init(document.getElementById("legenda_horizontal"));

    Drag.init(document.getElementById("legenda_vertical"));	

    Drag.init(document.getElementById("duvidas")); 

	
    //ms.draw();	
    	
  }
