document.onkeydown = function(evt) {
	evt = evt || window.event;
	var isEscape = false;
	if ("key" in evt) {
		isEscape = (evt.key === "Escape" || evt.key === "Esc");
	} else {
		isEscape = (evt.keyCode === 27);
	}
	if (isEscape) {
		if(scriptJquery(".stories_story_view_main").css('display') == "block"){
			scriptJquery(".stories_story_view_close_btn").trigger("click");
		}
	}
};

function selectfeedbgimage(background_id) {
  scriptJquery(".stories_btn_submit").removeAttr('disabled');
  scriptJquery(".background_img").removeClass('_selected');
  scriptJquery("#background_"+background_id).addClass('_selected');
  scriptJquery('#background_id').val(background_id);

  // set image
  let imageUrl = scriptJquery("#background_"+background_id).find("img").attr("src");
  scriptJquery(".stories_previewimg").css('background-image', 'url(' + imageUrl + ')');
}

function handleFileUploadstories(files)
{
	let isValid = false;
	for (var i = 0; i < files.length; i++)
	{
		if(scriptJquery('.multi_upload_stories').find(".filename")){
			scriptJquery('.multi_upload_stories').find(".filename").remove();
		}
		var url = files[i].name;
		var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
		if(ext == 'mp4' || ext == 'mpeg' || ext == 'mov' || ext == 'ogg' || ext == 'ogv' || ext == 'avi' || ext == 'flv' || ext == 'mpg' || ext == 'WMV'){
			//check upload limit
			var FileSize = files[i].size / 1024 / 1024; // in MB
			if(FileSize > post_max_size_story){
				alert("The size of the file exceeds the limits of "+post_max_size_story+"MB.");
				return;
			}else{
				isValid = true;
				scriptJquery('#story_type').val('imagevideo');
				var $source = scriptJquery('.stories_previewvideo').find("source");
				$source[0].src = URL.createObjectURL(files[i]);
				$source.parent()[0].load();
				let vid = document.getElementById("story_previewvideo");
				vid.muted = true;
				$source.parent()[0].play();
				scriptJquery('#stories_previewtext').html("");
				scriptJquery('#stories_add_bg_images').hide();
				scriptJquery('.stories_previewimg').hide();
				scriptJquery('.stories_previewvideo').show();
			}
		}
		scriptJquery('#story_type').val('imagevideo');
		if(scriptJquery('#story_type').val() == 'imagevideo' && (ext == "png" || ext == "jpeg" || ext == "jpg" ||  ext == 'gif' || ext == 'mp4' || ext == 'mpeg' || ext == 'mov' || ext == 'ogg' || ext == 'ogv' || ext == 'avi' || ext == 'flv' || ext == 'mpg' || ext == 'WMV' || ext == 'webp')){
			
			if(!isValid){
				isValid = true;
				let imageUrl = URL.createObjectURL(files[i]);
				scriptJquery(".stories_previewimg").css('background-image', 'url(' + imageUrl + ')');
				scriptJquery('#stories_add_bg_images').hide();
				scriptJquery('.stories_previewimg').show();
				scriptJquery('.stories_previewvideo').hide();
			}
		}else{
			// scriptJquery(".stories_btn_submit").attr('disabled',true);
			files.value = "";
		}
	}

	if(isValid){
		scriptJquery(".stories_btn_submit").removeAttr('disabled');
		// scriptJquery(".multi_upload_stories").append('<span class="filename">'+url+'</span>');
		scriptJquery("#multi_upload_stories").css("border",'');

		scriptJquery(".stories_story_uploader_main").hide();
		scriptJquery(".stories_story_uploader_preview").show();
		scriptJquery(".stories_description").show();
		scriptJquery(".stories_add_bg_images").hide();
		scriptJquery('#stories_previewtext').html("");
		scriptJquery('#stories_description').val("");
		scriptJquery('.stories_footer').show();
	}
}

AttachEventListerSE('click','.create_stories',function (e) {
	e.preventDefault();
	scriptJquery("#create-stories").trigger("click");
});

