/*
 * Arquivo resposável por analisar um formulário e pegar todos os itens e inserí-lo em um iframe para enviar a uma determinada página.
 *  
 */

$(function(){


	function addEvent( obj, type, fn )
	{
		if (obj.addEventListener)
			obj.addEventListener( type, fn, false );
		else if (obj.attachEvent)
		{
			obj["e"+type+fn] = fn;
			obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
			obj.attachEvent( "on"+type, obj[type+fn] );
		}
	}
	
	function removeEvent( obj, type, fn )
	{
		if (obj.removeEventListener)
			obj.removeEventListener( type, fn, false );
		else if (obj.detachEvent)
		{
			obj.detachEvent( "on"+type, obj[type+fn] );
			obj[type+fn] = null;
			obj["e"+type+fn] = null;
		}
	}

    function removeNode(el){
        el.parentNode.removeChild(el);
    }

    /**
    * Creates and returns element from html chunk
    * Uses innerHTML to create an element
    */
    var toElement = (function(){
        var div = document.createElement('div');
        return function(html){
            div.innerHTML = html;
            var el = div.firstChild;
            return div.removeChild(el);
        };
    })();
            
    /**
     * Function generates unique id
     * @return unique id 
     */
    var getUID = (function(){
        var id = 0;
        return function(){
            return 'W21_Formsend_' + id++;
        };
    })();  


	//Caso o namespace W21 não existir cria um novo.
	if (window.W21 == undefined)
		window.W21 = function() {};

	//Objeto principal que irá controlar todo o processo
	window.W21.FormSend = function(objFormulario, objConfiguracao){
		 // Formulário que será enviado
		this._objFormulario = objFormulario;
		
		//Objeto com as configurações da classe
		this._objConfiguracao = {
			 //URL que receberá os dados do formulário
			acao: 'upload.aspx',
			// Dados adicionais a serem inseridos quando for enviado o formulário
			dados: {}, 
			 //dados que serão enviados com o formulário, caso a função retorne false o envio é cancelado
			onSubmit: function(dados) {},
			// Doc no formato em XML (se disponível) e a resposta recebida após os dados serem enviados
			onComplete: function (resposta) {
				alert("Resp:" + resposta);
			}, 
			// resposta recebida após os dados serem enviados
			onError: function (XMLHttpRequest, textStatus, errorThrown) {  
				alert(XMLHttpRequest);
			} 
		};
		
		
		// Pegar os dados definido pelo usuário e adicionar aos valores padrões da classe
        for (var i in objConfiguracao) {
            if (objConfiguracao.hasOwnProperty(i)){
                this._objConfiguracao[i] = objConfiguracao[i];
            }
        }
		
		//Travar o evento de submit do formulário
        if (this._objFormulario != null){
			var self = this;
			var objConfig = this._objConfiguracao; 

            // desabilitar o submit
			this._objFormulario.submit(function(e) {


				objConfig.dados = $(this).serialize();

				var bolContinuar = true;
				if (objConfig.onSubmit != null) {
					bolContinuar = objConfig.onSubmit(objConfig.dados);
				}
				
				if (bolContinuar != false) {
					//TODO: Fazer o processo de envio
					self.enviarForm();
				}
				
				//Cancelar evento para não disparar o formulário original
                if (e && e.preventDefault){
                    e.preventDefault();
                } else if (window.event){
                    window.event.returnValue = false;
                }
			}); 
        }


	
	};
	
	//Configurar a classe
	window.W21.FormSend.prototype = {
		setDados: function(dados){
			this._objConfiguracao.dados = dados;
		},
		
        /**
         * Creates iframe with unique name
         * @return {Element} iframe
         */
        criarIframe: function(){
            // We can't use getTime, because it sometimes return
            // same value in safari :(
            var id = getUID();            
             
            // We can't use following code as the name attribute
            // won't be properly registered in IE6, and new window
            // on form submit will open
            // var iframe = document.createElement('iframe');
            // iframe.setAttribute('name', id);                        
 
            var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
            // src="javascript:false; was added
            // because it possibly removes ie6 prompt 
            // "This page contains both secure and nonsecure items"
            // Anyway, it doesn't do any harm.            
            iframe.setAttribute('id', id);
            
			var objConfig = this._objConfiguracao;
			var pularPrimeiraMensagem = false;
			
			if (!($.browser.mozilla || $.browser.msie)) {// Somente opera e chrome
				pularPrimeiraMensagem = true;
			}
			 
			$(iframe).bind("load", function(e){
				if (pularPrimeiraMensagem == true) {
					pularPrimeiraMensagem = false;
				  return;
				}
				
				var doc = e.target.contentDocument ? e.target.contentDocument : window.frames[e.target.id].document;
				if (objConfig.onComplete != null) {
					bolContinuar = objConfig.onComplete(doc.body.innerHTML);
				}
			});

            iframe.style.display = 'none';
            document.body.appendChild(iframe);
            
            return iframe;
        },
        /**
         * Creates form, that will be submitted to iframe
         * @param {Element} iframe Where to submit
         * @return {Element} form
         */
        criarFormulario: function(iframe){
            var objConfig = this._objConfiguracao;
                        
            // We can't use the following code in IE6
            // var form = document.createElement('form');
            // form.setAttribute('method', 'post');
            // form.setAttribute('enctype', 'multipart/form-data');
            // Because in this case file won't be attached to request                    
            var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
                        
            form.setAttribute('action', objConfig.acao);
            form.setAttribute('target', iframe.name);                                   
            
			//form.style.display = 'none';
			document.body.appendChild(form);
			
            // Create hidden input element for each data key
			for (var prop in objConfig.dados) {
                if (objConfig.dados.hasOwnProperty(prop)){
                    var el = document.createElement("input");
                    el.setAttribute('type', 'hidden');
                    el.setAttribute('name', prop);
                    el.setAttribute('value', objConfig.dados[prop]);
                    form.appendChild(el);
                }
            }
			
			var formInputs = $( this._objFormulario.selector + " :input");
			var formNovo = $(form);
			$.each(formInputs, function(ndx, objInput){
				//alert( "Name: " + ndx + ", Value: " + objInput );
				
				var objInputNovo = $(objInput).clone(true)
				if ( (objInput.type == "textarea") || (objInput.type == "file") ) {
					alert(objInputNovo.val() + ' -1- ' + objInput.value);
					objInputNovo.val(objInput.value);
					alert(objInputNovo.val() + ' -2- ' + objInput.value); 
				}
				
				objInputNovo.appendTo(formNovo);
			});


            return form;
        },

        mudarFormulario: function(iframe){
            var objConfig = this._objConfiguracao;
                        
            // We can't use the following code in IE6
            // var form = document.createElement('form');
            // form.setAttribute('method', 'post');
            // form.setAttribute('enctype', 'multipart/form-data');
            // Because in this case file won't be attached to request                    
            var form = this._objFormulario[0]; //toElement('<form method="post" enctype="multipart/form-data"></form>');
                        
			
            form.setAttribute('action', objConfig.acao);
            form.setAttribute('target', iframe.name);                                   
            
            // Create hidden input element for each data key
			/*
			for (var prop in objConfig.dados) {
                if (objConfig.dados.hasOwnProperty(prop)){
                    var el = document.createElement("input");
                    el.setAttribute('type', 'hidden');
                    el.setAttribute('name', prop);
                    el.setAttribute('value', objConfig.dados[prop]);
                    form.appendChild(el);
                }
            }
			*/

            return form;
        },
		
		prepararDados : function() {
			// var allInputs = this._objFormulario.input();

		},
	
		enviarForm: function() {
			// sending request    
            var iframe = this.criarIframe();
            //var form = this.criarFormulario(iframe);
			var form = this.mudarFormulario(iframe);
			
			this.prepararDados();
			
			form.submit();
			
		}
	
	};	


});


/*
$(function(){
	var o = new W21.FormSend(
		$('#frmEnviarEmail'), 
		{
			acao: "receber_arquivos.aspx"
			,
			onSubmit: function(dados) {
				
				$('#frmEnviarEmail').fadeOut('slow');
				$('#divStatusProcessando').fadeIn('fast');
				//alert(dados);
				//return false;
			},
			onComplete: function (resposta) {
				alert("Resposta:" + resposta);
				$('#divStatusProcessando').fadeOut('fast');
				$('#frmEnviarEmail').fadeIn('slow');
			} 
		})
	
});


*/