/**
// main.js
// este arquivo contempla as functions utilizadas em mais de uma área específica
*/

// function CopyHeight()
// author: Renato Albano - renatoalbano [arroba] gmail [ponto] com
// description: iguala dois ou mais boxes pela altura do maior
// used in: all pages
function CopyHeight() {
	var heights = [];
	for (var i = 0; i < arguments.length; i++) {
		if(document.getElementById(arguments[i])){
			document.getElementById(arguments[i]).style.height = '';
			heights.unshift(document.getElementById(arguments[i]).offsetHeight);
		}
	}
	hT = heights.sort(function(a,b){ return a - b }).reverse()[0]; //ninja *[1]
	for (var i = 0; i < arguments.length; i++)
		if(document.getElementById(arguments[i])){
			document.getElementById(arguments[i]).style.height = hT+'px';
		}
}

// function addPercentCompability()
// author: Leonardo Souza
// description: seta dinamicamente a barra de porcentagem de afinidade dos usuários da lista Minhas Metades
// used in: todas as instâncias de Minhas Metadas (obs: dependência do arquivo /lib/progressbar.js)
function addPercentCompability() {
	$('.percent').each(
		function() {
			var progress = new Number($(this)[0].firstChild.nodeValue);
			$(this).parent().next().reportprogress(progress);
		}
	);
}

/**
 * Converte os campos de um form para um array no formato aceito pelas funções Ajax do jQuery
 * @author Renato Rodrigues - renato [ponto] sp [arroba] gmail [ponto] com
 * @version 0.2
 * @param form (element) Elemento que contem os campos a serem serializados
*/
function fieldsToArray(form) {
	var tmpArr = new Array();
	var fields = $('input, select, textarea', $(form)).not('[@type=checkbox], [@type=radio]', form).add($('input[@checked]', $(form)));
	fields.each( function(i) {
		if (fields[i].name != '') {
			tmpArr[i] = ( { name: fields[i].name , value: fields[i].value } );
		};
	} );
	return tmpArr;
}

// function getState()
// author: Leonardo Souza leonardodisouza [arroba] gmail [ponto]
// description:  preenchimento de combo de estado
// used in: quickSearch, searchOnlineUsersForm, keyWordSearch, detailedSearch, homeSearch, Search Results, userHome
function getState(userOption) {
	var countrySelected = $('#pais')[0].value;
	if (countrySelected != '') {
		if($('#estado').length !=0) {
			$('#estado')[0].options.length = null;
			$('#estado')[0].options[0] = new Option('Carregando...','');
		}
		if(countrySelected != '' && $('#estado').length !=0) {
			jQuery.ajax({
				type: "GET",
				url: "/preview/ajaxGetStates.html",
				data: "countryId="+countrySelected,
				dataType: "json",
				success: function(jsonData) {
					if(jsonData.states.length > 0) {
						if($('#cidade').length !=0) {
							$('#cidade')[0].options[0] = new Option('Indiferente','0');
						}
						if($('#estado').length !=0) {
							$('#estado')[0].options[0] = new Option('Indiferente','0');
							$('#estado')[0].options[0].selected = true;
							for(i=0;i<jsonData.states.length;i++) {
								if(jsonData.states[i].state != undefined) {
									if(userOption && userOption == jsonData.states[i].id) {
										$('#estado')[0].options[i+1] = new Option(jsonData.states[i].state,jsonData.states[i].id);
										$('#estado')[0].options[i+1].selected = true;
									} else {
										$('#estado')[0].options[i+1] = new Option(jsonData.states[i].state,jsonData.states[i].id);
									}
								}
							}

						}
					} else {
						if($('#estado').length !=0) {
							$('#estado')[0].options.length = null;
							$('#estado')[0].options[0] = new Option('Falha ao Carregar...','');
						}
						if($('#cidade').length !=0) {
							$('#cidade')[0].options.length = null;
							$('#cidade')[0].options[0] = new Option('Falha ao Carregar...','');
						}
					}
				}
			});
		}
	} else {
		if($('#estado').length !=0) {
			$('#estado')[0].options.length = null;
			$('#estado')[0].options[0] = new Option('Indiferente','0');
		}
		if($('#cidade').length !=0){
			$('#cidade')[0].options.length = null;
			$('#cidade')[0].options[0] = new Option('Indiferente','0');
		}
	}
}

function addGetState(userOption) {
	$('#pais').change(function() { getState(userOption) }).each( function() { getState(userOption) });
}


// function getCity()
// author: Leonardo Souza leonardodisouza [arroba] gmail [ponto]
// description:  preenchimento de combo de cidade
// used in: quickSearch, searchOnlineUsersForm, keyWordSearch, detailedSearch, homeSearch, Search Results, userHome
function getCity(userOption) {
	var stateSelected = $('#estado')[0].value;
	var stateIdUserChoice = $('#stateIdUserChoice')[0].value;
	if(stateSelected != '' || userOption != '' || stateIdUserChoice != '') {
		if($('#cidade').length !=0) {
			$('#cidade')[0].options.length = null;
			$('#cidade')[0].options[0] = new Option('Carregando...','');
		}
		if((stateSelected != '' && $('#cidade').length !=0) || (stateIdUserChoice != '' && $('#cidade').length !=0)) {
			(stateSelected == '') ? stateSelected = stateIdUserChoice : stateSelected = stateSelected;
			if(stateSelected != '0') {
				jQuery.ajax({
					type: "GET",
					url: "/preview/ajaxGetCities.html",
					data: "stateId="+stateSelected,
					dataType: "json",
					success: function(jsonData) {
						if(jsonData.cities.length > 0) {
							if($('#cidade').length !=0) {
								$('#cidade')[0].options[0] = new Option('Indiferente','0');
								for(i=0;i<jsonData.cities.length;i++) {
									if(jsonData.cities[i].city != undefined) {
										if(userOption && userOption == jsonData.cities[i].id) {
											$('#cidade')[0].options[i+1] = new Option(jsonData.cities[i].city,jsonData.cities[i].id);
											$('#cidade')[0].options[i+1].selected = true;
										} else {
											$('#cidade')[0].options[i+1] = new Option(jsonData.cities[i].city,jsonData.cities[i].id);
										}
									}
								}
							}
						} else {
							if($('#cidade').length !=0) {
								$('#cidade')[0].options.length = null;
								$('#cidade')[0].options[0] = new Option('Falha ao Carregar...','');
							}
						}
					}
				});
			} else {
				if($('#cidade').length !=0) {
					$('#cidade')[0].options.length = null;
					$('#cidade')[0].options[0] = new Option('Indiferente','0');
				}
			}

		}
	} else {
		if($('#cidade').length !=0){
			$('#cidade')[0].options.length = null;
			$('#cidade')[0].options[0] = new Option('Indiferente','0');
		}
	}
}