AttachEventListerSE('submit','.submit_stories',function (e) {
	e.preventDefault();
// 	if(!scriptJquery("#file_multi_stories").val()){
// 		scriptJquery("#multi_upload_stories").css("border",'1px solid red');
// 		return false;
// 	}
	var formData = new FormData(this);
	if(scriptJquery('#file_multi_stories')[0].files[0]){
		var name = "attachmentVideo[0]";
		var url = scriptJquery("#file_multi_stories").val();
		var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
		if((ext == "png" || ext == "jpeg" || ext == "jpg" ||  ext == 'gif' || ext == 'webp')){
			name = "attachmentImage[0]";
		}
		formData.append(name, scriptJquery('#file_multi_stories')[0].files[0]);
	}
	scriptJquery(".submit_stories").append('<div class="stories_loading_image"></div>');
	formData.append('description', scriptJquery('#stories_description').val());

  formData.append('background_id', scriptJquery('#background_id').val());
  formData.append('story_type', scriptJquery('#story_type').val() ? scriptJquery('#story_type').val() : "text");

	var uploadURL = 'stories/index/create';
	scriptJquery(".stories_btn_submit").attr('disabled',true);
	scriptJquery('.stories_add_story_popup_content').append('<div class="core_loading_cont_overlay" style="display:block;"></div>')
	scriptJquery.ajax({
		url: uploadURL,
		type:'POST',
		data:formData,
		cache:false,
		contentType: false,
		processData: false,
		xhr:  function() {
			var xhrobj = scriptJquery.ajaxSettings.xhr();
			if (xhrobj.upload) {
				xhrobj.upload.addEventListener('progress', function(event) {
					var percent = 0;
					var position = event.loaded || event.position;
					var total = event.total;
					if (event.lengthComputable) {
						percent = Math.ceil(position / total * 100);
					}
					//Set progress
				}, false);
			}
			return xhrobj;
		},
		success: function(response){
			scriptJquery('.stories_add_story_popup_content').find('.core_loading_cont_overlay').remove();
			scriptJquery(".stories_btn_submit").attr('disabled',false);
			scriptJquery(".stories_loading_image").remove();
			response = scriptJquery.parseJSON(response);
			if (response.message) {
				// alert(response.message);
				scriptJquery("#success_stories_cnt").addClass('_show');
				scriptJquery("#success_stories_create").html(response.message);
				setTimeout(function () {
					ajaxsmoothboxclose();
				},10);
				getStoriesData();
			}else{
				alert('Something went wrong, please try again later.');
			}
		}
	});
})
 
function readImageUrlstories(input) {
	handleFileUploadstories(input.files);
}
AttachEventListerSE('click','#confirm_success_stories',function(e){
	scriptJquery("#success_stories_cnt").removeClass('_show');
});
AttachEventListerSE('click','#cancel_discard_stories',function(e){
	scriptJquery("#discard_stories_cnt").removeClass('_show');
});
AttachEventListerSE('click','.discard_stories_btn',function(e){
	let vid = document.getElementById("story_previewvideo");
	vid.muted = true;
	scriptJquery("#discard_stories_cnt").addClass('_show');

});
AttachEventListerSE('click','#confirm_discard_stories',function(e){
	scriptJquery("#discard_stories_cnt").removeClass('_show');
	scriptJquery(".stories_story_uploader_main").show();
	scriptJquery(".stories_story_uploader_preview").hide();
	scriptJquery(".stories_description").hide();
	scriptJquery(".stories_add_bg_images").hide();
    scriptJquery('#stories_add_bg_images').hide();
	scriptJquery('#stories_previewtext').html("");
	scriptJquery('#stories_description').val("");
	scriptJquery('.stories_footer').hide();
	scriptJquery('.stories_previewimg').hide();
	scriptJquery('.stories_previewvideo').hide();
    scriptJquery('#story_type').val('');
});

AttachEventListerSE('click','.multi_upload_stories, .text_stories',function(e){
	scriptJquery('#stories_previewtext').html("");
  if(scriptJquery(this).attr('data-type') == 'text') {
	scriptJquery(".stories_story_uploader_main").hide();
	scriptJquery(".stories_story_uploader_preview").show();
	scriptJquery(".stories_story_uploader_preview").addClass("_textpreview");
	scriptJquery(".stories_description").show();
	scriptJquery(".stories_add_bg_images").show();
    scriptJquery('#stories_add_bg_images').show();
	scriptJquery('#stories_previewtext').html("");
	scriptJquery('#stories_description').val("");
	scriptJquery('.stories_footer').show();
	scriptJquery('.stories_previewimg').show();
	scriptJquery('.stories_previewvideo').hide();
	scriptJquery("#stories_add_bg_images").children().eq(1).trigger("click");


    scriptJquery('#story_type').val('text');
	if(scriptJquery("#stories_description").val())
		scriptJquery(".stories_btn_submit").removeAttr('disabled');
  } else if(scriptJquery(this).attr('data-type') == 'imagevideo') {
    
    document.getElementById('file_multi_stories').click();
  }
});
AttachEventListerSE("keyup","#stories_description",function(e){
	// if(scriptJquery("#story_type").val() == "imagevideo"){
	// 	return;
	// }
	if(scriptJquery("#story_type").val() != "imagevideo"){
		scriptJquery('#stories_add_bg_images').show();
	}
	// if(!scriptJquery("#background_id").val()){
	// 	scriptJquery("#stories_add_bg_images").find("a").eq(0).trigger("click");
	// }
	scriptJquery(".stories_previewtext").html(scriptJquery(this).val());
	if(scriptJquery(this).val()){
		scriptJquery(".stories_btn_submit").removeAttr('disabled');
	}else{
		scriptJquery(".stories_btn_submit").attr('disabled',true);
	}
})
function timeSince(timeStamp) {
	var now = new Date(currentDateTime),
		secondsPast = (now.getTime() - timeStamp) / 1000;
	if (secondsPast < 60) {
		return parseInt(secondsPast) + 's';
	}
	if (secondsPast < 3600) {
		return parseInt(secondsPast / 60) + 'm';
	}
	if (secondsPast <= 86400) {
		return parseInt(secondsPast / 3600) + 'h';
	}
	if (secondsPast > 86400) {
		timeStamp = new Date(timeStamp);
		day = timeStamp.getDate();
		month = timeStamp.toDateString().match(/ [a-zA-Z]*/)[0].replace(" ", "");
		year = timeStamp.getFullYear() == now.getFullYear() ? "" : " " + timeStamp.getFullYear();
		return day + " " + month + year;
	}
}
function getIndex(data,id){
	const index = data.findIndex(p => p.user_id == id);
	return index;
}
function getStoryIndex(data,id){
	const index = data.findIndex(p => p.story_id == id);
	return index;
}
function getStories(rel,id) {
	var storyData;
	if(rel == id){
		//my story content
		storyData = storiesData.my_story
	}else{
		//user story content
		var index = getIndex(storiesData.stories,rel)
		storyData = storiesData.stories[index]
	}
	return storyData;
}

