/*
 * This file contains all the javascript function required for map functionality
 */

// List of Countries Continents

var country_code_with_continents = {
    "AF": "Asia",
    "Al": "Europe",
    "DZ": "Africa",
    "AS": "Oceania",
    "AD": "Europe",
    "AO": "Africa",
    "AI": "North America",
    "AQ": "Antarctica",
    "AG": "North America",
    "AR": "South America",
    "AM": "Europe",
    "AW": "North America",
    "AU": "Oceania",
    "AT": "Europe",
    "AZ": "Europe",
    "BS": "North America",
    "BH": "Asia",
    "BD": "Asia",
    "BB": "North America",
    "BY": "Europe",
    "BE": "Europe",
    "BZ": "North America",
    "BJ": "Africa",
    "BM": "North America",
    "BT": "Asia",
    "BO": "South America",
    "BA": "Europe",
    "BW": "Africa",
    "BR": "South America",
    "BN": "Asia",
    "BG": "Europe",
    "BF": "Africa",
    "BI": "Africa",
    "KH": "Asia",
    "CM": "Africa",
    "CA": "North America",
    "CV": "Africa",
    "KY": "North America",
    "CF": "Africa",
    "TD": "Africa",
    "CL": "South America",
    "CN": "Asia",
    "CO": "South America",
    "KM": "Africa",
    "CR": "North America",
    "CI": "Africa",
    "HR": "Europe",
    "CU": "North America",
    "CW": "South America",
    "CY": "Europe",
    "CZ": "Europe",
    "CD": "Africa",
    "DK": "Europe",
    "DJ": "Africa",
    "DM": "North America",
    "DO": "North America",
    "TL": "Asia",
    "EC": "South America",
    "EG": "Africa",
    "SV": "North America",
    "GQ": "Africa",
    "ER": "Africa",
    "EE": "Europe",
    "ET": "Africa",
    "FK": "South America",
    "FO": "Europe",
    "FJ": "Oceania",
    "FI": "Europe",
    "FR": "Europe",
    "PF": "Oceania",
    "GA": "Africa",
    "GM": "Africa",
    "GE": "Europe",
    "DE": "Europe",
    "GH": "Africa",
    "GI": "Europe",
    "GR": "Europe",
    "GL": "North America",
    "GD": "North America",
    "GU": "Oceania",
    "GT": "North America",
    "GG": "Europe",
    "GN": "Africa",
    "GW": "Africa",
    "GY": "South America",
    "HT": "North America",
    "HN": "North America",
    "HK": "Asia",
    "HU": "Europe",
    "IS": "Europe",
    "IN": "Asia",
    "ID": "Asia",
    "IR": "Asia",
    "IQ": "Asia",
    "IE": "Europe",
    "IM": "Europe",
    "IL": "Asia",
    "IT": "Europe",
    "JM": "North America",
    "JP": "Asia",
    "JE": "Europe",
    "JO": "Asia",
    "KZ": "Asia",
    "KE": "Africa",
    "XK": "Europe",
    "KI": "Oceania",
    "KP": "Asia",
    "KR": "Asia",
    "KW": "Asia",
    "KG": "Asia",
    "LA": "Asia",
    "LV": "Europe",
    "LB": "Asia",
    "LS": "Africa",
    "LR": "Africa",
    "LY": "Africa",
    "LI": "Europe",
    "LT": "Europe",
    "LU": "Europe",
    "MO": "Asia",
    "MK": "Europe",
    "MG": "Africa",
    "MW": "Africa",
    "MY": "Asia",
    "MV": "Asia",
    "ML": "Africa",
    "MT": "Europe",
    "MH": "Oceania",
    "MQ": "North America",
    "MR": "Africa",
    "MU": "Africa",
    "YT": "Africa",
    "MX": "North America",
    "FM": "Oceania",
    "MD": "Europe",
    "MC": "Europe",
    "MN": "Asia",
    "MS": "North America",
    "MA": "Africa",
    "MZ": "Africa",
    "MM": "Asia",
    "NA": "Africa",
    "NR": "Oceania",
    "NP": "Asia",
    "NL": "Europe",
    "AN": "South America",
    "NC": "Oceania",
    "NZ": "Oceania",
    "NI": "North America",
    "NE": "Africa",
    "NG": "Africa",
    "NU": "Oceania",
    "NF": "Oceania",
    "MP": "Oceania",
    "NO": "Europe",
    "OM": "Asia",
    "PK": "Asia",
    "PW": "Oceania",
    "PS": "Asia",
    "PA": "North America",
    "PG": "Oceania",
    "PY": "South America",
    "PE": "South America",
    "PH": "Asia",
    "PL": "Europe",
    "PT": "Europe",
    "PR": "North America",
    "CG": "Africa",
    "QA": "Asia",
    "RE": "Africa",
    "RO": "Europe",
    "RU": "Europe",
    "RW": "Africa",
    "BL": "North America",
    "SH": "Africa",
    "KN": "North America",
    "LC": "North America",
    "MF": "North America",
    "PM": "North America",
    "VC": "North America",
    "WS": "Oceania",
    "SM": "Europe",
    "ST": "Africa",
    "SA": "Asia",
    "Sc": "Europe",
    "SN": "Africa",
    "RS": "Europe",
    "SC": "Africa",
    "SL": "Africa",
    "SX": "North America",
    "SG": "Asia",
    "SK": "Europe",
    "SI": "Europe",
    "SB": "Oceania",
    "SO": "Africa",
    "ZA": "Africa",
    "SS": "Africa",
    "ES": "Europe",
    "LK": "Asia",
    "SD": "Africa",
    "SR": "South America",
    "SJ": "Europe",
    "SZ": "Africa",
    "SE": "Europe",
    "CH": "Europe",
    "SY": "Asia",
    "TW": "Asia",
    "TJ": "Asia",
    "TZ": "Africa",
    "TH": "Asia",
    "TG": "Africa",
    "TK": "Oceania",
    "TT": "South America",
    "TO": "Oceania",
    "TN": "Africa",
    "TR": "Asia",
    "TC": "North America",
    "TM": "Asia",
    "TV": "Oceania",
    "UG": "Africa",
    "UA": "Europe",
    "AE": "Asia",
    "GB": "Europe",
    "UY": "South America",
    "US": "North America",
    "UZ": "Asia",
    "VU": "Oceania",
    "VE": "South America",
    "VN": "Asia",
    "WF": "Oceania",
    "EH": "Africa",
    "YE": "Asia",
    "ZM": "Africa",
    "ZW": "Africa"
};
// map variable declaration as a global variable
var map;
var baseUrl = $('#baseUrl').val();
var locationDetails = [];
// Create a new blank array for all markers.
var markers = [];
// Create placemarkers array to use in multiple functions to have control
// over the number of places that show.
var placeMarkers = [];
/*
 * @Function            : initMap
 * @Used IN             : @function-'/current_location'
 * @Description         : display map using goole js map API
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 19-10-2016 12:57 PM 
 * @Parameter           : None
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available       
 */