function addGetCity(userOption) {
	$('#estado').change(function() { getCity(userOption) }).each( function() { getCity(userOption) });
}

/**
 * Recebe um retorno AJAX, interpreta como JSON, exibe o status e chama as funcões de callback dependendo do resultado.
 * @author Renato Rodrigues - renato [ponto] sp [arroba] gmail [ponto] com
 * @version 0.4.1
 * @param url (string) URL do request ajax
 * @param data (string) Dados a serem enviados no request
 * @param opt (json) Parâmetros opcionais em formato JSON (msgElem, msgOkElem,  msgErrorElem, fnSuccess, fnError, fnServerError, method, contentType, cache, async)
*/
function parseJson(url, data, opt) {
	/** Acerta os parâmetros opcionais */
	if (!opt) opt = {};
	if (opt['method']) opt['method'] = opt['method'].toUpperCase();
	if (opt['msgElem']) opt['msgOkElem'] = opt['msgErrorElem'] = opt['msgElem'];
	opt['contentType'] = ( (opt['method'] == 'POST') ? ('application/x-www-form-urlencoded') : (opt['contentType'] || ('text/plain')) );
	/** Dispara o Ajax */
	return jQuery.ajax({
		url: url,
		dataType: 'json',
		data: ( data || { } ),
		cache: ( opt['cache'] || true ),
		async: ( opt['async'] || true ),
		type: ( opt['method'] || 'GET' ),
		contentType: opt['contentType'],
		beforeSend: function(xhr) {
			xhr.setRequestHeader( "encoding", (opt['encoding'] || "ISO-8859-1") );
		},
		success: function(j){
			if (j.statusId === '0000') {
				/** Retorno com status OK, exibe a mensagem de sucesso, caso definida */
				if (opt['msgOkElem']) {
					showMsg(j.statusMessage, 'info', opt['msgOkElem']);
				/** Esconde alguma mensagem de erro que esteja sendo exibida */
				} else if (opt['msgErrorElem']) {
					$(opt['msgErrorElem']).addClass("hide");
				}
				/** Chama o Callback de sucesso, caso definido */
				if (opt['fnSuccess']) opt['fnSuccess'].call(this, j);
			} else if (j.statusId === '9996' || j.statusId === '9997' || j.statusId === '9998') {
				/** Retorno com Redirect, redireciona em caso de usuário não logado ou não autorizado a acessar o endereço requisitado */
				self.location.href = j.redirectURL+self.location.search;
			} else {
				/** Retorno com status de erro, exibe a(s) mensagem(ns) de erro retornada(s), caso definidas */
				if (opt['msgErrorElem']) {
					var errMsg = new String("");
					for (var id in j.statusMessage) {
						errMsg += j.statusMessage[id] + "<br />";
					}
					showMsg(errMsg, 'error', opt['msgErrorElem']);
				/** Esconde alguma mensagem de sucesso que esteja sendo exibida */
				} else if (opt['msgOkElem']) {
					$(opt['msgOkElem']).addClass("hide");
				}
				/** Chama o Callback de erro, caso definido */
				if (opt['fnError']) opt['fnError'].call(this, j);
			}
		},
		error: function (xhr) {
			/** Caso dê erro no retorno da resposta AJAX exibe a mensagem de erro no elemento definido  */
			if (opt['msgErrorElem']) {
				try {
					if (xhr.status == '200') {
						var errMsg = "Erro ao interpretar a resposta do servidor.<br />Resposta Inválida";
					} else {
						var errMsg = "Erro ao comunicar-se com o servidor.<br />Status: " + xhr.status + ": " + unescape(xhr.statusText).replace(/\+/g," ");
					}
					showMsg(errMsg, (xhr.status == '200')?('alert'):('error'), opt['msgErrorElem']);
				} catch(e) {}
			/** Esconde alguma mensagem de sucesso que esteja sendo exibida */
			} else if (opt['msgOkElem']) {
				$(opt['msgOkElem']).addClass("hide");
			}
			/** Chama o Callback de erro de servidor, caso definido */
			if (opt['fnServerError']) opt['fnServerError'].call(this, xhr);
		}
	});
}


// function modelRoration()
// author: Leonardo Souza
// description: randomiza a fotos das "modelos" nas páginas do site
// used in: all pages
function modelRoration(protocol) {
		var arrModels = ['teka','r.lindinha.j','drika','lua526'];
		var arrAlign = ['right','right','left','left'];
		var valRandom = Math.round(Math.random()*arrModels.length);
		var valRandom = (valRandom >= arrModels.length) ? 3 : valRandom;
		var imgDomain = "http://metadeideal.img.uol.com.br";
		if (protocol == "https") imgDomain = "https://p.simg.uol.com.br/mi";
		$('#randomwoman').css('background','url(' + imgDomain + '/home/modelo0'+[valRandom]+'.jpg) 0 10px no-repeat');
		$('#randomwoman p').addClass(arrAlign[valRandom]);
		$('#randomwoman p strong').html(arrModels[valRandom]);
		$('#randomwoman p img').attr('src',imgDomain+'/arrow'+arrAlign[valRandom]+'silver.gif');
		$('#randomwoman p').removeClass('hide');

	}


// function setPageNumberSubmit(pageNumber)
// author: TQI
// description:  funcionalidade especifíca para navegação por paginação
// used in: busca_resultado
function setPageNumberSubmit(pageNumber,pageNumberComputing){
	$('#pageNumber').attr('value',pageNumber);
	if(pageNumberComputing) {
		$('form.paging').attr('action',$('#searchUrl').attr('value')+'?pageNumberComputing='+pageNumberComputing);
	}
	$('form.paging').submit();
}

