/*****************************************************************
	Data Calculator Functions

	Written by Alex Prusevich - alex.proussevitch@unh.edu

	Updated January, 2010
******************************************************************/

	/* Global Variables */

var Clc_script = '/cgi-bin/calculations.pl?';
var Calculator_script = '/cgi-bin/calc_graph.pl?';
var Calc_signal_script = '/cgi-bin/calc_signal.pl?sid=';
var Update_Img = new Image(1050,480);
    Update_Img.src = '/images/explorer/wait_calc.gif';
var Not_requested  = '/images/explorer/not_requested.gif';
var calc_map,calc_img,ancor_img,calcMapOptElem,calcMapOptTD,calcMapOptImg;
var calc_status = false;
var PROGRESS;
var barObj;
var sid = 0;

	/* Calculator Functions */

function calculator_expand(swtch) {
  calc_status = swtch;
  var html = calc_status ? Clc_script + mapExtent.to_String(true) + map_options() : "calculator_out.htm";

  DownloadUrl(html, false, function(htmlDoc,responseCode) {
    $("data_calculator").innerHTML = htmlDoc;
    if (calc_status) calc_init();
				// Site specific options
    if (document.URL.indexOf("earthatlas.sr.unh.edu")!=-1) {
      var calc_coord = find_xy($("data_calculator"));
      window.scrollTo(0,calc_coord[1]);
    }
  });
}

function calc_init() {
  calc_map = document.getElementById('calc_map');
  calc_img = document.images['calc_map_img'];
  ancor_img= document.images['calc_map_background'];
  PROGRESS = document.getElementById('progress_bar');
  barObj   =  new progBarObj();
  elem_td  = $('td_opt');
  calcMapOptElem = $('map_options','data_options','color_options');
  calcMapOptTD = $('td_map_opt','td_data_opt','td_color_opt');
  calcMapOptImg= [document.images['img_map_opt'],document.images['img_data_opt'],document.images['img_color_opt']];

  calc_img.onload = function() { PROGRESS.style.visibility = "hidden"; };

  set_table(0);
}

function Set_Calc_Img_Position() {
  var img_coord = find_xy(ancor_img);
  var td_coord  = find_xy(elem_td);

  calc_map.style.left = img_coord[0]+"px";
  calc_map.style.top  = img_coord[1]+"px";
  calc_map.style.visibility = "visible";

  PROGRESS.style.left = img_coord[0]+160+"px";
  PROGRESS.style.top  = img_coord[1]+200+"px";

  for (var i=0; i<calcMapOptElem.length; i++) {
    calcMapOptElem[i].style.left = td_coord[0]+"px";
    calcMapOptElem[i].style.top  = td_coord[1]+"px";
  }
}

function Update(img) {
  img.src = Update_Img.src;
}

function calc_img_reset(butn) {
  butn.form.reset();
  calc_cancel();
  calc_img.src = Not_requested;
}

function Calculate(calc_form) {
  var Equation	= calc_form.equation.value;
  var Equation_i= calc_form.equation_i.value;
  var Average	= calc_form.area_avg.checked ? 1 : 0;
  var Map_min	= calc_form.min.value;
  var Map_max	= calc_form.max.value;
  var Range_min	= calc_form.range_min.value;
  var Range_max	= calc_form.range_max.value;
  var Index = 0; while (calc_form.legend[Index].checked == false) {Index++}
  var Legend	= calc_form.legend[Index].value;
  var Replace	= calc_form.replace.checked ? 1 : 0;
  var Data	= calc_form.to_data.checked ? 1 : 0;
  var Log_scale	= calc_form.log_scale.checked ? 1 : 0;
  var High_res	= (calc_form.high_res.checked) ? "640_480" : "320_240";
      sid	= Math.random().toString().substr(2,9);
  barObj.tsGraph= (Equation_i.indexOf("{}")!=-1) ? true : false;
  var RegExp	= /\+/g;
      Equation	= escape(Equation.replace(RegExp,'PLUS'));
      Equation_i= escape(Equation_i.replace(RegExp,'PLUS'));
  var url	= Calculator_script +  mapExtent.to_String(true) + map_options() +
	"&proj="		+ Map_proj +
	"&equation="		+ Equation +
	"&equation_i="		+ Equation_i +
	"&avg="			+ Average +
	"&replace="		+ Replace +
	"&data="		+ Data +
	"&min="			+ Map_min +
	"&max="			+ Map_max +
	"&range_min="		+ Range_min +
	"&range_max="		+ Range_max +
	"&legend="		+ Legend +
	"&log_scale="		+ Log_scale +
	"&data_dims="		+ High_res +
	"&sym="			+ symObj.str() +
	"&sid="			+ sid;
  Update(calc_img);
  if (calc_form.to_data.checked) {
    window.open(url);
//    window.location = url;
    calc_img.src = Not_requested;
  }
  else {
    calc_img.src = url;
  }
  barObj.start = true;
  setTimeout("barObj.getStatus()",500);
}

