function isUrl(s) {
	var expreg1= /\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i;
	var expreg2 = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
		
	if(expreg1.test(s) || expreg2.test(s)){
		return true;
	}else{
		return false;
	}
}

function cleanComment(message, text){
	var idC = "";
	idC = message.toString().split('-');
	
	if ($("#wallComment-" + idC[1]).val() == text ){
		$("#wallComment-" + idC[1]).val('');
	}
	$("#wallCommentBtn-" + idC[1]).show();
}

function restoreComment(message, text){
	var idC= "";
	idC = message.toString().split('-');
	if ($("#wallComment-" + idC[1]).val() == '' ){
		writeStateComment = 0;
		$("#wallComment-" + idC[1]).val(text);
		$("#wallCommentBtn-" + idC[1]).hide();
	}
}

function Wall() {
	/**
	* Set some variables to the post.
	*/
	this.input 				= "WallInput";
	this.button 			= "button3d";
	this.urlPost			= "ajax/wall_post_story.php";
	this.urlMorePosts		= "ajax/wall_get_stories.php";
	this.urlDelete			= "ajax/wall_delete_story.php";
	this.urlDeleteComment	= "ajax/wall_delete_comment.php";
	this.type				= 1;
	this.mid				= 0;
	this.tid				= 0;
	this.iso				= '';
	this.msg				= "";
	this.offset				= 0;
	this.writeState			= 0;
	this.writeStateComment	= 0;
	this.group_id			= 0;
	
	/**
	* Post a new message to a Member/Team wall.
	*/

	this.wallPost = function() {
		var me = this;
		
		this.msg = $('#'+this.input).val();
		
		if (jQuery.trim(this.msg) != "" && this.writeState != 0) {
			var expreg= /^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)( [a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$/

			if(isUrl(this.msg)){
				this._beforeWallPostUrl();
			}else{
				this._beforeWallPost();
			}
			
			$.ajax({
				type: "POST",
				dataType: "json",
				url: this.urlPost,
				data: ({ data_wall_message : encodeURIComponent(this.msg), data_wall_type : this.type, data_wall_member_id :this.mid, group_id: this.group_id }),	
				success: function(data) {
					var html = "";
					if ( data.result == 'done') {
						
						var UrlNations= (location.href.match('nations.php'))?'yes':'no';
						
						if(data.show_url.length && UrlNations == 'no'){
							var url= data.show_url[0];

							if(url.match('/www.youtube.com/') || url.match('/youtu.be/')){
								html = wallTpl._createWallItemUrlYoutube(data, false, me.type);
							}else{
								html = wallTpl._createWallItemUrl(data, false, me.type);	
							}
						}else{
							html = wallTpl._createWallItem(data, false, me.type);
						}
						
						$("#wall_itemsWrapper").prepend(html); 
						$("#ww_" + + data.wall_message_id).fadeIn(1500);
						
						/* set behaibour */
						$("textarea[id^='wallComment-']").autoResize({
						    onResize : function() {
						        $(this).css({opacity:0.8});
						    },
						    animateCallback : function() {
						        $(this).css({opacity:1});
						    },
						    animateDuration : 300,
						    extraSpace : 0
						});
						
						$("#wallComment-" + data.wall_message_id).click(function() {
							cleanComment('wallComment-' + data.wall_message_id, langPopup['POPUP_WW_COMMENT_WRITE']);
							
							if ( (id != ('wallComment-' + data.wall_message_id)) && id != 0) {
									restoreComment(id,langPopup['POPUP_WW_COMMENT_WRITE']);
							}
							
							id = 'wallComment-' + data.wall_message_id;
						});
										
					} else {
						alert(data.result);
					}

					me._afterWallPost();
				},
				error: function(data, err, otro) {
					/*alert("ENTREEEE ERROR");
					alert(data);
					alert(err);
					alert(otro);*/
				}
			});	
			
			$('#'+this.input).val(langPopup['POPUP_WW_WRITE']);
			$('#'+this.input).css({height:50});
		}
	}
	
	/**
	* Get More stories from a Member/Team wall.
	* We need to keep the offset updated correctly
	*/
	this.wallGetMorePosts = function() {
		me = this;
		$("#wallLoading").toggle();
		$.ajax({
			type: "POST",
			dataType: "json",
			url: this.urlMorePosts,
			data: ({ offset : this.offset, type : this.type, tid : this.tid, pid : this.mid, iso : this.iso }),	
			success: function(data){
				if ( data.result == "done") {
					var html = "";
					
					// Create the items container
					html = '<div id="more_'+me.offset+'" style="display:none;">';
					for (var i = 0; i < data.stories.length; i++) {
						// Create one wall Item
						if(data.stories[i].show_url.length){
							var url= data.stories[i].show_url;

							if(url.match('/www.youtube.com/') || url.match('/youtu.be/')){
								html += wallTpl._createWallItemUrlYoutube(data.stories[i], true, me.type);
							}else{
								html += wallTpl._createWallItemUrl(data.stories[i], true, me.type);	
							}
						}else{
							html += wallTpl._createWallItem(data.stories[i], true, me.type);
						}
					}
					html += '</div>';
					
					// Show the stories
					$("#wall_footer").before(html);
					$("#more_"+me.offset).fadeIn(1500);
					
					// Recalculate the offset and lesftsStories
					leftStories = leftStories - data.stories.length;
					me.offset = me.offset + data.stories.length;
					if (leftStories <= 0) {
						$(".wall_footer").children().html("");
					}
					
					$("#storiesLeft").html(leftStories); 
					
					// Rebind the texarea
					$("textarea[id^='wallComment-']").autoResize({
					    onResize : function() {
					        $(this).css({opacity:0.8});
					    },
					    animateCallback : function() {
					        $(this).css({opacity:1});
					    },
					    animateDuration : 300,
					    extraSpace : 0
					});
					
					$("textarea[id^='wallComment-']").click(function() {
						cleanComment($(this).attr('id'), langPopup['POPUP_WW_COMMENT_WRITE']);
						
						if (id != $(this).attr('id') && id != 0) {
								restoreComment(id,langPopup['POPUP_WW_COMMENT_WRITE']);
						}
						
						id = $(this).attr('id');
					});	
				} else {
					alert(data.result);
				}
				$("#wallLoading").toggle();
			}
		});
	}
	
	/**
	* Delete a wall post from a Member/Team wall.
	* We need to keep the offset updated correctly
	*/
	this.wallDelPost = function(msgId) {
		var me = this;
		$.ajax({
			type: "POST",
			dataType: "json",
			url: this.urlDelete,
			data: ({data_wall_type : this.type, data_wall_message_id : msgId }),	
			success: function(data){
				if ( data.result == "done") {
					$("#ww_"+msgId).fadeOut("slow");
					$("#split_"+msgId).fadeOut("slow");
					$('#wallComments-'+msgId).fadeOut('slow');
					$('#maxCommentsDiv-'+msgId).fadeOut('slow');
					$('#postComment-'+msgId).fadeOut('slow');
					
					me.offset--;
					$.facebox(futboleaOkBox(langPopup['POPUP_WW_DELETE_MESSAGE_OK']),'',0);
					futboleaCloseBoxTimer();
				} else {
					alert(data.result);
				}
			}
		});
	}
	
	this.wallDelPostBox = function(msgId) {
		$.facebox.settings.opacity = 0.5;
		$.facebox.settings.modal = true;
		futboleaLoadingBox();
		var HTML = '';

		HTML += '<div id="simpatizante" class="popup">' +
					'<h4>'+langPopup['POPUP_WW_DELETE']+'</h4>' +
					'<p class="warning">'+langPopup['POPUP_WW_DELETE_MESSAGE']+
					'</p>' +
					'<ul class="footer">' +
						'<li><a class="ok" href="javascript:wall.wallDelPost('+msgId+');">'+langPopup['POPUP_WW_DELETE']+'</a></li>' +
						'<li><a href="javascript:futboleaCloseBox();">'+langPopup['POPUP_CANCEL']+'</a></li>' +
					'</ul>' +
					'</p>' +
				'</div>';
		$.facebox(HTML,'', 1);
	}

	this.wallDelComment = function(msgId, commentId) {
		var me = this;
		$.ajax({
			type: "POST",
			dataType: "json",
			url: this.urlDeleteComment,
			data: ({data_wall_type : this.type, data_wall_comment_id : commentId }),	
			success: function(data){
				if ( data.result == "done") {
					
					$("#comment-"+commentId).fadeOut("slow");
					$("#maxComments-" + msgId).html(langPopup['POPUP_WW_COMMENT_SEE'] +' ' + data.count +' '+langPopup['POPUP_WW_COMMENTS']);
					
					$.facebox(futboleaOkBox(langPopup['POPUP_WW_DELETE_COMMENT_OK']),'',0);
					futboleaCloseBoxTimer();
				} else {
					alert(data.result);
				}
			}
		});
	}
	
	this.wallDelCommentBox = function(msgId, commentId) {
		$.facebox.settings.opacity = 0.5;
		$.facebox.settings.modal = true;
		futboleaLoadingBox();
		var HTML = '';

		HTML += '<div id="simpatizante" class="popup">' +
					'<h4>'+langPopup['POPUP_WW_DELETE']+'</h4>' +
					'<p class="warning">'+langPopup['POPUP_WW_COMMENT_DELETE']+
					'</p>' +
					'<ul class="footer">' +
						'<li><a class="ok" href="javascript:wall.wallDelComment('+msgId+','+commentId+');">'+langPopup['POPUP_WW_DELETE']+'</a></li>' +
						'<li><a href="javascript:futboleaCloseBox();">'+langPopup['POPUP_CANCEL']+'</a></li>' +
					'</ul>' +
					'</p>' +
				'</div>';
		$.facebox(HTML,'', 1);
	}
	
	/**
	* Post a new comment to a Member/Team post.
	*/	
	this.wallPostComment = function (msgId) {
		var me = this;
		var comment = $('#wallComment-'+msgId).attr('value');
		
		
		if (jQuery.trim(comment) != "" && this.writeStateComment != 0 && this.writeStateComment == msgId) {
			var encoded;
		
			var url = '';
			switch(this.type){
				case 1:
					url = 'ajax/wall_member_comment.php';
					break;
				case 2:
					url = 'ajax/wall_team_comment.php';
					break;
				case 5:
					url = 'ajax/wall_country_comment.php';
					break;
				case 8:
					url = 'ajax/wall_pronostic_group_comment.php';
					break;
			}
		
			encodedComment = encodeURIComponent(comment);
		
			$.ajax({
				type: "POST",
				url: url,
				dataType: "json",
				async: true,
				data: ({ message_id : msgId, comment : encodedComment }),
				beforeSend: function() {
					
					var expreg= /\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i;
		
					if(isUrl(comment)){
						$('#wallComment-' +msgId).attr('disabled', true);
						$('#wallCommentBtn-' +msgId).html('<img id="wallLoading" src="images/load.gif" alt="loading..." style="margin-right: 10px"/> <b>Cargando...</b>');
					}else{
						$('#wallComment-' +msgId).attr('disabled', true);
						$('#wallCommentBtn-' +msgId).html('<img id="wallLoading" src="images/sample_images/small_loading.gif" height="9" width="15"  alt="loading..." style="margin-right: 10px"/>');
					}
				},	
				success: function(data){
					if ( data.result == 'done') {
						// Show the comment
						if ($("#postCommentImg-" + msgId).length){
							var UrlNations= (location.href.match('nations.php'))?'yes':'no';
							
							if(UrlNations == 'no'){
								if(data.comment.show_url.length){
									var url= data.comment.show_url[0];
	
									if(url.match('/www.youtube.com/') || url.match('/youtu.be/')){
										$("#postCommentImg-" + msgId).before(wallTpl._createWallCommentUrlYoutube(data.comment, false, me.type));					
									}else{
										$("#postCommentImg-" + msgId).before(wallTpl._createWallCommentUrl(data.comment, false, me.type));
									}
								}else{
									$("#postCommentImg-" + msgId).before(wallTpl._createWallComment(data.comment, false, me.type));
								}								
							}else{
								$("#postCommentImg-" + msgId).before(wallTpl._createWallComment(data.comment, false, me.type));
							}

						} else {
							$("#postComment-" + msgId).before(wallTpl._createWallComment(data.comment, false, me.type));
						}
						
						$("#comment-"+ data.comment.wall_comment_id).fadeIn(500);
						$("#maxComments-" + msgId).html(langPopup['POPUP_WW_COMMENT_SEE'] +' ' + data.wall_comments +' '+langPopup['POPUP_WW_COMMENTS']);
						$('#wallCommentBtn-' +msgId).hide();
					} else {
						alert(data.result);
					}
					
					$('#wallComment-' +msgId).val('');
					
					$('#wallCommentBtn-' +msgId).html('<button class="ok" onclick="wall.wallPostComment('+msgId+', '+me.type+');">'+langPopup['POPUP_WW_COMMENT']+'</button>');
					$('#wallComment-' +msgId).attr('disabled', false);
					$("textarea[id^='wallComment-']").css({height:14});
				}
			});
		}

	}

	/**
	* Get all the comments from a Member/Team post.
	*/	
	this.wallgetMoreComments = function (msgId) {	
		var me = this;
		// loading
		$("#maxComments-" + msgId).after(' <img id="wallLoading" src="images/sample_images/small_loading.gif" height="9" width="15"  alt="loading..." />');
		
		var url = '';
		switch(this.type){
			case 1:
				url = 'ajax/wall_member_get_comments.php';
				break;
			case 2:
				url = 'ajax/wall_team_get_comments.php';
				break;
			case 5:
				url = 'ajax/wall_country_get_comments.php';
				break;
			case 8:
				url = 'ajax/wall_pronostic_group_get_comments.php';
				break;				
		}

		$.ajax({
			type: "POST",
			dataType: "json",
			url: url,
			data: ({ message_id : msgId }),	
			success: function ( data ){
				if ( data.result == "done") {
					var html = "";
					for (var i = 0; i < data.comments.length; i++) {
						// Create the comment Item
						var UrlNations= (location.href.match('nations.php'))?'yes':'no';
						
						if(UrlNations == 'no'){
							if(data.comments[i].show_url.length){
								var url= data.comments[i].show_url;
	
								if(url.match('/www.youtube.com/') || url.match('/youtu.be/')){
									html += wallTpl._createWallCommentUrlYoutube(data.comments[i], true, me.type);
								}else{
									html += wallTpl._createWallCommentUrl(data.comments[i], true, me.type);
								}
							}else{
								html += wallTpl._createWallComment(data.comments[i], true, me.type);
							}							
						}else{
							html += wallTpl._createWallComment(data.comments[i], true, me.type);							
						}

					}
					if (post_enable){
						html += wallTpl._createWallCommentPost(msgId);
					}
					
					// Show all the comments
					$("#wallComments-" + msgId).html(html);
					$("#maxCommentsImg-" + msgId).hide();
					$("#maxCommentsDiv-" + msgId).hide();
					
					// add the resize and write state
					$("#wallComment-" +msgId).autoResize({
						onResize : function() {
							$(this).css({opacity:0.8});
						},
						animateCallback : function() {
							$(this).css({opacity:1});
						},
						animateDuration : 300,
						extraSpace : 0
					});
					
					$("#wallComment-" +msgId).click(function() {
						cleanComment($(this).attr('id'), langPopup['POPUP_WW_COMMENT_WRITE']);
						
						if (id != $(this).attr('id') && id != 0) {
								restoreComment(id,langPopup['POPUP_WW_COMMENT_WRITE']);
						}
						
						id = $(this).attr('id');
					});
					
				} else {
					alert(data.result);
				}
			}
		});
	}



	/**
	* This is a private method to ejecute before calling a New post.
	*/	
	this._beforeWallPost = function() {
		$("#"+this.input).attr("disabled", true );
		$("."+this.button).toggleClass("disabled");
		$("."+this.button).html(' <img id="wallLoading" src="images/sample_images/small_loading.gif" height="9" width="15"  alt="loading..." />');
		$("."+this.button).unbind("click");	
	}
	
	this._beforeWallPostUrl = function() {
		$("#"+this.input).attr("disabled", true );
		$("."+this.button).toggleClass("disabled");
		$("."+this.button).html(' <img id="wallLoading" src="images/load.gif" height="9" alt="loading..." /> <b>Cargando...</b>');
		$("."+this.button).unbind("click");	
	}
	
	/**
	* This is a private method to ejecute after calling a New post.
	*/	
	this._afterWallPost = function() {
		$('#'+this.input).removeAttr('disabled');
		$('.'+this.button).toggleClass('disabled');
		$("."+this.button).html('Publicar');
		$("#BtnPostWall").click(function() {
			wall.wallPost();
		})
		//$('.'+this.button).attr("href","javascript:futbolea_mwall("+this.type+", "+this.mid+")");
		$('#'+this.input).val(langPopup['POPUP_WW_WRITE']);	
		this.writeState		= 0;
	}
	
	this.changeWriteStatus = function() {

		if(	$("#"+this.input).val().length > 0){
			this.writeState = 1;
		}
		else
			this.writeState = 0;
	}
	
	this.changeWriteStatusComment = function(msgId) {
		var comment = $('#wallComment-'+msgId).attr('value');
		if(	comment.length > 0){
			this.writeStateComment = msgId;
		}
		else
			this.writeStateComment = 0;
	}
	
	this.wallLike = function(type, post_id, comment_id) {
		var url = 'ajax/like_new.php?type='+type;
		var prefijo= '';
		var like_id= 0;
		
		switch(type){
			case 1:
				prefijo= 'post';
				like_id= post_id;
				break;
			case 3:
				prefijo= 'comment';
				like_id= comment_id;
				break;
		}
		
		var like_id= (comment_id != 0) ? comment_id : post_id;
		var type_increment= (comment_id != 0) ? 2 : 0;
		//$("#"+prefijo+"-like-"+like_id).attr("href", 'javascript:wall.wallNotLike('+(type + type_increment )+', '+post_id+', '+comment_id+');');  
		//$("#"+prefijo+"-like-"+like_id).attr("style", 'display:none');  
		$("#"+prefijo+"-like-"+like_id).removeAttr('href');
		
		$.ajax({
			type: "POST",
			dataType: "json",
			url: url,
			data: ({ like_post_id : post_id , like_comment_id : comment_id , data_wall_member_id : this.mid }),	
			success: function ( data ){
				if ( data.result == "done") {
					var oldHtml= $("#"+prefijo+"-"+like_id).html();
					//$("#"+prefijo+"-"+like_id).html(oldHtml+'<div class="likes"><p>A <a href="profile.php?pid='+data.member_id+'">ti</a> te gusta esto</p></div>');

					if($("#"+post_id+"-"+comment_id).length){
						$("#"+post_id+"-"+comment_id).html(data.html_like);
					}else{
						$("#"+prefijo+"-"+like_id).html(oldHtml+'<div id="'+post_id+'-'+comment_id+'" class="likes">'+data.html_like+'</div>');
					}
					//$("#"+prefijo+"-like-"+like_id).attr("style", 'display:show');  
					$("#"+prefijo+"-like-"+like_id).attr("href", 'javascript:wall.wallNotLike('+type+', '+post_id+', '+comment_id+');');  
					$("#"+prefijo+"-like-"+like_id).html('Ya no me gusta');
				} else {
					alert(data.result);
				}
			}
		});
		
	}
	
	this.wallNotLike = function(type, post_id, comment_id) {
		var url = 'ajax/like_new.php?type='+type+'&notlike=1';
		var prefijo= '';
		var like_id= 0;
		
		switch(type){
			case 1:
				prefijo= 'post';
				like_id= post_id;
				break;
			case 3:
				prefijo= 'comment';
				like_id= comment_id;
				break;
		}
		
		var like_id= (comment_id != 0) ? comment_id : post_id;
		var type_increment= (comment_id != 0) ? 2 : 0;
		//$("#"+prefijo+"-like-"+like_id).attr("href", 'javascript:wall.wallLike('+(type + type_increment )+', '+post_id+', '+comment_id+');'); 
		//$("#"+prefijo+"-like-"+like_id).attr("href", 'javascript:wall.wallLike('+type+', '+post_id+', '+comment_id+');'); 
		//$("#"+prefijo+"-like-"+like_id).attr("style", 'display:none');
		$("#"+prefijo+"-like-"+like_id).removeAttr('href');
		
		$.ajax({
			type: "POST",
			dataType: "json",
			url: url,
			data: ({ like_post_id : post_id , like_comment_id : comment_id , data_wall_member_id : this.mid }),	
			success: function ( data ){
				if ( data.result == "done") {
					//var oldHtml= $("#"+prefijo+"-"+like_id).html();
					//$("#"+prefijo+"-"+like_id).html(oldHtml+'<div class="likes"><p>A <a href="#">ti</a> ya no te gusta esto</p></div>');
					if($("#"+post_id+"-"+comment_id).length){
						if(data.html_like != null){
							$("#"+post_id+"-"+comment_id).html(data.html_like);
						}else{
							$("#"+post_id+"-"+comment_id).remove();
						}
					}
					//$("#"+prefijo+"-like-"+like_id).attr("style", 'display:show');
					$("#"+prefijo+"-like-"+like_id).attr("href", 'javascript:wall.wallLike('+type+', '+post_id+', '+comment_id+');'); 
					$("#"+prefijo+"-like-"+like_id).html('Me gusta');
				} else {
					alert(data.result);
				}
			}
		});
		
	}
	
	this.showLikes= function(type, post_id, comment_id){
		$.facebox.settings.opacity = 0.5;
		$.facebox.settings.modal = true;
		futboleaLoadingBox();
		
		$.ajax({
			type: "POST",
			dataType: "json",
			url: "ajax/members_like.php?type="+type,
			data: ({ like_post_id : post_id , like_comment_id : comment_id , data_wall_member_id : this.mid }),
			success: function(data){
				if ( data.result == 'done') {
					var htmlExtra= '<div style="text-align:right"><a href="javascript:futboleaCloseBox()">Cerrar</a></div>';
					$.facebox(htmlExtra+data.html,'',1);
				}
			}
		});
		
	}
	
	this.findFriends= function(evento, me){
		var e = evento || window.event;
		var codigo = (e.keyCode > 0) ? e.keyCode : e.charCode;
		
		if(codigo == 64){
			var str= me.value;
			var lastChar= str.substr(str.length-1, 1);
			
			/* Si el caracter antes del arroba es un espacio, o nada, muestro la lista de amigos */
			if(lastChar == ' ' || lastChar == ''){
				//alert(sf[0]['member_fullname']);
			}
		}
	}
}