/**
 * Funções para manipulação de objetos JSON
 * @author Renato Rodrigues - renato [ponto] sp [arroba] gmail [ponto] com
 * @version 0.2
*/
var jsonUtils = {
	/**
	 * Retorna o número de itens em um objeto JSON
	 * @param obj (json) Objeto JSON
	*/
	count: function(obj) {
		var i= 0;
		for (a in obj) {
			if (typeof obj[a] == 'string') i++;
		}
		return i;
	},
	/**
	 * Transforma um objeto JSON em Array comum
	 * @param obj (json) Objeto JSON
	*/
	toArray: function(obj) {
		var tmpArr = new Array();
		for (a in obj) {
			if (typeof obj[a] == 'string') tmpArr.push(new Array(a,obj[a]));
		}
		return tmpArr;
	},
	/**
	 * Retorna o primeiro item de um objeto JSON
	 * @param obj (json) Objeto JSON
	*/
	getFirst: function(obj) {
		return jsonUtils.toArray(obj)[0];
	},
	/**
	 * Retorna o último item de um objeto JSON
	 * @param obj (json) Objeto JSON
	*/
	getLast: function(obj) {
		var tmpArr = new Array();
		tmpArr = jsonUtils.toArray(obj);
		return tmpArr[tmpArr.length - 1];
	}
}

// function showMsg()
// author: Renato Rodrigues - renato [ponto] sp [arroba] gmail [ponto] com
// description: Exibe a mensagem no elemento especificado
//type: info alert error
function showMsg(msg, type, elem) {
	showMsgs(msg, type, elem, '#systemerror');
}

// function showMsgs()
// author: Renato Rodrigues - renato [ponto] sp [arroba] gmail [ponto] com
// description: Exibe a mensagem no elemento especificado
//type: info alert error
function showMsgs(msg, type, elem, hide) {
	if(hide && hide != '') $(hide).hide();
	type = (type)?(type):('alert');
	elem = (elem)?(elem):('#resultbox');
	$(elem + " p").html(msg);
	$(elem).removeClass("alert error info hide").addClass(type).fadeIn('slow');
}

// function addSearchHome()
// author: Leonardo Souza
// description: efetua buscas (básica e online) na páginas sem resultado (personalizadas)
function addSearchHome(urltrue,urlfalse) {
	$('#searchuseronline').click(
	    function() {
	        if($(this)[0].checked == true) {
				$('#quickSearchForm')[0].action = urltrue;
	        } else {
				$('#quickSearchForm')[0].action = urlfalse;
	        }
	    }
	);
}

function addInitPedingChats() {
	jQuery.ajax({
		type: "GET",
		url: "/app/ajaxGetInstantMessageNotice.html",
		dataType: "xml",
		success: function(responseXMLstatus) {
			$('useroption', responseXMLstatus).each(
				function() {
					var conf = $('chat', this).text();
					if(conf == 'on') {
						var vtime = 0;
						initPedingChats(vtime);

						var vtime = 15000;
						initPedingChats(vtime);
					}
				}
			);
		}
	});
}

// function LimitCharacters(strfield,maxlength)
// author: Leonardo Souza
// description: restringe a quantidade de caracteres digitados dentro do(s) campo(s) especificado(s)
// used in: profileEditor
function LimitCharacters(strfield,maxlength,cont) {
	$(strfield).keyup(
		function() {
			var txtlength = new String(this.value);
			var chars = maxlength-txtlength.length;
			var qtdchars = this.value.length;
			// Hack para corrigir problems com CRLF x CR (QC 2477)
			if (navigator.appVersion.indexOf("Win")!=-1) {
				var enters = this.value.match(/\n/g);
			}
			enters = enters || [];
			if($(cont)[0].value >= maxlength) {
				if(qtdchars>=maxlength){
					$(cont)[0].value = maxlength;
				}else{
					$(cont)[0].value = qtdchars + enters.length;
				}
			} else {
				if(qtdchars>=maxlength){
					$(cont)[0].value = maxlength;
				}else{
					$(cont)[0].value = qtdchars + enters.length;
				}
			}
			if(chars <= 0) {
				var chars = 0;
				this.value = this.value.substr(0,maxlength);
			}
		}
	);
}

// function addAboutSite()
// author: Raul Klumpp - raulklumpp [arroba] gmail [ponto] com
// description: adiciona popup no link 'Como funciona' do footer
function addAboutSite() {
	$('.btcomofunciona').click(
		function(){
			newWindow(this.href,'metadeideal',800,450,'no','center');
			return false;
		}
	);
}

// function newWindow()
// author: Raul Klumpp - raulklumpp [arroba] gmail [ponto] com
// description: exibe a popup centralizada
function newWindow(mypage,myname,w,h,scroll,pos){
	if(pos=="random"){
		LeftPosition=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;
		TopPosition=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;
	}

	if(pos=="center"){
		LeftPosition=(screen.width)?(screen.width-w)/2:100;
		TopPosition=(screen.height)?(screen.height-h)/2:100;
	}else if((pos!="center" && pos!="random") || pos==null){
		LeftPosition=0;
		TopPosition=20;
	}

	settings='width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';
	win=window.open(mypage,myname,settings);

	if(win.focus){
		win.focus();
		return false;
	}
}

// function isIE6()
// author: Renato Rodrigues - renato [ponto] sp [arroba] gmail [ponto] com
// description:  Verifica se o usuário está usando o IE6
// used in: profileEditor
function isIE6() {
	return ( window.ActiveXObject && typeof document.body.style.maxHeight == "undefined" );
}

