function editBasicInformation(){
	$('#loader_edit_basic_information').show();
	$.ajax({
		   url: "/frontend_dev.php/user/editBasicInformation",
		   data: "",
		   success: function(html){
			 $('#loader_edit_basic_information').hide();
		     $('#basic_information').html(html);
		     
		     $("#user_city_id").val($("#city").val());
		     $("#city").change(function(){
		         $("#user_city_id").val($("#city").val());
		     }); 
		   }
	 });
}
function showBasicInformation(){
	$('#loader_edit_basic_information').show();
	$.ajax({
		   url: "/frontend_dev.php/user/showBasicInformation",
		   data: "",
		   success: function(html){
			 $('#loader_edit_basic_information').hide();
		     $('#basic_information').html(html);
		   }
	 });
}
function updateBasicInformation(){
	$('#loader_edit_basic_information').show();
	$.ajax({
		   url: "/user/updateBasicInformation",
		   data: $('#basic_information_form').serialize(),
		   dataType: "json",
		   cache: false,
		   success: function(result){	
			 $('#loader_edit_basic_information').hide();
		     $('#basic_information').html(result.html);
		     if(result.state){
		    	 flash_message(result.flash);
		    	 
		     }
		     else
		    	 flash_error_message(result.flash);
		   }
	 });
}
function editRut(){
	$('#loader_edit_rut').show();
	$.ajax({
		   url: "/frontend_dev.php/user/editRut",
		   data: "",
		   success: function(html){
			 $('#loader_edit_rut').hide();
		     $('#rut').html(html);
		   }
	 });
}
function showRut(){
	$('#loader_edit_rut').show();
	$.ajax({
		   url: "/frontend_dev.php/user/showRut",
		   data: "",
		   success: function(html){
			 $('#loader_edit_rut').hide();
		     $('#rut').html(html);
		   }
	 });
}
function updateRut(){
	$('#loader_edit_rut').show();
	$.ajax({
		   url: "/user/updateRut",
		   data: $('#rut_form').serialize(),
		   dataType: "json",
		   cache: false,
		   success: function(result){	
			 $('#loader_edit_rut').hide();
		     $('#rut').html(result.html);
		     if(result.state)
		    	 flash_message(result.flash);
		     else
		    	 flash_error_message(result.flash);
		   }
	 });
}
function editEmail(){
	$('#loader_edit_email').show();
	$.ajax({
		   url: "/frontend_dev.php/user/editEmail",
		   data: "",
		   success: function(html){
			 $('#loader_edit_email').hide();
		     $('#email').html(html);
		   }
	 });
}
function showEmail(){
	$('#loader_edit_email').show();
	$.ajax({
		   url: "/frontend_dev.php/user/showEmail",
		   data: "",
		   success: function(html){
			 $('#loader_edit_email').hide();
		     $('#email').html(html);
		   }
	 });
}
function updateEmail(){
	$('#loader_edit_email').show();
	$.ajax({
		   url: "/user/updateEmail",
		   data: $('#email_form').serialize(),
		   dataType: "json",
		   cache: false,
		   success: function(result){	
			 $('#loader_edit_email').hide();
		     $('#email').html(result.html);
		     if(result.state)
		    	 flash_message(result.flash);
		     else
		    	 flash_error_message(result.flash);
		   }
	 });
}

function editPassword(){
	$('#loader_edit_password').show();
	$.ajax({
		   url: "/frontend_dev.php/user/editPassword",
		   data: "",
		   success: function(html){
			 $('#loader_edit_password').hide();
		     $('#password').html(html);
		   }
	 });
}
function showPassword(){
	$('#loader_edit_password').show();
	$.ajax({
		   url: "/frontend_dev.php/user/showPassword",
		   data: "",
		   success: function(html){
			 $('#loader_edit_password').hide();
		     $('#password').html(html);
		   }
	 });
}

function updatePassword(){
	$('#loader_edit_password').show();
	$.ajax({
		   url: "/user/updatePassword",
		   data: $('#password_form').serialize(),
		   dataType: "json",
		   cache: false,
		   success: function(result){	
			 $('#loader_edit_password').hide();
		     $('#password').html(result.html);
		     if(result.state)
		    	 flash_message(result.flash);
		     else
		    	 flash_error_message(result.flash);
		   }
	 });
}

