function popitup(url, name, width, height) {
//alert('popitup ' + url + ' ' + ' ' + ' ' + options);
	newwindow = window.open(url, name, 'resizable=yes');
	newwindow.resizeTo(width, height)
	if (window.focus)
		newwindow.focus();
	return false;
}//-->

function trocaimghome() {
	$('#imghome').fadeOut(2500, function() {
		$('#imghome').attr('src', './images/home/'+imgHome[imgnum]);
		$('#imghome').fadeIn(2500);
	});
	imgnum++;
	if (imgnum == imgHome.length)
		imgnum = 0;
}

function trocaimgMagda() {
	$('#imgMagda').fadeOut('slow', function() {
		$('#imgMagda').attr('src', './images/'+arrayMagda[magdanum]);
		$('#imgMagda').fadeIn('slow');
	});
	magdanum++;
	if (magdanum == arrayMagda.length)
		magdanum = 0;
}

function Anima(id, img, from, to, time) {
	$('#animahome').append('<div class="anima" id="'+id+'"></div>');
	$('#'+id).append('<img src="./images/home/'+img+'" height="151px" width="150px" border="0" />');
	$('#'+id).css('left',from);
	$('#'+id).fadeIn('slow').animate({left: to}, time);
}

function trocaimganimaHome() {
	if (animaGrupo == 1) {
		animaGrupo = 2;
	}
	else {
		animaGrupo = 1;
	}
	trocaimganimaHome2();
}

function trocaimganimaHome2() {
	var arrayaux = imganimaHome2;
	if (animaGrupo == 1)
		arrayaux = imganimaHome1;
	$('#animahome').empty();
	$('#animahome').fadeIn('slow');
	Anima("anima01", arrayaux[0], "100px", "0px", 600)
	$("#anima01").queue(function () {
		Anima("anima02", arrayaux[1], "150px", "40px", 600)
		$("#anima02").queue(function () {
			Anima("anima03", arrayaux[2], "190px", "80px", 600)
			$("#anima03").queue(function () {
				Anima("anima04", arrayaux[3], "230px", "120px", 600)
				$("#anima04").queue(function () {
					Anima("anima05", arrayaux[4], "270px", "160px", 600)
					$("#anima05").queue(function () {
						Anima("anima06", arrayaux[5], "310px", "200px", 600)
						$("#anima06").queue(function () {
							Anima("anima07", arrayaux[6], "310px", "240px", 600)
							$("#anima07").queue(function () {
								Anima("anima08", arrayaux[7], "310px", "280px", 600)
								$("#anima08").queue(function () {
									Anima("anima09", arrayaux[8], "320px", "320px", 600)
									$(this).dequeue();
								});
								$(this).dequeue();
							});
							$(this).dequeue();
						});
						$(this).dequeue();
					});
					$(this).dequeue();
				});
				$(this).dequeue();
			});
			$(this).dequeue();
		});
        $(this).dequeue();
	});
}

//carrega area administrativa
function admin() {
	if (userLogado == 'True')
		window.open(homeSite+'admin', '_self');
	else
		alert('unauthorized access...');
}

function contato() {
	$('#miolo').load("contato.php?", {  }, function(data){
		ligaFormContato();
		atribue("contato.php");
	});
}

function clubcadastro() {
	//~ if (serverName != 'localhost') {
		//~ alert("em breve...");
		//~ return;
	//~ }
	$('#club_itens').load("clubcadastro.php", {  }, function(data){
		cadastramento();
	});
}

function clubarte(sid) {
	$('#miolo').load("clubarte.php?"+sid, {  }, function(data){
		//~ ligaVerColMenu();
		ligaMenuCategoria();
		atribue("clubarte.php");
	});
}

