MOON
Server: Apache
System: Linux e2e-78-16.ssdcloudindia.net 3.10.0-1160.45.1.el7.x86_64 #1 SMP Wed Oct 13 17:20:51 UTC 2021 x86_64
User: imensosw (1005)
PHP: 7.4.33
Disabled: exec,passthru,shell_exec,system
Upload Files
File: /home/imensosw/www/mpl.imenso.co/public/js/main.js
$(window).load(function () {
    doNewsMasonary();
    doFanEventsMasonary();
});

// window.onpopstate = function (event) {
//     str = String(document.location);
//     if (!str.includes('search=true')) {
//         closeGlobalSearch()
//     }
// };

function goToSignupOnHome() {
    modal.close();
    scrollToSignup();
}

function closeVideoLightbox(el) {
    $(el).parents('.video-lightbox-background').remove();
}

function openVideoLightbox(video_id, video_type) {
    $('.video-lightbox-background').remove();
    var html = '<div class="video-lightbox-background">\
					<i class="fa fa-close" onclick="closeVideoLightbox(this)"></i>\
					<div class="video-wrap">';
    if (video_type == 'vimeo') {
        html += '<iframe src="https://player.vimeo.com/video/' + video_id + '?title=0&amp;byline=0&amp;portrait=0&loop=1" frameborder="0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>'
    }

    html += '</div>\
				</div>';

    $('body').append(html);

    $('.video-lightbox-background').on('click', function (event) {
        if ($(event.target).hasClass('video-lightbox-background')) {
            $('.video-lightbox-background').remove();
        }
    });
}

function changeGaurenteeOption(el) {
    if ($(el).val() == "yes") {
        $('.min-gaurentee-js').show();
    } else {
        $('.min-gaurentee-js').hide();
    }
}

function saveAvail(el) {
    $(el).parents('form').append('<input type="hidden" value="true" name="save">');
    $(el).parents('form').submit();
}

function ajaxUserFollowArtist(el, user_id, recommendee_id) {
    wrap = $(el).parents('.quick-links');
    $(wrap).empty();
    $(wrap).html('<div class="static-loader"><i class="fa fa-spin fa-spinner"></i></div>');
    var endpoint = url + "/ajax/user-follow-artist";
    var formData = {
        user_id: user_id,
        recommendee_id: recommendee_id,
        _token: csrf_token
    };
    $.post(endpoint, formData).done(function (data) {
        if (data = 'Success') {
            $(wrap).empty();
            $(wrap).html('<div class="static-message">Following <i class="fa fa-check"></i></div>')
        }
    });
}

function copyReferLink(el) {
    $(el).siblings('.link-copied').addClass('active');
    setTimeout(function () {
        $(el).siblings('.link-copied').removeClass('active');
    }, 2000);
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(el).attr('data-refer-link')).select();
    document.execCommand("copy");
    $temp.remove();
}

function reorderPencilsAjax(enquiry_id, direction){

	var endpoint = url+"/venue/reorder_enquiry";
	var formData = {
		enquiry_id: enquiry_id,
        direction: direction,
        _token: csrf_token
	};
	$.post(endpoint, formData).done(function (data) {
		response = JSON.parse(data);

		$('.dialog.manage-pencils table.secondary').empty();
		$('.dialog.manage-pencils table.secondary').append(response.html);
	});
}

function filterEventsList(el)
{
	searchval = $(el).val().toUpperCase();
	rows_displayed = 0;

	if($(el).val().length >= 3) {
		$('tr.single-event-js').each(function(){
			if ($(this).find('.name').text().toUpperCase().includes(searchval) || $(this).find('.promoter').text().toUpperCase().includes(searchval) || $(this).find('.artists').text().toUpperCase().includes(searchval) || $(this).find('.venue').text().toUpperCase().includes(searchval)) {
				$(this).css('display', '');
				rows_displayed++;
			} else {
				$(this).css('display', 'none');
			}
		});
	} else {
		$('tr.single-event-js').css('display', '');
		rows_displayed = 1;
	}

	if (rows_displayed == 0) {
		$('.no-results-row').css('display', '');
	} else {
		$('.no-results-row').css('display', 'none');
	}
}

function ajaxUserIgnoreArtist(el, user_id, recommendee_id){
	wrap = $(el).parents('.quick-links');
	$(wrap).empty();
	$(wrap).html('<div class="static-loader"><i class="fa fa-spin fa-spinner"></i></div>');
	var endpoint = url+"/ajax/user-ignore-artist";
	var formData = {
		user_id: user_id,
        recommendee_id: recommendee_id,
        _token: csrf_token
	};
	$.post(endpoint, formData).done(function (data) {
		if (data = 'Success') {
			$(wrap).empty();
			$(wrap).html('<div class="static-message">Dismissed <i class="fa fa-check"></i></div>')
		}
	});
}

function showMapPastEvents(){
	$('.venue-single .events .heading').text('Past Events');
	$('.venue-single .events .link.past').hide();
	$('.venue-single .events .link.future').show();

	$('.venue-single .events .future.events-list').hide();
	$('.venue-single .events .past.events-list').show();
}

function showMapFutureEvents(){
	$('.venue-single .events .heading').text('Events');
	$('.venue-single .events .link.past').show();
	$('.venue-single .events .link.future').hide();

	$('.venue-single .events .future.events-list').show();
	$('.venue-single .events .past.events-list').hide();
}

function togglePromoterSelection(el){
	if ($(el).find('option:selected').val() == 1) {
		$('.input-row.promoters').show();
	} else {
		$('.input-row.promoters').hide();
	}
}

function toggleParkingPref(el){
	if ($(el).find('option:selected').val() == "1") {
		$('.input-row.parking-details').show();
	} else {
		$('.input-row.parking-details').hide();
	}
}

function togglePromoterSelector(el)
{
	if ($(el).find('option:selected').val() == "1") {
		$('.input-row.promoters').show();
	} else {
		$('.input-row.promoters').hide();
	}
}

function toggleAvailGenrePref(el){
	if ($(el).find('option:selected').val() == "1") {
		$('.input-row.genre').show();
	} else {
		$('.input-row.genre').hide();
	}
}

function toggleAvailHireAmountPref(el){
	if ($(el).find('option:selected').val() == "Price") {
		$('.input-row.hire-amount-row').show();
	} else {
		$('.input-row.hire-amount-row').hide();
	}
}

function toggleAvailSecurityPref(el){
	if ($(el).find('option:selected').val() == 1) {
		$('.input-row.security-cost-row').hide();
	} else {
		$('.input-row.security-cost-row').show();
	}
}

function showVenueEditLngLatInputs(el)
{
	$('.lng-lat.input-row').toggle();
}

$(window).on('click', function(e){
	if(!$(e.target).parents().andSelf().hasClass('.search-result-container')){
		$('.search-result-inner').remove();
	}

	if(!$(e.target).parents().andSelf().hasClass('view-avail-switcher')){
		$('.avail-view-select .dropdown').hide();
		$('.avail-view-select .select-label .fa').removeClass('fa-angle-up');
		$('.avail-view-select .select-label .fa').addClass('fa-angle-down');
	}
});

var doc_scroll_top = $(document).scrollTop();
var header_is_fixed = false;

//Make header appear on mobile on scroll up :)
$(document).on('scroll', function () {
    if (window.location.pathname != '/') {
        if ($(window).width() < 1025 && $(document).scrollTop() > 100) {
            if (doc_scroll_top < $(document).scrollTop()) { //Scrolling down
                if (header_is_fixed == true) {
                    header_is_fixed = false;
                    $('.header').animate({
                        'margin-top': -$('.header').height()
                    }, 250, function () {
                        $('.header').css('position', '');
                        $('.header').css('left', '');
                        $('.header').css('right', '');
                        $('.header').css('margin-top', '');
                    });
                }

                doc_scroll_top = $(document).scrollTop();
            }
            else { //Scrolling up
                if (header_is_fixed == false) {
                    $('.header').css('position', 'fixed');
                    $('.header').css('left', '8px');
                    $('.header').css('right', '8px');
                    $('.header').css('margin-top', -$('.header').height());
                    $('.header').animate({
                        'margin-top': 0
                    }, 250);
                    header_is_fixed = true;
                }
                doc_scroll_top = $(document).scrollTop();
            }
        }
        else {
            $('.header').css('position', '');
            $('.header').css('margin-top', '');
            $('.header').css('left', '');
            $('.header').css('right', '');
        }
    }
});

