// JavaScript Document
/************** AJAX ************************/
var _sqlDebug = false;
var _janelaSqlDebug;

function getHTTPObject() {
	try 
	{ 
	 var requester = new XMLHttpRequest(); 
	} 
	catch (error) 
	{ 
	 try 
	 { 
		 var requester = new ActiveXObject("Microsoft.XMLHTTP"); 
	 } 
	 catch (error) 
	 { 
		 return false; 
	 } 
	}
	return requester;
}

function RVC(valor,tipo){
	switch(tipo.toLowerCase())
	{
		case "text":
		case "cpf":
		case "cnpj":
		case "email":
		case "homepage":
		case "textarea":
			return "'" + valor + "'";
		break;
		case "number":
		case "int":
		case "float":
			return valor;
		break;
		case "datetime":
			data = valor.substr(6,4) + '-' + valor.substr(3,2) + '-' + valor.substr(0,2);
			return "CONVERT(datetime, '"+data+"',111)";
		break;
	}
}

function DBDate(data){
	var http = getHTTPObject(); // Cria o objeto HTTP
	var result;
	http.open("POST", _dirPrograma + 'framework/config/ajax/db_date.php', false);
	http.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	
	if(navigator.appName == 'Netscape')
		http.onload = resposta;
	else
		http.onreadystatechange = resposta;
		
	http.send('data='+data);
	return result;
	function resposta() {
		if (http.readyState == 4) {
			result = http.responseText;
			if(http.status==404){
				alert('Página não encontrada');
				return false;
			} 
		}
	}
}

function executeSQL(sql){
	if(_sqlDebug){
		if(!_janelaSqlDebug)
			_janelaSqlDebug = open();
		_janelaSqlDebug.document.write(sql + '<br>');
		_janelaSqlDebug.document.write(_dirPrograma + 'framework/config/ajax/executa_sql.php <br>');
	}
	var result;
	var http = getHTTPObject(); // Cria o objeto HTTP
	if (http==null)
	{
		alert ("Browser does not support HTTP Request")
		return
	} 
	function resposta() {
		if (http.readyState == 4) {
			result = http.responseText;
			if(http.status==404){
				alert('Página não encontrada');
				return false;
			} 
		}
	}
	sql = sql;

	http.open("POST", _dirPrograma + 'framework/config/ajax/executa_sql.php', false);
	http.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	if(navigator.appName == 'Netscape')
		http.onload = resposta;
	else
		http.onreadystatechange = resposta;
		
	http.send('sql='+sql);
	
	return result;
}

function SelectSQL(sql){
	this.sql = sql;
	this.select;
	this.from;
	this.where;
	this.orderBy;
	this.addField = addField;
	this.makeSQL = makeSQL;
	this.alertSQL = alertSQL;
	this.execute = execute;
	this.debug = false;
	
	function addField(fieldName){
		this.fields.push(fieldName);
	}
	
	function makeSQL(){
		this.sql = 'SELECT ' + this.select.toLowerCase() + ' FROM ' + this.from.toLowerCase();
		if(this.where)
			this.sql += ' WHERE ' + this.where.toLowerCase();
		if(this.orderBy)
			this.sql += ' ORDERBY ' + this.orderBy.toLowerCase();
	}
	
	function alertSQL(){
		if(!this.sql)
			this.montaSQL();
		alert(this.sql);
	}
	
	function execute(){
		if(_sqlDebug){
			if(!_janelaSqlDebug)
				_janelaSqlDebug = open();
			_janelaSqlDebug.document.write(this.sql + '<br>');
		}
		var result;
		if(!this.sql)
			this.makeSQL();
		var http = getHTTPObject(); // Cria o objeto HTTP
		function respostaCSV() {
			if (http.readyState == 4) {
				result = http.responseText;
				if(http.status==404){
					alert('Página não encontrada');
					return false;
				} 
				//alert(result);
			}
		}
		sql = base64encode(this.sql);
		
		if(this.debug) {
			sql = sql+"&debug=1";
		}
		
		http.open("POST", _dirPrograma + 'framework/config/ajax/retorna_csv.php', false);
		http.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
		
		if(navigator.appName == 'Netscape')
			http.onload = respostaCSV;
		else
			http.onreadystatechange = respostaCSV;
		http.send('sql='+sql);
		if(result.indexOf('Erro') > -1) {
			eval(result);
			return false;
		}
		result = result.split('\n');
		var fieldsName = result[0].toLowerCase().split(';');
		var rs = new Array();
		for(i=0;i<result.length;i++){
			if(i){
				rs[i-1] = new Array();
				temp = result[i].split(';');
				for(j=0;j<temp.length;j++){
					rs[i-1][fieldsName[j]] = temp[j];
				}
			}
		}
		//alert(rs);
		return new RS(rs);
	}
}
SelectSQL.prototype.toString = function(){
	return '[SelectSQL Object - Sistema Aula]';
}
function RS(rs){
	this.vetor = rs;
	this.i = 0;
	if ( this.vetor.length > 0 )
		this.EOF = 0;
	else
		this.EOF = 1;
	this.fields = rs[0];
	this.MoveFirst = MoveFirst;
	this.MoveNext = MoveNext;
	this.MovePrevious = MovePrevious;
	this.MoveLast = MoveLast;
	this.posicionaVetor = posicionaVetor;
	this.RecordCount = RecordCount;
	
	function RecordCount(){
		return this.vetor.length;
	}
	
	function posicionaVetor(i){
		this.fields = this.vetor[i];
		this.EOF = (i>=this.vetor.length) ? 1 : 0;
	}
	
	function MoveFirst(){
		this.i = 0;
		this.posicionaVetor(this.i);
	}
	function MoveNext(){
		this.i++;
		this.posicionaVetor(this.i);
	}
	
	function MovePrevious(){
		this.i--;
		this.posicionaVetor(this.i);
	}

	function MoveLast(){
		this.i = this.vetor.length - 1;
		this.posicionaVetor(this.i);
	}
}
RS.prototype.toString = function(){
		return '[Result Set Object - Sistema Aula]';
}

