refresh_group_list=function() {
  grouplist=$('#group-choice');
  $('a.group-choice').each(function(idx,a) {
    $(a).parent().remove();
  });

  if (groups.count()==0) {
    grouplist.prepend('<li><a class="group-choice">Aucune groupe</a></li>');
  }
  else { 
    groups.each(function(idx,group) {
      grouplist.prepend('<li><a class="group-choice" data-uuid="'+group.uuid+'">'+group.name+'</a></li>');
    });

    $('a.group-choice').each(function(idx,a) {
      $(a).bind('click',on_group_choice_click);
    });
  }
}


/****************
 * Add group
 ****************/

on_click_add_group_btn=function(e) {
  navbar_collapse_hide();
  $('#add_group_modal').modal('show');
}

on_show_add_group_modal=function(e) {
  $('#add_group_modal #add_group_name').focus();
}

on_valid_add_group_modal=function (e) {
  e.preventDefault();
  var name=$('#add_group_name').val();
  if (name=='') {
    alert('Vous devez saisir un nom !');
    return;
  }
  if (groups[name]!==undefined) {
    alert('Ce groupe exite déjà !');
    return;
  }
  var uuid=groups.newGroup(name);
  refresh_group_list();
  $('#add_group_modal').modal('hide');
  groups.save();
  view_group(groups[uuid]);
}

on_close_add_group_modal=function () {
  $('#add_group_modal form')[0].reset();
}

/****************
 * Nav bars
 ****************/
on_group_choice_click=function(e) {
  view_group(groups[$(e.target).data('uuid')]);
  navbar_collapse_hide();
}

navbar_collapse_hide=function() {
  if ($('#navbar-groupe-collapse').hasClass('in')) {
    $('#navbar-groupe-collapse').collapse('hide');
  }
}

bottom_navbar_collapse_hide=function() {
  if ($('#bottom-navbar-collapse-1').hasClass('in')) {
    $('#bottom-navbar-collapse-1').collapse('hide');
  }
}

/****************
 * Parts
 ****************/

view_part=function(part) {
  $('.part').each(function(idx,div) {
    $(div).css('display','none');
  });
  $(part).css('display','block');
}

view_home=function() {
  navbar_collapse_hide();
  if (user) {
    $('#view-home #title').html('Bonjour '+user.name);
  }
  else {
    $('#view-home #title').html('Bonjour');
  }
  if (groups.count()>0) {
    tbody=$('#view-home #mybalances tbody');
    tbody.html('');
    balances=groups.balances();
    var sum=0;
    for (g in balances) {
      if (jQuery.type(balances[g]['balance'][user.email])!='undefined') {
        if (balances[g]['balance'][user.email]['diff']<0) {
          sum+=balances[g]['balance'][user.email]['diff'];
          diff='<td class="negative">'+balances[g]['balance'][user.email]['diff'].toFixed(2)+'</td>';
        }
        else {
          value=balances[g]['balance'][user.email]['total']-balances[g]['min'];
          sum+=value;
          diff='<td class="positive">+'+value.toFixed(2)+' €</td>';
        }
      }
      else {
        diff=$('<td>&nbsp;</td>');
      }
      tbody.html(tbody.html()+'<tr><td><a class="group-link" data-uuid="'+g+'">'+balances[g].name+'</a></td>'+diff+'</tr>');
    }
    $('#view-home #mybalances a.group-link').bind('click',function(e) {
      g=$(e.target).data('uuid');
      if (jQuery.type(groups[g])!='undefined') {
        view_group(groups[g]);
      }
    });
    $('a.home_grp_cat_btn').each(function(idx,a) {
      $(a).bind('click',on_home_grp_cat_btn_click);
    });
    if (sum<0) {
      $('#view-home #mybalances #total-value').html('<span class="negative">'+sum.toFixed(2)+' €</span>');
    }
    else {
      $('#view-home #mybalances #total-value').html('<span class="positive">'+(sum==0?'':'+')+sum.toFixed(2)+' €</span>');
    }
    $('#view-home #mybalances').css('display','table');
  }
  else {
    $('#view-home #mybalances').css('display','none');
  }
  view_part('#view-home');
}

/****************
 * View group
 ****************/
view_group=function(group,contributor_email) {
  $('#view-group').data('uuid',group.uuid);
  $('#view-group .group-title:first').html(group.name);
  set_contributors(group,contributor_email);
  on_contributor_change();
  view_part('#view-group');
}

set_contributors=function(group,contributor_email) {
  $('#view-group #contributor option').remove();
  if(group.contributors.length==0) {
    $('#view-group #contributor').append('<option>Aucun participant</option>');
  }
  else {
    for (email in group.contributors) {
      if (email == contributor_email) {
        sel=' selected';
      }
      else {
        sel='';
      }
      $('#view-group #contributor').append('<option value="'+email+'"'+sel+'>'+group.contributors[email].name+'</option>');
    }
  }
}

on_contributor_change=function(e) {
	if ($('#group-navbar-collapse-1').hasClass('in')) {
		$('#group-navbar-collapse-1').collapse('hide');
	}
	$('#view-group #group-username').html($('#view-group #contributor option:selected').text());
	show_contributions(groups[$('#view-group').data('uuid')],$('#view-group #contributor').val());
	$('#nav-search-form input').val('');
}