function bindTabs()
{
	$('.tab').on('click', function() {
		var tab = $(this);
		if(!tab.hasClass('inactive')){
			var tab_id = tab.data('tab');
			if(!tab.hasClass('active') && !tab.hasClass('open-menu') && !tab.hasClass('close-menu'))
			{
				var tabset = tab.parents("[data-tabset]").data('tabset');
				var tab_content_holder = $('.tab-content-holder[data-tabset="'+tabset+'"]');
				var tab_holder = tab.parents("[data-tabset]");

				tab_holder.find('.active').removeClass('active');
				tab_content_holder.find('.active').removeClass('active');
				tab_content_holder.find('[data-tab="'+tab_id+'"]').addClass('active');
				tab.addClass('active');
				$('.close-menu').click();
			}
		}
	});

	$('.tabs-underlined .tab-label').on('click', function(){
		var tab = $(this);
		var tab_id = $(this).attr('data-id');

		$('.tabs-underlined .tab-label').removeClass('active');
		$('.tab-content').removeClass('active');

		tab.addClass('active');
		$('.tab-content[data-id="'+tab_id+'"]').addClass('active');
	});
}

$(document).ready(function() {

	if(getParameterByName('display') && getParameterByName('search') == 'true')
	{
		toggleGlobalSearchByType(getParameterByName('display'));
	}
	else if(getParameterByName('search') == 'true')
	{
		toggleGlobalSearch();
	}

   	CKEDITOR.config.removePlugins = 'Save,Print,Preview,Find,About,Maximize,ShowBlocks';

	if ($('.recommends-carousel-row').length) {

		$.ajax({
			method: "GET",
			url: '/ajax-load-recommends-carousel'
		})
		.done(function(response) {
			data = JSON.parse(response);

			$('.recommends-carousel-wrap').html(data.html);

			$('.recommends-carousel').owlCarousel({
				'lazyLoad': true,
				'responsive': {
					0: {
						'items': 1,
						'center': true
					},
					700: {
						'items': 2,
						'center': false
					},
					1300: {
						'items': 3
					},
					1500: {
						'items': 4
					}
				},
				'nav': true,
				'navText': [
					'<i class="fa fa-angle-left"></i>',
					'<i class="fa fa-angle-right"></i>'
				],
				slideBy: 4,
				loop: true
			});
			$('.checkout-band .content').matchHeight();

		});
	}

	$('.match-heights').matchHeight();

	$('.news-gallery-carosuel').owlCarousel({
		'items': 1,
		'nav': true,
		'navText': [
		'<i class="fa fa-angle-left"></i>',
		'<i class="fa fa-angle-right"></i>'
		],
		'dots': false,
		'loop': true
	});

	$('.tours-carousel').owlCarousel({
		'items': 1,
		'nav': true,
		'navText': [
		'<i class="fa fa-angle-left"></i>',
		'<i class="fa fa-angle-right"></i>'
		],
		'dots': false,
		'loop': true
	});

	$('.gallery-carousel').owlCarousel({
		'items': 1,
		'autoHeight': true,
		'nav': true,
		'navText': [
		'<i class="fa fa-angle-left"></i>',
		'<i class="fa fa-angle-right"></i>'
		],
		'dots': false,
		'loop': true
	});

	$('body').on('click', function(event) {
		var box = $('.notifications');

		if(box.hasClass('active') && !$(event.target).parents('.notification-holder').length)
		{
			box.removeClass('active');
		}

		if (!$(event.target).parents('.typeahead').length) {
			$('.typeahead').each(function() {
				var input = $(this).find('input[type="text"]');
				var flyout = $(this).find('.flyout');

				input.val('');
				flyout.html('');
				flyout.removeClass('active');
			});
		}

	});

	doNewsMasonary();
	doFanEventsMasonary();

	$('.lineup-item').hover(function() {
		$(this).find('.remove-item').fadeIn();
	}, function() {
		$(this).find('.remove-item').fadeOut();
	});

	$('.account').hover(function() {
		var hover = $(this).children('img').data('hover');
		var original = $(this).children('img').attr('src');
		$(this).children('img').data('hover', original);
		$(this).children('img').attr('src', hover);
	}, function() {
		var original = $(this).children('img').data('hover');
		var hover = $(this).children('img').attr('src');
		$(this).children('img').data('hover', hover);
		$(this).children('img').attr('src', original);
	});

	$('.accordion .accordion-heading').on('click', function() {
		var accordion = $(this).parent();
		var content = accordion.find('.content');
		var heading = $(this).find('.fa');

		if(accordion.hasClass('active'))
		{
			heading.addClass('fa-plus').removeClass('fa-minus');
			content.stop().animate({
				'height': 0,
				'paddingTop': 0
			}, 250, function() {
				accordion.removeClass('active');
				content.css('width', '');
			});
		}
		else
		{
			heading.addClass('fa-minus').removeClass('fa-plus');
			var toHeight = 0;
			content.css('height', 'auto');
			content.css('width', '100%');
			toHeight = content.height()+16;
			content.css('height', 0);
			content.stop().animate({
				'height': toHeight,
				'paddingTop': 16
			}, 250, function() {
				accordion.addClass('active');
			});
		}
	});

	bindTypeaheads();
	bindTabs();
});

$('.event-tabs .tab-title').on('click', function () {
    $('.event-tabs .tab-title').removeClass('active');
    $('.event-tab-content .tab-content').css('display', 'none');

    $(this).addClass('active');
    $('.event-tab-content .tab-content[data-tabid="' + $(this).data('tabid') + '"]').css('display', 'block');
});

function openGalleryModal(slide_id) {
    var modal = $('[data-dialog="gallery"]').remodal();
    modal.open();

    $('.gallery-carousel').trigger('to.owl.carousel', slide_id);
}

var typeahead_throttle;

function bindTypeaheads()
{
	$('.typeahead').each(function() {
		var input = $(this).find('input[type="text"]');
		var flyout = $(this).find('.flyout');

		// input.on('blur', function(e){
		// 	// console.log(e);
		// 	input.val('');
		// 	flyout.html('');
		// 	flyout.removeClass('active');
		// });

		input.on('keyup', function() {
			if (input.val().length > 2) {
				clearTimeout(typeahead_throttle);

				var type = $(this).parents('.typeahead').data('type');
				var limit = $(this).parents('.typeahead').data('limit');
				var existing = $(this).parents('.typeahead').find('input[type="hidden"]').val();
				var flyout = $(this).parents('.typeahead').find('.flyout');
				var connected_only = $(this).parents('.typeahead').data('connected-only');


				flyout.html('');
				flyout.removeClass('active');

				typeahead_throttle = setTimeout(function() {
					$.ajax({
						method: "POST",
						url: url+"/ajax/typeahead",
						data: {
							_token: csrf_token,
							search_string: input.val(),
							type: type,
							limit: limit,
							existing: existing,
							connected_only: connected_only
						}
					})
					.done(function(response) {
						/*
							Because the data returned is key'd by ID, the thing that comes back isn't an array unless there are 0 results
						    (in which case it comes back as an empty array, hence this line being confusing...)
						    Berk
						*/
						if (!Array.isArray(response.data)) {
							flyout.html(response.html);
							flyout.addClass('active');
							flyout.find('.row').on('click', function() {
                                var id = $(this).data('id');
                                var id = $(this).data('id');
								var name = $(this).text();
								var typeahead = $(this).parents('.typeahead');
								var hidden_input = typeahead.find('input.hidden_id');
                                var single = typeahead.data('single');

                                if(typeahead.data('multiple') == 'true') {
                                    if (hidden_input.val() == '') {
                                        var ids = [];
                                        ids.push(id);
                                        hidden_input.val(JSON.stringify(ids));
                                    } else {
                                        var existing_ids = JSON.parse(hidden_input.val());
                                        existing_ids.push(id);
                                        hidden_input.val(JSON.stringify(existing_ids));
                                    }
                                } else {
                                    hidden_input.val(id)
                                }

								var flyout = $(this).parents('.typeahead').find('.flyout');
								var input = $(this).parents('.typeahead').find('input[type="text"]');
								input.val('');
								flyout.html('');
								flyout.removeClass('active');

								typeahead.find('.selected').append('<div class="selected-capsule" data-id="'+id+'" data-id="'+id+'"><span class="name">'+name+'</span><i class="fa fa-close" onclick="removeFromTypeahead(this)"></i></div>');

								if (single) {
									input.addClass('hidden');
								}

								if (typeahead.data('onchange')) {
									eval(typeahead.data('onchange'));
								}
							});
						} else {
							flyout.html(response.html);
							flyout.addClass('active');
						}
					});
				}, 500);
			} else {
				var flyout = $(this).parents('.typeahead').find('.flyout');

				flyout.html('');
				flyout.removeClass('active');
			}
		});
	});
}

