/* Class Login
* @author Christian Benseler 
* @observation Using Jquery 
* Manages Login
*/
function Login() {

	this.mask = function() {
		$("a#esqueceu_senha").click(function() {
			window.open($(this).attr("href"),"_blank", "width=495, height=210");
			return false;
		});
	}
	
	/*
	* Validates login form
	*/
	this.validate = function() {
		var validator = $("#form_login").validate({
			rules: {
				"username": {
					required: true
				},
				"password": {
					required: true
				}
			},
			
			messages: {
				"username": "Campo nome é obrigatório",
				"password": "Campo senha é obrigatório"
			}
		});
	}

/*
	* Validates login form do blog
	*/
	this.validate = function() {
		var validator = $("#login_form").validate({
			rules: {
				"username": {
					required: true
				},
				"password": {
					required: true
				}
			},
			
			messages: {
				"username": "Campo nome é obrigatório",
				"password": "Campo senha é obrigatório"
			}
		});
	}
	
	/*
	 * validação para os formulários dos templates pot_form.vm e post_form_admin.vm
	 */
	 	var selector=$("#postForm");
	this.validateForm = function(selector){
					$("#postForm").validate({
				rules:{
					'postTitle':{
						required:true
					},
					'category':{
						required:true
					}
				},
				messages:{
					'postTitle':{
						required: "Necessário um título para o post"
					},
					'category':{
						required: "Escolha uma categoria"
					}
				}
			});
	}

}

/**
* Class Login
* @author Christian Benseler 
* @observation Using Jquery 
* Manages Password recovering
*/
function ChangePassword() {
	this.mask = function() {
		$("a#btnConfirm").click(function() {
			$("#frmPassword").submit();
			return false;
		});
	}
	
	/*
	* Validates login form
	*/
	this.validate = function() {
		var validator = $("#frmPassword").validate({
			errorElement: "span",
			rules: {
				"_password": {
					required: true,
					minlength: 8
				},
				"_passwordReminder": {
					required: true
				}
			},
			
			messages: {
				"_password": "Campo Senha é obrigatório e deve ter no mínimo 8 dígitos",
				"_passwordReminder": "Campo Lembrete de Senha é obrigatório"
			}
		});
	}
}

/**
* Class Login
* @author Christian Benseler 
* @observation Using Jquery 
* Manages Conexao Opt-in
*/
function OptInConexao() {
	
	/*
	* Mask inputs
	*/
	this.mask = function() {
		$('input.txtFullPhone').setMask("(99) 9999-9999");
		$('input.txtDate').setMask("99/99/9999");
		$('input.txtCPF').setMask("999.999.999-99");
		$('input.txtCEP').setMask("99999-999");
		$("a#optinSubmit").click(function() {
			$("form#frmCreateUser").submit();
			return false;
		});
		$("a#btnUseTerm").click(function() {
			window.open($(this).attr("href"),"_blank", "width=495, height=300, scrollbars=yes");
			return false;
		});
		
	}
	
	/*
	* Validates login form
	*/
	this.validate = function() {
		var validator = $("#frmCreateUser").validate({
			errorElement: "span",
			rules: {
				"fullName": {
					required: true
				},
				"personalData.birthDate": {
					required: true
				},
				"personalData.cpf": {
					required: true
				},
				"personalData.city": {
					required: true
				},
				"personalData.state": {
					required: true
				},
				"personalData.address": {
					required: true
				},
				"personalData.zipCode": {
					required: true
				},
				"phone": {
					required: true
				},
				"email": {
					required: true,
					email: true
				},
				"name": {
					required: true
				},
				"password": {
					required: true,
					minlength: 8
				},
				"cryptPassword": {
					required: true
				},
				"passwordReminder": {
					required: true
				}, 
				"chkAcceptUseTerm": {
					required: true
				}
				
			},
			
			messages: {
				"fullName": "Campo Nome completo é obrigatório",
				"personalData.birthDate": "Campo Data de Nascimento é obrigatório",
				"personalData.cpf": "Campo CPF é obrigatório",
				"personalData.city": "Campo Cidade é obrigatório",
				"personalData.state": "Campo Estado é obrigatório",
				"personalData.address": "Campo Endereço é obrigatório",
				"personalData.zipCode": "Campo CEP é obrigatório",
				"phone": "Campo Telefone é obrigatório",
				"email": "Campo Email é obrigatório e deve ter formato válido",
				"name": "Campo Crie seu login é obrigatório",
				"password": "Campo Escolha sua senha é obrigatório",
				"cryptPassword": "Campo Confirme sua senha é obrigatório",
				"passwordReminder": "Campo Lembrete é obrigatório",
				"chkAcceptUseTerm": "O termo de uso deve ser aceito"
				
			}
		});
	}
}

/**
* Class Forum
* @author Christian Benseler 
* @observation Using Jquery 
* Manages Forum
*/
function Forum() {
	
	/*
	* Manages the list with the 10 topics with newests posts
	*/
	this.lastTopicsList = function() {
		$("div.ultimas_novidades table tr").mouseover(function() {
			$(this).css({"font-weight": "bold"});
		});
		$("div.ultimas_novidades table tr").mouseout(function() {
			$(this).css({"font-weight": ""});
		});
		$("div.ultimas_novidades table tr").click(function() {
			document.location = $(this).attr("title");	
		});
	}
	
	/**
	* Manages topics list
	*/
	this.changeTopic = function() {
		$("select#categories_list").change(function() {
			document.location = $(this).val();
		});
	}
	
	/*
	* Manages the list with the topics, in a specific category area of the forum
	*/
	this.topicsList = function() {
		$("table#forum_tabela tr").click(function() {
			document.location = $(this).attr("title");	
		});
	}
	
	this.postPage = function() {
		
		var validator = $("#frmPostComment").validate({
			errorElement: "span",
			rules: {
				"content": {
					required: true
				}
			},
			messages: {
				"content": "Campo Comentário é obrigatório"
			},
			
			submitHandler: function(form) {
				$(form).ajaxSubmit({
					type: "post",
					contentType: "application/x-www-form-urlencoded; charset=UTF-8",
					success: function(html) {
						$("div#postResults").html(html);
					}

				});
			}
		});
		
		$("a#btnSubmitPost").click(function() {
			$("#frmPostComment").submit();
		});
		
	}
	
	this.suggestButton = function() {
		$("a#btnNewTopic").click(function() {
			window.open($(this).attr("href"),"_blank", "width=448, height=143");
			return false;
		});
	}
}