// function intelligentText()
// author: Renato Rodrigues - renato [ponto] sp [arroba] gmail [ponto] com
// description:  Atualiza textos dinamicamente na interface de acordo com a sexualidade passda
// used in: profileEditor
var intelligentText = {
	get: function(wordMale, wordFemale, sex){
		if (sex == 'M') {
			return wordMale;
		} else {
			return wordFemale;
		}
	},
	busco: function() {
		$('#busco').change(
			function() {
				$('label[@for=searchuserphoto] span').html( intelligentText.get('usuários', 'usuárias', $(this).val() ) );
				$('label[@for=searchuseronline] span').html( intelligentText.get('usuários', 'usuárias', $(this).val() ) );
			}
		);
	},
	profileEditor: function() {
		$('#sexToSave').change(
		    function() {
	            $('#h5oqespero').css('background','url(http://metadeideal.img.uol.com.br/' + intelligentText.get('txoqueeuespero', 'txoqueeuesperodela', $(this).val() ) + '.gif)  no-repeat');
		    }
		);
	},
	detailedSearch: function() {
		$('#busco').change(
			function() {
				$('label[@for=characteristic_5637]').html( intelligentText.get('Pós-graduado', 'Pós-graduada', $(this).val() ) );
				$('label[@for=characteristic_1537]').html( intelligentText.get('Sozinho', 'Sozinha', $(this).val() ) );
			}
		);
	},
	userHome: function() { intelligentText.busco() },
	keyWordSearch: function() { intelligentText.busco() },
	searchOnlineUsersForm: function() { intelligentText.busco() }
}

// function showBar()
// author: Leonardo Souza
// description: faz um match na url e exibe a barra correta
function showBar() {
	if( document.location.toString().match(/https?:\/\/namoro/) ) {
		$('.barra_uolnamoro').show();
	} else if( document.location.toString().match(/https?:\/\/bolnamoro/) ) {
		$('.barra_bolnamoro').show();
	}
}

// function addHasFocus()
// author: Renato Rodrigues - renato [ponto] sp [arroba] gmail [ponto] com
// description:  Verifica se a janela tem foco e adiciona o resultado do teste em uma variável global
// used in: *
function addHasFocus() {
	hasFocus = true;
	oTitle = document.title;
	nTitle = "                                             ";
	dlId = "";

	window.onblur = function() {
		hasFocus = false;
	}

	window.onfocus = function() {
		hasFocus = true;
	}
}

// function changeTitle()
// author: Renato Rodrigues - renato [ponto] sp [arroba] gmail [ponto] com
// description:  Alterna o titulo da janela quando ocorrer um convite para bate papo
// used in:  chat, convite chat
function changeTitle() {
	dlId = setInterval ( function ( ) {
		if ( hasFocus ) {
			clearInterval ( dlId );
			document.title = oTitle;
		}
		else {
			document.title = ( document.title == nTitle ) ? oTitle : nTitle;
		}
	}, 1000);
}

// function restoreTitle()
// author: Renato Rodrigues - renato [ponto] sp [arroba] gmail [ponto] com
// description:  Alterna o titulo da janela quando ocorrer um convite para bate papo
// used in: chat, convite chat
function restoreTitle() {
	if ( typeof(dlId) == 'number') { clearInterval ( dlId ) };
	document.title = oTitle;
}

//function: checkFormText();
//author: Hugo Ribeiro - hugosenari [arroba] gmail [ponto] com
//description: Verificador de campos de texto, utilize sendPartner e sendAnnounces como exemplo
function checkFormText(){
	res = true, args = arguments;
	ok = args[0].ok||function(ele){$(ele).addClass('elementok').removeClass('elementerror')};
	okAll = args[0].okAll||function(){null};
	err = args[0].err||function(ele){$(ele).addClass('elementerror').removeClass('elementok')};
	errAll = args[0].errAll||function(){null};
	if (args.length > 0){
		for (i = 1; i < arguments.length; i++) {
			$(args[i][0]).each(function(){
				switch (this.nodeName){
					case "INPUT": if (!this.type.match(/text|password|file|hidden/)) break;
					case "TEXTAREA":
						if (this.value.match(args[i][1])) ok(this);
						else {err(this); res = false;}
						break;}});}}
	res ? okAll() : errAll();
}

// function keepSearch()
// description: passa os parametros da busca adiante
function keepSearching(exLnk, frm) {
    try{
	if(frm.length > 0){
		frm[0].method = "post";
		frm[0].action = exLnk;
		frm[0].submit();
		return false;
	} else	return true;
    }
    catch(e){
        return true;
    }
}

//function keepPushing
//description: "empurra" os parâmetros recebidos para frente, útil para links
function keepPushing(){
    return keepSearching(this.href, $(this).parents("form"));
}


// REFACTORING

var userActions = {
	blocked : {
		add: function(callback) {
			if ( this.tagName == 'A') btn = this;
			if ( typeof callback != 'function') { callback = toolbarResult.blocked.addOk; }
			parseJson(
				'/app/ajaxBlockProfile.html?' + btn.rel,
				{}, { msgErrorElem: "#resultbox", fnSuccess: callback }
			);
		},

		del: function(callback) {
			if ( this.tagName == 'A') btn = this;
			if ( typeof callback != 'function') { callback = toolbarResult.blocked.delOk; }
			parseJson(
				'/app/ajaxUnblockProfile.html?' + btn.rel,
				{}, { msgErrorElem: "#resultbox", fnSuccess: callback }
			);
		}
	},

	favorite : {
		add : function(callback) {
			if ( this.tagName == 'A') btn = this;
			if ( typeof callback != 'function') { callback = toolbarResult.favorite.addOk; }
			parseJson(
				'/app/ajaxManageFavoriteProfileAdd.html?' + btn.rel,
				{}, { msgElem: "#resultbox", fnSuccess: callback }
			)
		},

		del : function(callback) {
			if ( this.tagName == 'A') btn = this;
			if ( typeof callback != 'function') { callback = toolbarResult.favorite.delOk; }
			parseJson(
				'/app/ajaxManageFavoriteProfileRemove.html?' + btn.rel,
				{}, { msgElem: "#resultbox", fnSuccess: callback }
			);
		}
	},

	flashMail : {
		send : function() {
			userData = this.rel;
			parseJson(
				'/app/ajaxSendExpressMessage.html?' + userData + '&personalInfoAgreement=' + $('#personalInfoAgreement').val() + '&sensoredWordsAgreement=' + $('#sensoredWordsAgreement').val(),
				{},
				{
					fnSuccess: function(j){
						if ($('#sensoredWordsAgreement').val() == 'false' && $('#personalInfoAgreement').val() == 'false') {
							sendValidation.badWords(j, toolbarResult.flashMail.sendOk);
						} else {
							toolbarResult.flashMail.sendOk(j);
						}
					},
					fnError: toolbarResult.flashMail.sendError
				}
			);
		},

		edit : function() {
			$('.toId, .toNickname, toNicknames').remove();
			return keepPushing.apply(this);
		},
		sendToAll : function() {
			var url = new Array();
			$('input[@name=toId]').each( function(i) { url.push('toId=' + this.value) } );
			$('input[@name=toNickname]').each( function(i) { url.push('toNicknames=' + this.value) } );

			if (url.length > 0) {
				parseJson(
					'/app/ajaxSendExpressMessage.html?' + url.join('&') + '&personalInfoAgreement=' + $('#personalInfoAgreement').val() + '&sensoredWordsAgreement=' + $('#sensoredWordsAgreement').val(),
					{},
					{
						fnSuccess: function(j) {
							if ($('#sensoredWordsAgreement').val() == 'false' && $('#personalInfoAgreement').val() == 'false') {
								sendValidation.badWords(j, toolbarResult.flashMail.sendOk);
							} else {
								toolbarResult.flashMail.sendOk(j);
							}
						},
						fnError: toolbarResult.flashMail.sendToAllError
				    }
				);
			};
		}
	},
    profileView : keepPushing,

	message : {
		send: keepPushing
	},

	album : {
		view : keepPushing,
		viewProfile : keepPushing
	},

    photoAlbum : keepPushing
};