function initMap() {

// Constructor creates a new map - only center is placed to dhaka.
    var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 23.8103, lng: 90.4125},
        zoom: 7
    });
    var profileUrl = $('#profileUrl').val();
    var geocoder = new google.maps.Geocoder;
    var infoWindow = new google.maps.InfoWindow({map: map});
    $.post(baseUrl + 'admin/get-current-location', {profile_url: profileUrl}, function (data) {
        var value = JSON.parse(data);
        if (value !== null && value.person_current_latitude_longitude.length > 0) {
            $('#formated_address').html('Current Location is: '+value.person_address);
            $('#addCurrentLocation').attr('title', 'Update Current Location');
            var locationDetails = (value.person_current_latitude_longitude.replace(/[{()}]/g, '')).split(",");
            var mLocation = {lat: parseFloat(locationDetails[0]), lng: parseFloat(locationDetails[1])};
            infoWindow.setPosition(mLocation);
            infoWindow.setContent('Current Location');
            map.setCenter(mLocation);
        } else {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function (position) {
                    var pos = {
                        lat: position.coords.latitude,
                        lng: position.coords.longitude
                    };
                    $('#addCurrentLocation').attr('title', 'Add current location');
                    infoWindow.setPosition(pos);
                    infoWindow.setContent('Location Assumed.');
                    map.setCenter(pos);
                    geocodeLatLng(geocoder, map, infoWindow, position)

                }, function () {
                    handleLocationError(true, infoWindow, map.getCenter());
                });
            } else {
                // Browser doesn't support Geolocation
                handleLocationError(false, infoWindow, map.getCenter());
            }
        }


    });
// Create a searchbox in order to execute a places search
    var searchInput = document.getElementById('places-search');
    var searchBox = new google.maps.places.SearchBox(searchInput);
    // Bias the searchbox to within the bounds of the map.
    searchBox.setBounds(map.getBounds());
// Listen for the event fired when the user selects a prediction from the
// picklist and retrieve more details for that place.
    searchBox.addListener('places_changed', function () {
        $('#success_message').html('');
        searchBoxPlaces(this, map);
    });

}


/*
 * @Function            : initTravelMap
 * @Used IN             : @function-'/travel'
 * @Description         : display map using goole js map API in travel location
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 19-10-2016 12:57 PM 
 * @Parameter           : reUse[this is optional parameter]
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available       
 */


function initTravelMap() {

// Constructor creates a new map - only center is placed to dhaka.
    var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 23.8103, lng: 90.4125},
        zoom: 1
    });