/**
* Class Forum
* @author Christian Benseler 
* @observation Using Jquery 
* Manages all My Profile area
*/
function MyProfile() {
	var userId;
	
	this.setUserId = function(id) {
		this.userId = id;
	}
	/*
	* Mask inputs
	*/
	this.maskStepOne = function() {
		$('input.txtFullPhone').setMask("(99) 9999-9999");
		$('input.txtDate').setMask("99/99/9999");
		$('input.txtCPF').setMask("999.999.999-99");
		$("a.editar_perfil").click(function() {
			var cpfVal = String($('input.txtCPF').val());
			if(cpfVal.length < 14){
				alert('Digite o CPF completo para continuar.')
			}else{
				$("form#frmEditUser").submit();
			}
			return false;
		});
		
		//habilita edição
		$("a#btnAllowEdit").click(function() {
			$("a.editar_perfil, a#btnCancelEdit").css({display: "block", float: "none"});
			$(".editPersonalItem").css({display: "inline"});
			$(".viewPersonalItem").css({display: "none"});
			$(this).css({display: "none"});
		});
		
		//cancela edição
		$("a#btnCancelEdit").click(function() {
			$("a.editar_perfil, a#btnCancelEdit").css({display: "none"});
			$(".editPersonalItem").css({display: "none"});
			$(".viewPersonalItem").css({display: "inline", float: "none"});
			$("a#btnAllowEdit").css({display: "block"});
		});
		
		//pop-up
		$("a#delete_perfil").click(function(){
			window.open("/conexao/profile/user.management.view.pm.action?method=deletePMUserForm","_blank", "width=495, height=180");
			return false;
		});
			
	}

	/*
	* Validates Personal Data form
	*/
	this.validateStepOne = function() {
		var validator = $("#frmEditUser").validate({
			errorElement: "span",
			rules: {
				"fullName": {
					required: true
				},
				"personalData.cpf": {
					required: true
				}
				,
				"birthDate": {
					required: true
				}
				,
				"personalData.city": {
					required: true
				},
				"personalData.state": {
					required: true
				}
				,
				"phone": {
					required: true
				},
				"email": {
					required: true,
					email: true
				}
				
			},
			
			messages: {
				"fullName": "Campo Nome completo é obrigatório",
				"personalData.cpf": "Campo CPF é obrigatório",
				"birthDate": "Campo Data de Nascimento é obrigatório",
				"personalData.city": "Campo Cidade é obrigatório",
				"personalData.state": "Campo Estado é obrigatório",
				"phone": "Campo Telefone é obrigatório",
				"email": "Campo Email é obrigatório e deve ter formato válido"
			},
			
			submitHandler: function(form) {
				$(form).ajaxSubmit({
					type: "post",
					contentType: "application/x-www-form-urlencoded; charset=UTF-8",
					success: function(html) {
						$("form#frmEditUser").html(html);
					}

				});
			}
		});
	}
	
	/*
	* Mask inputs
	*/
	this.maskStepTwo = function() {
		$("a.editar_cv").click(function() {
			$("form#frmEditUser").submit();
			return false;
		});
	}
	
	/*
	* Validates CV form
	*/
	this.validateStepTwo = function() {
		var validator = $("#frmEditUser").validate({
			errorElement: "span",
			rules: {
				"historic": {
					required: true,
					maxlength: 2000
				},
				"lastWorks": {
					required: true,
					maxlength: 2000
				}
			},
			
			messages: {
				"historic": "Campo Histórico Profissional é obrigatório e deve ter no máximo 2000 caracteres",
				"lastWorks": "Campo Últimos Trabalhos é obrigatório e deve ter no máximo 2000 caracteres"
			},
			
			submitHandler: function(form) {
				$(form).ajaxSubmit({
					type: "post",
					contentType: "application/x-www-form-urlencoded; charset=UTF-8",
					success: function(html) {
						$("form#frmEditUser").html(html);
					}

				});
			}
		});
		
	}
	
	this.showAvatarForm = function() {
		$(".foto_perfil#avatarImg").click(function() {
			window.open("/conexao/avatar/user.management.action?method=addAvatarImageFileForm","_blank", "width=495, height=130");
			return false;
		});
	}
	
	/**
	 * dá um reload no avatar
	 */
	this.reloadAvatar = function(url) {
		$(".foto_perfil").attr("src", url + "?rnd=" + Math.random());
	}
	
	/**
	 * carrega lista de imagens do usuário 
	 */
	this.loadUserResources = function(id, p, editable) {
		var thisClass = this;
		$("div#abas_content").html("<img src='/htmls/_img/ajax-loader.gif' style='margin:200px;' />");
		$.post("/conexao/user.management.action?method=listResourceFileByUser", { userId:  id, page: p},
				function(data){
					$("div#abas_content").html(data);
					//máscaras gerais
					thisClass.portfolioMask();
					$("a#enableImageUpload").click(function() {
						var txt = $(this).html();
						var t = this;
						if(txt=="EDITAR") {
							$("a.add_imagem").css({display: "block"});
							$("ul#minhas_imagens_conteudo a.excluir, ul#minhas_imagens_conteudo a.editar").css({display: "inline"});
							$(this).html("CANCELAR");
						} else {
							$("a.add_imagem").css({display: "none"});
							$("ul#minhas_imagens_conteudo a.excluir, ul#minhas_imagens_conteudo a.editar").css({display: "none"});
							$(this).html("EDITAR");
						}
						
						return false;
					});
					
					

					$(".lightbox_port").lightbox({
			    		fitToScreen: true
		   			 });
					
					$("ul#minhas_imagens_conteudo a.excluir").click(function() {
						if(!confirm("Deseja realmente excluir a imagem?"))
							return false;
						var thisId = $(this).attr("href").split("=")[1];
						securityService.deleteResourceFile(thisId, {
							callback:function(dataFromServer) {
								//reload na lista
								thisClass.loadUserResources(thisClass.userId, 0, true);
							}
						});
						return false;
					});
					
					$("ul#minhas_imagens_conteudo a.editar").click(function() {
						var query = $(this).attr("href").split("?")[1];
						var thisId = query.split("&")[0].split("=")[1];
						var thisLegend = query.split("&")[1].split("=")[1];
						window.open("/conexao/resourceFile/user.management.view.pm.action?method=editPhotoDataForm&type=photo&photoId=" + thisId +"&legend=" + thisLegend,"_blank", "width=495, height=160");
						return false;
					});
					$("ul#minhas_imagens_pager li a").click(function() {
						var p = $(this).attr("href").split("=")[1];
						thisClass.loadUserResources(thisClass.userId, p);
						return false;
					});
					//upload de imagem
					$("a.add_imagem").click(function() {
						window.open("/conexao/resourceFile/user.management.action?method=addResourceFileForm","_blank", "width=495, height=160");
						return false;
					});
					if(editable)
						$("a#enableImageUpload").trigger("click");
		});
	}
	
	/**
	 * carrega lista de urls do usuário
	 */
	this.loadUserMediaUrls = function(id, p) {
		var thisClass = this;
		$("div#abas_content").html("<img src='/htmls/_img/ajax-loader.gif' style='margin:200px;' />");
		$.post("/conexao/user.management.action?method=listMediaUrlsByUser", { userId:  id, page: p},
				function(data){
					$("div#abas_content").html(data);
					$('div#abas_content a.mediaUrlThumb').flash(
						
						{ height: 92, width: 112 },
						{ version: 8 },
						function(htmlOptions) {
							$this = $(this);
							htmlOptions.src = $(this).attr('href').replace("?","/").replace("=","/");
							var url = htmlOptions.src.toString();
							
							var results;
							if(url.indexOf("&")>0)
								url = url.split("&")[0];
							results = url.split("/")[5];
							$(this).html("<img src='http://img.youtube.com/vi/"+results+"/2.jpg' />");
							
							var thisHref = this;
							$(thisHref).click(function() {
								document.location = "/conexao/mediaUrl/homepage.mmp?userId=" + thisClass.userId  + "&passo=3&videoId=" + $(this).attr("id").split("_")[1];
								return false;
							});
						}
					);
					thisClass.portfolioMask();
					$("a#enableMediaUrlUpload").click(function() {
						var txt = $(this).html();
						var t = this;
						if(txt=="EDITAR") {
							$("a#add_video").css({display: "block"});
							$("ul#minhas_imagens_conteudo a.excluir").css({display: "inline"});
							$("ul#minhas_imagens_conteudo a.editar").css({display: "inline"});
							$(this).html("CANCELAR");
						} else {
							$("a#add_video").css({display: "none"});
							$("ul#minhas_imagens_conteudo a.excluir").css({display: "none"});
							$("ul#minhas_imagens_conteudo a.editar").css({display: "none"});
							$(this).html("EDITAR");
						}
						
						return false;
					});
					
					//upload de video
					$("a#add_video").click(function() {
						window.open("/conexao/mediaUrl/user.management.action?method=addMediaUrlForm","_blank", "width=495, height=160");
						return false;
					});
					
					$("ul#minhas_imagens_conteudo a.excluir").click(function() {
						if(!confirm("Deseja realmente excluir o vídeo?"))
							return false;
						var id = $(this).attr("id").split("_")[1];
						securityService.deleteMediaUrl(id, {
							callback:function(dataFromServer) {
								thisClass.loadUserMediaUrls(thisClass.userId, 0);
							}
						});
						
						return false;
					});
					$("ul#minhas_imagens_conteudo a.editar").click(function() {
						var query = $(this).attr("href").split("?")[1];
						var thisId = query.split("&")[0].split("=")[1];
						var thisLegend = query.split("&")[1].split("=")[1];
						window.open("/conexao/mediaUrl/user.management.view.pm.action?method=editVideoForm&videoId=" + thisId +"&name=" + thisLegend,"_blank", "width=495, height=160");
						return false;
					});

					//paginação
					$("ul#meus_videos_pager li a").click(function() {
						var p = $(this).attr("href").split("=")[1];
						thisClass.loadUserMediaUrls(thisClass.userId, p);
						return false;
					});
		});
	}
	
	this.loadVideo = function() {
		
		$('a#youtubeVideoDetail').flash(
			{ height: 92, width: 112 },
			{ version: 8 },
			function(htmlOptions) {
				var url = $(this).attr("href");
				var src = url.replace("?","/").replace("=","/");
				 $('a#youtubeVideoDetail').flash({
				        src: src
				    });
			}
		);
	}
	
	this.portfolioMask = function() {
		var thisClass = this;
		
		//abas
		$("a#minhas_imagens").unbind("click");
		$("a#minhas_imagens").click(function() {
			$(this).removeClass("minhas_imagens_off");
			$(this).addClass("minhas_imagens_on");
			$("a#meus_videos").removeClass("meus_videos_on");
			$("a#meus_videos").addClass("meus_videos_off");
			thisClass.loadUserResources(thisClass.userId, 0, false);
		});
		$("a#meus_videos").unbind("click");
		$("a#meus_videos").click(function() {
			$(this).removeClass("meus_videos_off");
			$(this).addClass("meus_videos_on");
			$("a#minhas_imagens").removeClass("minhas_imagens_on");
			$("a#minhas_imagens").addClass("minhas_imagens_off");
			thisClass.loadUserMediaUrls(thisClass.userId, 0);
		});
		
		
	}
	
}


/**
* Class ConexaoIndicate
* @author Christian Benseler 
* @observation Using Jquery 
* Manages Indicate Popup
*/
function ConexaoIndicate() {
	
	/*
	* Mask inputs
	*/
	this.mask = function() {
		$("img#btnIndicate").click(function() {
			$("form").submit();
			return false;
		});
		$("input").focus(function() {
			if($(this).attr("title")==$(this).val())
				$(this).val("");
		});
		$("input").blur(function() {
			if($(this).val()=="")
				$(this).val($(this).attr("title"));
		});
	}
	
	/*
	* Validates form
	*/
	this.validate = function() {
		var validator = $("form").validate({
			errorElement: "span",
			rules: {
				"yourName": {
					required: true
				},
				"yourEmail": {
					required: true,
					email: true
				},
				"friendsName": {
					required: true
				},
				"to": {
					required: true,
					email: true
				}
			},
			
			messages: {
				"yourName": "Campo Seu Nome completo é obrigatório",
				"yourEmail": "Campo Seu Email é obrigatório e deve ter formato válido",
				"friendsName": "Campo Nome do seu Amigo é obrigatório",
				"to": "Campo Email do seu Amigo é obrigatório e deve ter formato válido"
				
			}
		});
	}
}