function selectDate(nomeCampo, alias){
	if (!alias) 
		alias = nomeCampo;
		
	var http = getHTTPObject(); // Cria o objeto HTTP
	var result;
	http.open("POST", _dirPrograma + 'framework/config/ajax/select_date.php', false);
	http.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	
	if(navigator.appName == 'Netscape')
		http.onload = resposta;
	else
		http.onreadystatechange = resposta;
		
	http.send('nomeCampo='+nomeCampo+'&alias='+alias);

	return result;

	function resposta() {
		if (http.readyState == 4) {
			result = http.responseText;
			if(http.status==404){
				alert('Página não encontrada');
				return false;
			} 
		}
	}
}
/*********** fim do ajax *****************/

/********** DB com Iframe ****************/
function sqlSet(){
	this.itens = new Array();
	this.i = 0;
	this.onFinish;
	this.gauge;
	this.execute = execute;
	this.clear = clear;
	this.add = add;
	this.next = next;
	function execute(titulo){
		this.gauge = new Gauge(200,7,titulo);
		this.gauge.inicializa();
		this.next();
	}
	function clear(){
		this.itens = new Array();
		this.i = 0;
		this.onFinish = '';
	}
	function add(sql){
		this.itens[this.itens.length] = sql;
	}
	function next(){
		if(this.i==this.itens.length){
			eval(this.onFinish);
			this.gauge.fecha();
			return true;
		}
		this.gauge.aumenta(100/this.itens.length);
		frames['iFrmAuxiliar'].location = _dirPrograma + 'framework/config/ajax/sql_set.php?sql=' + base64encode(this.itens[this.i]);
		this.i++;
	}
}

var sqlSet = new sqlSet;
function postaFormulario(objForm,action,async){
	var req = getHTTPObject();
	var stringPost = '';
	for(i=0;i<objForm.elements.length;i++)
		stringPost += objForm.elements[i].name + '=' + objForm.elements[i].value + '&';
		stringPost = stringPost.substring(0,stringPost.length-1);
	req.open("POST",action, async);
	req.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	req.send(stringPost);
}

function dateAdd(diasSomar, dataBase){
	dataBase = dataBase.substr(6,4) + '/' + dataBase.substr(3,2) + '/' + dataBase.substr(0,2);
	var http = getHTTPObject(); // Cria o objeto HTTP
	var result;
	http.open("POST", _dirPrograma + 'framework/config/ajax/date_add.php', false);
	http.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	
	if(navigator.appName == 'Netscape')
		http.onload = resposta;
	else
		http.onreadystatechange = resposta;
		
	http.send('diasSomar='+base64encode(diasSomar.toString())+'&dataBase='+base64encode(dataBase));
	return result;
	function resposta() {
		if (http.readyState == 4) {
			result = http.responseText;
			if(http.status==404){
				alert('Página não encontrada');
				return false;
			} 
		}
	}
}