
/**
 * Autocomplete phone number to the advertising page
 * @param {Object} "#phone"
 * 
 */
$(document).ready(function(){
         
         var count= 0;
         var numeroSecciones = 0;
         
        $("#phone").keypress(function(e){
           
           if(e.which == 8){
                count = 0;
                numeroSecciones = 0;
                return;
           }
           
           count++;
           
           if(count > 3 && numeroSecciones < 2){
                count = 1;
                numeroSecciones++;
                
                var value = $(this).attr("value");
                value += "-";
                $(this).attr("value",value);
                
           }           
     });
});

/*
 * This section work with the autocomplete textfield of the 
 * Certification level and Certification Agencies 
 */
function findValueCallback(event, data, formatted) {
	$("<li>").html( !data ? "No match!" : "Selected: " + formatted).appendTo("#result");
}
	
function formatItem(row) {
	$("#email").attr('value',row[1]);
	return row[0];
}

function formatResult(row) {
	$("#email").attr('value',row[1]);
	return row[0].replace(/(<.+?>)/gi, '');
}
	

/**
 * Function to show the Error and Advertising message
 * The object is the message to show
 * @param {Object} message
 */
function showMessageError(message){
       if($("#messageErrorAlt").css("display") == "none"){
              $("#messageErrorAlt").fadeIn("fast");
			  $("#messageErrorAlt").text(message);
              setTimeout("hideMessageError()",5000);
       }
}

function hideMessageError(){
       $("#messageErrorAlt").fadeOut("fast");
}


$(document).ready(function(){

if (document.getElementById("txtCertificationAgencies")) {
	$("#txtCertificationAgencies").autocomplete
	(getBaseURL() + 'index.php',
	 {
	 	autoFill:true,
		delay:10,
		cacheLength:1,
		extraParams:{c:"user", m:"certification_agencies"},
		formatItem: formatItem,
		formatResult: formatResult
	 }
	);
}

if (document.getElementById("txtCertificationLevels")) {
	$("#txtCertificationLevels").autocomplete
	(getBaseURL() + 'index.php',
	 {
		autoFill:true,
		delay:10,
		cacheLength:1,
		extraParams:{c:"user", m:"certification_levels"},
		formatItem: formatItem,
		formatResult: formatResult
	 }
	);
}

	if(window.location.href.indexOf('compose') > -1 || window.location.href.indexOf('sendMessage') > -1){
		$('#txtEmailCompose').autocomplete(getBaseURL() + 'index.php',
		{
			autoFill:true,
			delay : 10,
			cacheLength:1,
			extraParams: {c: 'inbox', m: 'getEmailFriends'},
			formatItem: formatItem,
			formatResult: formatResult
		});
	}
});


/**
 * Get the Code IGniter Base URL
 */
function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));


    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
   }
}

/**
 * Configure the datepicker to select user's birthday
 * or diveshop Open Since
 * @param {Object} event
 */
$(document).ready(function(event){
	var fechaMinima = new Date();
	var fechaMaxima = new Date();
	fechaMinima.setFullYear(1930,1,1);

	if (document.getElementById("txtBirthday")) {
		
		$('#txtBirthday').datepicker
        ({
                  changeYear : true,
                  changeMonth : true,
                  dateFormat :'mm-dd-yy',
				  minDate : fechaMinima,
				  maxDate : fechaMaxima,
				  yearRange:'1930:2010'
         });
	}
});

/**
 * Function to fill the state by ajax when the user select
 * united states
 * @param {Object} event
 */
$(document).ready(function(event){
	
	if(window.location.href == (getBaseURL() + 'user/signup')
	   || window.location.href == (getBaseURL() + 'user/signup_diveshops')
	   || window.location.href == (getBaseURL() + 'user/create')){
			
		if($('#lstCountry').val() == 'us'){
			fillStates('');
		}else{
			$('p:has(#lstState)').css('display','none');
			$('p:has(#txtZipCode)').css('display','none');
		}
		
			
		$('#lstCountry').change(function(event){
			
			if($(this).val() == 'us'){
					fillStates('');
					$('p:has(#lstState)').fadeIn();
					$('p:has(#txtZipCode)').fadeIn();
					$('#txtZipCode').val('');
				}else{
					fillStateWidthAlternateData();
					$('p:has(#lstState)').fadeOut();
					$('p:has(#txtZipCode)').fadeOut();
					$('#txtZipCode').val('');
				}
		});				   	
	}
	
		
	if(window.location.href == (getBaseURL() + 'user/edit_profile')){
		
			if($('#lstCountry').val() == 'us'){
				fillStates($('#userStateLocation').val());
			}else{
				$('p:has(#lstState)').css('display','none');
				$('p:has(#txtZipCode)').css('display','none');
			}
			
			$('#lstCountry').change(function(event){
			
				if($(this).val() == 'us'){
					fillStates('');
					$('p:has(#lstState)').fadeIn();
					$('p:has(#txtZipCode)').fadeIn();
					$('#txtZipCode').val('');
				}else{
					fillStateWidthAlternateData();
					$('p:has(#lstState)').fadeOut();
					$('p:has(#txtZipCode)').fadeOut();
					$('#txtZipCode').val('');
				}
		});	
	}
});

