// Meters per second to miles per hour conversion.
var mps2mph = 2.23693629;

var nodes = [];

var secondary;
var f5_f9_str = "F5/F9, Green: < 30 mph; Yellow: 30-40 mph (point away from wind); Red: > 40 MPH (possibly close)";
var f15_str = "F15, Green: < 30 mph; Yellow: 30-35 mph (point away from wind); Red: > 35 MPH (close)";

var ts = 0;

// "top" div locations in pixels.
var tops = [];
tops.vaisala3_deg = 382;
tops.vaisala3_mph = 397;

tops.vaisala4_deg = 75;
tops.vaisala4_mph = 90;

tops.young_deg = 382;
tops.young_mph = 397;

tops.mount_alt = 260;
tops.mount_az = 275;

var n = (new Date()).getTime()/1000;
var vaisala3_timestamp = n;
var vaisala4_timestamp = n;
var young_timestamp = n;

var ajax = null;
var ajax_limit= 10000; // In milliseconds
var timer;
var timer_interval = 1000;  // In milliseconds
var url ="/engineering/mini2json.php";

// Add Vaisala4 when it has returned from the shop.
var param_str = "miniserver=YOUNG&miniserver2=VAISALA3&miniserver3=VAISALA4&miniserver4=HEXAPOD_MINI";
var web_id = (new Date()).getTime();
var params = param_str + "&web_id=" + web_id;

/* The ids of HTML elements to be assigned to DOMNode instances. */
/* The keys of data (and divs) to be updated. */
var assign_ids = ['vaisala3_deg',
                  'vaisala3_mph',
                  'vaisala3_update',
                  'vaisala4_deg',
                  'vaisala4_mph',
                  'vaisala4_update',
                  'young_deg',
                  'young_mph',
                  'young_update',
                  'mount_alt',
                  'mount_az'
                  ];

var pts_x = [    10,  20, 25, 62, 67, 75, 75, 70, 68, 50, 48, 40, 40, 30, 30, 10,  10 ];
var pts_y = [   11, 11,   3,   3, 11, 11, 65, 65, 67, 67, 65, 65, 70, 70, 65, 65, 11];


var image_path = "rotator.php?ang=";
var mount_path = "rotator.php?color=yellow&pivot=white&ang=";
// var image_path = "/python/rotator.py/draw?ang=";
var building_path = "/src/php/polyline.php?width=85&height=85&r=255&g=0&b=255";

if (pts_x.length == pts_y.length) { 
   building_path += "&pts_x="  
   for (var i = 0; i < pts_x.length; i++) {
      building_path += pts_x[i];  
      if (i < pts_x.length - 1) {
         building_path += ",";
      }
   }
   building_path += "&pts_y="  
   for (var i = 0; i < pts_y.length; i++) {
      building_path += pts_y[i] + 5;  
      if (i < pts_y.length - 1) {
         building_path += ",";
      }
   }  
}
building_path += "&rotate=";

function start () {
   nodes.vaisala3 = document.getElementById('vaisala3');
   nodes.vaisala4 = document.getElementById('vaisala4');
   nodes.young = document.getElementById('young');
   nodes.building = document.getElementById('building');
   nodes.mount_orientation = document.getElementById('mount_orientation');
   nodes.background_image = document.getElementById('background_image');
   assign();  
   requester();
   timer = window.setInterval(requester, timer_interval);    
}

function stop() {
   if ( timer ) {
      window.clearInterval(timer);
   }
   timer = null;
}

/*  Assign DOMNodes instances. */
function assign() {
   for (var i = 0; i < assign_ids.length; i++ ) {
      var index = assign_ids[i];	
      nodes[index] = new DOMNode( index );
   }
}

function requester() {
   /* Check if ajax has stalled. */
   if ( ajax != null && ajax.stalled()) {  
      ajax = null;
   }
   /* Create a new ajax instance, if needed. */
   if ( ajax == null ) {
      ajax = new ajaxObject(url);
      ajax.callback = function(responseText,responseStatus) {
         if(responseStatus==200 && repaint) {
            repaint( eval('(' + responseText + ')') );
         } 
      }
   }
   ajax.update(params, 'POST'); 
}

function do_deg(data, index, node) {
   if (isset(data[index])) {
      nodes[node].text(Math.round(data[index]) + " deg");

      if (index == "vaisala3_average_wind_direction") {
         if (data[index] > 90 && data[index] < 270) {
            // Shift up 45 pixels so that text doesn't block needle.
            //  Note that we MUST add the units, e.g., "px" for
            //  the "top" CSS coordinate.
            nodes.vaisala3_deg.top((tops.vaisala3_deg - 45) + "px");
            nodes.vaisala3_mph.top((tops.vaisala3_mph - 45) + "px");
         } else {
            nodes.vaisala3_deg.top(tops.vaisala3_deg + "px");         
            nodes.vaisala3_mph.top(tops.vaisala3_mph + "px");         
         }      
      } else if (index == "vaisala4_average_wind_direction") {
         if (data[index] > 90 && data[index] < 270) {
            nodes.vaisala4_deg.top((tops.vaisala4_deg - 45) + "px");
            nodes.vaisala4_mph.top((tops.vaisala4_mph - 45) + "px");
         } else {
            nodes.vaisala4_deg.top(tops.vaisala4_deg + "px");         
            nodes.vaisala4_mph.top(tops.vaisala4_mph + "px");         
         }      
      }  else if (index == "young_wind_direction") {
         if (data[index] > 90 && data[index] < 270) {
            nodes.young_deg.top((tops.young_deg - 45) + "px");
            nodes.young_mph.top((tops.young_mph - 45) + "px");
         } else {
            nodes.young_deg.top(tops.young_deg + "px");         
            nodes.young_mph.top(tops.young_mph + "px");         
         }      
      }
   }
}