function removeFromTypeahead(el)
{
	var typeahead = $(el).parents('.typeahead');
	var capsule = $(el).parents('.selected-capsule');
	var id = capsule.data('id');
	var hidden_input = typeahead.find('input.hidden_id');
	var existing_ids = JSON.parse(hidden_input.val());
	if (existing_ids.length > 1) {
		var index = existing_ids.indexOf(id);
		existing_ids.splice(index, 1);
		hidden_input.val(JSON.stringify(existing_ids));
	} else {
		hidden_input.val('');
	}
	typeahead.find('input.hidden').removeClass('hidden');
	capsule.remove();

	if (typeahead.data('onchange')) {
		eval(typeahead.data('onchange'));
	}
}

function reportComment(id, el)
{
	var endpoint = url+"/ajax/report-comment";
	var formData = {
        id: id,
        _token: csrf_token,
	};
	$.post(endpoint, formData).done(function (data) {
		$(el).css('display', 'none');
		$(el).siblings('.reported').css('display', 'inline-block');
	});
}

function openPostModal(el){
	var openid = $(el).parents('.post').attr('data-postid');
	if ($('.post[data-postid="'+openid+'"] .extra-content .video-link-js').length > 0) {
		$('.post-modal-box[data-postid="'+openid+'"] .news-video-wrap').html($('.post[data-postid="'+openid+'"] .extra-content .video-link-js .featured-image').data('iframe'));
	}
	$('.post-modal-box[data-postid="'+openid+'"]').show();
	$('.news-modal').show();
	$('html, body').css('overflow-y', 'hidden');
	$('html, body').css('position', 'relative');
	$('html, body').css('height', '100%');
}

function closePostModal(){
	$('.post-modal-box').hide();
	$('.post-modal-box .news-video-wrap').empty();
	$('.news-modal').hide();
	$('html, body').css('overflow-y', '');
	$('html, body').css('position', '');
	$('html, body').css('height', '');
}

function openArtstAvailInfo(id, avail_id){
	var endpoint = url+"/ajax/getArtistAvailDetailsDialog";
	var formData = {
		artist_id: id,
        availability_id: avail_id,
        _token: csrf_token
	};
	$.post(endpoint, formData).done(function (data) {
		$('body').append(data.html);
		openDialog(data.name);
		var fans = JSON.parse(data.fans);
		var localFans = 0;
		var lat;
		var lng;
		var distance;

		$.each(fans, function(i, fan) {
			lat = fan.lat;
			lng = fan.lng;
			distance = getDistanceFromCoords(lat, lng, data.userLat, data.userLng);
			if(distance <= 50)
			{
				localFans++;
			}
		});
		$('.available-details .fan-count').text(localFans);
	});
}

function getDistanceFromCoords(lat1, lon1, lat2, lon2)
{
  var R = 6371;
  var dLat = deg2rad(lat2 - lat1);
  var dLon = deg2rad(lon2 - lon1);

  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
          Math.sin(dLon/2) * Math.sin(dLon/2);

  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var km = R * c;
  km = k2m(km);
  return km;
}

function deg2rad(deg)
{
  return deg * (Math.PI/180);
}

function k2m(kilometers)
{
    var km = parseFloat(kilometers);
    var mi = "";
    if (!isNaN(km)) {
        mi = km * 0.621371192;
        return mi.toFixed();
    }
}

$('.news-modal').on('click', function () {
    closePostModal();
});

$('.header .share-holder').on('click', function () {
    $(this).find('.share-flyout').toggle();
});

$('.manage-news table.secondary .share-holder').on('click', function () {
    $(this).find('.share-flyout').toggle();
});

$('.single-event .share-holder').on('click', function () {
    $(this).find('.share-flyout').toggle();
});

$('.single-tour .share-holder').on('click', function () {
    $(this).find('.share-flyout').toggle();
});

$('.popup-message-share-row .share-holder').on('click', function () {
    $(this).find('.share-flyout').toggle();
});

$('.post .share').on('click', function () {
    $(this).find('.share-flyout').toggle();
});

$('.events-table-wrap .share').on('click', function () {
    $(this).find('.share-flyout').toggle();
});

function submitGlobalComment(el, postid) {
    if ($(el).val().length > 0) {
        var endpoint = url + "/ajax/comment-global-post";
        var formData = {
            comment: $(el).val(),
            post_id: postid,
            _token: csrf_token
        };
        $.post(endpoint, formData).done(function (data) {
            if ($('.post-modal-box[data-postid="' + postid + '"] .comments-box').length) {
                $('.post[data-postid="' + postid + '"] .comment-count').text(parseInt($('.post[data-postid="' + postid + '"] .comment-count').text()) + 1);
                $('.post-modal-box[data-postid="' + postid + '"] .comments-box').prepend(data);
                $(el).val('');
                $('.post-modal-box[data-postid="' + postid + '"] .no-comments').remove();
            }
            else {
                $('.mpl-post .comment-count').text(parseInt($('.mpl-post .comment-count').text()) + 1);
                $('.mpl-post .post-modal-box .comments-box').prepend(data);
                $(el).val('');
                $('.mpl-post .post-modal-box .no-comments').remove();
            }
        });
    }
    else {
        alert('You cannot post an empty comment');
    }
}

function submitComment(el, postid) {
    if ($(el).val().length > 0) {
        var endpoint = url + "/ajax/comment-post";
        var formData = {
            comment: $(el).val(),
            post_id: postid,
            _token: csrf_token,
        };
        $.post(endpoint, formData).done(function (data) {
            $('.post[data-postid="' + postid + '"] .comment-count').text(parseInt($('.post[data-postid="' + postid + '"] .comment-count').text()) + 1);
            $('.post-modal-box[data-postid="' + postid + '"] .comments-box').prepend(data);
            $(el).val('');
            $('.post-modal-box[data-postid="' + postid + '"] .no-comments').remove();
        });
    }
    else {
        alert('You cannot post an empty comment');
    }
}

function submitTourComment(el, tourid) {
    if ($(el).val().length > 0) {
        var endpoint = url + "/ajax/comment-tour";
        var formData = {
            comment: $(el).val(),
            post_id: tourid,
            _token: csrf_token
        };
        $.post(endpoint, formData).done(function (data) {
            $('.single-tour .comments .comment-count').text(parseInt($('.single-tour .comments .comment-count').text()) + 1);
            $('.single-tour .comments .comments-box').prepend(data);
            $(el).val('');
            $('.single-tour .comments .no-comments').remove();
        });
    }
    else {
        alert('You cannot post an empty comment');
    }
}