function fillStateWidthAlternateData(){
	$('#lstState').html('');
	$('#lstState').append('<option value="other">Other state</option>');
}

function fillStates(stateSelected){
	$('#lstState').html('');
	$.ajax({
		dataType : 'HTML',
		type : 'POST',
		data : 'stateSelected='+stateSelected,
		url : getBaseURL() + 'user/get_states',
		error : function(obj,mensaje,obj2){
			alert(mensaje);
		},
		success : function(datos){
			$('#lstState').append(datos);
		}
	});
}


/**
 * Function to accept via ajax
 * a friend request 
 * @param {Object} userId
 */
function acceptFriendRequest(userId){
	
	$.ajax({
		dataType: 'html',
		type: 'post',
		url: getBaseURL() + '/friendlist/friend',
		data: 'might_id='+userId,
		success: function(event){
			
			var layoutId = '#userAccept'+userId;
			var linkProfileLayout = '#userLinkProfile';
			var friendFullName = '#userFullName'+userId;
			var message = "You have accepted "+$(friendFullName).text()+" as your friend. To see this profile"+
			" click <a href='"+getBaseURL()+"/user/profile/"+userId+"/dropoff'>here</a>";
			$(layoutId).slideUp('fast');
			$(linkProfileLayout).html(message);
			$(linkProfileLayout).slideDown('fast');
		},
		error : function(data, msg, data2){
			alert(msg);	
		}
	});
}

/**
 * Function to cancel a friend request
 * via ajax
 * @param {Object} userId
 */
function cancelFriendRequest(userId){
	
	$.ajax({
		dataType: 'html',
		type: 'post',
		url:getBaseURL() + '/friendlist/friend',
		data: 'might_id='+userId+'&deny=deny',
		success: function(event){
			var friendFullName = '#userFullName'+userId;
			var message = "You have denied "+$(friendFullName).text()+" as your friend.";
			var linkProfileLayout = '#userLinkProfile';
			var layoutId = '#userAccept'+userId;
			$(layoutId).slideUp('fast');
			$(linkProfileLayout).html(message);
			$(linkProfileLayout).slideDown('fast');
			$(linkProfileLayout).html(message);
		}
	});
}

/*
 * Method to upload the new avatar in the
 * edit profile page.
 * 
 */

$(document).ready(function(event){
	
	$('#changePassword').click(function(event){
		
		$('#txtPassword').attr("readonly","");
		$('#txtPassword').attr("value","");	
		$('#txtConfirmPassword').attr("readonly","");
		$('#txtConfirmPassword').attr("value","");
	});
/*
breaks IE filestyle jquery plugin

     if($('#uploader').length > 0){
        $("#uploader").filestyle({ 
		image: getBaseURL() + "images/buttons/browse.gif",
		imageheight : 34,
		imagewidth : 84,
		width : 150
		});
     }
*/
});

$(document).ready(function(event){
	$('#btnUploadAvatar').click(function(event){
		
		$.ajaxFileUpload({
			url: getBaseURL() + "user/upload_avatar/"+$('#member_type').val(),
			secureuri:false,
			fileElementId: 'uploader',
			dataType: 'json',
			success: function(data, status){				
				if(data.msg == "no path"){
					alert("It has ocurred an error in the process of upload the image");
					return;
				}
				$('#imgAvatar').attr('src',data.msg);
				$('#imgAvatar').css('width','90px');
				$('#imgAvatar').css('height','90px');
				showMessageError("You have uploaded a new avatar for your profile.");
			},
			error : function(data, status, e){
			}
		});
	});
});

$(document).ready(function(event){

	if((window.location.href != (getBaseURL() + 'polls')) &&
	   (window.location.href != (getBaseURL() + 'welcome') &&
	   (window.location.href != getBaseURL()))){
		return;
	}
	
	loadPoll(0);
});

