/*
// external.js
// este arquivo contempla as functions utilizadas na área não logada do sistema
*/
/**** INIT DAS PÁGINAS ****/
	function init_announces() {
		CopyHeight('effectbar','space','section');
		// validada formulario e submete-o em caso de sucesso
		sendAnnounce();
	};
	function init_home() {
		addJS('../js/external/home.js');
		login();
		addAboutSite();
	};
	function init_indicatesFriend() {
		CopyHeight('effectbar','space','section');
		sendIndicates();
		addAboutSite();
	};
	function init_partnerships() {
		CopyHeight('effectbar','space','section');
		// validada formulario e submete-o em caso de sucesso
		sendPartner();
		// pop-up sobre o site
		addAboutSite();
	};
	function init_registerUserStepFour() {
		// ajuste vertical
		CopyHeight('effectbar','space','registerformbig');
		CopyHeight('effectbar2','destaktext');
		CopyHeight('effectbar3','correio');
		// atualiza o cookie para não experirar enquanto o usuário se cadastra
		setInterval(function () { activeUrlRefreshCookie() }, 840000);
		// aplica funcionalidade aos botões enviar foto
		addUploadPhoto();
	};
	function init_registerUserStepThree() {
		// ajuste vertical
		CopyHeight('effectbar','space','registerformbig');
		// restringe o número de cliques
		RestrictClick('.relacaovalorizo',5);
		// limitar caracteres
		LimitCharacters("#comentario1",600,"#contador1");
		LimitCharacters("#comentario2",600,"#contador2");
		LimitCharacters("#minhafrase",70,"#contador3");
		// atualiza o cookie para não experirar enquanto o usuário se cadastra
		setInterval(function () { activeUrlRefreshCookie() }, 840000);
		$('#contador1')[0].value = $('#comentario1')[0].value.length;
		$('#contador2')[0].value = $('#comentario2')[0].value.length;
		$('#contador3')[0].value = $('#minhafrase')[0].value.length;
	};
	function init_registerUserStepTwo() {
		addJS('../js/external/registerUserStepTwo.js');
		CopyHeight('effectbar','space','registerformbig');
		// Restringindo clique dinamicamente
		RestrictClick('#tiporelacionamento', 2);
		// troca as opções de estado civil de acordo com o sexo do usuário
		opposingCivilState();
		// troca as palavras (dele/dela ou ele/ela) de acordo com a escolha do usuario
		opposingSex();
		// atualiza o cookie para não expirar enquanto o usuário se cadastra
		setInterval(function () { activeUrlRefreshCookie() }, 840000);
	};