function submitEventComment(el, eventid) {
    if ($(el).val().length > 0) {
        var endpoint = url + "/ajax/comment-event";
        var formData = {
            comment: $(el).val(),
            post_id: eventid,
            _token: csrf_token
        };
        $.post(endpoint, formData).done(function (data) {
            $('.single-event .comments .comment-count').text(parseInt($('.single-event .comments .comment-count').text()) + 1);
            $('.single-event .comments .comments-box').prepend(data);
            $(el).val('');
            $('.single-event .comments .no-comments').remove();
        });
    }
    else {
        alert('You cannot post an empty comment');
    }
}

function toggleGlobalPostLike(id) {
    var endpoint = url + "/ajax/like-global-post";
    var formData = {
        post: id,
        _token: csrf_token
    };

    $.post(endpoint, formData).done(function (data) {
        var result = JSON.parse(data);

        if ($('.post[data-postid="' + id + '"]').length) {
            if (result.liked == 1) {
                $('.post[data-postid="' + id + '"]').each(function () {
                    $(this).find('.share-row .likes').addClass('liked');
                    $(this).find('.share-row .likes .count').text(parseInt($(this).find('.share-row.share-row-js .likes .count').text()) + 1);
                });
            }
            else {
                $('.post[data-postid="' + id + '"]').each(function () {
                    $(this).find('.share-row .likes').removeClass('liked');
                    $(this).find('.share-row .likes .count').text(parseInt($(this).find('.share-row.share-row-js .likes .count').text()) - 1);
                });
            }
        }
        else {
            if (result.liked == 1) {
                $('.mpl-post.post').find('.share-row .likes').addClass('liked');
                $('.mpl-post.post').find('.share-row .likes .count').text(parseInt($('.mpl-post .post-modal-box').find('.share-row .likes .count').text()) + 1);
            }
            else {
                $('.mpl-post.post').find('.share-row .likes').removeClass('liked');
                $('.mpl-post.post').find('.share-row .likes .count').text(parseInt($('.mpl-post .post-modal-box').find('.share-row .likes .count').text()) - 1);

            }
        }


        $('.news-gallery-carosuel').owlCarousel('destroy');
        $('.news-gallery-carosuel').owlCarousel({
            'items': 1,
            'nav': true,
            'navText': [
                '<i class="fa fa-angle-left"></i>',
                '<i class="fa fa-angle-right"></i>'
            ],
            'dots': false,
            'loop': true
        });
    });
}

function togglePostLike(id) {
    var endpoint = url + "/ajax/like-post";
    var formData = {
        post: id,
        _token: csrf_token,
    };
    $.post(endpoint, formData).done(function (data) {
        var result = JSON.parse(data);

        if (result.liked == 1) {
            $('.post[data-postid="' + id + '"]').each(function () {
                $(this).find('.share-row .likes').addClass('liked');
                $(this).find('.share-row .likes .count').text(parseInt($(this).find('.share-row.share-row-js .likes .count').text()) + 1);
            });
        }
        else {
            $('.post[data-postid="' + id + '"]').each(function () {
                $(this).find('.share-row .likes').removeClass('liked');
                $(this).find('.share-row .likes .count').text(parseInt($(this).find('.share-row.share-row-js .likes .count').text()) - 1);
            });
        }

        $('.news-gallery-carosuel').owlCarousel('destroy');
        $('.news-gallery-carosuel').owlCarousel({
            'items': 1,
            'nav': true,
            'navText': [
                '<i class="fa fa-angle-left"></i>',
                '<i class="fa fa-angle-right"></i>'
            ],
            'dots': false,
            'loop': true
        });
    });
}

function toggleEventMenu(el) {
    var share = $(el).siblings('.rsvp');
    var rsvp = $(el).siblings('.share');
    if (share.hasClass('active')) {
        share.removeClass('active');
        rsvp.removeClass('active');
        return false;
    }
    $('.menu-container .rsvp').removeClass('active');
    $('.menu-container .share').removeClass('active');
    share.toggleClass('active');
    rsvp.toggleClass('active');
}

function toggleCommentLike(id) {
    var endpoint = url + "/ajax/like-comment";
    var formData = {
        comment: id,
        _token: csrf_token,
    };
    $.post(endpoint, formData).done(function (data) {
        var result = JSON.parse(data);

        if (result.liked == 1) {
            $('.comments-box .comment[data-id="' + id + '"] .likes').addClass('liked');
            $('.comments-box .comment[data-id="' + id + '"] .likes .count').html(parseInt($('.comments-box .comment[data-id="' + id + '"] .likes .count').html()) + 1);
        } else {
            $('.comments-box .comment[data-id="' + id + '"] .likes').removeClass('liked');
            $('.comments-box .comment[data-id="' + id + '"] .likes .count').html(parseInt($('.comments-box .comment[data-id="' + id + '"] .likes .count').html()) - 1);
        }
    });
}


function deleteComment(id) {
    var endpoint = url + "/ajax/delete-comment";
    var formData = {
        comment: id,
        _token: csrf_token,
    };
    $.post(endpoint, formData).done(function (data) {
        var postid = $('.comments-box .comment[data-id="' + id + '"]').parents('.post').data('postid');
        $('.post[data-postid="' + postid + '"] .comment-count').text(parseInt($('.post[data-postid="' + postid + '"] .comment-count').text()) - 1);
        $('.single-tour .comments .comment-count').text(parseInt($('.single-tour .comments .comment-count').text()) - 1);
        $('.single-event .comments .comment-count').text(parseInt($('.single-event .comments .comment-count').text()) - 1);
        $('.comments-box .comment[data-id="' + id + '"]').remove();
    });
}

document.addEventListener('gesturestart', function (e) {
    e.preventDefault();
});

var modal;

function openDialog(dialog_name) {
    modal = $('[data-dialog="' + dialog_name + '"]').remodal();
    modal.open();
}

function openSpecificLoginDialog(dialog_name, return_url) {
    modal = $('[data-dialog="' + dialog_name + '"]').remodal();
    modal.open();

    $('input[name="return_url"]').remove();
    $('.dialog[data-dialog="' + dialog_name + '"]').find('form').append('<input type="hidden" class="hidden" name="return_url" value="' + return_url + '">');
}

function changeTicketTotal(el) {
    var total = 0;

    $('.ticket-purchase .ticket-selects').each(function () {
        var price = parseFloat($(this).data('price'));
        var quantity = parseInt($(this).val());
        total += price * quantity;
    });

    $('.ticket-purchase .totals .value').text(total.toFixed(2));
}

function validateTicketOrder() {
    var total_tickets = 0;

    $('.ticket-purchase .ticket-selects').each(function () {
        var quantity = parseInt($(this).val());
        total_tickets += quantity;
    });

    if (total_tickets > 0) {
        return true;
    }
    else {
        alert('You have not selected any tickets, please try again');
        return false;
    }
}

function openTicketPurchaseDialog(event_id) {
    $.ajax({
        method: "POST",
        url: url + "/ajax/get-ticket-dialog",
        data: {
            event_id: event_id,
            _token: csrf_token
        }
    })
        .done(function (response) {
            $('[data-dialog="ticket-purchase"] .content').html(response.html);
            modal = $('[data-dialog="ticket-purchase"]').remodal();
            modal.open();
        });
}

function callAjax(link, callback) {
    $.ajax({
        method: "GET",
        url: link
    })
        .done(function (response) {
            eval(callback);
        });
}

function openSearchFilter(name) {
    $('.type-dropdown').hide();
    $('.quick-search').hide();

    $('.' + name).show();
}

function toggleButtons(id) {
    if ($('.off[data-btn="' + id + '"]').css('display') == 'inline-block') {
        $('.off[data-btn="' + id + '"]').css('display', 'none');
        $('.on[data-btn="' + id + '"]').css('display', 'inline-block');
    }
    else {
        $('.on[data-btn="' + id + '"]').css('display', 'none');
        $('.off[data-btn="' + id + '"]').css('display', 'inline-block');
    }
}