function loadPoll(idPoll){
	
	if(idPoll != 0){
		$('#pollContainer').slideUp('fast');
		$('#pollContainer').html('');
		$('#pollContainer').slideDown('fast');
		$('#pollId').attr('value',idPoll);
		var pollTitle = $('#' + idPoll).text();
		$('#pollTitle').text(pollTitle);
	}
	
	$.ajax({
		type: 'post',
		dataType : 'html',
		url : getBaseURL() + 'polls/getAnswers',
		data : 'pollId=' + idPoll,
		success : function(data){
			
			var answerArray = data.split(',');
			var answerText = new Array();
			var answerId = new Array();
			
			for(var i = 0; i < answerArray.length; i++){
				
				var answerPart = answerArray[i].split('=');
				answerText[i] = answerPart[1];
				answerId[i] = answerPart[0];
			}			
			
			$('#pollContainer').jPoll({
				pollHeading: '',
				groupName : 'optionSelected',
				groupIDs : answerId,
				groupTexts : answerText,
				errors : true,
				ajaxOpts: {
					url : getBaseURL() + 'polls/vote'
				} 
			});
		}
	});
}

$(document).ready(function(event){

if((window.location.href == (getBaseURL() + 'user/signup')) ||
   (window.location.href == (getBaseURL() + 'user/signup_diveshops'))){
 			
		$('#registrationProcess input').blur(function(event){
			var title = new String($(this).attr("id"));
			title = title.substring(3,title.length);
		
		
			if ($(this).val() == "") {
				$(this).css('border-style', 'solid');
				$(this).css('border-width', '1px');
				$(this).css('border-color', 'red');
				$(this).attr('title','Introduce the ' + title + ' field.');
			}else{
				$(this).css('border-style', 'none');
				$(this).css('border-width', '0px');
				$(this).css('border-color', 'red');
				$(this).attr('title','');
			}
		});			
	}
});

/**
 * Function to slide Down the Advance search y friends section
 * 
 */

$(document).ready(function(event){
		
	$("#advanceSearchButton").click(function(event){
		$('#advanceSearchBox').slideToggle('fast');
	});
});

//=============================================== articles section ==================================================

/**
 * Assign event of the category link to get articles by category
 * @param {Object} event
 */
$(document).ready(function(event){
	
	if (window.location.href.indexOf(getBaseURL() + 'articles') > -1) {
		$('span[id^=category]').click(function(event){
			getArticlesByCategory($(this).attr('id'));
		});
	}
});

/**
 * Assign event of the month link to get articles by month
 * @param {Object} event
 */
$(document).ready(function(event){
	
	if (window.location.href.indexOf(getBaseURL() + 'articles') > -1) {
		$('span[id^=articlesByMonth]').click(function(event){
			getArticlesByMonth($(this).attr('id'));
		});
	}
})

/**
 * Assign the event of the article link to show the article
 * @param {Object} event
 */
$(document).ready(function(event){
	
	if(window.location.href.indexOf(getBaseURL() + 'articles') > -1){
		$('span[id^=article]').click(function(event){
			showArticle($(this).attr('id'));
		});
	}
});

/**
 *Assign event to get articles by year
 **/
$(document).ready(function(event){
	
	if (window.location.href.indexOf(getBaseURL() + 'articles') > -1) {
		$('h2[id^=articlesYear]').click(function(event){
			
			getArticlesByYear($(this).attr('id'));	
		});
	}
});

/*
 *Get articles order by year
 */
function getArticlesByYear(year){
	cleanArticleReader();
	
	var regularExpression = new RegExp('(\\d)+');
	var matches = regularExpression.exec(year);
	var id = matches[0];
		
	$.ajax({
		dataType : 'json',
		type : 'post',
		url : getBaseURL() + 'articles/year/'+id,
		success : function(data){
			showListOfArticles(data);
		}
	});
}

/**
 * Get articles order by month
 */
function getArticlesByMonth(month){
	var monthInfo = month.split('-');
	
	cleanArticleReader();
	
	$.ajax({
		dataType : 'json',
		type : 'post',
		url : getBaseURL() + 'articles/month/'+monthInfo[1]+'/'+monthInfo[2],
		success : function(data){
			showListOfArticles(data);
		}
	});
}

/*
 * Get articles by category
 */

function getArticlesByCategory(category){
		$('span[id^=category]').css('font-size','13px');
		$('#'+category).animate({fontSize : '115%'},100);
		
		var regularExpression = new RegExp('(\\d)+');
		var matches = regularExpression.exec(category);
		var id = matches[0];
		
		cleanArticleReader();
		
		$.ajax({
			dataType : 'json',
			type : 'get',
			url : getBaseURL() + 'articles/category/' + id,
			success : function(data){
				showListOfArticles(data);
			}
	});
}