function postWall(priv){
	$('.loader_wall').show();
	$.ajax({
		   url: "/wall/update?p="+priv,
		   data: $('#wallform').serialize(),
		   dataType: "json",
		   cache: false,
		   success: function(result){	
			 $('.loader_wall').hide();
		     $('#wallform_div').html(result.html);
		     if(result.state){
		    	 //flash_message(result.flash);
		    	 $('#wall_posts').prepend(result.wall_post);
		    	 $('#feeds').prepend(result.wall_post);
		    	 $('#wall_post_post').val('');
		     }
		     else
		    	 flash_error_message(result.flash);
		   }
	 });
}
function saveWallAlbum(){
    set_loader($('#thepictureform div div#album span'));
    $.ajax({
           url: '/frontend_dev.php/media/saveWallAlbum',
           data: $('#thepictureform').serialize(),
           type: "POST",
           dataType: "json",
           cache: false,
           success: function(result){   
             if(result.state){               
                 $('#feeds').prepend(result.feed);
                unset_loader($('#thepictureform div div#album span'));
                $('#thepictureform').hide();
                $('#thevideoform').hide();
                $('#thevideoform input[type=text]').val('');
                 //window.location = result.url;
             }
             else
                 flash_error_message(result.flash);
           }
     });
}
function saveWallVideo(){
    $('.loader_wall').show();
    $.ajax({
           url: $('#thevideoform').attr('action'),
           data: $('#thevideoform').serialize(),
           type: "POST",
           dataType: "json",
           cache: false,
           success: function(result){   
             if(result.state){               
                 $('.loader_wall').hide();
                 $('#feeds').prepend(result.feed);
                 //window.location = result.url;
             }
             else
                 flash_error_message(result.flash);
           }
     });
}

function follow(el, table, id, value, update_home){
	set_loader($(el));
	$.ajax({
		   url: "/follow/update",
		   data: {table:table, id:id, value:value, update_home: update_home},
		   dataType: "json",
		   cache: false,
		   success: function(result){		     
		     flash_message(result.flash);
		     	$(el).hide();
		     	$('#follow_'+table+'_'+id).append(result.html);
		     	if(update_home){
                 
		     		$('#recentlyFollowed'+update_home).html(result.recentlyFollowed);
		     		$('#feeds').html(result.feeds);
		     	}
		     
		   }
	 });
}

function showCommentaryForm(table, id){
	$('.write_comment').show();
	$('.commentary_form').remove();
	$('#write_comment_'+id).hide();
	$.ajax({
		   url: "/commentary/form",
		   data: {table:table, id:id},
		   //dataType: "json",
		   cache: false,
		   success: function(result){    
		   
		     $('#commentaryform_div_'+id).append(result);
		     $('#commentaries_'+id).slideToggle();
		     
		     $('textarea').css('overflow','hidden');
		 	 $('textarea').css('height','auto');
		 	 $('textarea').autoGrow();
		   }
	 });
}
function postCommentary(){
	$('#loader_commentary').show();
	$.ajax({
		   url: "/commentary/update",
		   data: $('#commentaryform').serialize(),
		   dataType: "json",
		   cache: false,
		   success: function(result){	
			 $('#loader_commentary').hide();
		     $('#commentaryform_div_'+result.id).html(result.html);
		     if(result.state){
		    	 flash_message(result.flash);
		    	 $('#commentaries_'+result.id).append(result.commentary);
		     }
		     else
		    	 flash_error_message(result.flash);
		   }
	 });
}


//Private variables
var colsDefault = 2;
var rowsDefault = 0;
//var rowsCounter = 0;

//Private functions
function setDefaultValues(txtArea)
{
	colsDefault = txtArea.cols;
	rowsDefault = txtArea.rows;
	//rowsCounter = document.getElementById("rowsCounter");
}

function bindEvents(txtArea)
{
	txtArea.onkeyup = function() {
		grow(txtArea);
	}
}