_current_displayed_contributions=[];
_current_displayed_contributions_group=null;
show_contributions=function(group,contributor_email,contributions) {
  var tbody=$('#view-group #contributions tbody').first();
  tbody.html('');
  if (!contributions) {
    contributions=group.contributionsByContributorEmail(contributor_email);
  }
  _current_displayed_contributions=contributions;
  _current_displayed_contributions_group=group;

  show_more_contributions();
}

show_more_contributions=function(count) {
  if (!_current_displayed_contributions_group) return;
  var tbody=$('#view-group #contributions tbody').first();
   if (_current_displayed_contributions.length==0) {
    tbody.html('');
    tbody.append('<tr><td colspan=3>Aucune contributions</td></tr>');
  }
  else {
    var previous=0;
    if (tbody.children('tr').length>0) {
      previous=tbody.children('tr').length;
    }
    if (!count) count=20;
    for (var i=0; i<count; i++) {
      var idx=previous+i;
      if (!_current_displayed_contributions[idx]) break;
      var cat='';
      if (_current_displayed_contributions[idx].category && jQuery.type(_current_displayed_contributions_group.categories[_current_displayed_contributions[idx].category])) {
		cat='<br/><span class="category"><span class="cat-color" style="background-color: '+_current_displayed_contributions_group.categories[_current_displayed_contributions[idx].category]['color']+'"></span> '+_current_displayed_contributions_group.categories[_current_displayed_contributions[idx].category]['name']+"</span>";
	  }
      col_actions='<td><div class="btn-group" data-uuid="'+_current_displayed_contributions[idx].uuid+'"><button type="button" class="btn btn-default btn-sm contribution_edit_btn"><span class="glyphicon glyphicon-edit"></span></button><button type="button" class="btn btn-default btn-sm contribution_delete_btn"><span class="glyphicon glyphicon-trash"></span></button></div></td>';
      var tr=$('<tr><td>'+_current_displayed_contributions[idx].getTitle()+cat+'</td><td>'+_current_displayed_contributions[idx].cost.toFixed(2)+' €<br/><span class="date">'+moment(_current_displayed_contributions[idx].date).format('DD/MM/YYYY')+'</span></td>'+col_actions+'</tr>');

      tr.find('.contribution_delete_btn').bind('click',on_contribution_delete_btn_click);
      tr.find('.contribution_edit_btn').bind('click',on_contribution_edit_btn_click);

      tbody.append(tr);
    }
  } 
}

_view_group_scroll_lock=false;
on_view_group_scroll=function(event) {
  if (_view_group_scroll_lock) return;
  _view_group_scroll_lock=true;
  if ($('#view-group').css('display')=='block' && is_on_bottom()) {
    show_more_contributions(20);
  }
  _view_group_scroll_lock=false;
}

on_categories_group_btn_click=function(e) {
  group=groups[$('#view-group').data('uuid')];
  $('#view-group-categories').data('group-uuid',$('#view-group').data('uuid'));
  refresh_group_categories(group);
  bottom_navbar_collapse_hide();
  view_part('#view-group-categories');
}

refresh_group_categories=function(group) {
  ul=$('#view-group-categories ul');
  html="";
  for(cid in group.getSortedCategories()) {
    html+="<li data-uuid='"+cid+"'><span class='cat-color' style='background-color: "+group.categories[cid]['color']+"'></span> "+group.categories[cid]['name']+"</li>";
  }
  ul.html(html);
  $('#view-group-categories ul li').bind('click',on_categories_group_cat_click);
  
  $('#cats-chart').css('width',$(window).width()*0.9+'px');
  
  $.plot($('#cats-chart'),group.getCategoriesStats(),{
    'grid': {
        'hoverable': true
    }, 
    'legend': {
        'show': false,
    },
    'series': { 
        'pie': {
            'show': true,
            'innerRadius': 0.5,
            'radius': .8,
            'tilt': .5,
            'label': {
                'show': true,
                'formatter': function (label, series) {
return '<div class="cats-chart-label">' + label + '<br/><span>' +   
                            Math.round(series.percent) + '% - '+series.data[0][1].toFixed(2)+'€</span></div>';
                }
            }
        }
    }
});
}

on_categories_group_cat_click=function(e) {
  li=$(e.target);
  if (li.prop("tagName")!='LI') {
    return true;
  }
  cid=li.data('uuid');
  group=groups[$('#view-group-categories').data('group-uuid')];
  cat=group.categories[cid];
  li.html("<span class='cat-color' style='background-color: "+cat['color']+"'></span> "+
  "<input type='text' value=\""+cat.name+"\"/> "+
  "<button class='btn btn-default btn-xs cat_edit'><span class='glyphicon glyphicon-ok'></span></button>"+
  "<button class='btn btn-default btn-xs cat_delete'><span class='glyphicon glyphicon-trash'></span></button>");
  li.children('button.cat_edit').bind('click',{'li': li,'group': group,'cid': cid},on_categories_group_cat_edit_valid_btn_click);
  li.children('button.cat_delete').bind('click',{'li': li,'group': group,'cid': cid},on_categories_group_cat_delete_btn_click);
}