/**
 * Get an article 
 * @param {Object} button
 */
function showArticle(button){
	var regularExpression = new RegExp('(\\d)+');
	var matches = regularExpression.exec($("#"+button).attr('id'));
	var id = matches[0];
	window.scrollTo(0,0);
	$.ajax(
	{
		dataType : 'json',
		type : 'get',
		url : getBaseURL() + 'articles/show/'+id,
		success : function(data){
			$('#articlesList').slideUp();
			$("#articlesList").empty();
			$('#articlesDate').text(data.article.date);
			$("#articlesTitle").text(data.article.title);
			$("#articlesContent").html(data.article.content);
			$('#articlesReader').append('<input type="hidden" id="articlesIdentifier" value="'+data.article.id+'" />');
			$("#articlesReader").slideUp('fast');
			$("#articlesReader").slideToggle('fast');
			$('#articlesNavigation').html('');
			$('#articlesNavigation').css('display','block');
			
			if(data.prevArticle != null){
				var prevArticleId = "articlesPrev"+data.prevArticle.id
				$("#articlesNavigation").append
				("<span class='fakeLink' id="+prevArticleId+">Preview </span>");
				$('#'+prevArticleId).click(function(event){
					showArticle($(this).attr('id'));
				});
			}
				
			if(data.nextArticle != null){
				var nextArticleId = "articlesNext"+data.nextArticle.id;
				$("#articlesNavigation").append
				("<span class='fakeLink' id='articlesNext"+data.nextArticle.id+"'>Next</span>");
				$('#'+nextArticleId).click(function(event){
					showArticle($(this).attr('id'));
				});
			}
			
			$('#commentLayout').css('display','block');
			showAllComments(id);
			createCommentPostLayout();
		}
	});
}

function createCommentPostLayout(){
	$.ajax({
		dataType : 'html',
		type : 'get',
		url : getBaseURL() + 'articles/createCommentPostLayout',
		success : function(data){
	
			if(data != null){
				$('#commentPostLayout').html(data);
				$('#btnComment').click(function(event){
					postComment();
				});
			}
		}
	});
}

function postComment(){
	$.ajax({
		dataType : 'html',
		type : 'post',
		data : 'comment='+$('#txtComment').attr('value'),
		url : getBaseURL() + 'articles/comment/' + $('#articlesIdentifier').attr('value'),
		success : function(data){
			showAllComments($('#articlesIdentifier').attr('value'));
		}
	});
}

function showAllComments(idArticle){

	$.ajax({
		dataType : 'json',
		type : 'get',
		url : getBaseURL() + 'articles/getComments/'+idArticle,
		success : function(data){
			
			$('#commentList').slideUp('fast');
			$('#commentList').html('');
			
			
			for(var i = 0; i < data.comments.length; i++){
				$("#commentList").append(data.comments[i]);
			}
			
			$('#commentList').slideDown();
			submitComment();
			setReplyComment();
		}
	});
}

function showListOfArticles(data){
	
	if(data.articles.length == 0){
		$('#articlesList').slideUp('fast').html('').append
		('<div style="text-align:center">There are no articles in this section').slideDown();
		return;
	}	
			
	$('#articlesList').slideUp('fast').html('');
		
	for(var i = 0; i < data.articles.length; i++){
		var article = data.articles[i];
		$('#articlesList').html(getFormatArticle(article));
	}	

	$('#articlesList').slideDown('fast');		
}

function cleanArticleReader(){
	$('#articlesDate').html('');
	$("#articlesTitle").html('');
	$("#articlesContent").html('');
	$('#articlesIdentifier').attr('value','');
	$("#articlesReader").css('display','none');
	$('#commentLayout').css('display','none');
	$('#commentList').html('');
	$('#commentPostLayout').html('');
	$('#articlesNavigation').css('display','none');
	$('#articlesNavigation').html('');
}


/**
 * Get the format of the article
 * @param {Object} article
 */
function getFormatArticle(article){
	$('#articlesList').append('<div id="articles'+article.id+'"></div>');
	$('#articles'+article.id).addClass('article_PItTx');
	$('#articles'+article.id).addClass('snArt_read');
	$('#articles'+article.id).append('<span id="articlesSummaryDate">'+article.date+'</span>');
	$('#articles'+article.id).append('<h3></h3>');
	$('#articles'+article.id+' h3').append('<span id="article'+article.id+'">'+article.title+'</span>');
	$('#articles'+article.id+' h3'+ ' span#article'+article.id).addClass('fakeLink');
	$('#articles'+article.id+' h3'+ ' span#article'+article.id).click(function(event){
		showArticle($(this).attr('id'));
	});
	$('#articles'+article.id).append('<div id="articlesSummaryContent">'+article.content+'</div>');
	$('#articles'+article.id).addClass('article-content');
	
	return;
}

