function pagefunctions(){
	var keyuser = localStorage.getItem('keyuser');
	
	$.ajax({
       type: "POST",
       crossDomain: true,
       url: "http://m2s.es/app/api/states.php",
       data: {"s": "friends", "key": keyuser},
       cache: false,
       dataType: 'json',
       success: function(result) {
         if (result.states) {
            for (var i = 0; i < result.states.length; i++) {
              id = result.states[i].id;
              iduser = result.states[i].iduser;
              username = result.states[i].username;
              imagepr = result.states[i].imagepr;
              if(imagepr == null){
                imagepr = 'images/icon-user-default.png';
              }
              message = result.states[i].message;
              date = result.states[i].date;
              message = linkscom(message);
              locationgg = result.states[i].location;
              if (locationgg.longitud != null) {
                  longitud = locationgg.longitud;
                  locatisn = '<iframe marginheight="0" marginwidth="0" src="http://maps.google.com/maps?client=safari&ll=' + locationgg.latitude + ',' + longitud + '&z=14&output=embed" frameborder="0" scrolling="no" style="height: 24%;max-height: 200px;max-width: 700px;width: 100%;"></iframe>';
              }else{
                  locatisn = '';
              }

              $('#list-friends').append("<li class='li-chats state-"+id+"' id='"+date+"' style='display:none'><a href='profile.html?id="+iduser+"'><img src='"+imagepr+"' class='img'/></a><div class='right-info'></div><div class='right-p'><div class='stateci'><span class='name'>"+username+"</span><p class='state-text'>"+message+"</p>"+ locatisn + " <font class='date'>"+convert(date)+"</font></div></div></li>");
                if(username == localStorage.getItem('user')){
	              heigcv = $('.state-'+id).height();
                  $('.state-'+id).prepend('<a href="javascript:deletestate(' + id + ')" class="deletered trash" style="display:none;height:'+heigcv+'"><span class="icon trash"></span></a>');
                      $$('.state-'+id).swipeLeft(function() {
	                      		if($(".trash").is(":visible")){
		                      		$(".trash").css('display', 'none');
		                      		$(".li-chats").removeAttr('style');
	                      		}
                                $(".trash", this).css('display', 'block');
                                $("span.trash", this).css('line-height', heigcv+'px');
                                $(this).css('left', '-30px');
                                $(this).css('position', 'relative');
                                console.log('swipe!'+id);
                      });
					  $$('.state-'+id).swipeRight(function() {
                                $(".trash", this).css('display', 'none');
                                $(this).removeAttr('style');
                      });
                }  
            }
         }
         groupsd();
       },
       error: function(XMLHttpRequest, textStatus, errorThrown) {
         console.error(textStatus + ' ' + XMLHttpRequest.status);
       }
  });
}

