var app = angular.module('JdwApp', ['ngCookies', 'rzModule']);

app.directive('ngFinishRender', function ($timeout) {
    return {
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit('ngRepeatFinished');
                });
            }
        }
    };
});

app.directive('toggle', function () {
    return function (scope, elem, attrs) {
        scope.$on('event:toggle', function() {
            elem.slideToggle();
            $(event.currentTarget).toggleClass("is-active");
        });
    };
});

app.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if (event.which === 13) {
                scope.$apply(function () {
                    scope.$eval(attrs.ngEnter);
                });
                event.preventDefault();
            }
        });
    };
});

app.filter('slice', function () {
    return function (arr, start, end) {
        if (!arr || !arr.length) {
            return;
        }
        return arr.slice(start, end);
    };
});

app.controller('PubSearchCtrl', function ($scope, $http, $timeout, $cookies) {

    $scope.pubSearchTerm = '';
    $scope.pubs = [];
    $scope.pubPredictiveResults = [];
    $scope.isopen = false;
    $scope.cookieName = '';
    $scope.myLocal = null;
    $scope.pubId = '';
    $scope.loadedLocal = "";
    $scope.hideCloseCta = true;
    $scope.hideFinder = "is-hidden";
    $scope.hideResults = "is-hidden";
    $scope.hideLoading = true;
    $scope.menuOpen = "is-close";
    $scope.overlay = "is-hidden";
    $scope.geoError = false;
    $scope.removeFromTab = true;
    $scope.showPreditive = false;
    $scope.resultIndex = -1;

    var geocoder = new google.maps.Geocoder(),
        removeVenueSearch = null,
        stopTimeout = null,
        venueItemUrl = null;

    if (navigator.geolocation) {
        $scope.locationSupport = true;
    } else {
        $scope.locationSupport = false;
    }

    ///
    // Sets the pubId variable, depends on $scope.cookieName being set - rg
    ///
    $scope.setPubId = function () {
        $scope.pubId = $cookies.get($scope.cookieName);

        // visable states of elements
        if ($scope.pubId) {
            $scope.hideMyLocal = false;
            $scope.hidePubSearch = true;
        } else {
            $scope.hideMyLocal = true;
            $scope.hidePubSearch = false;
        }
    };

    function letterCount() {
        var string = $(".js-lettercount").text();
        var count = string.length;
        $scope.hideMyLocal = false;
        $scope.hidePubSearch = true;

        if (count >= 21 && count < 29) {
            $scope.loadedLocal = "is-visible med";
        }
        else if (count >= 30) {
            $scope.loadedLocal = "is-visible lrg";
        }
        else {
            $scope.loadedLocal = "is-visible";
        }
    }


    ////
    // Sets the pub based on $scope.cookieName
    ////
    $scope.setPub = function () {
        if ($scope.pubId) {
            $http.get('/api/pubs/' + $scope.pubId).success(function (response) {
                $scope.myLocal = response;

                $timeout(function () {
                    letterCount();
                }, 200);
            });
        }
    };

    $scope.hideOnClick = function () {
        $(document).on("touchstart click", function (e) {

            if (!$(".js-venue-finder-wrapper").is(e.target) && $(".js-venue-finder-wrapper").has(e.target).length === 0) {
                $timeout(function () {
                    $scope.showPreditive = false;
                }, 1);
            }

        });
    };

    $scope.removeMyLocal = function () {
        $cookies.remove($scope.cookieName);
        $scope.hideMyLocal = true;
        $scope.hidePubSearch = false;
    };


    $scope.defaultCloseState = function () {
        clearTimeout(removeVenueSearch);
        $scope.menuOpen = "is-close";
        $scope.hideCloseCta = true;
        $scope.overlay = "is-hidden";
        $scope.hideFinder = "is-hidden";
        $scope.hideResults = "is-hidden";
        $('#venue-search').val("").blur();

        $scope.pubSearchTerm = '';
        if ($scope.pubId) {
            $scope.hideMyLocal = false;
        } else {
            $scope.hidePubSearch = false;
        }

        if ($scope.isopen) {
            $timeout(function () {
                $scope.hideFinder = "is-hidden";
                $scope.hideResults = "is-hidden";
                $scope.hideLoading = true;
                $scope.isopen = false;
            }, 1);
        }

        removeVenueSearch = setTimeout(function () {
            $scope.removeFromTab = true;
        }, 3000);

    };

    $scope.openState = function () {
        clearTimeout(removeVenueSearch);
        $scope.removeFromTab = false;
        $timeout(function () {
            $scope.menuOpen = "is-open is-overflow";
            $scope.hideFinder = "is-visible";
            $scope.hideCloseCta = false;
            $scope.hidePubSearch = true;
            $scope.hideMyLocal = true;
            $scope.hideLoading = true;
            $scope.overlay = "";
            $scope.lengthError = false;
            $scope.inputError = false;
            $scope.geoError = false;
            $scope.isopen = true;
            $('#venue-search').val("");
            if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) === false) {
                $('#venue-search').focus();
            }
        }, 1);
    };

    function httpLocation(Lng, Lat) {
        $scope.showResults = false;
        $timeout.cancel(stopTimeout);

        $http.post('/api/pubs', {"location": {"lng": Lng, "lat": Lat}, "paging": {"numberPerPage": 3, "page": 1}})
            .success(function (response) {
                $scope.pubs = response.results;
                $scope.isPubName = false;

                $timeout(function () {
                    if ($scope.isopen) {
                        $scope.hideFinder = "is-hidden";
                        $scope.hideLoading = true;
                        $scope.hideResults = "is-visible";
                        $scope.geoError = false;
                    }
                }, 500);
            })
            .error(function () {
                $scope.hideLoading = true;
                $scope.hideFinder = "is-visible";
                $scope.geoError = true;
            });
    }

    function httpGoogleLocation(location) {

        var request = {
            address: location,
            region: 'GB'
        };

        var latLng = new google.maps.LatLng(0, 0);

        geocoder.geocode(request, function (results, status) {

            if (status == google.maps.GeocoderStatus.OK && containsValidType(results[0].types)) {

                latLng = results[0].geometry.location;
                httpLocation(latLng.lng(), latLng.lat());

            } else {
                $http.post('/api/pubs', {"term": $scope.pubSearchTerm, "paging": {"numberPerPage": 3, "page": 1}})
                    .success(function (response) {

                        $scope.pubs = response.results;
                        if (response.results.length > 0) {
                            $scope.isPubName = true;

                            $timeout(function () {
                                if ($scope.isopen) {
                                    $scope.hideFinder = "is-hidden";
                                    $scope.hideLoading = true;
                                    $scope.hideResults = "is-visible";
                                    $scope.geoError = false;
                                }
                            }, 500);

                        } else {

                            $timeout(function () {
                                $scope.pubSearchTerm = '';
                                $('#venue-search').focus();
                                $scope.hideLoading = true;
                                $scope.hideFinder = "is-visible";
                                $scope.geoError = true;
                            }, 300);

                        }


                    }).error(function (status) {

                    $timeout(function () {
                        $scope.hideLoading = true;
                        $scope.hideFinder = "is-visible";
                        $scope.geoError = true;
                    }, 300);

                });

            }
        });

    }

    function containsValidType(googleResultTypes) {
        if (googleResultTypes.indexOf("street_address") != -1 || googleResultTypes.indexOf("sublocality") != -1 ||
            googleResultTypes.indexOf("locality") != -1 || googleResultTypes.indexOf("neighborhood") != -1 ||
            googleResultTypes.indexOf("postal_code") != -1 || googleResultTypes.indexOf("airport") != -1 ||
            googleResultTypes.indexOf("colloquial_area") != -1 || googleResultTypes.indexOf("park") != -1 ||
            googleResultTypes.indexOf("stadium") != -1 || googleResultTypes.indexOf("political") != -1 ||
            googleResultTypes.indexOf("natural_feature") != -1) {
            return true;
        }
        return false;
    }

    $scope.geoLocationSearch = function () {

        navigator.geolocation.getCurrentPosition(getLocation, showError);

        function getLocation(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            $scope.hideLoading = false;
            $scope.hideFinder = "is-hidden";
            $scope.isopen = true;
            $scope.inputError = false;
            $scope.lengthError = false;
            $scope.geoError = false;
            httpLocation(longitude, latitude);
        }

        function showError(error) {
            switch (error.code) {
                case error.PERMISSION_DENIED:
                    alert("User denied the request for Geolocation.");
                    break;
                case error.POSITION_UNAVAILABLE:
                    alert("Location information is unavailable.");
                    break;
                case error.TIMEOUT:
                    alert("The request to get user location timed out.");
                    break;
                case error.UNKNOWN_ERROR:
                    alert("An unknown error occurred.");
                    break;
            }
        }
    };


    $scope.search = function () {

        var address = $scope.pubSearchTerm.replace(/[^.\w\s]/gi, '');
        if (address.length >= 3) {
            $scope.hideLoading = false;
            $scope.hideFinder = "is-hidden";
            $scope.isopen = true;
            $scope.lengthError = false;
            $scope.inputError = false;
            httpGoogleLocation(address);
            $('#venue-search').blur();
        } else if (address.length > 0) {
            $scope.lengthError = true;
            $scope.inputError = false;
            $scope.geoError = false;
        } else {
            $scope.lengthError = false;
            $scope.inputError = true;
            $scope.geoError = false;
        }
        return false;
    };

    $scope.closeEsc = function () {
        $(document).keyup(function (e) {
            if ($scope.isopen) {
                if (e.keyCode == 27) {
                    $scope.defaultCloseState();
                }
            }
        });
    };

    $scope.restartSearch = function () {
        $scope.hideResults = "is-hidden";
        $timeout(function () {
            $scope.hideFinder = "is-visible";
            $scope.pubSearchTerm = '';
            $('#venue-search').val("");
            if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) === false) {
                $('#venue-search').focus();
            }
        }, 500);
    };

    $scope.openInfoAddress = function (event) {
        var $infobtn = $(".js-venue-info");

        if ($(event.currentTarget).hasClass("is-active")) {
            $(event.currentTarget).toggleClass("is-active");
        } else {
            $infobtn.removeClass("is-active");
            $(event.currentTarget).toggleClass("is-active");
        }
    };

    /**
     *  Pub search predictive
     */

    function pubNameSearch(name) {
        $http.post('/api/pubs', {"term": name, "paging": {"numberPerPage": 100, "page": 1}})
            .success(function (response) {
                $scope.pubPredictiveResults = response.results;
                if ($scope.pubPredictiveResults.length < 1) {
                    $scope.showPreditive = false;
                    return;
                }
                $scope.showPreditive = true;
            });
    }


    // Set focus on list item
    $scope.activeResult = function (itemIndex) {
        return (itemIndex) === $scope.resultIndex;
    };
    
    // Load predictive search results
    $scope.predictivePubSearch = function (event) {
        var deviceSize = device.getSize();
        if (deviceSize === "mobile" || deviceSize === "small-mobile") {
            return;
        }

        var pubName = $scope.pubSearchTerm.replace(/the|The[^.\w\s]/gi, '');

        if (pubName.length >= 4) {

            if (event.keyCode === 40) {
                if ($scope.resultIndex < 2) {
                    $scope.resultIndex++;
                }
            } else if (event.keyCode === 38) {
                if ($scope.resultIndex >= 0) {
                    $scope.resultIndex--;
                }
            } else {
                $scope.resultIndex = -1;
                $scope.showPreditive = false;
                $timeout.cancel(stopTimeout);
                stopTimeout = $timeout(function () {
                    pubNameSearch(pubName);

                }, 500);
            }
        }

        if ($scope.resultIndex !== -1) {
            if ($scope.resultIndex < 2 && $scope.pubPredictiveResults.length) {
                venueItemUrl = $scope.pubPredictiveResults[$scope.resultIndex].url;
            } else if ($scope.resultIndex === 2) {
                venueItemUrl = '/pubs/all-pubs?searchterm=' + $scope.pubSearchTerm;
            }
        } else {
            venueItemUrl = null;
        }

        // Check for query string and run search
        $scope.loadResult = function () {
            if (venueItemUrl !== null) {
                window.location.href = venueItemUrl;
                $scope.showPreditive = false;
            }
        };

    };

});


