var keyuser = localStorage.getItem('keyuser');


$('#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];
  $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);
  });
  $('.confirmimg').show();
  $('.squarecanvas').css('height',$('.squarecanvas').width())
  $('.changeimg').hide();
}

$('#confrimg').click(function(){
	var canvas = document.getElementById("canvas");
	var url = canvas.toDataURL("image/png", 1.0);
	$('.loadingimg').show();
	$('.confirmimg').hide();
	$('.changeimg').show();
	console.log(url);
		$.ajax({
      		type: "POST",
      		crossDomain: true,
      		url: "http://m2s.es/app/api/connect/editprofile.php",
      		data: {"imgeprofile": url, "key": keyuser},
      		cache: false,
      		dataType: 'json',
      		success: function(result) {
          		console.log(result.mensaje);
          		if(result.mensaje == 'ok'){
          			$('.loadingimg').hide();
          			$('.imguserdff').attr('src', url);
          			localStorage.setItem('imguse', url);
          		}else{
          			errormod('Error uploading...');
          			$('.loadingimg').hide();
          		}
      		}
     	})
});

$('#updtphbtn').click(function(){
	var newphnum = $('#mophn').val();
	$.ajax({
      type: "POST",
      crossDomain: true,
      url: "http://m2s.es/app/api/connect/editprofile.php",
      data: {"phonenumber": newphnum, "key": keyuser},
      cache: false,
      dataType: 'json',
      success: function(result) {
          console.log(result.mensaje);
          if(result.mensaje == 'ok'){
          	infomod(Language.updatephonesucces);
          	$('#mophn').val('');
          }else{
          	console.log(result.mensaje);
          }
      }
     })
})

$('#updpassn').click(function(){
	var newpassw = $('#newpassi').val();
	var confpassw = $('#confnewpassi').val();
	if(newpassw != ''){
	$.ajax({
      type: "POST",
      crossDomain: true,
      url: "http://m2s.es/app/api/connect/editprofile.php",
      data: {"password": newpassw, "password_conf": confpassw, "key": keyuser},
      cache: false,
      dataType: 'json',
      success: function(result) {
          console.log(result.mensaje);
          if(result.mensaje == 'ok'){
          	infomod(Language.updatepasssucces);
          	$('#newpassi').val('');
          	$('#confnewpassi').val('');
          	localStorage.removeItem('keyuser');
          }else{
            infomod(result.mensaje);
          }
          if(result.mensaje == 'e3'){
          	errormod(Language.passnotmatch);
          }
      }
     })
}else{
  errormod(Language.nointrpass);
}
})

$('.changelang').click(function(){
   if($('#idiomch').val() != langdefault){
     localStorage.setItem('lang', $('#idiomch').val());
     document.location.href='index.html';
   }
});

function pagefunctions(){
	$('.collapsible .head').click(function(){
		$('.collapsible .cont').hide();
		if($(this).next('.cont').is(':visible')){
			$('.collapsible .cont').hide();
		}else{
			$(this).next('.cont').show();
		}
	})
	
	if(localStorage.getItem('darkmode')){
		$('#darkmode').attr('checked', 'checked');
	}
	
	$('#darkmode').change(function(){
		if($('#darkmode').is(':checked')){
			$('body').addClass('blacka');
			localStorage.setItem('darkmode', '1');
			$('meta[name="theme-color"]').attr('content','#043966');
		}else{
			$('body').removeClass('blacka');
			localStorage.removeItem('darkmode');
			$('meta[name="theme-color"]').attr('content','#0092ff');
		}
	});

	if(!localStorage.getItem('imguse')){
        $('.imguserdff').attr('src', "images/icon-user-default.png");
    }else{
  	    $('.imguserdff').attr('src', localStorage.getItem('imguse'));
    }
    $('option[value="'+langdefault+'"]').attr('selected','selected');
    
    $('.listfriendblock').html('<div id="loading-user" id="load-idsd"><img src="images/loading.gif" width="25px" height="25px"/> <span>'+Language.loading+'</span></div>');
    $.ajax({
    	type: "POST",
    	crossDomain: true,
    	url: "http://m2s.es/app/api/blocklist.php",
    	data: {"key": keyuser},
    	cache: false,
    	dataType: 'json',
    	success: function(result) {
      		if(result.list.length != '0'){
         		$('.listfriendblock').html('');
         		for (var i = 0; i < result.list.length; i++) {
            		idg = result.list[i].id;
            		username = result.list[i].name;
            		imageprofile = result.list[i].imagepr;
            		blockstatesfv = result.list[i].block;
            		if(imageprofile == null){
	            		imageprofile = 'images/icon-user-default.png';
            		}
            		divcont = '<div class="userblockgrouplist" id="'+idg+'"><img src="'+imageprofile+'" class="img"/><div class="left-jk"><b>'+username+'</b>';
            		if(blockstatesfv == 'yes'){
              			divcont += ' <button class="btn unblockbu" id="'+idg+'" onclick="unblocpfu('+idg+')">'+Language.unblock+'</button>';
            		}else{
              			divcont += ' <button class="btn blockbu" id="'+idg+'" onclick="blockpfu('+idg+')">'+Language.block+'</button>';
            		}
            		divcont += ' <a href="profile.html?id='+idg+'"><span>'+Language.viewhisprofile+'</span></a> </div></div>';
            		$('.listfriendblock').append(divcont);
         		}
      		}else{
            $('.listfriendblock').html('<p>'+Language.nofriends+'</p>');
          }
    	},
    	error: function(XMLHttpRequest, textStatus, errorThrown) {
      		console.error(textStatus + ' ' + XMLHttpRequest.status);
      		errormod(Language.errorpetitionm2s);
    	}
	})
}

function unblocpfu(datadi){
   $('#'+datadi+'.unblockbu').html(Language.loading);
   $.ajax({
      type: "POST",
      crossDomain: true,
      url: "http://m2s.es/app/api/connect/acceptuser.php",
      data: {"id": datadi, "key": keyuser},
      cache: false,
      dataType: 'json',
      success: function(result) {
        if(result.mensaje == 'ok'){
          $('#'+datadi+'.unblockbu').html(Language.block);
          $('#'+datadi+'.unblockbu').attr('onclick', 'blockpfu("'+datadi+'")');
          $('#'+datadi+'.unblockbu').addClass('blockbu');
          $('#'+datadi+'.unblockbu').removeClass('unblockbu');
        }else{
          console.log('Error:'+result.mensaje);
        }
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        console.error(textStatus + ' ' + XMLHttpRequest.status);
        errormod(Language.errorpetitionm2s);
      }
   })
}

function blockpfu(datadi){
   $('#'+datadi+'.blockbu').html(Language.loading);
   $.ajax({
      type: "POST",
      crossDomain: true,
      url: "http://m2s.es/app/api/connect/blockuser.php",
      data: {"recid2": datadi, "key": keyuser},
      cache: false,
      dataType: 'json',
      success: function(result) {
        if(result.mensaje == 'ok'){
          $('#'+datadi+'.blockbu').html(Language.unblock);
          $('#'+datadi+'.blockbu').attr('onclick', 'unblockpfu("'+datadi+'")');
          $('#'+datadi+'.blockbu').addClass('unblockbu');
          $('#'+datadi+'.blockbu').removeClass('blockbu');
        }else{
          console.log('Error:'+result.mensaje);
        }
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        console.error(textStatus + ' ' + XMLHttpRequest.status);
        errormod(Language.errorpetitionm2s);
      }
   })
}