/**
* Class Poll
* @author Christian Benseler 
* @observation Using Jquery 
* Manages Poll
*/
function Poll() {
	this.mask = function() {
		$("form#frmPoll a.votar").click(function() {
			$("form#frmPoll").ajaxSubmit({
				type: "post",
				contentType: "application/x-www-form-urlencoded; charset=UTF-8",
				success: function(html) {
					$("form#frmPoll").html("<p>" + html + "</p>");
				}
			});
			return false;
		});
		$("form#frmPoll a.resultado").click(function() {
			var href = $(this).attr("href");
			$.post(href, function(html) {
				$("form#frmPoll").html("<p>" + html + "</p>");
			});
			return false;
		});
		
		
		$("a#pollVote").click(function() {
			$("input[name=id]").each(function() {
				if($(this).is(':checked') ) {
					//
					$("form#frmOpenPoll").ajaxSubmit({
						type: "post",
						contentType: "application/x-www-form-urlencoded; charset=UTF-8",
						beforeSend: function() {
							$("div.frm_conteudo").html("<img src='/htmls/_img/ajax-loader.gif' style='margin:200px;' />");
						},
						success: function(html) {
							$("div.frm_conteudo").html("<br /><br />" + html);
						}
					});
					return false;
				}else{
					$(".erro").css("display","block");
				}
			});
		});
		
		
		$("select#categories_list").change(function() {
			document.location = $(this).val();
		});
		
	}
	
	/*
	* Manages the list with the topics, in a specific category area of the forum
	*/
	this.pollsList = function() {
		$("table.listing_polls tr").click(function() {
			document.location = $(this).attr("title");	
		});
	}
	
	/*
	* Manages the list with the 10 topics with newests posts
	*/
	this.lastTopicsList = function() {
		$("div.ultimas_novidades table tr").mouseover(function() {
			$(this).css({"font-weight": "bold"});
		});
		$("div.ultimas_novidades table tr").mouseout(function() {
			$(this).css({"font-weight": ""});
		});
		$("div.ultimas_novidades table tr").click(function() {
			document.location = $(this).attr("title");	
		});
	}
	
	/**
	* Manages topics list
	*/
	this.changeTopic = function() {
		$("select#categories_list").change(function() {
			document.location = $(this).val();
		});
	}
	
	/*
	* Manages the list with the topics, in a specific category area of the forum
	*/
	this.topicsList = function() {
		$("table#enquete_tabela tr").click(function() {
			document.location = $(this).attr("title");	
		});
	}
	
	this.postPage = function() {
		
		var validator = $("#frmPostComment").validate({
			errorElement: "span",
			rules: {
				"content": {
					required: true
				}
			},
			messages: {
				"content": "Campo Comentário é obrigatório"
			},
			
			submitHandler: function(form) {
				$(form).ajaxSubmit({
					type: "post",
					contentType: "application/x-www-form-urlencoded; charset=UTF-8",
					success: function(html) {
						$("div#postResults").html(html);
					}

				});
			}
		});
		
		$("a#btnSubmitPost").click(function() {
			$("#frmPostComment").submit();
		});
		
	}
	
	this.suggestButton = function() {
		$("a#btnNewTopic").click(function() {
			window.open($(this).attr("href"),"_blank", "width=448, height=143");
			return false;
		});
	}
	
	
}

function Search() {

	/*
	* Mask inputs
	*/
	this.mask = function() {
		try {
		$("a#btnSearch").click(function() {	
			if($("select[name='searchType']").val()==1)
				$("#frmMainSearch").attr("action", "/conexao/user.search.action");
			else
				$("#frmMainSearch").attr("action", "/conexao/search.action");
			if($("select[name='searchType']").val()==2)
				$("input#startObjectId").val($("input#categoriasId").val());
			else if($("select[name='searchType']").val()==3)
				$("input#startObjectId").val($("input#oquerolaId").val());
			$("#txtSearchUserName").val($("input#globalKeyword").val());
			$("#txtSearchKeywords").val($("input#globalKeyword").val());
			$("input#toPage").val(1);
			$("input#page").val(1);
			$("#frmMainSearch").submit();
			return false;
		});
		} catch(e) {
			
		}
		if($("ul.searchPagerUser")) {
			$("ul.searchPagerUser li a").click(function() {
				$("input#toPage").val($(this).attr("title"));

				$("input#txtSearchUserName").val($("#loadedKey").val());
				$("#frmMainSearch").attr("action", "/conexao/user.search.action");
				$("#frmMainSearch").submit();
				return false;
			});
		}
		
		if($("ul#searchPagerCommon")) {
			$("ul#searchPagerCommon li a").click(function() {
				$("input#toPage").val($(this).attr("title"));
				$("input#txtSearchKeywords").val($("#loadedKey").val());
				
				$("input#txtSearchUserName").val($("#loadedKey").val());
				$("input#startObjectId").val($("#loadedStartObject").val());
				$("#frmMainSearch").attr("action", "/conexao/search.action");
				$("#frmMainSearch").submit();
				return false;
			});
		}
		
		//para o enter no input
		$("#globalKeyword").keypress(function(e) {
			var code = (e.keyCode ? e.keyCode : e.which);
			if(code == 13) {
				$("a#btnSearch").trigger("click");
			}
		});
	}

	/*
	* Validates form
	*/
	this.validate = function() {
		if($("form#frmMainSearch")) {
			var validator = $("form#frmMainSearch").validate({
				errorElement: "span",
				rules: {
					"pesquisa": {
						required: true
					}
				},
				messages: {
					"pesquisa":{
						required:"Campo obrigatório"
					}
				}
			});
		}
	}
}

/**
* Class Poll
* @author Christian Benseler 
* @observation Using Jquery 
* Manages Friends
*/
function Friend() {
	
	this.reloadList = function() {

		if ($(".box_meus_amigos")[0]){
			$(".box_meus_amigos").html("<img src='/htmls/_img/ajax-loader.gif' />");
			var id = $(".box_meus_amigos").attr("id").split("_")[1];
			$(".box_meus_amigos").load("/conexao/friends/user.management.action?method=listUserFriends&userId=" + id);
		}

	}
}

/* chamadas que estão presentes em todas as páginas */

$(document).ready(function() {
	var search = new Search();
	search.mask();
	search.validate();

		if ($('div.img_colorida')[0]) {
			$('div.img_colorida').flash({
				//src: '/htmls/_img/conexao-beauty-art/bolinhas.swf',
				src: '/htmls/_img/conexao-beauty-art/bolinhas.swf',
				width: 835,
				height: 64,
				wmode: "transparent"
			
			}, {
				version: '8'
			});
		}

	
	
	var friend = new Friend();
	
	//botões de adicionar amigo
	if($(".btnAddAsFriend")) {
		
		$(".btnAddAsFriend").click(function() {
			var btn = this;
			var id = $(btn).attr("href").split("=")[1];
			
			securityService.addUserFriendToApprove(id, {
				callback:function(dataFromServer) {
					$(btn).css({display: "none"});
					friend.reloadList();
				}
			});
			return false;
		});
	}
	
	if($(".btnAddedAsFriend")) {
		
		$(".btnAddedAsFriend").click(function() {
		    var isApprove = true;
			var btn = this;
			var id = $(btn).attr("href").split("=")[1];
			
			securityService.approveUserFriend(isApprove,id, {
				callback:function(dataFromServer) {
					$(btn).css({display: "none"});
					friend.reloadList();
				}
			});
			return false;
		});
	}
	
	if($(".btnRefuseAsFriend")) {
		
		$(".btnRefuseAsFriend").click(function() {
		    var isApprove = false;
			var btn = this;
			var id = $(btn).attr("href").split("=")[1];
			
			securityService.approveUserFriend(isApprove,id, {
				callback:function(dataFromServer) {
					$(btn).css({display: "none"});
					friend.reloadList();
				}
			});
			return false;
		});
	}
	
	if($(".btnRemoveAsFriend")) {
		$(".btnRemoveAsFriend").click(function() {
			
			var btn = this;
			var id = $(btn).attr("href").split("=")[1];
			
			securityService.removeUserFriend(id, {
				callback:function(dataFromServer) {
					$(btn).css({display: "none"});
					friend.reloadList();
				}
			});
			return false;
		});
	}
	
	//lista de amigos
	if($(".box_meus_amigos")) {
		friend.reloadList();
		
	}

});


/**
* Class ConexaoIndicate
* @author Christian Benseler 
* @observation Using Jquery 
* Manages Suggest Popup
*/
function Suggest() {
	
	/*
	* Mask inputs
	*/
	this.mask = function() {
		$("a#btnSend").click(function() {
			$("form").submit();
			return false;
		});
		$("a#btnClose").click(function() {
			window.close();
			return false;
		});
	}
	
	/*
	* Validates form
	*/
	this.validate = function() {
		var validator = $("form").validate({
			errorElement: "span",
			rules: {
				"message": {
					required: true
				}
			},
			messages: {
				"message": "O Campo é obrigatório"
			}
		});
	}
}