app.controller('AdvPubSearchCtrl', function ($scope, $http, $timeout, $location) {

    /** 
     * Scope Variables
     */

    $scope.listing = [];
    $scope.advPredictiveResults = [];
    $scope.nameResults = [];

    $scope.useGeo = false;
    $scope.showGeoLayout = false;
    $scope.activeBrowserGeo = false;
    $scope.activeSearch = false;
    $scope.locationSearch = '';
    $scope.loadingRequest = true;
    $scope.latitude = null;
    $scope.longitude = null;
    $scope.loader = "is-hidden";
    $scope.isType = "is-all";
    $scope.clearFilterCta = false;
    $scope.region = null;
    $scope.errorShortSearchTerm = false;
    $scope.errorNoLocation = false;
    $scope.showSearchResults = false;
    $scope.facilities = [];
    $scope.searchType = 1;

    $scope.resultIncrement = 1;
    
    var concatenatedResults = [];

    /** 
     * Local varibales 
     */

    var cancelTimeout = null;
    var debounce = null;
    var loadmoreTimeout = null;
    var httprequestTimeout = null;

    function venueType() {
        switch ($scope.searchType) {
            case 1:
                $scope.isType = "is-pubs";
                break;
            case 2:
                $scope.isType = "is-hotels";
                break;
            default:
                $scope.isType = "is-all";
        }
    }

    function resultCount() {
        var result = 0;
        $(".js-count").each(function () {
            var $this = $(this);
            result += parseInt($this.attr("data-result"));
        });
        $(".js-results").text(result);
    }


    function getQueryVariable(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] == variable) {
                return decodeURIComponent(pair[1]);
            }
        }
        return (false);
    }

    /**
     * Split results into columns 
     * Thanks Mark Wilson =) 
     */

    function columnize(arrayItem, cols) {
        var arr = [];
        var itemsRemaining = arrayItem.length;

        for (var i = 0; i < cols; i++) {
            var sliceLength = Math.ceil(itemsRemaining / (cols - i));
            arr.push(arrayItem.slice(i * sliceLength, i * sliceLength + sliceLength));
            itemsRemaining -= sliceLength;
        }

        return arr;
    }

    /**
     * Post request 
     */

    function httpPubList() {
        var deviceSize = device.getSize();
        $scope.facilities = [];

        $(".js-facilities").each(function () {
            if ($(this).is(':checked')) {
                var facilityId = $(this).val();
                $scope.facilities.push(facilityId);
            }
        });

        $(".js-searchtype").each(function () {
            if ($(this).is(':checked')) {
                $scope.searchType = parseInt($(this).val());
            }
        });

        removeClearButton();

        if ($scope.useGeo) {


            if (getQueryVariable("facility").length) {
                var facid = getQueryVariable("facility").toString();
                if (facid === "pizza") {
                    $scope.facilities[0] = "67035341-c6d6-47bc-9837-a291ca8ff3ab";
                }
            }
            var post = $http.post('/api/advancedsearch', { "term": $scope.locationSearch, "region": $scope.region, "location": { "lng": $scope.longitude, "lat": $scope.latitude }, "paging": { "numberPerPage": 30, "page": 0, "UsePagination": true }, "facilities": $scope.facilities, "searchType": $scope.searchType })
            .success(function (response) {

                $scope.nameResults = response.nameResults;
                $scope.locationSearchtext = $scope.locationSearch;

                if (response.results.length > 0){
                    $scope.listing = response.results;
                    concatenatedResults = response.results;
                    $scope.columns = columnize(response.results.slice(3), 3);
                    $scope.hideLocationResults = false;

                } else {
                    $scope.listing = [];
                    $scope.hideLocationResults = true;
                }

                $scope.resultIncrement = 1;

                $timeout(function () {
                    venueType();
                    $scope.loader = "is-visible";
                    $scope.loadingRequest = false;
                    $scope.showGeoLayout = true;
                    if (deviceSize === "mobile" || deviceSize === "small-mobile") {
                        $('html, body').animate({
                            scrollTop: $(".js-scrollto").offset().top - 100
                        }, 1000);
                    }
                }, 500);
            });

        } else {

            if (getQueryVariable("facility").length) {
                var facid = getQueryVariable("facility").toString();
                if (facid === "pizza") {
                    $scope.facilities[0] = "67035341-c6d6-47bc-9837-a291ca8ff3ab";
                }
            }

            $http.post('/api/advancedsearch', { "region": $scope.region, "paging": { "UsePagination": false }, "facilities": $scope.facilities, "searchType": $scope.searchType })
            .success(function (response) {
                $scope.listing = response.regions;
                $timeout(function () {
                    venueType();
                    resultCount();
                    $scope.loadingRequest = false;
                    $scope.loader = "is-visible";
                }, 500);
            });
        }

    }

    // remove clear if default settings 

    function removeClearButton() {
        if ($scope.facilities.length < 1 && $scope.region === null && $scope.searchType === 0) {
            $scope.clearFilterCta = false;
        }
    }

    /**
     * Initial Http request  
     */

    $scope.onLoadHttp = function () {
        google.maps.event.addDomListener(window, 'load', function () {

            if (getQueryVariable("searchterm").length) {
                $scope.locationSearch = getQueryVariable("searchterm").toString();
                $scope.googleSearch();
            } else {
                httpPubList();
            }
        
            $(document).on("touchstart click", function (e) {
                if (!$(".js-search-wrapper").is(e.target) && $(".js-search-wrapper").has(e.target).length === 0) {
                    $timeout(function () {
                        $scope.showSearchResults = false;
                    }, 1);
                }
            });
        });
    };

    /**
     * Facilities searchtype Search  
     */

    $scope.httpRequest = function () {
        $scope.loadingRequest = true;
        $timeout.cancel(debounce);
        debounce = $timeout(function () {
            $scope.loader = "is-hidden";
            $scope.clearFilterCta = true;
            httpPubList();
        }, 1000);
    };

    /**
     * Load more results  
     */

    $scope.loadmore = function () {
        $timeout.cancel(loadmoreTimeout);

        $scope.loadingMoreResults = true;

        loadmoreTimeout = $timeout(function () {
            $scope.resultIncrement = $scope.resultIncrement + 1;

            if (getQueryVariable("facility").length) {
                var facid = getQueryVariable("facility").toString();
                if (facid === "pizza") {
                    $scope.facilities[0] = "67035341-c6d6-47bc-9837-a291ca8ff3ab";
                }
            }

            $http.post('/api/advancedsearch', { "region": $scope.region, "location": { "lng": $scope.longitude, "lat": $scope.latitude }, "paging": { "numberPerPage": 30, "page": $scope.resultIncrement, "UsePagination": true }, "facilities": $scope.facilities, "searchType": $scope.searchType })
            .success(function (response) {
                var newListing = concatenatedResults.concat(response.results);
                $scope.columns = columnize(newListing.slice(3), 3);
                concatenatedResults = newListing;
                $scope.loadingMoreResults = false;
                if (response.results.length < 30) {
                    $scope.hideloadmore = true;
                }
            });

        }, 1000);

    };

    /**
     * Region Search  
     */

    $scope.regionHttpRequest = function (region) {
        $scope.loadingRequest = true;
        $scope.region = region;
        $timeout.cancel(debounce);
        debounce = $timeout(function () {
            $scope.loader = "is-hidden";
            $scope.clearFilterCta = true;
            httpPubList();
        }, 500);
    };


    /** 
     * Search using User browser gps location 
     */

    $scope.geoPubSearch = function () {

        if ($scope.activeBrowserGeo) {
            return;
        }

        $timeout.cancel(httprequestTimeout);

        $scope.activeBrowserGeo = true;
        $scope.activeSearch = false;
        $scope.loadingRequest = true;
        $scope.errorShortSearchTerm = false;

        httprequestTimeout = $timeout(function () {

            navigator.geolocation.getCurrentPosition(getLocation, showError);

            function getLocation(position) {
                $scope.loader = "is-hidden";
                $scope.latitude = position.coords.latitude;
                $scope.longitude = position.coords.longitude;
                $scope.useGeo = true;
                $scope.locationSearch = '';
                httpPubList();
                $scope.townSearchType = false;
            }

            function showError(error) {
                switch (error.code) {
                    case error.PERMISSION_DENIED:
                        alert("User denied the request for Geolocation.");
                        $scope.activeBrowserGeo = false;
                        break;
                    case error.POSITION_UNAVAILABLE:
                        alert("Location information is unavailable.");
                        $scope.activeBrowserGeo = false;
                        break;
                    case error.TIMEOUT:
                        alert("The request to get user location timed out.");
                        $scope.activeBrowserGeo = false;
                        break;
                    case error.UNKNOWN_ERROR:
                        alert("An unknown error occurred.");
                        $scope.activeBrowserGeo = false;
                        break;
                }
            }

        }, 500);

    };

    /** 
     * Term search using Googles API 
     */

    $scope.googleSearch = function () {
        

        if ($scope.locationSearch.length < 3) {
            $scope.errorShortSearchTerm = true;
            return;
        } else {

            $scope.errorShortSearchTerm = false;
            $scope.activeBrowserGeo = false;
            $scope.activeSearch = true;
            $scope.loadingRequest = true;
            $scope.showSearchResults = false;
            $timeout(function () {
                $timeout.cancel(cancelTimeout);
            }, 100);

            var geocoder = new google.maps.Geocoder();
            var latLng = new google.maps.LatLng(0, 0);
            var searchTerm = $scope.locationSearch.replace(/[^.\w\s]/gi, '');

            var request = {
                address: searchTerm,
                region: 'GB'
            };

            geocoder.geocode(request, function (results, status) {
                $scope.useGeo = true;

                if (status == google.maps.GeocoderStatus.OK && containsValidType(results[0].types)) {
                    latLng = results[0].geometry.location;

                    $scope.loader = "is-hidden";
                    $scope.longitude = latLng.lng();
                    $scope.latitude = latLng.lat();
                    httpPubList();

                    $scope.townSearchType = true;
                } else {

                    $scope.loader = "is-hidden";
                    $scope.longitude = null;
                    $scope.latitude = null;
                    httpPubList();

                }
            });
        }  
    };

    /** 
     * Term search using Googles API 
     */
    function containsValidType(googleResultTypes) {
        if (googleResultTypes.indexOf("street_address") != -1 || googleResultTypes.indexOf("sublocality") != -1 ||
          googleResultTypes.indexOf("locality") != -1 || googleResultTypes.indexOf("neighborhood") != -1 ||
          googleResultTypes.indexOf("postal_code") != -1 || googleResultTypes.indexOf("airport") != -1 ||
          googleResultTypes.indexOf("colloquial_area") != -1 || googleResultTypes.indexOf("park") != -1 ||
          googleResultTypes.indexOf("stadium") != -1 || googleResultTypes.indexOf("political") != -1 ||
          googleResultTypes.indexOf("natural_feature") != -1) {
            return true;
        }
        return false;
    }

    /**
     * Set filters to default state and calls new Http reqest
     */

    $scope.clearFilters = function () {
        $scope.clearFilterCta = false;
        $scope.loadingRequest = true;

        $('.js-facilities').prop('checked', false);
        $('.js-radio-country[value="all"]').prop('checked', true);
        $('.js-searchtype[value="0"]').prop('checked', true);
        $scope.region = null;
        $scope.loader = "is-hidden";
        httpPubList();

    };

    $scope.toggle = function () {
        $scope.$broadcast('event:toggle');
    };


    /**
     * Advance pub search predictive
     */

    function pubNameSearch(name) {
        $http.post('/api/pubs', { "term": name, "paging": { "numberPerPage": 3, "page": 1 } })
            .success(function (response) {
                $scope.advPredictiveResults = response.results;
                $scope.showSearchResults = true;
            });
    }

    $scope.predictiveAdvPubSearch = function (e) {
        $scope.showSearchResults = false;

        if (e.keyCode === 13) {
            return;
        }

        var pubAdvName = $scope.locationSearch.replace(/the|The[^.\w\s]/gi, '');

        if (pubAdvName.length >= 4) {
            $timeout.cancel(cancelTimeout);
            cancelTimeout = $timeout(function () {
                pubNameSearch(pubAdvName);
            }, 1000);
        }

    };

});