on_categories_group_cat_edit_valid_btn_click=function(e) {
  name=e.data.li.children('input:first').val();
  cat=e.data.group.categories[e.data.cid];
  e.data.group.updateCategory(e.data.cid,new Category(name,cat.color));
  groups.save();
  refresh_group_categories(e.data.group);
}

on_categories_group_cat_delete_btn_click=function(e) {
  e.data.group.deleteCategory(e.data.cid);
  groups.save();
  refresh_group_categories(e.data.group);
}

on_categories_go_back_group_btn_click=function(e) {
  view_group(groups[$('#view-group-categories').data('group-uuid')]);
}

on_categories_group_add_btn_click=function(e) {
  e.preventDefault();
  name=$('#add_category input').val();
  
  if (jQuery.type(name)!='string' || name=='') {
    return;
  }
  group_uuid=$('#view-group-categories').data('group-uuid');
  group=groups[group_uuid];
  
  if (group.getCategoryByName(name,true)) {
    alert('Cette catégorie existe déjà');
  }
  else {
    group.addCategory(new Category(name));
    $('#add_category input').val('');
    refresh_group_categories(group);
    $('#add_category input').focus();
  }
}

on_export_group_btn_click=function(e) {
  if (user) {
    group=$('#view-group').data('uuid');
    document.location=user.server+'/export2csv?email='+user.email+'&password='+user.password+'&group='+group;
  }
  else {
    alert('Vous devez être connecté à un serveur pour cela !');
  }
}

on_nav_search_form_submit=function(e) {
  e.preventDefault();
}

on_nav_search_form_input=function(e) {
  var ipt=$(e.target);
  var pattern=ipt.val();

  group=groups[$('#view-group').data('uuid')];
  contributor_email=$('#view-group #contributor').val();
 
  var found=group.searchContributions(pattern,contributor_email);
  show_contributions(group,null,found);
}


/*****************************
 * Trash
 *****************************/

on_trash_group_btn_click=function(e) {
  group=groups[$('#view-group').data('uuid')];
  contributor_email=$('#view-group #contributor').val();
  bottom_navbar_collapse_hide();
  view_group_trash(group,contributor_email);
}

on_go_back_group_btn_click=function(e) {
  group=groups[$('#view-group-trash').data('uuid')];
  contributor_email=$('#view-group-trash').data('contributor-email');
  view_group(group,contributor_email);
}

view_group_trash=function(group,contributor_email) {
  $('#view-group-trash').data('uuid',group.uuid);
  $('#view-group-trash').data('contributor-email',contributor_email);
  var tbody=$('#view-group-trash #trash tbody');
  tbody.html('');
  contributions=group.deletedContributionsByContributorEmail(contributor_email);
  contributions.reverse();
  if (contributions.length==0) {
    tbody.append('<tr><td colspan=3>Aucune contributions</td></tr>');
  }
  else {
    for (idx in contributions) {
      tbody.append('<tr data-uuid="'+contributions[idx].uuid+'"><td>'+contributions[idx].getTitle()+'</td><td>'+contributions[idx].cost.toFixed(2)+' €<br/><span class="date">'+moment(contributions[idx].date).format('DD/MM/YYYY')+'</span></td><td><button type="button" class="btn btn-default contribution_restore_btn"><span class="glyphicon glyphicon-share"></span></button></td></tr>');
    }
  }
  
  $('#view-group-trash .contribution_restore_btn').bind('click',on_contribution_restore_btn_click);
 
  view_part('#view-group-trash');
}

on_contribution_restore_btn_click=function(e) {
  var group=groups[$('#view-group-trash').data('uuid')];
  contribution_uuid=$(e.target).parents('tr').first().data('uuid');
  contribution=group.importContribution(group.deletedContributions[contribution_uuid]);
  myconfirm('Etes-vous sûre de vouloir restaurer la participation '+contribution.getTitle()+' de '+contribution.contributor.name+' ?',on_confirm_contribution_restore,null,{'group':group,'contribution_uuid':contribution_uuid, 'contribution': contribution} );
}

on_confirm_contribution_restore=function(data) {
  data.group.restoreContribution(data.contribution_uuid);
  groups.save();
  view_group(data.group,data.contribution.contributor.email);
}

on_trash_group_contributors_btn_click=function(e) {
  group=groups[$('#view-group').data('uuid')];
  view_group_trash_contributors(group);
}

on_go_back_group_trash_contributors_btn_click=function(e) {
  group=groups[$('#view-group-trash-contributors').data('uuid')];
  view_group(group);
}

view_group_trash_contributors=function(group) {
  $('#view-group-trash-contributors').data('uuid',group.uuid);
  var tbody=$('#view-group-trash-contributors #trash tbody');
  tbody.html('');
  contributors=group.getDeletedContributors();
  if (contributors.length==0) {
    tbody.append('<tr><td colspan=3>Aucun participant</td></tr>');
  }
  else {
    for (idx in contributors) {
      tbody.append('<tr data-email="'+contributors[idx].email+'"><td>'+contributors[idx].name+'</td><td><button type="button" class="btn btn-default contributor_restore_btn"><span class="glyphicon glyphicon-share"></span></button></td></tr>');
    }
  }

  $('#view-group-trash-contributors .contributor_restore_btn').bind('click',on_contributor_restore_btn_click);

  view_part('#view-group-trash-contributors');
}