//    var marker = new google.maps.Marker({
//        position: {lat: 23.8103, lng: 90.4125},
//        map: map
//    });

    var geocoder = new google.maps.Geocoder;
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {


            var pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };
            var infoWindow = new google.maps.InfoWindow({map: map});
            $('#addTravelLocation').attr('title', 'Add Travel Location');
            infoWindow.setPosition(pos);
            infoWindow.setContent('Current Location.');
            map.setCenter(pos);
            geocodeLatLng(geocoder, map, infoWindow, position);
        }, function () {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else if (!navigator.geolocation) {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    }

// suggestion array that contains autocomplete suggestions
    var suggestion = autocomplete_suggestion();
// received value from selected search and geocoding the result
    $("#travel-search").autocomplete({
        source: suggestion,
        minLength: 3,
        select: function (event, ui) {
            var place = ui.item.value;
            $('#success_message_travel').html(' ');
            geocodeAddress(geocoder, place, map);
            var splitPlace = place.split(",");
            $('#city_name').val(splitPlace[0]);
            $('#travel_country').val(splitPlace[1]);
        }
    });

    // Displays the travel locations in the My Travel Location Section
    showTraLoc(map);
}

/*
 * @Function            : handleLocationError
 * @Used IN             : @function- initMap, initTravelMap
 * @Description         : display geolocation service failure error
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 19-10-2016 12:57 PM 
 * @Parameter           : browserHasGeolocation[type = boolean] - determines 
 *                        either browser has geolocation info or not.
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available       
 */

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
            'Error: The Geolocation service failed.' :
            'Error: Your browser doesn\'t support geolocation.');
}


/*
 * @Function            : hideMarkers
 * @Used IN             : @function - searchBoxPlaces
 * @Description         : hide existing map markers in the map
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 25-10-2016 10:00AM 
 * @Parameter           : markers - existing map markers position
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available       
 */
function hideMarkers(markers) {
    for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(null);
    }
}

/*
 * @Function            : searchBoxPlaces
 * @Used IN             : @function-'initMap, initTravelMap'
 * @Description         : Does a nearby search using the selected query string
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 22-10-2016 3:00 PM 
 * @Parameter           : searchBox- Input query sting value given by user
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available       
 */

function searchBoxPlaces(searchBox, map) {

    hideMarkers(placeMarkers);
    var places = searchBox.getPlaces();
    // For each place, get the icon, name and location.
    createMarkersForPlaces(places, map);
    if (places.length == 0) {
        window.alert('We did not find any places matching that search!');
    }
}

/*
 * @Function            : createMarkersForPlaces
 * @Used IN             : @function-'searchBoxPlaces'
 * @Description         : creates markers for each place found in places search
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 23-10-2016 9:30 AM 
 * @Parameter           : places - places detail from search
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available       
 */

function createMarkersForPlaces(places, map) {

    var bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < places.length; i++) {
        var place = places[i];
        // Create a marker for each place.
        var marker = new google.maps.Marker({
            map: map,
            title: place.name,
            position: place.geometry.location,
            id: place.id
        });
        // If a marker is clicked, do a place details search on it in the next function.
        marker.addListener('click', function () {
            getPlacesDetails(this, place);
        });
        placeMarkers.push(marker);
        if (place.geometry.viewport) {
            // Only geocodes have viewport.
            bounds.union(place.geometry.viewport);
        } else {
            bounds.extend(place.geometry.location);
        }

        // This function is used to handle the result data of google api
        useLocationInfo(place);
    }
    map.fitBounds(bounds);
}

/*
 * @Function            : useLocationInfo
 * @Used IN             : @function-'geocodeLatLng'
 * @Description         : using places library data finds out country and city
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 22-10-2016 3:00 PM 
 * @Parameter           : places - places detail from search
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available       
 */

