// JavaScript Document

// Cross-browser implementation of element.addEventListener()
// link: http://snipplr.com/view/561/add-event-listener/
function addListener(element, type, expression, bubbling)
{
	bubbling = bubbling || false;
	if(window.addEventListener) { // Standard
		element.addEventListener(type, expression, bubbling);
		return true;
    } else if(window.attachEvent) { // IE
		element.attachEvent('on' + type, expression);
		return true;
    } else return false;
}

/**
 * Formata texto para decimal 
 *
 * @param string text
 */
function formatCoord(text) {

	text = text.replace( /^\s*|\s*$/g, "" );
	text = text.replace( /,/g, "." );
	text = text.replace( /[a-zA-Z;\-_]|([.]$)/g, "" );
	text = text.replace( /[.]+/g, "." );
	if( text.length == "") {
		text = 0;
	}
	text = parseFloat( text );
	
//	var pattern = new RegExp(/(\d+\.?\d+)/g);
//	var result = pattern.exec(text);

	return text;		
}


function clearInputs(form_id) {
	var form = document.getElementById(form_id);
	var input = form.getElementsByTagName('input');
	var iselect = form.getElementsByTagName('select');
	for (var i=0; i < input.length; i++) {
		if ( input[i].type == 'text' ) {
			input[i].value = '';
		}
	}
	for (var i=0; i < iselect.length; i++) {
		iselect[i].selectedIndex = 0;
	}
}


function writeEmail( name, domain ) {
	var mail = name + "&#064;" + domain;
	document.write( '<a href="#" onclick="javascript:window.location=\'&#109;&#097;&#105;&#108;&#116;&#111;:' + mail + '\'">' + mail + '</a>' );
}


/**
 * Controle de formulário de entrada de coordenadas geográficas 
 *
 * @param string decimal - id da tag referente aos valores em graus decimais
 * @param string polar - id da tag referente aos valores em graus
 */
function inputCoord( decimal, polar ) {
	this.decimal = document.getElementById(decimal);
	this.polar = document.getElementById(polar);
	this.setInputFormat( 1 );
	this.changeInputFormat();
}

/**
 * Define o formato de entrada de dados de coordenadas a ser exibido
 *
 * @param int value - 1:decimal | 0:polar 
 * @param string decimal - input|tag referente ao formato decimal
 * @param string polar - input|tag referente ao formato polar
 */
inputCoord.prototype.setInputFormat = function ( value ) {
	var value = parseInt( value );
	this.decimal.style.display = ( value )? "inline": "none";
	this.polar.style.display = ( !value )? "inline": "none";
}


/**
 * Atribui o valor convertido de formato para outro com o event handler 'onblur'
 *
 * @param string decimal - input|tag referente ao formato decimal
 * @param string polar - input|tag referente ao formato polar
 */
inputCoord.prototype.changeInputFormat = function () {
	var polar = this.polar.getElementsByTagName("input");
	var decimal = this.decimal;
	
	var polar_len = polar.length;
	
	for ( var i=0; i < polar_len; i++ ) 
	{		
		polar[i].onblur = function() {
			
			polar[0].value = formatCoord( polar[0].value );
			polar[1].value = formatCoord( polar[1].value );
			polar[2].value = formatCoord( polar[2].value );
			decimal.value =  parseFloat( polar[0].value ) + parseFloat( polar[1].value )/ 60 + parseFloat( polar[2].value ) / 3600;			
		}
	}
	
	decimal.onblur = function() {
		
		decimal.value = formatCoord( decimal.value );
		
		var resto;
		polar[0].value = Math.floor( decimal.value );
		resto = decimal.value - polar[0].value;
		polar[1].value = Math.floor( resto * 60 );
		resto -= polar[1].value / 60; 
		polar[2].value = Math.floor( resto * 3600 );
	}
}

/**
 * Converte uma texto XML em HTML aplicando uma transformação XSL
 *
 * @param string container - id da tag de envelope
 * @param string xmlstr - texto XML 
 * @param string xsldoc - nome do documento XSL
 */
function getHTML ( container, xmlstr, xsldoc ) {
	
   	var div = document.getElementById( container );
	var xml_doc = parseXML( xmlstr );
	
    // Get the XSLT from the server.
    ajax = new Ajax( xsldoc, "", "GET", null);
    ajax.setAsync (false);
    ajax.request ();
    var xsl_doc = ajax.req.responseXML;

    // Use object detection to find out if we have
    // Firefox/Mozilla/Opera or IE XSLT support.

    if (typeof XSLTProcessor != "undefined") {
        var xsl_proc = new XSLTProcessor ();
        xsl_proc.importStylesheet (xsl_doc);
        var node = xsl_proc.transformToFragment (xml_doc, document);
        div.innerHTML = "";
        div.appendChild (node);
		
    }
    else if (typeof xml_doc.transformNode != "undefined") {
        div.innerHTML = xml_doc.transformNode (xsl_doc);
    }
    else {
        div.innerHTML = "XSLT não é suportada no navegador.";
    }
}

/**
 * Converte uma texto XML em HTML aplicando uma transformação XSL
 *
 * @param string xmlstr - texto XML 
 * @param string wrapper - id da tag de envelope
 * @param string xsldoc - nome do documento XSL
 */