//Helper functions
function grow(txtArea)
{
    var linesCount = 0;
    var lines = txtArea.value.split('\n');

    for (var i=lines.length-1; i>=0; --i)
    {
        linesCount += Math.floor((lines[i].length / colsDefault) + 1);
    }

    if (linesCount >= rowsDefault)
        txtArea.rows = linesCount + 1;
	else
        txtArea.rows = rowsDefault;
	//rowsCounter.innerHTML = linesCount + " | " + txtArea.rows;
}

//Public Method
jQuery.fn.autoGrow = function(){
	return this.each(function(){
		setDefaultValues(this);
		bindEvents(this);
	});
};
$(document).ready(function(){
	$('textarea').css('overflow','hidden');
	$('textarea').css('height','auto');
	$('textarea').autoGrow();
});

function searchTeams(page){
	if(!page)
		page = 1;
	$('#team_search_loader').show();
	$.ajax({
		   url: "/team/search",
		   data: $('#team_invite_form').serialize()+'&page='+page,
		   dataType: "json",
		   cache: false,
		   success: function(result){	
			 $('#team_search_loader').hide();
			 
		     $('#result_teams').html(result.html);
             if(result.form){
                $('#newSimple').html(result.form);
                $('#team_team').bt({positions:['left'], contentSelector: $('#create-team-tooltip')}).btOn();
             }
             else
                $('#newSimple').html('');
             $('.invite-helper').bt({positions:['left']}).btOn();
             
		   }
	 });
}
function inviteTeam(e, id){
	
	var championship_id = $('#championship_id').val();
	if($('#iteam_'+id).length<=0){ //invite
		$('#team_'+id).removeClass('allgrey');
		$('#team_'+id).addClass('allblack');
		$('#invited_teams').append($('#team_'+id).clone().attr('id','iteam_'+id));
        
        $('#team_'+id+' .link-invited').attr('invited', 1);
        $('#iteam_'+id+' .link-invited').attr('invited', 1);
		$.ajax({
			   url: "/championship/inviteTeam/"+id+"/"+championship_id+"?_="+Math.floor(Math.random()*10001),
               dataType: "json",
               success: function(result){

                   $("#summary").html(result.summary);
                   if(result.tabs){
                       $('.tabs').replaceWith(result.tabs);
                   }
               }
		});
		$('#team_'+id+" .button_invite").html($('#team_'+id+" .button_invite").attr('no'));
		$('#iteam_'+id+" .button_invite").html($('#team_'+id+" .button_invite").attr('no'));
        
	}
	else{ //uninvite
		$('#team_'+id).removeClass('allblack');
		$('#team_'+id).addClass('allgrey');
        $('#team_'+id+" .link-invited").removeClass('black-capsule').addClass('green-capsule')
		$('#iteam_'+id).remove();
		$.ajax({
			   url: "/championship/uninviteTeam/"+id+"/"+championship_id+"?_="+Math.floor(Math.random()*10001),
               dataType: "json",
               success: function(result){
                   $("#summary").html(result.summary);
                   if(result.tabs){
                       $('.tabs').replaceWith(result.tabs);
                   }
               }
		});
		$('#team_'+id+" .button_invite").html($('#team_'+id+" .button_invite").attr('yes'));
		$('#team_'+id+' .link-invited').attr('invited', 0);
		
		
	}
	if (!e) var e = window.event;
	    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();

}
function playersTeamChampionship(e, championship_id, id){
	
	$( "#roster_dialog" ).dialog({
		height: 400,
		width:700,
		modal: true
	});
	$( "#roster_dialog" ).html('Loading...');
	$.ajax({
		   url: "/championship/roster/"+id+"/"+championship_id+"?_="+Math.floor(Math.random()*10001),
		   success: function(result){	
			   $( "#roster_dialog" ).html(result);
		   }
	});
		
	if (!e) var e = window.event;
	    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();

}
function changeSlot(sel, slot_id){
	//deasignar slot actual
	
	var team_id = $(sel).val();
	/*
	$.each($('div.boxSlot.team'+team_id),function(){
		var box = $(this);
		box.find('.team_select_select').val("");
		box.removeClass('team'+team_id);
		box.find('span.team_name').html('Free Slot');
		box.find('img:first').attr('src','/uploads/teams/default.png');
		$.get('/frontend_dev.php/championship/deassignTeamSlot/'+team_id+'/'+box.find('input').val(),[],function(data){ });
	});
	*/
	
	$.get('/frontend_dev.php/championship/assignTeamSlotJson?team_id='+team_id+'&slot_id='+slot_id,[],function(data){
		//console.log(team_id);
		element = $(data.slot_box);
		$('div.boxSlot.plain.boxSlotGroupped'+slot_id).html(element);
		$('#team_select_'+slot_id).val(data.team);
		$('div.boxSlot.slot'+slot_id+' .team_select').val(data.team);
		$('#team_select_'+data.prev_slot).val(data.prev_team);
		$('div.boxSlot.slot'+data.prev_slot+' .team_select').val(data.prev_team);
		$('div.boxSlot.slot'+slot_id+' img').attr('src',data.team_logo);
		$('div.boxSlot.slot'+prev_slot+' img').attr('src',data.prev_team_logo);
	});
	
	return;

}