on_contributor_restore_btn_click=function(e) {
  var group=groups[$('#view-group-trash-contributors').data('uuid')];
  contributor_email=$(e.target).parents('tr').first().data('email');
  contributor=group.importContributor(group.deletedContributors[contributor_email]);
  myconfirm('Etes-vous sûre de vouloir restaurer '+contributor.name+' ?',on_confirm_contributor_restore,null,{'group':group,'contributor_email':contributor_email, 'contributor': contributor} );
}

on_confirm_contributor_restore=function(data) {
  data.group.restoreContributor(data.contributor_email);
  groups.save();
  view_group(data.group,data.contributor_email);
}

/******************************
 * Add/Edit/remove contributor
 ******************************/
on_click_add_contributor_btn=function() {
  $('#add_contributor_modal').data('group-uuid',$('#view-group').data('uuid'))
  $('#add_contributor_modal h4').first().html('Ajouter un participant');
  $('#add_contributor_modal #add_contributor_submit').first().html('Ajouter');
  $('#add_contributor_modal').data('edit-id','-1');
  $('#add_contributor_modal #add_contributor_email').attr('disabled',false);
  $('#add_contributor_modal').modal('show');
}

on_show_add_contributor_modal=function(e) {
  $('#add_contributor_modal #add_contributor_name').focus();
}

validateEmail=function(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}

on_valid_add_contributor_modal=function(e) {
  e.preventDefault();
  var group=groups[$('#add_contributor_modal').data('group-uuid')];
  var name=$('#add_contributor_name').val();
  var edit_id=$('#add_contributor_modal').data('edit-id');
  if (name=='') {
    alert('Vous devez saisir un nom !');
    return;
  }
  var email=$('#add_contributor_email').val();
  if (email=='') {
    alert('Vous devez saisir un email !');
    return;
  }
  duplicate=group.contributorByEmail(email)
  if (duplicate!=undefined && edit_id=='-1') {
    alert('Un contributor utilise déjà cet email !');
    return;
  }
  if (!validateEmail(email)) {
    alert('Email invalide !');
    return;
  }
  if(edit_id=='-1') {
    group.addContributor(new Contributor(name,email));
  }
  else {
    group.replaceContributor(email,new Contributor(name,email));
  }
  set_contributors(group);
  $('#add_contributor_modal').modal('hide');
  groups.save();
  view_group(group,email);
}

on_close_add_contributor_modal=function () {
  $('#add_contributor_name').val('');
  $('#add_contributor_email').val('');
}

on_edit_contributor_btn_click=function(e) {
  var group=groups[$('#view-group').data('uuid')];
  $('#add_contributor_modal').data('group-uuid',group.uuid);
  contributor_email=$('#view-group #contributor').val();
  contributor=group.contributorByEmail(contributor_email);
  $('#add_contributor_modal').data('edit-id',contributor_email);
  $('#add_contributor_modal #add_contributor_name').val(contributor.name);
  $('#add_contributor_modal #add_contributor_email').val(contributor.email);
  $('#add_contributor_modal #add_contributor_email').attr('disabled',true);
  $('#add_contributor_modal h4').html('Editer un participant');
  $('#add_contributor_modal #add_contributor_submit').html('Valider');
  $('#add_contributor_modal').modal('show');
}

on_click_del_contributor_btn=function() {
  var group=groups[$('#view-group').data('uuid')];
  contributor=group.contributorByEmail($('#view-group #contributor').val());
  question='Voulez-vous vraiment supprimer '+contributor.name+' ?';
  myconfirm(question,on_confirm_del_contributor,null,contributor);
}

on_confirm_del_contributor=function(contributor) {
  var group=groups[$('#view-group').data('uuid')];
  group.removeContributor(contributor);
  view_group(group);
  groups.save();
}

/********************************
 * Add/edit/delete contribution
 ********************************/
last_selected_date=moment().format('DD/MM/YYYY');
on_show_add_contribution_modal=function(e) {
  $('#add_contribution_modal #add_contribution_contributor_email').html($('#view-group #contributor').html());
  $('#add_contribution_modal #add_contribution_contributor_email').val($('#view-group #contributor').val());
  gid=$('#add_contribution_modal').data('group-uuid');
  group=groups[gid];
  populate_add_contribution_categories(group);
  $('#add_contribution_modal #add_contribution_title').typeahead('destroy');
  $('#add_contribution_modal #add_contribution_title').typeahead({
    hint: true,
    highlight: true,
    minLength: 1
  },
  {
    name: 'titles',
    displayKey: 'value',
    source: group.findContributionByTitleMatches()
  });
}