/**
* Class ConexaoRegistration
* @author Christian Benseler 
* @observation Using Jquery 
* Manages Indicate Popup
*/
function ConexaoRegistration() {

	
	/*
	 * Allows personal data to be editable
	 */
	this.allowEdit = function() {
		
		//habilita edição
		$("a#btnAllowEdit").click(function() {
			$("a#editar_perfil, a#btnCancelEdit").css({display: "inline"});
			$(".editPersonalItem").css({display: "inline"});
			$(".viewPersonalItem").css({display: "none"});
			$(this).css({display: "none"});
		});
		
		//cancela edição
		$("a#btnCancelEdit").click(function() {
			$("a#editar_perfil, a#btnCancelEdit").css({display: "none"});
			$(".editPersonalItem").css({display: "none"});
			$(".viewPersonalItem").css({display: "inline", float: "none"});
			$("a#btnAllowEdit").css({display: "block"});
		});
		
	}

	this.validateEditForm = function() {
		//máscaras
		$('input.txtFullPhone').setMask("(99) 9999-9999");
		$('input.txtCPF').setMask("999.999.999-99");
		
		$("#editar_perfil").click(function() {
			$("#frmEditUserRegister").submit();
			return false;
		});
		
		var validator = $("#frmEditUserRegister").validate({
			errorElement: "div",
			rules: {
				"fullName": {
					required: true
				},
				"personalData.cpf": {
					required: true
				},
				"personalData.homePhone": {
					required: true
				},
				"email": {
					required: true,
					email: true
				}
			},
			
			messages: {
				"fullName": "Campo Nome completo é obrigatório",
				"personalData.cpf": "Campo CPF é obrigatório",
				"personalData.homePhone": "Campo Telefone é obrigatório",
				"email": "Campo Email é obrigatório e deve ter formato válido"
			}
		});
	}
	
	/*
	 * Validates if the user accepts or not the regulation 
	 */
	this.validateRegulationForm = function() {
		$("a#btnAcceptRegulation").click(function() {
			if(!$("#aceito_regulamento").is(":checked")) {
				alert("Para prosseguir, o Regulamento deve ser aceito");
				return false;
			}
		});
	}
	
	/*
	 * List photos from the desired category
	 */
	this.listPhotos = function(category) {
		var thisClass = this;
		$("#fotos_categoria").html("<img src='/htmls/_img/ajax-loader.gif' />");
		$("#fotos_categoria").load("/conexao/concurso/conexao.registration.action?method=listPhotosFromCategory&category=" + category + "&rnd=" + + Math.random()*4, "", function() {
			var remaining = 15 - $("#fotos_categoria ul li").length;
			if(remaining>0) {
				$("#btnAddPhoto").css({display: "block"});
				$("#infos_remaining_photos").html("Você ainda pode enviar mais <span>" + remaining + " fotos</span>");
			} else {
				$("#btnAddPhoto").css({display: "none"});
				$("#infos_remaining_photos").html(" Limite de 15 fotos atingido");
			}
			//exibe quantidade de fotos
			//
			
			//listeners para botões de excluir
			$("#fotos_categoria a.apagar").click(function() {
				if(confirm("Deseja realmente excluir essa foto?")) {
					
					var id = $(this).attr("href").split("=")[1];
					userPMService.deleteContestEntry(id, $("#categoryIdToDelete").val(),"photo", {
						callback:function(dataFromServer) {
							thisClass.listPhotos(category);
							return false;
						}
					});
				}
				return false;
			})
		});
	}
	
	/*
	 * List videos from the desired category
	 */
	this.listVideos = function(category) {
		var thisClass = this;
		$("#videos_categoria").html("<img src='/htmls/_img/ajax-loader.gif' />");
		$("#videos_categoria").load("/conexao/concurso/conexao.registration.action?method=listVideosFromCategory&category=" + category + "&rnd=" + + Math.random()*4, "", function() {
			
			var remaining = 15 - $("#videos_categoria ul li").length;
			if(remaining>0) {
				$("#btnAddVideo").css({display: "inline"});
				$("#infos_remaining_videos").html("Você ainda pode enviar mais <span>" + remaining + " vídeos</span>");
			} else {
				$("#btnAddVideo").css({display: "none"});
				$("#infos_remaining_videos").html(" Limite de 15 vídeos atingido");
			}
			
			//carrega miniaturas do Youtube...
			$("#videos_categoria a.mediaUrlThumb").each(function() {
				var url = $(this).attr('href').replace("?","/").replace("=","/");
				
				var results;
				if(url.indexOf("&")>0)
					url = url.split("&")[0];
				
				results = url.split("/")[5];
				
				$(this).html("<img src='http://img.youtube.com/vi/"+results+"/2.jpg' />");
				
			});
			
			//listeners para botões de excluir
			$("#videos_categoria a.apagar").click(function() {
				var id = $(this).attr("href").split("=")[1];
				if(confirm("Deseja realmente excluir esse video?")) {
					userPMService.deleteContestEntry(id, $("#categoryIdToDelete").val(),"video", {
						callback:function(dataFromServer) {
						thisClass.listVideos(category);
						}
					});
				}
				return false;
			})
		});
	}
	
	this.validateUploadPhotoForm = function() {
		//máscaras
		$('input.txtFullDate').setMask("99/99/9999");
		
		
		$("#btnUploadPhoto").click(function() {
			$("#frmUploadPhoto").submit();
			return false;
		});
		
		var validator = $("#frmUploadPhoto").validate({
			submitHandler: function(form){
				var firstDate = new Date(2008, 0, 1);
				var currentDate = new Date();
				var spl = $("#data").val().toString().split("/");
				var thisDate;
				
				thisDate = new Date(spl[2], spl[1] - 1, spl[0]);
				if(thisDate<firstDate || currentDate<thisDate){
					$("#dataValida").css('display','block')
					return false;
				};
				form.submit();
			},
			
			errorElement: "span",
			rules: {
				"title": {
					required: true,
					maxlength: 255
				},
				"date": {
					required: true,
					date: true
				},
				"local": {
					required: true,
					maxlength: 255
				},
				"client": {
					required: true,
					maxlength: 255
				},
				"briefing": {
					required: true,
					maxlength: 1000
				},
				"other_infos": {
					maxlength: 1000
				},
				"file": {
					required: true
				}
			},
			
			messages: {
				"title": {
					required: "Campo " + $("#frmUploadPhoto input.txtInput1").attr("title") + " é obrigatório",
					maxlength: "Campo " + $("#frmUploadPhoto input.txtInput1").attr("title") + " tem limite de 255 caracteres"
				},
				"date": {
					required: "Campo " +  $("#frmUploadPhoto input.txtInput2").attr("title") + " é obrigatório"
				},
				"local": {
					required: "Campo " +  $("#frmUploadPhoto input.txtInput3").attr("title") + " é obrigatório",
					maxlength: "Campo " + $("#frmUploadPhoto input.txtInput3").attr("title") + " tem limite de 255 caracteres"
				},
				"client": {
					required :"Campo " +  $("#frmUploadPhoto input.txtInput4").attr("title") + " é obrigatório",
					maxlength: "Campo " + $("#frmUploadPhoto input.txtInput4").attr("title") + " tem limite de 255 caracteres"
				},
				"briefing": {
					required: "Campo " +  $("#frmUploadPhoto textarea.txtInput5").attr("title") + " é obrigatório",
					maxlength: "Campo " + $("#frmUploadPhoto textarea.txtInput5").attr("title") + " tem limite de 1000 caracteres"
				},
				"other_infos": "Campo " +  $("#frmUploadPhoto textarea.outros_maquiadores").attr("title") + " tem limite de 1000 caracteres",
				"file": "Campo arquivo é obrigatório"
			}
		});
	}
	
	
	
	this.validateUploadVideoForm = function() {
		
		//máscaras
		$('input.txtFullDate').setMask("99/99/9999");
		
		
		$("#btnUploadVideo").click(function() {
			$("#frmUploadVideo").submit();
			return false;
		});
		
		var validator = $("#frmUploadVideo").validate({
			submitHandler: function(form){
				var firstDate = new Date(2008, 0, 1);
				var currentDate = new Date();
				var spl = $("#data").val().toString().split("/");
				var thisDate;
				
				thisDate = new Date(spl[2], spl[1] - 1, spl[0]);
				if(thisDate<firstDate || currentDate<thisDate){
					$("#dataValida").css('display','block')
					return false;
				};
				
				if($("#txtMediaUrl").val().indexOf("http://www.youtube.com")!=0) {
					$("#urlValida").css('display','block');
					return false;
				}
				
				form.submit();
			},	
			
			errorElement: "span",
			
			rules: {
				"title": {
					required: true,
					maxlength: 255
				},
				"date": {
					required: true,
					date: true
				},
				"local": {
					required: true,
					maxlength: 255
				},
				"client": {
					required: true,
					maxlength: 255
				},
				"briefing": {
					required: true,
					maxlength: 1000
				},
				"other_infos": {
					maxlength: 1000
				},
				"mediaUrl": {
					required: true
				}
			},
			
			messages: {
				"title": {
					required: "Campo " + $("#frmUploadVideo input.txtInput1").attr("title") + " é obrigatório",
					maxlength: "Campo " + $("#frmUploadVideo input.txtInput1").attr("title") + " tem limite de 255 caracteres"
				},
				"date": {
					required: "Campo " +  $("#frmUploadVideo input.txtInput2").attr("title") + " é obrigatório"
				},
				"local": {
					required: "Campo " +  $("#frmUploadVideo input.txtInput3").attr("title") + " é obrigatório",
					maxlength: "Campo " + $("#frmUploadVideo input.txtInput3").attr("title") + " tem limite de 255 caracteres"
				},
				"client": {
					required :"Campo " +  $("#frmUploadVideo input.txtInput4").attr("title") + " é obrigatório",
					maxlength: "Campo " + $("#frmUploadVideo input.txtInput4").attr("title") + " tem limite de 255 caracteres"
				},
				"briefing": {
					required: "Campo " +  $("#frmUploadVideo textarea.txtInput5").attr("title") + " é obrigatório",
					maxlength: "Campo " + $("#frmUploadVideo textarea.txtInput5").attr("title") + " tem limite de 1000 caracteres"
				},
				"other_infos": "Campo " +  $("#frmUploadVideo textarea.outros_maquiadores").attr("title") + " tem limite de 1000 caracteres",
				"mediaUrl": "Campo URL é obrigatório"
			}
		});
		
	}
}