function createSimpleTeam(){
	$.ajax({
		   url: $('#create_simple_team').attr('action'),
		   data: $('#create_simple_team').serialize(),
		   dataType: "json",
		   type: "POST",
		   cache: false,
		   success: function(result){	
		     if(result.state){		    	 
	    	 	 flash_message(result.flash);
	    	 	$('#invited_teams').append(result.team_box);


                 $("#summary").html(result.summary);
                 if(result.tabs){
                    $('.tabs').replaceWith(result.tabs);
                 }

		     }
		     else
		    	 flash_error_message(result.flash);
		   }
	 });
}

function saveAlbum(){
	$.ajax({
		   url: '/frontend_dev.php/media/saveAlbum',
		   data: $('#theform').serialize(),
		   type: "POST",
		   dataType: "json",
		   cache: false,
		   success: function(result){	
		     if(result.state){		    	 
	    	 	 flash_message(result.flash);
	    	 	 window.location = result.url;
		     }
		     else
		    	 flash_error_message(result.flash);
		   }
	 });
}

function changeAttendance(el, team_player_id, match_id){
	$.ajax({
		   url: '/frontend_dev.php/match/changeAttendance',
		   data: {team_player_id: team_player_id, match_id: match_id, value:$(el).is(':checked')?1:0},
		   type: "POST",
		   dataType: "json",
		   cache: false,
		   success: function(result){	
		     if(result.state){		    	 
	    	 	 flash_message(result.flash);	    	 	 
		     }
		     else
		    	 flash_error_message(result.flash);
		   }
	 });
}

function uploadPhotos(event, a){
	$('#media_album').val("");
	$('#dialog-upload').show();
	/*$( "#dialog-upload" ).dialog({
		height: 240,
		width: 500,
		modal: true
	});*/
	/*$.ajax({
		   url: $(a).attr('href'),
		   
		   type: "POST",
		   
		   cache: false,
		   success: function(result){	
			 

		     $('#dialog-upload').html(result);
		   }
	 });*/
}

function saveServices(){
	$('#services-form-saving').show();
	$('#services-form-submit').hide();
	$.ajax({
		   url: $('#services_form').attr('action'),
		   data: $('#services_form').serialize(),
		   type: "POST",
		   dataType: "json",
		   cache: false,
		   success: function(result){
			 $('#services-form-saving').hide();
			 $('#services-form-submit').show();
		     if(result.state){		    	 
	    	 	 flash_message(result.flash);	    	 	 
		     }
		     else
		    	 flash_error_message(result.flash);
		   }
	 });
}


