/*
	Gateways de conexão dos formulários e AJAX requests
*/
var AdGatewayFormEndereco = "form/endereco/";


/*
	@package	AdForm
	@class		AdFormAjax
	@author 	Possidonio <possidonio@admt.com.br>
	@copyright 	2008 Ag&ecirc;nciadigital Marketing &amp; Tecnologia <agenciadigital@admt.com.br>
	@link 		Ag&ecirc;nciadigital Marketing &amp; Tecnologia <http://www.admt.com.br/>
	
	Envia um formulrio via AJAX, retorna a resposta da requisio para callback
*/
var AdFormAjax = function(form, callback) {
	this.init(form, callback);
}
AdFormAjax.prototype = {
	component:{
		formObject: false,
		callback: false
	},
		
	init: function(form, callback) {
		form = AdFormUtil.form(form);
		if (!form) return;
		
		if (typeof(callback) != "function") {
			callback=function(response, form, callback){
				new AdFormResponse(response, form, callback);
			};
		}
		
		this.component.callback = callback
		this.component.formObject = form;
				
		YAHOO.util.Connect.asyncRequest(
			"POST", 
			form.action +"?"+ YAHOO.util.Connect.setForm(form), 
			{
				success:function(o){callback(o.responseText, o.argument)},
				failure: function(o){new AdFormResponse(o.responseText, o.argument)},
				argument: form
			}
		);
							
		return false;
	}
}


/*
	@package	AdForm
	@class		AdFormIframeCall
	@author 	Possidonio <possidonio@admt.com.br>
	@copyright 	2008 Ag&ecirc;nciadigital Marketing &amp; Tecnologia <agenciadigital@admt.com.br>
	@link 		Ag&ecirc;nciadigital Marketing &amp; Tecnologia <http://www.admt.com.br/>
	
	Envia um formulrio via iframe, retorna o contedo do iframe para callback
	Cria um iframe em tempo de execuo para servir de gateway para a requisio do form. Aps o carregamento,
	o conte�do do iframe passado como atributo da funo callback.
*/
var AdFormIframeCall = function(form, callback) {
	this.init(form, callback);
	return false;
}
AdFormIframeCall.prototype = {
	component:{
		iframeObject: 'AdFormIframeCallObject',
		formObject: false
	},
		
	init:function(form, callback){
		form = AdFormUtil.form(form);
		if (!form) return;
		
		if (typeof(callback) != "function") {
			callback=function(response, form, callback){
				new AdFormResponse(response, form, callback, true);
			};
		}
		
		this.component.callback = callback;
		this.component.formObject = form;

		this.createIframe();
		this.setFormTarget();
		this.setFormTimeout();
		this.setIframeEvent();
					
		return false;
	},
	
	iframeEventResponse: function(e) {
		content = AdFormUtil.iframeContent(YAHOO.util.Event.getTarget(e));
		setTimeout("AdDom.remove('"+this.component.iframeObject+"')",250);
		this.component.callback(content, this.component.formObject, this.component.callback);
	},
	
	createIframe: function() {
		var iframe;
		
		if (document.getElementById(this.component.iframeObject) != null){
			iframe = document.getElementById(this.component.iframeObject);
		} else {
			try {
			  iframe = document.createElement('<iframe name="'+this.component.iframeObject+'">');
			} catch (ex) {
			  iframe = document.createElement('iframe');
			}
			
			iframe.id = this.component.iframeObject;
			iframe.name = this.component.iframeObject;
			iframe.src = "";
			iframe.width = 0;
			iframe.height = 0;
			iframe.marginHeight = 0;
			iframe.marginWidth = 0;
			document.body.appendChild(iframe);
		}
		return iframe;
	},
	
	setFormTarget: function() {
		this.component.formObject.setAttribute("target",this.component.iframeObject);
	},
	
	setFormTimeout: function() {
		//setTimeout("document.getElementById('"+this.component.formObject.id+"').submit()",2000);
		this.component.formObject.submit();
	},
	
	setIframeEvent:function(){
		YAHOO.util.Event.addListener(this.component.iframeObject, "load", this.iframeEventResponse, this, true);
	}
};

/*
	@package	AdForm
	@class		AdFormResponse
	@author 	Possidonio <possidonio@admt.com.br>
	@copyright 	2008 Ag&ecirc;nciadigital Marketing &amp; Tecnologia <agenciadigital@admt.com.br>
	@link 		Ag&ecirc;nciadigital Marketing &amp; Tecnologia <http://www.admt.com.br/>
	
	Tratamento padr�o de formulrios
	Processa os campos e prepara alertas de erros
*/
var AdFormResponse = function(response, form, callback, previousCallbackUndefined) {
	this.init(response, form, callback, previousCallbackUndefined);
}
AdFormResponse.prototype = {
	init: function(response, form, callback,previousCallbackUndefined) {
		responseText=response;
		
		try{
			if (typeof(response) == "string") {
				response = AdJson(response);
			} else if (typeof(response.responseText)!="undefined") {
				response = AdJson(response.responseText);
			} else {
				response = false;
			}
			
			var mess = "";
			
			if (response==null) {
				alert("Resposta não interpretada");
				return;
			}
			
			var status = response.status;
			if (status==true) {
				mess += typeof(response.argumentos) != 'undefined' && typeof(response.argumentos.mensagem) != 'undefined' ? response.argumentos.mensagem : "Formulário enviado com sucesso";
				alert(mess);
				
				if (response.callback)
					try{
						c = eval(response.callback);
						c(response, form);
					}catch(e){
						//alert(e);
					}
			} else {
				mess += "Falha ao processar formulário\n\n";
				//mess += responseText+"\n\n";
				
				if (typeof(response.argumentos) != 'undefined' && response.argumentos != false) {
					mess += " - "+response.argumentos+"\n";
				}
				
				if (response.campos) {
					mess += " - Os campos destacados possuem informação incorreta.\n";
					for (fi in response.campos) {
						e = AdDom.$(response.campos[fi]);
						if (e) {
							AdFormUtil.input.alerta(e);
							//mess += "   "+response.campos[fi]+"\n";
						}
					}
				}
				
				if (response.files) {
					mess += " - Problemas ao receber o arquivo:\n";
					mess += "	- Você não selecionou um arquivo ou\n";
					mess += "	- O tipo do arquivo que você enviou não é aceito.\n";
					for (ff in response.files) {
						e = AdDom.$(response.files[ff]);
						AdFormUtil.input.alerta(e);
					}
				}
			
				alert(mess);
			}
			
			if (typeof(callback) == "function" && previousCallbackUndefined != true) {
				callback(response, form);
			}
			
		} catch(e) {
			alert(responseText);
		}
	}
};