app.controller('SiteSearchCtrl', function ($scope, $timeout, $http) {

    $scope.showSearch = false;
    $scope.isVisible = false;
    $scope.isfocused = false;
    $scope.searchTerm = '';
    $scope.activeResult = false;

    var reset = null,
        focusRest = null,
        resultIndex = -1,
        searchItemUrl = null;

    // Toggle mobile search
    $scope.toggleMobileSearch = function () {
        $scope.showSearch = !$scope.showSearch;

        if ($scope.showSearch === true) {
            $timeout(function () {
                $(".js-search-input--mobile").focus();
            }, 100);
        }
        return false;
    };

    // Set focus on list item
    $scope.activeResult = function (itemIndex) {
        return (itemIndex) === resultIndex;
    };

    // Predictive search
    $scope.predictiveSearch = function (searchTerm, event) {

        if (event.keyCode === 40 && $scope.searchItems.length) {
            if (resultIndex < $scope.searchItems.length -1) {
                resultIndex++;
            }
        } else if (event.keyCode === 38 && $scope.searchItems.length) {
            if (resultIndex > -1) {

                resultIndex--;
            }
        } else {

            resultIndex = -1;

            $timeout.cancel(reset);

            reset = $timeout(function () {
                if (searchTerm === "" || searchTerm.length <= 2) {
                    $scope.isVisible = false;
                } else {
                    $http.get('/api/search/' + searchTerm).success(function (response) {
                        $scope.searchItems = response;
                        $scope.isVisible = true;
                    });
                }
            }, 1000);

        }

        if (resultIndex >= 0) {
            searchItemUrl = $scope.searchItems[resultIndex].url;
        } else {
            searchItemUrl = null;
        }

    };

    // Check for query string and run search
    $scope.triggerSearch = function (searchTerm) {
        if (resultIndex >= 0) {
            window.location.href = searchItemUrl;
        } else {
            window.location.href = "/search?q=" + searchTerm;
        }
    };


    $scope.isFocused = function (isSelected) {
        $timeout.cancel(focusRest);

        if (isSelected) {
            $scope.isVisible = true;
            $scope.isfocused = true;
            $scope.searchItems = [];
            $scope.searchTerm = '';
        } else {
            focusRest = $timeout(function () {
                $scope.searchTerm = '';
                $scope.isVisible = false;
                $scope.isfocused = false;
            }, 500);

        }
    };


    $scope.search = function () {
        return false;
    };

});
var jdwMaxCalories = 2500;