function anfaMoreInfo(id){
	$('.anfa-home-masinfo').hide();
	$('#anfa-home-moreinfo').hide();
	if($('#'+id+'-info').length>0){
		$('#'+id+'-info').show();
		$('#anfa-home-moreinfo').show('blind', 200);
	}
}
function autoAssignTeamsToSlots(event, phase_id){
    if(event.preventDefault) event.preventDefault();
	else event.returnValue = false;
	var target = $(event.target);
    $('#automatic-assign-teams-loader').show();
    $(target).hide();
	$.ajax({
		   url: target.attr('href'),
		   cache: false,
		   success: function(result){
                if(result.state){
                    loadFixture(null, $('#link-phase-'+phase_id)[0]);
                }
		   }
	 });
}
function formationTooltip(id){
	$("#formation_tooltip_"+id).bt($('#positions').html(), {
		trigger: 'click', 
		positions: 'bottom',
		preBuild: function(){
			$('.position-team_player-id').val(id);
		}
	});
}
function setFormationPosition(el){
	var id = $('.position-team_player-id').val();
	$('#formation_position_'+id).removeClass().addClass('iconset player-position position position'+$(el).attr('position')); 
	$('#formation_tooltip_'+id).btOff();
	$('#position_'+id).val($(el).attr('position'));
}
function loadFormation(el, match_id){
	$('#formation_loader').show();
	$.ajax({
		   url: '/frontend_dev.php/formation/load',
		   data: 'id='+el.val()+'&match_id='+match_id,
		   cache: false,
		   dataType: "json",
		   success: function(result){
			 $('#sfield-div').html(result.field);
			 $('#steam-div').html(result.team);
			 $('#formation_loader').hide();
		   }
	 });
}

function rate(id, match_id){
	$('#rating_loader_'+id).show();
	$('#rating_button_'+id).hide();
	var inputs = $('#rating_form_'+id+' input');
	var rating = 0;
	inputs.each(function(){
		if(this.checked)
			rating = this.value;
	});
	if(!match_id)
		match_id='';
	$.ajax({
		   url: '/frontend_dev.php/rating/rate',
		   data: 'id='+id+'&rating='+rating+'&match_id='+match_id,
		   cache: false,
		   dataType: "json",
		   success: function(result){
				$('#rating_form_'+id).replaceWith(result.html);
		   }
	 });
}

function openNotifications()
{
	$('#notifications_link').removeClass('new');
	$('#notifications_link').html('0');
	$.ajax({
		   url: "/notification/clear",
		   data: "",
		   success: function(html){
			 
		   }
	 });
}
function silentFacebookLogin(access_token){
	$.ajax({
		   url: "/account/silentFacebookLogin",
		   data: {access_token: access_token},
		   success: function(html){
			
		   }
	 });
}
function silentFacebookLogout(){
	$.ajax({
		   url: "/account/silentFacebookLogout",
		   data: {},
		   success: function(html){
			
		   }
	 });
}

function attendance(el, table, item_id, value){
	set_loader($(el));
	$.ajax({
		   url: "/attendance/update",
		   data: {table:table, item_id:item_id, value:value},
		   dataType: "json",
		   cache: false,
		   success: function(result){		     
			    unset_loader($(el));
			    
			    $('#attendance_'+table+'_'+item_id).replaceWith(result.html);
		     	$('#attendance_'+table+'_'+item_id+'_'+result.user_id).html(result.text);
		     
		   }
	 });
}
function scoreModifier(phase_id, team_id, value){
    $('#sm_'+phase_id+'_'+team_id).hide();
    $('#sm_'+phase_id+'_'+team_id+'_loader').show();
    $.ajax({
           url: "/phase/scoreModifier",
           data: {phase_id:phase_id, team_id:team_id, value:value},
           dataType: "json",
           cache: false,
           success: function(result){    
               $('#sm_'+phase_id+'_'+team_id).html(result.sm);
               $('#score_'+phase_id+'_'+team_id).html(result.score);
               $('#sm_'+phase_id+'_'+team_id).show();
               $('#sm_'+phase_id+'_'+team_id+'_loader').hide();               
           }
     });
}

function deleteFeed(id){
	/*
	if(confirm('Esta seguro de borrar este feed?')){
		$('#feed_'+id).effect( 'explode', {}, 500,function(){$(this).remove() } );
		$('#feed_'+id).remove();
		$.ajax({
			   url: "/frontend_dev.php/feed/delete",
			   data: "id="+id,
			   success: function(html){
				 
			    
			   }
		 });
	}*/
}
/*
function getRecentlyFollowedChampionships(){
	$.ajax({
		   url: '/user/recentlyFollowedChampionships',		   
		   type: "POST",
		   dataType: "json",
		   cache: false,
		   success: function(result){
			 $('#services-form-saving').hide();
			 $('#services-form-submit').show();
		     if(result.state){		    	 
	    	 	 flash_message(result.flash);	    	 	 
		     }
		     else
		    	 flash_error_message(result.flash);
		   }
	 });
}*/