function openBasicDialog(title, content) {
    var html = '<div class="dialog basic" data-dialog="basic">\
	<button data-remodal-action="close" class="remodal-close"></button>\
	<div class="heading">\
	' + title + '\
	</div>\
	<div class="constrainer">\
	<div class="content">\
	' + content + '\
	</div>\
	</div>\
	</div>';
    $('body').append(html);
    modal = $('[data-dialog="basic"]').remodal();
    modal.open();
}

var account_nav = false;

function toggleAccountNav() {
    if (!account_nav) {
        if (global_search) {
            toggleGlobalSearch();
        }

        $('.header').addClass('menu-open');

        $('html, body').css('overflow', 'hidden');

        $('.full-size-menu').css({
            'display': 'block'
        }).stop().animate({
            'opacity': 1
        }, 250, function () {
            account_nav = true;
        });
    }
    else {
        $('.header').removeClass('menu-open');

        $('html, body').css('overflow', '');

        $('.full-size-menu').stop().animate({
            'opacity': 0
        }, 250, function () {
            $('.full-size-menu').css('display', 'none');
            account_nav = false;
        });
    }

    $('#nav-icon3').toggleClass('open');
}

$('.full-size-menu .parent-title').on('click', function () {
    $(this).parents('.inner-wrap').toggleClass('opened-sub')
    $('.full-size-menu .sub-items[data-id="' + $(this).attr('data-id') + '"]').toggleClass('open');
});

function closeMenuSubItems(el) {
    $('.full-size-menu .inner-wrap').removeClass('opened-sub');
    $('.full-size-menu .sub-items').removeClass('open');
}

function scrollToEl(el) {
    $("html, body").animate({
        scrollTop: $(el).offset().top - 60
    }, 1000);
}

function goToEventAddStep(step) {
    $('.add-event-dialog .form-step.active, .edit-event-dialog .form-step.active').removeClass('active');
    $('.add-event-dialog .form-step[data-step="' + step + '"], .edit-event-dialog .form-step[data-step="' + step + '"]').addClass('active');
}

function removeTicketRow(id) {
    var table = $('.dialog .ticket-table');
    table.find('[data-row="' + id + '"]').remove();
}

function addTicketType() {
    var table = $('.dialog .ticket-table');
    var row_count = table.find('tbody').children('tr').length;

    if (table.parents('.edit-event-dialog').length > 0) {
        row_count = 'new-' + row_count;
    }

    var html = '\
		<tr data-row="' + row_count + '">\
			<td><input type="text" class="primary" name="tickets[' + row_count + '][name]" placeholder="e.g. General Admission"></td>\
			<td class="allocation-input"><input type="number" class="primary" data-min="0" name="tickets[' + row_count + '][qty]" placeholder="e.g. 100"></td>\
			<td class="price-input"><input type="text" onkeyup="setMinimumBookingFee(this)" class="primary" name="tickets[' + row_count + '][price]" placeholder="e.g. 10.00"></td>\
			<td class="fee-input"><input type="text" onkeyup="validateBookingFee(this)" class="primary" name="tickets[' + row_count + '][fee]" placeholder="e.g. 1.00"></td>\
			<td><i class="fa fa-close" onclick="removeTicketRow(\'' + row_count + '\')"></i></td>\
		</tr>\
	';
    table.find('tbody').append(html);
}

function changeTicketingType(type) {
    $('.add-event-dialog input[name="ticketing"], .edit-event-dialog input[name="ticketing"]').val(type);
}

var is_artist_adding_event = false;

function validateAddEventForm() {
    $('.add-event-dialog .errors').html('');
    $('.add-event-dialog .errors').css('display', 'none');

    var errors = [];

    var form = $('.add-event-dialog');
    var table = $('.add-event-dialog .ticket-table');
    var row_count = table.find('tbody').children('tr').length;

    var name = form.find('input[name="name"]');
    var doors = form.find('input[name="doors"]');
    var artist_ids = form.find('input[name="artist_ids"]');
    var ticketing = form.find('input[name="ticketing"]');

    if (name.val() == '') {
        errors.push('Event name is empty.');
    }

    if (is_artist_adding_event) {
        if ($('input[name="venue_id"]').val() == '' || $('input[name="selected_venue"]').val() == '') {
            errors.push('You must select a venue to add an event');
        }
    }

    if (doors.val() == '') {
        errors.push('You did not enter the doors time.');
    }

    if (artist_ids.val() == '') {
        errors.push('You didn\'t select any artists.');
    }

    if (ticketing.val() == 'internal') {
        for (var i = 0; i < row_count; i++) {
            // if(
            // 	$('input[name="tickets['+i+'][name]"]').val() == '' ||
            // 	$('input[name="tickets['+i+'][qty]"]').val() == '' ||
            // 	!parseInt($('input[name="tickets['+i+'][qty]"]').val()) > 0 ||
            // 	$('input[name="tickets['+i+'][price]"]').val() == '' ||
            // 	!$.isNumeric(parseFloat($('input[name="tickets['+i+'][price]"]').val())) ||
            // 	$('input[name="tickets['+i+'][fee]"]').val() == '' ||
            // 	!$.isNumeric(parseFloat($('input[name="tickets['+i+'][fee]"]').val()))
            // )
            // {
            // 		errors.push('Ticket type '+(i+1)+' is invalid.');
            // }
        }
    }
    else if (ticketing.val() == 'external') {
        var external_ticketing_link = form.find('input[name="external_ticketing_link"]');

        if (external_ticketing_link.val() == '') {
            //errors.push('External ticket link is invalid.');
        }
    }

    if (errors.length > 0) {
        for (x in errors) {
            $('.add-event-dialog .errors').append('<div class="error">' + errors[x] + '</div>');
        }

        $('.add-event-dialog .errors').css('display', 'block');

        goToEventAddStep(1);
    }
    else {
        $('.add-event-form').submit();
    }
}

var header_background = 0;

var genreAutocompleteTimeout;

function genreAutocomplete(el, results, selected, excluding)
{
	clearTimeout(genreAutocompleteTimeout);
	if($(el).val().length > 2)
	{
		genreAutocompleteTimeout = setTimeout(function() {
			results.css('display', 'none');
			results.html('');
			var search = $(el).val();
			$.ajax({
				method: "POST",
				url: url+"/ajax/genre-autocomplete",
				data: {
					search: search,
					excluding: excluding,
					_token: csrf_token
				}
			})
			.done(function(response) {
				results.html(response.html);
				results.css('display', 'block');
				$(selected).css('display', 'block');
				results.find('.genre').on('click', function() {
					results.css('display', 'none');
					results.html('');
					var genre_id = $(this).data('id');
					var genre_label = $(this).data('name');
					genreAutocompleteAddGenre(genre_id, selected);
					$(el).val('');
					$(selected).append('<div class="selected-genre">'+genre_label+'<span class="remove" onclick="genreAutocompleteRemoveGenre(\''+genre_id+'\', \''+selected+'\'); $(this).parent().remove()"><i class="fa fa-close"></i></span></div>');
				});
			});
		}, 500);
	}
	else
	{
		results.css('display', 'none');
		results.html('');
	}
}

function genreAutocompleteAddGenre(id, selected)
{
	var current_genres_string = $(selected).find('.hidden-genres').val();
	if(current_genres_string == '')
	{
		var current_genres = [];
	}
	else
	{
		var current_genres = current_genres_string.split(":");
	}
	current_genres.push(id);
	$(selected).find('.hidden-genres').val(current_genres.join(":"));
}

function genreAutocompleteRemoveGenre(id, selected)
{
	var current_genres_string = $(selected).find('.hidden-genres').val();
	var current_genres = current_genres_string.split(":");
	var index = current_genres.indexOf(id);
	current_genres.splice(index, 1);
	if(current_genres.length == 0)
	{
		$(selected).css('display', 'none');
	}
	$(selected).find('.hidden-genres').val(current_genres.join(":"));
}