function addSourceToVideo(element, src, type) {
	var source = document.createElement('source');
	source.src = src;
	source.type = type;
	element.appendChild(source);
}
function storieshoverStopPlay(type){
	if(type){
		StoriesHoverItem = true;
		if(Storiesvideo){
			Storiesvideo.pause();
		}
		if(scriptJquery('.story_play_pause').find('i').hasClass("fa-pause")){
			scriptJquery('.story_play_pause').find('i').addClass("fa-play");
			scriptJquery('.story_play_pause').find('i').removeClass("fa-pause");
		}

	}else{
		if(Storiesvideo){
			Storiesvideo.play();
		}
		StoriesHoverItem = false;
		if(scriptJquery('.story_play_pause').find('i').hasClass("fa-play")){
			scriptJquery('.story_play_pause').find('i').removeClass("fa-play");
			scriptJquery('.story_play_pause').find('i').addClass("fa-pause");
		}
	}
}
AttachEventListerSE('click','.stories_option_elm',function (e) {
	e.preventDefault();
	storieshoverStopPlay(true);
	var type = scriptJquery(this).attr('type');
	var id = scriptJquery(this).attr('rel');
	if(type == "delete"){
		openSmoothBoxInUrl(en4.core.baseUrl +"stories/index/delete/id/"+id);
	}else if(type == "report"){
		openSmoothBoxInUrl(en4.core.baseUrl +'report/create/route/default/subject/stories_story_'+id+'/format/smoothbox');
	}else if (type == "mute"){
		scriptJquery.post(en4.core.baseUrl +"stories/index/mute/story_id/"+id,{},function (res) {
			if(res){
				var storyData = storiesData
				//user story content
				var index = getIndex(storyData.stories,selectedStoryUserId)
				storyData.stories.splice(index, 1);
				storiesData = storyData;
				selectedStoryId = 0;
				if (storyData.stories.length >= index + 1 && index > -1){
					selectedStoryUserId = storyData.stories[index].user_id
					callNextStory();
				}else{
					scriptJquery(".stories_story_view_close_btn").trigger("click");
				}
				getStoriesData();
			}
		})
	}else{
		storieshoverStopPlay(false);

	}

})
var deleteStoryIndex = -1;
function storyDeleted(){
	var storyData = storiesData
	//user story content
	var index = getStoryIndex(storyData.my_story.story_content,selectedStoryId)
	deleteStoryIndex = index;
	scriptJquery(".stories_story_slider_loader").children().eq(index).remove();
	callNextStory();
	storyData.my_story.story_content.splice(index, 1);
	storiesData = storyData;
	getStoriesData();
}
AttachEventListerSE('click','.story_play_mute',function (e) {
	e.preventDefault();
	if(scriptJquery(this).find('i').hasClass("fa-volume-up")){
		scriptJquery(this).find('i').addClass("fa-volume-mute");
		scriptJquery(this).find('i').removeClass("fa-volume-up");
		Storiesvideo.muted = true;
		storiesVideoVolumeMute = true;
	}else{
		scriptJquery(this).find('i').removeClass("fa-volume-mute");
		scriptJquery(this).find('i').addClass("fa-volume-up");
		Storiesvideo.muted = false;
		storiesVideoVolumeMute = false;
	}
})
AttachEventListerSE('click','.story_play_pause',function (e) {
	e.preventDefault();
	if(scriptJquery(this).find('i').hasClass("fa-pause")){
		stopTimerStories = true;
		// scriptJquery(this).find('i').addClass("fa-play");
		// scriptJquery(this).find('i').removeClass("fa-pause");
		storieshoverStopPlay(true);
	}else{
		stopTimerStories = false;
		// scriptJquery(this).find('i').removeClass("fa-play");
		// scriptJquery(this).find('i').addClass("fa-pause");
		storieshoverStopPlay(false);
	}
})
function markStoryViewed(data){
	let storyID = data.story_id;
	let viewer = en4.user.viewer.id;
	scriptJquery.post(en4.core.baseUrl + 'stories/index/view-story',{story_id:storyID, user_id: viewer},function(){

	})
}
var selectedStoryId;
var selectedStoryUserId;
var storiesVideoVolumeMute = false;
var story_type;
function createSliders(rel,id,data,index = 0){
	if(typeof data == "undefined")
		data = getStories(rel,id);
	stopTimerStories = false;
	if(Storiesvideo){
		Storiesvideo.pause();
	}
	Storiesvideo = undefined;
	storieshoverStopPlay(false);

	if(data){
		var total = data.story_content.length;
		var slides = "";
		for(i=0;i<total;i++){
			if(i == index){
				scriptJquery(".stories_name").html(data.username);
				scriptJquery(".stories_user_image").attr('src',data.user_image);
				//update options
				scriptJquery(".stories_story_item_header").find(".stories_controller").remove();
				var optionsData = "<span class='story_play_pause'><i class='fas fa-pause'></i></span>";

				if(data.story_content[index].is_video) {
					if(!storiesVideoVolumeMute)
						optionsData = optionsData + "<span class='story_play_mute'><i class='fas fa-volume-up'></i></span>";
					else
						optionsData = optionsData + "<span class='story_play_mute'><i class='fas fa-volume-mute'></i></span>";
				}

				scriptJquery(".stories_story_item_header").append("<div class='stories_controller'>"+optionsData+"</div>");
				if(data.story_content[index].options && data.story_content[index].options.length){
					var optionsData = "";
					data.story_content[index].options.forEach(item => {
						optionsData = optionsData +  "<li><a href='javascript:;' class='stories_option_elm dropdown-item' type='"+item.name+"' rel='"+data.story_content[index].story_id+"'>"+item.label+"</a></li>";
					})
					scriptJquery(".stories_story_item_header").find(".stories_option").remove();
					scriptJquery(".stories_story_item_header").append("<div class='stories_option dropdown'><a href='javascript:;' class='ajaxPrevent' type='button' data-bs-toggle='dropdown'><i class='fas fa-ellipsis-h'></i></a><ul class='stories_option_ul dropdown-menu'>"+optionsData+"</ul></div>");
				}
				selectedStoryId = data.story_content[index].story_id;
				selectedStoryUserId = data.user_id;
        		story_type = data.story_content[index].story_type;
				if(selectedStoryUserId == parseInt(en4.user.viewer.id) || !data.story_content[index].can_comment){
					scriptJquery(".stories_message_cnt").hide();
				}else{
					scriptJquery(".stories_message_cnt").show();
				}
				scriptJquery('.stories_story_item_caption').removeClass("_photo");
				scriptJquery('.stories_story_item_caption').removeClass("_video");
				scriptJquery('.stories_media_content').removeClass("_isphoto");
				scriptJquery('.stories_media_content').removeClass("_isvideo");
				
				if(data.story_content[index].is_video){
					scriptJquery('.stories_media_content').addClass("_isvideo");
					scriptJquery('.stories_story_item_caption').addClass("_video");
				} else if(story_type == 'imagevideo') {
					scriptJquery('.stories_story_item_caption').addClass("_photo");
					scriptJquery('.stories_media_content').addClass("_isphoto");
				}
				scriptJquery(".stories_time").html(timeSince(new Date(data.story_content[index].creation_date).getTime()));
				scriptJquery(".stories_story_item_caption").html(data.story_content[index].comment);
				scriptJquery(".storiescommentlike").attr('data-storyid',data.story_content[index].story_id);
        if(!data.story_content[index].is_video) {
          //Text Story Work
          if(story_type == 'text') {
            scriptJquery('.stories_content_text').show();
            scriptJquery('.stories_content_text_reaction').show();
						scriptJquery('.stories_content').hide();
            scriptJquery(".stories_content_text").css("background-image", "url(" + data.story_content[index].media_url + ")");
            scriptJquery(".stories_contenttext").html(data.story_content[index].comment);
            scriptJquery(".stories_content_bg_image").attr('src',data.story_content[index].media_url);
          } else if(story_type == 'imagevideo') {
            scriptJquery('.stories_content_text').hide();
						scriptJquery('.stories_content_text_reaction').hide();
            scriptJquery('.stories_content').show();
            scriptJquery(".stories_content_bg_image").attr('src',data.story_content[index].media_url);
          }
        } else {
          if(story_type == 'text') {
            scriptJquery('.stories_content').hide();
            scriptJquery('.stories_content_text').show();
						scriptJquery('.stories_content_text_reaction').show();
            scriptJquery(".stories_content_text").css("background-image", "url(" + data.story_content[index].media_url + ")");
            scriptJquery(".stories_contenttext").html(data.story_content[index].comment);
            scriptJquery(".stories_content_bg_image").attr('src',data.story_content[index].media_url);
          } else if(story_type == 'imagevideo') {
            scriptJquery('.stories_content_text').hide();
						scriptJquery('.stories_content_text_reaction').hide();
            scriptJquery('.stories_content').show();
            scriptJquery(".stories_content_bg_image").attr('src',data.story_content[index].photo);
          }
        }
				markStoryViewed(data.story_content[index]);
				updateStoryReactionData(data.story_content[index]);
				//check next
				var isNext = callNextStory(true);
				if(isNext){
					scriptJquery(".stories_next").show();
				}else{
					scriptJquery(".stories_next").hide();
				}
				//check previous
				var isPrev = callPreviousStory(true);
				if(isPrev){
					scriptJquery(".stories_previous").show();
				}else{
					scriptJquery(".stories_previous").hide();
				}
				if(data.story_content[index].is_video){
					Storiesvideo = document.createElement('video');
					Storiesvideo.preload = true;
					Storiesvideo.controls = false;
					if(storiesVideoVolumeMute){
						Storiesvideo.muted = true;
					}
					scriptJquery('.stories_content').html(Storiesvideo);
					addSourceToVideo(Storiesvideo, data.story_content[index].media_url, 'video/mp4');
					Storiesvideo.play();
					Storiesvideo.onended = function () {
						//call next data
						callNextStory();
					}
					Storiesvideo.onpause = function(){
						if(!StoriesHoverItem && Storiesvideo){
							var sliderBar = scriptJquery(".stories_story_slider_loader").children().eq(index);
							sliderBar.find("span").find('span').css("width","100%");
						}
					}
					Storiesvideo.ontimeupdate = function (event) {
						if(!Storiesvideo){
							return;
						}
						var currentTime = event.srcElement.currentTime;
						var duration = event.srcElement.duration;
						//update bar
						var sliderBar = scriptJquery(".stories_story_slider_loader").children().eq(index);
						var percentage = (currentTime * 100) / duration
						sliderBar.find("span").find('span').css("width",percentage+"%");
					}
				}else{
					scriptJquery('.stories_content').html('<img rel="'+index+'" onload="imageLoaded();" src="'+data.story_content[index].media_url+'" />');
				}
			}
			slides = slides+'<div class="'+(deleteStoryIndex == i ? "d-none" : "")+'"><span><span style="width: '+(i < index ? 100 : 0)+'%"></span></span></div>';
		}
		scriptJquery('.stories_story_slider_loader').html(slides);
	}
}
var Storiesvideo;
var currentTimeForStories = 0;
var breakTimeStories = false;
var storiesIntervalObj;
function runTimer() {
	if(StoriesHoverItem){
		return;
	}
	var index = scriptJquery(".stories_content").find('img').attr('rel');
	var sliderBar = scriptJquery(".stories_story_slider_loader").children().eq(parseInt(index));
	var percentage = (currentTimeForStories * 100) / parseInt(stories_webstoryviewtime);
	sliderBar.find("span").find('span').css("width",percentage+"%");
	if(percentage == "100"){
		callNextStory();
	}else{
		currentTimeForStories++;
		if(!storiesIntervalObj)
			storiesIntervalObj = setInterval(runTimer, 500);
	}
}
function imageLoaded() {
	breakTimeStories = false;
	runTimer();
}
function callPreviousStory(checkExist = false) {
	if(checkExist) {
		currentTimeForStories = 0
		breakTimeStories = true;
		if (storiesIntervalObj) {
			clearInterval(storiesIntervalObj);
			storiesIntervalObj = undefined;
		}
	}
	var storyData = storiesData
	var valid = false
	if(storyData.my_story){
		//my story content
		if(storyData.my_story.user_id == selectedStoryUserId) {
			valid = true;
			var index = getStoryIndex(storyData.my_story.story_content,selectedStoryId);
			if(index > -1){
				if(index && index > index - 1){
					if(checkExist)
						return true;
					var storyData = storyData.my_story
					createSliders(0,0,storyData,index-1)
				}else{
					if(checkExist)
						return false;
					scriptJquery(".stories_content").html('');
					scriptJquery('.stories_story_view_close_btn').trigger("click");
				}
			}
		}
	}
	if(!valid){
		//user story content
		var index = getIndex(storyData.stories,selectedStoryUserId);
		var storyindex = getStoryIndex(storyData.stories[index].story_content,selectedStoryId);
		if( storyindex - 1 >= 0){
			if(checkExist)
				return true;
			var storyData = storyData.stories[index]
			createSliders(0,0,storyData,storyindex-1)
		}else if( index-1 >= 0){
			if(checkExist)
				return true;
			var storyData = storyData.stories[index-1]
			createSliders(0,0,storyData,0)
		}else if(storyData.my_story.story_content && storyData.my_story.story_content.length){
			if(checkExist)
				return true;
			var storyData = storyData.my_story
			createSliders(0,0,storyData,0)
		}else{
			if(checkExist)
				return false;
			scriptJquery(".stories_content").html('');
			scriptJquery('.stories_story_view_close_btn').trigger("click");
		}
	}
}
//hover on reactions
var StoriesHoverItem = false;
var stopTimerStories = false;
scriptJquery(function() {
	scriptJquery('.stories_story_item_reply_box').hover( function(){
			storieshoverStopPlay(true);
		},
		function(){
			if(!stopTimerStories)
				storieshoverStopPlay(false);
		});
});
function callNextStory(checkExist = false) {
	if(checkExist) {
		currentTimeForStories = 0
		breakTimeStories = true;
		if (storiesIntervalObj) {
			clearInterval(storiesIntervalObj);
			storiesIntervalObj = undefined;
		}
	}
	var storyData = storiesData
	var valid = false
	if(storyData.my_story){
		//my story content
		if(storyData.my_story.user_id == selectedStoryUserId) {
			valid = true;
			var index = getStoryIndex(storyData.my_story.story_content,selectedStoryId);
			if(index > -1){
				var dataStory = storyData['my_story']['story_content'][index]
				if(storyData['my_story']['story_content'].length > index + 1){
					if(checkExist)
						return true;
					var storyData = storyData.my_story
					createSliders(0,0,storyData,index+1)
				}else if(storyData.stories && storyData.stories.length){
					if(checkExist)
						return true;
					createSliders(0,0,storyData.stories[0],0);
				}else{
					if(checkExist)
						return false;
					scriptJquery(".stories_content").html('');
					scriptJquery('.stories_story_view_close_btn').trigger("click");
				}
			}
		}
	}
	if(!valid){
		//user story content
		var index = getIndex(storyData.stories,selectedStoryUserId);
		var storyindex = getStoryIndex(storyData.stories[index].story_content,selectedStoryId)
		if(storyData.stories[index]['story_content'].length > storyindex + 1){
			if(checkExist)
				return true;
			var storyData = storyData.stories[index]
			createSliders(0,0,storyData,storyindex+1)
		}else if(storyData.stories.length > index+1){
			if(checkExist)
				return true;
			var storyData = storyData.stories[index+1]
			createSliders(0,0,storyData,0)
		}else{
			if(checkExist)
				return false;
			scriptJquery(".stories_content").html('');
			scriptJquery('.stories_story_view_close_btn').trigger("click");
		}
	}
}
AttachEventListerSE('click','.stories_previous',function (e) {
	e.preventDefault();

})
AttachEventListerSE('click','.stories_next',function (e) {
	e.preventDefault();
	callNextStory();
})

