/**
 * caderiego.js: data input dialog for irrigation calculation,
 *               part of the CadeMET project.
 *
 * by Eduardo Hernando Izcara. Copyright 2009 agroGEX.
 */
// ------------------------------------------------------------------------

// Make sure we haven't already been loaded
var CadeRiego;
if (CadeRiego && (typeof CadeRiego != "object" || CadeRiego.NAME))
{
	throw new Error("Namespace 'CadeRiego' already exists");
}

// Create our namespace, and specify some meta-information
CadeRiego = {};
CadeRiego.NAME = "CadeRiego";   // The name of this namespace
CadeRiego.VERSION = 1.0;        // The version of this namespace

// Algunas variables globales del namespace:
//
CadeRiego.inputDialogo = {};
// en lo siguiente, el array de 'eficiencia' se corresponde con el de 'sistema':
CadeRiego._calc_data = { cultivo:['crz','mnz'], sistema:['asp','loc','sup'], eficiencia:['0.8','0.9','0.5'] };
CadeRiego._wait = {};
CadeRiego._codstat = 0;
// ------------------------------------------------------------------------

CadeRiego.necesidades_init = function(contenedores)
{
	CadeRiego._wait = Rutinas.createWaitPanel();
	CadeRiego._codstat = Rutinas.getVar('codstat','header-rpt');

	var seleccionado = function(e)
	{
		var targ;
		if (!e) var e = window.event;
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;
		if (targ.nodeType == 3) // defeat Safari bug
			targ = targ.parentNode;

		CadeRiego._codstat = targ.value;
		CadeRiego.necesidades_tbl(contenedores.tabla);

		// actualización vía Ajax de algunos textos
		var url = Rutinas.baseUrl() + "/riego/necesidadesdata/format/json/cod_station/" + targ.value;
		var callback =
		{ 
			success: function(o) {
						var json_data = eval( "(" + o.responseText + ")" );
						Rutinas.setHTML(json_data.datos.nombre, 'nombre', 'riego-necesidades');
						Rutinas.setHTML(json_data.datos.altitud, 'altitud', 'riego-necesidades');
						Rutinas.setHTML(json_data.datos.latitud, 'latitud', 'riego-necesidades');
					 },
			failure: function(o) {}
		};
		YAHOO.util.Connect.initHeader('X_REQUESTED_WITH', 'XMLHttpRequest');
		YAHOO.util.Connect.asyncRequest('GET', url, callback);
	}

	var datos_changed = function(e)
	{
		CadeRiego.necesidades_tbl(contenedores.tabla);
	}

	var selector = YAHOO.util.Dom.getElementBy(function(el){return el.name=='sel-estacion';}, 'select', 'stats-selection');
	YAHOO.util.Event.addListener(selector, 'change', seleccionado);

	var change_datos = YAHOO.util.Dom.getElementBy(function(el){return el.name=='submitbutton';}, 'input', 'datos-select');
	YAHOO.util.Event.addListener(change_datos, 'click', datos_changed);

	// ............................................................................
	// se actualizan los campos 'select' del formulario de datos de cálculo:
	var _act_select = function(sel,val) {
		for (var i = 0; i < sel.length; i++) {
			if (sel.options[i].value == val) { sel.selectedIndex = i; break; }
		}
	}
	_act_select(YAHOO.util.Dom.getElementBy(function(el){return el.name=='sel-riego-desde';}, 'select', 'datos-select'), Rutinas.getVar('numdias', 'datos-select'));
	_act_select(YAHOO.util.Dom.getElementBy(function(el){return el.name=='sel-riego-cultivo';}, 'select', 'datos-select'), Rutinas.getVar('cultivo', 'datos-select'));
	_act_select(YAHOO.util.Dom.getElementBy(function(el){return el.name=='sel-riego-sistema';}, 'select', 'datos-select'), Rutinas.getVar('sistema', 'datos-select'));
	// ............................................................................

	CadeRiego.necesidades_tbl(contenedores.tabla);
	//CadeRiego.necesidades_res(contenedores.total);
}
// ------------------------------------------------------------------------

