// JavaScript Document
$(document).ready(function() {
  $.base_url = 'http://localhost:8888/'; // Your website name
  /*Search Modal Button Clik*/
 $("#demo02, #demo03").animatedModal({
  modalTarget: 'modal-02',
  animatedIn: 'lightSpeedIn',
  animatedOut: 'bounceOutDown',
  color: '#4DB6AC',
  // Callbacks
  beforeOpen: function() {
   // console.log("The animation was called");
  },
  afterOpen: function() {
   // console.log("The animation is completed");
  },
  beforeClose: function() {
   // console.log("The animation was called");
  },
  afterClose: function() {
   // console.log("The animation is completed");
  }
});
  $("a.timeago").livequery(function() {
	  // Post time
    $(this).timeago();
  });
  $("span.timeago").livequery(function() {
	  // Notification and conversation time
    $(this).timeago();
  });
  $(".smcommenttime").livequery(function() {
	  // Comment time
    $(this).timeago();
  });
  $(".conversation-reply-text").livequery(function () { $(this).linkify({
   target: "_blank"
  }); });
  $(".conversation-reply-text, .incoming-reply-text").livequery(function() {
    $(this).emoticons();
  });
  $(".conversation-reply-text, .incoming-reply-text").livequery(function() {
    $(this).emoticonsB();
  });
  new materialTouch('.md-ripple');
  var item = $('.js-onebyone');

  $.fn.animateIn = function(options) {
    var self = $(this);

    var settings = $.extend({
      cname: 'class',
    }, options);

    var action = function() {
      (function animate(counter) {

        setTimeout(function() {

          self.eq(counter).addClass(settings.cname);

          counter++;

          if (counter < self.length) animate(counter);

        }, 60);

      })(0);
    };
    action();
  };

  item.animateIn({
    cname: 'show'
  });
  /* Notification link */
  $("#notificationLink").on('click', function() {
    var URL = $.base_url + 'notification_created_ajax.php';
    $.ajax({
      type: "POST",
      url: URL,
      cache: false,
      success: function(html) {
        if (html) {

          if ($(".notification").is(':visible')) $(".notification").fadeOut(300);

          $(".notificationContainer").fadeToggle(300);
          $(".not_count").fadeOut('slow');
          $("#notifications_container").html(html);
        }
      }
    });

    return false;
  });
  /*Show the Status message from the right to left with the msg id*/
  $('body').on('click', '.ShowStatus', function(event) {
    event.preventDefault();
    var id = $(this).data("id");
    $.ajax({
      url: $.base_url + "ShowStatus.php?msg_id=" + id,
      type: 'get',
      beforeSend: function() {
		  // Show the loader before open the status
        $("#loader").fadeIn(100);
      },
    }).done(function(data) { 
	  // Hide the loader when page is loaded
      $("#loader").fadeOut(100);
	  // Show the status update from the UserPostArea div
      $(".UserPostContent").fadeIn().find(".UserPostArea").animate({
        "right": 0
      }, 200).html(data);
    });

  });
  // Click to hide Status update left to right
  $(".UserPostContent").click(function(e) {
    var preventClick = $(".UserPostArea");

    if (!preventClick.is(e.target) && preventClick.has(e.target).length === 0) {
      $(".UserPostArea").animate({
        "right": "0%"
      }, 200, function() {
        $(".UserPostContent").fadeOut();
        $('body').css('overflow', 'auto');
      });
    };
  });
  // Click to show the message from the header Notification message
  $(".ShowMessage").on('click', function() {
	  // Open Message container
    $(".NotificationMessageContainer").fadeToggle(300);
    $("#messageSum").fadeOut('slow');
  });
  // Hide Notification Container
  $('body').on('click', function(e) {
	  // Click to body then hide notificationContainer
    if ($(e.target).closest('#notificationLink').length == 0 && $(e.target).closest('.notificationContainer').length == 0) {
		// Hide the notification container
      $(".notificationContainer").fadeOut(300);

    }
  });
  $('body').on('click', function(e) {
	  // Click to body then hide NotificationMessage container
    if ($(e.target).closest('.ShowMessage').length == 0 && $(e.target).closest('.NotificationMessageContainer').length == 0) {
		// Hide notification Message Container
      $(".NotificationMessageContainer").fadeOut(300);
    }
  });
  // Delete Post
  $('body').on('click', '.smdelete', function(event) {
    event.preventDefault();

    var ID = $(this).attr("id");
    var dataString = 'msg_id=' + ID;
    // Show the confirm dialog before delete
    jConfirm('Sure you want to delete this Update? There is NO undo!', '',
      function(r) {
		  // If clicked OK for delete do it
        if (r == true) {

          $.ajax({
            type: "POST",
            url: $.base_url + "message_delete_ajax.php",
            data: dataString,
            cache: false,
            beforeSend: function() {
				// Hide the post body with the background animate
              $("#smbody" + ID).animate({
                'backgroundColor': '#323949'
              }, 300);
            },
            success: function(html) {
				// If the post will deleted successfully then show the swall dialog
              swal({
                title: "Gönderi başarıyla silindi",
                text: "",
                timer: 5000
              });
			  // And remove the post
              $("#smbody" + ID).fadeOut(300, function() {
                $("#smbody" + ID).remove();
              });
              var c = $('#update_count').html();
              $('#update_count').html(parseInt(c) - 1);
            }
          });
        }
      });
    return false;
  });
  //Delete Comment
  $('body').on('click', '.stcommentdelete', function(event) {
    event.preventDefault();
    var ID = $(this).attr("id");
    var dataString = 'com_id=' + ID;
    var URL = $.base_url + 'comment_delete_ajax.php';
    // Show the confirm dialog before delete
    jConfirm('Bu yorumu silmek istediğinizden eminmisiniz?', '',
      function(r) {
		  // If clicked ok then do
        if (r == true) {

          $.ajax({
            type: "POST",
            url: URL,
            data: dataString,
            cache: false,
            beforeSend: function() {
				// Hide the post comment body with the background animate
              $("#smcommentbody" + ID).animate({
                'backgroundColor': '#f6f7f8'
              }, 300);
            },
            success: function(html) {
				// If the comment will deleted successfully then remove the comment
              $("#smcommentbody" + ID).fadeOut(300, function() {
                $("#smcommentbody" + ID).remove();
              });
            }
          });

        }
      });
    return false;
  });
  // Like and Unlike
  $('body').on('click', '.like_button', function(event) {
    event.preventDefault();
    var KEY = parseInt($(this).attr("data"));
    var ID = $(this).attr("id");
    if (KEY == '1') {
      var sid = ID.split("likes");
    } else {
      var sid = ID.split("like");
    }
    var New_ID = sid[1];
    var REL = $(this).attr("rel");
    var URL = $.base_url + 'like_post.php';
    var dataString = 'msg_id=' + New_ID + '&rel=' + REL;
    $.ajax({
      type: "POST",
      url: URL,
      data: dataString,
      cache: false,
      success: function(html) {
        if (html) {
          if (REL == 'Like') {
            $("#elikes" + New_ID).show('slow').prepend("<span id='you" + New_ID + "' class='bbc'><a href='#'>bunu</a> beğendin.</span>");
            $("#likes" + New_ID).prepend("<span id='you" + New_ID + "'><a href='#'>sen</a>, </span>");
            $('#' + ID).html('<div class="icon-like-comment icon-heart-2"></div>').attr('rel', 'Unlike').attr('title', 'Unlike');
          } else {
            $("#elikes" + New_ID).hide('slow');
            $("#you" + New_ID).remove();
            $('#' + ID).attr('rel', 'Like').attr('title', 'Like').html('<div class="icon-like-comment icon-heart-empty-1"></div>');
          }
        }

      }
    });

    return false;
  });
  //Load More Comments
  $('body').on('click', '.comment_button', function(event) {
    event.preventDefault();
    var ID = $(this).attr("id");
    var OID = $(this).attr("rel");
    var URL = $.base_url + 'comments.php';
    var comment = $("#ctextarea" + ID).val();
    var dataString = 'comment=' + comment + '&msg_id=' + OID;

    if ($.trim(comment).length == 0) {
      swal({
        title: "Lütfen yorum yazın!",
        text: "",
        timer: 5000
      });
    } else {
      $.ajax({
        type: "POST",
        url: URL,
        data: dataString,
        cache: false,
        success: function(html) {
          $("#commentload" + ID).append(html);
          $("#ctextarea" + ID).val('').css("height", "35px").focus();

        }
      });
    }
    return false;
  });

  $('body').on('click', '.commentopen_button', function(event) {
    event.preventDefault();
    var ID = $(this).attr("id");
    $("#commentbox" + ID).slideToggle('fast');
    $("#ctextarea" + ID).focus();
    return false;

  });
  $('body').on('click', '.openCommentArea', function(event) {
    event.preventDefault();
    var ID = $(this).attr("id");
    $("#commentbox" + ID).slideToggle('fast');
    $("#ctextarea" + ID).focus();
    return false;
  });
  // Kişi Ara
  $("#searchinput").keyup(function() {
    var searchbox = $(this).val();
    var dataString = 'searchword=' + searchbox;

    if (searchbox.length > 0) {

      $.ajax({
        type: "POST",
        url: $.base_url + "search_ajax.php",
        data: dataString,
        cache: false,
        beforeSend: function() {
          $('.ajax-loading').addClass('active'); // Note the ,e that I added
        },
        success: function(html) {
          $(".bulunan_kisi_listesi").html(html).show();
        }
      }).complete(function() {
        $('.ajax-loading').removeClass('active');
      });
    }
    return false;
  });

  $(".bulunan_kisi_listesi").mouseup(function() {
    return false;
  });

  //Send a conversation started here
  function htmlEscape(str) {
    return String(str)
      .replace(/&/g, '&amp;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;');
  }

  function list_more(dataString) {
    $.ajax({
      type: "POST",
      url: $.base_url + "daha_mesaj_ajax.php",
      data: dataString,
      cache: false,
      success: function(html) {

        if ($.trim(html).length > 0) {
          $("#replylist_content").append(html);
        } else {
          $("#replylist_content").removeClass('conversation_grid').addClass('conversation_grid_block');
        }

      }
    });
  }

  function list_more_reply(dataString) {
    $.ajax({
      type: "POST",
      url: $.base_url + "load_more_conversation.php",
      data: dataString,
      cache: false,
      success: function(html) {
        if ($.trim(html).length > 0) {
          $("#reply_content").prepend(html);
        } else {
          $("#reply_content").removeClass('conversationReply_grid').addClass('conversation_grid_blockk');
        }

      }
    });
  }
    $("#reply_content").animate({
      "scrollTop": $('#reply_content')[0].scrollHeight
    }, "slow");
    var playlist_content_height = 1070;

    $('.conversation_grid').scroll(function(eve) {
      var a = 0;
      var s = $(document).height() - playlist_content_height;
      if (s > 3028) {
        s = 3028;
      }
      if ($('.conversation_grid').scrollTop() >= s) {

        var ID = $(".user_m:last").attr("rel");
        var dataString = 'last_time=' + ID;
        if (a == 0) {
          list_more(dataString);
          a = 1;
        }

      }
    });

    var playlist_contentReply_height = 1070;

    $('.conversationReply_grid').scroll(function(eve) {
      var a = 0;
      var s = $(document).height() - playlist_contentReply_height;

      if ($('.conversationReply_grid').scrollTop() == 0) {
        var b = 0;
        var C_ID = $('#cid').val();
        var ID = $(".reply_smbody:first").attr("id");
        var sid = ID.split("smbody");
        var New_ID = sid[1];
        var dataString = 'last_time=' + New_ID + '&c_id=' + C_ID;
        if (b == 0) {
		  console.log(dataString);
          list_more_reply(dataString, C_ID);
          b = 1;
        }

      }

    });
	$('.sm-sticker').click(function(){
		var sticker = $(this).attr('sticker');
		var msg = jQuery.trim($('#text_up_p').val());
		
		if(msg == ''){
		   var sp = '';
		} else {
		   var sp = ' ';
	    }
		$('#text_up_p').val(jQuery.trim(msg + sp + sticker + sp));
	});
	$('#text_up_p').bind('keydown', function(e) {
		if(e.keyCode==13) {

      var A = $('#text_up_p').val();
      var B = $('#cid').val();
	  var BL = $('#cuid').val();
      var C = $('#uploadvalues').val();
      var X = $('.preview_img').attr('id');

      var T = $.trim(C).length > 0 ? C : 0;
      var dataString = '';

      if ($.trim(A).length == 0 && $.trim(C).length == 0) {
        swal({
          title: "Lütfen bir mesaj yazın!",
          text: "",
          timer: 3000
        });
      } else {
        dataString = 'reply=' + A + '&cid=' + B + '&upload=' + T + '&cuid=' + BL;
      }
      $.ajax({
        type: "POST",
        url: $.base_url + "chat_ajax.php",
        data: dataString,
        cache: false,
        beforeSend: function() {
          $("#flash").html('<img src="wall_icons/ajaxloader.gif"  />');
        },
        success: function(html) {
          if (html) {
            //var B=$('#cid').val();						
            if (A.length > 20) {
              A = A.substring(0, 17);
              A += '...';
            }

            $('#reply' + B).html("<img src='$.base_url+wall_icons/send.png'  class='con_send'/>" + htmlEscape(A));
            $('#reply_content').append(html);
            $("#reply_content").animate({
              "scrollTop": $('#reply_content')[0].scrollHeight
            }, "slow");
            $('#flash').hide();
			$(".changec").removeClass("talk-with");
			$(".changec").addClass("messages--wrap");
			$(".changec").addClass("all-current-messages");
			$(".changec").html("");
            $('#text_up_p').val('');
            $('#text_up_p').focus();
            $('#uploadvalues').val('');
            $('.image-preview-c').html('');
            $('.fotograf-m-wr').hide();
			$('.image-preview-area').fadeOut("fast");
          } else {}
        }
      });

      return false;
		}
    });
    $(".reply_button, .send_emo").on("click", function() {

      var A = $('#text_up_p').val();
      var B = $('#cid').val();
	  var BL = $('#cuid').val();
      var C = $('#uploadvalues').val();
      var X = $('.preview_img').attr('id');

      var T = $.trim(C).length > 0 ? C : 0;
      var dataString = '';

      if ($.trim(A).length == 0 && $.trim(C).length == 0) {
        swal({
          title: "Lütfen mesaj yazın!",
          text: "",
          timer: 3000
        });
      } else {
        dataString = 'reply=' + A + '&cid=' + B + '&upload=' + T + '&cuid=' + BL;
      }
      $.ajax({
        type: "POST",
        url: $.base_url + "chat_ajax.php",
        data: dataString,
        cache: false,
        beforeSend: function() {
          $(".sending_message").fadeIn("fast");
        },
        success: function(html) {
          if (html) {
            //var B=$('#cid').val();						
            if (A.length > 20) {
              A = A.substring(0, 17);
              A += '...';
            }
            $(".sending_message").fadeOut("fast");
            $('#reply' + B).html("<img src='$.base_url+wall_icons/send.png'  class='con_send'/>" + htmlEscape(A));
            $('#reply_content').append(html);
            $("#reply_content").animate({
              "scrollTop": $('#reply_content')[0].scrollHeight
            }, "slow");
            $('#flash').hide();
			$(".changec").removeClass("talk-with");
			$(".changec").addClass("messages--wrap");
			$(".changec").addClass("all-current-messages");
			$(".changec").html("");
            $('#text_up_p').val('');
            $('#text_up_p').focus();
            $('#uploadvalues').val('');
            $('.image-preview-c').html('');
            $('.fotograf-m-wr').hide();
			$('.image-preview-area').fadeOut("fast");
          } else {}
        }
      });

      return false;

    });
    $('#photoimg').off('click').on('change', function() {
      var values = $("#uploadvalues").val();
      $("#previeww").html('<img src="wall_icons/loader.gif"/>');
      $("#imageform").ajaxForm({
        target: '.image-preview-c',
        beforeSubmit: function() {
          $("#imageloadstatus").show();
          $("#imageloadbutton").show();
        },
        success: function() {
          $("#imageloadstatus").hide();
          $("#imageloadbutton").show();
          var X = $('.preview_img').attr('id');
          var C = X + ',' + values;
          if (C != 'undefined,') {
            $("#uploadvalues").val(C);
          }
        },
        error: function() {
          $("#imageloadstatus").hide();
          $("#imageloadbutton").show();
        }
      }).submit();

    });
// Delete Conversation
  $('body').on('click', '.delete_conversation', function() {
    var ID = $(this).attr("id");
    //var X=$(this).attr("my");
    var dataString = 'c_id=' + ID;
    jConfirm("Bu sohbeti silmek istediğinizden eminmisiniz?", '',
      function(r) {
        if (r == true) {
          $.ajax({
            type: "POST",
            url: $.base_url+"conversation_delete_ajax.php",
            data: dataString,
            cache: false,
            beforeSend: function() {
              $("#smbody" + ID).animate({
                'backgroundColor': '#f2f2f2'
              }, 300);
            },
            success: function(html) {
              window.location = $.base_url+'chat.php';
			  /*$("#chatbody" + ID).fadeOut(300, function() {
                $("#chatbody" + ID).remove();
              });*/
            }
          });

        }
      });

    return false;
  });
  $(function() {
    $('.konfi').click(function() {
      $('.image-preview-area').slideToggle("fast");
    });
  });
  /*Show user profile details*/
  $(".materiald").on('click', function() {

    var id = $(this).data("id");
    var state = $(this).data("state");
    $.ajax({
      url: $.base_url + "user-details.php?uid=" + id,
      type: 'get',
      beforeSend: function() {
        //$("#loader").fadeIn(100); 
      },
    }).done(function(data) {
      if (state === "close") {
        $('.materiald').data("state", 'open');
        $(".global-message-container").addClass("tess");
        $(".close-info").addClass("active-profile");
        $(".user-container").animate({
          width: "100%"
        }, 200).find(".sidebar-content").animate({
          width: "100%"
        }, 200).html(data);
      } else {
        $(".close-info").removeClass("active-profile");
        $('.materiald').data("state", 'close');
        $(".user-container").animate({
          width: "0%"
        }, 200).find(".sidebar-content").animate({
          width: "0%"
        }, 200).html(data);
      }
    });
  });
  /*Show User Profile Details in Mobile version*/
  $(".materiald-mobile, .materiald-mobile-close").on('click', function() {

    var id = $(this).data("id");
    var statesmob = $(this).data("statesmob");
    $.ajax({
      url: $.base_url + "user-details.php?uid=" + id,
      type: 'get',
      beforeSend: function() {
        //$("#loader").fadeIn(100); 
      },
    }).done(function(data) {
      if (statesmob === "close") {
        $('.materiald-mobile, .materiald-mobile-close').data("statesmob", 'open');
        $(".close-info-mobile").addClass("active-profile");
        $(".user-container-mobile").animate({
          width: "70%"
        }, 200).find(".sidebar-content-mobile").animate({
          width: "100%"
        }, 200).html(data);
      } else {
        $(".close-info-mobile").removeClass("active-profile");
        $('.materiald-mobile, .materiald-mobile-close').data("statesmob", 'close');
        $(".user-container-mobile").animate({
          width: "0%"
        }, 200).find(".sidebar-content-mobile").animate({
          width: "0%"
        }, 200).html(data);
      }
    });
  });
  /*Test For The Slide Left Chat List Active and Deactive*/

  $(".open-chat-list").on('click', function() {
    var state = $(this).data("states");
    if (state === "close") {
      $(this).data("states", 'open');
      $(".chat-list-active").addClass("active");
      $(".icon-ls").addClass("icon-cross-mark");
      $(".icon-ls").removeClass("icon-align-justify");
      $('.chat-list-active').animate({
        left: "0%"
      }, 10);
      $('.chat-container').animate({
        right: "-80%"
      });
    } else {
      $(this).data("states", 'close');
      $(".icon-ls").removeClass("icon-cross-mark");
      $(".icon-ls").addClass("icon-align-justify");
      $('.chat-list-active').animate({
        left: "0%"
      }, 10);
      $(".chat-list-active").removeClass("active");
      $('.chat-container').animate({
        right: "0%"
      });
    }
  });

  /*Window Resize ComeBack Original Size*/
  var $window = $(window),
    $BackToOriginal = $('.chat-list-active');

  $(window).on('resize', function() {
    if ($window.width() > 880) {
      $(".icon-ls").removeClass("icon-cross-mark");
      $(".icon-ls").addClass("icon-align-justify");

      $BackToOriginal.removeClass('active');
      $('.chat-container').animate({
        right: "0%"
      });
    }
  });

  /*Right settings menu*/
  $('html').click(function() {
    $('.some-info-menu').removeClass("activated");
  });

  $('.some-info-menu ul li').each(function() {
    var delay = $(this).index() * 50 + 'ms';

    $(this).css({
      '-webkit-transition-delay': delay,
      '-moz-transition-delay': delay,
      '-o-transition-delay': delay,
      'transition-delay': delay
    });
  });

  $(".mat-menu").click(function(e) {
    e.stopPropagation();
    $('.some-info-menu').toggleClass("activated");
  });

  $('.some-info-menu').click(function(e) {
    e.stopPropagation();
  });
  /*Some user info cubic bezier*/

  $('html').on('click', function(e) {
    e.stopPropagation();
    $('.some-info-menu').removeClass("active-mm");
  });

  $(".list-view-btn").on("click", function() {
    $(".follow-list-container").fadeIn(100);
  });
  $(".back-to-chat-list").on("click", function() {
    $(".follow-list-container").fadeOut(100);
  });
  /*Left Menu Show Hide*/
  $('html').click(function() {
    $('.menu-area-wrap').removeClass("activedd");
  });

  $(".tt").click(function(e) {
    e.stopPropagation();
    $('.menu-area-wrap').toggleClass("activedd");
  });

  $('.menu-area-wrap').click(function(e) {
    e.stopPropagation();
  });
    // Change Language
  $(function() {
    var i;
    $('.change-language').on('click', function() {
      $('.backbar').animate({
        'opacity': '.50'
      }, 300, 'linear');
      $('.language_wrap').animate({
        'opacity': '1.00'
      }, 300, 'linear');
      $('.backbar, .language_wrap').css('display', 'block');
      //get id
      i = $(this).attr('id');

    });
    //click .report button
    $('body').on('click', '.send_this_language', function(event) {
    event.preventDefault();
      $.ajax({
        type: "POST",
        url: $.base_url +'change_language.php',
        data: {
          id: i,
          u_lang: $('input[name="u_lang"]:checked').val()
        },
        beforeSend: function() {
          $("#posting").html('<img src="icons/ajaxloader.gif"/>');
        },
        success: function(html) {
          if (html.trim() === "1") {
            window.location.reload();
          } else {
            swal({
              title: "Geçersiz dil seçimi!",
              text: ":o",
              timer: 4000
            });
          }
        }
      });
      return false;
    });
    $('.go').click(function() {
      close_box11();
    });
  });

  function close_box11() {
    $('.backbar, .language_wrap').animate({
      'opacity': '0'
    }, 300, 'linear', function() {
      $('.backbar, .language_wrap').css('display', 'none');
    });
    $('input[name="report_type"]').attr('checked', false);
  }
});