   if (!localStorage.getItem('user')) {
       window.location.href = "login.html"
   }
   var user = localStorage.getItem('user');
   var passmd5 = localStorage.getItem('passwd');
   var keyuser = localStorage.getItem('keyuser');

   registerntf();
   
   $('.backck').click(function(){
	   localStorage.setItem('lasturl', document.URL);
   })
   
   $('.backhe').attr('href', localStorage.getItem('lasturl'));
   
   if(localStorage.getItem('darkmode')){
      $('body').addClass('blacka');
      $('meta[name="theme-color"]').attr('content','#043966');
   }
   
   if(localStorage.getItem('barnotif')){
	  if($('body.notifications').length == '0'){
      	$('body').prepend('<div class="bar-notification backck"></div>');
      	$('header').css('margin-top','22px');
	  	$('meta[name="theme-color"]').remove();
	  	if($('body.chats').length == '1'){
		  	$('.msmdiv').css('top','83px');
		  	$('.msmdiv').css('height','calc(100% - 136px)');
	  	}
      }
   }
   
   notifications();
   
   function datahours() {
       var now = new Date();
       var hour = 60 * 60 * 1000;
       var min = 60 * 1000;
       var madrid = new Date(now.getTime() + (now.getTimezoneOffset() * min) + ('1' * hour)).getHours();
       var d = new Date();
       var local = d.getHours();
       var diference = madrid - local;
       if (diference < '0') {
           var diferencenew = diference *= -1;
       } else {
           if (diference != '0') {
               var diferencenew = '-' + diference;
           } else {
               var diferencenew = '0';
           }
       }
       if (localStorage) {
           localStorage.setItem("datehours", diferencenew);
       }
   }


   function convert(data) {
       if (localStorage.getItem('datehours')) {
           var diferenced = parseInt(localStorage.getItem('datehours'));
       } else {
           if (localStorage) {
               datahours();
               var diferenced = parseInt(localStorage.getItem('datehours'));
           } else {
               datahours();
               var diferenced = parseInt(diferencenew);
           }
       }
       t = data.split(' ');
       r = new Object;
       r.dia = t[0].substr(8, 2);
       r.mes = t[0].substr(5, 2);
       r.ano = t[0].substr(0, 4);
       r.hora = parseInt(t[1].substr(0, 2));
       r.minutos = t[1].substr(3, 2);
       d = new Date(r.ano, r.mes, r.dia, r.hora + diferenced, r.minutos);
       resdia = ("0" + d.getDate()).slice(-2);
       resmes = ("0" + d.getMonth()).slice(-2);
       resano = d.getFullYear();
       reshora = ("0" + d.getHours()).slice(-2);
       resminutos = ("0" + d.getMinutes()).slice(-2);
       ret = resdia + "/" + resmes + "/" + resano + " "+Language.at+" " + reshora + ":" + resminutos;
       return ret;
   };

   function openimg(url){
	   	var imgd = document.createElement("div");
        imgd.setAttribute("id", "imagebackg");
        imgd.setAttribute("class", "imagebackg");
        document.body.appendChild(imgd);
        $('#imagebackg').append('<span class="icon remove"></span><img class="responsiveimd" src="'+url+'"/>');
        $('.responsiveimd').css('margin-top', ($('.responsiveimd').height())/2 * -1);
        $('.responsiveimd').css('margin-left', ($('.responsiveimd').width())/2 * -1);
        $('#imagebackg .icon.remove').click(function(){
	        $('#imagebackg').remove();
        })
   }
   
   function linkscom(textdf) {
       var str = textdf;
       var exp = /((https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])(?=([^"']*["'][^"']*["'])*[^"']*$)/ig;
       var exp2 = /((https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]+\.(?:jpe?g|gif|png))(?=([^"']*["'][^"']*["'])*[^"']*$)/ig;
       var exp3 = /(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/ig;
       var instag = /(?:http:\/\/)?(?:www\.)?(?:instagram\.com)\/(?:p)\/?(.+)\/(?:([^"']*["'][^"']*["'])*[^"']*$)/ig;
       var images = str.replace(exp2, "<div class='imagechat "+langdefault+"' style='background-image:url($1)' onclick='openimg(&quot;$1&quot;)'></div>");
       var youtube = images.replace(exp3, "<div id='maxwidthyo'><div class='videoWrapper'><iframe frameborder='0' allowfullscreen src='http://www.youtube.com/embed/$1'/></div></div>");
       var linksd = youtube.replace(instag, "<style>.embed-container {position: relative; padding-bottom: 110%; height: 0; overflow: hidden;} .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }</style><div class='embed-container' ><iframe src='http://instagram.com/p/$1/embed/' frameborder='0' scrolling='no' allowtransparency='true'></iframe></div>");
       var links = linksd.replace(exp, "<a href='$1' target='_blank' class='nolink'>$1</a>");
       return links
   }

   function acceptgrj(idgroup, id) {
       $.ajax({
           type: "POST",
           crossDomain: true,
           url: "http://m2s.es/app/api/connect/acceptpjg.php",
           data: {"id": idgroup, "iduser": id, "key": keyuser},
           cache: false,
           dataType: 'json',
           beforeSend: function () {
               console.log('Connecting...');
               $('#acceptpeogroup-' + id).attr('disabled', true);
               $('#acceptpeogroup-' + id).html(Language.loading)
           },
           success: function (result) {
               if (result.mensaje == 'ok') {
                   setInterval(function () {
                       $('#fgr-' + id).fadeOut(500, function () {
                           $('#fgr-' + id).remove();
                       })
                       if ($('#list-notifications .item').length == '0') {
                           $('.background-dark').remove();
                       }
                   }, 3000);
               }
           },
           error: function (XMLHttpRequest, textStatus, errorThrown) {
               console.error(textStatus + ' ' + XMLHttpRequest.status);
               if ($('#list-notifications .item').length == '0') {
                   $('.background-dark').remove();
               }
               errormod(Language.errorpetitionm2s);
           }
       })
   }

   function blockgrj(idgroup, id) {
       $.ajax({
           type: "POST",
           crossDomain: true,
           url: "http://m2s.es/app/api/connect/blockpjg.php",
           data: {"id": idgroup, "iduser": id, "key": keyuser},
           cache: false,
           dataType: 'json',
           beforeSend: function () {
               console.log('Connecting...');
               $('#blockpeogroup-' + id).attr('disabled', true);
               $('#blockpeogroup-' + id).html(Language.loading)
           },
           success: function (result) {
               if (result.mensaje == 'ok') {
                   setInterval(function () {
                       $('#fgr-' + id).fadeOut(500, function () {
                           $('#fgr-' + id).remove();
                       })
                       if ($('#list-notifications .item').length == '0') {
                           $('.background-dark').remove();
                       }
                   }, 3000);
               }
           },
           error: function (XMLHttpRequest, textStatus, errorThrown) {
               console.error(textStatus + ' ' + XMLHttpRequest.status);
               if ($('#list-notifications .item').length == '0') {
                   $('.background-dark').remove();
               }
               errormod(Language.errorpetitionm2s);
           }
       })
   }

   function acceptfriend(id) {
       $.ajax({
           type: "POST",
           crossDomain: true,
           url: "http://m2s.es/app/api/connect/acceptfriend.php",
           data: {"id": id, "key": keyuser},
           cache: false,
           dataType: 'json',
           beforeSend: function () {
               console.log('Connecting...');
               $('#acceptfriend-' + id).attr('disabled', true);
               $('#acceptfriend-' + id).html(Language.loading)
           },
           success: function (result) {
               if (result.mensaje == 'ok') {
                   setInterval(function () {
                       $('#fr-' + id).fadeOut(500, function () {
                           $('#fr-' + id).remove();
                       })
                       if ($('#list-notifications .item').length == '0') {
                           $('.background-dark').remove();
                       }
                       if (document.location.pathname.indexOf("index.html") != 0) {
                           document.location.href = 'index.html';
                       }
                   }, 3000);
               }
           },
           error: function (XMLHttpRequest, textStatus, errorThrown) {
               console.error(textStatus + ' ' + XMLHttpRequest.status);
               if ($('#list-notifications .item').length == '0') {
                   $('.background-dark').remove();
               }
               errormod(Language.errorpetitionm2s);
           }
       })
   };

   function blockuser(id) {
       $.ajax({
           type: "POST",
           crossDomain: true,
           url: "http://m2s.es/app/api/connect/blockuser.php",
           data: {"recid2": id, "key": keyuser},
           cache: false,
           dataType: 'json',
           beforeSend: function () {
               console.log('Connecting...');
               $('#blockuser-' + id).attr('disabled', true);
               $('#blockuser-' + id).html(Language.loading)
           },
           success: function (result) {
               console.log(result.mensaje);
               if (result.mensaje == 'ok') {
                  if($('#closenotifications')){
                   setInterval(function () {
                       $('#fr-' + id).fadeOut(500, function () {
                           $('#fr-' + id).remove();
                       })
                       if ($('#list-notifications .item').length == '0') {
                           $('.background-dark').remove();
                       }
                   }, 3000);
                  }else{
                    var pathname = window.location.pathname;
                    if(pathname == '/chat.html'){
                      var win = gui.Window.get();
                      win.close()
                    }
                  }
               }
           },
           error: function (XMLHttpRequest, textStatus, errorThrown) {
               console.error(textStatus + ' ' + XMLHttpRequest.status);
               if ($('#list-notifications .item').length == '0') {
                   $('.background-dark').remove();
               }
               errormod(Language.errorpetitionm2s);
           }
       })
   };
   function deletefriend(id){
      $.ajax({
          type: "POST",
          crossDomain: true,
          url: "http://m2s.es/app/api/connect/deletefriend.php",
          data: {"id": id, "key": keyuser},
          cache: false,
          dataType: 'json',
          beforeSend: function () {
              console.log('Connecting to delete friend...');
          },
          success: function (result) {
              if (result.mensaje == 'ok') {
                  infomod(Language.succesdeletefriend);
                  var pathname = window.location.pathname;
                  if(pathname == '/myfriends.html'){
                     $('#list-'+id).remove();
                  }
                  if(pathname == '/chat.html'){
                    var win = gui.Window.get();
                    win.close()
                  }
                  if(pathname == '/prfmod.html'){
                    document.location.href= 'prfmod.html?id='+id;
                  }
              }
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) {
              console.error(textStatus + ' ' + XMLHttpRequest.status);
              errormod(Language.errorpetitionm2s);
          }
      })
   }
   function notifications() {
       console.log('Checking notifications...');
       $.ajax({
           type: "POST",
           crossDomain: true,
           url: 'http://m2s.es/app/api/notifications.php',
           data: {"key": keyuser},
           cache: false,
           dataType: 'json',
           success: function (result) {
               if (result.mensaje == 'nologin') {
                   console.log('No session');
                   login(user, passmd5, 'session');
               } else {
                   if (result.newnotication != '0') {
                   }
                   if (result.notification != '0') {
                        if($('.bar-notification').length == '0'){
	                        $('body').prepend('<div class="bar-notification clickable backck">'+Language.havenewnotifications+'</div>');
	                        $('.bar-notification').click(function(){
                              document.location.href = 'notifications.html';
                          	});
                          	$('header').css('margin-top','22px');
                          	$('meta[name="theme-color"]').remove();
                          	localStorage.setItem('barnotif', '1');
                          	if($('body.chats').length == '1'){
						  		$('.msmdiv').css('top','83px');
						  		$('.msmdiv').css('height','calc(100% - 136px)');
	  						}
	                    }else{
		                    if($('.bar-notification clickable').length == '0'){
                             	$('.bar-notification').html(Language.havenewnotifications);
							 	$('.bar-notification').click(function(){
                                  document.location.href = 'notifications.html';
                             	});
							 	$('.bar-notification').addClass('clickable');
                          	}
	                    }
                   } else {
                       $('.bar-notification').remove();
                       localStorage.removeItem('barnotif');
                       $('header').css('margin-top','0px');
                       if(localStorage.getItem('darkmode')){
	                       	$('meta[name="theme-color"]').attr('content','#043966');
                       }else{
                       		$('head').append('<meta name="theme-color" content="#0092ff">');
                       }
                       if($('body.chats').length == '1'){
						  	$('.msmdiv').css('top','61px');
						  	$('.msmdiv').css('height','calc(100% - 114px)');
	  				    }
                   }
               }
           },
           error: function (XMLHttpRequest, textStatus, errorThrown) {
               console.error(textStatus + ' ' + XMLHttpRequest.status);
           }
       })
   }


   function signout() {
      confirmod(Language.suresignout, function(){
           unregisterntf()
     });
   }