/*
Digital Industry 2009
Ajax Functions
*/

var host 	= "http://marge:200";

function newAjaxObject(){
	var objAjax;

	try{
		objAjax 	= new ActiveXObject('Microsoft.XMLHTTP');
	}
	catch(e){
		try{
			objAjax = new ActiveXObject('Msxml2.XMLHTTP');
			objAjax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		}
		catch(ex){
			try{
				objAjax = new XMLHttpRequest();
			}
			catch(exc){
				objAjax = null;
			}
		}
	}
	return objAjax;
}

function RunAjaxRequest(stMethod, stUrl, stParameters, objFunction, idElement, stTitle){
	objXmlRequest 	= newAjaxObject()
	process 		= objFunction;

	objXmlRequest.onreadystatechange = function(){
		try{
			if(!idElement){
				/* Sem par?metros de Retorno */
				process(objXmlRequest);

			}else{
				/* Com par?metros de Retorno */
				process(objXmlRequest, idElement, stTitle);
			}
		}
		catch(ex){
			alert('Um erro ocorreu ao tentar carregar os dados. Tente novamente.\nDescricao: ' + ex.message + '\nArquivo: \t' + ex.fileName + '\nStack: \t' + ex.stack + '\nLInha: \t' + ex.lineNumber )
		}
	}

	stMethod = stMethod.toUpperCase();
	objXmlRequest.open(stMethod, stUrl, true);

	if(stMethod == 'POST'){
		objXmlRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
		objXmlRequest.setRequestHeader('Method', 'POST ' + stUrl + 'HTTP/1.1');
		objXmlRequest.setRequestHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
		objXmlRequest.setRequestHeader('Cache-Control', 'post-check=0, pre-check=0');
		objXmlRequest.setRequestHeader('Pragma', 'no-cache');
		/*
		objXmlRequest.setRequestHeader('charset','ISO-8859-1');
		objXmlRequest.setRequestHeader('encoding','ISO-8859-1');
		*/
	}
	objXmlRequest.send(stParameters);
	return objXmlRequest;
}

function LoadDropDown(stMethod, stUrl, stParameters, idDropDestiny, stTitle){
	RunAjaxRequest(stMethod, stUrl, stParameters, TrataXmlDropDown, idDropDestiny, stTitle)
}


function LoadAjaxPage(stMethod, stUrl, stParameters, objFunction){
	RunAjaxRequest(stMethod, stUrl, stParameters, objFunction, null)
}

function TrataXmlDropDown(objXmlRequest, idDropDestiny, stTitle){
	var idFeedback					= 'obj_Feedback'
	var objDropDown 				= document.getElementById(idDropDestiny)
	var objFeedback					= document.getElementById(idFeedback)

	if(objFeedback){
		ShowHideElement(objFeedback, 1)
		CenterObject(objFeedback, 600, 50)
	}

	if(objDropDown) resetDropDown(objDropDown);

	objDropDown.options[0] 			= new Option('Carregando ...','');
	objDropDown.options[0].selected	= true;

	BlockUnblockElement(objDropDown, 0)

	if(objXmlRequest.readyState == 4){
		if (objXmlRequest.status == 200){
			try{
				var objXmlResult	 	= objXmlRequest.responseXML

				/* Verifica??o Bug Firefox */
				var objFirstNode		= objXmlResult.childNodes[1]
				if(!objFirstNode)		objFirstNode = objXmlResult.childNodes[0]

				var objChildNode		= objFirstNode.firstChild
				var stChildNode			= objChildNode.nodeName
				//var nmTotalResults 	= objXmlRequest.responseXML.getElementsByTagName(""+stChildNode+"").length
			}

			catch(ex){
				alert('Um erro ocorreu ao tentar carregar os dados. Tente novamente.\nDescri??o: ' + ex.message)
			}

			/* End Of File */
			if(stChildNode == 'eof'){
				objDropDown.options[objDropDown.options.length] = new Option('Dados n?o encontrados', '');
			}else{
				var objFieldXml = objXmlResult.getElementsByTagName(stChildNode);
				var nminc 		= 0
				var arrayNodes 	= new Array();

				for (i=0; i < objFieldXml.length; i++){
					for (j=0; j < objFieldXml[i].childNodes.length; j++){
						var nmNodeType = objFieldXml[i].childNodes[j].nodeType

						if(nmNodeType == 1){
							arrayNodes[nminc] = objFieldXml[i].childNodes[j].firstChild.nodeValue
							nminc ++
						}
					}
				}

				for(nmInc = 0; nmInc < arrayNodes.length; nmInc = nmInc + 2){
					var nmValue		= arrayNodes[nmInc]
					var stDisplay	= arrayNodes[nmInc + 1]

					stTitle

					if(stTitle && 	nmInc == 0) objDropDown.options[objDropDown.options.length] = new Option(stTitle, '');
					if(!stTitle && 	nmInc == 0) objDropDown.options[objDropDown.options.length] = new Option('Favor selecionar', '');
//					if(nmInc == 0) objDropDown.options[objDropDown.options.length] = new Option('Favor selecionar', '');
					objDropDown.options[objDropDown.options.length] = new Option(stDisplay, nmValue);
				}
			}

			Timer(2000, "EndLoadDropDown('"+idDropDestiny+"', '"+idFeedback+"')");
		}
	}
}

function gravaFrase(nmValue, idDepoimento){
	/*document.getElementById('stLabel').innerHTML		= '';*/
	RunAjaxRequest('POST', 'atualizaFrase.php', 'nmValue='+nmValue+'&idDepoimento='+idDepoimento, retornaRespostaFrase);
}