function useLocationInfo(place) {


    var location = place.geometry.location;
    var cityName;
    var countryName;
    // iterate through address_component array
    $.each(place.address_components, function (i, address_component) {

        if (address_component.types[0] == "locality") {
            //alert(address_component.long_name);
            cityName = address_component.long_name;
        }

        if (address_component.types[0] == "country") {
            //alert(address_component.short_name);
            countryName = address_component.short_name;
        }
        //return false; // break the loop   
    });
// Displaying the formatted address in the front end Your current location is:
    $('#formated_address').html('Current Location is: ' + place.formatted_address);
    $('#city_name').val(cityName);
    $('#country_name').val(countryName);
    $('#geo_lat_lng').val(location);
    var countryFullName = getCountryName(countryName);
    var travelAddress = cityName + ',' + countryFullName;
    var geocoder = new google.maps.Geocoder;
    geocoder.geocode({'address': travelAddress}, function (results, status) {
        if (status == 'OK') {

            var geoInfoLocation = results[0].geometry.location;
            $("#geo_travel").val(geoInfoLocation);
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

/*
 * @Function            : geocodeLatLng
 * @Used IN             : @function-'initMap, travelMap'
 * @Description         : using latitude and longitude finds address
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 24-10-2016 3:00 PM 
 * @Parameter           : geocoder - geocoder methode of google api
 *                        map - current map
 *                        position - latitude and longitude details
 *                        infowindow - required for useLocationInfo function
 *                        within this function
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available       
 */


function geocodeLatLng(geocoder, map, infowindow, position) {

    var latlng = {lat: position.coords.latitude, lng: position.coords.longitude};
    geocoder.geocode({'location': latlng}, function (results, status) {
        if (status === 'OK') {
            if (results[1]) {
                map.setZoom(11);
                useLocationInfo(results[1]);
            } else {
                window.alert('No results found');
            }
        } else {
            window.alert('Geocoder failed due to: ' + status);
        }
    });
}

/*
 * @Function            : geocodeAddress
 * @Used IN             : @function-'travelMap'
 * @Description         : using city country to find coordinates
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 29-10-2016 4:00 PM 
 * @Parameter           : geocoder - geocoder methode of google api
 *                        map - current map
 *                        position - latitude and longitude details
 *                        infowindow - required for useLocationInfo function
 *                        within this function
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available       
 */
function geocodeAddress(geocoder, address, map) {

    geocoder.geocode({'address': address}, function (results, status) {
        if (status == 'OK') {

            map.setCenter(results[0].geometry.location);
            map.setZoom(11);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
            $('#geo_travel').val(results[0].geometry.location);
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}
/*
 * @function            : addCurrentLocation
 * @Used IN             : @add current location[button]
 * @Description         : gets users current location deatils input and saves to
 *                        database via ajax and displays message.
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 24-10-2016 10:00 AM 
 * @Parameter           : None
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available       
 */

function addCurrentLocation() {
    var profileUrl = $('#profileUrl').val();
    var address = $('#formated_address').html().replace('Current Location is: ','');
    var cityName = $('#city_name').val();
    var countryName = $('#country_name').val();
    var geoLocation = $('#geo_lat_lng').val();
    var postDataUrl = baseUrl + 'admin/change-current-location';
    if (geoLocation) {
        $.post(
                postDataUrl,
                {address: address,
                    cityName: cityName,
                    countryName: countryName,
                    geoLocation: geoLocation,
                    profile_url: profileUrl
                },
                function (message) {
                    $('#success_message').html(message);
                    $('#geo_lat_lng').val('');
                });
    } else {
        $('#success_message').html(
                '<i class="fa fa-exclamation-circle text-danger" aria-hidden="true"> Please Select Location From Search.</i>'
                );
    }


}

/*
 * @function            : addtraveltLocation
 * @Used IN             : @add_current_location, add_travel_location
 * @Description         : gets users travel location deatils input and saves to
 *                        database via ajax and displays message.
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 31-10-2016 04:10 PM 
 * @Parameter           : None
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available       
 */

function addTravelLocation() {

    var profileUrl = $('#profileUrl').val();
    var cityName = $('#city_name').val();
    var countryName = $('#country_name').val();
    var travelCountry = $('#travel_country').val();
    if (travelCountry) {
        var countryFullName = travelCountry;
    } else {
        var countryFullName = getCountryName(countryName);
    }

    var postDataUrl = baseUrl + 'admin/add-travel-location';
    var geoInfoLocation = $('#geo_travel').val();
    if (geoInfoLocation) {
        $.post(
                postDataUrl,
                {
                    cityName: cityName,
                    countryName: countryFullName,
                    geoInfoLocation: geoInfoLocation,
                    profile_url: profileUrl
                },
                function (data) {
                    $('#success_message_travel').html(data);
                });
    } else {
        $('#success_message_travel').html(
                '<i class="fa fa-exclamation-circle text-danger" aria-hidden="true"> Please Select Travel Location From Search.</i>'
                );
    }


}

/*
 * @function            : showTraLoc
 * @Used IN             : @initTravelMap
 * @Description         : get all travel location from database and display in
 *                        travel page
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 01-11-2016 03:29 PM 
 * @Parameter           : None
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available       
 */

function showTraLoc(map) {

    //hideTravelLocations();
    var profileUrl = $('#profileUrl').val();
    var dataUrl = baseUrl + 'admin/get-travel-location';
    $.post(
            dataUrl,
            {
                profile_url: profileUrl
            },
            function (data) {
                if(data){
                    $('#traLocs').empty();
                }
                var traLocs = JSON.parse(data);
                //var countryByContinent = [];
                //var cityByCountry = [];
                //var geoIdByCity = [];
                var locations = [];
                for (i = 0; i < traLocs.length; i++) {
                    var countryName = traLocs[i].geo_country_name.trim();
                    var cityName = traLocs[i].geo_city_name.trim();
                    var geoInfoId = traLocs[i].geo_information_id.trim();
                    locations[i] = traLocs[i].geo_latitude_longitude.split(',');
                    //var listContinent = [];
                    // Displays the continent Names
                    for (var countryCode in country_code_with_country) {
                        if (country_code_with_country[countryCode] == countryName) {
                            var continent = country_code_with_continents[countryCode];
                            //showContinent(continent);
                            //listContinent.push(continent);
                        }
                    }                    
                    $('#traLocs').append(
                            '<div id="' + continent + geoInfoId + '" class="col-sm-12 padding-zero" style="border-bottom: 1px solid #E5E3DF">'
                            + '<div class="col-sm-12 text-right">'
                            + '<a href="javascript:void(0)" onclick="removeTraLoc(' + geoInfoId + ',\'' + continent + geoInfoId + '\')"><i class="fa fa-times"></i></a>'
                            + '</div>'
                            + '<div class="col-sm-1 text-left">'
                            + '<i class="fa fa-map-marker green"></i>'
                            + '</div>'
                            + '<div class="col-sm-10 text-left" style="padding-left: 5px;">'
                            + '<p>'
                            + 'City: <strong>' + cityName + '</strong><br>'
                            + 'Country: <strong>' + countryName + '</strong><br>'
                            + 'Continent: <strong>' + continent + '</strong>'
                            + '</p>'
                            + '</div>'
                            + '</div>'

                            );
                }
                placeClusterMarker(locations, map);
            }
    );
}


/*
 * @function            : placeClusterMarker
 * @Used IN             : showTraLoc
 * @Description         : displays cluster marker
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 03-11-2016 05:15 PM 
 * @Parameter           : locations
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available       
 */

function placeClusterMarker(locations, map) {

    if (locations.length !== 0) {
        var markers = [];
        for (var value in locations) {
            var lat = parseFloat(locations[value][0].replace(/[{()}]/g, ''));
            var lng = parseFloat(locations[value][1].replace(/[{()}]/g, ''));
            var markerLocations = {lat: lat, lng: lng};
            var marker = new google.maps.Marker({
                position: markerLocations,
                map: map
            });
            markers.push(marker);
        }

        // Add a marker clusterer to manage the markers.
        var markerCluster = new MarkerClusterer(map, markers,
                {imagePath: baseUrl + 'resource_library/map_marker/m'});

    }

}

/*
 * @function            : removeTraLoc
 * @Used IN             : on click check box
 * @Description         : removes the geo location id
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 02-11-2016 04:29 PM 
 * @Parameter           : geoId
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available       
 */

function removeTraLoc(geoId, checkBoxId) {
    $('#delTraLoc').modal('show');
    $('#modalYesButton').on('click', function () {
        var profileUrl = $('#profileUrl').val();
        var dataUrl = baseUrl + 'admin/remove-travel-location';
        $.post(
                dataUrl,
                {
                    geoId: geoId,
                    profile_url: profileUrl
                },
                function () {
                    $('#' + checkBoxId).hide();
                }
        );
    });
    $('#modalNoButton').click(function () {
        $('#delTraLoc').modal('hide');
    });

}

/*
 * @function            : hideTravelLocations
 * @Used IN             : @initTravelMap
 * @Description         : hides the travel My Travel Location Content
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 02-11-2016 10:38 AM 
 * @Parameter           : contentName
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available
 */

function hideTravelLocations() {
    $('#tabs').children().hide();
    $('#travelLocations').hide();
}


$(document).ready(function () {
    // Event fires when Add current location button clicked in current location 
    $("#addCurrentLocation").click(function () {
        addCurrentLocation();
        addTravelLocation();
    });

    // Event fires when Add Travel location button clicked in travel
    $("#addTravelLocation").click(function () {

        addTravelLocation();
        $('#traLocs').empty();
        //exit;
        initTravelMap();
    });
});

// =============== Following codes are for connectivity =============================
/*
 * @function            : displayConnectivitySuggestion
 * @Used IN             : @initLinkMap
 * @Description         : Displays link suggestions in connectivity page
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 12-11-2016 10:00 AM
 * @Parameter           : Null
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available
 */

function displayConnectivitySuggestion() {
    var suggestionUrl = baseUrl + 'admin/get-link-suggestion';
    var profileUrl = $('#profileUrl').val();
    $.post(suggestionUrl, {profile_url: profileUrl}, function (data) {
        var suggestion = JSON.parse(data);
        //console.log(suggestion);
        for (value in suggestion) {

            var personId = suggestion[value].person_id;
            var personName = suggestion[value].person_full_name;
            var personUrl = suggestion[value].person_url;

            if (suggestion[value].person_image) {
                var personImage = baseUrl + 'content-library/' + personUrl + '/' + suggestion[value].person_image;
            } else {
                var personImage = baseUrl + 'image/no_profile_picture.png';
            }
            if (suggestion[value].organization_name) {
                var personOrg = suggestion[value].organization_name;
            } else {
                var personOrg = ' ';
            }
            if (suggestion[value].designation) {
                var personDesignation = suggestion[value].designation;
            } else {
                var personDesignation = ' ';
            }


            $("#link_suggestion").append(
                    '<div class="col-sm-6 form-group" id="' + personUrl + '">'
                    + '<div class="col-sm-12  white link-height padding-zero gray_ttc" style="height: 170px">'
                    + '<span class="col-sm-12 text-right padding-zero ">'
                    + '<a href="javascript:void(0)"'
                    + 'onclick="sendLinkRequest(' + '\'' + personUrl + '\'' + ')">'
                    + '<i class="fa fa-chain" title="Connect"></i>'
                    + '</a>&nbsp;'
                    + '<a href="javascript:void(0)"'
                    + 'onclick="blockPersonLink(' + '\'' + personUrl + '\'' + ')">'
                    + '<i class="fa fa-ban" title="Block Person"></i>'
                    + '</a>&nbsp;&nbsp;'
                    + '<a href="javascript:void(0)"'
                    + 'onclick="removeSuggestion(' + '\'' + personUrl + '\'' + ')">'
                    + '<i class="fa fa-times"></i>'
                    + '</a>&nbsp;&nbsp;'
                    + '</span>'
                    + '<div class="col-sm-5">'
                    + '<a href="' + baseUrl + personUrl + '" target="_blank">'
                    + '<img src="' + personImage + '" class="img-responsive image-thum" alt="User Profile Image">'
                    + '</a>'
                    + '</div>'
                    + '<div class="col-sm-7 text-left" style="padding: 10px;">'
                    + '<span class="padding-zero">'
                    + '<div class="col-sm-12 padding-zero">' + personOrg + '</div>'
                    + '<div class="col-sm-12 padding-zero">' + personDesignation + '</div>'
                    + '</span>'
                    + '</div>'
                    + '<div class="col-sm-12 padding-zero text-left">'
                    + '<div class="col-sm-12" style="margin-top:5px;">'
                    + '<a href="' + baseUrl + personUrl + '" target="_blank">' + personName + '</a>'
                    + '</div>'
                    + '</div>'
                    + '</div>'
                    + '</div>'
                    );
            //displaying only first 8 items
            $("#link_suggestion > div").slice(8).css("display", "none");

        }

    });
}

/*
 * @function            : showCityByCountry
 * @Used IN             : @initLinkMap
 * @Description         : Displays map and link suggestions in connectivity page
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 05-11-2016 11:12 AM
 * @Parameter           : Null
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available
 */

function initLinkMap() {
    // Constructor creates a new map - only center is placed to dhaka.
    var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 23.8103, lng: 90.4125},
        zoom: 1
    });
    var markers = [];
    var profileUrl = $('#profileUrl').val();
    var getMapUrl = baseUrl + 'admin/get-link-location';
    $.post(getMapUrl, {profile_url: profileUrl}, function (data) {

        if (data) {
            var locationData = JSON.parse(data);
            //console.log(data);

            for (var value in locationData) {

                var name = locationData[value].person_first_name + ' '
                        + locationData[value].person_last_name;

                if (locationData[value].person_current_latitude_longitude) {
                    var latLng = locationData[value].person_current_latitude_longitude.split(',');
                    var lat = parseFloat(latLng[0].replace(/[{()}]/g, ''));
                    var lng = parseFloat(latLng[1].replace(/[{()}]/g, ''));
                }

                var marker = new google.maps.Marker({
                    position: {lat: lat, lng: lng},
                    map: map,
                    title: name
                });

                markers.push(marker);
            }           
        }
    });

    //displays the suggestions for connectivity
    displayConnectivitySuggestion();


}

/*
 * @function            : removeSuggestion
 * @Used IN             : link_location
 * @Description         : removes suggestion one by one from connectivity page
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 11-11-2016 10:00 AM
 * @Parameter           : suggestionId
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available
 */

function removeSuggestion(suggestionId) {
    $('#' + suggestionId).remove();
    $("#link_suggestion > div:nth-child(4)").show(function () {
        $("this").slideDown('slow');
    });
}

/*
 * @function            : sendLinkRequest
 * @Used IN             : link_location
 * @Description         : Send link request from connect option from suggestion
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 04-01-2017 
 * @Parameter           : personUrl - to whom request is being sent
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available
 */

function sendLinkRequest(personUrl) {
    
    var requestedBy = $('#profileUrl').val();    
    postUrl = baseUrl + 'admin/connect-suggested-user';
    $.post(
            postUrl,
            {
                profile_url: personUrl,
                requested_by: requestedBy
            },
            function () {
                $('#' + personUrl).remove();
                $("#link_suggestion > div:nth-child(8)").show(function () {
                    $("this").fadeIn();
                });
            }
    );

}

/*
 * @function            : blockPersonLink
 * @Used IN             : link_location
 * @Description         : block a person from the suggestion
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 04-01-2017
 * @Parameter           : personUrl - that will be blocked
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available
 */

function blockPersonLink(personUrl) {
    var blockedBy = $('#profileUrl').val();
    var postUrl = baseUrl + 'admin/user-block-link';
    $.post(
            postUrl,
            {
                profile_url: personUrl,
                blocked_by: blockedBy
            },
            function () {
                $('#' + personUrl).remove();
                $("#link_suggestion > div:nth-child(8)").show(function () {
                    $("this").fadeIn();
                });
            }
    );
}

// =============== Following codes are for My Link =============================
/*
 * @function            : displayLinks
 * @Used IN             : @My Link
 * @Description         : Displays links and pending link requests in My Link
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 23-11-2016 03:00 PM
 * @Parameter           : Null
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available
 */

function displayLinks() {
    var profileUrl = $('#profileUrl').val();
    var dataUrl = baseUrl + 'admin/get-link-detail';
    $.post(dataUrl, {profile_url: profileUrl}, function (data) {       
        var linkDetail = JSON.parse(data);
        if (linkDetail.sorted_pending_request) {
            $('#pendingButton').show();
            showLinkContent(linkDetail.sorted_pending_request, '#pendingLinkRequest');
            $('#divideBar').hide();
        } else {
            $('#pendingButton').hide();
            $('#divideBar').hide();
        }

        if (linkDetail.sorted_linked_user) {
            showLinkContent(linkDetail.sorted_linked_user, '#linkedUser');
        } else {
            $('#divideBar').hide();
        }

    });
}

/*
 * @function            : showLinkContent
 * @Used IN             : @displayLinks
 * @Description         : Push Html for links
 * @Developed By        : MD MASHQUR UL ALAM
 * @Start DateTime      : 25-11-2016 10:00 AM
 * @Parameter           : linkDetail, detailType
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available
 */

function showLinkContent(linkDetail, detailType) {

    for (var value in linkDetail) {

        var personId = linkDetail[value].person_id;
        var personName = linkDetail[value].person_full_name;
        var personUrl = linkDetail[value].person_url;

        if (linkDetail[value].person_image) {
            var personImage = baseUrl + 'content-library/' + personUrl + '/' + linkDetail[value].person_image;
        } else {
            var personImage = baseUrl + 'image/no_profile_picture.png';
        }
        if (linkDetail[value].organization_name) {
            var personOrg = linkDetail[value].organization_name;
        } else {
            var personOrg = ' ';
        }
        if (linkDetail[value].designation) {
            var personDesignation = linkDetail[value].designation;
        } else {
            var personDesignation = ' ';
        }


        if (detailType === '#linkedUser') {
            $(detailType).append(
                    '<div class="col-sm-6 form-group" id="' + personUrl + '">'
                    + '<div class="col-sm-12  white link-height padding-zero gray_ttc" style="height: 170px">'
                    + '<span class="col-sm-12 text-right padding-zero ">'
                    + '<a href="javascript:void(0)"'
                    + 'onclick="deleteLink(' + '\'' + personUrl + '\'' + ')">'
                    + '<i class="fa fa-chain-broken" title="Unlink"></i>'
                    + '</a>&nbsp;'
                    + '<a href="javascript:void(0)"'
                    + 'onclick="blockLink(' + '\'' + personUrl + '\'' + ')">'
                    + '<i class="fa fa-ban" title="Block Person"></i>'
                    + '</a>&nbsp;&nbsp;'
                    + '</span>'
                    + '<div class="col-sm-5">'
                    + '<a href="' + baseUrl + personUrl + '" target="_blank">'
                    + '<img src="' + personImage + '" class="img-responsive image-thum" alt="User Profile Image">'
                    + '</a>'
                    + '</div>'
                    + '<div class="col-sm-7 text-left" style="padding: 10px;">'
                    + '<span class="padding-zero">'
                    + '<div class="col-sm-12 padding-zero">' + personOrg + '</div>'
                    + '<div class="col-sm-12 padding-zero">' + personDesignation + '</div>'
                    + '</span>'
                    + '</div>'
                    + '<div class="col-sm-12 padding-zero text-left">'
                    + '<div class="col-sm-12" style="margin-top:5px;">'
                    + '<a href="' + baseUrl + personUrl + '" target="_blank">' + personName + '</a>'
                    + '</div>'
                    + '</div>'
                    + '</div>'
                    + '</div>'
                    );
        } else if (detailType === '#pendingLinkRequest') {
            $(detailType).append(
                    '<div class="col-sm-6 form-group" id="' + personUrl + '">'
                    + '<div class="col-sm-12  white link-height padding-zero gray_ttc" style="height: 170px">'
                    + '<span class="col-sm-12 text-right padding-zero ">'
                    + '<a href="javascript:void(0)"'
                    + 'onclick="acceptLinkRequest(' + '\'' + personUrl + '\'' + ')">'
                    + '<i class="fa fa-chain" title="Accept Request"></i>'
                    + '</a>&nbsp;'
                    + '<a href="javascript:void(0)"'
                    + 'onclick="blockLink(' + '\'' + personUrl + '\'' + ')">'
                    + '<i class="fa fa-ban" title="Block Person"></i>'
                    + '</a>&nbsp;&nbsp;'
                    + '<a href="javascript:void(0)"'
                    + 'onclick="deleteLink(' + '\'' + personUrl + '\'' + ')">'
                    + '<i class="fa fa-times" title="Delete Request"></i>'
                    + '</a>&nbsp;&nbsp;'
                    + '</span>'
                    + '<div class="col-sm-5">'
                    + '<a href="' + baseUrl + personUrl + '" target="_blank">'
                    + '<img src="' + personImage + '" class="img-responsive image-thum" alt="User Profile Image">'
                    + '</a>'
                    + '</div>'
                    + '<div class="col-sm-7 text-left" style="padding: 10px;">'
                    + '<span class="padding-zero">'
                    + '<div class="col-sm-12 padding-zero">' + personOrg + '</div>'
                    + '<div class="col-sm-12 padding-zero">' + personDesignation + '</div>'
                    + '</span>'
                    + '</div>'
                    + '<div class="col-sm-12 padding-zero text-left">'
                    + '<div class="col-sm-12" style="margin-top:5px;">'
                    + '<a href="' + baseUrl + personUrl + '" target="_blank">' + personName + '</a>'
                    + '</div>'
                    + '</div>'
                    + '</div>'
                    + '</div>'
                    );
        }      

    }
}


/*
         * @function            : displayMyLinkSuggestion
         * @Used IN             : My Link
         * @Description         : Displays suggestion in my link page based on work and education
         * @Developed By        : MD MASHQUR UL ALAM
         * @Start DateTime      : 26-11-2016 04:00 PM
         * @Parameter           : Null
         * @View                : None
         * @Redirect            : None
         * @Return              : NULL    
         * @Status              : Available
         */

        function displayMyLinkSuggestion() {
            var profileUrl = $('#profileUrl').val();
            var suggestionUrl = baseUrl + 'admin/suggested-link';
            $.post(suggestionUrl,{profile_url: profileUrl},function (data) {
                var suggestion = JSON.parse(data);
                if(suggestion){
                    $("#linkSuggestion").append('<h3 class="text-success">Suggested Link</h3>');
                }
                for (value in suggestion) {

                    var personId = suggestion[value].person_id;
                    var personName = suggestion[value].person_full_name;
                    var personUrl = suggestion[value].person_url;

                    if (suggestion[value].person_image) {
                        var personImage = baseUrl + 'content-library/' + personUrl + '/' + suggestion[value].person_image;
                    } else {
                        var personImage = baseUrl + 'image/no_profile_picture.png';
                    }
                    if (suggestion[value].organization_name) {
                        var personOrg = suggestion[value].organization_name;
                    } else {
                        var personOrg = ' ';
                    }
                    if (suggestion[value].designation) {
                        var personDesignation = suggestion[value].designation;
                    } else {
                        var personDesignation = ' ';
                    }


                    $("#linkSuggestion").append(
                            '<div class="col-sm-6 form-group" id="' + personUrl + '">'
                            + '<div class="col-sm-12  white link-height padding-zero gray_ttc" style="height: 170px">'
                            + '<span class="col-sm-12 text-right padding-zero ">'
                            + '<a href="javascript:void(0)"'
                            + 'onclick="sendLinkRequest(' + '\'' + personUrl + '\'' + ')">'
                            + '<i class="fa fa-chain" title="Connect"></i>'
                            + '</a>&nbsp;'
                            + '<a href="javascript:void(0)"'
                            + 'onclick="blockPersonLink(' + '\'' + personUrl + '\'' + ')">'
                            + '<i class="fa fa-ban" title="Block Person"></i>'
                            + '</a>&nbsp;&nbsp;'
                            + '<a href="javascript:void(0)"'
                            + 'onclick="removeSuggestion(' + '\'' + personUrl + '\'' + ')">'
                            + '<i class="fa fa-times"></i>'
                            + '</a>&nbsp;&nbsp;'
                            + '</span>'
                            + '<div class="col-sm-5">'
                            + '<a href="' + baseUrl + personUrl + '" target="_blank">'
                            + '<img src="' + personImage + '" class="img-responsive image-thum" alt="User Profile Image">'
                            + '</a>'
                            + '</div>'
                            + '<div class="col-sm-7 text-left" style="padding: 10px;">'
                            + '<span class="padding-zero">'
                            + '<div class="col-sm-12 padding-zero">' + personOrg + '</div>'
                            + '<div class="col-sm-12 padding-zero">' + personDesignation + '</div>'
                            + '</span>'
                            + '</div>'
                            + '<div class="col-sm-12 padding-zero text-left">'
                            + '<div class="col-sm-12" style="margin-top:5px;">'
                            + '<a href="' + baseUrl + personUrl + '" target="_blank">' + personName + '</a>'
                            + '</div>'
                            + '</div>'
                            + '</div>'
                            + '</div>'
                            );
                    

                }

            });
        }