app.controller('MenuFilterCtrl', ['$scope', '$http', '$timeout', '$sce', function ($scope, $http, $timeout, $sce) {
    var timer = null;
    $scope.allergensArray = [];
    $scope.foodTypeArray = [];
    $scope.categories = [];
    $scope.dietary = [];
    $scope.hideClass = "is-visible";
    $scope.hideClearCta = true;
    $scope.pubId = null;
    $scope.dietaryContent = "is-hidden";

    $scope.calorieSliderValue = jdwMaxCalories;

    $scope.calorieSlider = {
        ceil: jdwMaxCalories,
        floor: 0
    };

    $scope.apiUrl = '';
    $scope.initialCategories = [];

    /**
     * Splits url query string into Arrray
     */

    function getQueryVariable(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] == variable) {
                return pair[1];
            }
        }
        return (false);
    }

    /**
     * Get pubsId from url query string and passes to the scope
     * Request food items.
     */

    $scope.initialHttpRequest = function () {
        $scope.wrapperHideClass = "is-hidden";
        $scope.pubId = getQueryVariable("pub");
        httpRequest(true);
    };

    /**
     * Loops through allergens & foodtype active checkboxes passes id into arrays
     * Allergens & foodtype arrays are passed pass into httpRequest parameters
     */

    $scope.allergenHttpRequest = function () {

        $scope.wrapperHideClass = "is-hidden";
        $scope.allergensArray = [];
        $scope.foodTypeArray = [];

        $(".js-allergens").each(function () {
            if ($(this).is(':checked')) {
                var allergensId = $(this).val();
                $scope.allergensArray.push(allergensId);
            }
        });

        $(".js-foodtype").each(function () {
            if ($(this).is(':checked')) {
                var foodTypeId = $(this).val();
                $scope.foodTypeArray.push(foodTypeId);
            }
        });

        $scope.hideClearCta = false;
        httpRequest();
    };

    /**
     * Http Post request to receieve food items bindes to $scope.categories (json)
     *
     * Parameters :
     * allergensList = Array
     * foodTypes = Array
     */

    function httpRequest(setInitialCats) {
        $timeout.cancel(timer);
        removeClearbutton();

        timer = $timeout(function () {
            $http.get($scope.apiUrl, {"params": { "allergens": $scope.allergensArray, "foodtypes": $scope.foodTypeArray, "pubId": $scope.pubId } })
            .success(function (response) {
                $scope.categories = response.Results;

                if (setInitialCats) {
                    for (var i = 0; i < $scope.categories.length; i++) {
                        var encoded = encodeURIComponent($scope.categories[i].category).replace(/'/g, "%27");
                        $scope.initialCategories.push(encoded);
                    }
                }

                $timeout(function () {
                    $scope.wrapperHideClass = "is-visible";
                    gridReset();
                }, 250);
            });
        }, 1000);
    }

    /**
     * Hide Clear button if default filters set
     */

    function removeClearbutton() {
        if ($scope.calorieSliderValue === jdwMaxCalories && $scope.allergensArray.length < 1 && $scope.foodTypeArray.length < 1 && $(".js-active-categories:first-child").hasClass("is-active") === true) {
            $scope.hideClearCta = true;
        }
    }


    /**
     * Clears all filters
     * Returns all filters to default value and requests new json
     */

    $scope.clearfilter = function () {
        $scope.wrapperHideClass = "is-hidden";
        $scope.hideClearCta = true;
        $(".js-active-categories").removeClass("is-active");
        $(".js-active-categories:first-child").addClass("is-active");
        $('.js-allergens, .js-foodtype').prop('checked', false);
        $scope.allergensArray = [];
        $scope.foodTypeArray = [];
        $scope.calorieSliderValue = jdwMaxCalories;
        httpRequest();
    };


    /**
     * Http Post request to recieve dietary info bindes to $scope.dietary (json)
     *
     * Parameters :
     * dietaryItemId = string
     */

    function httpDietaryRequest(dietaryItemId) {
        $http.get($scope.apiUrl + dietaryItemId).success(function (response) {
            $scope.dietary = response;
            $timeout(function () {
                $scope.dietaryContent = "is-visible";
            }, 200);
        });
    }

    /**
     * Resets masonry grid layout
     */

    function gridReset() {
        $('.js-masonry-grid.is-open').masonry({
            itemSelector: '.js-masonry-item'
        });
        $('.js-masonry-grid.is-open').masonry('destroy');
        $('.js-masonry-grid.is-open').masonry({
            itemSelector: '.js-masonry-item'
        });
        $scope.hideClass = "is-visible";
    }

    /**
     * Fades in results
     */

    $scope.refreshResults = function () {
        $scope.hideClass = "is-hidden";
        removeClearbutton();
        $timeout(function () {
            gridReset();
        }, 200);
    };

    /**
     * Fades out results
     */

    $scope.hideResults = function () {
        $scope.hideClass = "is-hidden";
        $scope.hideClearCta = false;
    };

    /**
     * Slide toggle Adv filters using directive
     */

    $scope.toggle = function () {
        $scope.$broadcast('event:toggle');
    };

    /**
     * Toggle active class on food catergory
     */

    $scope.activeState = function (event) {
        $(".js-active-categories").removeClass("is-active");
        $(event.currentTarget).addClass("is-active");
        removeClearbutton();
    };

    /**
     * Shows Clear cta button
     */

    $scope.showClear = function () {
        $scope.hideClearCta = false;
    };

    /**
     * Collapsible Category Panels
     */

    $scope.collapse = function (event) {
        var $this = $(event.currentTarget);

        if ($this.hasClass('icon-up')) {
            $this.toggleClass('icon-up icon-down');
            $this.parent().find('.js-collapse-panel').slideUp("fast", function () {
                $this.parent().find('.js-collapse-panel').removeClass("is-open");
            });
        } else {
            $this.toggleClass('icon-up icon-down');
            $this.parent().find('.js-collapse-panel').slideDown("fast", function () {
                $(this).addClass('is-open');
                gridReset();
            });
        }
    };

    /**
     * Initializes magnificPopup to show dietary info
     * Runs httpDietaryRequest
     */

    $scope.showDietaryInfo = function (event) {
        var foodId = $(event.currentTarget).attr("data-food-id");
        var foodName = $(event.currentTarget).attr("data-name");

        $scope.foodName = foodName;
        $scope.dietaryContent = "is-hidden";

        $(event.currentTarget).magnificPopup({
            items: {
                type: 'inline',
                src: '#dietary-popup'
            }
        }).magnificPopup('open');

        httpDietaryRequest(foodId);
    };


    $scope.refreshSlider = function () {
        $timeout(function () {
            $scope.$broadcast('rzSliderForceRender');
        });
    };

    //
    $scope.trustedResource = function (input) {
        return $sce.trustAsHtml(input);
    };
            
}]);