function do_mph(data, index, node) {
   if (isset(data[index])) {
      var speed_mph = Math.round(data[index] * mps2mph);
      var txt = speed_mph + " mph";
      nodes[node].text(txt);
      // Changing the background color, based on wind speed.
      //  For F15: Gusts above 30 you must point away from wind, gusts over 35 you must close.
      // http://mmtao.org/wiki/doku.php?id=mmtao:procedures:ngs_operating
      //  For F5 and F9:  Sustained winds above 30 you must point away from wind, sustained winds over 40 you must close.
      // http://www.mmto.org/misc/weather.pdf
      if ( speed_mph >= 35 && isset(secondary) && secondary == "f15" ) {
         nodes[node].error();
      } else if ( speed_mph >= 40) {
         nodes[node].error();
      } else if ( speed_mph >= 30) {
         nodes[node].warn();
      } else {
         nodes[node].ok();
      }
      
   }
}

/* Update function for web page.  */
function repaint(d) {
   var img;
   var str;
   var now;
   if (isset(d.webserver_timestamp)) {
      now = d.webserver_timestamp;
      ts = d.webserver_timestamp;
   } else {
      now = ts;
   }
   
   // Getting the secondary information.
   if (isset(d.secondary)) {
      secondary = d.secondary;
      if (secondary == "f15") {
         str = f15_str;
      } else {
         str = f5_f9_str;
      }
      nodes.background_image.title = str;
   }
   
   do_deg(d,'young_wind_direction','young_deg');
   do_mph(d,'young_wind_speed','young_mph');
   do_deg(d,'vaisala3_average_wind_direction','vaisala3_deg');
   do_mph(d,'vaisala3_average_wind_speed','vaisala3_mph');
   
   // Creating random data for Vaisala4 for now.
   // d.vaisala4_average_wind_direction = Math.random() * 360;
   // d.vaisala4_average_wind_speed = Math.random() * 20;
   // d.vaisala4_average_wind_direction = 0;
   // d.vaisala4_average_wind_speed = 0;
   
   do_deg(d,'vaisala4_average_wind_direction','vaisala4_deg');
   do_mph(d,'vaisala4_average_wind_speed','vaisala4_mph');
   
   if (isset(d.young_wind_direction)) {
      img = image_path + Math.round(d.young_wind_direction); 
      nodes['young'].src = img;
   }
   
   if (isset(d.vaisala3_average_wind_direction)) {
      img = image_path + Math.round(d.vaisala3_average_wind_direction); 
      nodes['vaisala3'].src = img;
   }
   
   if (isset(d.vaisala4_average_wind_direction)) {
      img = image_path + Math.round(d.vaisala4_average_wind_direction); 
      nodes['vaisala4'].src = img;
   }
   
   if (isset(d.abs_el)) {
      var alt = d.abs_el;
      var txt = "Alt: " + alt;
      nodes.mount_alt.text(txt);
   }
   
   if (isset(d.abs_az)) {
       // d.abs_az = 330;
       nodes.mount_orientation.src = mount_path + Math.round(d.abs_az);
       nodes.building.src = building_path + Math.round(d.abs_az);
       // nodes.building.src = building_path + "45";
      //alert(building_path);

      var az = d.abs_az;
      var txt = "Az: " + az;
      nodes.mount_az.text(txt);
   
      if (Math.round(d.abs_az) > 90 && Math.round(d.abs_az) < 270) {
         nodes.mount_alt.top((tops.mount_alt - 60) + "px");
         nodes.mount_az.top((tops.mount_az - 60) + "px");
      } else {
         nodes.mount_alt.top(tops.mount_alt + "px");         
         nodes.mount_az.top(tops.mount_az + "px");         
      }      
   }
   
   if (isset(d.young_timestamp)) {
      nodes.young_update.toDateTime(d.young_timestamp);
      young_timestamp = d.young_timestamp;
   }
   if (now - young_timestamp < 60) {
      nodes.young_update.ok();
   } else {
      nodes.young_update.error();            
   }
   
   if (isset(d.vaisala3_timestamp)) {
      nodes.vaisala3_update.toDateTime(d.vaisala3_timestamp);
      vaisala3_timestamp = d.vaisala3_timestamp;
   }
   if (now - vaisala3_timestamp < 60) {
      nodes.vaisala3_update.ok();
   } else {
      nodes.vaisala3_update.error();            
   }
   
   if (isset(d.vaisala4_timestamp)) {
      nodes.vaisala4_update.toDateTime(d.vaisala4_timestamp);
      vaisala4_timestamp = d.vaisala4_timestamp;
   }
   if (now - vaisala4_timestamp < 60) {
      nodes.vaisala4_update.ok();
   } else {
      nodes.vaisala4_update.error();            
   }
}

function isset( variable ) { return ( typeof (variable) != 'undefined' ); } 
function isnull( variable ) { return ( variable == null ); } 