/*
 * ============================================= Friend Section ====================================================
 */

$(document).ready(function(event){
	
	$('span[id^=letter]').click(function(event){
		
		var	letter = $(this).attr('id').substring(6,$(this).attr('id').length);
		var userId = $('#activeUser').attr('value');
		
		if(window.location.href.indexOf('user/more_friend') > -1)
			findFriendAlphabetically(letter,userId);
		else if(window.location.href.indexOf('search') > -1)
			findUserAlphabetically(letter);
	});
});

assignEventDeleteFriend();
assignEventAddUserAsFriend();

$(document).ready(function(event){
	
	$('#btnSearch').click(function(event){
			
			var criteria = $('input:radio[name=rbSearchOption]:checked').val();
		
			if(criteria == '' || criteria == undefined || criteria == null){
				showMessageError('You must select the criteria.');
				return;
			}
			
			if (window.location.href.indexOf('search') > -1) {
				findUsers(criteria, $('#txtSearchValue').val())
			}
			else {
				findFriends(criteria, $('#txtSearchValue').val());
			}
	});
	
	$('#btnAdvanceSearch').click(function(event){
		if(window.location.href.indexOf('search') > -1){
			findUsersAdvance();
		}else{
			findFriendsAdvance();			
		}
	});
});

$(document).ready(function(event){
	
	$('#txtSearchValue').keypress(function(event){
				
		if(event.which == 13){
			var criteria = $('input:radio[name=rbSearchOption]:checked').val();
		
			if(criteria == '' || criteria == undefined){
				showMessageError('You must select the criteria.');
				return;
			}
			
			if (window.location.href.indexOf('search') > -1) {
				findUsers(criteria, $('#txtSearchValue').val())
			}
			else {
				findFriends(criteria, $('#txtSearchValue').val());
			}
		}
	})
});

function assignEventDeleteFriend(){
	$(document).ready(function(event){
	
		$('span[id^=delete]').click(function(event){
			
			var friend = $(this).attr('id').substring(6,$(this).attr('id').length);
			
			if(confirm('Do you want to remove this friend.'))
				deleteFriend(friend);
		});
	});
}

function assignEventAddUserAsFriend(){
	$(document).ready(function(event){
		
		$('span[id^=addFriend]').click(function(event){
			var userId = $(this).attr('id').substring(9,$(this).attr('id').length);
			addUserAdFriend(userId);
		});
	});
}

function deleteFriend(friendId){
	$.ajax({
		type : 'post',
		dataType : 'html',
		url : getBaseURL() + 'user/deleteFriendship/',
		data : 'friend=' + friendId,
		success : function(data){
			
			var friendName = $('#friendName').text();
			if(data == "deleted"){
				$('#friendInformation'+friendId).slideUp('fast');
				$('#friendInformation'+friendId).html('');
				showMessageError(friendName + 'Has been removed of your friend list.');
			}else{
				alert(data);	
			}			
		}
	});
}

function addUserAdFriend(userId){
	$.ajax({
		type : 'post',
		dataType :'html',
		url : getBaseURL() + 'user/add_friend/'+userId,
		success : function(data){
			$('#friendInformation'+userId).slideUp('fast');
			$('#friendInformation'+userId).html('');
			showMessageError('Your invitation has been sent to ' + data);
		}
	});
}

function findFriendAlphabetically(letter,user){
	
	$.ajax({
		type : 'post',
		dataType : 'json',
		url : getBaseURL() + 'user/filterfriends/'+user+'/'+letter,
		success : function(data){
			showUsersFound(data);
		}
	});
}

function findUserAlphabetically(letter){
	
	$.ajax({
		type : 'post',
		dataType : 'json',
		url : getBaseURL() + 'search/userByLetter/',
		data : 'letter='+letter,
		success : function(data){
			showUsersFound(data);
		}
	});
}


function findUsers(criteria, criteriaValue){
	
	$.ajax({
		type : 'post',
		dataType : 'json',
		url : getBaseURL() + 'search/findUsersSingleCriteria',
		data : 'criteria='+criteria+'&criteriaValue='+criteriaValue,
		success : function(data){
			showUsersFound(data);
		}
	});
}