/**
* Class ConexaoIndicate
* @author Christian Benseler 
* @observation Using Jquery 
* Manages Suggest Popup
*/
function Scrap() {
	/*
	* Enviar Scrap
	*/
	this.success = function() {
		$("#enviar_mensagem").click(function() {
			$("#form_scrap").submit();
			return false;
		});
		
		$("#form_scrap").validate({
			errorElement: "span",
			rules: {
				"scrap": {
					required: true
				}
			},
			messages: {
				"scrap": "O Campo é obrigatório"
			},
			submitHandler: function(form){
				form.submit()
				alert('Mensagem enviada com sucesso!')
			}
		});
	}
	
	this.clearScrap = function(){
		$(".apagar").click(function(){
			 if(confirm("Tem certeza que deseja apagar esse recado?")){
				  alert("Recado apagado com sucesso!");
			 }else{
			 	return false
			 }
		})
	}
}


/**
* Class preavaliacao
* @author Guilherme Serrano 
* @observation Using Jquery 
* Manages tabs
*/
function Preavaliacao(){
	this.selectEvaluated = function(){
		$("#toevaluate").hide();
		$("#evaluated").show();
		$("#aba_evaluated").removeClass("aba_preavaliados_off").addClass("aba_preavaliados_on btn_on");
		$("#aba_toevaluate").removeClass("btn_on aba_preavaliacao_on").addClass("aba_preavaliacao_off");
	}
	this.selectToevaluate = function(){
		$("#evaluated").hide();
		$("#toevaluate").show();
		$("#aba_toevaluate").removeClass("aba_preavaliacao_off").addClass("aba_preavaliacao_on btn_on");
		$("#aba_evaluated").removeClass("btn_on aba_preavaliados_on").addClass("aba_preavaliados_off");
	}
}
function Avaliacao(){
	this.selectEvaluated = function(){
		$("#toevaluate").hide();
		$("#evaluated").show();
		$("#aba_evaluated").removeClass("aba_avaliados_off").addClass("aba_avaliados_on btn_on");
		$("#aba_toevaluate").removeClass("btn_on aba_nao_avaliados_on").addClass("aba_nao_avaliados_off");
	}
	this.selectToevaluate = function(){
		$("#evaluated").hide();
		$("#toevaluate").show();
		$("#aba_toevaluate").removeClass("aba_nao_avaliados_off").addClass("aba_nao_avaliados_on btn_on");
		$("#aba_evaluated").removeClass("btn_on aba_avaliados_on").addClass("aba_avaliados_off");
	}
}


/**
* Class Votação Popular
* @author Guilherme Serrano
* @observation Using Jquery 
* Manage votes
*/
function Votes(){
	thisClass = this;
	
	this.initializeCarousel = function(){
		var categories = new Array("audiovisual", "editorial", "passarela", "publicidade", "social", "artescenicas");
		for (c in categories)
		{
			if($.cookie(categories[c]+"_UserId")){
				thisClass.selectUser(categories[c],$.cookie(categories[c]+"_UserId"),$.cookie(categories[c]+"_User"))
			}else{
				thisClass.selectNone(categories[c])
			}
		}
		$("#confirm_votes").click(function(){
			incomplete = 0
			$("#value_votes").children().each(function(){
				var child = $(this);
				val = child.attr("value");
				if(val == ""){
					incomplete = incomplete+1;
				}
			})
			if (incomplete == 6) {
				alert("Você precisa votar em pelo menos uma categoria para continuar.")
			}else{
				if (incomplete > 0) {
					if (confirm("Você não selecionou um finalista para cada categoria, deseja continuar mesmo assim?")) {
						$("#value_votes").submit();
					}
				}else{
					$("#value_votes").submit();
				}
			}
		})
		
		$(".check").click(function(){
			var query = $(this).attr("href").replace("#", "");
			var category = query.split("&")[0].split("=")[1];
			var selected = query.split("&")[1].split("=")[1];
			var userName = $(this).html();
			if ($(this).attr("class") == "check selected") {
				thisClass.selectNone(category);
				$("#" + category + " .check").removeClass("selected");
			}
			else {
				$("#" + category + " .check").removeClass("selected");
				thisClass.selectUser(category, selected, userName);
			}
			return false;
		})
	
	}
	

	this.confirm = function(){
		
		if ($.cookie("inputName")) {
			$("#inputName").attr({value: $.cookie("inputName")});
		}
		if ($.cookie("inputEmail")) {
			$("#inputEmail").attr({value: $.cookie("inputEmail")});
		}
		if ($.cookie("checkNews") == "true") {
			$("#checkNews").attr({checked: "checked"});
		}
		
		$.cookie("inputName", null);
		$.cookie("inputEmail", null);
		$.cookie("checkNews", null);
		
		$("#confirm_logged").click(function(){
			var hasError = false;
			$("#form_logged .required").each(function(){
				val = $(this).attr("value");
				if (!thisClass.notNull(val)) {
					hasError = true
				}
			})
			
			if (hasError) {
				alert("Preencha todos os campos do formulário para continuar a votação")
			}
			else {
				if(thisClass.hasVotes()){
					$("#form_logged").submit();
				}else{
					alert("Você não selecionou nenhum finalista.  Para votar volte para a tela anterior e selecione os finalistas.")
				}
			}
			
		})
		
		$("#confirm_unlogged").click(function(){
			var hasError = false;
			$("#form_unlogged .required").each(function(){
				val = $(this).attr("value");
				if (!thisClass.notNull(val)) {
					hasError = true
				}
			})
			
			if (hasError) {
				alert("Preencha todos os campos do formulário para continuar a votação")
			}
			else {
				if(thisClass.hasVotes()){
					$.cookie("inputName", $("#inputName").val(), { expires: 10 });
					$.cookie("inputEmail", $("#inputEmail").val(), { expires: 10 });
					$.cookie("checkNews", $("#checkNews").attr("checked"), { expires: 10 });
					$("#form_unlogged").submit();
				}else{
					alert("Você não selecionou nenhum finalista.  Para votar volte para a tela anterior e selecione os finalistas.")
				}
			}

		})
	}

	this.notNull = function(a){
		if(a!="" && !(a.match(/^\s+$/))){
			return true;
		}else{
			return false;
		}
	}

	this.selectUser = function(category,userId,userName){
		$("#selected").removeClass("red").addClass("green").html(userName);
		$("."+category).addClass("green").html(userName);
		$("#" + category + " form input[name='selected']").attr({value: userName});
		$("#"+category+"_userId").attr({value: userId});
		$("#"+category+" #"+userId).addClass("selected");
		$.cookie(category+"_UserId", userId, { expires: 10 });
		$.cookie(category+"_User", userName, { expires: 10 });
	}
	
	this.selectNone = function(category){
		$("#selected").removeClass("green").addClass("red").html("Nenhum finalista selecionado");
		$("."+category).removeClass("green").addClass("red").html("Nenhum finalista selecionado");
		$("#"+category+"_userId").attr({value: ""});
		$.cookie(category+"_UserId", null);
		$.cookie(category+"_User", null);
	}
	
	this.hasVotes = function(){
		existVotes = false;
		$(".voteValue").each(function(){
			val = $(this).attr("value");
			if (thisClass.notNull(val)) {
				existVotes = true
			}
		})
		if(existVotes){
			return true
		}else{
			return false
		}
	}
	
	this.cleanVotes = function(){
		var categories = new Array("audiovisual", "editorial", "passarela", "publicidade", "social", "artescenicas");
		for (c in categories)
		{
			$.cookie(categories[c]+"_UserId", null);
			$.cookie(categories[c]+"_User", null);
		}
		$.cookie("inputName", null);
		$.cookie("inputEmail", null);
		$.cookie("checkNews", null);
	}
}

/**
* Class Enviar Commentários
* @author Bruno Moura
* @observation Using Jquery 
*/
function sendComments(){
	this.msgRequired = "Preencha o campo [FIELD].";
	this.msgMin = "O campo [FIELD] deve conter no m&iacute;nimo ";
	this.msgEmail = "O campo [FIELD] deve ter formato válido. ";
	
	var thisClass = this;
	if($(".frmSendComment")){
		jQuery($(".frmSendComment")).validate({	
			
			rules:{
				'content':{
					required: true,
					minlength:10
				},
				'author':{
					required: true
				},
				'email':{
					required: true,
					email: true
				}
			},
			messages:{
				'content':{
					required: this.msgRequired.replace("[FIELD]",$("[name=content]").attr("title")),
					minlength: this.msgMin.replace("[FIELD]",$("[name=content]").attr("title")) + 10 + " caracteres"
				},
				'author':{
					required: this.msgRequired.replace("[FIELD]",$("[name=author]").attr("title"))
				},
				'email':{
					required: this.msgRequired.replace("[FIELD]",$("[name=email]").attr("title")),
					email: this.msgEmail.replace("[FIELD]",$("[name=email]").attr("title"))
				}
			},
			submitHandler: function(form) {
				$(form).ajaxSubmit({
					type: "post",
					contentType: "application/x-www-form-urlencoded; charset=UTF-8",
					success: function(html) {
						$("form#frmSendComment").html(html);
					},
					error: function(error){
						alert(error)
					}

				});
			}
		});
		return false;
	}
}

/**
 * Exibe uma lista de fotos do Flickr
 * @author Guilherme Serrano
 * Baseado no WSFlickrWidget - Chris Benseler
 * Copyright (c) 2010 - MMCafé
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html 
 */

function getTwitter(id, user, max){
	var pars = "count="+max;
	$.ajax({
		url: "/blog/load.url.action?url=http://twitter.com/statuses/user_timeline/"+user+".xml?params=" + pars,
		cache: false,
		success: function(dataFromServer){
			var str = "";
			var json = $.xml2json(dataFromServer);
			//alert(json);
			if (!json.status) {
				$("#" + id).html("<li>Nenhuma foto encontrada</li>")
				alert("Não foi possível conectar ao twitter.")
				return false;
			}
			else {
				$.each(json.status, function(index, item){
					str += "<li>"+item.text+"<br /><a href=\"http://twitter.com/"+user+"/status/"+item.id+"\" target=\"_blank\">"+item.created_at.substr(4,15)+"</a></li>";
				});
				$('#' + id).html(str);
			}
		}
	});
}