AttachEventListerSE('click','.stories_previous',function (e) {
	e.preventDefault();
	callPreviousStory();
})

AttachEventListerSE("click",'.ajaxsmoothbox',function (e) {
	if(scriptJquery(".stories_story_view_main").css('display') == "block"){
		storieshoverStopPlay(true);
	}
})
var open_story_archive = false;
AttachEventListerSE("click",'.open_story_archive',function (e) {
	open_story_archive = true;
})
function ajaxsmoothboxcallbackclose() {
	if(open_story_archive)
		storieshoverStopPlay(true);
	else
		storieshoverStopPlay(false);

	open_story_archive = false;
}
function updateStoryReactionData(data){
	if(data.reactionData && data.reactionData.length){
		if(data.like.image) {
			scriptJquery(".stories_comment_d").removeClass("_icon");
			scriptJquery(".stories_comment_d").css('background-image', 'url(' + data.like.image + ')');
		}
		var reactionImages = "";
		data.reactionData.forEach(item => {
			reactionImages =  reactionImages + '<span class="comments_likes_reactions"><a title="'+item['title']+'" href="javascript:;" class="ajaxsmoothbox" data-url="comment/ajax/likes/type//id/'+selectedStoryId+'/resource_type/stories_story/item_id/'+selectedStoryId+'/format/smoothbox"><i style="background-image:url('+item['imageUrl']+');"></i></a></span>';
		});
		var finalData = '<div class="comments_stats_likes">'+reactionImages+
			'<a href="javascript:;" class="ajaxsmoothbox" data-url="comment/ajax/likes/type//id/'+selectedStoryId+'/resource_type/stories_story/item_id/'+selectedStoryId+'/format/smoothbox">  '+data.reactionUserData+'</a>'+
			'</div>';
		scriptJquery(".stories_reaction_data").html(finalData);
	}else{
		scriptJquery(".stories_reaction_data").html('');
		scriptJquery(".stories_comment_d").css('background-image','url()');
		scriptJquery(".stories_comment_d").addClass("_icon");
	}
}
AttachEventListerSE('click','.open_story',function (e) {
	breakTimeStories=false;
	currentTimeForStories = 0;
	var rel = parseInt(scriptJquery(this).attr('rel'));
	var id = en4.user.viewer.id;
	var storyData;
	storyData = getStories();
	//make sliders stories_story_slider_loader
	if(typeof selectedStoryId != "undefined"){
		var storyData = storiesData
		var valid = false
		if(storyData.my_story){
			//my story content
			if(storyData.my_story.user_id == selectedStoryUserId) {
				var index = getStoryIndex(storyData.my_story.story_content,selectedStoryId);
				if(index > -1){
					valid = true;
					var storyData = storyData.my_story
					createSliders(0,0,storyData,index)
					scriptJquery(".stories_story_view_main").show();
				}
			}
		}
		if(!valid){
			//user story content
			if(storyData.stories) {
				var index = getIndex(storyData.stories, selectedStoryUserId);
				var storyindex = getStoryIndex(storyData.stories[index].story_content, selectedStoryId);
				if (storyindex > -1) {
					storyData = storyData.stories[index]
					var storyData = storyData.my_story
					createSliders(0, 0, storyData, storyindex)
					scriptJquery(".stories_story_view_main").show();
				} else {
					scriptJquery(".stories_content").html('');
					scriptJquery('.stories_story_view_close_btn').trigger("click");
					alert("Story you are looking does not exists.");
				}
			}else{
				scriptJquery(".stories_content").html('');
				scriptJquery('.stories_story_view_close_btn').trigger("click");
				alert("Story you are looking does not exists.");
			}
		}
	}else{
		createSliders(rel,id);
		scriptJquery(".stories_story_view_main").show();
	}
})
AttachEventListerSE('click','.stories_story_view_close_btn',function (e) {
	e.preventDefault();
	breakTimeStories=true;
	if(storiesIntervalObj){
		clearInterval(storiesIntervalObj);
		storiesIntervalObj = undefined;
	}
	selectedStoryId = undefined;
	storieshoverStopPlay(true);
	scriptJquery(".stories_story_view_main").hide();
})