function findFriends(criteria, criteriaValue){
	
		$.ajax({
			type : 'post',
			dataType : 'json',
			url : getBaseURL() + 'user/searchFriendSingleCriteria/',
			data : 'criteria='+criteria+'&criteriaValue='+criteriaValue,
			success : function(data){
				showUsersFound(data);
				
			}
		});
}

function findUsersAdvance(){
	var ageFrom = $('#txtAgeFrom').val();
	var ageTo = $('#txtAgeTo').val();
	var gender = $('#lstGender').val();
	var country = $('#lstCountry').val();
	var zipCode = $('#txtZipCode').val();
	
	$.ajax({
		type : 'post',
		dataType : 'json',
		url : getBaseURL() + 'search/findUsersAdvanceCriteria' ,
		data : 'ageFrom='+ageFrom+'&ageTo='+ageTo+'&gender='+gender+'&country='+country+'&zipCode='+zipCode,
		success : function(data){
			showUsersFound(data);
		}
	})
}

function findFriendsAdvance(){
	var ageFrom = $('#txtAgeFrom').val();
	var ageTo = $('#txtAgeTo').val();
	var gender = $('#lstGender').val();
	var country = $('#lstCountry').val();
	var zipCode = $('#txtZipCode').val();
	
	$.ajax({
		type : 'post',
		dataType : 'json',
		url : getBaseURL() + 'user/getFriendsAdvanceSearch' ,
		data : 'ageFrom='+ageFrom+'&ageTo='+ageTo+'&gender='+gender+'&country='+country+'&zipCode='+zipCode,
		success : function(data){
			showUsersFound(data);
		}
	})
}

function showUsersFound(data){
	$('#friends').slideUp('fast');
	$('#friends').html('');
	
	if(data.friendsFound.length == 0){
		$('#friends').append('<div style="font-weight:bold; text-align:center; margin-top:7px;">No friends was found.</div>');
		$('#friends').slideDown('fast');
		return;
	}
	
	for(var i = 0; i < data.friendsFound.length; i++){
		var friend = data.friendsFound[i];
	
		if(friend.stateName == null)
			friend.stateName = "";
	
		makeUserFriendLayout(data.friendsFound[i],data.isLogged);
	}
	
	if(window.location.href.indexOf('more_friend') > -1)
		assignEventDeleteFriend();
	else
		assignEventAddUserAsFriend();
	
	$('#friends').slideDown('fast');
}

function makeUserFriendLayout(friend,isLogged){
	var friendLayout = '<div id="friendInformation'+friend.user_id+'" class="user group">' +
					   '<a href="'+getBaseURL()+'user/profile/'+friend.user_id+'">'+
					    friend.avatarImage+'</a>'+
					   '<div id="friendName"><a href="'+getBaseURL()+'user/profile/'+friend.user_id+'">'+
						friend.fname + ' ' + friend.lname + '</a></div>';
			           
					   if(friend.nickname != '' && friend.nickname != undefined){
					   		friendLayout += '<div id="friendNickname">' + friend.nickname + '</div>';
					   }
					   
					   friendLayout += '<div id="friendLocation">';
					   
					   if(friend.countryName != undefined){
					   		friendLayout += friend.countryName + '<br />';			   	
					   }
					   
					   friendLayout += friend.city + ', ';
		
					   if(friend.stateName != undefined){
					 	  friendLayout += friend.stateName;  	
					   }
					   
					   friendLayout += '</div>';
					   
					   var h = new String('hola');
					  
					   if(friend.experience != ''){
					   		friendLayout += '<div id="friendExperience">' + friend.experience;
					   }
					   
					   if(window.location.href.indexOf('search') == -1){
				   	   		friendLayout += '<div style="float:right">'+
					   		'<span class="fakeLink" id="delete'+friend.user_id+'">'+
					   		'Delete</span></div>';	
					   }else{
							if (isLogged == true) {
							
								friendLayout += '<div style="float:right">' +
								'<span class="fakeLink" id="addFriend' +
								friend.user_id +
								'">' +
								'Add friend</span></div>';
							}
					   }
					   
					  friendLayout += '</div></div>';
	$('#friends').append(friendLayout);
}

/* ====================================================== Inbox Section ============================================================ */


$(document).ready(function(event){
	$('#btnReplyMessage').click(function(event){
		$.ajax({
			url : getBaseURL() + 'inbox/replyMessage',
			dataType : 'json',
			data : 'messageId='+$('#messageId').val() + '&userToReply='+ $('#userId').val()+'&replyBody='
			+ $('#txtReplyMessage').val(),
			type : 'post',
			success : function(data){
				if(data.error == 'incomplete'){
					showMessageError('Introduce the message of the reply.');
					return;
				}
				
				makeReplyMessage(data);
				$('#txtReplyMessage').text('');
			}
		});
	});
});