function calc_cancel() {
  barObj.tsGraph = false;
  barObj.stop();
  DownloadUrl(Calc_signal_script+sid, false, function(htmlDoc,responseCode) {
//    alert(htmlDoc);
  });
}

function set_table(num) {
  symObj.table = (num == 'U') ? true : false;
  if (num == 'U') num = '0&sym=' + symObj.str();
  var html = Clc_script + 'data_table=' + num;

  DownloadUrl(html, false, function(htmlDoc,responseCode) {
    $('calc_data_table').innerHTML = htmlDoc;
    Set_Calc_Img_Position();
  });
}

/////////////////////////////////////////////////////////
///////////////   Paste-in section   ////////////////////

var eqInput;	// = document.calc.equation;

function set_input(inpt) {
  eqInput = inpt;
}

function paste_function(selct) {
  if (!eqInput) eqInput = document.calc.equation;
  insertAtCaret(eqInput,selct.options[selct.selectedIndex].value);
  selct.selectedIndex = 0;
  eqInput.focus();
}

function paste_symbol(a_sym) {
  if (!calc_status) return false;
  if (!eqInput) eqInput = document.calc.equation;
  insertAtCaret(eqInput,a_sym.innerHTML);
  eqInput.focus();
}

function insertAtCaret(obj, text) {
  if(document.selection) {			// IE part
    obj.focus();
    var orig = obj.value.replace(/\r\n/g, "\n");
    var range = document.selection.createRange();

    if(range.parentElement() != obj) return false;

    range.text = text;

    var actual = tmp = obj.value.replace(/\r\n/g, "\n");

    for(var diff = 0; diff < orig.length; diff++) {
      if(orig.charAt(diff) != actual.charAt(diff)) break;
    }

    for(var index=0,start=0; tmp.match(text) && (tmp=tmp.replace(text, "")) && index<=diff; index=start+text.length) {
      start = actual.indexOf(text, index);
    }
  }
  else if(obj.selectionStart) {			// Firefox/Mozilla part
    var start = obj.selectionStart;
    var end   = obj.selectionEnd;

    obj.value = obj.value.substr(0, start) + text + obj.value.substr(end, obj.value.length);
  }

  if(start == null) {
    var start = 0;
    obj.value = obj.value.substr(0, start) + text + obj.value.substr(end, obj.value.length);
  }

  setCaretTo(obj, start + text.length);
}

function setCaretTo(obj, pos) {
  if(obj.createTextRange) {
    var range = obj.createTextRange();
    range.move('character', pos);
    range.select();
  }
  else if(obj.selectionStart) {
    obj.focus();
    obj.setSelectionRange(pos, pos);
  }
}

/////////////////////////////////////////////////////////
///////////////   Progress Bar Object   /////////////////

function progBarObj() {
  this.topDiv	= $("progress_bar");
  this.barDiv	= $("progress_bar_progress");
  this.pcntDiv	= $("progress_percent");
  this.textDiv	= $("progress_bar_text");

  this.start	= false;
  this.tsGraph	= false;
  this.startTime= null;
  this.Status	= new Array(3);		// (Text, Run Time, Wait Time)
  this.sumTime	= null;			// Run Time + Wait Time
  this.runStep	= 200;			// in milliseconds
  this.checkStep= 4000;			// in milliseconds
  this.Timeout	= new Array(2);
}

progBarObj.prototype.getStatus = function() {
  var pObj = this;
  var num  = Math.random().toString().substr(2,7);	// Avoiding cacheing
  DownloadUrl(Calc_signal_script+sid+'&update=1&num='+num, false, function(htmlDoc,responseCode) {
    if (responseCode == 200) {
      clearTimeout(pObj.Timeout[1]);
      pObj.Status  = htmlDoc.split("\t");
      pObj.Status[1] = Number(pObj.Status[1]); pObj.Status[2] = Number(pObj.Status[2]);
      pObj.sumTime = pObj.Status[1] + pObj.Status[2];
      pObj.setStatus();
    }
  });

  pObj.Timeout[0] = setTimeout(function(){pObj.getStatus()}, pObj.checkStep);
};