populate_add_contribution_categories=function(group,select) {
  if (!group) {
    gid=$('#add_contribution_modal').data('group-uuid');
    group=groups[gid];
  }
  current_cat=$('#add_contribution_modal #add_contribution_category').val();
  cats="<option value=''>Non définie</option>";
  for (u in group.getSortedCategories()) {
	cats+="<option value='"+u+"'>"+group.categories[u]['name']+"</option>";
  }
  $('#add_contribution_modal #add_contribution_category').html(cats);
  if (select) {
    $('#add_contribution_modal #add_contribution_category').val(select);
  }
  else {
    $('#add_contribution_modal #add_contribution_category').val(current_cat);
  }
}

on_select_contribution_suggestion=function(event,choice,name) {
  if (jQuery.type(choice['category'])=='string') {
    populate_add_contribution_categories(null,choice['category']);
  }
}

on_click_add_contribution_btn=function() {
  $('#add_contribution_modal').data('group-uuid',$('#view-group').data('uuid'));
  $('#add_contribution_modal #edit_uuid').val('-1');
  $('#add_contribution_date').val(last_selected_date);
  $('#add_contribution_date').data('value',last_selected_date);
  $('#add_contribution_modal h4').html('Ajouter une contribution');
  $('#add_contribution_modal #add_contribution_submit').html('Ajouter');
  $('#add_contribution_modal').modal('show');
  $('#add_contribution_title').val('').focus();
}

on_valid_add_contribution_modal=function(e) {
  e.preventDefault();
  var group=groups[$('#add_contribution_modal').data('group-uuid')];
  var contributor_email=$('#add_contribution_contributor_email').val();
  var contributor=group.contributorByEmail(contributor_email);
  if (contributor==undefined) {
    alert('Participant inconu !');
    return;
  }
  var title=$('#add_contribution_title').val();
  if (title=='') {
    $('#add_contribution_title').focus();
    alert('Vous devez saisir un titre !');
    return;
  }
  var cost=$('#add_contribution_cost').val();
  if (cost=='') {
    $('#add_contribution_cost').focus();
    alert('Vous devez saisir un coût !');
    return;
  }
  else if(!RegExp('^[0-9]*((,|\.)[0-9]{1,2})*$').test(cost)) {
    $('#add_contribution_cost').focus();
    alert('Coût incorrect !');
    return;
  }
  cost=parseFloat(cost.replace(',','.'));
  
  var date=$('#add_contribution_date').val();
  date.replace(/ /g,'');
  if (date!='') {
    if(!RegExp('^[0-3][0-9]\/[0-1][0-9]\/[0-2][0-9][0-9][0-9]$').test(date)) {
      $('#add_contribution_date').focus();
      alert('Date incorrect !');
      return;
    }
    date=moment(date,'DD-MM-YYYY').toDate();
    if (jQuery.type(date)!='date') {
      alert('Date non-reconnu !');
      return;
    }
  }
  else {
    date=new Date();
  }
  last_selected_date=moment(date).format('DD/MM/YYYY');
  
  var cat=$('#add_contribution_category').val();
  if (cat != '' && !jQuery.type(group.categories[cat])) {
	alert('Category incorrect');
	return;
  }
  
  if($('#add_contribution_modal #edit_uuid').val()=='-1') {
    group.addContribution(new Contribution(contributor,cost,title,date,cat));
  }
  else {
    contribution_uuid=$('#add_contribution_modal #edit_uuid').val();
    group.updateContribution(contribution_uuid,new Contribution(contributor,cost,title,date,cat));
  }
  show_contributions(group,$('#view-group #contributor').val());
  $('#add_contribution_modal').modal('hide');
  $('#add_contribution_modal form')[0].reset();
  groups.save();
}

on_close_add_contribution_modal=function () {
  $('#add_contribution_modal form')[0].reset();
}

on_contribution_delete_btn_click=function(e) {
  var group=groups[$('#view-group').data('uuid')];
  contribution_uuid=$(e.target).parents('div').first().data('uuid');
  contribution=group.contributions[contribution_uuid];
  myconfirm('Etes-vous sûre de vouloir supprimer la participation '+contribution.getTitle()+' de '+contribution.contributor.name+' ?',on_confirm_contribution_delete,null,{'group':group,'contribution_uuid':contribution_uuid, 'contribution': contribution} );
}

on_confirm_contribution_delete=function(data) {
  data.group.deleteContribution(data.contribution_uuid);
  groups.save();
  on_contributor_change();
}

on_contribution_edit_btn_click=function(e) {
  var group=groups[$('#view-group').data('uuid')];
  $('#add_contribution_modal').data('group-uuid',$('#view-group').data('uuid'));
  $('#add_contribution_modal h4').first().html('Editer une contribution');
  $('#add_contribution_modal #add_contribution_submit').html('Valider');
  contribution_uuid=$(e.target).parents('div').first().data('uuid');
  contribution=group.contributions[contribution_uuid];
  $('#add_contribution_modal #add_contribution_contributor_email').val(contribution.contributor.email);
  $('#add_contribution_modal #add_contribution_title').val(contribution.getTitle());
  $('#add_contribution_modal #add_contribution_cost').val(contribution.cost);
  $('#add_contribution_modal #add_contribution_date').val(moment(contribution.date).format('DD/MM/YYYY'));
  $('#add_contribution_modal #add_contribution_date').data('value',moment(contribution.date).format('DD/MM/YYYY'));
  if (contribution.category) {
    populate_add_contribution_categories(group,contribution.category);
  }
  $('#add_contribution_modal #edit_uuid').val(contribution_uuid);
  $('#add_contribution_modal').modal('show');
}



