﻿// Geocoder helper 
function UserLocationGeocoder(latitude, longitude, formattedAddress) {
    this.googleMapsGeocoder = new google.maps.Geocoder();
    this.latitude = latitude;
    this.longitude = longitude;
    this.formattedAddress = formattedAddress;
}

function findComponent(address_components, type) {
    var result = null;

    for (var i = 0; i < address_components.length; i++) {
        var address_component = address_components[i];

        var found = false;

        for (var j = 0; j < address_component.types.length; j++) {
            if (address_component.types[j] == type) {
                result = address_component.long_name;
                found = true;
                break;
            }
        }

        if (found == true) {
            break;
        }
    }

    return result;
}

// Get source for autocomplete
UserLocationGeocoder.prototype.AutoCompleteSource = function (request, response) {
    this.googleMapsGeocoder.geocode({ 'address': request.term, 'language': 'NO', 'region': 'NO' },
         function (results, status) {

             results = $.grep(results, function (n, i) {
                 var country = findComponent(n.address_components, 'country');
                 return country == null || country == 'Norge';
             });

             results = $.map(results, function (item) {
                 var itemLabel = item.formatted_address;
                 itemLabel = itemLabel.replace(/,\sNorge/g, '')/*.replace(/[0-9]{4}\s/g, '')*/;
                 return {
                     label: itemLabel/*item.formatted_address*/,
                     value: itemLabel/*item.formatted_address*/,
                     latitude: item.geometry.location.lat(),
                     longitude: item.geometry.location.lng()
                 }
             });

             response(results);
         }
   );
}

var geocoderInstanceUser = null;

// Geocode address
UserLocationGeocoder.prototype.GeocodeRequest = function (address, onComplete) {
    geocoderInstanceUser = this;
    geocoderInstanceUser.onComplete = onComplete;

    this.googleMapsGeocoder.geocode({ 'address': address, 'language': 'NO', 'region': 'NO' },
        function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                geocoderInstanceUser.latitude = results[0].geometry.location.lat();
                geocoderInstanceUser.longitude = results[0].geometry.location.lng();
                geocoderInstanceUser.formattedAddress = results[0].formatted_address;
                geocoderInstanceUser.onComplete();
            }
        });
}

// Location changer helper
function LocationChangeLink(element, expandedPanel,labelExpand, labelClose) {
    this.isExpanded = false;
    this.element = element;
    this.expandedPanel = expandedPanel;
    this.labelClose = labelClose;
    this.labelExpand = labelExpand;
}

// Expand panel for changing location
LocationChangeLink.prototype.Expand  = function () {
    this.isExpanded = true;
    $("#" + this.element).text(this.labelClose);
    $("#"+this.expandedPanel).css("display", "block");
}

// Close panel for changing location
LocationChangeLink.prototype.Close  = function () {
    this.isExpanded = false;
    $("#" + this.element).text(this.labelExpand);
    $("#"+this.expandedPanel).css("display", "none");
}

// Change state of panel for changing location
LocationChangeLink.prototype.ChangeState  = function () {
    if (this.isExpanded)
        this.Close();
    else
        this.Expand();
}

var userLocationGeocoder = null;
var locationChangeLink = null;

// click on "change address" link
function startChangeLocation() {

    if (!locationChangeLink) {
        userLocationGeocoder = new UserLocationGeocoder($("#userLatitude").val(), $("#userLongitude").val(), $("#userAddress").val());
        locationChangeLink = new LocationChangeLink("locationLink", "locationSelect", "endre din plassering", "avbryte");
    }

     if ($("#refreshedFilter").val() == "1") {
         $("#locationInput").autocomplete({
             source: function (request, response) { userLocationGeocoder.AutoCompleteSource(request, response); }
         });

         $("#locationButton").button().click(stopChangeLocation);

         $("#refreshedFilter").val("0");
     }

     locationChangeLink.ChangeState();
     return false;
}

// returns parameters with user location data
function GetUserLocationRequestParameter() {
    var lat = $("#userLatitude").val();
    var lon = $("#userLongitude").val();
    var address = $("#userAddress").val();
    return 'FormattedAddress=' + address + '&Latitude=' + lat + '&Longitude=' + lon;
}

function setCookie(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + encodeURIComponent(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

Date.prototype.addHours = function (h) {
    this.setTime(this.getTime() + (h * 60 * 60 * 1000));
    return this;
}

// accepts changing of the address
function stopChangeLocation()
{
     if (!locationChangeLink) 
	    return false;

     var request = $('#locationInput').val();
     userLocationGeocoder.GeocodeRequest(request, function () {
         locationChangeLink.Close();

         $("#yourLocationValue").text(userLocationGeocoder.formattedAddress);
         // save values to hidden fields. javascript object can be not initialized
         $("#userLatitude").val(userLocationGeocoder.latitude.toString());
         $("#userLongitude").val(userLocationGeocoder.longitude.toString());
         $("#userAddress").val(userLocationGeocoder.formattedAddress);
         var findNeighbours = $("#FindNeighbours").val();

         var parameter = 'FormattedAddress=' + userLocationGeocoder.formattedAddress +
                        '&Latitude=' + userLocationGeocoder.latitude.toString() +
                        '&Longitude=' + userLocationGeocoder.longitude.toString();

         setCookie("FindNeighbours", findNeighbours, (new Date()).addHours(1).toUTCString(), "/");
         setCookie("FormattedAddress", userLocationGeocoder.formattedAddress, (new Date()).addHours(1).toUTCString(), "/");
         setCookie("Latitude", userLocationGeocoder.latitude.toString(), (new Date()).addHours(1).toUTCString(), "/");
         setCookie("Longitude", userLocationGeocoder.longitude.toString(), (new Date()).addHours(1).toUTCString(), "/");

         /*
         $.ajax({
         type: 'POST',
         url: '/Search/UpdateUserLocation',
         data: parameter,
         success: function (data) { }
         });
         */

         if (findNeighbours == "1") {
             var searchText = $(".input-search").first().val();
             autosearch(searchText, null, true);
         }
     });
     return false;
 }

 function changeFindNeighboursValue() {
     var value = $("#FindNeighbours").val();
     if (value == "1")
         value = 0;
     else
         value = 1;
     $("#FindNeighbours").val(value);
     setCookie("FindNeighbours", value, (new Date()).addHours(1).toUTCString(), "/");

     /*
     if (value == 0) {
         $("#findNeighboursTrue").css("display", "none");
         $("#findNeighboursFalse").css("display", "block");
     } else {
         $("#findNeighboursTrue").css("display", "block");
         $("#findNeighboursFalse").css("display", "none");
     }
     var searchText = $(".input-search").first().val();
     autosearch(searchText, null, true);
     */
     $('#submit').click();
 }