progBarObj.prototype.setStatus = function() {
  if (this.Status[0] == "Error") {
    this.stop();
  }
  else if (this.Status[0] == "Done") {
    if (this.tsGraph) Get_CalcTS_Graph(sid);
    this.tsGraph = false;
    this.stop();
  }
  else {
    if (this.start) {
      this.start  = false;
      this.topDiv.style.visibility = "visible";
      var theDate = new Date();
      this.startTime = theDate.getTime()/1000;
    }

    var theDate = new Date();
    var runTime = theDate.getTime()/1000 - this.startTime;
    var runMin  = parseInt(runTime/60);
    var runSec  = parseInt(runTime-runMin*60).toString();
    if (runSec.length == 1) runSec= "0" + runSec;

    var waitMin = parseInt(this.Status[2]/60);
    var waitSec = parseInt(this.Status[2]-waitMin*60).toString();
    if (waitSec.length == 1) waitSec= "0" + waitSec;
    var progress= this.Status[1]/this.sumTime;

    this.textDiv.innerHTML = this.Status[0]+' '+waitMin+':'+waitSec+' ('+runMin+':'+runSec+')';
    this.pcntDiv.innerHTML = parseInt(progress*100)+"%";
    this.barDiv.style.width= (this.topDiv.style.width.replace(/px/,'')-20)*progress+"px";

    this.Status[1]  = Math.min(this.Status[1]+this.runStep/1000, this.sumTime);
    this.Status[2]  = Math.max(this.Status[2]-this.runStep/1000, 0);

    var pObj = this;
    pObj.Timeout[1] = setTimeout(function(){pObj.setStatus()}, pObj.runStep);
  }
};

progBarObj.prototype.stop = function() {
  var pObj = this;
  clearTimeout(pObj.Timeout[0]);
  clearTimeout(pObj.Timeout[1]);
  this.topDiv.style.visibility = "hidden";
};

/////////////////////////////////////////////////////////
///////////////   Map Options Section   ////////////////
var calcMapOptStatus = [false,false,false];
var calcMapOptColor  = ["#FFF0F0","pink"];
var expandImg = [new Image(14,14),new Image(14,14)];
expandImg[0].src = "/images/icons/category_collapsed.gif";
expandImg[1].src = "/images/icons/category_expanded.gif";

function calcMapOptions(ind) {
  for (var i=0; i<calcMapOptElem.length; i++) {
    if (i != ind) {
      calcMapOptElem[i].style.visibility = "hidden";
      calcMapOptStatus[i] = false;
      calcMapOptTD[i].style.backgroundColor = calcMapOptColor[0];
      calcMapOptImg[i].src = expandImg[0].src;
    }
  }

  if (calcMapOptStatus[ind]) {
    calcMapOptStatus[ind] = false;
    elem_td.style.width = "1px";
    calcMapOptElem[ind].style.visibility = "hidden";
    calcMapOptTD[ind].style.backgroundColor = calcMapOptColor[0];
    calcMapOptImg[ind].src = expandImg[0].src;
  }
  else {
    calcMapOptStatus[ind] = true;
    elem_td.style.width = "260px";
    calcMapOptElem[ind].style.visibility = "visible";
    calcMapOptTD[ind].style.backgroundColor = calcMapOptColor[1];
    calcMapOptImg[ind].src = expandImg[1].src;
  }
}

/////////////////////////////////////////////////////////
///////////   Calculator Graph Page Section   ///////////
var calc_ts_graph_win = 0;
var calc_windowName,calc_params,calc_ts_graph_url;


function Get_CalcTS_Graph(id) {

		// Open a window for the Graph
  calc_windowName   = "Calc_TS_Graph";
  calc_params = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=700,height=700";
  calc_ts_graph_url = "/cgi-bin/graph_page.pl?sid="+id;

  if ((calc_ts_graph_win) && (!calc_ts_graph_win.closed)) calc_ts_graph_win.focus();
  setTimeout("calc_ts_graph_win = window.open(calc_ts_graph_url, calc_windowName , calc_params);",200);
}

/////////////////////////////////////////////////////////