$(document).ready(function(event){
	$('#selectAllMessage').click(function(event){
		$('input:checkbox').attr('checked','checked');
	});
	
	$('#deselectAllMessage').click(function(event){
		$('input:checkbox').attr('checked','');
	});
	
	$('#selectReadMessage').click(function(event){
		$('div[id^=inboxItemWrap]:has(input[value=read]) input:checkbox').attr('checked','checked');
	});
	
	assignEventSelectUnreadMessages();
	
	$('#selectReadMessage').click(function(event){
		$('div[id^=inboxItemWrap]:has(input[value=read]) input:checkbox').attr('checked','checked');
	});
    
    $('#btnSearchMessages').click(function(event){
       findInboxMessages();
    });
	
	changeStatusToUnread();
	changeStatusToRead();
	assignEventDeleteMessages();
	assignEventDeleteInboxMessage();
});

function assignEventDeleteInboxMessage(){
	$(document).ready(function(event){
	$('span[id^=inboxDelete]').click(function(event){
		var regularExpression = new RegExp('(\\d)+');
		var matches = regularExpression.exec($(this).attr('id'));
		var id = matches[0];
		
		if(!confirm('Do you want to delete this message?')){
			return;
		}
		
		deleteMessage(id);
	
	});
});
	
}

function assignEventDeleteMessages(){
	$('#btnDelete').click(function(event){
		
		if(!confirm('Do you want to delete these messages?')){
			return;
		}
		
		$('input:checkbox:checked').each(function(event){
			var inboxId = $(this).val();
			deleteMessage(inboxId);
		});
		
	});
}

function deleteMessage(messageId){
	$.ajax({
		data : 'inboxId=' + messageId,
		type : 'post',
		dataType : 'html',
		url : getBaseURL() + 'inbox/delete',
		success : function(data){
			$('#inboxItemWrap' + messageId).fadeOut('fast');
	
		}
	});
}

function changeStatusToRead(){
	$('#btnMarkRead').click(function(event){
		$('input:checkbox:checked').each(function(event){
			var inboxId = $(this).val();
			changeStatusMessage(inboxId,'yes');
		})
		
		if($('input:checkbox:checked').length == $('input:checkbox').length){
			$('#selectUnreadMessage').remove();
		}
	});
}

function changeStatusToUnread(){
	$('#btnMarkUnread').click(function(event){
		
		$('input:checkbox:checked').each(function(event){
			var inboxId = $(this).val();
			changeStatusMessage(inboxId,'no');
		});
		
		if($('input:checkbox:checked').length > 0){
			if ($('#selectUnreadMessage').length == 0) {
				$('#selectors').append('<span id="selectUnreadMessage">Unread</span>');
				$('#selectUnreadMessage').addClass('fakeLink');
			}
			assignEventSelectUnreadMessages();
		}
	});
}

function assignEventSelectUnreadMessages(){
		if($('#selectUnreadMessage').length > 0){
		$('#selectUnreadMessage').click(function(event){
			$('div[id^=inboxItemWrap]:has(input[value=unread]) input:checkbox').attr('checked','checked');
		});
	}
}

function changeStatusMessage(inboxId,status){
			
	$.ajax({
		data : 'inboxId='+inboxId+'&status='+status,
		dataType : 'html',
		url : getBaseURL() + 'inbox/changeStatus',
		type : 'post',
		success : function(data){
				
			if(status == 'yes'){
				$('#statusMessageText'+inboxId).text('');
				$('#statusMessage'+inboxId).attr('value','read');
			}else if(status == 'no'){
				$('#statusMessageText'+inboxId).text('(New)');
				$('#statusMessage'+inboxId).attr('value','unread');
			}
		}
	});
}

function makeReplyMessage(data){
	var message = '<div class="messageBodyReply" style="display:none;" id="reply'+data.messageId+'">'+
				  '<div id="imageAvatar" style="float:left; margin-right:5px;">'+data.userAvatar+'</div>'+
				  '<div id="messageData" style="float:left;">'+
				  '<div class="messageInboxBody" style="padding-left:5px;"><div id="dateMessage">'
				  +data.userAndDate+'</div>'+data.messageBody+'</div></div>'+
				  '<div style="clear:both"></div></div><hr />';
	$('#replayMessages').append(message);
	
	$('#reply'+data.messageId).fadeIn('slow');
}