function clubShow(categoria, dir, projeto) {
	//~ alert('categoria=' + categoria + " dir:" + dir + " projeto:" + projeto);
	$('#club_itens').load("clubshow.php", { 'categoria' : categoria, 'dir' : dir, 'projeto' : projeto }, function(data){
		clickOn('club_passoclick');
		//~ $('#club_titulo').slideDown('fast');
	});
}
function ligaVerColMenu() {
	// Collapse everything but the first menu:
	$("#VerColMenu > li > a").not(":first").find("+ ul").slideUp(1);
	// Expand or collapse:
	$("#VerColMenu > ul > li > a").click(function() {
		alert("clicouuu..."+'class='+$(this).attr('class')+' '+$(this).text());
		$(this).find("+ ul").slideToggle("fast");
	});
}
function ligaMenuCategoria() {
	// Collapse everything but the first menu:
	$(".club_menucategoria > li > a + ul").not(":first").slideUp('slow');
	// Expand or collapse:
	$("ul.club_menucategoria > li > a").click(function() {
		//~ alert("clicou..."+'class='+$(this).attr('class')+' '+$(this).text());
		$(this).next("ul").slideToggle("fast");
	});
}
/*
function doLoad() {;
	bomdia();
	setInterval("bomdia()", 30000); //a cada 30 segundos atualiza hora
	//setTimeout( "refresh()", 360 );
}

function bomdia() {
	var today = new Date();
	var browserName=navigator.appName;
	var somadata = 0;
	if (browserName=="Netscape") {
		somadata = 1900;
	}
	else {
		if (browserName=="Microsoft Internet Explorer") ;
	else {
		alert("browserName");
	  }
	}
	if (today.getMinutes() < 10)
		pad = "0";
	else
		pad = "";
	cumprimento = '<b><font color="#000000" face="Verdana" size="2">';
	dia = 'Bem Vindo!!!</font><br><font size="2">Desejamos-lhe <font color=red size="2">';
	if ((today.getHours() < 12) && (today.getHours() >= 6))
		dia += "BOM DIA"; // Aqui é o que aparece entre 06:00 e 12:00 hs.
	else
	if ((today.getHours() >= 12) && (today.getHours() < 18))
		dia += "BOA TARDE";  // Aqui é o que aparece entre 12:00 e 18:00 hs.
	else
	if ((today.getHours() >= 18) && (today.getHours() <= 23))
		dia += "BOA NOITE";  // Aqui é o que aparece entre 18:00 e 24:00 hs.
	cumprimento += (dia + "!!</font></b><br>");
	cumprimento += ("Hoje &eacute; " + today.getDate() + "/" + (today.getMonth()+1) + "/" + (today.getYear()+somadata) + ", " );
	cumprimento += (today.getHours() + ":" + pad + today.getMinutes() + "hs"); // + "'" + today.getSeconds() + "''")
	cumprimento += ("</font></b>");
	$('#cumpri').html(cumprimento);
}
*/
/*
function swapImage(foto) {
	var par = window.document; //window.parent.document;
	var imgdiv = par.getElementById('idesam_foto_galeria');
	var image = imgdiv.getElementsByTagName('img')[0];
	imgdiv.removeChild(image);
	var image_new = par.createElement('img');
	image_new.src = 'resize.php?pic=' + foto + '&width=300&height=213';
	image_new.className = 'loaded';
	imgdiv.appendChild(image_new);
}

function popitup(url, name, width, height) {
	//~ alert('popitup ' + url + ' ' + ' ' + ' ' + options);
	newwindow = window.open(url, name, 'resizable=yes');
	newwindow.resizeTo(width, height)
	if (window.focus)
		newwindow.focus();
	return false;
}

function sendMail() {
	//document.mailForm.submit();
	ajaxMail();
}

function ajaxMail() {
	ajaxSendFormById("ajaxmail.php", "mailForm", "miolo");
}

function change(image, picture) {
	document.getElementById(image).src = picture;
}

function change2(picture) {
	document.theimg2.src = picture;
}
*/
function startList() {
	if (document.all && document.getElementById) {
		navRoot = document.getElementById("nav");
		for (i=0; i<navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			if (node.nodeName.toLowerCase() == "li") {
				node.onmouseover=function() {
					this.className+=" over";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" over", "");
				}
			}
		}
	}
}

function atribue(url) {
	$('#jq-primaryNavigation .jq-current').removeClass('jq-current');
	var arr = url.split(".");
	$('#jq-primaryNavigation .'+arr[0]).addClass('jq-current');

}

//prepara plugin form para formulario de contato
function ligaFormContato() {
	$("#loadContato").hide();

	$('#formContato').ajaxForm({
		//~ target: '#erroHome',			// target element(s) to be updated with server response
		url: 'contato.php',			// server url to call
		beforeSubmit: validarContato,		// função a executar antes de submeter
		dataType: '',					// forma da resposta do server; header('Content-Type: text/plain; charset=ISO-8859-1');
		success: resultadoContato,	// função a executar após retorno do server
		type: 'POST'						// tipo de submissão
		}
	);

}