/*
 * Recebe um retorno AJAX, interpreta como JSON, exibe o status e chama as funcões de callback dependendo do resultado.
 * @author Renato Rodrigues - renato [ponto] sp [arroba] gmail [ponto] com
 * @version 0.4.1
 * @change {date: '19/05/2008', ticket: [2614], description : 'Adiciona evento no visualizar foto do visualizar perfil', test : ['visualizar perfil','como meu perfil é visto']}
*/
var toolbarEvents = {
	generic : function() {
		$(".sendFlashMail a").not('.cannot').click( userActions.flashMail.send ); //Enviar FlashMail
		$(".baractions .bteditar").not('.cannot').click( userActions.flashMail.edit ); //Editar FlashMail
		$("#sendFlashMailAll").click( userActions.flashMail.sendToAll ); //Enviar FlashMail para Todos

		$('.offline').click( // chat para usario offline)
			function() {
				showMsg(this.rel + ' não está online. Mande um e-mail ou um Flashmail','error');
			}
		);

		$('.cannot').click( // para usuario com sexualidade nao condizente
			function() {
				showMsg('Você NÃO pode se relacionar com ' + this.rel + '. A sexualidade de vocês não é condizente.','error');
			}
		);
	},

	//Páginas específicas
	searchResults : function() {
		toolbarEvents.generic(); //adiciona as funções de busca
		$(".baractions .btemail, .icons .icomail").not('.cannot').click( userActions.message.send ); //Enviar mensagem
		$(".btpretendente").add('.icoadd').click( userActions.favorite.add ); //Adicionar a Pretendente
		$(".btpretendenteremove").add('.icodel').click( userActions.favorite.del ); //Remover Pretendente
		$('.btdesbloquear').click( userActions.blocked.del ); //Desbloquear Usuário pela barra
		$(".extraphoto").click(userActions.album.view);
		$(".extraalbum").click(userActions.photoAlbum);
	},

	manageBlockedProfile : function() {
		//Remover Pretendente (Página de bloqueados)
		$('.btdesbloquear').click(
			function() {
				btn = this;
				userActions.blocked.del( toolbarResult.manageBlockedProfile );
			}
		);
	},

	manageFavoriteProfile: function() {
		toolbarEvents.generic(); //adiciona as funções genéricas
		$('.btdesbloquear').click( userActions.blocked.del ); //Desbloquear Usuário pela barra

		//Remover Pretendente (Página de meus pretendentes)
		$(".btpretendenteremove").click(
			function() {
				btn = this;
				userActions.favorite.del( toolbarResult.manageFavoriteProfile );
			}
		);
	},
	profileViewer : function() {
		toolbarEvents.generic(); //adiciona as funções genéricas
		$(".photoprofile a").click(userActions.album.view);//Visualizar abum (backTo)
		$(".baractions .btemail").not('.cannot').click( userActions.message.send ); //Enviar mensagem
		$(".btpretendente").click( userActions.favorite.add ); //Adicionar a Pretendente
		$(".btpretendenteremove").click( userActions.favorite.del ); //Remover Pretendente
		$('.btdesbloquear').click(
			function() {
				btn = this;
				userActions.blocked.del( toolbarResult.profileViewer ); //Desbloquear Usuário pela barra (Album)
			}
		)
	},

	album : function() {
		$(".btverperfil").click(userActions.album.viewProfile);//visualizar perfil (backTo)
		toolbarEvents.profileViewer();
	},

    photoAlbum : function(){
        toolbarEvents.album();
    },
	compareProfile : function() { toolbarEvents.searchResults() },
	favoriteFromUsers : function() { toolbarEvents.searchResults() },
	manageBirthdayFavoriteProfile: function() { toolbarEvents.manageFavoriteProfile() },
	manageOnlineFavoriteProfile: function() { toolbarEvents.manageFavoriteProfile() },
	profileViewLog: function() { toolbarEvents.searchResults() },
	manageOnlineNotify: function() { toolbarEvents.searchResults() }
};