function transformXML ( xmlstr, xsldoc ) {

	var xml_doc = parseXML( xmlstr );
	
    // Get the XSLT from the server.
    ajax = new Ajax( xsldoc, "", "GET", null);
    ajax.setAsync (false);
    ajax.request ();
    var xsl_doc = ajax.req.responseXML;

	// Create temporary node
//	var newel=document.createElement("div");
//	var nbody =document.getElementsByTagName("body")[0];
//	newel = nbody.appendChild(newel); 
	
    // Use object detection to find out if we have
    // Firefox/Mozilla/Opera or IE XSLT support.

    if (typeof XSLTProcessor != "undefined") {
        var xsl_proc = new XSLTProcessor ();
        xsl_proc.importStylesheet (xsl_doc);
			  
  		// XMLSerializer exists in current Mozilla browsers
       	var node = xsl_proc.transformToDocument ( xml_doc );		
		var serializer = new XMLSerializer();
		var serialized = serializer.serializeToString( node );
		return serialized;
    }
    else if (typeof xml_doc.transformNode != "undefined") {
		return ( xml_doc.transformNode (xsl_doc) );
    }
    else {
		return false;
    }
}


/**
 * Classe de consulta via Ajax de dados de fontes renováveis
 *
 */
function DataRen() {
	this.coord;
	this.stringXML = "";
	this.dataOutput;
	this.divchart; 
	this.chartId = new Array();
}

/**
 * Define coordenadas geográficas para consulta
 *
 * @param array coord - [latitude,longitude]
 *
 * @return array
 */
DataRen.prototype.setCoord = function( coord ) {
	this.coord = coord;
	return coord;
}

/**
 * Exibe da consulta resultado em HTML
 *
 * @param string container - id do elemento HTML que exibe a resultado
 * @param string xsldoc - caminho do arquivo de XSLT
 */
DataRen.prototype.render = function( container, xsldoc ) {
	this.dataOutput = container;
	// XSLT padrão
	if( !xsldoc ) {
		xsldoc = "xsl/default.xsl";
	}
	// Exibe html na tag de Id CONTAINER
	getHTML ( container, this.stringXML, xsldoc );
}

/**
 * Cria gráfico
 *
 * @param string container - id do elemento HTML que exibe o gráfico
 * @param string type - tipo do gráfico
 * @param string chartid
 *
 * @ return string - chartid
 */
DataRen.prototype.createChart = function( container, type, chartid ) {
	// Aplica uma transformação 
	var xmlchart = transformXML( this.stringXML, "xsl/chart.xsl" );
	
	// Tipo de gráfico
	type = type || "line";	
	var chartname = new Array();
	chartname["line"] = "Line";
	chartname["column"] = "Column2D";
	chartname["area"] = "Area2D";
	chartname["bar"] = "Bar2D";
	
	// Chart Id
	if( chartid == "undefined" ) {
		chartid = "chart" + this.chartId.length + "Id";
	}
	
	// Cria gráfico
	var chart = new FusionCharts("../FusionCharts/FusionCharts/FCF_MS" + chartname[ type ] +".swf", chartid, "600", "450");				
	chart.setDataXML( xmlchart );
	chart.render( container );	
	this.divchart = container;
	
	this.chartId.push( chartid );
	
	return chartid;
}

/**
 * Atualiza a string XML do gráfico
 *
 * @param string chartid - id do gráfico
 * @param string xmlstr 
 */
DataRen.prototype.updateChart = function( chartid, xmlstr ){
      //using updateChartXML method defined in FusionCharts JavaScript class
      updateChartXML( chartid, xmlstr);
}

/**
 * Consulta de dados por coordenadas geográficas via Ajax
 */
DataRen.prototype.getDataByCoord = function () {
	var instanceOf = this;
	var coord = this.coord;
	
	var param= "?longitude="+coord['longitude']+"&latitude="+coord['latitude'];
	param += "&task=ajax";
	param += "&rid="+Math.random();

    // Get the XML file from the server.
	var xmlstr;
    var ajax = new Ajax
				( "index.php",
				 param,
				 "GET",
				 function (req) {
					var xmlstr = req.responseText;
					instanceOf.stringXML = xmlstr;
	
					// Cria tabela 
					instanceOf.render("data_output");
					// Cria Gráfico
					instanceOf.createChart("chartdiv_recurso_eolico", "column");
					window.location = '#data';
				}
				 );
	ajax.request ();
}


function formValidation() {
	
	var form = document.dataForm;
	var latitude = ( form.hemi_lat.value == 0 )? -form.latitude_dec.value : form.latitude_dec.value;
	var longitude = -form.longitude_dec.value;
	
	// do field validation
	if (latitude == '' || longitude == '') {
		return alert ( "Os valores válidos de latitude devem estar na faixa de 12° Norte e 40° Sul e de longitude na faixa de 30° Oeste e 80° Oeste" );
	}
	
	//Limites de busca
	//Latitude: [-40:12]
	if (latitude < -40 || latitude > 12 ) {
		return alert ( "Os valores de Latitude devem estar na faixa de 12° Norte e 40° Sul" );
	}
	//Longitude: [80:30]
	if (longitude < -80 || longitude > -30 ) {
		return alert ( "Os valores de Longitude devem estar na faixa de 30° Oeste e 80° Oeste" );
	}
	
	form.latitude.value = latitude;
	form.longitude.value = longitude;

	var coord = new Array();
	coord['longitude'] = parseFloat(longitude);
	coord['latitude'] = parseFloat(latitude);
	return coord;	
}

// Envio de formulário

function submitform()
{
	if (typeof document.dataForm.onsubmit == "function") {
		document.dataForm.onsubmit();
	}
	document.dataForm.submit();
}

function submitButton()
{
	if (formValidation()) {	
		submitform();
	}
}

function ajaxSubmitButton()
{
	return getDataByCoord( formValidation() );
}



 


var allChecked = true;
/**
 * Marca todas a checkboxes 'cid[]'
 */
function checkAll(data_id, tagname) {
	var inputs = document.getElementsByName(tagname);
	allChecked = !allChecked;
	for (var i=0; i < inputs.length; i++) {
		inputs[i].checked = allChecked;
		updateChart(data_id, inputs[i].value, inputs[i].checked );
	}
	//return false;
}