/**
 * Custom filter for calorie count slider
 * Pushes new item to the scope
 */

app.filter('rangeFilter', function () {
    return function (items, calorieSliderValue) {
        var filtered = [];

        var calMax = parseInt(calorieSliderValue);
        var maxCalsSelected = calMax == jdwMaxCalories;

        angular.forEach(items, function (item) {
            // If item calories are lower than selected max OR the selected max is equal to the calorie slider ceil
            if (item.cals <= calMax || maxCalsSelected) {
                filtered.push(item);
            }
        });

        return filtered;
    };
});
function PostcodeAnywhereController() {
    var searchContext = "",
        key = "BW55-PZ65-GT77-RH67";

    function retrieveAddress(id) {
        $.ajax({
            url: "//services.postcodeanywhere.co.uk/CapturePlus/Interactive/Retrieve/v2.10/json3.ws",
            dataType: "jsonp",
            data: {
                key: key,
                id: id
            },
            success: function (data) {
                if (data.Items.length) {
                    populateAddress(data.Items[0]);
                }
            }
        });
    }

    function populateAddress(address) {
        $(".js-address-display").html(address.Label.replace(/\n/g, '<br/>'));

        $(".js-PostalCode").val(address.PostalCode);
        $(".js-Line1").val(address.Line1);
        $(".js-Line2").val(address.Line2);
        $(".js-City").val(address.City);
        $(".js-Province").val(address.Province);
    }

    this.init = function () {
        if ($(".js-address-search").length < 1) {
            return;
        } else {
            $(".js-address-search").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "//services.postcodeanywhere.co.uk/CapturePlus/Interactive/Find/v2.10/json3.ws",
                        dataType: "jsonp",
                        data: {
                            key: key,
                            searchFor: "Everything",
                            country: $(".js-country-select").val(),
                            searchTerm: request.term,
                            lastId: searchContext
                        },
                        success: function (data) {
                            response($.map(data.Items, function (suggestion) {
                                return {
                                    label: suggestion.Text,
                                    value: "",
                                    data: suggestion
                                };
                            }));
                        }
                    });
                },
                select: function (event, ui) {
                    var item = ui.item.data;
                    if (item.Next == "Retrieve") {
                        retrieveAddress(item.Id);
                    } else {
                        var field = $(this);
                        searchContext = item.Id;

                        window.setTimeout(function () {
                            field.autocomplete("search", item.Id);
                        });
                    }
                },
                autoFocus: true,
                minLength: 1,
                delay: 100
            }).focus(function () {
                searchContext = "";
            });
        }
    };
}