//Funções de retorno de chamada ajax da toolbar (genéricas primeiro, específicas por ultimo)
var toolbarResult = {
	//Adicionar e Remover Pretendentes
	favorite : {
		addOk: function(j) {
			//$(btn).parent().removeClass('show').addClass('hide');
			$(btn).removeClass('show').addClass('hide');
			$(btn).parent().next().removeClass('hide').addClass('show');
			$(btn).parent().next().children().removeClass('hide').addClass('show');
			updateSideBarValues();
		},

		delOk: function(j) {
			//$(btn).parent().removeClass('show').addClass('hide');
			$(btn).removeClass('show').addClass('hide');
			$(btn).parent().prev().removeClass('hide').addClass('show');
			$(btn).parent().prev().children().removeClass('hide').addClass('show');
			updateSideBarValues();
		}
	},

	//Bloquear e desbloquar usuário
	blocked : {
		delOk: function() {
			$(btn).parent().parent().removeClass('show').addClass('hide');
			$(btn).parent().parent().prev().removeClass('hide').addClass('show');
		}
	},

	//Enviar FlashMail e enviar FlashMail para todos
	flashMail : {
		sendError: function(j) {
			if ((j.statusMessage['UMM-1158'] || j.statusMessage['UMM-40003'] || j.statusMessage['UMM-40001']) && jsonUtils.count(j.statusMessage) == 1) {
				$('.toId, .toNickname, toNicknames').remove();
				return keepSearching('/app/composeExpressMessage.html?' + userData, $('#content form'));
			} else {
				showMsg(jsonUtils.getFirst(j.statusMessage)[1], 'error');
			}
		},

		sendToAllError: function(j) {
			if ((j.statusMessage['UMM-1158'] || j.statusMessage['UMM-40003'] || j.statusMessage['UMM-40001']) && jsonUtils.count(j.statusMessage) == 1) {
				self.location.href = '/app/editTemplateMessage.html'+self.location.search;
			} else {
				showMsg(jsonUtils.getFirst(j.statusMessage)[1], 'error');
			}
		},

        sendOk: function(j) {
            showMsg(j.statusMessage, 'info', '#resultbox');
		}
	},

	//Páginas Específicas
	manageBlockedProfile : function() {
		$(btn).parent().parent().parent().find('.sign').hide();
		$(btn).parent().parent().parent().slideUp('slow').addClass('remove');
		if(!$('.useractions').not('.remove').size()) { self.location.reload(); }
	},

	manageFavoriteProfile : function() {
		$(btn).parent().parent().parent().find('.sign').hide();
		$(btn).parent().parent().parent().slideUp('slow').addClass('remove');
		if(! $('.useractions').not('.remove').size()) { self.location.reload();	} else { updateSideBarValues(); }
	},

	profileViewer : function() {
		toolbarResult.blocked.delOk();
		$(".unblockeduser").parent().removeClass('show').addClass('hide');
		$(".unblockeduser").parent().prev().removeClass('hide').addClass('show');
	},

	album : function() { toolbarResult.profileViewer(); },
    photoAlbum : function() { toolbarResult.profileViewer(); }
};

var buttonEvents = {
	profileViewer : function() {
		$('.userblockdenounce .blockeduser').click(
			function() {
				btn = this;
				userActions.blocked.add( buttonResult.blocked.addOk ); //Desbloquear Usuário pela barra (Album)
			}
		);

		$('.userblockdenounce .unblockeduser').click(
			function() {
				btn = this;
				userActions.blocked.del( buttonResult.blocked.delOk ); //Desbloquear Usuário pela barra (Album)
			}
		);
	},

	message : function() {
		$('#message .blockeduser').click(
			function() {
				btn = this;
				userActions.blocked.add( buttonResult.message.blockOk ); //Desbloquear Usuário (mensagens)
			}
		);

		$('#message .unblockeduser').click(
			function() {
				btn = this;
				userActions.blocked.del( buttonResult.message.unblockOk ); //Desbloquear Usuário (mensagens)
			}
		);

		$("#message .btpretendente").click(
			function() {
				btn = this;
				userActions.favorite.add( buttonResult.message.addFavoriteOk );  //Adicionar a Pretendente
			}
		);

		$("#message .btpretendenteremove").click(
			function() {
				btn = this;
				userActions.favorite.del( buttonResult.message.delFavoriteOk );  //Remover Pretendente
			}
		);
	},

	album : function() { buttonEvents.profileViewer(); },
    photoAlbum : function() {
        buttonEvents.profileViewer();
        $('a.btvoltarlista').click(keepPushing);
    }
};

var buttonResult = {
	blocked : {
		delOk: function() {
			var bar = $('.btdesbloquear').parent().parent();
			bar.removeClass('show').addClass('hide');
			bar.prev().removeClass('hide').addClass('show');

			$(btn).parent().removeClass('show').addClass('hide');
			$(btn).parent().prev().removeClass('hide').addClass('show');
		},

		addOk: function() {
			var bar = $('.btpretendenteremove').parent().parent();
			bar.removeClass('show').addClass('hide');
			bar.next().removeClass('hide').addClass('show');

			$(btn).parent().removeClass('show').addClass('hide');
			$(btn).parent().next().removeClass('hide').addClass('show');
		}
	},

	message : {
		blockOk : function() {
			$(btn).parent().removeClass('show').addClass('hide');
			$(btn).parent().next().removeClass('hide').addClass('show');
		},

		unblockOk : function() {
			$(btn).parent().removeClass('show').addClass('hide');
			$(btn).parent().prev().removeClass('hide').addClass('show');
		},

		addFavoriteOk : function() {
			$(btn).parent().removeClass('show').addClass('hide');
			$(btn).parent().next().removeClass('hide').addClass('show');
			$(btn).parent().next().children().removeClass('hide').addClass('show');
			updateSideBarValues();
		},

		delFavoriteOk : function() {
			$(btn).parent().removeClass('show').addClass('hide');
			$(btn).parent().prev().removeClass('hide').addClass('show');
			$(btn).parent().prev().children().removeClass('hide').addClass('show');
			updateSideBarValues();
		}
	}
};

// function addJS( jsFile, [debug] )
// author: Renato Rodrigues - renato [ponto] sp [arroba] gmail [ponto] com
// description:  Adiciona e executa arquivos JS dinamicamente aos templates, para debug passar o segundo parâmetro para a função
function addJS(jsFile, debug) {
	if (debug) {
		$('head').append('<script type="text/javascript" src="' + jsFile + '">');
	} else {
		jQuery.ajax({
			url: jsFile,
			dataType: "script",
			async: false,
			cache: true,
			contentType: "text/plain",

			beforeSend: function(xhr) {
				xhr.setRequestHeader( "encoding", "ISO-8859-1" );
			}
		});
	}
}

