$(document).on("focus", "#locationSearch", function(){
    $("#locationSearch").attr("placeholder", "Insert location...");
});

function selectSubspeciality(text, id) {
    $('#subspecId').val(id);
    $('#expertiseId').val('');
    $('#filterByTag').val(text);

    closeSubspecialityDropDown();

    $('#searchFormSubmit').prop('disabled', false);

    return false;
}

function selectWholeExpertise(text, id)
{
    $('#subspecId').val('');
    $('#expertiseId').val(id);
    $('#filterByTag').val(text);

    closeSubspecialityDropDown();

    $('#searchFormSubmit').prop('disabled', false);

    return false;
}

function selectInsurer(text, id)
{
    $('#insurerLabel').html(text);
    $('#insurerId').val(id);
}

function closeSubspecialityDropDown()
{
    $('.dropdown.open').removeClass('open');
}

function toggleExpertiseSection(id) {
    var currentSection = $('#expertise_' + id);
    var isOpen = currentSection.find('.expertiseCaret').hasClass('sectionIsOpen') ? true : false;

    var caret = currentSection.find('.expertiseCaret');
    var subspecs = currentSection.find('.expertiseSubspeciality');

    if (isOpen) {
        caret.removeClass('sectionIsOpen').addClass('sectionIsClosed');
        subspecs.addClass('hidden');
    } else {
        caret.removeClass('sectionIsClosed').addClass('sectionIsOpen');
        subspecs.removeClass('hidden');
    }
}

$(document).ready(function() {
    $('#expertiseScroll').slimscroll({
        height: 'auto'
    });

    $('#insurersScroll').slimscroll({
        height: 'auto'
    });

    $('#filterByTag').on('keyup click', function () {
        var search = jQuery.trim($(this).val());
        var boxes = $('.expertiseBox');

        if (search.length === 0) {
            boxes.removeClass('hidden');
            boxes.find('.expertiseCaret').removeClass('sectionIsOpen').addClass('sectionIsClosed');
            boxes.find('.expertiseSubspeciality').addClass('hidden');

            return;
        }

        boxes.addClass('hidden');
        boxes.find('.expertiseCaret').removeClass('sectionIsOpen').addClass('sectionIsClosed');
        boxes.find('.expertiseSubspeciality').addClass('hidden');

        var elements = $("div.expertiseBox:regex(data-tags, .*" + search + ".*)");
        elements.each(function () {
            var box = $(this);

            box.find('.expertiseCaret').removeClass('sectionIsOpen').addClass('sectionIsClosed');
            box.find('.expertiseSubspeciality').addClass('hidden');
            box.removeClass('hidden');
        });

        var unhiddenExpertiseBoxes = $('.expertiseBox:not(.hidden)');

        var boxesUnhiddenCount = unhiddenExpertiseBoxes.length;

        if (boxesUnhiddenCount === 1) {
            var expertiseId = $(unhiddenExpertiseBoxes[0]).data('id');
            var isOpen = $('#expertise_' + expertiseId).find('.expertiseCaret').hasClass('sectionIsOpen') ? true : false;

            if (!isOpen) {
                toggleExpertiseSection(expertiseId);
            }
        }
    });

    $('#filterByTag').on('keyup', function () {
        var totalBoxesCount = $('.expertiseBox').length;
        var boxesHiddenCount = $('.expertiseBox.hidden').length;

        $('#searchFormSubmit').prop('disabled', true);

        if (totalBoxesCount === boxesHiddenCount) {
            $('#expertiseNoResults').removeClass('hidden');
        } else {
            $('#expertiseNoResults').addClass('hidden');
        }

        if ( $(this).val().length == 0 ) {
            $('#searchFormSubmit').prop('disabled', false);
        }

    });

    $('#filterByTag').on('keydown', function () {

        if (!$('#expertiseSelect').hasClass('open')) {
            $('#expertiseSelect').addClass('open');
        }
    });

    $('#expertiseSelect .dropdown-menu').on('click', function(event){
        var events = $._data(document, 'events') || {};
        events = events.click || [];
        for(var i = 0; i < events.length; i++) {
            if(events[i].selector) {

                if($(event.target).is(events[i].selector)) {
                    events[i].handler.call(event.target, event);
                }

                $(event.target).parents(events[i].selector).each(function(){
                    events[i].handler.call(this, event);
                });
            }
        }
        event.stopPropagation(); //Always stop propagation
    });

    var autocomplete = new google.maps.places.Autocomplete(document.getElementById('locationSearch'), {types: ['geocode']});
    autocomplete.addListener('place_changed', function () {
        $('#searchLat').val(this.getPlace().geometry.location.lat());
        $('#searchLng').val(this.getPlace().geometry.location.lng());
    });

    $('#locationSearch').change(function () {
        $('#searchLat').val('');
        $('#searchLng').val('');
    });
});

jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ?
                matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

function getGeoLocation() {
    if (navigator.geolocation) {

        $("#locationIcon, #locationIcon .faLocationIcon").addClass("pulseAnimation");

        navigator.geolocation.getCurrentPosition(function(position) {
            var lat = position.coords.latitude;
            var lng = position.coords.longitude;

            $('#searchLat').val(lat);
            $('#searchLng').val(lng);

            var geocoder = new google.maps.Geocoder;

            geocoder.geocode({'location': { lat: lat, lng: lng}}, function(results, status) {
                if (status === 'OK') {
                    if (results[0]) {
                        $('#locationSearch').val(results[0].formatted_address);
                    }
                }
                $("#locationIcon, #locationIcon .faLocationIcon").removeClass("pulseAnimation");

            });
        }, function(positionError) {
            $("#locationIcon, #locationIcon .faLocationIcon").removeClass("pulseAnimation");
            $("#locationSearch").attr("placeholder", "We can't locate you");
        });
    }

}