function findInboxMessages(){
    var keySearch = $('#txtSearchMessages').val();
    $.ajax({
       url : getBaseURL() + 'inbox/findInboxMessage',
       data : 'keySearch= ' + keySearch,
       dataType : 'json',
       type : 'post',
       success : function(data){
            
            if(data.error == 'no found'){
                return;
            }    
			
			showFoundMessages(data.messages);
       }
    });
}

function showFoundMessages(messages){
	$('div.inboxWrapper').slideUp('fast');
	$('div.inboxWrapper').html('');
	
	for(var i = 0; i < messages.length; i++){
		message = messages[i];
		
		$('div.inboxWrapper').append('<div id="inboxItemWrap'+message.inbox_id+'"></div>');
		$('#inboxItemWrap'+message.inbox_id).addClass('inboxItemWrap');
		$('#inboxItemWrap'+message.inbox_id).append('<input type="hidden" id="statusMessage'+message.inbox_id+'" />');
	
		if(message.read == 'no' || message.hasNewReplyMessages == false){
			$('#statusMessage'+message.inbox_id).attr('value','unread');
		}else{
			$('#statusMessage'+message.inbox_id).attr('value','read');
		}
		
		$('#inboxItemWrap'+message.inbox_id).append('<div class="inboxItemBullet"></div>');
		$('#inboxItemWrap'+message.inbox_id+' div.inboxItemBullet').append('<input type="checkbox" id="'+message.inbox_id+'"/>');
		$('input#'+message.inbox_id).attr('value',message.inbox_id);
		$('#inboxItemWrap'+message.inbox_id).append('<div class="inboxItemPic"></div>');
		$('#inboxItemWrap'+message.inbox_id+' div.inboxItemPic').append('<a></a>');
		$('#inboxItemWrap'+message.inbox_id+' div.inboxItemPic a').attr('href',getBaseURL()+'user/profile/'+message.user.user_id);
		$('#inboxItemWrap'+message.inbox_id+' div.inboxItemPic a').append(message.avatar);
		$('#inboxItemWrap'+message.inbox_id).append('<div class="inboxItemName"></div>');
		$('#inboxItemWrap'+message.inbox_id+' div.inboxItemName').append('<a></a>');
		$('#inboxItemWrap'+message.inbox_id+' div.inboxItemName a').attr('href',getBaseURL()+'user/profile/'+message.user.user_id);
		$('#inboxItemWrap'+message.inbox_id+' div.inboxItemName a').append('<span>'+message.user.fname +' '
		+ message.user.lname +'</span>');
		$('#inboxItemWrap'+message.inbox_id+' div.inboxItemName').append('<br />');
		$('#inboxItemWrap'+message.inbox_id+' div.inboxItemName').append(message.date);
		$('#inboxItemWrap'+message.inbox_id).append('<div id="inboxItemMessage'+message.inbox_id+'"></div>');
		$('#inboxItemWrap'+message.inbox_id).append('<div id="inboxItemMessage'+message.inbox_id+'"></div>');
		$('#inboxItemMessage'+message.inbox_id).addClass('inboxItemMessage');
		$('#inboxItemMessage'+message.inbox_id).append('<a>'+message.subject+'</a>');
		$('#inboxItemMessage'+message.inbox_id+' a').attr('href',getBaseURL()+'inbox/show/'+message.inbox_id);	
		$('#inboxItemMessage'+message.inbox_id).append('<span class="bold" id="statusMessageText'+message.inbox_id+'"> </span>');
		$('#statusMessageText'+message.inbox_id).text(message.status);
		$('#inboxItemWrap'+message.inbox_id).append('<div class="inboxItemDel"></div>');
		$('#inboxItemWrap'+message.inbox_id+' div.inboxItemDel').append('<span id="inboxDelete'+message.inbox_id+'">Delete</span>');
		$('#inboxItemWrap'+message.inbox_id+' div.inboxItemDel span').addClass('fakeLink');
		
		assignEventDeleteInboxMessage();
	}
	
	
	
	$('div.inboxWrapper').slideDown('fast');
}

/* ====================================================== Disable Account ============================================================ */

$(document).ready(function(event){
	$('#btnAcceptCancel').click(function(event){
		window.location.href = getBaseURL() + 'user/deactivateUserAccount';
	});
	
	$('#btnCancelOperation').click(function(event){
		window.location.href = getBaseURL() + 'user/me';
	});
})

$(document).ready(function(event){
	$('#imgAvatar').css('width','90px');
	$('#imgAvatar').css('height','90px');
});