/********************
 * Clear local data
 ********************/
clear_local_data=function() {
  navbar_collapse_hide();
  myconfirm('Etes-vous sûre de vouloir supprimer les données locales ?',on_confirm_clear_local_data);
}

on_confirm_clear_local_data=function(data) {
  delete localStorage.groups;
  location.reload();
}

/*********************
 * View balance
 *********************/

on_display_balance_btn_click=function(e) {
  group=groups[$('#view-group').data('uuid')];
  display_balance(group);
}

display_balance=function(group) {
  bal=group.balance();
  tbody=$('#display_balance_modal tbody').first();
  tbody.html('');
  for (c in bal['balance']) {
    if(bal['balance'][c]['diff']<0) {
      diff='<td class="negative">'+bal['balance'][c]['diff'].toFixed(2)+' €</td>';
    }
    else {
      diff='<td><span class="glyphicon glyphicon-thumbs-up"></span></td>';
    }
    tbody.append('<tr><td>'+bal['balance'][c]['name']+'</td><td>'+bal['balance'][c]['total'].toFixed(2)+' €</td>'+diff+'</tr>');
  }
  $('#display_balance_modal #total-value').html(bal.sum.toFixed(2)+' €');
  $('#display_balance_modal').modal('show');
}

/*********************
 * Remove group
 *********************/

on_remove_group_btn_click=function(e) {
  group=groups[$('#view-group').data('uuid')];
  bottom_navbar_collapse_hide();
  myconfirm('Etes-vous sûre de vouloir supprimer le group '+group.name+' ?',on_confirm_remove_group,null,group);
}

on_confirm_remove_group=function(group) {
  if(groups.removeGroup(group.uuid)) {
    groups.save();
    location.reload();
  }
  else {
    alert('Erreur en supprimant le groupe '+group.name+' :(');
  }
}

/********************
 * Login
 ********************/
on_close_login_modal=function(e) {
  $('#login_modal form')[0].reset();
}

sync_server=false;
on_valid_login_modal=function(e) {
  e.preventDefault();
  email=$('#login_modal #login_email').val();
  pass=$('#login_modal #login_pass').val();
  server=$('#login_modal #login_server').val();
  $('#login_modal').modal('hide');
  pleaseWaitShow();
  sync_server.login(server,email,pass,
    function(data) {
      localStorage.user=JSON.stringify({
        'name': data.name,
        'email': email,
        'password': pass,
        'server': server,
        'lastsync': null
      });
      pleaseWaitHide();
      logged_menu();
    },
    function(data) {
      pleaseWaitHide();
      if (jQuery.type(data) != 'object' && data.loginerror) {
        alert(data.loginerror);
      }
      else {
        console.log(data);
        alert('Erreur durant la connexion au serveur');
      }
    }
  );
}

on_click_go_to_subscribe_btn=function() {
  $('#login_modal').modal('hide');
  $('#subscribe_modal').modal('show');
}

/********************
 * Subscribe
 ********************/
on_close_subscribe_modal=function(e) {
  $('#subscribe_modal form')[0].reset();
}

sync_server=false;
on_valid_subscribe_modal=function(e) {
  e.preventDefault();
  email=$('#subscribe_modal #subscribe_email').val();
  name=$('#subscribe_modal #subscribe_name').val();
  pass=$('#subscribe_modal #subscribe_pass').val();
  server=$('#subscribe_modal #subscribe_server').val();
  $('#subscribe_modal').modal('hide');
  pleaseWaitShow();
  sync_server.subscribe(server,email,name,pass,
    function(data) {
      localStorage.user=JSON.stringify({
        'name': data.name,
        'email': data.email,
        'password': data.password,
        'server': server,
      });
      pleaseWaitHide();
      logged_menu();
      alert('Bienvenu '+data.name+' !');
    },
    function(data) {
      pleaseWaitHide();
      if (jQuery.type(data) == 'object' && jQuery.type(data.subscribeerror)!='undefined') {
        alert(data.subscribeerror);
      }
      else {
        console.log(data);
        alert('Erreur durant la connexion au serveur');
      }
    }
  );
}

/********************
 * Sync
 ********************/
on_click_sync_btn=function(e) {
  navbar_collapse_hide();
  if (user) {
    pleaseWaitShow();
    onsuccess=function(data) {
      console.log(data);
      if (data.groups) {
        groups.import(data.groups);
        groups.save();
        user.lastsync=new Date().getTime();
        localStorage.user=JSON.stringify(user);
        refresh_group_list();
        pleaseWaitHide();
        view_home();
        alert('Groupes synchronisés');
      }
      else {
        onerror(data);
      }
    }
    onerror=function(data) {
      pleaseWaitHide();
      console.log(data);
      if (jQuery.type(data['loginerror'])!='undefined') {
        alert(data['loginerror']);
      }
      else if (jQuery.type(data['syncerror'])!='undefined') {
        alert(data['syncerror']);
      }
      else {
        alert('Erreur durant la synchronisation :(');
      }
    }
    sync_server.sync(user.server, user.email, user.password, groups.export(),onsuccess,onerror);
  }
  else {
    alert("Vous devez vous connecter pour commencer");
    $('#login_modal').modal('show');
  }
}