/*
	@package	AdForm
	@class		AdFormUtil
	@author 	Possidonio <possidonio@admt.com.br>
	@copyright 	2008 Ag&ecirc;nciadigital Marketing &amp; Tecnologia <agenciadigital@admt.com.br>
	@link 		Ag&ecirc;nciadigital Marketing &amp; Tecnologia <http://www.admt.com.br/>
	
	Funcoes teis para manipulao de formulrios
*/
var AdFormUtil = {
	/*
		Se form for string, entende como o id de um formulrio e seta form como um objeto
		Checa se o objeto form existe, validando o atributo action, se falhar retorna false, seno retorna o form
	*/
	form: function(form) {
		form = AdDom.$(form);
		if (form.tagName.toUpperCase()!= "FORM")
			return false;
		return form;
	},
	
	iframeContent: function(el){
		if(el.contentWindow) {
			return el.contentWindow.document.body.innerHTML;
		} else if(el.contentDocument){
			return el.contentDocument.document.body.innerHTML;
		} else {
			return false;
		}
	},
	
	input:{
		classe: function(e, className) {
			p = AdDom.$P(e,"p");
			p.className+=" "+className;
			e.onfocus=function(){document.oldValue = this.value;};
			e.onblur=function(){p = AdDom.$P(this,"p"); if (this.value != document.oldValue) p.className=p.className.replace(className,'');};
		},
		erro:function(e){
			AdFormUtil.input.classe(e, 'input-erro');
		},
		alerta:function(e){
			AdFormUtil.input.classe(e, 'input-alerta');
		}
	}
};

/*
	@package	AdForm
	@class		AdFormEndereco
	@author 	Possidonio <possidonio@admt.com.br>
	@copyright 	2008 Ag&ecirc;nciadigital Marketing &amp; Tecnologia <agenciadigital@admt.com.br>
	@link 		Ag&ecirc;nciadigital Marketing &amp; Tecnologia <http://www.admt.com.br/>
	
	Manipulação DOM de elementos relacionados a endereço.
	Obtenção de endereço por CEP
	Lista de estados e cidades
*/
var AdFormEndereco = {
	populaSelectEstados: function(el) {
		try {
			el.innerHTML="";
			var opt = document.createElement("option");
			opt.value="false";opt.innerHTML="Carregando...";		
			el.appendChild(opt);
			
			
			YAHOO.util.Connect.asyncRequest(
				"GET", 
				AdGatewayFormEndereco + "?a=listaEstados", 
				{
					success: function(o) {
						el = o.argument.el;
						m = YAHOO.lang.JSON.parse(o.responseText);
						AdFormEndereco.selectPopulaOptions(el, m, 'cd_estado', 'nm_estado', true);
					},
					argument:{el:el}
				}
			);
		} catch (e) {alert(e);}
	},
	
	populaSelectCidadesPorEstado: function(e) {
		el = YAHOO.util.Event.getTarget(e);
		v = el.options[el.selectedIndex].value;
		
		if (v=='false') {
			return;
		}
		
		el = document.getElementById("AdFormCidadeEndereco");
		
		el.innerHTML="";
		var opt = document.createElement("option");
		opt.value="false";opt.innerHTML="Carregando...";		
		el.appendChild(opt);
		
		YAHOO.util.Connect.asyncRequest(
			"GET", 
			AdGatewayFormEndereco + "?a=listaCidadesPorEstado&cdEstado=" + v, 
			{
				success: function(o) {
					el = o.argument.el;
					//alert(o.responseText);
					m = YAHOO.lang.JSON.parse(o.responseText);
					AdFormEndereco.selectPopulaOptions(el, m, 'cd_cidade', 'nm_cidade');
				},
				argument:{el:el}
			}
		);
	},
	
	selectPopulaOptions: function(target, matriz, value, label, selectLabel) {
		target.innerHTML="";
		if (selectLabel == true) {
			var opt = document.createElement("option");
			opt.value="false";opt.innerHTML="Selecione";opt.setAttribute("selected","selected");
			target.appendChild(opt);
			var opt = document.createElement("option");
			opt.value="false";opt.innerHTML="-";
			target.appendChild(opt);
		}
		for (i in matriz) {
			v = matriz[i][value];
			l = matriz[i][label];
			
			o = document.createElement("option");
			o.value=v; o.innerHTML=l;
			target.appendChild(o);
		}
	}
};