/**
 * Exibe uma lista de fotos do Flickr
 * @author Guilherme Serrano
 * Copyright (c) 2010 - MMCafé
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html 
 */

function getFlickr(id, max){
	var pars = "method=flickr.photos.search|api_key=01ad2ba53ea4e01e02bf3fced0b81266|user_id=40553763@N07|per_page="+max;
	$.ajax({
		url: "/blog/load.url.action?url=http://api.flickr.com/services/rest/&params=" + pars,
		cache: false,
		success: function(dataFromServer){
			var str = "";
			var json = $.xml2json(dataFromServer);
			
			if (!json.photos.photo) {
				$("#" + id).html("<li>Nenhuma foto encontrada</li>")
				alert("Nenhuma foto no flickr")
				return false;
			}
			else {
				$.each(json.photos.photo, function(index, item){
					var url = "http://farm" + item.farm + ".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_t.jpg";
				str += "<li><a href=\"http://www.flickr.com/photos/" + item.owner +"/" + item.id +"\" title=\""+ item.title +"\" target=\"_blank\"><img src=" + url + " /></a></li>";
				});
				$('#' + id).html(str);
			}
		}
	});
}

/**
 * Embeda vídeos do youtube em links que estejam entre chaves: [http://www.youtube.com/watch?v=lhiP4cNgHxs&feature=topvideos]
 * @author Guilherme Serrano
 * id = id do elemento html
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html 
 */
function embedYoutube(element){
	var txt = $(element).html();
	var vidWidth = 425;
	var vidHeight = 344;

	var vid = txt.match(/\[http:\/\/www\.youtube.com\/watch\?v=(\w[\w|-]*)(.)*\]/g);
	if (vid != null) {
		$.each(vid, function(i){
			toReplace = this;
			var vidId = toReplace.match(/\[http:\/\/www\.youtube.com\/watch\?v=(\w[\w|-]*)(.)*\]/);
			vidId = vidId[1];
			
			//Embed code
			var embed = '<obj' + 'ect width="' + vidWidth + '" height="' + vidHeight + '"><param name="movie" value="http://www.youtube.com/v/' +
			vidId +
			'&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" ' +
			'value="always"></param><em' +
			'bed src="http://www.youtube.com/v/' +
			vidId +
			'&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' +
			vidWidth +
			'" ' +
			'height="' +
			vidHeight +
			'"></embed></object> ';
			
			$(element).html($(element).html().replace(toReplace, embed));
		})
	}

}

/**
 * Limpa o value de um input de texto no focus
 * @author Guilherme Serrano
 * id = id do elemento html
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html 
 */
function cleanOnFocus(element, msg){
	$(element).focus(function(){
		if($(this).val() == msg){
			$(this).val('')
		}
	});
	$(element).blur(function(){
		if($(this).val() == ''){
			$(this).val(msg)
		}
	});
}

function confirmAction(element, msg){
	$(element).click(function(){
		if (confirm(msg)) {
			document.location = $(element).attr('rel');
		}
	});
}


/**
 * Concurso 2010
 * @author Guilherme Serrano
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html 
 */