/**************************
 * Export/Import all
 **************************/

on_export_all_btn_click=function(e) {
  e.preventDefault();
  navbar_collapse_hide();
  var blob=new Blob([JSON.stringify(groups.export(),null,2)],{type: 'text/plain'});
  var a=$('<a download="myco-export.json">download</a>');
  a.attr('href',window.URL.createObjectURL(blob));
  a.css('display','none');
  $('body').append(a);
  a.click();
  a.remove();
}

on_import_all_btn_click=function(e) {
  e.preventDefault();
  navbar_collapse_hide();
  myconfirm(
    "Voulez-vous vraiment inporter des données à partir d'un fichier externe ?<br/><strong>Important : cela écrasera l'ensemble des données actuellement présente dans l'application.</strong",
    function() {
      var input=$('<input type="file"/>');
      input.css('display','none');
      $('body').append(input);
      input.click();
      input.bind('change',{'input': input},function(e) {
        pleaseWaitShow();
        var file=input.prop('files')[0];
        if (file) {
          var reader = new FileReader();
          $(reader).bind('load',function(e) {
            try {
              var data=JSON.parse(e.target.result);
              if (jQuery.type(data)!='object') {
                alert("Fichier invalide !");
                pleaseWaitHide();
              }
              else {
                var backup=groups.export();
                try {
                  groups.import(data);
                  groups.save();
                  view_home();
                }
                catch(e) {
                  groups.import(backup);
                  alert("Une erreur est survenue durant l'importation des données.");
                }
              }
            }
            catch(e) {
              alert("Une erreur est survenue durant le parsing du contenu du fichier.");
            }
            pleaseWaitHide();
          });
          reader.readAsText(file);
        }
      });
  });
}

/*
 * User menu
 */
user=false;
logged_menu=function() {
  user=JSON.parse(localStorage.user);
  $('#user-name').html(user.name);
  $('#user-menu li').remove();
  menu=$('#user-menu');
  menu.html("<li><a id='myaccount_btn'>Mon compte</a></li>"+
  "<li><a id='sync_btn'>Synchroniser</a></li>" +
  "<li class='divider'></li>" +
  "<li><a id='logoff_btn'>Déconnexion</a></li>");
  $('#myaccount_btn').bind('click',on_click_myaccount_btn);
  $('#sync_btn').bind('click',on_click_sync_btn);
  $('#logoff_btn').bind('click',on_click_logoff_btn);
}

logged_out_menu=function() {
  user=false;
  $('#user-name').html('Connexion');
  $('#user-menu li').remove();
  menu=$('#user-menu');
  menu.html("<li><a id='login_btn'>Connexion</a></li>"+
	"<li><a id='subscribe_btn'>Inscription</a></li>");
  $('#login_btn').bind('click',on_click_login_btn);
  $('#subscribe_btn').bind('click',on_click_subscribe_btn);
}

on_click_myaccount_btn=function() {
  $('#myaccount_modal #myaccount_email').html(user.email);
  $('#myaccount_modal #myaccount_name').val(user.name);
  $('#myaccount_modal #myaccount_server').html(user.server);
  if (user.lastsync) {
    $('#myaccount_modal #myaccount_lastsync').html(moment(user.lastsync).format('DD/MM/YYYY HH:mm:ss'));
  }
  else {
    $('#myaccount_modal #myaccount_lastsync').html('Jamais synchronis&eacute;');
  }
  $('#myaccount_modal').modal('show');
}

on_click_login_btn=function() {
  $('#login_modal').modal('show');
}

on_click_subscribe_btn=function() {
  $('#subscribe_modal').modal('show');
}

on_click_logoff_btn=function() {
  delete localStorage.user;
  logged_out_menu();
}

is_on_bottom=function(){
  var totalHeight, currentScroll, visibleHeight;
  
  if (document.documentElement.scrollTop) {
    currentScroll = document.documentElement.scrollTop;
  }
  else {
    currentScroll = document.body.scrollTop;
  }
  
  totalHeight = document.body.offsetHeight;
  visibleHeight = document.documentElement.clientHeight;
  
  return (totalHeight <= currentScroll + visibleHeight );
}
  

/*******************
 * pleaseWaitDialog
 *******************/

pleaseWaitShow=function() {
  $('#please_wait_modal').modal('show');
}

pleaseWaitHide=function() {
  $('#please_wait_modal').modal('hide');
}

/**************************
 * Cache / Update
 *************************/

_checkForUpgrade=false;
onUpdateReady=function() {
  if (_checkForUpgrade) {
    pleaseWaitHide();
  }
  myconfirm(
    "Une nouvelle version de l'application est disponible. Voulez-vous lancer la mise à jour ?",
    onConfirmUpdate,null,{} 
  );
}

onConfirmUpdate=function() {
  window.applicationCache.swapCache();
  location.reload();  
}

updateApp = function() {
  navbar_collapse_hide();
  pleaseWaitShow();
  _checkForUpgrade=true;
  window.applicationCache.update();
}