// function login()
// author: Leonardo Souza
// description:  funcionalidade para limpar os campos de login e senha na home
// used in: home
function login() {
	$("#userlogin")[0].focus();
}
// function RestrictClick(target, limit)
// author: Leonardo Souza
// description: restringe a quantidade de campos do tipo checkbox que podem ser selecionados
// used in: cadastro_passo2, cadastro_passo3
function RestrictClick(target, limit, exception, equal, escopetarget) {
	$(target + " input[@type=checkbox]").click(
		function() {
			if($(target + " input[@type=checkbox]:checked").length > limit && this.id != exception) {
				this.checked = false;
			} else if(this.id == exception) {
				if(this.checked == true) {
					$(equal)[0].checked = false;
					for(i=1;i<$(target + " input[@type=checkbox]").length;i++) {
						$(target + " input[@type=checkbox]")[i].checked = false;
						$(target + " input[@type=checkbox]")[i].disabled = 'disabled';
					}
					$("#" + this.name + "Importance ul li div input")[0].checked="checked";
					$("#" + this.name + "Importance ul li div input").attr('disabled','disabled')[0].disabled = false;
				} else {
					for(i=1;i<$(target + " input[@type=checkbox]").length;i++) {
						$(target + " input[@type=checkbox]")[i].disabled = '';
					}
					$("#" + this.name + "Importance ul li div input").attr('disabled','');
				}
			} else if($(target + " input[@type=checkbox]:checked").length == limit-1) {
				var fieldname = new String(this.id);
				var re = new RegExp("^dele_");
				if(fieldname.match(re)) {
					for(i=0;i<$(target + " input[@type=checkbox]").length;i++) {
						if(i == 0) {
							$(target + " input[@type=checkbox]")[i].checked = true;
						} else {
							$(target + " input[@type=checkbox]")[i].checked = false;
							$(target + " input[@type=checkbox]")[i].disabled = 'disabled';
						}
					}
					if($(equal)[0].checked == true) {
						$(equal)[0].checked = false
					}
				}
			}
			if(this.checked == true) {
				if($(equal)[0].checked == true) {
					for(i=0;i<$(target + " input[@type=checkbox]").length;i++) {
						if($(target + " input[@type=checkbox]")[i].checked == true) {
							for(x=0;x<$(escopetarget + " input[@type=checkbox]").length;x++) {
								$(escopetarget + " input[@type=checkbox]")[x].checked = false;
							}
							if($(escopetarget + " input[@type=checkbox]")[i+1] != undefined) {
								$(escopetarget + " input[@type=checkbox]")[i+1].checked = true;
							}
						}
					}
				}
			} else {
				for(x=1;x<$(escopetarget + " input[@type=checkbox]").length;x++) {
					if($(target + " input[@type=checkbox]")[x-1].checked == true && $(escopetarget + " input[@type=checkbox]")[0].checked != true && $(equal)[0].checked == true) {
						$(escopetarget + " input[@type=checkbox]")[x].checked = true;
					} else {
						if($(equal)[0].checked == true) {
							$(escopetarget + " input[@type=checkbox]")[x].checked = false;
						}
					}
				}
			}
		}
	);
}
// function EqualsFields(target, escope1,escope2)
// author: Leonardo Souza
// description: iguala checkbox dentro do(s) escopo(s) especificado(s)
// used in: cadastro_passo2
function EqualsFields(target, escope1,escope2) {
	$(target).click(
		function() {
			if(this.checked == true) {
				if($(escope2 + " input[@type=checkbox]")[0].checked == true) {
					for(x=0;x<$(escope2 + " input[@type=checkbox]").length;x++) {
						$(escope2 + " input[@type=checkbox]")[x].checked = false;
						$(escope2 + " input[@type=checkbox]")[x].disabled = '';
					}
					$("#" + $(escope2 + ' li input')[0].name + "Importance ul li div input").attr('disabled','');
				}
				for(i=0;i<$(escope1 + " input[@type=checkbox]").length;i++) {
					if($(escope1 + " input[@type=checkbox]")[i].checked == true) {
						for(x=0;x<$(escope2 + " input[@type=checkbox]").length;x++) {
							$(escope2 + " input[@type=checkbox]")[x].checked = false;
							$(escope2 + " input[@type=checkbox]")[x].disabled = '';
						}
						$(escope2 + " input[@type=checkbox]")[i+1].checked = true;
					}
				}
			} else {
				for(x=0;x<$(escope2 + " input[@type=checkbox]").length;x++) {
					$(escope2 + " input[@type=checkbox]")[x].checked = false;
				}
			}
		}
	);
	$(escope2).click( function() { $(target)[0].checked = false; } );
}
// function EqualsCombos(target, escope1,escope2)
// author: Renato Rodrigues - renato [ponto] sp [arroba] gmail [ponto] com
// description: iguala comboboxes dentro do(s) escopo(s) especificado(s)
// used in: cadastro_passo2
function EqualsCombos(target, escope1,escope2) {
	$(target).click(
		function() {
			if(this.checked == true) {
				if ($(escope1)[0].options[$(escope1)[0].selectedIndex].value != "" && $(escope1)[0].selectedIndex < $(escope2)[0].length) {
						$(escope2)[0].selectedIndex = $(escope1)[0].selectedIndex;
						$("#" + $(escope2)[0].name + "Importance ul li div input").attr('disabled','');
				} else {
					this.checked = false;
					$(escope1)[0].focus();
				}
			}
		}
	);
	$(escope1).change(
		function() {
			if($(target)[0].checked == true) {
				if (this.options[this.selectedIndex].value != "" && (this.selectedIndex < $(escope2)[0].length)) {
					$(escope2)[0].selectedIndex = this.selectedIndex;
				} else {
					$(escope2)[0].selectedIndex = 0;
					$(target)[0].checked = false;
				}
			}
		}
	);
	$(escope2).change(
		function() {
			if($(target)[0].checked == true) {
				$(target)[0].checked = false;
			}
			if(this.selectedIndex == 0) {
				$("#" + this.name + "Importance ul li div input")[0].checked="checked";
				$("#" + this.name + "Importance ul li div input").attr('disabled','disabled')[0].disabled = false;
			} else {
				$("#" + this.name + "Importance ul li div input").attr('disabled','');
			}
		}
	);
}
// function LimitCharacters(strfield,maxlength)
// author: Leonardo Souza
// description: restringe a quantidade de caracteres digitados dentro do(s) campo(s) especificado(s)
// used in: cadastro_passo3
function LimitCharacters(strfield,maxlength,cont) {
	$(strfield).keyup(
		function() {
			var txtlength = new String(this.value);
			var chars = maxlength-txtlength.length;
			var qtdchars = this.value.length;
			if($(cont)[0].value >= maxlength) {
				if(qtdchars>=maxlength){
					$(cont)[0].value = maxlength;
				}else{
					$(cont)[0].value = qtdchars;
				}
			} else {
				if(qtdchars>=maxlength){
					$(cont)[0].value = maxlength;
				}else{
					$(cont)[0].value = qtdchars;
				}
			}
			if(chars <= 0) {
				var chars = 0;
				this.value = this.value.substr(0,maxlength);
			}
		}
	);
}
// TQI
// function goUrl
// author: TQI (Original) // Leonardo Souza  (adaptação jquery)
// description:  seta os parametros do usuário levando a página de resultados de busca
// used in: busca externa
function goUrl(){
	if($('#procuro') && $('#idade') && $('#estado')) {
		document.location = self.location.protocol + '//' + self.location.host + '/external-search/' + $('#procuro')[0].value + '_' + $('#idade')[0].value + '_' + $('#estado')[0].value + '.html';
	}
}
// function validaReligiao(selecionado, num)
// author: Hugo Sena Ribeiro - hugosenari [arroba] gmail [ponto] com
// description: Não permite a seleção de valores iguais nos combos
// used in: cadastro_passo2
function validaReligiao(selecionado, num) {
	var _ = [0,0,0];
	options = $(selecionado).parent().children('select').children('option');
	_[num] = selecionado.selectedIndex;
	for (i = 2; i < (options.length/3); i++){
		if (options[i].selected == true) {
			_[0] = i;
			options[i+(options.length/3)].style.display = 'none';
			options[i+((options.length/3)*2)].style.display = 'none';
		}
		if (options[i+(options.length/3)].selected == true) {
			_[1] = i;
			options[i].style.display = 'none';
			options[i+((options.length/3)*2)].style.display = 'none';
		}
		if (options[i+((options.length/3)*2)].selected == true) {
			_[2] = i;
			options[i].style.display = 'none';
			options[i+(options.length/3)].style.display = 'none';
		}
	}
	for (i = 1; i < ((options.length)/3); i++){
		if (i != _[0] && i != _[1] && i != _[2]) {
			options[i].style.display = 'block';
			options[i+(options.length/3)].style.display = 'block';
			options[i+((options.length/3)*2)].style.display = 'block';
		}
	}
}
// function opposingSex()
// author: Leonardo Souza
// description: inteligência para trocar os textos baseando-se na escolha do usuário
// used in: cadastro_passo2, home logada
function opposingSex() {
	$('#dele_procuro').change(
	    function() {
	        var index = $(this)[0].options.selectedIndex;
	        var searchsex = $(this)[0].options[index].value;
	        var usersex = $('#usersex').attr('value');
			//var arrEscopo = ['#deleestadocivil label'];
	        if((usersex == "M" && (searchsex == "M")) || (usersex == "F" && (searchsex == "M" || searchsex == "B"))) {
	            $('form span').each(
	                function() {
	                    if($(this).text().length == 3) {
	                        $(this).text('ele');
	                    } else {
	                        $(this).text('dele');
	                    }
	                }
	            );
				/*for(i=0;i<arrEscopo.length;i++) {
					$(arrEscopo[i]).each(
					    function() {
					        var strText = new String($(this).text());
					        var expReg = /a\b/gi;
					        $(this).text(strText.replace(expReg,'o'));
					    }
					);
				}*/
	        } else {
	            $('form span').each(
	                function() {
	                    if($(this).text().length == 3) {
	                        $(this).text('ela');
	                    } else {
	                        $(this).text('dela');
	                    }
	                }
	            );
				/*for(i=0;i<arrEscopo.length;i++) {
					$(arrEscopo[i]).each(
					    function() {
					        var strText = new String($(this).text());
					        var expReg = /o\b/gi;
					        $(this).text(strText.replace(expReg,'a'));
					    }
					);
				}*/
			}
	    }
	);
}
function opposingCivilState() {
	var arrEscopo = ['#meuestadocivil label','#deleestadocivil label'];
	for(i=0;i<arrEscopo.length;i++) {
		$(arrEscopo[i]).each(
			function() {
				var strText = new String($(this).text());
				var expReg = /[a-z]\(a\)?/gi;
				var usersex = $('#usersex').attr('value');
				if(i == 0) {
					if(usersex == 'M') {
						$(this).text(strText.replace(expReg,'o'));
					} else {
						//$(this).text(strText.replace(expReg,'a'));
						$(this).text(strText.replace(expReg,'o'));
					}
				} else {
					if(usersex == 'M') {
						//$(this).text(strText.replace(expReg,'a'));
						$(this).text(strText.replace(expReg,'o'));
					} else {
						$(this).text(strText.replace(expReg,'o'));
					}
				}
			}
		);
	}
}
function activeUrlRefreshCookie(){
	$('.refreshcookie').append('<iframe src ="https://cadastro.acesso.uol.com.br/refreshCookie.html?url=http://metadeideal.uol.com.br"></iframe>');
}
function sendAnnounce() {
	$(".btsendannounce").click(
		function(){
			checkFormText({errAll:erros, okAll:oks},['#Nome, #Empresa', /.+/],['#Email', /.+@.+\..+/],['#Telefones input', /^\d+/])
		}
	);
}
function sendPartner() {
	$(".btsendpartner").click(
		function(){
			checkFormText({errAll:erros, okAll:oks},['#Nome, #Url_site, #Pageviews_mensais', /.+/],['#Email', /.+@.+\..+/],['#Telefones input', /^\d+/])
		}
	);
}
function sendIndicates() {
	$(".btsendindicates").click(
		function(){
			checkFormText({errAll:erros, okAll:oks},['.full[@name="Nome"], .full[@name="NomePara"]', /.+/],['.full[@name="Email"], .full[@name="CorreioPara"]', /.+@.+\..+/])
		}
	);
}
	// callback error
	erros = function(){
		showMsg('Os campos marcados abaixo estão incorretos. Por favor, preencha-os novamente.', 'alertnew');
		CopyHeight('effectbar','space','section');
		window.scrollTo(0,0);
	}
	// callback success
	oks = function(){$('#content form')[0].submit()}
function addUploadPhoto() {
	$("#facephoto").add('#extraphoto1').add('#extraphoto2').click(
		function() {
			//$(this).attr('href','javascript:;');
			if(parseInt($('.'+$(this).attr('id')).val()) == 0) {
				if($(this).parent().parent().find('.i'+$(this).attr('id')).val() != '') {
					$(this).parent().parent().parent()[0].submit();
				} else {
					scrollTo(0,0);
					showMsg('Clique em "Browse ou Arquivo" e escolha uma foto em seu computador.','error');
				}
			} else {
				if($(this).parent().parent().find('.i'+$(this).attr('id')).val() != '') {
					self.location = 'http://'+skinDomain+'/register/registerUserStepFourFinish.html'+self.location.search;
				} else {
					scrollTo(0,0);
					showMsg('Clique em "Browse ou Arquivo" e escolha uma foto em seu computador.','error');
				}
			}
		}
	);
}
function notConfirm() {
	$('#btnao').click(
		function() {
			self.location = 'http://'+skinDomain+'/app/userHome.html';
		}
	);
}