function searchGenreAutocompleteRemoveGenre(id, selected)
{
	var current_genres_string = $(selected).find('.hidden-genres').val();
	var current_genres = current_genres_string.split(":");
	var index = current_genres.indexOf(id);
	current_genres.splice(index, 1);
	if(current_genres.length == 0)
	{
		$(selected).css('display', 'none');
	}

	$(selected).find('.hidden-genres').val(current_genres.join(":"));
	doGlobalSearch();
}

function searchGenreAutocomplete(el, results, selected, excluding)
{
	clearTimeout(genreAutocompleteTimeout);
	if($(el).val().length > 2)
	{
		genreAutocompleteTimeout = setTimeout(function() {
			results.css('display', 'none');
			results.html('');
			var search = $(el).val();
			$.ajax({
				method: "POST",
				url: url+"/ajax/genre-autocomplete",
				data: {
					search: search,
					excluding: excluding,
					_token: csrf_token
				}
			})
			.done(function(response) {
				results.html(response.html);
				results.css('display', 'block');
				$(selected).css('display', 'inline-block');
				results.find('.genre').on('click', function() {
					results.css('display', 'none');
					results.html('');
					var genre_id = $(this).data('id');
					var genre_label = $(this).data('name');
					genreAutocompleteAddGenre(genre_id, selected);
					$(el).val('');
					$(selected).append('<div class="selected-genre">'+genre_label+'<span class="remove" onclick="searchGenreAutocompleteRemoveGenre(\''+genre_id+'\', \''+selected+'\'); $(this).parent().remove()"><i class="fa fa-close"></i></span></div>');
					doGlobalSearch();
				});
			});
		}, 500);
	}
	else
	{
		results.css('display', 'none');
		results.html('');
	}
}

var global_search = false;

function closeGlobalSearch() {
    $('.global-search').removeClass('active');
    if ($('.header').hasClass('black-version')) {
        $('.header').css('background', '#232323');
    }
    else {
        $('.header').css('background', 'transparent');
    }
    $('.header-gradient').css('display', 'block');
    $('html, body').css({
        'overflow-y': 'auto',
        height: 'auto'
    });
    global_search = false;
    history.pushState({state: 1}, document.title, window.location.pathname);
}

function toggleGlobalSearch() {
    if (!global_search) {
        if (account_nav) {
            toggleAccountNav();
        }

        $('.global-search').addClass('active');
        $('.header').css('background', '#70C6AE');
        $('.header-gradient').css('display', 'none');
        $('html, body').css({
            'overflow-y': 'hidden',
            height: '100%'
        });
        $('.global-search-box').focus();
        global_search = true;
        history.pushState({state: 1}, "Music Planet Live - Search", "?search=true");
    }
    else {
        $('.global-search').removeClass('active');
        if ($('.header').hasClass('black-version')) {
            $('.header').css('background', '#232323');
        }
        else {
            $('.header').css('background', 'transparent');
        }
        $('.header-gradient').css('display', 'block');
        $('html, body').css({
            'overflow-y': 'auto',
            height: 'auto'
        });
        global_search = false;
        history.pushState({state: 1}, document.title, window.location.pathname);
    }
}

function toggleGlobalSearchByType(type) {
    if (account_nav) {
        toggleAccountNav();
    }

    $('.global-search').addClass('active');
    $('.header').css('background', '#70C6AE');
    $('.header-gradient').css('display', 'none');
    $('html, body').css({
        'overflow-y': 'hidden',
        height: '100%'
    });
    $('.global-search-box').focus();
    global_search = true;

    doGlobalSearchSingleType(type);
}

var global_search_timeout;

function doGlobalSearch()
{
	var search = $('.global-search-box').val();
	var genres = $('.global-search .hidden-genres').val();
	clearTimeout(global_search_timeout);

	if(typeof search !== "undefined") {
		if(search.length > 2)
		{
			global_search_timeout = setTimeout(function() {
				$.ajax({
					method: "POST",
					url: url+"/ajax/global-search",
					data: {
						search: search,
						type: 'all',
						genre_list: genres,
						_token: csrf_token
					}
				})
				.done(function(response) {
					$('.global-search .results').html(response.html);
					$('.global-search .results').css('display', 'block');
					$('.global-search .genre-filter').css('display', 'block');

					$('.global-search .quick-results-row .column').matchHeight();

					$('.carousel-version .owl-carousel').owlCarousel({
						'responsive': {
							0: {
								'items': 1
							},
							350: {
								'items': 2
							},
							600: {
								'items': 3
							},
							800: {
								'items': 4
							},
							1099: {
								'items': 5
							}
						},
						'items': 5,
						'loop': true,
						'margin': 12,
						'navText': [
						'<i class="fa fa-chevron-left"></i>',
						'<i class="fa fa-chevron-right"></i>'
						],
						'nav': true
					});
				});
			}, 500);
		}
		else
		{
			$('.global-search .results').css('display', 'none');
		}
	}
}

function setEnquiryFormDate(date)
{
	$('.enquiry-add-dialog input[name="date"]').val(date);
}

function setPencilFormDate(date)
{
	$('.pencil-add-dialog input[name="date"]').val(date);
}

var global_search_single_total = 0;
var global_search_single_showing = 0;
var global_search_single_type;

function doGlobalSearchSingleType(type) {
    var search = $('.global-search-box').val();
    var genres = $('.global-search .hidden-genres').val();
    global_search_single_type = type;
    // console.log('type: ' + global_search_single_type);
    clearTimeout(global_search_timeout);

    if (search.length > 2) {
        global_search_timeout = setTimeout(function () {
            $.ajax({
                method: "POST",
                url: url + "/ajax/global-search",
                data: {
                    search: search,
                    type: global_search_single_type,
                    genre_list: genres,
                    _token: csrf_token
                }
            })
                .done(function (response) {
                    $('.global-search .results').html(response.html);
                    global_search_single_total = $('input[name="total_quick_search_items"]').val();
                    global_search_single_showing = $('.quick-results-single-items .global-search-up').length;
                    $('.global-search .results').css('display', 'block');
                    if (global_search_single_showing >= global_search_single_total) {
                        $('.quick-results-row-single .load-more-btn-row').css('display', 'none');
                    }
                    $('.quick-results-row-single .global-search-up').matchHeight();
                    history.pushState({state: 1}, "Music Planet Live - Search", "?search=true&display=" + global_search_single_type);
                });
        }, 500);
    }
    else {
        $('.global-search .results').css('display', 'none');
    }
}

function goBackToAllGlobalResults() {
    doGlobalSearch();
    history.pushState({state: 1}, "Music Planet Live - Search", "?search=true");
}

function getMoreGlobalSingleResults() {
    var search = $('.global-search-box').val();

    $.ajax({
        method: "POST",
        url: url + "/ajax/global-search-get-more-items",
        data: {
            search: search,
            showing: global_search_single_showing,
            type: global_search_single_type,
            _token: csrf_token
        }
    })
        .done(function (response) {
            $('.global-search .quick-results-single-items').append(response.html);

            global_search_single_total = $('input[name="total_quick_search_items"]').val();
            global_search_single_showing = $('.quick-results-single-items .global-search-up').length;

            if (global_search_single_showing >= global_search_single_total) {
                $('.quick-results-row-single .load-more-btn-row').css('display', 'none');
            }
            $('.quick-results-row-single .global-search-up').matchHeight();
        });
}

function toggleMobileTabMenu() {
    $('.tab-inner').toggleClass('open');
}

function checkerChange(el) {
    var new_id = $(el).data('id');
    var new_partial = $(el).data('partial');

    $(el).siblings('.checker-wrap').children('.checker').removeClass('checked');
    $(el).children('.checker').addClass('checked');

    $(el).siblings('input').prop('checked', false);
    $(el).siblings('input[value="' + new_id + '"]').prop('checked', true);

    $('.extra-content-row').hide();
    if (new_partial != "") {
        $('.extra-content-row.' + new_partial).show();
    }
}

