// JavaScript Document

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;		
}


	/**
	 * 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
	 */
	function setInputFormat(value, decimal, polar) {
		var decimal = document.getElementById(decimal);
		var polar = document.getElementById(polar);
		if (value == 1) {
			decimal.style.display = "inline";
			polar.style.display = "none";
		} else {
			decimal.style.display = "none";
			polar.style.display = "inline";
		}
	}
		
	/**
	 * 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
	 */
	function changeInputFormat(decimal, polar) {
		var polar = document.getElementById(polar).getElementsByTagName("input");
		var decimal = document.getElementById(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 );
		}
	}


var orderby=new Array('localidade', 'uf', 'longitude', 'latitude', 'distancia', 'jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez', 'media');

function getHTML( text, div_name ) {
    var div = document.getElementById (div_name);
	
	var xml_doc = parseXML( text );
	
    // Get the XSLT from the server.

    ajax = new Ajax("sundata/xsl/ajax.xsl", "", "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 not supported in browser.";
    }
}


function showSunData( coord, div_name ) {
	
	if ((coord['longitude'] == '') || (coord['latitude'] == ''))
  	{
  	document.getElementById(tag_wrap).innerHTML="";
  	return;
  	}
 
	var param= "?longitude="+coord['longitude']+"&latitude="+coord['latitude'];
	param += "&task=ajax";
	param += "&rid="+Math.random();

    // Get the XML file from the server.
	  
    var ajax = new Ajax
				( "sundata/index.php",
				 param,
				 "GET",
				 function (req) {
					getHTML( req.responseText, div_name );
	//				var st = new sortTable("tb_sundata");
					goSetDimensions();
					window.location = '#sundata';
				}
				 );
    ajax.request ();

}





function submitform()
{
	if (typeof document.sundataForm.onsubmit == "function") {
		document.sundataForm.onsubmit();
	}
	document.sundataForm.submit();
}

function formValidation() {
	
	var form = document.sundataForm;
	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;

// Ajax:
	var coord = new Array();
	coord['longitude'] = parseFloat(longitude);
	coord['latitude'] = parseFloat(latitude);
	
	return coord;	
}

function submitbutton()
{

	if (formValidation()) {	
		submitform();
	}
}


function ajaxSubmitButton()
{
	
	showSunData( formValidation(), 'sundata_output' );
}

/**
 * Marca todas a checkboxes 'cid[]'
 */
function checkAll(data_id, tagname) {
	var inputs = document.getElementsByName(tagname);
	allChecked[data_id] = !allChecked[data_id];
	for (var i=0; i < inputs.length; i++) {
		inputs[i].checked = allChecked[data_id];
		updateChart(data_id, inputs[i].value, inputs[i].checked );
	}
	//return false;
}