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

function pagefunctions(){
	$.ajax({
    type: "POST",
    crossDomain: true,
    url: "http://m2s.es/app/api/groupinfo.php",
    data: {"id": id, "key": keyuser},
    cache: false,
    dataType: 'json',
    success: function (result) {
        id = result.id;
        name = result.groupname;
        image = result.imagein;
        private = result.private;
        admininfo = result.admininfo;
        official = result.official;
        local = result.local;
        decription = result.description;
        peoplejoin = result.peoplejoined;
        mutegroup = result.mute;
        $('#loading-user').hide();

        if(admininfo == 'me'){
            $('header ul.right').show();
        }

        var modaluser = '';

        if (image != null) {
            $('header h1').append('<img src="' + image + '" class="profile-badge"/>');
        }else{
            var namesplit = name.split(' ');
            abv1 = namesplit[0].charAt(0);
            if (namesplit[1]) {
                abv2 = namesplit[1].charAt(0);
                abv = abv1 + abv2;
            }else{
                abv = abv1;
            }
            $('header h1').append('<div class="img profile-badge" style="background-color:#777"><p unselectable="on" onselectstart="return false;" onmousedown="return false;">' + abv + '</p></div>');
        }

        $('header h1').append('<h5>'+name+'</h5>');
        if (official == 'yes') {
           $('header h1').addClass('official');
        }
		$('header h1').append('<div class="infomodf"></div>');
		
        if (local.longitud) {
            $('.infomodf').append('<iframe marginheight="0" marginwidth="0" src="http://maps.google.com/maps?client=safari&ll=' + local.latitude + ',' + local.longitud + '&z=14&output=embed" frameborder="0" scrolling="no" style="height: 24%;max-height: 200px;width: 100%;border-radius:5px;margin-bottom:5px"></iframe>');
        }

        $('.infomodf').append('<p>' + linkscom(decription) + '</p>');
        $('header h1').append('<div class="linksoptions"></div>');
        
        if (result.yourstate == '1') {
           $('.linksoptions').append('<a id="chatbutton" href="chatgr.html?id='+id+'">'+Language.chat+'</a>');          
            if(mutegroup == 'no'){
             $('.linksoptions').append('<a id="mutegroupbutton" class="mute">'+Language.mutegroup+'</a>');
            }else{
              $('.linksoptions').append('<a id="mutegroupbutton" class="unmute">'+Language.unmutegroup+'</a>');
            }
            if (admininfo != 'me') {
                $('.linksoptions').append('<a id="leavegroupbutton">'+Language.leavegroup+'</a>');
            }else{
            	$('.linksoptions').append('<a id="admingroupbutton" href="admingroup.html?id='+id+'">'+Language.admingroup+'</a>');
            }
            if (result.states != '') {
                for (var i = 0; i < result.states.length; i++) {
                    idt = result.states[i].id;
                    text = result.states[i].text;
                    date = result.states[i].date;
                    locationgg = result.states[i].location;
                    if (admininfo != 'me') {
                        mens = '';
                    }else{
                        mens = 'me';
                    }
                    if (locationgg.latitude != '') {
                        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 = '';
                    }
					
						
                    $('.steats').append("<li class='li-chats noimgsd' id='"+idt+"'><div class='right-info'></div><div class='right-p'><div class='stateci'><span class='name'></span><p class='state-text'>"+linkscom(text)+"</p>"+ locatisn + " <font class='date'>"+convert(date)+"</font></div></div></li>");

                    if(admininfo == 'me'){
	                    heigcv = $('#'+idt).height();
                        $('#'+idt).prepend('<a href="javascript:deletestategr(' + idt + ')" class="deletered trash" style="display:none;height:'+heigcv+'"><span class="icon trash"></span></a>');
                    }

                    if(admininfo == 'me'){
                        $$('#'+idt).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);
						});
					  $$('#'+idt).swipeRight(function() {
                                $(".trash", this).css('display', 'none');
                                $(this).removeAttr('style');
                      });
                    }
                }
            }
        }

        if (result.yourstate == null || result.yourstate == '0') {
            if (!result.yourstate) {
                $('.linksoptions').append('<a id="joingroupbutton">'+Language.jointhisgroup+'</a>');
            }else{
               $('.linksoptions').append('<font>'+Language.waitadminacceptyou+'</font>');
            }
            if (admininfo != null || peoplejoin != '0') {
                modaluser = '';
                if (admininfo != null) {
                    if(admininfo.imagein == null){
                      admininfo.imagein = 'images/icon-user-default.png';
                    }
                    modaluser += '<li class="li-chats createdbyd">';
                    modaluser += "<a href='profile.html?id="+admininfo.id+"'><img src='"+admininfo.imagein+"' class='img'/></a>";
                    modaluser += "<div class='right-info'></div><div class='right-p'><div class='stateci'><span class='name'><i>"+Language.createdby+"</i>";
                    modaluser += "</span><p class='state-text'><b class='selecton'>" + admininfo.username + "</b></p></div></div></li>";
                }
                if (peoplejoin != '0') {
                    modaluser += '<li class="li-chats noimgsd userjoinsd">';
                    modaluser += "<div class='right-info'></div><div class='right-p'><div class='stateci'><span class='name'></span><p class='state-text'>";
                    modaluser += '<i>'+Language.peoplejoined+'</i> <b>' + peoplejoin + '</b></p></div></div></li>';
                }
            $('.steats').append(modaluser);
            }
        }

        if (!result.yourstate) {
            $('#joingroupbutton').click(function () {
                $.ajax({
                    type: "POST",
                    crossDomain: true,
                    url: 'http://m2s.es/app/api/connect/joingroup.php',
                    data: {"id": id, "key": keyuser},
                    cache: false,
                    dataType: 'json',
                    beforeSend: function () {
                        console.log('Connecting...');
                        $('#joingroupbutton').attr('disabled', 'disabled');
                        $('#joingroupbutton').html(Language.loading);
                    },
                    success: function (data) {
                        if (data.mensaje == 'ok') {
                            if (private == 'no') {
                                document.location.href= 'profilegr.html?id='+id;
                            }else{
                                document.location.href= 'profilegr.html?id='+id;
                            }
                        }else{
                            console.error('Error to join to the group: ' + data.mensaje);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.error(textStatus + ' ' + XMLHttpRequest.status);
                        errormod(Language.errorpetitionm2s);
                    }
                })
            });
        }	
        $('#leavegroupbutton').click(function () {
	        confirmod(Language.sureleavegroup, function(){
                        $.ajax({
                            type: "POST",
                            crossDomain: true,
                            url: 'http://m2s.es/app/api/connect/leavegroup.php',
                            data: {"id": id, "key": keyuser},
                            cache: false,
                            dataType: 'json',
                            beforeSend: function () {
                                console.log('Connecting...');
                                $('#leavegroupbutton').attr('disabled', 'disabled');
                                $('#leavegroupbutton').html(Language.loading);
                            },
                            success: function (data) {
                                if (data.mensaje == 'ok') {
                                    document.location.href= 'profilegr.html?id='+id;
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                console.error(textStatus + ' ' + XMLHttpRequest.status);
                                errormod(Language.errorpetitionm2s);
                            }
                        })
            });
        })

        $('#mutegroupbutton').click(function(){
            $.ajax({
                type: "POST",
                crossDomain: true,
                url: 'http://m2s.es/app/api/connect/mutegroup.php',
                data: {"id": id, "key": keyuser},
                cache: false,
                dataType: 'json',
                beforeSend: function () {
                    console.log('Connecting...');
                    $('#mutegroupbutton').html(Language.loading);
                },
                success: function (data) {
                    if (data.mensaje == 'ok') {
                       document.location.href= 'profilegr.html?id='+id;
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.error(textStatus + ' ' + XMLHttpRequest.status);
                    errormod(Language.errorpetitionm2s);
                }
            })
        })
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.error(textStatus + ' ' + XMLHttpRequest.status);
        errormod(Language.errorpetitionm2s);
    }
})
}

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

function showrittestate(){
	if(!$('.writtste').is(":visible")){
        $('.writtste').show();
    }else{
        $('.writtste').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-group.php",
      data: {"txt": text, "map": map, "id": id, "key": keyuser},
      cache: false,
      dataType: 'json',
      beforeSend: function() {
        console.log('Connecting...');
      },
      success: function(writers) {
        if(writers.mensaje == 'ok'){
            document.location.href= 'profilegr.html?id='+id;
        }
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        console.error(textStatus + ' ' + XMLHttpRequest.status);
        errormod(Language.errorpetitionm2s);
      }
   })
}