//validando o formulário
function validarContato(formData, jqForm, options) {
	var check = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
	var status = "";
	$("#erroContato").hide();
	var mySplitResult = $("#required", jqForm).val().split(",");
	//~ alert("mySplitResult="+mySplitResult);
	for(i = 0; i < mySplitResult.length; i++){
		var varname = mySplitResult[i];
		var varvalue = $("input[name="+varname+"]", jqForm).val();
		if (!varvalue)
			varvalue = $("select[name="+varname+"]", jqForm).val();
		if (!varvalue)
			varvalue = $("textarea[name="+varname+"]", jqForm).val();
		//~ alert("Element " + i + " = " + varname + '=' + varvalue);
		if (!varvalue) { status += '<li>Informe '+varname+'</li>';}
	}
	if(status!="") {
		$('#erroContato').empty();
		$('#erroContato').append(status);
		$('#erroContato').fadeIn('slow');
		return false;
	}
	else {
		$('input[name=action]', jqForm).val('processa');
	}

	$("#loadContato").fadeIn('slow');
	$('#erro_form').fadeOut('slow');
}

// Callback do retorno do ajax;
function resultadoContato(responseText, statusText) {
	//~ alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + '\n\nThe output div should have already been updated with the responseText.');
	$("#loadContato").fadeOut('slow');
	$('#erroContato').html(responseText);
	$('#erroContato').fadeIn('slow');
	$('#formContato').resetForm();
}




//esqueceu a Senha??
function esqueceuSenha() {
	alert("esqueceu a senha ?");
}

//login do home (left.php)
function logarHome(funcao) {
//~ alert('logarHome '+funcao);
	$('#LOGON').val(funcao);
	//~ document.formCadastro.submit();
	$('#formLogon').submit();
}

//prepara plugin form para formulario de login do home
function startLogonHome() {
//~ alert('startLogonHome');
	$("#loadHome").hide();

	$('#imglogin').click(function() {
		logarHome($('#action').val());
		});
	$('#imglogin').mouseover(function() {
		$(this).attr('src',$('#action').val()=='login'?'images/user_green.png':'images/user_red.png');
		});
	$('#imglogin').mouseout(function() {
		$(this).attr('src',$('#action').val()=='login'?'images/user_red.png':'images/user_green.png');
		});

	$('#formLogon').ajaxForm({
		//~ target: '#erroHome',		// target element(s) to be updated with server response
		url: 'logonHome.php',			// server url to call
		beforeSubmit: validarHome,		// função a executar antes de submeter
		dataType: 'xml',					// xml request; forma da resposta do server
		success: resultadoLoginHome,	// função a executar após retorno do server
		type: 'POST'						// tipo de submissão
		}
	);

}

//validando o formulário de logon do Home (left.php)
function validarHome(formData, jqForm, options) {
	var check = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
	$('#erroHome ul').empty();
	if ($('#LOGON').val() == 'logoff')
		return true;
 	var email = $('input[name=email]', jqForm).val();
	var senha = $('input[name=senha]', jqForm).val();
	var status = "";

	if(!email)
		status += '<li>E-mail vazio</li>';
	//~ else if(!check.test(email))
		//~ status += '<li>E-mail inválido</li>';

	if(!senha) {status += '<li>Informe a senha</li>';}

	if(status) {
		$('#erroHome').fadeIn('slow');
		$('#erroHome ul').append(status);
		return false;
	}
	//~ else {
		//~ $('input[name=LOGON]', jqForm).val('processa');
	//~ }
	$("#loadHome").fadeIn('fast');
	$('#erroHome').fadeOut('fast');
	return true;
}

//recebe o controle após retorno de "logonHome.php"
function resultadoLoginHome(responseText, statusText) {
	//~ alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + '\n\nThe output div should have already been updated with the responseText.');
//	var retorno = parseInt($(responseText, 'login').text());

	//limpa área com resultado do logon
	$("#loadHome").fadeOut('fast');
	$('#erroHome').hide();
	var erro = $('erro', responseText).text();
	//~ alert(erro);
	//logonHome.php devolve resultado do login na tag <login>; pode ser '1' ou '0'
	var login = parseInt($('login', responseText).text());
	if (login == 1) {
		// mais ações podem ser adicionadas aqui para o login encontrado
		$('#formLogon').resetForm();
	}
	//logonHome.php devolve status de usuario logado na tag <userlogado>; pode ser 'True' ou 'False'
	userLogado = $('userlogado', responseText).text();
	$('#LOGON').val(userLogado);
	if (userLogado == 'True') {
		$('#action').val("logoff");
		$('#imglogin').attr({
			src: "images/user_green.png",
			title: "sair",
			alt: "sair"
		});
	} else {
		$('#action').val("login");
		$('#imglogin').attr({
			src: "images/user_red.png",
			title: "entrar",
			alt: "entrar"
		});
	}
	$('#erroHome ul').empty();
	$('#erroHome').fadeIn('slow');
	$('#erroHome ul').append('<li>'+erro+'</li>');
	$('#menu').load('menuHome.php');
	//~ startLogonHome();
}