function deleteGalleryImage(id) {
    if (confirm("Are you sure you wish to delete this image?") == true) {
        var form = document.getElementById('deleteGalleryImageForm_'+id)
        form.submit()
    } else {
        return false;
    }
}

function doNewsMasonary() {
    $('.news-masonry-grid').masonry({
        columnWidth: 420,
        fitWidth: true,
        itemSelector: '.post-wrap'
    });
}

function doFanEventsMasonary() {
    $('.fan-events-masonry-grid').masonry({
        columnWidth: 400,
        fitWidth: true,
        itemSelector: '.post-wrap'
    });
}

function decrementNotificationCount() {
    var current_count = parseInt($('.notification-holder .notification-counter').text());
    $('.notification-counter').text(current_count - 1);

    if (current_count - 1 == 0) {
        $('.notification-holder').removeClass('active');
    }
}

function incrementNotificationCount() {
    $('.notification-holder .notification-counter').text(parseInt($('.notification-holder .notification-counter').text()) + 1);

    if (!$('.notification-holder').hasClass('active')) {
        $('.notification-holder').addClass('active');
    }
}

function openNewNotification(html) {
    if (!$('.header .notifications').hasClass('active')) {
        $('.new-notification-flyout .notification').html(html);
        $('.new-notification-flyout').addClass('active');
        setTimeout(function () {
            $('.new-notification-flyout').removeClass('active');
        }, 5000);
    }
}

function toggleNotificationDropdown(e) {
    if ($(e.target).hasClass('notification-counter') || $(e.target).hasClass('fa-bell')) {
        var box = $('.notifications');

        $('.new-notification-flyout').removeClass('active');

        if (box.hasClass('active')) {
            box.removeClass('active');
        }
        else {
            box.addClass('active');
            fixNotificationHeights();
        }
    }
}

function openExternalTicketLinkDialog(link) {
    openDialog('external-ticket-link');
    $('.external-ticket-link .external-ticketing-link-btn').attr('href', link);
}

function actionNotification(id, callback_url) {
    $.ajax({
        method: "POST",
        url: url + '/notification-action',
        data: {
            'notification_id': id,
            '_token': csrf_token
        }
    })
        .done(function (response) {
            location.href = callback_url;
        });
}

function fixNotificationHeights() {
    $('.header .notification').each(function () {
        var height = parseInt($(this).css('height').replace('px', '')) - parseInt($(this).css('padding-top').replace('px', '')) - parseInt($(this).css('padding-bottom').replace('px', ''));
        $(this).find('.image-holder').css('margin-bottom', height - $(this).find('.image-holder').height() + 'px');
    });
}

function openEditEventDialog(id) {
    $.ajax({
        method: "POST",
        url: url + '/get-event-edit-dialog',
        data: {
            'event_id': id,
            '_token': csrf_token
        }
    })
        .done(function (response) {
            $('.edit-event-dialog .content').html(response.html);
            bindArtistSelector();
            openDialog('edit-event');
            bindTypeaheads();
            $('#wysiwyg').ckeditor();
            $('.match-heights').matchHeight();
            $('.edit-event-dialog .time').pickatime({
                format: 'h:i A',
                formatSubmit: 'HH:i'
            });
            bindTabs();
        });
}

function clearNotification(id) {
    $.ajax({
        method: "POST",
        url: url + '/notification-clear',
        data: {
            'notification_id': id,
            '_token': csrf_token
        }
    });

    $('.header [data-notification="' + id + '"]').animate({
        'opacity': 0
    }, 250, function () {
        $(this).remove();
        decrementNotificationCount();

        if ($('.header .notifications .notification-inner .notification').length == 0) {
            $('.header .notifications .notification-inner').append('<div class="no-notifications">You currently have no new notifications</div>');
        }
    });
}

var alreadyFoundLink = false;
var typingTimer;