AttachEventListerSE('click','.storiescommentlike',function(){
	var obj = scriptJquery(this);
	previousSesadvcommLikeObj = obj.closest('.sesadvcmt_hoverbox_wrapper');
	var story_id = selectedStoryId;
	//var guid = scriptJquery(this).attr('data-guid');

	var type = scriptJquery(this).attr('data-type');
	var datatext = scriptJquery(this).attr('data-text');
	//check for like
	var isLikeElem = false;
	if(scriptJquery(this).hasClass('reaction_btn')){
		var image = scriptJquery(this).find('.reaction').find('i').css('background-image');
		image = image.replace('url(','').replace(')','').replace(/\"/gi, "");
		var elem = scriptJquery(this).parent().parent().parent().find('a');
		isLikeElem = true;
	}else{
		var image = scriptJquery(this).parent().find('.sesadvcmt_hoverbox').find('span').first().find('.reaction_btn').find('.reaction').find('i').css('background-image');
		image = image.replace('url(','').replace(')','').replace(/\"/gi, "");
		var elem = scriptJquery(this);
		isLikeElem = false
	}

	var likeWorkText = scriptJquery(elem).attr('data-like');
	var unlikeWordText = scriptJquery(elem).attr('data-unlike');

	//unlike
	if(scriptJquery(elem).hasClass('_reaction') && !isLikeElem){
		scriptJquery(elem).find('i').removeAttr('style');
		scriptJquery(elem).find('span').html(unlikeWordText);
		scriptJquery(elem).removeClass('storiescommentunlike').removeClass('_reaction').addClass('storiescommentlike');
		scriptJquery(elem).parent().addClass('feed_item_option_like').removeClass('feed_item_option_unlike');
	}else{
		//like
		scriptJquery(elem).find('i').css('background-image', 'url(' + image + ')');
		scriptJquery(elem).find('span').html(datatext);
		scriptJquery(elem).removeClass('storiescommentlike').addClass('_reaction').addClass('storiescommentunlike');
		scriptJquery(elem).parent().addClass('feed_item_option_unlike').removeClass('feed_item_option_like');
	}
	scriptJquery(".stories_comment_d").removeClass('_icon');
	var ajax = scriptJquery.ajax({
		url : en4.core.baseUrl + 'stories/index/like',
		data : {
			format : 'json',
			story_id : story_id,
			type:type
		},
		'onComplete' : function(responseHTML) {
			if( responseHTML ) {
				changeDataReaction(responseHTML);
			}
		}
	});
	
});
//like feed action content
AttachEventListerSE('click','.storiescommentunlike',function(){
	var obj = scriptJquery(this);
	var story_id = selectedStoryId;
	var type = scriptJquery(this).attr('data-type');
	var datatext = scriptJquery(this).attr('data-text');
	var likeWorkText = scriptJquery(this).attr('data-like');
	var unlikeWordText = scriptJquery(this).attr('data-unlike');

	//check for unlike
	scriptJquery(this).find('i').removeAttr('style');
	scriptJquery(this).find('span').html(likeWorkText);
	scriptJquery(this).removeClass('storiescommentunlike').removeClass('_reaction').addClass('storiescommentlike');
	scriptJquery(this).parent().addClass('feed_item_option_like').removeClass('feed_item_option_unlike');
	scriptJquery(".stories_comment_d").addClass('_icon');
	var ajax = scriptJquery.ajax({
		url : en4.core.baseUrl + 'stories/index/unlike',
		data : {
			format : 'json',
			story_id : story_id,
			type:type
		},
		'onComplete' : function(responseHTML) {
			if( responseHTML ) {
				changeDataReaction(responseHTML);

			}
		}
	});
	
});
function changeDataReaction(responseHTML){
	var valid = true;
	var storyData = storiesData
	var data;
	if(storyData.my_story){
		//my story content
		if(storyData.my_story.user_id == selectedStoryUserId) {
			valid = true;
			var index = getStoryIndex(storyData.my_story.story_content,selectedStoryId);
			if(index > -1){
				storyData['my_story']['story_content'][index]['reactionData'] = responseHTML.reactionData['reactionData'];
				storyData['my_story']['story_content'][index]['is_like'] = responseHTML.reactionData['is_like'];
				storyData['my_story']['story_content'][index]['like'] = responseHTML.reactionData['like'];
				storyData['my_story']['story_content'][index]['reactionUserData'] = responseHTML.reactionData['reactionUserData'];
				data = storyData['my_story']['story_content'][index]
			}
		}
	}
	if(!valid){
		//user story content
		var index = getIndex(storyData.stories,selectedStoryUserId)
		var storyindex = getStoryIndex(storyData.stories[index].story_content,selectedStoryId)
		storyData.stories[index]['story_content'][storyindex]['reactionData'] = responseHTML.reactionData['reactionData'];
		storyData.stories[index]['story_content'][storyindex]['is_like'] = responseHTML.reactionData['is_like'];
		storyData.stories[index]['story_content'][storyindex]['like'] = responseHTML.reactionData['like'];
		storyData.stories[index]['story_content'][storyindex]['reactionUserData'] = responseHTML.reactionData['reactionUserData'];
		data = storyData.stories[index]['story_content'][storyindex]
	}
	storiesData = storyData;
	updateStoryReactionData(data)
}
AttachEventListerSE('click','#stories_setting_cnt > li',function (e) {
	var index = scriptJquery(this).index();
	scriptJquery("._active").removeClass("_active");
	scriptJquery(this).find("a").addClass('_active');
	scriptJquery('.stories_archive_popup_cont').children().hide();
	scriptJquery('.stories_archive_popup_cont').children().eq(index).show();
});

AttachEventListerSE('click','.stories_highlight',function (e) {
	var id = scriptJquery(this).attr('rel');
	if(scriptJquery(this).hasClass('_active')){
		scriptJquery(this).removeClass('_active')
	}else{
		scriptJquery(this).addClass('_active')
	}
	scriptJquery.post(en4.core.baseUrl + 'stories/index/highlight',{story_id:id},function (e) {
		getStoriesData();
	})
})

AttachEventListerSE('click','.stories_unmute',function (e) {
	var id = scriptJquery(this).attr('rel');
	scriptJquery(this).closest('li').remove();
	scriptJquery.post(en4.core.baseUrl + 'stories/index/unmute',{mute_id:id},function (e) {
		getStoriesData();
	})
});
AttachEventListerSE('submit','#stories_form_create',function (e) {
	e.preventDefault();
	scriptJquery(this).find("#submit").html("Saving...");
	var obj = this;
	scriptJquery.post(en4.core.baseUrl + 'stories/index/save-form',{story_privacy:scriptJquery("input[name='story_privacy']:checked").val()
		,story_comment:scriptJquery("input[name='story_comment']:checked").val()},function (response) {
			getStoriesData();
		scriptJquery(obj).find("#submit").html("Save Changes")
	})
});
AttachEventListerSE('click','.stories_message_cnt_btn',function (e) {
	var value = scriptJquery('.stories_message_cnt_input').val();
		if(value){
			scriptJquery('.stories_message_cnt_input').val("");
			scriptJquery('.stories_reply_success_msg').show();
			setTimeout(function () {
				scriptJquery('.stories_reply_success_msg').hide();
			},2000)
			scriptJquery.post(en4.core.baseUrl + 'stories/index/message',{data:value,owner_id:selectedStoryUserId},function (response) {

			})
		}
})
AttachEventListerSE('keypress','.stories_message_cnt_input',function (e) {
	if (e.which == 13) {
		var value = scriptJquery(this).val();
		if(value){
			scriptJquery(this).val("");
			scriptJquery('.stories_reply_success_msg').show();
			setTimeout(function () {
				scriptJquery('.stories_reply_success_msg').hide();
			},2000)
			scriptJquery.post(en4.core.baseUrl + 'stories/index/message',{data:value,owner_id:selectedStoryUserId},function (response) {

			})
		}
	}
});