/* funções do administrativo
 */


//prepara plugin form para formulario de login do admin
function startLogon() {

	$("#carregando").hide();

	//~ $("#carregando").ajaxStart(function(){
			//~ $(this).fadeIn('fast');
			//~ $('#erro_form').fadeOut('fast');
		//~ }
	//~ );

	//~ $("#carregando").ajaxStop(function(){
		//~ $(this).fadeOut('fast');
		//~ }
	//~ );

//	$('#erro_form').hide();

	$('#formLogon').ajaxForm({
		target: '#login_admin',		// target element(s) to be updated with server response
		url: 'logonAdmin.php',			// server url to call
		beforeSubmit: validarUser,	// função a executar antes de submeter
		dataType: 'xml',					// xml request; forma da resposta do server
		success: resultadoLogin,	// função a executar após retorno do server
		type: 'POST'					// tipo de submissão
		}
	);

}

//validando o formulário de logon
function validarUser(formData, jqForm, options) {
	// formData is an array; here we use $.param to convert it to a string to display it
	// but the form plugin does this for you automatically when it submits the data
	var queryString = $.param(formData);
	// jqForm is a jQuery object encapsulating the form element.  To access the
	// DOM element for the form do this:
	// var formElement = jqForm[0];
	//~ alert('About to submit: \n\n' + queryString);

 	var usuario = $('input[name=USUARIO]').fieldValue();
	var senha = $('input[name=SENHA]').fieldValue();
	var status = "";
//	document.formLogon.ACAO.value = "check";

	if(!usuario[0]) {status += '<li>Informe o usuário</li>';}

	if(!senha[0]) {status += '<li>Informe a senha</li>';}

	$('#erro_form ul').empty();
	if(status!="") {
		$('#erro_form').fadeIn('slow');
		$('#erro_form ul').append(status);
		return false;
	}
	$("#carregando").fadeIn('fast');
	$('#erro_form').fadeOut('fast');
	return true;
}

// Callback do retorno do ajaxForm;
function resultadoLogin(responseText, statusText) {
    // for normal html responses, the first argument to the success callback
    // is the XMLHttpRequest object's responseText property

    // if the ajaxForm method was passed an Options Object with the dataType
    // property set to 'xml' then the first argument to the success callback
    // is the XMLHttpRequest object's responseXML property

    // if the ajaxForm method was passed an Options Object with the dataType
    // property set to 'json' then the first argument to the success callback
    // is the json data object returned by the server

	//~ alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + '\n\nThe output div should have already been updated with the responseText.');
//	var retorno = parseInt($(responseText, 'login').text());

	$('#erro_form').hide();
	$("#carregando").fadeOut('fast');
	var retorno = parseInt($('login', responseText).text());
	if(retorno == 1) {
		//no lugar da instrução abaixo, usar jQuery para hiden o ul de logoff
		loadMenu();
		$('#conteudo_admin').load(admin + 'blank.php?' + sid);
//		$("#menuadmin").load(admin + "menuadmin.php");
		// mais ações podem ser adicionadas aqui para o login encontrado
		$('#formLogon').resetForm();
		$('#login_admin').empty();
		$('input[id="userLogado"]').val("true");
	} else {
		var erro = $('erro', responseText).text();
		$('#erro_form ul').empty();
		$('#erro_form').fadeIn('slow');
		$('#erro_form ul').append('<li>'+erro+'</li>');
		alert(erro);
	}
	startLogon();
}

function logoff(id) {
	$('#erro_carga ul').empty();
	$('#conteudo_admin').empty();
	$("#login_admin").load(admin + "logonAdmin.php", {'ACAO': "logoff"}, function() {
			loadMenu();
			startLogon();
			$('input[id="userLogado"]').attr("value","false");
		}
	);
}
//carga do menu admin
function loadMenu() {
//alert("loadMenu " + admin);
	$("#menuadmin").load(admin + "menuadmin.php?" + sid, {}, function() {
			startList();
		}
	);
}