// function redirectIsHttps(target)
// author: Leonardo Souza
// description: redireciona páginas em https para http
function redirectIsHttps(target) {
	if(document.location.toString().match(/https/)) {
		self.location = target;
	}
}

// function addTooltip()
// author: Leonardo Souza
// description: adiciona a funcionalidade de tooltip ao(s) elemento(s) indicado(s)
function addTooltip(elem, opt) {
	if (!opt) opt = {};
	opt['delay'] = (opt['delay'] || (0));
	opt['showURL'] = (opt['showURL'] || (false));
	opt['track'] = (opt['track'] || (true));
	opt['reloadLib'] = (opt['reloadLib'] || (true));
	if(opt['reloadLib'] != 'false' || !$(elem)['Tooltip']){
		addJS('../js/lib/jquery.dimensions.pack.js');
		addJS('../js/lib/jquery.tooltip.pack.js');
	}
	$(elem).Tooltip(opt);
}

// function updateSideBarValues()
// author: Renato Rodrigues
// description: Atualiza dinamicamente os dados da barra lateral e cabeçalho no load das páginas.
function updateSideBarValues() {
	if($('p.inboxmessage')){
		parseJson(
			'/app/ajaxGetSideBar.html',{},
			{
				fnSuccess: function(j){
	
					$('dd.perfil a').html(j.profileView);
					$('dd.numberOfOnlineFavorites a').html(j.onlineFavorites);
					$('dd.pretendenteM a, dd.pretendenteF a').html(j.favoriteFromUsers);
					$('dd.mensagens a').html(j.unreadMessages);
					$('dd.aniversario a').html(j.birthdayFavorite);
					messages = $('p.inboxmessage a');
					if(messages.length > 0){
						$(messages[0]).html(j.unreadMessagesHeader);
						$(messages[1]).html(j.onlineFavoritesHeader);
					}
					$('dl#status').show();
					if(j.unreadMessagesLength > 0 && $('#newMailMsgbox').length > 0){
						showMsgs( j.urneadMessagesAlert, 'alert', '#newMailMsgbox', null);
						$('#newMailMsgbox').removeClass('hide');
					}
				},
				fnError: function() {
						
					$('dl#status').hide();
					$('p.inboxmessage').html($('p.inboxmessage a:last')).css('background','none');
				}
			}
		);
	}
};

function addRefreshCookie() {
	var actualLoadTime = new Date();
	window.setInterval( function () {
		jQuery.ajax({
			type: "POST",
			url: "/mm-video-papo/norefresh/ajaxRefreshCookie.html",
			dataType: "xml",
			data: "lastActionTime=" + actualLoadTime.getTime()
		});
	}, 690000  );
}

//Zebra table
function addOddClass() {
	$("#boxorangecnt p:nth-child(odd)").addClass("odd");
}


/**
 * Adiciona o box de desativar auto-login (DHTML) ao link Sair
 * @version 1.0
 * @author Renato Rodrigues - renato [ponto] sp [arroba] gmail [ponto] com
 */
function addAutoLoginDialog() {
    $('body').append('<div id="autoLoginDialog" class="fakebox"> </div>');
    $('#autoLoginDialog').jqm({ajax: '@href', trigger: '#lnkSair', overlay: 60 });
}

//function ieFixMyPhoto
//description: no ie o MyPhoto implede o click no link.
function addIeFixMyPhoto() {
	if ($.browser.msie == true) {
		ieFixMyPhoto($(".infouser .photo div a, .infousercertified .photo div a, #photouser"));
	}
}

function ieFixMyPhoto(localDoFix){
	$(localDoFix).click(function(){self.location = this.href;});
}

/*
 * Retorna n caracteres do início da string.
 * Adaptada da função em http://www.codigofonte.com.br/codigo/js-dhtml/strings/funcao-left-e-right-no-javascript
 * @author Renato Rodrigues - renato [ponto] sp [arroba] gmail [ponto] com
 * @version 0.1
 * @param n (number) O número de caracteres a serem retornardos
*/
String.prototype.left = function(n){
	if (n <= 0)
	    return "";
	else if (n > String(this).length)
	    return this;
	else
	    return String(this).substring(0,n) + '...';
}

/*
 * Retorna n caracteres do final da string.
 * Adaptada da função em http://www.codigofonte.com.br/codigo/js-dhtml/strings/funcao-left-e-right-no-javascript
 * @author Renato Rodrigues - renato [ponto] sp [arroba] gmail [ponto] com
 * @version 0.1
 * @param n (number) O número de caracteres a serem retornardos
*/
String.prototype.right = function(n){
    if (n <= 0)
       return "";
    else if (n > String(this).length)
       return this;
    else {
       var iLen = String(this).length;
       return String(this).substring(iLen, iLen - n);
    }
}
/*
 * trim
 */
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
/*
 * escapeHTML
 */
String.prototype.escapeHTML = function() {
	return this.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
}
/*
 * omniture
 */
function pvOMTR() {
	if(typeof uol_sc!="undefined" && (typeof uol_sc.t).toLowerCase()=='function'){uol_sc.t();}
}

function hitOMTR() {
	if(typeof uol_sc!="undefined" && (typeof uol_sc.tl).toLowerCase()=='function'){uol_sc.tl();}
}

/**
 *MIG, objeto principal do MIG
 *
*/
var mig = {
	/**
	 * executada por todas as páginas
	 *
	 * em fase de migração (atualmente só usado pelo mig)
	 *
	*/
	main : function () {
		jQuery(function(){
			//adiciona "sobre o site
			addAboutSite();
		});
	},
	/**
	 * executada por todas as páginas internas do site (usuário logado)
	 *
	 * em fase de migração (atualmente só usado pelo mig)
	 * @param autoLogin {boolean} indica se o autoLogin esta ativado
	*/
	onLineMain: function(autoLogin){
		jQuery(function(){
			mig.main();
			//video papo
			jQuery.cookie('wposition',null);
			addInvitation({});
			addInitPedingChats();
			//indica se a janela tem ou não foco
			addHasFocus();
			//atualiza os valores da sidebar
			updateSideBarValues();
			//"Aumenta o tempo de seção
			addRefreshCookie();
			//Adiciona Dialogo de auto-login
			if(autoLogin){
				addAutoLoginDialog();
				jQuery('#lnkSair').click(function(){
				    jQuery.cookie('instantmsg', 'true');
				    jQuery.cookie('visitprofile', 'true');
				});
			}
		});
	},
	/**
	 * executada por todas as páginas externas do site (usuario não logado)
	 *
	 * em fase de migração (atualmente só usado pelo mig)
       */
        offLineMain: function(){
		jQuery(function(){
			mig.main();
		});
	}
};