function groupsd(){
  $.ajax({
       type: "POST",
       crossDomain: true,
       url: "http://m2s.es/app/api/states.php",
       data: {"s": "groups", "key": keyuser},
       cache: false,
       dataType: 'json',
       success: function(result) {
          if (result.states) {
              for (var i = 0; i < result.states.length; i++) {
                  id = result.states[i].id;
                  idgroup = result.states[i].idgroup;
                  namegr = result.states[i].username;
                  imagepr = result.states[i].imagepr;
                  officiald = result.states[i].official;
                  message = result.states[i].message;
                  date = result.states[i].date;
                  meadmin = result.states[i].meadmin;
                  message = linkscom(message);
                  local = result.states[i].location;
                  var imageprr = '';
                  if(imagepr){
                    imageprr += "<img src='"+imagepr+"' class='img'/>";
                  }else{
                    var namesplit = namegr.split(' ');
                    abv1 = namesplit[0].charAt(0);
                    if (namesplit[1]) {
                        abv2 = namesplit[1].charAt(0);
                        abv = abv1 + abv2;
                    }else{
                        abv = abv1;
                    }
                    imageprr += '<div class="img" style="background-color:#777"><p unselectable="on" onselectstart="return false;" onmousedown="return false;">' + abv + '</p></div>';
                  }
                  if(officiald == 'yes'){
                    offcisl = '<span class=" icon ok"></span>';
                  }else{
	                offcisl = '';
                  }
                  if (local.longitud != null) {
                    longitud = local.longitud;
                    locatisn = '<iframe marginheight="0" marginwidth="0" src="http://maps.google.com/maps?client=safari&ll=' + local.latitude + ',' + longitud + '&z=14&output=embed" frameborder="0" scrolling="no" style="height: 24%;max-height: 200px;max-width: 700px;width: 100%;"></iframe>';
                  }else{
                    locatisn = '';
                  }
                  $('#list-friends').append("<li class='li-chats stategr-"+id+"' id='"+date+"' style='display:none'><a href='profilegr.html?id="+idgroup+"'>"+imageprr+"</a><div class='right-info'></div><div class='right-p'><div class='stateci'><span class='name'>"+namegr+offcisl+"</span><p class='state-text'>"+message+"</p>"+ locatisn + " <font class='date'>"+convert(date)+"</font></div></div></li>");
                  if(meadmin == 'yes'){
	                  heigcv = $('.stategr-'+id).height();
                  $('.stategr-'+id).prepend('<a href="javascript:deletestategr(' + id + ')" class="deletered trash" style="display:none;height:'+heigcv+'"><span class="icon trash"></span></a>');
                      $$('.stategr-'+id).swipeLeft(function() {
	                      		if($(".trash").is(":visible")){
		                      		$(".trash").css('display', 'none');
		                      		$(".li-chats").removeAttr('style');
	                      		}
                                $(".trash", this).css('display', 'block');
                                $("span.trash", this).css('line-height', heigcv+'px');
                                $(this).css('left', '-30px');
                                $(this).css('position', 'relative');
                                console.log('swipe!'+id);
                      });
					  $$('.stategr-'+id).swipeRight(function() {
                                $(".trash", this).css('display', 'none');
                                $(this).removeAttr('style');
                      });
	              }
	         }
	     }
	     
	     $('#loading-user').hide();
		 if($('.li-chats').length == 0){
            $('#list-friends').append("<div class='no-friends' id='nostates'><h4>"+Language.nostatesfriends+"</h4></div>");
         }else{
            tinysort('.li-chats',{attr:'id',order:'desc'});
            $('.li-chats').show();
         }
	   },
       error: function(XMLHttpRequest, textStatus, errorThrown) {
         console.error(textStatus + ' ' + XMLHttpRequest.status);
       }
  });
} 

function deletestate(id){
   $.ajax({
       type: "POST",
       crossDomain: true,
       url: "http://m2s.es/app/api/connect/delete-state.php",
       data: {"id": id, "key": keyuser},
       cache: false,
       dataType: 'json',
       success: function(result) {
         if(result.mensaje == 'ok'){
            $('.state-'+id).remove();
         }
       },
       error: function(XMLHttpRequest, textStatus, errorThrown) {
         console.error(textStatus + ' ' + XMLHttpRequest.status);
       }
   });
}


function deletestategr(id){
   $.ajax({
       type: "POST",
       crossDomain: true,
       url: "http://m2s.es/app/api/connect/delete-state-gr.php",
       data: {"id": id, "key": keyuser},
       cache: false,
       dataType: 'json',
       success: function(data) {
         if(data.mensaje == 'ok'){
            $('.stategr-'+id).remove();
         }else{
          console.log('Error: '+data.mensaje);
         }
       },
       error: function(XMLHttpRequest, textStatus, errorThrown) {
         console.error(textStatus + ' ' + XMLHttpRequest.status);
       }
   });
}
        
function showrittestate(){
    if(!$('.writestate').is(":visible")){
        $('.writestate').show();
    }else{
        $('.writestate').hide();
    }
}

$('.moreiss').click(function(){
   $('.share-moreapp').show();
})

$('.modal-share span.remove').click(function(){
   $('.share-moreapp').hide();
})

$('.optlink#stickerss').click(function(){
   var slec = $('.optlink.sel').attr('id');
   $('.optlink.sel').removeClass('sel');
   $('.optlink#stickerss').addClass('sel');
   $('.'+slec).hide();
   $('.stickerss').show();
})

$('.optlink#imagest').click(function(){
   var slec = $('.optlink.sel').attr('id');
   $('.optlink.sel').removeClass('sel');
   $('.optlink#imagest').addClass('sel');
   $('.'+slec).hide();
   $('.imagest').show();
})

$('.optlink#locastdfg').click(function(){
   var slec = $('.optlink.sel').attr('id');
   $('.optlink.sel').removeClass('sel');
   $('.optlink#locastdfg').addClass('sel');
   $('.'+slec).hide();
   $('.locastdfg').show();
})

$('.bargroup-emo span').click(function(){
  name = $(this).attr('class');
  $('.icon-group').hide();
  $('.icon-group#'+name).show();
})