$(document).ready(function () {
    $('.goal').on('click', function (ev) {
        var $jself = $(this);
        var goalId = $jself.attr('data-goalId');
        var itemId = $jself.attr('data-itemId');
        var itemPath = $jself.attr('data-itemPath');
        $.ajax('/services/TrackGoal.aspx/Track', {
            type: 'POST',
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: "{'goalId':'" + goalId + "', 'itemId':'" + itemId + "', 'itemPath':'" + itemPath + "'}",
            success: function (success) {
                if (success) {
                } else {
                }
            },
            error: function () {
            }
        });
    });
});
if (!String.prototype.includes) {
    String.prototype.includes = function (search, start) {
        'use strict';

        if (search instanceof RegExp) {
            throw TypeError('first argument must not be a RegExp');
        }
        if (start === undefined) { start = 0; }
        return this.indexOf(search, start) !== -1;
    };
}

function disableWFFM(formId, submitId) {

    if ($scw.webform.validators.setFocusToFirstNotValid(formId)) { //'form_30D94A94BE1747F7916B32D59D243A74_submit')}) {
        var submit = document.getElementById(submitId);
        if (submit != null) {
            submit.style.cursor = 'wait';
        }

        document.body.style.cursor = 'wait';

        /*
        for (var i = 0; i < document.getElementsByTagName('form')[0].elements.length; i++) {
            document.getElementsByTagName('form')[0].elements[i].readonly = true;
        };
        */
        // only disable the refresh which is causing form submission issues
        var refreshes = document.querySelectorAll('input[type=image]');
        for (var i = 0; i < refreshes.length; i++) {
            if (refreshes[i].src.includes('refresh.png')) {
                refreshes[i].disabled = true;

            }
        };
    }
}
