/*
    Yuffie
    01/01/2010
    Copyright (C) 2010  Alessandro Ramos dos Santos

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

(function(){
	
	
	/**
	 * Query String
	 */
	(function(){
		
		window.$qs = { };
		window.$id = '';
		
		var slice1 = window.location.href.split ( '?' );
		
		if ( slice1.length == 2 )
		{
			
			var querystring = slice1[1].replace ( /(#.*)/ , '' );
			var values = querystring.split ( '&' );
			
			for ( var a = 0 ; a < values.length ; a++ )
			{
				
				$qs[values[a].split ( '=' )[0]] = values[a].split ( '=' )[1];
				
			};
			
		};
		
		var slice2 = window.location.href.split ( '#' );
	
		if ( slice2.length == 2 )
		{
			
			$id = slice2[1];
			
		};
		
	})();
	
	/**
	 * Atalho para objeto document
	 * Retorna o objeto document
	 */
	window.$d = document;
	
	
	/**
	 * Atalho para encodeURIComponent
	 */
	window.$euc = encodeURIComponent;
	
	
	/**
	 * Atalho para decodeURIComponent
	 */
	window.$duc = decodeURIComponent;
	
	
	/**
	 * Atalho para método createElement
	 * Cria um elemento DOM com propriedades ou não
	 *
	 * Exemplos:
	 * var a = $ce ( 'p' );
	 * var a = $ce ( 'p' , { innerHTML : 'Parágrafo' } );
	 * var a = $ce ( 'p' , { innerHTML : 'Parágrafo' , onclick : function ( ) { this.style.color = '#900'; } } );
	 *
	 * O objeto resultante contém o método $ac que é um atalho para o método appendChild
	 * Exemplo:
	 * var a = $ce ( 'p' );
	 * var b = $ce ( 'a' , { href : 'index.html' , innerHTML : 'Home' } );
	 * a.$ac ( b );
	 *
	 * O método não suporta sobrecarga de propriedades, exemplo:
	 * var a = $ce ( 'p' , { style.color : '#0f0' } )
	 *
	 * Ao invés disso, use:
	 * var a = $ce ( 'p' );
	 * a.style.color = '#0f0';
	 */
	window.$ce = function ( element )
	{
		
		var e = $d.createElement ( element );
		
		e.$ac = e.appendChild;
		
		e.$sa = e.setAttribute;
		
		if ( arguments[1] != undefined )
		{
			
			var
				a = 0 ;
				
			for ( a in arguments[1] )
			{
				
				e[a] = arguments[1][a];
				
			};
			
		};
		
		return e;
		
	};
	
	
	/**
	 * Atalho para o método document.getElementById
	 * Retorna uma referência ao objeto DOM
	 *
	 * O objeto resultante contém o método $ac que é um atalho para o método appendChild
	 * Exemplo:
	 * var a = $o ( 'minhaDIV' );
	 * var b =  document.createElement ( 'p' );
	 * b.innerHTML = 'Meu parágrafo dentro de minha DIV.';
	 * a.$ac ( b );
	 */
	window.$o = function ( id )
	{
		
		var e = $d.getElementById ( id );
		
		e.$ac = e.appendChild;
		
		return e;
		
	};
	
	
	/**
	 * Retorna um número inteiro randômico entre min e max
	 */
	window.$ran = function ( min , max )
	{
		
		return Math.floor ( Math.random ( ) * ( max - min + 1 ) ) + min;
		
	};
	
	
	/**
	 * Substitui caracteres especiais
	 */
	window.$he = function ( str )
	{
		
		str = str.replace ( /&/gi , '&amp;' );
		
		return str;
		
	};
	
	
	/**
	 * Popula a DIV 'mensagens' com as mensagens recebidas via $async
	 */
	window.$m = function ( m )
	{
		
		var a;
		
		for ( a = 0 ; a < m.mensagemErro.length ; a++ )
			$o ( 'mensagens' ).$ac ( $ce ( 'p' , { innerHTML : m.mensagemErro[a] , className : 'mensagemErro' } ) );
		
		for ( a = 0 ; a < m.mensagemInformacao.length ; a++ )
			$o ( 'mensagens' ).$ac ( $ce ( 'p' , { innerHTML : m.mensagemInformacao[a] , className : 'mensagemInformacao' } ) );
		
		for ( a = 0 ; a < m.mensagemSucesso.length ; a++ )
			$o ( 'mensagens' ).$ac ( $ce ( 'p' , { innerHTML : m.mensagemSucesso[a] , className : 'mensagemSucesso' } ) );
		
		$o ( 'mensagens' ).scrollTop = $o ( 'mensagens' ).scrollHeight;
		
	};
	
	
	/**
	 * Classe para requisições assíncronas
	 *
	 * Exemplo:
	 * var x = new $async ( 'json.php' , 'get' , 'acao=listarCidades&posicao=0&limite=10 );
	 * x.rs4 = function ( )
	 * {
	 *   // Tarefas a se fazer quando a requisição estiver completa
	 * };
	 * x.chama ( );
	 */
	window.$async = function ( arquivo , metodo , dados )
	{
		
		try { this.xmlHttp = new XMLHttpRequest ( ); }
		catch ( e ) { try { this.xmlHttp = new ActiveXObject ( 'Msxml2.XMLHTTP' ); }
		catch ( e ) { try { this.xmlHttp = new ActiveXObject ( 'Microsoft.XMLHTTP' ); }
		catch ( e ) { alert ( 'Seu agente de navegação não suporta requisições assíncronas.' ); } } };
		
		this.arquivo = arquivo;
		this.metodo = metodo;
		this.dados = dados;
		this.resposta = '';
		this.json = { };
		
		this.traduzJSON = function ( )
		{
			
			this.json = eval ( '(' + this.resposta + ')' );
			$m ( this.json.mensagens );
			
		};
		
		var A = this;
		
		A.rs0 = function ( ) { };
		A.rs1 = function ( ) { };
		A.rs2 = function ( ) { };
		A.rs3 = function ( ) { };
		A.rs4 = function ( ) { };
		A.s404 = function ( ) { alert ( 'Erro na requisição assíncrona: o arquivo não foi encontrado.' ); };
		A.aborta = function ( ) { this.abort ( ); };
		
		A.xmlHttp.onreadystatechange = function ( )
		{
			
			switch ( A.xmlHttp.readyState )
			{
				
				case 0 : A.rs0 ( ); break;
				case 1 : A.rs1 ( ); break;
				case 2 : A.rs2 ( ); break;
				case 3 : A.rs3 ( ); break;
				case 4 :
					
					switch ( parseInt ( A.xmlHttp.status ) )
					{
						
						case 404 : A.s404 ( ); break;
						case 200 :
							
							A.resposta = A.xmlHttp.responseText;
							A.rs4 ( );
							
							break;
						
						default:
							
							alert ( 'Erro na requisição assíncrona: a requisição retornou um código de status ' + A.xmlHttp.status );
							
							break;
						
					};
					
					break;
				
			};
			
		};
		
		A.chama = function ( )
		{
			
			switch ( this.metodo )
			{
				
				case 'post' :
					
					A.xmlHttp.open ( this.metodo , this.arquivo , true );
					A.xmlHttp.setRequestHeader ( 'Content-Type','application/x-www-form-urlencoded' );
					A.xmlHttp.send ( this.dados );
					
					break;
				
				case 'get' :
					
					A.xmlHttp.open ( this.metodo , this.arquivo + '?' + this.dados , true );
					A.xmlHttp.send ( null );
					
					break;
				
				default : alert ( 'Erro na requisição assíncrona: método não reconhecido.' ); break;
				
			};
			
		};
		
	};
	
	
	/**
	 * Classe para requisições assíncronas
	 * DEPRECATED!
	 * Esta classe está aqui só para manter a retrocompatibilidade com meus outros projetos.
	 * Veja a classe $async no lugar desta
	 */
	window.async=function(){try{this.xmlHttp=new XMLHttpRequest()}catch(e){try{this.xmlHttp=new ActiveXObject('Msxml2.XMLHTTP')}catch(e){try{this.xmlHttp=new ActiveXObject('Microsoft.XMLHTTP')}catch(e){alert('Seu agente de navegação não suporta requisições assíncronas.')}}};this.arquivo='';this.metodo='post';this.dados='';this.resposta='';this.json={};this.traduzJSON=function(){this.json=eval('('+this.resposta+')')};var A=this;A.rs0=function(){};A.rs1=function(){};A.rs2=function(){};A.rs3=function(){};A.rs4=function(){};A.s404=function(){alert('Erro na requisição assíncrona: o arquivo não foi encontrado.')};A.xmlHttp.onreadystatechange=function(){if(A.xmlHttp.readyState==0){A.rs0()}else if(A.xmlHttp.readyState==1){A.rs1()}else if(A.xmlHttp.readyState==2){A.rs2()}else if(A.xmlHttp.readyState==3){A.rs3()}else if(A.xmlHttp.readyState==4){if(parseInt(A.xmlHttp.status)==404){A.s404()}else if(parseInt(A.xmlHttp.status)==200){A.resposta=A.xmlHttp.responseText;A.rs4()}else{alert('A requisição retornou um código de status '+A.xmlHttp.status)}}};A.chama=function(){if(this.metodo=='post'){A.xmlHttp.open(this.metodo,this.arquivo,true)}else if(this.metodo=='get'){A.xmlHttp.open(this.metodo,this.arquivo+'?'+this.dados,true)};if(this.metodo=='post'){A.xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');A.xmlHttp.send(this.dados)}else if(this.metodo=='get'){A.xmlHttp.send(null)}}};
	
})();