function retornaRespostaFrase(objXmlRequest){
	/* Recebe campo que exibir? status da opera??o */
	//objSpan			= document.getElementById('stLabel');

	/* Verifica se o objeto est? pronto para ser utilizado
	if(objXmlRequest.readyState == 4){
		if(objXmlRequest.status == 200){

			nmTotalResults 		= objXmlRequest.responseXML.getElementsByTagName("status").length;
			objXml 		    	= objXmlRequest.responseXML;
			nmTotalResults > 0 ? objSpan.innerHTML	= 'Atualizado com sucesso!' : objSpan.innerHTML	= 'Ocorreu um erro na atualiza??o. Favor tentar mais tarde!';
		}
	}*/
	/* Aciona o timer para remover a exibi??o */
	//timeOut(1500, 'objSpan.innerHTML = ""');
}

function EndLoadDropDown(idDropDestiny, idFeedback){
	var objDropDown 		= document.getElementById(idDropDestiny)

	BlockUnblockElement(objDropDown, 1)
	objDropDown.options[0] = null;

	FadeElement(idFeedback, 'out', 0250)
}

function lookup(inputString){

	if(inputString.length == 0) {
		// Hide the suggestion box.
		$('#suggestions').hide();
	} else {
		$.post(host + "/xml/buscaPerfume.php", {queryString: ""+inputString+""}, function(data){
			if(data.length >0) {
				$('#suggestions').show();
				$('#autoSuggestionsList').html(data);
			}
		});
	}
} // lookup

function fill(thisValue) {
	$('#estilo_perfume_texto').val(thisValue);
	setTimeout("$('#suggestions').hide();", 200);
}

function buscaCep(nmCep){
    if(nmCep.length == 8){
	    RunAjaxRequest('POST', '../xml/logradouro.php'    , 'nmCep='+nmCep+'', retornaXmlCep);
    }else{
        limpaCampoCep();
    }
}

function limpaCampoCep(){
    var obj_Cep                 = document.getElementById("id_Cep");
    var obj_stLogradouro        = document.getElementById("id_stLogradouro");
    var obj_Endereco            = document.getElementById("id_stEndereco");
    var obj_Bairro              = document.getElementById("id_Bairro");
    var obj_Cidade              = document.getElementById("id_Cidade");
    var obj_stUf                = document.getElementById("id_stUf");

    obj_Endereco.value        = '';
    obj_Bairro.value        = '';
    obj_Cidade.value        = '';
//    obj_Cep.value            = '';

    obj_stLogradouro.options[0].selected    = true;
    obj_stUf.options[0].selected            = true;
}

function retornaXmlCep(objXmlRequest){
	var obj_Cep 	= document.getElementById("id_Cep");

	if(objXmlRequest.readyState == 4){
		if(objXmlRequest.status == 200){

            var stLogradouro, obj_stLogradouro;
			var stEndereco, obj_Endereco;
			var stBairro, obj_Bairro;
			var stCidade, obj_Cidade;
			var stUf, obj_stUf;


			nmTotalResults 		= objXmlRequest.responseXML.getElementsByTagName("logradouro").length
			objXml 		    	= objXmlRequest.responseXML

			obj_stLogradouro 	= document.getElementById("id_stLogradouro");
			obj_Endereco		= document.getElementById("id_stEndereco");
			obj_Bairro			= document.getElementById("id_Bairro");
			obj_Cidade			= document.getElementById("id_Cidade");
			obj_stUf		  	= document.getElementById("id_stUf");

			if(nmTotalResults > 0){
				for(i = 0 ; i < nmTotalResults ; i++){

                    stLogradouro = (objXml.getElementsByTagName("logradouro")[i].getElementsByTagName("stLogradouro")[0].firstChild.nodeValue)
                    stEndereco   = (objXml.getElementsByTagName("logradouro")[i].getElementsByTagName("stEndereco")[0].firstChild.nodeValue)
                    stBairro     = (objXml.getElementsByTagName("logradouro")[i].getElementsByTagName("stBairro")[0].firstChild.nodeValue)
                    stCidade     = (objXml.getElementsByTagName("logradouro")[i].getElementsByTagName("stCidade")[0].firstChild.nodeValue)
                    stUf         = (objXml.getElementsByTagName("logradouro")[i].getElementsByTagName("stUf")[0].firstChild.nodeValue)

                    for(nmInc = 0; nmInc < obj_stLogradouro.length; nmInc ++){
                        if(Trim(obj_stLogradouro[nmInc].value.toUpperCase()) == Trim(stLogradouro.toUpperCase())) obj_stLogradouro[nmInc].selected = true
                    }

                    for(nmInc = 0; nmInc < obj_stUf.length; nmInc ++){
                        if(Trim(obj_stUf[nmInc].value.toUpperCase()) == Trim(stUf.toUpperCase())) obj_stUf[nmInc].selected = true
                    }

                    obj_Endereco.value    = stEndereco;
                    obj_Bairro.value      = stBairro;
                    obj_Cidade.value      = stCidade;
				}
			}else{
                limpaCampoCep();
            }
		}
	}
}

function buscaCpf(stCpf){
    if(stCpf.length == 11){
        $.post("../xml/busca-cpf.php", {stCpf: ""+stCpf+""}, function(data){
            if(data.length > 0) {
                if(parseInt(data) == 1){
                    alert("Seu CPF já está cadastrado!");
                    window.location.href="../login";
                }
            }
        });
    }
}