function subscribe(url)
{
	parseJson(
		"/user/invalidatePaymentBookletCache.html",
		{},
		{ fnSuccess: function() {window.location.href = url; } }
	);
}

jQuery(function() {
        $('.subscriberURL').click(function(e){
        	e.stopPropagation();
        	e.preventDefault();
                subscribe(this.href);
        })
})

/**
 * Recebe o retorno AJAX, interpreta como JSON, exibe o status e chama as funcões de callback dependendo do resultado.
 * @param url (string) URL do request ajax
 * @param data (string) Dados a serem enviados no request
 * @param opt (json) Parâmetros opcionais em formato JSON
 * 	{msgElem,
 * 	 msgOkElem,
 * 	 msgErrorElem,
 * 	 fnSuccess,
 * 	 fnEach
 * 	 fnError,
 * 	 fnServerError,
 * 	 fnIsEmpty,
 * 	 method,
 * 	 contentType,
 * 	 cache,
 * 	 async
 * 	}
*/
function parseJsonCollection(url, data, opt) {
	if (!opt)
		opt = {};
	else if(opt['fnIsEmpty'] || opt['fnEach']){
		var callerSuccess = opt['fnSuccess'] ? opt['fnSuccess'] : false;
		opt['fnSuccess'] = function(json){
			if(opt['fnIsEmpty'] && (!json['collection'] || !json['collection'].length > 0))
				opt['fnIsEmpty'].call(this, json);
			else{
				if(opt['fnEach'])
					for(n = 0; n < json['collection'].length; n++)
						opt['fnEach'].call(json['collection'][n], n, json['collection'].length, this, json['collection'][n]);
				if(callerSuccess)
					callerSuccess.call(this, json);
			}
		};
	}
	parseJson.call(this, url, data, opt);
}

/**
 *	altera todas as referencias de '{objectName.attrName}' pelo atributo do objeto
 *	@param objectName {string} nome do objeto para trocar
 *	@param font {string} html ou txt no qual se quer realizar as alterações
 *	@param object {objeto} objeto que contenha as informações
 *	@returns {string} txt com as alterações realizadas
 */
function fillTxtWithObject(font, objectName, object){
	if(!font) return '';
	if(!object) object = this;
	objectName = objectName && objectName != ''? objectName + '\.' : '';
	for(attrName in object){
                type = typeof(object[attrName]) + '';
		if ( type.match(/object/)) font = fillTxtWithObject.call(object[attrName], font, objectName + '\.' + attrName);
		else{
			font = font.replace(new RegExp("\{" + objectName + attrName + "\}", "g"),object[attrName])
			.replace(new RegExp("%7B" + objectName + attrName + "%7D", "g"),object[attrName]);
		}
	}
	font = font.replace(new RegExp("\{" + objectName + "[^}]+\}", "g"), '');
	return font;
}
/**
 *	altera todas as referencias de '{objectName.attrName}' pelo atributo do objeto
 *	@param objectName {string} nome do objeto para trocar
 *	@param font {Object} objeto ou seletor (string) do jquery
 *	@param objeto {Object} objeto que contém os valores
 *	@returns {Object} objeto jquery com o resultado.
 * 	**preferivelmente não usar em imagens, pois o carregamento inicial gerará um 404 **
 */
function fillHtmlWithObject(font, objectName, object){
	if(!font) return null;
	if(!object) object = this;
	if(!objectName) objectName = '';
	return $(font).html(fillTxtWithObject.call(object, $(font).html(), objectName));
}
/**
 * dispara request para o servidor, retornando os perfís para serem exibidos na side bar
 * @argument qtd {number} número de resultados a serem retornados
 * @returns {userProfile} resultado da story
 *
*/
function ajaxGetProfilesSideBar(qtd){
	if(!qtd) qtd = 6;
	parseJsonCollection(
		  '/user/ajaxGetProfilesSideBar.html?max=' + qtd,{},
		  {
			fnSuccess: function(j){
				$('#seemoreprofiles').removeClass('none');
				$('#seemoreprofiles').show();
				addTooltip('#seemoreprofiles .addTooltip .photo img',{extraClass: 'moreprofilesttt'});
				$('#seemoreprofiles .onlineprofile .isonline a').not('.msnchat').click(function(){
					return inviteToChat(this.rel);
				})
			},
			fnEach: function(n, total, caller, I){
				copy = $('.seemoreprofilebase').clone();
				copy.removeClass('seemoreprofilebase');
				copy.addClass('seemoreprofile' + n);
				fillHtmlWithObject.call(this, copy, 'userProfile');
				$(".photo img", copy).attr("src", this.facePhotoUrl);
				$('#seemoreprofiles').append(copy);
				if(!this.country || this.country == ''){
					copy.addClass('addTooltip');
					$(".photo img", copy).attr("title", '').attr("alt", '');
				}
				if(this.isOnline){
					copy.addClass('onlineprofile');
					if(this.msnToken != ''){
						$('.isonline a', copy).addClass('msnchat').addClass('animated').attr('rev',this.msnToken);
						endereco = "http://messenger.services.live.com/users/" + this.msnToken + "/presence/?cb=checkMsnStatus&mkt=pt-BR";
						$('head').append($(document.createElement("script")).attr('src', endereco));
					}
				}
			},
			fnIsEmpty: function(j){}
		});
}

/**
 * inicia a montagem de perfis na lateral do site
 * @param qtd {number} quantidade máxima de perfis
 */
function initGetProfilesSiteBar(qtd){ajaxGetProfilesSideBar(qtd);}