CadeRiego.necesidades_tbl = function(contenedor)
{
	CadeRiego._wait.show();

	// sacamos datos de cálculo directamente de los campos de formulario
	var numdias = YAHOO.util.Dom.getElementBy(function(el){return el.name=='sel-riego-desde';}, 'select', 'datos-select').value;
	var cultivo = YAHOO.util.Dom.getElementBy(function(el){return el.name=='sel-riego-cultivo';}, 'select', 'datos-select').value;
	var sistema = YAHOO.util.Dom.getElementBy(function(el){return el.name=='sel-riego-sistema';}, 'select', 'datos-select').value;

	var url = Rutinas.baseUrl() + "/riego/necesidadesget" +
			"/cod_station/" + CadeRiego._codstat +
			"/numdias/" + numdias +
			"/cultivo/" + CadeRiego._calc_data.cultivo[cultivo] +
			"/sistema/" + CadeRiego._calc_data.sistema[sistema] +
			"/id/" + Math.random(1);
	//alert(url);

	var jsonData = new YAHOO.util.DataSource(url);
	jsonData.responseType = YAHOO.util.DataSource.TYPE_JSON;
	jsonData.responseSchema =
	{ 
		resultsList: "ResultSet.Result",
		fields: [ "fecha",
			{key: "eto", parser: "number"},
			{key: "kc", parser: "number"},
			{key: "etc", parser: "number"},
			{key: "pe", parser: "number"} ]
	};

	// ....................................................................
	// Esto es para cerrar la barra de progreso cuando la consulta ha ido bien,
	// y se aprovecha también para totalizar algunas cosas:
	var ETc_tot = 0.0;
	var Pe_tot = 0.0;
	var Riego_tot = 0.0;
	jsonData.doBeforeCallback = function(oRequest, oFullResponse, oParsedResponse, oCallback)
	{
		var res = oParsedResponse.results;
		for (var i = 0; i < res.length; i++) {
			ETc_tot += res[i].etc.valueOf();
			Pe_tot += res[i].pe.valueOf();
		}
		Riego_tot = (ETc_tot-Pe_tot)/CadeRiego._calc_data.eficiencia[sistema].valueOf();
		if (Riego_tot < 0) Riego_tot = 0;
		// tabla de totales para el periodo:
		Rutinas.setHTML(YAHOO.util.Number.format(ETc_tot,{decimalPlaces:2,decimalSeparator:','}), 'tot-etc', 'tot-necesidades');
		Rutinas.setHTML(YAHOO.util.Number.format(Pe_tot,{decimalPlaces:2,decimalSeparator:','}), 'tot-pe', 'tot-necesidades');
		Rutinas.setHTML(CadeRiego._calc_data.eficiencia[sistema], 'tot-ef', 'tot-necesidades');
		Rutinas.setHTML(YAHOO.util.Number.format(Riego_tot,{decimalPlaces:2,decimalSeparator:','}), 'tot-riego', 'tot-necesidades');

		CadeRiego._wait.hide();
		return oParsedResponse;
	}
	// ....................................................................

	// Formataje de fechas
	var myCellDateFormat = function(elCell, oRecord, oColumn, oData) {
		elCell.innerHTML = YAHOO.util.Date.format(new Date(oData.replace(/-/g,"/")), {format:"%d-%b-%Y"}, "es_ES").toString();
	};

	// ....................................................................
	// Formataje de números; la cifra al final del nombre es el número de decimales
	var myNumberFormat_1 = function(elCell, oRecord, oColumn, oData) {
		elCell.innerHTML = YAHOO.util.Number.format(oData, {decimalPlaces:1, decimalSeparator:','});
	};
	var myNumberFormat_2 = function(elCell, oRecord, oColumn, oData) {
		elCell.innerHTML = YAHOO.util.Number.format(oData, {decimalPlaces:2, decimalSeparator:','});
	};
	// ....................................................................

	var myColumnDefs = [ {key: "fecha", label: "Fecha", formatter: myCellDateFormat},
						 {key: "eto", label: "ETo (mm)", formatter: myNumberFormat_2},
						 {key: "kc", label: "Kc", formatter: myNumberFormat_2},
						 {key: "etc", label: "ETc (mm)", formatter: myNumberFormat_2},
						 {key: "pe", label: "Pe (mm)", formatter: myNumberFormat_2} ];

	var myDataTable = new YAHOO.widget.DataTable(contenedor, myColumnDefs, jsonData);
}
// ------------------------------------------------------------------------

CadeRiego.createInputDialogo = function()
{
	var handleSuccess = function(o) {
		var json_data = eval( "(" + o.responseText + ")" );

		var url = Rutinas.baseUrl() + "/riego/necesidades" +
				"/cod_station/" + CadeStations.SelectedStat.cod +
				"/numdias/" + json_data.datos.numdias +
				//"/cultivo/" + CadeRiego._calc_data.cultivo[json_data.datos.cultivo] +
				//"/sistema/" + CadeRiego._calc_data.sistema[json_data.datos.sistema] +
				"/cultivo/" + json_data.datos.cultivo +
				"/sistema/" + json_data.datos.sistema +
				"/id/" + Math.random(1);
		//alert(url);
		window.open(url);
	};
	var handleFailure = function(o) {};

	var handleSubmit = function() { this.submit(); };
	var handleCancel = function() { this.cancel(); };

	document.getElementById("riego-dialogo").style.position = "relative";
	CadeRiego.inputDialogo = new YAHOO.widget.Dialog("riego-dialogo",
			{ width:"340px",
			  //fixedcenter:true,
			  xy:[560,460],
			  visible:false,
			  modal:true,
			  constraintoviewport:true,
			  buttons:[	{text:"Enviar", handler:handleSubmit, isDefault:true},
						{text:"Cancel", handler:handleCancel} ]
			});

	CadeRiego.inputDialogo.callback = { success: handleSuccess, failure: handleFailure };
	CadeRiego.inputDialogo.render();
}
// ------------------------------------------------------------------------

CadeRiego.inputLaunch = function()
{
	//Rutinas.setHTML("", 'riego-dialogo-result');
	CadeRiego.inputDialogo.show();
}
// ------------------------------------------------------------------------