$('#file-input').change(function(e) {
  var file = e.target.files[0],
    imageType = /image.*/;

  if (!file.type.match(imageType))
    return;

  var reader = new FileReader();
  reader.onload = fileOnload;
  reader.readAsDataURL(file);

});

function fileOnload(e) {
  var $img = $('<img>', {
    src: e.target.result
  });
  var canvas = $('#canvas')[0];
  $('#file-input').val('');
  $img.load(function() {
    canvas.width = this.width;
    canvas.height = this.height;
    var context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(this, 0, 0, this.width, this.height);
  });
  $('#upload-imge').show();
  $('#share-mre').hide();
  $('.selct-shareop').hide();
  $('.sections-share').hide();
  $('.imageuplo').show();
}

$('#upload-image').click(function() {
    var canvas = document.getElementById("canvas");
    var url = canvas.toDataURL("image/png", 1.0);
    url = url.replace('data:image/png;base64,', '');
    console.log(url);
    $.ajax({
      url: 'https://api.imgur.com/3/image',
      method: 'POST',
      headers: {
        Authorization: 'Client-ID def4c03828b22c2',
        Accept: 'application/json'
      },
      data: {
        image: url,
        type: 'base64'
      },
      success: function(result) {
        var link = result.data.link;
        $('textarea').val($('textarea').val() + ' ' + link);
        $('#share-mre').show();
        $('.selct-shareop').show();
        $('.sections-share').show();
        $('.imageuplo').hide();
        $('.share-moreapp').hide();
        $('#upload-imge').hide();
      }
    });
});

$('#cancel-upl-image').click(function() {
   $('#upload-imge').hide();
   $('#share-mre').show();
   $('.selct-shareop').show();
   $('.sections-share').show();
   $('.imageuplo').hide();
   $('#upload-imge').hide();
})

$('.sendyh').click(function(){
    sendmsm();
})

$('#btn-location').click(function() {
    if ($('#btn-location.btn-info').length != '0') {
      if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(function(position) {
           console.log('Loading location...');
           var latitud = position.coords.latitude;
           var longitud = position.coords.longitude;
           var latlong = latitud + ' ' + longitud;
           console.log('Location:' + latlong);
           $('.writestate').append(
             $(document.createElement("input")).attr("value", latlong).attr('name', 'map').attr('type', 'hidden').attr('class', 'map')
           );
           var mapht = '<iframe marginheight="0" marginwidth="0" src="http://maps.google.com/maps?client=safari&ll=' + latitud + ',' + longitud + '&z=14&output=embed" frameborder="0" scrolling="no" style="height: 50%;margin-top: 10px;max-height: 200px;max-width: 700px;width: 100%;" id="map-html"></iframe>';
           $('#location').append(mapht);
           $('#btn-location').removeAttr("disabled");
           $('#btn-location').html(Language.removelocation);
           $('#btn-location').removeClass('btn-info');
           $('#btn-location').addClass('btn-danger');
        }, function(error) {
                alert('Error occurred. Error code: ' + error.code);         
            },{timeout:5000});
      }else{
        alert("Your browser doesn't the location API");
      }
      $('#btn-location').attr('disabled', 'disabled');
      $('#btn-location').html(Language.locationloading);
    } else {
      $('#btn-location').html(Language.sharelocation);
      $('#btn-location').removeClass('btn-danger');
      $('#btn-location').addClass('btn-info');
      $('#map-html').remove();
      $('input.map').remove();
    }
});

function poststick(text) {
  $('.share-moreapp').hide();
  sendstate('<div class="'+text+'"></div>', '');
}

function sendmsm() {
  var txtvalue = document.getElementsByName('txt')[0].value;
  if (document.getElementsByName('map')[0]) {
    var mapv = document.getElementsByName('map')[0].value;
  } else {
    var mapv = "";
  }
  sendstate(txtvalue, mapv);
}

function sendstate(text, map){
   $.ajax({
      type: "POST",
      crossDomain: true,
      url: "http://m2s.es/app/api/connect/write-state.php",
      data: {"txt": text, "map": map, "key": keyuser},
      cache: false,
      dataType: 'json',
      beforeSend: function() {
        console.log('Connecting...');
      },
      success: function(writers) {
        if(writers.mensaje == 'ok'){
          document.location.href= 'states.html';
        }
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        console.error(textStatus + ' ' + XMLHttpRequest.status);
        errormod(Language.errorpetitionm2s);
      }
   })
}
