var f = new Validate();
function showCoords (c)
	{
		$('#x').attr('value',c.x);
		$('#y').attr('value',c.y);
		$('#x2').attr('value',c.x2);
		$('#y2').attr('value',c.y2);
		$('#w').attr('value',c.w);
		$('#h').attr('value',c.h);
	};

var Usuario ={
	type:'POST',
	url:'/ajax/ajax_usuario.php',
	global:false,
	novoUsuario: function(){
		var data = $("#formulario-cadastro").serialize();
		$.ajax({
			type:this.type,
			url:this.url,
			global:this.global,
			data:"acao=1&"+data,
			success:function(response){
				if(response == "1" ){
					window.location.href='/admin/admin-tivis.php';
				}else{
					$("#box-erro").html(response);
					setTimeout('$("#box-erro").fadeIn()',500);
					setTimeout('$("#box-erro").fadeOut()',2000);
				}
			}
		});
	},
	editarDados: function(){
		var msg = "";
		var options ={
			type:this.type,
		    data:{'acao':'3'},
 			beforeSubmit: function() {
 				$("#box-msg-dados").empty();
				$("#box-msg-dados").html("Please wait....");
				setTimeout('$("#box-msg-dados").slideDown()',500);
				
				var data_nasc = "";
				var dia = $("#campo-dia").val();
				var mes = $("#campo-mes").val();
				var ano = $("#campo-ano").val();
				
				if(f.isEmpty($("#campo-nome").val())){
					 msg += "<p>- Please enter your name.</p>";
				}
				
				if(f.isEmpty($("#combo-pais").val()) || $("#combo-pais").val() == 0){
					 msg += "<p>- Please enter Country</p>";
				}
				
				if((f.isNotEmpty(dia) && f.isNotEmpty(mes) && f.isNotEmpty(ano))){
					data_nasc = dia+"/"+mes+"/"+ano;
					if(!f.isDate(data_nasc) || f.isEmpty(data_nasc)){
						msg += "<p>- invalid Birthdate</p>";
					}
				}else{
					msg += "<p>- Please enter a Birthdate</p>";
				}
				
				if(f.isNotEmpty(msg)){
					$("#box-msg-dados").empty();
					$("#box-msg-dados").html(msg);
					setTimeout('$("#box-msg-dados").slideDown()',500);
					setTimeout('$("#box-msg-dados").slideUp();',2000);
					return false;
				}
 			},
			success:function(response){
				if(response == "1" ){
					$("#box-msg-dados").empty();
					$("#box-msg-dados").html("Update Ok.");
					setTimeout('$("#box-msg-dados").fadeIn()',500);
				}else{
					$("#box-msg-dados").empty();
					$("#box-msg-dados").html("Update Error.");
					setTimeout('$("#box-msg-dados").fadeIn()',500);
				}
			}
		};
		$('#formulario-editar-dados').ajaxSubmit(options);
	},
	novaSenha: function(){
		var msg = "";
		var options ={
			type:this.type,
		    data:{'acao':'3'},
 			beforeSubmit: function() {
				$("#box-msg-conta").empty();
				$("#box-msg-conta").html('Please wait....');
				setTimeout('$("#box-msg-conta").slideDown()',500);
				
				if(f.isEmpty($("#campo-nova-senha").val())){
					 msg += "<p>- Please enter a new password.</p>";
				}
				
				if(f.isEmpty($("#campo-nova-senha-2").val())){
					 msg += "<p>- Please, confirm password.</p>";
				}
				
				if($("#campo-nova-senha").val() != $("#campo-nova-senha-2").val()){
					 msg += "<p>- Erro na confirmação de Senha.</p>";
				}
				
				if(f.isNotEmpty(msg)){
					$("#box-msg-conta").empty();
					$("#box-msg-conta").html(msg);
					setTimeout('$("#box-msg-conta").slideDown()',500);
					setTimeout('$("#box-msg-conta").slideUp();',2000);
					return false;
				}
 			},
			success:function(response){
				if(response == "1" ){
					$("#box-msg-conta").empty();
					$("#box-msg-conta").html("Successfully update password.");
					setTimeout('$("#box-msg-conta").fadeIn()',500);
				}else{
					$("#box-msg-conta").empty();
					$("#box-msg-conta").html("Erro ao atualizar perfil.");
					setTimeout('$("#box-msg-conta").fadeIn()',500);
				}
			}
		};
		$('#formulario-editar-conta').ajaxSubmit(options);
	},
	novaURL: function(){
		var msg = "";
		var validChars = "0123456789abcdefghijklmnopqrstuvwxyz_";
		var options ={
			type:this.type,
		    data:{'acao':'3'},
 			beforeSubmit: function(){
				$("#box-msg-url").empty();
				$("#box-msg-url").html("Save URL...");
				setTimeout('$("#box-msg-url").fadeIn()',500);
				
				if(f.isEmpty($("#campo-url").val())){
					 msg += "<p>- Enter a URL.</p>";
				}
				
				if(!f.hasValidChars($("#campo-url").val(),validChars,false)){
					 msg += "<p>- Invalid URL.</p>";
				}
				
				if(f.isNotEmpty(msg)){
					$("#box-msg-url").empty();
					$("#box-msg-url").html(msg);
					setTimeout('$("#box-msg-url").slideDown()',500);
					setTimeout('$("#box-msg-url").slideUp();',2000);
					return false;
				}
 			},
			success:function(response){
				var resp = new String(response);
				var arrResp = resp.split("|");
				if(arrResp[0] == "1" ){
					$("#box-msg-url").empty();
					$("#box-msg-url").html("Update URL.");
					setTimeout('$("#box-msg-url").slideDown()',500);
					setTimeout('$("#box-msg-url").slideUp();',2000);
				}else{
					$("#box-msg-url").empty();
					$("#box-msg-url").html(arrResp[1]);
					setTimeout('$("#box-msg-url").slideDown()',500);
					setTimeout('$("#box-msg-url").slideUp();',2000);
				}
			}
		};
		$('#formulario-editar-url').ajaxSubmit(options);
	},
	imagemPerfil: function(){
		var msg = "";
		var options ={
			type:this.type,
		    data:{'acao':'3'},
		    beforeSubmit: function(){
				$("#box-msg-imagem").empty();
				$("#box-msg-imagem").html("Please wait...");
				setTimeout('$("#box-msg-imagem").fadeIn()',500);
		    },
			success:function(response){
				var resp = new String(response);
				var arrResp = resp.split("|");

				if(arrResp[0] == "1" ){					
					var w= new String(arrResp[2]);
					var h=new String(arrResp[3]);
					w =Number(arrResp[2] )+100;
					h =Number(arrResp[3] )+100;
					href="#TB_inline?height="+h+"&width="+w+"&inlineId=box-crop-modal";
					$('#link-crop-modal').attr('href',href);

					$('#imagem-crop').attr('src',arrResp[1]);
					$('#imagem-crop').attr('width',w);
					$('#imagem-crop').attr('hieght',h);
					//$("#imagem-crop").trigger('click');
					$("#link-crop-modal").trigger('click');
					$('#TB_ajaxContent').css('width',w);
					$('#TB_ajaxContent').css('height',h);
					//alert($('#TB_ajaxContent').html());
					$('#TB_closeWindowButton').unbind('click',tb_remove);					
					$('#TB_closeWindowButton').bind('click', function(){
						$.ajax({
							type:'POST',
							url:"../ajax/ajax_usuario.php",
							data:"arq="+arrResp[4]+"&campo-usuario="+$('#campo-usuario').attr('value')+"&campo-area=6&acao=3",
							success: function(msg){
								if (!msg){
									$("#box-msg-imagem").html("O arquivo temporário não pode ser removido.");
								}
							}
						});
						tb_remove();
						setTimeout('$("#box-msg-imagem").fadeIn()',500);
						setTimeout('$("#box-msg-imagem").fadeOut()',2000);
					})
					$("#box-crop-foto").empty();
					$("#box-crop-foto").html("<img id='imagem-crop' src='"+arrResp[1]+"' width="+w+" hieght="+h+" /><input type='button' id='bt_envia' class='btimportante' value='Cortar e Salvar' />");
					$('#imagem-crop').Jcrop({
						onChange: showCoords,
						onSelect: showCoords,
						boxWidth:  w, 
						boxHeight: h,
						setSelect:   [(arrResp[2]/2)+100, (arrResp[3]/2)+100, 200, 200 ],
						aspectRatio: 180/134
					});
					$('#bt_envia').bind("click",function(){
						if(($('#w').attr('value')<=0)||($('#h').attr('value')<=0)){
							alert("Uma área mínima precisa ser selecionada");
							return; 
						}
						$.ajax({
							type: "POST",
			   				url: "../ajax/ajax_usuario.php",
			   				data: "arq="+arrResp[4]+"&campo-usuario="+$('#campo-usuario').attr('value')+"&campo-area=5&acao=3&w="+$('#w').attr('value')+"&h="+$('#h').attr('value')+"&x="+$('#x').attr('value')+"&y="+$('#y').attr('value'),
			   				success: function(msg){
			   					$("#box-msg-imagem").empty();
								$("#box-msg-imagem").html("Successfully update.");
								$("#box-foto").empty();
								$("#box-foto").html("<img id='imagem-perfil' src='"+msg+"'>");
								$('#TB_closeWindowButton').trigger('click');
								setTimeout('$("#box-msg-imagem").fadeIn()',500);
								setTimeout('$("#box-msg-imagem").fadeOut()',2000);
			   				}
			   			});
					});					
				}else{
					$("#box-msg-imagem").empty();
					$("#box-msg-imagem").html(arrResp[1]);
					setTimeout('$("#box-msg-imagem").fadeIn()',500);
					setTimeout('$("#box-msg-imagem").fadeOut()',2000);
				}
			}
		};
		$('#formulario-editar-imagem').ajaxSubmit(options);
	},
	login: function(formulario){
		var source  = $("#"+formulario+" #campo-source").val();
		
		var ereg_email = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		
		var valor_email  = $("#"+formulario+" #campo-email-login").val();
		var valor_senha  = $("#"+formulario+" #campo-senha-login").val();
		var msg    = "";
		
		if(f.isEmpty(valor_email)){
			 msg += "<p>- Enter your Email.</p>";
		}else if(!String(valor_email).match(ereg_email)){
			 msg += "<p>- Invalid Email.</p>";
		}
		
		if(f.isEmpty(valor_senha)){
			msg += "<p> - Please enter a password.</p>"
		}
		
		if(f.isNotEmpty(msg)){
			$("#"+formulario+" #msg-login").empty();
			$("#"+formulario+" #msg-login").html(msg);
			setTimeout('$("#'+formulario+' #msg-login").slideDown()',500);
		}else{
			$("#"+formulario+"").submit();
		}
	},
	logout: function(){
		$.ajax({
			type:this.type,
			url:this.url,
			global:this.global,
			data:"acao=4",
			success:function(response){
				if(response == "1" ){
					window.location.href='/index.php';
				}
			}
		});
	},
	verificarURL: function(url){
		var valor_url = $("#"+url+"").val();
		if(f.isNotEmpty(valor_url)){
			$.ajax({
				type:this.type,
				url:this.url,
				global:this.global,
				data:"acao=5&url="+valor_url,
				success:function(response){
					if(response == "1" ){
						$("#"+url+"").removeClass("campo-texto-ok");
						$("#"+url+"").addClass("campo-texto-erro");
						$("#msg-url").html("URL já cadastrado.");
						setTimeout('$("#msg-url").fadeIn()',500);
						setTimeout('$("#msg-url").fadeOut();',2000);
					}else{
						$("#"+url+"").addClass("campo-texto-ok");
					}
				}
			});
		}
	},
	verificarEmail: function(email){
		var valor_email = $("#"+email+"").val();
		if(f.isNotEmpty(valor_email)){
			$.ajax({
				type:this.type,
				url:this.url,
				global:this.global,
				data:"acao=6&email="+valor_email,
				success:function(response){
					if(response != "0" ){
						$("#"+email+"").removeClass("campo-texto-ok");
						$("#"+email+"").addClass("campo-texto-erro");
						if(response == "1"){
							$("#msg-email").html("Email already exists.");
						}
						if(response == "2"){
							$("#msg-email").html("Invalid Email.");
						}
						setTimeout('$("#msg-email").fadeIn()',500);
						setTimeout('$("#msg-email").fadeOut()',2000);
					}else{
						$("#"+email+"").addClass("campo-texto-ok");
					}
				}
			});
		}
	},
	lembrarSenha: function(){
		var email = $("#campo-lembrar-email").val();
		
		$("#msg-lembrar").removeClass("off");
		$("#msg-lembrar").addClass("on");
		$("#msg-lembrar").html('Please wait, confirming email...');
		
		if(f.isEmpty(email)){
			$("#msg-lembrar").removeClass("off");
			$("#msg-lembrar").addClass("on");
			$("#msg-lembrar").html('Please enter your email.');
			return;
		}
		
		$.ajax({
			type:this.type,
			url:this.url,
			data:"acao=7&email="+email,
			success:function(response){
				if(response == 1 ){
					$("#msg-lembrar").html("Successfully sent email.");
					setTimeout('$("#msg-lembrar").fadeIn()',500);
					setTimeout('$("#msg-lembrar").fadeOut();tb_remove();',2000);
					$("#campo-lembrar-email").empty();
				}else{
					$("#msg-lembrar").html("Invalid Email.");
					setTimeout('$("#msg-lembrar").fadeIn()',500);
					setTimeout('$("#msg-lembrar").fadeOut();',2000);
				}
			}
		});
	},
	reenvioAtivacao: function(){
		var msg = "";
		var options ={
			type:this.type,
		    data:{'acao':'9'},
 			beforeSubmit: function() {				
				if(f.isEmpty($("#campo-email-reenvio").val())){
					msg += "<p>- Please enter your Email.</p>";
				}else if(!f.isEMailAddr($("#campo-email-reenvio").val())){
					msg += "<p>- Invalid Email.</p>";
				}
				
				if(f.isEmpty($("#campo-senha-reenvio").val())){
					 msg += "<p>- Please enter a password.</p>";
				}
				
				if(f.isNotEmpty(msg)){
					$("#box-msg-erro").empty();
					$("#box-msg-erro").html(msg);
					setTimeout('$("#box-msg-erro").slideDown()',500);
					setTimeout('$("#box-msg-erro").slideUp();',3000);
					return false;
				}
 			},		    
			success:function(response){
				var resp = new String(response);
				var arrResp = resp.split("|");
				if(arrResp[0] == "1" ){
					setTimeout('$("#box-reenvio").fadeIn()',500);
					setTimeout('$("#box-reenvio").fadeOut()',3000);
				}else{
					$("#box-msg-erro").empty();
					$("#box-msg-erro").html(arrResp[1]);
					setTimeout('$("#box-msg-erro").slideDown()',500);
					setTimeout('$("#box-msg-erro").slideUp();',3000);
					setTimeout('$("#ocorreu-erro").fadeIn()',500);
					setTimeout('$("#ocorreu-erro").fadeOut()',3000);
				}
			}
		};
		$('#formulario-reenvio-ativacao').ajaxSubmit(options);
	},
	listagemTivis:function(id_usuario,pagina,ordem){
		$.ajax({
			type:this.type,
			url:'../ajax/ajax_tivi.php',
			data:'acao=4&id_usuario='+id_usuario+'&pagina='+pagina+'&ordem='+ordem,
			success:function(response){
				if(response != "0"){										
					$("#listagem-tivis").empty();
					$("#listagem-tivis").html(response);
				}
			},
			beforeSend:function(){
				$("#listagem-tivis").html("<center><img src='/imgs/ajax-loader-clock.gif'></center>");
			}
		}); 		
	},
	listagemTivisFront:function(id_usuario,tipo,pagina,ordem){
		$.ajax({
			type:this.type,
			url:'../ajax/ajax_tivi_usuario.php',
			data:'acao=16&id_usuario='+id_usuario+'&tipo='+tipo+'&pagina='+pagina+'&ordem='+ordem,
			success:function(response){
				if(response != "0"){
					switch(tipo){
						case 0:
							$("#li-link-tivis").removeClass('tt-off');
							$("#li-link-tivis").addClass('tt-on');
							$("#li-link-favoritos").removeClass('tt-on');
							$("#li-link-favoritos").addClass('tt-off');
							break;
						case 1:
							$("#li-link-favoritos").removeClass('tt-off');
							$("#li-link-favoritos").addClass('tt-on');
							$("#li-link-tivis").removeClass('tt-on');
							$("#li-link-tivis").addClass('tt-off');
							break;
					}
					$("#box-lista-tivis").empty();
					$("#box-lista-tivis").html(response);
				}
			},
			beforeSend:function(){
				$("#box-lista-tivis").html("<center><img src='imgs/ajax-loader-clock.gif'></center>");
			}
		});
	},	
	loginExterno:function(id_tivi_canal,site,div,form){
		if(form == 1){
			switch(site){
				case 1:
					dialogLogin('/ajax/form_login_videolog.php',id_tivi_canal)
					break;
				case 2:
					dialogLogin('/ajax/form_login_youtube.php',id_tivi_canal)
					break;
			}
		}else{
			var options ={
				type:this.type,
			    data:{'site':site,'acao':'1'},
				beforeSubmit: function(formArray, jqForm) {
			  		$("#box-aviso-"+site).html("Please wait, confirming Login e Senha...");
					setTimeout('$("#box-aviso-'+site+'").fadeIn()',500);
					
					var empty = 0;
					for(i=0;i<formArray.length;i++) {
						$("#"+formArray[i].name+"-"+site).removeClass("campo-texto-erro");
			    		$("#"+formArray[i].name+"-"+site).addClass("modal-borda");
						if(f.isEmpty(formArray[i].value)){
							$("#"+formArray[i].name+"-"+site).removeClass("modal-borda");
				    		$("#"+formArray[i].name+"-"+site).addClass("campo-texto-erro");
				    		empty++;
						}
				  	}
				  	
				  	if(empty != 0){
				  		$("#box-aviso-"+site).empty();
				  		$("#box-aviso-"+site).html("Please, it informs the indicated fields.");
						setTimeout('$("#box-aviso-'+site+'").fadeIn()',500);
						setTimeout('$("#box-aviso-'+site+'").fadeOut()',5000);
				  		return false;
				  	}
				},
				success:function(response){
					var resp = new String(response);
					var arrResp = resp.split("|");
					if(arrResp[0] != "0" ){
						switch(site){
							case 1:
								Videos.videosVideolog(id_tivi_canal,1,0,response,1,div);
								break;
							case 2:
								Videos.videosYoutube(id_tivi_canal,1,0,response,1,div);
								break;
						}
						$("#div-form-login").dialog("destroy");
					}else{
				  		$("#box-aviso-"+site).html("<p>Error login:</p>");
				  		$("#box-aviso-"+site).append("<p> - "+arrResp[1]+"</p>");
						setTimeout('$("#box-aviso-'+site+'").fadeIn()',500);
						setTimeout('$("#box-aviso-'+site+'").fadeOut()',5000);
					}
				}
			};
			$("#formulario-login-externo-"+site+"").ajaxSubmit(options);
		}
	},
	logoutExterno: function(id_tivi_canal,site,div){
		$.ajax({
			type:this.type,
			url:"/ajax/ajax_login_externo.php",
			global:this.global,
			data:"id_tivi_canal="+id_tivi_canal+"&site="+site+"&acao=2",
			success:function(response){
				switch(site){
					case 1:
						Videos.videosVideolog(id_tivi_canal,1,2,'',1,div);
						break;
					case 2:
						Videos.videosYoutube(id_tivi_canal,1,2,'',1,div);
						break;
				}
			}
		});
	},
	adicionarFavorito: function(id_usuario,id_tivi){
		$.ajax({
			type:this.type,
			url:'/ajax/ajax_favorito.php',
			global:this.global,
			data:"acao=1&id_usuario="+id_usuario+"&id_tivi="+id_tivi,
			success:function(response){
				if(response == "1" ){
					html  = '<img src="/imgs/icon-favorito-excluir.jpg"/>';
					html += '<a href="javascript:void(0);" onclick="Usuario.removerFavorito('+id_usuario+','+id_tivi+')">Favoritos</a>';
					$("#li-favorito").empty();
					$("#li-favorito").html(html);
				}
			}
		});
	},
	removerFavorito: function(id_usuario,id_tivi){
		$.ajax({
			type:this.type,
			url:'/ajax/ajax_favorito.php',
			global:this.global,
			data:"acao=2&id_usuario="+id_usuario+"&id_tivi="+id_tivi,
			success:function(response){
				if(response == "1" ){
					html  = '<img src="/imgs/icon-favorito-adicionar.jpg"/>';
					html += '<a href="javascript:void(0);" onclick="Usuario.adicionarFavorito('+id_usuario+','+id_tivi+')">Favoritos</a>';
					$("#li-favorito").empty();
					$("#li-favorito").html(html);
				}
			}
		});
	},
	retornaMilesugndos: function(){
		randomDate = new Date();	
		return randomDate.getMilliseconds();
	},
	enviarFaleConosco: function(){
		var msg = "";
		var options ={
			type:this.type,
			clearForm:true,
 			beforeSubmit: function() { 				
				if(f.isEmpty($("#campo-email").val())){
					msg += "<p>- Please enter a Email.</p>";
				}else if(!f.isEMailAddr($("#campo-email").val())){
					msg += "<p>- Invalid Email.</p>";
				}
				
				if(f.isEmpty($("#campo-nome").val())){
					 msg += "<p>- Please enter your name.</p>";
				}
				
				if(f.isEmpty($("#campo-assunto").val())){
					 msg += "<p>- Please enter a subject.</p>";
				}
				
				if(f.isEmpty($("#campo-mensagem").val())){
					 msg += "<p>- Please enter message.</p>";
				}				
				
				if(f.isNotEmpty(msg)){
					$("#box-msg-erro").empty();
					$("#box-msg-erro").html(msg);
					setTimeout('$("#box-msg-erro").slideDown()',500);
					setTimeout('$("#box-msg-erro").slideUp();',3000);
					return false;
				}
 			},		    
			success:function(response){
				if(response == "1" ){
					setTimeout('$("#confirmacao").fadeIn()',500);
				}else{
					$("#box-msg-erro").empty();
					$("#box-msg-erro").html(response);
					setTimeout('$("#box-msg-erro").fadeIn()',500);
				}
			}
		};
		$('#formulario-fale-conosco').ajaxSubmit(options);
	}
};