onNoUpdate = function() {
  if (_checkForUpgrade) {
    pleaseWaitHide();
    _checkForUpgrade=false;
    alert('Aucune mise à jour disponible');
  }
}

/*********************
 * Activate
 *********************/
$( document ).ready( function() {
  pleaseWaitShow();
  if(typeof(Storage)!=="undefined"){
    groups=new GroupList();
    groups.loadFromLocalStorage();
    refresh_group_list();
    if (jQuery.type(localStorage.user)!='undefined') {
      logged_menu();
    }
    else {
      logged_out_menu();
    }
  }
  else {
    alert('Local storage not supported !');
    pleaseWaitHide();
    return;
  }
  sync_server=new SyncServer();

  $('#app-name').bind('click',view_home);

  $('#add_group_btn').bind('click',on_click_add_group_btn);
  $('#add_group_submit').bind('click',on_valid_add_group_modal);
  $("#add_group_modal").on('shown.bs.modal',on_show_add_group_modal);
  $("#add_group_modal").on('hidden.bs.modal',on_close_add_group_modal);
  $("#add_group_modal form").bind('submit',on_valid_add_group_modal);

  $('#clear_local_data').bind('click',clear_local_data);

  $('#login_modal').on('hidden.bs.modal',on_close_login_modal);
  $('#login_modal #login_submit').bind('click',on_valid_login_modal);
  $('#login_modal #go_to_subscribe_btn').bind('click',on_click_go_to_subscribe_btn);
  $('#login_modal form').bind('submit',on_valid_login_modal);

  $('#subscribe_modal').on('hidden.bs.modal',on_close_subscribe_modal);
  $('#subscribe_modal #subscribe_submit').bind('click',on_valid_subscribe_modal);
  $('#subscribe_modal form').bind('submit',on_valid_subscribe_modal);

  $('#view-group #contributor').bind('change',on_contributor_change);
  $(window).bind('scroll',on_view_group_scroll);

  $('#add_contributor_btn').bind('click',on_click_add_contributor_btn);
  $('#add_contributor_submit').bind('click',on_valid_add_contributor_modal);
  $("#add_contributor_modal").on('shown.bs.modal',on_show_add_contributor_modal);
  $("#add_contributor_modal").on('hidden.bs.modal',on_close_add_contributor_modal);
  $("#add_contributor_modal form").bind('submit',on_valid_add_contributor_modal);
  $("#add_contribution_date").pickadate({
    format: 'dd/mm/yyyy',
    firstDay: 1,
    container: $('body'),
    monthsFull: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'],
    weekdaysShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
    today: 'aujourd\'hui',
    clear: 'effacer',
    formatSubmit: 'yyyy/mm/dd'
  });

  $('#edit_contributor_btn').bind('click',on_edit_contributor_btn_click);
  $('#trash_contributor_btn').bind('click',on_trash_group_contributors_btn_click);
  $('#del_contributor_btn').bind('click',on_click_del_contributor_btn);

  $('#add_contribution_btn').bind('click',on_click_add_contribution_btn);
  $('#add_contribution_submit').bind('click',on_valid_add_contribution_modal);
  $("#add_contribution_modal").on('shown.bs.modal',on_show_add_contribution_modal);
  $("#add_contribution_modal").on('hidden.bs.modal',on_close_add_contribution_modal);
  $("#add_contribution_modal form").on('submit',on_valid_add_contribution_modal);
  $('#add_contribution_modal #add_contribution_title').on('typeahead:selected', on_select_contribution_suggestion);

  $("#display_balance_btn").bind('click',on_display_balance_btn_click);

  $("#view-group-trash #go-back-group").bind('click',on_go_back_group_btn_click);
  $("#view-group-trash-contributors #go-back-group").bind('click',on_go_back_group_trash_contributors_btn_click);

  $('#categories_group_btn').bind('click',on_categories_group_btn_click);
  $('#export_group_btn').bind('click',on_export_group_btn_click);
  $('#trash_group_btn').bind('click',on_trash_group_btn_click);
  $('#remove_group_btn').bind('click',on_remove_group_btn_click);
  $('#nav-search-form').bind('submit',on_nav_search_form_submit);
  $('#nav-search-form input').bind('input',on_nav_search_form_input);
  
  $('#view-group-categories span.input-group-addon').bind('click',on_categories_group_add_btn_click);
  $('#view-group-categories form').bind('submit',on_categories_group_add_btn_click);
  $("#view-group-categories button.go-back-group").bind('click',on_categories_go_back_group_btn_click);

  $('#export_all_btn').bind('click',on_export_all_btn_click);
  $('#import_all_btn').bind('click',on_import_all_btn_click);
  
  view_home();
  pleaseWaitHide();

  if (window.applicationCache.status==window.applicationCache.UNCACHED) {
    $('#update_app').parent().remove();
  }
  else {
    $('#update_app').bind('click',updateApp);
    window.applicationCache.addEventListener('updateready', onUpdateReady);
    window.applicationCache.addEventListener('noupdate', onNoUpdate);
    if(window.applicationCache.status === window.applicationCache.UPDATEREADY) {
      onUpdateReady();
    }
  }
} );