function concurso2010(){
	thisClass = this;
	
	this.personalData = function(){
		$('.formPersonal').validate({
		   rules: {
		     name: 'required',
		     email: {
		       required: true,
		       email: true
		     },
			 cpf: 'required',
			 telefone: 'required',
			 carreira: 'required',
			 resumo: 'required'
		   },
		   messages: {
			name: 'Campo obrigatório',
			email: {
				required: 'Campo obrigatório',
				email: 'E-mail inválido'
		    },
			cpf: 'Campo obrigatório',
			telefone: 'Campo obrigatório',
			carreira: 'Campo obrigatório',
			resumo: 'Campo obrigatório'
		   }
		})
	}
	
	this.acceptRegulament = function(){
		
		$('#acceptRegulament').click(function(){
			if($('#checkAcceptRegulament').attr('checked')){
				window.location=$(this).attr('rel');
			}else{
				alert('Você precisa concordar com o regulamento para continuar.')
			}
		})
	}
	
	this.registerAlbum = function(){
		$('#submitAlbumType').click(function(){
			$('#formTypeAlbum').submit();
		})
	}
	
	this.editAlbum = function(){
		
		$('#formAlbum').validate({
		   rules: {
		     titulo: 'required',
			 data: 'required',
			 cliente: 'required'
		   },
		   messages: {
			titulo: 'Campo obrigatório',
			data: 'Campo obrigatório',
			cliente: 'Campo obrigatório'
		   }
		})
		
		$("a[rel^='BlackPrettyPhoto']").prettyPhoto({
			animationSpeed: 'normal', /* fast/slow/normal */
			padding: 40, /* padding for each side of the picture */
			opacity: 0.35, /* Value betwee 0 and 1 */
			showTitle: true, /* true/false */
			allowresize: true, /* true/false */
			counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
			theme: 'dark_rounded', /* light_rounded / dark_rounded / light_square / dark_square */
			callback: function(){
			}
		});
		$("#albumDate").datepicker({
			minDate: '01/08/2009',
			maxDate: '02/08/2010',
			dateFormat: 'dd/mm/yy'
		});

		$('#sendFormAlbum').click(function(){
			$('#formAlbum').submit();
		})
		
		$('#adicionarVideo').click(function(){
			$('#videoForm').attr('action', '/conexao/concurso2010/inscreva-se/conexao.registration.contest.action?method=uploadVideoToAlbum')
			$('#videoName').val('');
			$('#videoId').val('');
			$('#videoUrl').val('');
			$('#videoForm').fadeIn();
		})
		$('#adicionarFoto').click(function(){
			$('#photoForm').fadeIn();
		})

		$('#insertVideo').click(function(){
			if ($('#videoId').val()) {
				videoLink = $('#'+$('#videoId').val());
				videoLink.attr('href', $('#videoUrl').val());
				videoLink.attr('title', $('#videoName').val());
				
				editLink = $('#edit_'+$('#videoId').val());
				editLink.attr('href', $('#videoUrl').val());
				editLink.attr('id', $('#videoId').val());
				editLink.attr('title', $('#videoName').val());
				
				$('#videoForm').ajaxSubmit();
				$('#videoForm').fadeOut();
				//thisClass.createMediaActions();
			}else{
				if ($('#infos_remaining_videos span').html() < 1 || $('#infos_remaining_videos span').html() == null) {
					alert('Você não pode mais enviar vídeos para este álbum.');
				}else{
					$('#videoForm').ajaxSubmit({
						clearForm: true,
						success: updateVideoList
					});
				}
			}
		})
		
		$('#insertFoto').click(function(){
			$('#photosList').append('<li id="uploadLoader" style="background: #000; text-align: center; color: #fff;"><img src="/htmls/_img/conexao-beauty-art/concurso-2010/loader.gif" style="margin-top: 15px;"/><br /><br /> Carregando foto(s)</li><li id="lastChild"></li>');
			$('#lastChild').remove();
			
			$('#photoForm').ajaxSubmit({
				clearForm: true,
				success: updatePhotosList
			});
			$('#photoForm').fadeOut();
			$('#adicionarFoto').fadeOut();
		})

		$('#updatePhoto').click(function(){
			$('#editPhotoForm').submit();
		})
		
		$('#editPhotoForm').submit(function(){
			photoName = $('#photoName').val();
			$('#'+$('#photoId').val()).attr('title', photoName);
			$('#edit_'+$('#photoId').val()).attr('title', photoName).html('editar legenda');
			$('#editPhotoForm').ajaxSubmit({ 
				clearForm: true,
				success: updatePhotoName
			});
			return false;
		})
		
		$('#sendChangeAlbumType').click(function(){
			$('#changeAlbumType').submit();
		})
		
		function updatePhotoName(data){
			$('#editPhotoForm').fadeOut();
			$('#photoName').val('');
			$('#photoId').val('');
			
			//thisClass.createMediaActions();
		}
		
		function updateVideoList(data){
			if (data == '0') {
				alert('Você já enviou o limite de vídeos para esta álbum.')
			}else {
				$('#videosList').append(data);
				//Correção de posicionamento no FF
				$('#videosList').append('<li id="lastVideoChild"></li>');
				$('#lastVideoChild').remove();
				
				$('#infos_remaining_videos').html('Você ainda pode enviar mais <span>1</span> vídeos');
				
				if ($('#videosRemain').html() > 0) {
					$('#infos_remaining_videos span').html($('#videosRemain').html())
				}
				else {
					$('#infos_remaining_videos').html('Você enviou o limite de vídeos para este álbum')
				}
				
				$('#videosRemain').remove();
				
				thisClass.createMediaActions();
			}
		}
		
		function updatePhotosList(data){
			$('#uploadLoader').remove();
			if (data == '0') {
				alert('Você já enviou o limite de fotos para esta álbum.')
			}else{
				$('#photosList').append(data);
				//Correção de posicionamento no FF
				$('#photosList').append('<li id="lastPhotoChild"></li>');
				$('#lastPhotoChild').remove();
				//Reset upload form
				$('#photoForm input[type=file]').remove();
				$('#qtdFiles').val('1');
				$('#photoForm').prepend('<input type="file" id="photo_1" name="photo_1" style="height: 25px;"/>');
				
				
				//Update counter
				$('#infos_remaining_photos').html('Você ainda pode enviar mais <span>1</span> fotos');
				
				if ($('#photosRemain').html() > 0) {
					$('#infos_remaining_photos span').html($('#photosRemain').html())
					$('#adicionarFoto').fadeIn();
					if ($('#photosRemain').html() > 1) {
						$('#addInputFile').html('<a href="#addInput" style="color: #fac638;">Inserir mais uma foto</a>');
						$('#addInputFile').show();
					}
					else {
						$('#addInputFile').hide();
					}
				}
				else {
					$('#infos_remaining_photos').html('Você enviou o limite de fotos para este álbum')
				}
				$('#photosRemain').remove();
				
				thisClass.createMediaActions();
			}
		}

		//Form de upload de fotos
		$('#addInputFile').click(function(){
			counter = parseInt($('#qtdFiles').val());
			next = parseInt(counter+1)
			maxFiles = $('#infos_remaining_photos span').html();
			if(maxFiles > 5)
				maxFiles = 5;
				
			if(counter < maxFiles){
				$('#photo_'+counter).after('<input type="file" id="photo_'+next+'" name="photo_'+next+'" style="height: 25px;"/>')
				$('#qtdFiles').val(next);
				if(next==maxFiles){
					$('#addInputFile').html('Você só pode enviar mais ' + maxFiles + ' fotos para este álbum.')
					if(maxFiles == 5)
						$('#addInputFile').html('Você só pode enviar 5 fotos por vez.')
				}
			}
		})
		$('#closePhotoForm').click(function(){
			$('#photoForm').fadeOut();
		})
	}


	this.listUserAlbums = function(){
		$('#albums .excluir').click(function(){
			album = $(this).parent().parent();
			action = '/conexao/concurso2010/inscreva-se/conexao.registration.contest.action?method=deleteAlbum&albumId='+$(this).attr('rel');
			if(confirm('Deseja apagar este album?')) {
				$.ajax({
					url: action,
					success: function(data) {
						album.fadeOut();
						//album.remove();
					}
				});
			}
		})
	}
	
	this.createMediaActions = function(){
		$("a[rel^='prettyPhoto']").prettyPhoto({
			animationSpeed: 'normal', /* fast/slow/normal */
			padding: 40, /* padding for each side of the picture */
			opacity: 0.35, /* Value betwee 0 and 1 */
			showTitle: true, /* true/false */
			allowresize: true, /* true/false */
			counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
			theme: 'light_rounded', /* light_rounded / dark_rounded / light_square / dark_square */
			callback: function(){
			}
		});
		
		$("a.mediaUrlThumb").each(function() {
			var url = $(this).attr('href').replace("?","/").replace("=","/");
			var results;
			if(url.indexOf("&")>0)
				url = url.split("&")[0];
			
			results = url.split("/")[5];
			
			$(this).html("<img src='http://img.youtube.com/vi/"+results+"/2.jpg' />");
		});
		
		$('#videosList .apagar').unbind('click');
		$('#videosList .apagar').click(function(){
			video = $(this).parent();
			action = '/conexao/concurso2010/inscreva-se/conexao.registration.contest.action?method=deleteVideo&videoId='+$(this).attr('rel');
			if(confirm('Deseja apagar este vídeo?')) {
				$.ajax({
					url: action,
					success: function(data) {
						video.fadeOut();
						video.remove();
						if ($('#infos_remaining_videos span')[0]) {
							qtd = parseInt($('#infos_remaining_videos span').html());
						}else{
							qtd=0;
						}
						$('#infos_remaining_videos').html('Você ainda pode enviar mais <span>1</span> fotos');
						$('#infos_remaining_videos span').html(qtd+1)
					}
				});
			}
		});
		
		$('#videosList .editar').unbind('click');
		$('#videosList .editar').click(function(){
			$('#videoForm').attr('action', '/conexao/concurso2010/inscreva-se/conexao.registration.contest.action?method=updateVideo')
			videoId = $(this).attr('rel');
			videoName = $(this).attr('title');
			videoUrl = $(this).attr('href');
			if ( $('#videoForm').is(':visible') ) {
				$('#videoForm').fadeOut();
			}
			$('#videoName').val(videoName);
			$('#videoId').val(videoId);
			$('#videoUrl').val(videoUrl);
			$('#videoForm').fadeIn();
			return false;
		});
		
		$('#photosList .apagar').unbind('click');
		$('#photosList .apagar').click(function(){
			photo = $(this).parent();
			action = '/conexao/concurso2010/inscreva-se/conexao.registration.contest.action?method=deletePhoto&photoId='+$(this).attr('rel');
			if(confirm('Deseja apagar esta foto?')) {
				$.ajax({
					url: action,
					success: function(data) {
						photo.fadeOut();
						photo.remove();
						if ($('#infos_remaining_photos span')[0]) {
							qtd = parseInt($('#infos_remaining_photos span').html());
						}else{
							qtd=0;
						}
						$('#infos_remaining_photos').html('Você ainda pode enviar mais <span>1</span> fotos');
						$('#infos_remaining_photos span').html(qtd+1)
						$('#addInputFile').fadeOut();
						$('#adicionarFoto').fadeIn();
						if(qtd > 0){
							$('#addInputFile').html('<a href="#addInput" style="color: #fac638;">Inserir mais uma foto</a>')
							$('#addInputFile').fadeIn();
						}
					}
				});
			}

		});
		
		$('#photosList .editar').unbind('click');
		$('#photosList .editar').click(function(){
			photoId = $(this).attr('rel');
			photoName = $(this).attr('title')

			if ( $('#editPhotoForm').is(':visible') ) {
				$('#editPhotoForm').fadeOut();
			} 
			
			$('#photoName').val(photoName);
			$('#photoId').val(photoId);
			$('#editPhotoForm').fadeIn()
		})
	}
	
	this.createOpenActions = function(){
		$('.open').unbind('click');
		$('.open').bind('click', function(){
			var target = $('#'+$(this).attr('rel'));
			target.fadeIn(); 
			$(this).removeClass('open');
			$(this).addClass('close');
			thisClass.createCloseActions();
		})
		
	}
	
	this.createCloseActions = function(){
		$('.close').unbind('click');
		$('.close').bind('click', function(){
			var target = $('#'+$(this).attr('rel'));
			target.fadeOut(); 
			$(this).removeClass('close');
			$(this).addClass('open');
			thisClass.createOpenActions();
		})
	}
	
	this.managerEvaluation = function(){
		thisClass.createManagerMediaActions();
		thisClass.createOpenActions();
		thisClass.createCloseActions();
		
		$('.addInputFile').click(function(){
			albumId = $(this).attr('title');
			counter = parseInt($('#qtdFiles_'+ albumId).val());
			next = parseInt(counter+1);
			maxFiles = $('#infos_remaining_photos_'+albumId+' span').html();
			if(maxFiles > 5)
				maxFiles = 5;
			if(counter < maxFiles){
				$('#photoForm_'+albumId+' .photo_'+counter).after('<input type="file" class="photo_'+next+'" name="photo_'+next+'" style="height: 25px; display: block;" />');
				$('#qtdFiles_'+albumId).val(next);
				if(next==maxFiles){
					$('#addInputFile_'+albumId).html('Você só pode enviar mais ' + maxFiles + ' fotos para este álbum.')
					if(maxFiles == 5)
						$('#addInputFile_'+albumId).html('Você só pode enviar 5 fotos por vez.')
				}
			}
		})

		$('.adicionarFoto').click(function(){
			var target = $('#'+$(this).attr('rel'));
			target.fadeIn();
		})
		
		$('.adicionarVideo').click(function(){
			var target = '#'+$(this).attr('rel');
			$(target).attr('action', '/conexao/concurso2010/manager/manager.beautyart.action?method=uploadVideoToAlbum')
			$(target+' .videoName').val('');
			$(target+' .videoId').val('');
			$(target+' .videoUrl').val('');
			$(target).fadeIn();
		})
		
		$('.insertVideo').click(function(){
			var albumId = $(this).attr('rel')
			var target = '#videoForm_'+albumId;
			if ($(target+' .videoId').val()) {
				videoLink = $('#'+$(target+' .videoId').val());
				videoLink.attr('href', $(target+' .videoUrl').val());
				videoLink.attr('title', $(target+' .videoName').val());
				
				editLink = $('#edit_'+$(target+' .videoId').val());
				editLink.attr('href', $(target+' .videoUrl').val());
				editLink.attr('id', $(target+' .videoId').val());
				editLink.attr('title', $(target+' .videoName').val());
				
				$(target).ajaxSubmit();
				$(target).fadeOut();
				//thisClass.createMediaActions();
			}else{
				if ($('#infos_remaining_videos_'+ albumId +' span').html() < 1 || $('#infos_remaining_videos_'+ albumId +' span').html() == null) {
					alert('Você não pode mais enviar vídeos para este álbum.');
				}else{
					$(target).ajaxSubmit({
						clearForm: true,
						success: function(data) {
							updateVideoList(data, albumId)
						}
					});
				}
			}
		})
		
		$('.insertFoto').click(function(){
			var albumId = $(this).attr('rel')
			var target = '#photoForm_'+albumId;
			
			$(target).ajaxSubmit({
				clearForm: true,
				success: function(data) {
					updatePhotosList(data, albumId)
				}
			});
			$(photoForm).fadeOut();
			$('.adicionarFoto').fadeOut();
			alert('Suas fotos estão sendo enviadas.')
		})

		$("#form-personal-data").validate({
			rules: {
				name: 'required',
				email: {
					required: true,
					email: true
				},
				cpf: 'required',
				telefone: 'required',
				carreira: 'required',
				resumo: 'required'
			},
			messages: {
				name: 'Campo obrigatório',
				email: {
					required: 'Campo obrigatório',
					email: 'E-mail inválido'
				},
				cpf: 'Campo obrigatório',
				telefone: 'Campo obrigatório',
				carreira: 'Campo obrigatório',
				resumo: 'Campo obrigatório'
			},
			submitHandler: function(form) {
				jQuery(form).ajaxSubmit({
					clearForm: false,
					success: function(data) {
						alert('As informações pessoais foram salvas.')
					}
				});
			}
		}); 

		$('#save-personal-data').click(function(){
			$(this).parent().submit();
		})

		$('.saveAlbum').click(function(){
			$(this).parent().ajaxSubmit({
				clearForm: false,
				success: function(data) {
					alert('As informações pessoais foram salvas.')
				}
			});
		})

		$(".albumDate").datepicker({
			minDate: '01/08/2009',
			maxDate: '02/08/2010',
			dateFormat: 'dd/mm/yy'
		});
		
		function updatePhotosList(data, albumId){
			if (data == '0') {
				alert('Você já enviou o limite de fotos para esta álbum.')
			}else{
				$('#photosList_'+ albumId).append(data);
				//Correção de posicionamento no FF
				$('#photosList_'+ albumId).append('<li id="lastPhotoChild"></li>');
				$('#lastPhotoChild').remove();
				//Reset upload form
				$('#photoForm_'+ albumId +' input[type=file]').remove();
				$('#photoForm_'+ albumId +' .qtdFiles').val('1');
				$('#photoForm_'+ albumId).prepend('<input type="file" class="photo_1" name="photo_1" style="height: 25px;"/>');
				
				
				//Update counter
				$('#infos_remaining_photos_'+ albumId).html('Você ainda pode enviar mais <span>1</span> fotos');
				if ($('#photosRemain').html() > 0) {
					$('#infos_remaining_photos_'+ albumId +' span').html($('#photosRemain').html())
					$('.adicionarFoto').fadeIn();
					if ($('#photosRemain').html() > 1) {
						$('#addInputFile_'+ albumId).html('<a href="#addInput" style="color: #fac638;">Inserir mais uma foto</a>');
						$('#addInputFile_'+ albumId).show();
					}
					else {
						$('#addInputFile_'+ albumId).hide();
						$('#adicionarFoto_'+ albumId).hide();
					}
				}
				else {
					$('#infos_remaining_photos_'+ albumId).html('Você enviou o limite de fotos para este álbum')
					$('#photoForm_'+ albumId).hide();
					$('#adicionarFoto_'+ albumId).hide();
				}
				$('#photosRemain').remove();
				
				thisClass.createManagerMediaActions();
			}
		}
		
		function updateVideoList(data, albumId){
			if (data == '0') {
				alert('Você já enviou o limite de vídeos para esta álbum.')
			}else {
				$('#videosList_'+ albumId).append(data);
				//Correção de posicionamento no FF
				$('#videosList_'+ albumId).append('<li id="lastVideoChild"></li>');
				$('#lastVideoChild').remove();

				$('#infos_remaining_videos_'+ albumId).html('Você ainda pode enviar mais <span>1</span> vídeos');

				if ($('#videosRemain').html() > 0) {
					$('#infos_remaining_videos_'+ albumId +' span').html($('#videosRemain').html())
				}
				else {
					$('#infos_remaining_videos_'+ albumId).html('Você enviou o limite de vídeos para este álbum')
				}
				
				$('#videosRemain').remove();
				
				thisClass.createManagerMediaActions();
			}
		}

		$('.closePhotoForm').click(function(){
			$(this).parent().fadeOut();
		})

		$('.updatePhoto').click(function(){
			$(this).parent().submit();
		})
		
		$('.editPhotoForm').submit(function(){
			var albumId = $(this).attr('name');
			var photoName = $('#editPhotoForm_'+ albumId +' .photoName').val();
			var photoId = $('#editPhotoForm_'+ albumId +' .photoId').val();
			$('#'+ photoId).attr('title', photoName);
			$('#edit_'+ photoId).attr('title', photoName);
			$('#edit_'+ photoId).html('editar legenda');
			$('#editPhotoForm_'+ albumId).ajaxSubmit({ 
				clearForm: true,
				success: updatePhotoName  
			});
			updatePhotoName();
			return false;
		})

		function updatePhotoName(data){
			$('.editPhotoForm').fadeOut();
			$('.photoName').val('');
			$('.photoId').val('');
		}
		
		$('.submitEvaluation').click(function(){
			status = $(this).attr('rel');
			$('#statusEvaluation').val(status);
			$(this).parent().submit();
		})
	}

	this.createManagerMediaActions = function(){

		$("a[rel^='prettyPhoto']").prettyPhoto({
			animationSpeed: 'normal', /* fast/slow/normal */
			padding: 40, /* padding for each side of the picture */
			opacity: 0.35, /* Value betwee 0 and 1 */
			showTitle: true, /* true/false */
			allowresize: true, /* true/false */
			counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
			theme: 'light_rounded', /* light_rounded / dark_rounded / light_square / dark_square */
			callback: function(){
			}
		});
		
		$('a.mediaUrlThumb').each(function() {
			var url = $(this).attr('href').replace("?","/").replace("=","/");
			var results;
			if(url.indexOf("&")>0)
				url = url.split("&")[0];
			
			results = url.split("/")[5];
			
			$(this).html("<img src='http://img.youtube.com/vi/"+results+"/2.jpg' />");
		});
		
		$('.videosList .editar').unbind('click');
		$('.videosList .editar').click(function(){
			var albumId = $(this).parent().parent().attr('title');
			$('#videoForm_'+ albumId).attr('action', '/conexao/concurso2010/manager/manager.beautyart.action?method=updateVideo')
			var videoId = $(this).attr('rel');
			var videoName = $(this).attr('title');
			var videoUrl = $(this).attr('href');

			if ($('#videoForm_'+albumId).is(':visible') ) {
				$('#videoForm_'+albumId).fadeOut();
			}
			$('#videoForm_'+albumId +' .videoName').val(videoName);
			$('#videoForm_'+albumId +' .videoId').val(videoId);
			$('#videoForm_'+albumId +' .videoUrl').val(videoUrl);
			$('#videoForm_'+albumId).fadeIn();
			return false;
		});

		$('.videosList .apagar').unbind('click');
		$('.videosList .apagar').click(function(){
			var video = $(this).parent();
			var albumId = $(this).parent().parent().attr('title');
			var action = '/conexao/concurso2010/manager/manager.beautyart.action?method=deleteVideo&videoId='+$(this).attr('rel');
			if(confirm('Deseja apagar este vídeo?')) {
				$.ajax({
					url: action,
					success: function(data) {
						video.fadeOut();
						video.remove();
						if ($('#infos_remaining_videos_'+ albumId +' span')[0]) {
							qtd = parseInt($('#infos_remaining_videos_'+ albumId +' span').html());
						}else{
							qtd=0;
						}
						$('#infos_remaining_videos_'+ albumId).html('Você ainda pode enviar mais <span>1</span> vídeos');
						$('#infos_remaining_videos_'+ albumId +' span').html(qtd+1);
						
					}
				});
			}
		});
		
		$('.photosList .editar').unbind('click');
		$('.photosList .editar').click(function(){
			var albumId = $(this).parent().parent().attr('title');
			var photoId = $(this).attr('rel');
			var photoName = $(this).attr('title')
			
			if ( $('#editPhotoForm_'+albumId).is(':visible') ) {
				$('#editPhotoForm'+albumId).fadeOut();
			} 

			$('#editPhotoForm_'+albumId+' .photoName').val(photoName);
			$('#editPhotoForm_'+albumId+' .photoId').val(photoId);
			$('#editPhotoForm_'+albumId).fadeIn();
		})

		$('.photosList .apagar').unbind('click');
		$('.photosList .apagar').click(function(){
			var photo = $(this).parent();
			var albumId = $(this).parent().parent().attr('title');
			var action = '/conexao/concurso2010/manager/manager.beautyart.action?method=deletePhoto&photoId='+$(this).attr('rel');
			if(confirm('Deseja apagar esta foto?')) {
				$.ajax({
					url: action,
					success: function(data) {
						photo.fadeOut();
						photo.remove();
						if ($('#infos_remaining_photos_'+ albumId +' span')[0]) {
							qtd = parseInt($('#infos_remaining_photos_'+ albumId +' span').html());
						}else{
							qtd=0;
						}
						qtd = qtd+1
						$('#infos_remaining_photos_'+ albumId).html('Você ainda pode enviar mais <span>1</span> fotos');
						$('#infos_remaining_photos_'+ albumId +' span').html(qtd);
						$('#addInputFile_'+ albumId).fadeOut();
						$('#adicionarFoto_'+ albumId).fadeIn();
						if(qtd > 0){
							$('#addInputFile_'+ albumId).html('<a href="#addInput" style="color: #fac638;">Inserir mais uma foto</a>')
							$('#addInputFile_'+ albumId).fadeIn();
							$('#adicionarFoto_'+ albumId).fadeIn();
						}
					}
				});
			}
		});

	}
	
	this.selectCategory = function(){
		$('#selectCategory').change(function(){
			if($(this).val() != '-1')
				$(this).parent().submit();
		})
	}
	
	this.managerReports = function(){
		$('#formReports select').change(function(){
			if($(this).val() == 1 || $(this).val() == 10)
				$('#formDates').hide();
			else
				$('#formDates').show();
		});
		
		$('#dataInicio').change(function(){
			$('#dataFinal').datepicker('destroy').val('').datepicker({
				minDate: $('#dataInicio').val(),
				maxDate: '02/08/2010',
				dateFormat: 'dd/mm/yy'
			});
		});

		$(".reportDate").datepicker({
			minDate: '24/05/2010',
			maxDate: '02/08/2010',
			dateFormat: 'dd/mm/yy'
		});
		
		$('.submitReport').click(function(){
			extension = $(this).attr('id');
			$('#extensao').val(extension);
			$(this).parent().submit();
		})
	}
}