function checkForLinksInText(input, hiddenFieldWrapper) {
    clearTimeout(typingTimer);
    typingTimer = setTimeout(function () {

        if ((/(?:(?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?:\w+:\w+@)?((?:(?:[-\w\d{1-3}]+\.)+(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|edu|co\.uk|ac\.uk|it|fr|tv|museum|asia|local|travel|[a-z]{2}))|((\b25[0-5]\b|\b[2][0-4][0-9]\b|\b[0-1]?[0-9]?[0-9]\b)(\.(\b25[0-5]\b|\b[2][0-4][0-9]\b|\b[0-1]?[0-9]?[0-9]\b)){3}))(?::[\d]{1,5})?(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?:#(?:[-\w~!$ |\/.,*:;=]|%[a-f\d]{2})*)?/).test($(input).val()) && (alreadyFoundLink == false || alreadyFoundLink != $(input).val().match(/(https?:\/\/[^\s]+)/g))) {

            var curl_url = $(input).val().match(/(https?:\/\/[^\s]+)/g);

            var endpoint = url + "/ajax/curl-for-og";
            var formData = {
                url: curl_url,
                _token: csrf_token
            };
            $.post(endpoint, formData).done(function (data) {
                var meta = JSON.parse(data);
                $(hiddenFieldWrapper).find('.content').empty();
                $(hiddenFieldWrapper).find('.content').append(meta.html);

                $(hiddenFieldWrapper).find('.og-title').val(meta.title);
                $(hiddenFieldWrapper).find('.og-description').val(meta.description);
                $(hiddenFieldWrapper).find('.og-image').val(meta.image);
                $(hiddenFieldWrapper).find('.og-href').val(meta.url);
            });

            alreadyFoundLink = curl_url;
        }
        else if (!(/(?:(?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?:\w+:\w+@)?((?:(?:[-\w\d{1-3}]+\.)+(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|edu|co\.uk|ac\.uk|it|fr|tv|museum|asia|local|travel|[a-z]{2}))|((\b25[0-5]\b|\b[2][0-4][0-9]\b|\b[0-1]?[0-9]?[0-9]\b)(\.(\b25[0-5]\b|\b[2][0-4][0-9]\b|\b[0-1]?[0-9]?[0-9]\b)){3}))(?::[\d]{1,5})?(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?:#(?:[-\w~!$ |\/.,*:;=]|%[a-f\d]{2})*)?/).test($(input).val())) {
            alreadyFoundLink = false;
        }

    }, 1000);
}

if (typeof genre_list == 'undefined') {
    var genre_list = [];
}

function toggleCheck(el) {
    var checkbox = $(el).siblings('input[type="checkbox"]');
    checkbox.prop("checked", !checkbox.prop("checked"));
    // console.log(genre_list);
    if (checkbox.is(':checked') && $.inArray(checkbox.val(), genre_list)) {
        genre_list.push(checkbox.val());
        $(el).addClass('selected');
    }
    else if (!checkbox.is(':checked')) {
        genre_list.splice($.inArray(checkbox.val(), genre_list), 1);
        $(el).removeClass('selected');
    }
    // console.log(genre_list);
    $('.hidden-genres').val(genre_list);
}

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

function bindGeolocationOnQuickRegister() {
    var autocomplete2;

    autocomplete2 = new google.maps.places.Autocomplete($('.member-location-autocomplete')[0]);

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            var bounds = new google.maps.LatLngBounds(
                new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
                new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
            );
            autocomplete2.setBounds(bounds);
        });
    }

    autocomplete2.addListener('place_changed', function () {
        var place = autocomplete2.getPlace();
        var arrAddress = place.address_components;
        $('.hidden-lat').val(place.geometry.location.lat);
        $('.hidden-lng').val(place.geometry.location.lng);
        $.each(arrAddress, function (i, address_component) {
            if (address_component.types[0] == "locality") {
                $('.hidden-city').val(address_component.long_name);
            }
            if (address_component.types[0] == "country") {
                $('.hidden-country').val(address_component.long_name);
            }
        });
    });
}

function openShareFlyout(el) {
    var flyout = $(el).find('.share-flyout');
    if (flyout.hasClass('active')) {
        flyout.removeClass('active');
    }
    else {
        flyout.addClass('active');
    }
}

function hideMobileCalendarUXDialog() {
    createCookie('hide_calendar_ux_dialog', '1', 365);
    modal.close();
}

function turnOffSigninMessage() {
    modal.close();
    $.ajax({
        method: "GET",
        url: '/ajax-turn-off-signin-message'
    })
        .done(function (response) {
            // console.log(response);
        });
}

function createCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

function setMinimumBookingFee(el) {
    var value = $(el).val().replace('£', '');
    $(el).val(value);
    var fee = '0.50';

    if ($.isNumeric(value)) {
        fee = 0.5;
    }

    $(el).parent('td').siblings('.fee-input').children('input').val(fee);
    validateBookingFee($(el).parent('td').siblings('.fee-input').children('input')[0]);
}

function validateBookingFees() {
    if ($('input[name="ticketing"]').val() == 'internal') {
        var error = false;

        $('.fee-input').each(function () {
            if (!validateBookingFee($(this).children('input')[0])) {
                error = true;
            }
        });

        if (error) {
            alert('Please ensure that your booking fees are between the minimum and maximum thresholds');
            return false;
        }
        else {
            return true;
        }
    }
    else {
        return true;
    }
}

function validateBookingFee(el) {
    $(el).removeClass('invalid');
    $(el).removeClass('valid');

    var fee = $(el).val();
    var cost = $(el).parent('td').siblings('.price-input').children('input').val();

    var error = false;

    if (cost !== '') {
        if ($.isNumeric(cost) && $.isNumeric(fee)) {
            if (fee >= 0.5 && fee <= 3) {
                $(el).addClass('valid');
            }
            else {
                error = true;
            }
        }
        else {
            error = true;
        }

        if (error) {
            $(el).addClass('invalid');
            return false;
        }
        else {
            return true;
        }
    }
    else {
        return false;
    }
}

function validateAllocationChanges() {
    if ($('input[name="ticketing"]').val() == 'internal') {
        var error = false;

        $('.allocation-input').each(function () {
            if (!validateAllocationChange($(this).children('input')[0])) {
                error = true;
            }
        });

        if (error) {
            alert('The allocation you\'ve entered is below the number of purchased tickets, you may increase this allocation or cancel your event and create a new one.');
            return false;
        }
        else {
            return true;
        }
    }
    else {
        return true;
    }
}

function validateAllocationChange(el) {
    $(el).removeClass('valid');
    $(el).removeClass('invalid');

    var allocation = $(el).val();
    var min_allocation = $(el).data('min');
    var error = false;

    if ($.isNumeric(allocation) && $.isNumeric(min_allocation)) {
        if (allocation < min_allocation) {
            error = true;
        }
    }
    else {
        error = true;
    }

    if (!error) {
        $(el).addClass('valid');
        return true;
    }
    else {
        $(el).addClass('invalid');
        return false;
    }
}

function saveCroppieImage() {
    $croppie.croppie('result', {
        type: 'base64',
        size: 'original'
    }).then(function (image_url) {
        $('.image-manipulation .image-data').val(image_url);
        $('.image-manipulation form').submit();
    });
}

function openPictureUploadDialog(input, title, vp_width, vp_height, b_width, b_height, type) {
    if (input.files && input.files[0]) {
        if (input.files[0].type.match('image.*')) {
            var reader = new FileReader();

            reader.onload = function (e) {

                $('.image-manipulation .heading').text(title);
                openDialog('image-manipulation');

                $('.image-manipulation .croppie').html('');
                $('.image-manipulation .type').val(type);

                // console.log();

                if (window.innerWidth < 700) {
                    $croppie = $('.image-manipulation .croppie').croppie({
                        url: e.target.result,
                        viewport: {
                            width: vp_width / 3,
                            height: vp_height / 3,
                            type: 'square'
                        },
                        boundary: {
                            width: '100%',
                            height: 200
                        },
                        enableOrientation: true,
                        orientation: 1
                    });
                }
                else {
                    $croppie = $('.image-manipulation .croppie').croppie({
                        url: e.target.result,
                        viewport: {
                            width: vp_width,
                            height: vp_height,
                            type: 'square'
                        },
                        boundary: {
                            width: b_width,
                            height: b_height
                        },
                        enableOrientation: true,
                        orientation: 1
                    });
                }


                $('.image-manipulation .rotate-left').off('click').on('click', function () {
                    $croppie.croppie('rotate', -90);
                });

                $('.image-manipulation .rotate-right').off('click').on('click', function () {
                    $croppie.croppie('rotate', 90);
                });
            }

            reader.readAsDataURL(input.files[0]);
        }
        else {
            alert('You did not select a valid image');
        }
    }
}

var google_map_styling =
    [
        {
            "elementType": "geometry",
            "stylers": [
                {
                    "color": "#212121"
                }
            ]
        },
        {
            "elementType": "labels.icon",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "elementType": "labels.text.fill",
            "stylers": [
                {
                    "color": "#757575"
                }
            ]
        },
        {
            "elementType": "labels.text.stroke",
            "stylers": [
                {
                    "color": "#212121"
                }
            ]
        },
        {
            "featureType": "administrative",
            "elementType": "geometry",
            "stylers": [
                {
                    "color": "#757575"
                }
            ]
        },
        {
            "featureType": "administrative.country",
            "elementType": "geometry",
            "stylers": [
                {
                    "color": "#87f9d9"
                }
            ]
        },
        {
            "featureType": "administrative.country",
            "elementType": "labels.text.fill",
            "stylers": [
                {
                    "color": "#9e9e9e"
                }
            ]
        },
        {
            "featureType": "administrative.land_parcel",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "administrative.locality",
            "elementType": "labels.text.fill",
            "stylers": [
                {
                    "color": "#bdbdbd"
                }
            ]
        },
        {
            "featureType": "poi",
            "elementType": "labels.text.fill",
            "stylers": [
                {
                    "color": "#757575"
                }
            ]
        },
        {
            "featureType": "poi.park",
            "elementType": "geometry",
            "stylers": [
                {
                    "color": "#181818"
                }
            ]
        },
        {
            "featureType": "poi.park",
            "elementType": "labels.text.fill",
            "stylers": [
                {
                    "color": "#616161"
                }
            ]
        },
        {
            "featureType": "poi.park",
            "elementType": "labels.text.stroke",
            "stylers": [
                {
                    "color": "#1b1b1b"
                }
            ]
        },
        {
            "featureType": "road",
            "elementType": "geometry.fill",
            "stylers": [
                {
                    "color": "#2c2c2c"
                }
            ]
        },
        {
            "featureType": "road",
            "elementType": "labels.text.fill",
            "stylers": [
                {
                    "color": "#8a8a8a"
                }
            ]
        },
        {
            "featureType": "road.arterial",
            "elementType": "geometry",
            "stylers": [
                {
                    "color": "#373737"
                }
            ]
        },
        {
            "featureType": "road.highway",
            "elementType": "geometry",
            "stylers": [
                {
                    "color": "#3c3c3c"
                }
            ]
        },
        {
            "featureType": "road.highway.controlled_access",
            "elementType": "geometry",
            "stylers": [
                {
                    "color": "#4e4e4e"
                }
            ]
        },
        {
            "featureType": "road.local",
            "elementType": "labels.text.fill",
            "stylers": [
                {
                    "color": "#616161"
                }
            ]
        },
        {
            "featureType": "transit",
            "elementType": "labels.text.fill",
            "stylers": [
                {
                    "color": "#757575"
                }
            ]
        },
        {
            "featureType": "water",
            "elementType": "geometry",
            "stylers": [
                {
                    "color": "#000000"
                }
            ]
        },
        {
            "featureType": "water",
            "elementType": "labels.text.fill",
            "stylers": [
                {
                    "color": "#3d3d3d"
                }
            ]
        }
    ];